$(function(){
  $('.bundle-list').sortable(bundle_sorting_options);

  $('a.new-bundle').click(function(){ return bundle_dialog($(this).attr('href'), "Add category", add_bundle); });
  $(".link-group").bundlize();
});

(function($){
  $.fn.bundlize = function(settings){
  
    return $(this).each(function(){
      //console.log("Bundlizing: " + $(this).find('.links').attr('name'));
      
      $(this).find('a.new-link').click(function(event){
        return link_dialog(this, $(this).attr('href'), "Add link", add_link);
      });
      $(this).find('a.edit-bundle').click(function(){ return bundle_dialog($(this).attr('href'), "Edit category", edit_bundle); });
      $(this).find('a.delete-bundle').click(function(){ return delete_bundle($(this)); });
      $(this).find('img.bundle-menu-root').menufy({target: ".bundle-menu"});    
    });
  }
})(jQuery);

var start_index;
var bundle_sorting_options = {
  cursor: 'move',
  handle: 'h2',
  items: '.bundle',
  revert: true,
  placeholder: 'ui-state-highlight',
  start: function(event, ui){
    start_index = get_bundle_index(ui.item);
    
    $(ui.placeholder).height(ui.item.outerHeight(true)).width(ui.item.outerWidth(true));
    $('.bundle')
      .addClass('droppable-bundle-target');
//      .css('min-height', ui.item.height())
//      .css('min-width', ui.item.width());
  },
  stop: function(event, ui){
    var to_index = get_bundle_index(ui.item);

    if (to_index != start_index) {
      move_bundle(ui.item.find('a.data'), to_index);
    }
    
    $('.bundle')
      .removeClass('droppable-bundle-target');
//      .css('min-height', 'auto')
//      .css('min-width', 'auto');
  }
};

function get_bundle_index(bundle){
  return $('.bundle-list').children().index(bundle);
}

function add_bundle(bundle_data, status, container){

  if (!or.admin.has_errors(bundle_data)) {
    var bundle = $('<div></div>').addClass('bundle').appendTo( $('.bundle-list')).hide();
    
    bundle.load('/bundles/' + bundle_data.bundle.id, 
      function(){
        make_links_sortable_for(bundle);
        bundle.bundlize().fadeIn();
        container.dialog('close');
      });
  }
}

function edit_bundle(bundle_data, status, container){

  if (!or.admin.has_errors(bundle_data)) {
    var bundle_to_update = $('#bundle_' + bundle_data.bundle.id).closest(".bundle");
    
    var new_name = bundle_data.bundle.display_name;
    bundle_to_update.find('ul.links').attr('name', new_name);
    bundle_to_update.find(".link-group h2").fadeOut(function(){
      container.dialog('close');
      $(this).text( new_name ).fadeIn();
    });
  }
}

function move_bundle(bundle, to_index){
  console.log("Moving bundle " + bundle + " to " + to_index);
  
  $.post(bundle.attr('rel') + '/move',
    {
      "_method": "post",
      "authenticity_token": form_authenticity_token,
      "display_order": to_index,
      "id": bundle.id
    },
    function(data, status){
      console.log("Moved category");
      console.log(data);
    }
  );
}

function delete_bundle(bundle_link){
  if(confirm("Are you sure you want to delete this category?")){
    
    $.post(
      bundle_link.attr('rel'), 
      {
        '_method': 'delete',
        "authenticity_token": form_authenticity_token
      },
      function(data, status){
        if (status == "success") {
          $(bundle_link).closest('.bundle').fadeOut(function(){ $(this).remove(); });
        }
      }, 
      "script"
    ); 
  }
  
  return false;
}

var bundle_dialog_options = {dialogClass: 'edit-bundle', draggable: false, resizable: false, modal: true, width: "360px" };

function bundle_dialog(content_url, title, callback){

  $.get(content_url,
    function(data, textStatus){
      
      var dialog = $("<div></div>")
        .html(data)
        .dialog($.extend(bundle_dialog_options, {title: title}));
      
      var form = dialog.find("form");

      form.ajaxForm({ 
        dataType: 'json',
        beforeSubmit: function(formData, jqForm, options){
          var bundle_name = jqForm.find('input:text[name*=display_name]').val();
          jqForm.find('input:hidden[name*=name]').val( bundle_name );
          return true;
        },
        success: function(data, status){ callback(data, status, dialog); } 
      });
    },
    'script');
    
  return false;
}