$('.hornet.media .thumbs a').concrete({
  onclick: function() {
    $('.hornet.dialog div.tabs').tabs('add', $(this).attr('href'), $(this).children('img').attr('alt'));
    return false;
  }
});

$('.hornet.media .use-this-image-style').concrete({
  onclick: function() {
    var win = tinyMCEPopup.params.window
    var src = $(this).parent().next('img').attr('src')
    win.document.getElementById('src').value = src;
    win.document.getElementById('alt').value = $('.hornet.media.asset-wrapper h2').text();
    if (typeof(win.ImageDialog) != "undefined") {
      // we are, so update image dimensions...
      if (win.ImageDialog.getImageData) win.ImageDialog.getImageData();
      // ... and preview if necessary
      if (win.ImageDialog.showPreviewImage) win.ImageDialog.showPreviewImage(src);
    }
    tinyMCEPopup.close();
  }
});

$('.hornet.media a.ajax').concrete({
  onclick: function() {
    $(this).closest('.ui-tabs-panel').load($(this).attr('href'), null,
    function(){

    });
    return false;
  }
});

$('.hornet.media .resize input').concrete({
  onkeyup: function() {
    if ($(this).attr('id') == 'image_width') {
      $('.hornet.media .original img').resizebywidth($(this).val());
    } else if ($(this).attr('id') == 'image_height') {
      $('.hornet.media .original img').resizebyheight($(this).val());
    }
  }
});

$('.hornet.media .original img').concrete({
  Width: 0,
  Height: 0,
  onmatch: function() {
    $(this).setWidth(parseInt($('.hornet.media .resize #original_width').val()));
    $(this).setHeight(parseInt($('.hornet.media .resize #original_height').val()));
  },
  resizebywidth: function(width) {
    ratio = parseInt(width)/$(this).getWidth();
    $(this).width($(this).getWidth()*ratio);
    newheight = $(this).getHeight()*ratio;
    $(this).height(newheight);
    $('.hornet.media .resize #image_height').val(Math.round(newheight));
  },
  resizebyheight: function(height) {
    ratio = parseInt(height)/$(this).getHeight();
    $(this).height($(this).getHeight()*ratio);
    newwidth = $(this).getWidth()*ratio;
    $(this).width(newwidth);
    $('.hornet.media .resize #image_width').val(Math.round(newwidth));
  }
});

$('.hornet.media form.edit_image').concrete({
  onsubmit: function() {
    $(this).ajaxSubmit({
      dataType: 'script'
    });
    return false;
  }
})

$('.hornet.media .image_gallery').concrete({
  onmatch: function() {
    $('.hornet.media .thumbs .thumb').draggable({
      revert: true,
      revertDuration: 10,
      zIndex: 1000,
      containment: 'document'
    });
    $('.hornet.media .image_gallery .drop_target').droppable({
      accept: '.thumb',
      hoverClass: 'hovering',
      drop: function(event, ui) {
        $(this).children('span').remove();
        thumb = ui.draggable.clone().attr('style', '');
        $('.hornet.media .image_gallery .drop_target').append(thumb);
        ui.draggable.draggable('disable').addClass('nodrag');
        // console.log(ui);
      }
    });
  }
})

$('.hornet.media.right-pane').concrete({
  Height: 0,
  onmatch: function() {
    $(this).scrollable({
      size: 1,
      clickable: false
      // keyboard: false
    });
    $(this).setHeight($(this).parent('.hornet.media.modal.dialog.large').innerHeight()-$(this).siblings('h1').outerHeight());
    $(this).height($(this).getHeight());
    $('.hornet.media.left-pane').height($(this).getHeight());
    $('.scrollable-item', this).height($(this).getHeight()).width($(this).width());
  }
});

$('.hornet.media.left-pane .tools a.upload').concrete({
  onclick: function() {
    $('.hornet.media.upload').animate({
      height: $('.hornet.media.right-pane').getHeight(),
      bottom: 0
    }, 100);
    return false;
  }
})

$('.hornet.media.upload .close').concrete({
  onclick: function() {
    $(this).parent().animate({
      height: 0, 
      bottom: '-100px'
    }, 100);
    return false;
  }
})

$('.hornet.media.upload form input[type=file]').concrete({
  onmatch: function() {
    uploadify_settings = {
      'format': 'json',
      '_hornet_session': $(this).parent().siblings('input#_hornet_session').val(),
      'authenticity_token' : $(this).parent().siblings('input#authenticity_token').val(),
      'image[parent_id]' : $('.hornet.media.tree .current').parent('li').attr('id')
    };
    $(this).uploadify({
      uploader: '/javascripts/jquery.uploadify-v2.1.0/uploadify.swf',
      script: '/hornet/images',
      method: 'POST',
      cancelImg: '/javascripts/jquery.uploadify-v2.1.0/cancel.png',
      buttonText: 'Select files',
      'auto': false,
      'multi': true,
      fileDataName: 'image[file]',
      scriptData: uploadify_settings,
      onSelect: function() {
        uploadify_settings['image[parent_id]'] = $('.hornet.media.tree .current').parent('li').attr('id');
        $('.hornet.media.upload form input[type=file]').uploadifySettings('scriptData', uploadify_settings);
      },
      onComplete: function(event, queueID, fileObj, response, data) {
        response = eval('('+response+')');
        if (response.result == 'success') {
          $('.hornet.media.thumbs .tools').after('<a href="#" id="'+response.id+'" class="thumb"><img src="'+response.thumb_src+'" alt="" /><span class="name">Untitled image</span></a>');
          $('.hornet.media.tree .current > a > .contents_count').text('('+$('.hornet.media.thumbs .thumb').length+')');
        }
      }
    })
  }
})

$('.hornet.media.upload .tools a.do-upload').concrete({
  onclick: function() {
    $('.hornet.media.upload form input[type=file]').uploadifyUpload();
    return false;
  }
})

$('.hornet.media.new-folder').concrete({
  onclick: function() {
    if ($('.hornet.media.tree .creating').length > 0) { 
      $('.hornet.media.tree .creating input').focus();
      return false 
    };
    current = $('.hornet.media.tree .current').parent('li');
    if ($(current).children('ul').length == 0) {
      current.append('<ul></ul>');
    }
    icon_width = parseInt($('.icon', current).width())+10;
    input_width = (parseInt(current.width())-icon_width)*0.9;
    $(current).children('ul').append('<li class="leaf Mnode"><div class="wrapper creating"><div class="icon" style="width:'+icon_width+'px"></div><a href="#" class="node"><input type="text" value="" /></a></div></li>');
    $('.creating input', current).width(input_width).focus();
    return false;
  }
});

$('.hornet.media.tree .creating input').concrete({
  onkeyup: function(e) {
    // console.log(e.which)
    if (e.which == 13) {
      input = $(this);
      $(this).parent().prev('.icon').addClass('saving');
      $.post('/hornet/media/create', {format: 'json', 'mnode[name]': $(this).val(), 'mnode[parent_id]': $('.hornet.media.tree .current').parent('li').attr('id')},
      function(response){
        response = eval('('+response+')');
        if (response.result == 'success') {
          // Set the id on the li
          $('.hornet.media.tree .creating').parent('li').attr('id', response.mnode);
          // Remove the saving class
          $('.hornet.media.tree .creating .icon').removeClass('saving');
          // Hide the input
          input.hide();
          // Add the anchor tag
          $('.hornet.media.tree .creating a').text(input.val());
          // Remove the input tag
          input.remove();
          // Remove the creating class
          $('.hornet.media.tree .creating').removeClass("creating");
        }
      });
    } else if (e.which == 27) {
      $('.hornet.media.tree .creating').parent('li').remove();
    }
  }
});

$('.hornet.media.tree .wrapper').concrete({
  onclick: function() {
    if ($('.hornet.media.tree .creating').length > 0) { return false };
    id = $(this).parent('li').attr('id');
    tinymce = $('.hornet.media.dialog').hasClass('tinymce') ? '?tinymce=true' : ''
    $('.hornet.media.right-pane .scrollable-items .thumbs').load('/hornet/media/folders/'+id+tinymce,
    function(){
      $('.hornet.media.tree .current').removeClass('current');
      $('.hornet.media.tree li#'+id+' > .wrapper').addClass('current');
      scrollable = $('.hornet.media.right-pane').scrollable();
      if (scrollable.getPageIndex() > 0) {
        scrollable.begin()
      }
    });
    return false;
  }
});

$('.hornet.media.thumbs .thumb').concrete({
  onclick: function() {
    id = $(this).attr('id');
    tinymce = $('.hornet.media.dialog').hasClass('tinymce') ? '?tinymce=true' : ''
    $('.hornet.media.asset-wrapper').load('/hornet/images/'+id+tinymce,
    function() {
      $('.hornet.media.right-pane').scrollable().next()
    });
    return false;
  }
});

function hornet_media (type, target) {
  if($('#file-browser').length > 0) return false;
  $('body').append('<div class="hornet modal blocker" id="file-browser-modal-blocker"></div>');
  $('body').append('<div id="file-browser"></div>');
  $('#file-browser').load('/hornet/media', null,
   function() {
     $('#file-browser').addClass('hornet modal top')
     $('.hornet.media.modal.dialog').attr('id', type).data('target', target)
  });
};

$('.hornet.media#image-gallery .tools .image-gallery-select').concrete({
  onclick: function() {
    attachment = {
      id: $('.hornet.media.tree .current').parent().attr('id'),
      name: $('.hornet.media.thumbs h2').text()
    }
    target = $('.hornet.media.modal.dialog').data('target');
    $('.mnode_id', target).val(attachment.id);
    $('span', target).text(attachment.name);
    $('.hornet.dialog.modal').close();
    return false;
  }
})

$('.hornet.media#thumbnail .tools .use-this-image').concrete({
  onclick: function() {
    target = $('.hornet.media.modal.dialog').data('target')
    $('.mnode_id', target).val($('.hornet.media.asset-wrapper input#id').val())
    $('span', target).text($('.hornet.media.asset-wrapper h2').text())
    $('.hornet.dialog.modal').close()
    return false
  }
})

$('.hornet.media.asset-wrapper .tools .back-to-folder').concrete({
  onclick: function() {
    scrollable = $('.hornet.media.right-pane').scrollable()
    scrollable.prev()
    return false
  }
})

// $('.hornet.media.asset-wrapper .image-style').concrete({
//   onmatch: function() {
//     width = $('.hornet.media.asset-wrapper').width();
//     $('.hornet.media.asset-wrapper img').each(function(index) {
//       if (parseInt($(this).width()) > width) {
//         width = $(this).width()
//       }
//     })
//     $(this).width(width)
//     $('.hornet.media.asset-wrapper .image-style').width(width)
//     $('.hornet.media.asset-wrapper h2').width(width)
//   }
// })

$('.honrnet.media.asset-wrapper .delete-image').concrete({
  onclick: function() {
    if (confirm('Are you sure?')) {
      $.post($(this).attr('href')+'.json', 
      { 
        '_format' : 'json',
        '_method': 'delete', 
        'authenticity_token': $('.hornet.upload form input#authenticity_token').val()
      },
      function() {
        response = eval('('+response+')')
        if (response.result == 'success') {
          $('.hornet.media.tree .current.wrapper').click()
        }
      }, 'json')
      return false
    }
  }
      // var f = document.createElement('form'); f.style.display = 'none'; 
      // this.parentNode.appendChild(f); f.method = 'POST'; 
      // f.action = this.href;
      // var m = document.createElement('input'); 
      // m.setAttribute('type', 'hidden'); 
      // m.setAttribute('name', '_method'); 
      // m.setAttribute('value', 'delete'); 
      // f.appendChild(m); 
      // var s = document.createElement('input'); 
      // s.setAttribute('type', 'hidden'); 
      // s.setAttribute('name', 'authenticity_token'); 
      // s.setAttribute('value', 'gl8wAdPafdaYnNS97tJInilCoCKb8GCyhvyKyogdOj4='); 
      // f.appendChild(s);f.submit(); };
      // return false;
})