// The "module" exported by this script is called "ngbundle":
// Applies drag and drop behaviour to templates/bundle


var ngbundle = function() {

function Bundle(bundle_list) {

  // Add 'new' if we were not called with 'new', so prototyping works.
  if(!(this instanceof Bundle)) {
    return new Bundle(bundle_list);
  }
  
  this._bundle_list = bundle_list;
  this._bundle_handle_selector = ".bundle-handle";
  this._bundle_sortable_selector = ".sortable-bundle"; // our bundle "object"

  clog("Bundle setup");
  clog(this._bundle_list);
}

/* Creates a POST to /bundle/id/move. The display_order is the destination */
Bundle.prototype.move_bundle = function(bundle, idx_dest) {
  var data = bundle.find("a.data");
  var display_order = idx_dest + 1;
  var id = data.attr("id");
  var rel = data.attr("rel");
  var url = rel + "/move";
  clog("Moving bundle " + data.attr("rel") + " to " + display_order);
  jQuery.post(url, {
    "authenticity_token": form_authenticity_token,
    "display_order": display_order,
    "id": id
  }, function(data, status) {
    clog("Moved bundle: " + status);
    clog(data);
  });
};

// bundle = jQuery("li.sortable-bundle")
Bundle.prototype.delete_bundle = function(bundle) {
  var data = bundle.find("a.data");
  var rel = data.attr("rel");

  // clog(bundle);
  // clog(data);
  // clog(rel);

  jQuery.post(rel, {
    "_method": "delete",
    "authenticity_token": form_authenticity_token
  }, function(data, status) {
    bundle.fadeOut(function() {
      $(this).remove();
    });
  }, "script");
};

Bundle.prototype.new_link = function(form, success) {
  clog(form);
  form.ajaxSubmit({
    success: success
  });
  // form.find(".new_link").formSerialize();
  // clog(fields);
};

Bundle.prototype.enableSorting = function() {
  var self = this;
  var startAt, endAt = null;

  this._bundle_list.sortable({
    items: self._bundle_sortable_selector,
    placeholder: 'ui-state-highlight',
    handle: self._bundle_handle_selector,
    cursor: "move",
    revert: true,

    start: function(event, ui) {
      startAt = endAt = indexAt(self._bundle_list, ui.item);
      autofit(ui.placeholder, ui.item);
    },
    
    stop: function(event, ui) {
      endAt = indexAt(self._bundle_list, ui.item);
      if (startAt != endAt) {
        self.move_bundle(ui.item, endAt);
      }
    }
  });
};

Bundle.prototype.enableMenus = function() {
  
  var self = this;
  var menu = null;

  // Set the cursor type via JS. (Doing it in a stylesheet didn't work)
  this._bundle_list.find(this._bundle_handle_selector).css("cursor", "move");

  // TODO: How to make the bundle-actions stay open if the user moved from the title to the actions

  // Take 1. 
  // function checkHover() {
  //   console.log("calling check hover");
  //   if (menu) {
  //     menu.fadeOut("fast");
  //     menu = null;
  //   }
  // }
  // 
  // this._bundle_list.find("div.title")
  // .hover(
  //   function() {
  //     if (menu) {
  //       menu.fadeOut("fast");
  //       menu = null;
  //     }
  //     $(this).next(".bundle-actions").fadeIn("slow");
  //   },
  //   function() {
  //     menu = $(this).next(".bundle-actions");
  //     setTimeout(function() { checkHover(); }, 400);
  //   }
  // );

  // Take 2..
  // // Add hover behaviour and style to the handle selectors
  // this._bundle_list.find(this._bundle_handle_selector)
  // .hover(
  //   function() { 
  //     var bundle_actions = $(this).next(".bundle-actions");
  //     bundle_actions.fadeIn(100);
  //     bundle_actions.find(".move-bundle-action").addClass("ui-state-hover"); 
  //   },
  //   function() { 
  //     var bundle_actions = $(this).next(".bundle-actions");
  //     setTimeout(function() {
  //       // buggy
  //       bundle_actions.hide();
  //       bundle_actions.find(".move-bundle-action").removeClass("ui-state-hover"); 
  //     }, 2500);
  //   }
  // );
  
  // Take 3
  this.forEachSortableBundle(function(bundle) {
    bundle.find(".bundle-actions").hover(
      function() {}, 
      function() { $(this).hide(); }
    );
  });
  
  this.forEachSortableBundle(function(bundle) {
    bundle.find(".title.bundle-handle").hover(
      function() { 
        var bundle_actions = bundle.find(".bundle-actions");
        // $(this).find(".move-bundle-action").addClass("ui-state-hover"); 
        bundle_actions.show();
      }, 
      function() { 
        // $(this).find(".move-bundle-action").removeClass("ui-state-hover");
        // var bundle_actions = $(this).next(".bundle-actions");
        // bundle_actions.hide();
      }
    );
  });

  // Add hover styles to the action icons
  this.forEachSortableBundle(function(bundle) {
    bundle.find(".move-bundle-action, .new-link-action, .edit-bundle-action, .destroy-bundle-action").hover(
      function() { 
        $(this).addClass("ui-state-hover"); 
      },
      function() {
        $(this).removeClass("ui-state-hover");
      }
    );
  });

};

Bundle.prototype.enableActions = function() {
  
  var self = this;

  // Show "Create new link" dialog on click
  this.forEachSortableBundle(function(bundle) {
    bundle.find(".new-link-action").click(function() {
      new_dialog = bundle.next(".new-link-dialog").clone();
      new_dialog.dialog({
        bgiframe: true,
        autoOpen: false,
        height: 300,
        modal: true,

        buttons: {
          "Ok": function() {
            var form = $(this).find(".new-link-form");
            self.new_link(form, function(response, status) {
              console.log(response, status);
            });
            $(this).dialog("close");
          },
          "Cancel": function() {
            $(this).dialog("close");
          }
        }
      });
      new_dialog.dialog("open");
      return false;
    });
  });

  // Show "Edit existing link" dialog on click
  this.forEachSortableBundle(function(bundle) {
    bundle.find(".edit-bundle-action").click(function() {
      console.log("Editing link " + $(this).attr("rel"));
      return false;
    });
  });

  // Show "Destroy existing bundle" dialog on click
  this.forEachSortableBundle(function(bundle) {
    bundle.find(".destroy-bundle-action").click(function() {
      $("<div>Delete bundle and all links?</div>").dialog({ 
        title: "Delete?",
        buttons: { 
          "Ok": function() { 
            self.delete_bundle(bundle); 
            $(this).dialog("close");
          },
          "Cancel": function() { 
            $(this).dialog("close");
          }
        }
      });
      return false;
    });
  });
  
};

Bundle.prototype.forEachSortableBundle = function(func) {
  this._bundle_list.find(this._bundle_sortable_selector).each(function() {
    var sortableBundle = $(this);
    func(sortableBundle);
  });
};

// Bundle.prototype.forEachBundleUnit = function(func) {
//   this._bundle_list.find(".bundle.unit").each(function() {
//     var bundleUnit = $(this);
//     bundleUnit.find(this._bundle_sortable_selector).each(function() {
//       var bundleItem = $(this);
//
//     })
//     func(bundleItem);
//   });
// };

/*
 Accepts only 
 <ul class="ui-sortable bundle-list">
 </ul>
 
 See bundle.liquid for details
*/
Bundle.prototype.setup = function() {
  this.enableSorting();
  this.enableMenus();
  this.enableActions();
  this._bundle_list.disableSelection();
};

/* Autofits the placeholder to the height&width of the item */
function autofit(placeholder, item) {
  jQuery(placeholder).height(item.outerHeight(true)).width(item.outerWidth(true));
}

function indexAt(bundles, bundle) {
  return bundles.children().index(bundle);
}

function logBundle(ui) {
  clog("Helper: ");
  clog(ui.helper);
  clog("Position: ");
  clog(ui.position);
  clog("Offset: ");
  clog(ui.offset);
  clog("Item: ");
  clog(ui.item);
  clog("PlaceHolder: ");
  clog(ui.placeholder);
  clog("Sender: ");
  clog(ui.sender);
}

return {Bundle: Bundle};

}();
