/**
 * Javascript classes for the Folders plugin.
 */

cw.provide("Folders", function(){

var Helpers = cw.require("CW-Helpers"),
    Popup = cw.require("CW-Popup");

function EditPopup(node, clobber) {
  EditPopup.base.call(this, node, null, clobber);
} cw.extend(EditPopup, Popup.DefaultPopup);

EditPopup.prototype.TextChangeTimeout = 250;
EditPopup.prototype.NodeHeightPadding = 20;

EditPopup.prototype.determineDisplayDirection = function(anchor) {
  var anchorTop = anchor.offset().top,
      windowBottom = $(window).scrollTop() + $(window).height(),
      spaceAvailable = windowBottom - anchorTop,
      nodeHeight = this.Node.height() + this.NodeHeightPadding;

  return anchorTop < nodeHeight || nodeHeight <= spaceAvailable;
};

function ItemEditPopup(node, clobber) {
  ItemEditPopup.base.call(this, node, clobber);
  this.RouterUrl = cw.getRouterUrl();
} cw.extend(ItemEditPopup, EditPopup);

ItemEditPopup.prototype.anchor = function(anchor, options) {
  this.setFolderId(anchor.data("folderid"));
  this.setItemId(anchor.data("itemid"));
  this.setItemNote(anchor.data("itemnote"));

  this.setupAutoUpdates();

  if (this.determineDisplayDirection(anchor)) {
    // show the pointer
    $(".folders-popup-toppointer", this.Node).css("visibility", "visible");
    $(".folders-popup-bottompointer", this.Node).css("visibility", "hidden");

    options = $.extend({
      "anchorHandle": "50%",
      "popupHandle": "87%",
      "distance": 18,
      "anchorSide": "bottom"}, options);
  } else {
    // show the pointer
    $(".folders-popup-toppointer", this.Node).css("visibility", "hidden");
    $(".folders-popup-bottompointer", this.Node).css("visibility", "visible");

    options = $.extend({
      "anchorHandle": "50%",
      "popupHandle": "87%",
      "distance": 18,
      "anchorSide": "top"}, options);
  }

  Helpers.AnchoredPopup.prototype.anchor.call(this, anchor, options);
};

ItemEditPopup.prototype.setupAutoUpdates = function() {
  var noteChangeTimeout;
  var popup = this;

  $(".folders-itemedit-note", this.Node).onvaluechange(function($elem, prev, curr){
    var folderId = popup.getFolderId(),
        itemId = popup.getItemId(),
        elements = $(".folders-item-note[data-folderid='"+folderId+"'][data-itemid='"+itemId+"']");

    // set the description while transforming newlines to breaks
    elements.each(function(){
      var element = $(this);

      element.text(curr);
      element.html(element.html().replace(/(\r\n|\n\r|\r|\n)/g, "<br />"));
    });

    clearTimeout(noteChangeTimeout);

    noteChangeTimeout = setTimeout(function(){
      popup.updateItemNote();
    }, popup.TextChangeTimeout);
  });

  $(".folders-itemedit-remove", this.Node).click(function(){
    popup.removeItem();
  });
};

ItemEditPopup.prototype.getFolderId = function() {
  return this.FolderId;
};

ItemEditPopup.prototype.getItemId = function() {
  return this.ItemId;
};

ItemEditPopup.prototype.getItemNote = function() {
  return $(".folders-itemedit-note", this.Node).val();
};

ItemEditPopup.prototype.setFolderId = function(folderId) {
  this.FolderId = folderId;
};

ItemEditPopup.prototype.setItemId = function(itemId) {
  this.ItemId = itemId;
};

ItemEditPopup.prototype.setItemNote = function(note) {
  $(".folders-itemedit-note", this.Node).val(note);
};

ItemEditPopup.prototype.updateItemNote = function() {
  var folderId = this.getFolderId(),
      itemId = this.getItemId(),
      itemNote = this.getItemNote(),
      items = $("[data-itemnote][data-folderid='"+folderId+"'][data-itemid='"+itemId+"']");

  items.data("itemnote", itemNote);
  $.get(this.RouterUrl+"?P=P_Folders_UpdateResourceNote&SuppressHtmlOutput=1", {
    "FolderId": folderId,
    "ItemId": itemId,
    "ResourceNote": itemNote
  });
};

ItemEditPopup.prototype.removeItem = function() {
  var folderId = this.getFolderId(),
      itemId = this.getItemId(),
      item = $(".folders-resource[data-itemid='"+itemId+"']");

  $.get(this.RouterUrl+"?P=P_Folders_RemoveItem&SuppressHtmlOutput=1", {
    "FolderId": folderId,
    "ItemId": itemId
  });

  this.hide();

  item.slideUp("fast", function(){
    var resources;

    // these need to come in this order
    item.remove();
    resources = $(".folders-items > .folders-resource");

    if (!resources.length) {
      $(".folders-items").html('<p class="folders-noitems">There are no items in this folder.</p>');
    }
  });
};

ItemEditPopup.prototype.RouterUrl = null;
ItemEditPopup.prototype.FolderId = null;
ItemEditPopup.prototype.ItemId = null;

function FolderEditPopup(node, clobber) {
  FolderEditPopup.base.call(this, node, clobber);
  this.RouterUrl = cw.getRouterUrl();
} cw.extend(FolderEditPopup, EditPopup);

FolderEditPopup.prototype.anchor = function(anchor, options) {
  this.setFolderId(anchor.data("folderid"));
  this.setFolderName(anchor.data("foldername"));
  this.setFolderDescription(anchor.data("folderdescription"));
  this.setFolderIsShared(anchor.data("folderisshared"));
  this.setFolderSelect(anchor.data("folderselect"));

  this.setupAutoUpdates(anchor);

  if (this.determineDisplayDirection(anchor)) {
    // show the pointer
    $(".folders-popup-toppointer", this.Node).css("visibility", "visible");
    $(".folders-popup-bottompointer", this.Node).css("visibility", "hidden");

    options = $.extend({
      "anchorHandle": "50%",
      "popupHandle": "87%",
      "distance": 18,
      "anchorSide": "bottom"}, options);
  } else {
    // show the pointer
    $(".folders-popup-toppointer", this.Node).css("visibility", "hidden");
    $(".folders-popup-bottompointer", this.Node).css("visibility", "visible");

    options = $.extend({
      "anchorHandle": "50%",
      "popupHandle": "87%",
      "distance": 18,
      "anchorSide": "top"}, options);
  }

  Helpers.AnchoredPopup.prototype.anchor.call(this, anchor, options);
};

FolderEditPopup.prototype.setupAutoUpdates = function(){
  var nameChangeTimeout, descriptionChangeTimeout;
  var popup = this;

  $(".folders-edit-share", this.Node).change(function(){
    popup.updateFolderIsShared();
  });

  $(".folders-edit-name", this.Node).onvaluechange(function($elem, prev, curr){
    var folderId = popup.getFolderId();

    $(".folders-folder-name[data-folderid='"+folderId+"']").text(curr);

    clearTimeout(nameChangeTimeout);

    nameChangeTimeout = setTimeout(function(){
      popup.updateFolderName();
    }, popup.TextChangeTimeout);
  });

  $(".folders-edit-description", this.Node).onvaluechange(function($elem, prev, curr){
    var folderId = popup.getFolderId(),
        elements = $(".folders-folder-description[data-folderid='"+folderId+"']");

    // set the description while transforming newlines to breaks
    elements.each(function(){
      var element = $(this);

      element.text(curr);
      element.html(element.html().replace(/(\r\n|\n\r|\r|\n)/g, "<br />"));
    });

    clearTimeout(descriptionChangeTimeout);

    descriptionChangeTimeout = setTimeout(function(){
      popup.updateFolderDescription();
    }, popup.TextChangeTimeout);
  });

  $(".folders-edit-select", this.Node).click(function(){
    popup.select();
  });

  $(".folders-edit-delete", this.Node).click(function(){
    popup.deleteFolder();
  });
};

FolderEditPopup.prototype.getFolderId = function() {
  return this.FolderId;
};

FolderEditPopup.prototype.getFolderName = function() {
  return $(".folders-edit-name", this.Node).val();
};

FolderEditPopup.prototype.getFolderDescription = function() {
  return $(".folders-edit-description", this.Node).val();
};

FolderEditPopup.prototype.getFolderIsShared = function() {
  return $(".folders-edit-share", this.Node).is(":checked");
};

FolderEditPopup.prototype.setFolderId = function(id) {
  this.FolderId = id;
};

FolderEditPopup.prototype.setFolderName = function(name) {
  $(".folders-edit-name", this.Node).val(name);
};

FolderEditPopup.prototype.setFolderDescription = function(description) {
  $(".folders-edit-description", this.Node).val(description);
};

FolderEditPopup.prototype.setFolderIsShared = function(isShared) {
  if (isShared) {
    $(".folders-edit-share", this.Node).attr("checked", "true");
  } else {
    $(".folders-edit-share", this.Node).removeAttr("checked");
  }
};

FolderEditPopup.prototype.setFolderSelect = function(isSelected) {
  if (isSelected) {
    $(".folders-edit-select", this.Node).attr("checked", "true");
  } else {
    $(".folders-edit-select", this.Node).removeAttr("checked");
  }
};

FolderEditPopup.prototype.updateFolderName = function() {
  var folderId = this.getFolderId(),
      folderName = this.getFolderName(),
      items = $("[data-foldername][data-folderid='"+folderId+"']");

  items.data("foldername", folderName);
  $.get(this.RouterUrl+"?P=P_Folders_UpdateFolderName&SuppressHtmlOutput=1", {
    "FolderId": folderId,
    "FolderName": folderName
  });
};

FolderEditPopup.prototype.updateFolderDescription = function() {
  var folderId = this.getFolderId(),
      folderDescription = this.getFolderDescription(),
      items = $("[data-folderdescription][data-folderid='"+folderId+"']");

  items.data("folderdescription", folderDescription);
  $.get(this.RouterUrl+"?P=P_Folders_UpdateFolderDescription&SuppressHtmlOutput=1", {
    "FolderId": folderId,
    "FolderDescription": folderDescription
  });
};

FolderEditPopup.prototype.updateFolderIsShared = function() {
  var folderId = this.getFolderId(),
      items = $("[data-folderisshared][data-folderid='"+folderId+"']");

  if (this.getFolderIsShared()) {
    $(".folders-header").addClass("folders-isshared");
    items.data("folderisshared", true);
    $.get(this.RouterUrl+"?P=P_Folders_ShareFolder&SuppressHtmlOutput=1", {
      "FolderId": folderId
    });
  } else {
    $(".folders-header").removeClass("folders-isshared");
    items.data("folderisshared", false);
    $.get(this.RouterUrl+"?P=P_Folders_WithdrawFolder&SuppressHtmlOutput=1", {
      "FolderId": folderId
    });
  }
};

FolderEditPopup.prototype.select = function() {
  var folderId = this.getFolderId();

  // only the current folder should be selected
  $("[data-folderselect]").data("folderselect", false);
  $("[data-folderselect][data-folderid='"+folderId+"']").data("folderselect", true);

  $.get(this.RouterUrl+"?P=P_Folders_SelectFolder&SuppressHtmlOutput=1", {
    "FolderId": folderId
  });
};

FolderEditPopup.prototype.deleteFolder = function() {
  var redirect;
  var button = $(".folders-edit-delete", this.Node);

  // disable form input
  $("input, textarea, button", this.Node).attr("disabled", true);

  // let the user know the folder is being deleted
  button.addClass("cw-button-active");
  button.html("Deleting folder...");

  redirect = function() {
    window.location = this.RouterUrl+"?P=P_Folders_ManageFolders";
  };

  $.ajax({
    "url": this.RouterUrl+"?P=P_Folders_DeleteFolder&SuppressHtmlOutput=1",
    "data": { "FolderId": this.getFolderId() },
    "success": redirect
    });
};

FolderEditPopup.prototype.RouterUrl = null;
FolderEditPopup.prototype.FolderId = null;

this.ItemEditPopup = ItemEditPopup;
this.FolderEditPopup = FolderEditPopup;

});
