/**
 *
 */
(function($){
  var MoveItemUrl = "index.php?P=P_Folders_MoveItem&SuppressHtmlOutput=1",
      MoveItemToNewFolderUrl = "index.php?P=P_Folders_MoveItemToNewFolder&SuppressHtmlOutput=1",
      ShareFolderUrl = "index.php?P=P_Folders_ShareFolder&SuppressHtmlOutput=1",
      WithdrawFolderUrl = "index.php?P=P_Folders_WithdrawFolder&SuppressHtmlOutput=1";

  /**
   * Take an item that has been moved and update its position in the database.
   * @param $item jQuery object wrapping the DOM item
   * @return void
   */
  function itemUpdate($item) {
    var $target;

    if ($item.prev().length) {
      moveItem(
        $item.attr("data-parentfolderid"),
        $item.prev().attr("data-itemid"),
        $item.attr("data-itemid"));
    } else if ($item.next().length) {
      // first move it after the first item...
      prependItem(
        $item.attr("data-parentfolderid"),
        $item.attr("data-itemid"));
    }
  }

  /**
   * Do an AJAX callback to move the item.
   * @param folderId ID of the folder the items are in
   * @param targetItemId ID of the target item
   * @param itemId ID of the item
   * @return void
   */
  function moveItem(folderId, targetItemId, itemId) {
    $.get(MoveItemUrl, {
      "FolderId": folderId,
      "ItemId": itemId,
      "TargetItemId": targetItemId
    });
  }

  /**
   * Do an AJAX callback to move the item to the beginning of the list.
   * @param folderId ID of the folder the items are in
   * @param itemId ID of the item
   * @return void
   */
  function prependItem(folderId, itemId) {
    $.get(MoveItemUrl, {
      "FolderId": folderId,
      "ItemId": itemId
    });
  }

  /**
   * Do an AJAX callback to move the item to a new folder.
   * @param oldFolderId ID of the old folder the item was in
   * @param newFolderId ID of the folder the item is now in
   * @param itemId ID of the item
   * @return void
   */
  function moveItemToNewFolder(oldFolderId, newFolderId, itemId, onSuccess) {
    $.get(MoveItemToNewFolderUrl, {
      "OldFolderId": oldFolderId,
      "NewFolderId": newFolderId,
      "ItemId": itemId
    }, onSuccess);
  }

  /**
   * Do an AJAX callback to share the folder.
   * @param folderId folder ID
   * @return void
   */
  function shareFolder(folderId) {
    $.get(ShareFolderUrl, {
      "FolderId": folderId
    });
  }

  /**
   * Do an AJAX callback to withdraw the folder.
   * @param folderId folder ID
   * @return void
   */
  function withdrawFolder(folderId) {
    $.get(WithdrawFolderUrl, {
      "FolderId": folderId
    });
  }

  $(document).ready(function(){
    var Folders = cw.require("Folders"),
        Popup = cw.require("CW-Popup");

    // folder edit popup
    var folderEditPopup;
    var $folderEditPopupTrigger = $(".folders-folderedit-trigger"),
        $folderEditPopup = $(".folders-popup-edit"),
        folderEditClobber = $.clobber({"delay": 250});

    // show hidden triggers
    $folderEditPopupTrigger.css({"visibility": "visible"});

    if ($(".folders-popup-edit").length) {
        folderEditPopup = new Folders.FolderEditPopup($folderEditPopup, folderEditClobber);

        $folderEditPopupTrigger.click(function(){
          folderEditPopup.anchor($(this));
          folderEditPopup.show();
          return false;
        });

        $folderEditPopupTrigger.mouseleave(function(){
          folderEditClobber(function(){
              folderEditPopup.hide();
          }, {"delay": 30});
        });
    }

    // item edit popup
    var itemEditPopup;
    var $itemEditPopupTrigger = $(".folders-itemedit-trigger"),
        $itemEditPopup = $(".folders-popup-itemedit"),
        itemEditClobber = $.clobber({"delay": 250});

    // show hidden triggers
    $itemEditPopupTrigger.css({"visibility": "visible"});

    if ($(".folders-popup-itemedit").length) {
        itemEditPopup = new Folders.ItemEditPopup($itemEditPopup, itemEditClobber);

        $itemEditPopupTrigger.click(function(){
          itemEditPopup.anchor($(this));
          itemEditPopup.show();
          return false;
        });

        $itemEditPopupTrigger.mouseleave(function(){
          itemEditClobber(function(){
              itemEditPopup.hide();
          }, {"delay": 30});
        });
    }

    // edit popup tooltips
    var $tooltipNode = $("#folders-edit-tooltip"),
        $tooltipAnchor = $("img.folders-edit-help"),
        tooltip = new Popup.Tooltip($tooltipNode);

    tooltip.anchor($tooltipAnchor);

    // add move cursor to certain items
    $(".cw-section.folders-folder .cw-section-header,\
       .folders-folder ul.folders-items li,\
       .folders-items:not(.folders-nojs) > .folders-resource ").css({
      "cursor": "move"});

    function dragStart() {
      if (folderEditPopup) {
        folderEditPopup.hide();
      }

      if (itemEditPopup) {
        itemEditPopup.hide();
      }
    }

    function itemOver(event, ui) {
      var $lists = $(".folders-items");

      $lists.each(function(){
        var $list = $(this);

        if ($list.children(":visible").length == 0) {
          $list.prepend('<li class="folders-noitems">There are no items in this folder.</li>');
        }
      });

      var $list = $(".folders-items .ui-sortable-helper").parent();

      if ($list.children().length == 1) {
        $list.prepend('<li class="folders-noitems">There are no items in this folder.</li>');
      }

      $(event.target).children("li.folders-noitems").remove();
    }

    function miniItemUpdate(event, ui) {
      var $item = $(ui.item),
          $list = $item.parent(),
          itemId = $item.attr("data-itemid"),
          currentFolderId = $list.attr("data-folderId"),
          lastFolderId = $item.attr("data-parentfolderid");

      if (currentFolderId == lastFolderId) {
        itemUpdate($item);
      } else {
        // update parent folder ID data
        $item.attr("data-parentfolderid", currentFolderId);

        // remove siblings that are the same
        $item.siblings("[data-itemid='"+itemId+"']").remove();

        // move the item to the new folder at the beginning
        moveItemToNewFolder(lastFolderId, currentFolderId, itemId, function(){
          // only need to consider position if not at the beginning
          if ($item.prev().length) {
            moveItem(
              $item.attr("data-parentfolderid"),
              $item.prev().attr("data-itemid"),
              $item.attr("data-itemid"));
          }
        });
      }
    }

    // disable text selection on the folders
    $(".folders-folders").disableSelection();

    $(".folders-folders").sortable({
      "axis": "y",
      "containment": "document",
      "handle": ".cw-section-header",
      "update": function(e, ui) { itemUpdate($(ui.item)); },
      "start": dragStart
    });

    $(".folders-items:not(.folders-nojs)").sortable({
      "axis": "y",
      "containment": "document",
      "update": function(e, ui) { itemUpdate($(ui.item)); },
      "start": dragStart
    });

    $(".folders-items.folders-items-mini").sortable({
      "axis": "y",
      "containment": "document",
      "update": miniItemUpdate,
      "start": dragStart,
      "cancel": ".folders-noitems",
      "connectWith": ".folders-items",
      "over": itemOver
    });

    $("input[type='checkbox'][name='Share']").change(function(){
      var $this = $(this),
          folderId = $this.attr("data-folderid");

      if ($this.is(":checked")) {
        shareFolder(folderId);
      } else {
        withdrawFolder(folderId);
      }
    });
  });

}(jQuery));
