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

//Ensure all of the folders and their items have loaded.
$(document).ready(function() {

// Folder Clearing Popup

  //Get all the links to clear a folder
  FolderClearLinks = $("a").filter(".cw-folders-clear-confirmlink");

  //Set up the dialog box for each folder clearing link
  FolderClearLinks.each(function(link) {
    //Do an additional check to ensure we have the right link
    //because IE8 doesn't support filter, can be removed
    //when we stop supporting IE8
    var classarray = FolderClearLinks[link].className.split(' ');
    if($.inArray('cw-folders-clear-confirmlink'), classarray){
    //Get the folderid from the link element
    folderid = FolderClearLinks[link].getAttribute('data-folderid');
    createClearDialogBox(folderid, link);
    createClearClickCallback(folderid, link);
    }
  });

  // Function to set up the click callbacks to avoid issues with closures in loops.
  // @param folderid the id of the folder
  // @param a the link object
  function createClearClickCallback(folderid, link) {
      //Set up the click listener for dialog opening
      $("#cw-folders-folderlink"+folderid).click(function(e) {
        e.preventDefault();
        var targetUrl = FolderClearLinks[link].href;

        $("#cw-folders-folderclear"+folderid).dialog('option', 'buttons', {
            "Confirm" : function() {
            //Confirm clicks lead to a folder clear
              window.location.href = targetUrl;
            },
            "Cancel" : function() {
              $(this).dialog("close");
            }
          });

        //Open the dialog box itself, finally, when the link is clicked.
        $("#cw-folders-folderclear"+folderid).dialog("open");
      });
    };

  // Function to set up the jQuery dialog boxes to avoid issues with closures in loops.
  // @param folderid the id of the folder
  function createClearDialogBox(folderid) {
      $("#cw-folders-folderclear"+folderid).dialog({
        dialogClass: "cw-folders-folderclear cw-no-close",
        autoOpen: false,
        open: function() {
        //Place the overlay behind the dialog box when it's opened
          var overlay = document.createElement("div");
          overlay.className = "cw-dialog-overlay";
          $("body").append(overlay);
        },
        close: function() {
        //Remove the overlay when the dialog closes
          $(".cw-dialog-overlay").remove();
        },
        modal: true,
        bgiframe: true,
      });
  }

// Name Editing Popup
  //Get all the links to edit a folder
  FolderNameEditLinks = $("a").filter(".cw-folders-editnamelink");

  //Set up the dialog box for each folder editing link
  FolderNameEditLinks.each(function(link) {
    //Do an additional check to ensure we have the right link
    //because IE8 doesn't support filter, can be removed
    //when we stop supporting IE8
    var classarray = FolderNameEditLinks[link].className.split(' ');
    if($.inArray('cw-folders-editnamelink'), classarray){
    //Get the folderid from the link element
    folderid = FolderNameEditLinks[link].getAttribute('data-folderid');
    createNameDialogBox(folderid, link);
    createNameClickCallback(folderid, link);
    }
  });

  // Function to set up the click callbacks to avoid issues with closures in loops.
  // @param folderid the id of the folder
  // @param a the link object
  function createNameClickCallback(folderid, link) {
      //Set up the click listener for dialog opening
      $("#cw-folders-namechange"+folderid).dialog('option', 'buttons', {
          "Change Name" : function() {
          //Confirm clicks lead to a name edit
           //click callback function handles this
          },
          "Cancel" : function() {
            $(this).dialog("close");
          }
        });
      foldername = $("#cw-folders-namechange"+folderid).attr("data-foldername");
      $("#cw-folders-namechange"+folderid).parent().children(".ui-dialog-titlebar").children("span.ui-dialog-title").append("<i>" + foldername + "</i>")
      $("#cw-folders-foldernamelink"+folderid).click(function(e) {
        e.preventDefault();

        //Open the dialog box itself, finally, when the link is clicked.
        $("#cw-folders-namechange"+folderid).dialog("open");
      });
    };

  // Function to set up the jQuery dialog boxes to avoid issues with closures in loops.
  // @param folderid the id of the folder
  function createNameDialogBox(folderid) {
      $("#cw-folders-namechange"+folderid).dialog({
        dialogClass: "cw-folders-namechange cw-no-close",
        autoOpen: false,
        open: function() {
        //Place the overlay behind the dialog box when it's opened
          var overlay = document.createElement("div");
          overlay.className = "cw-dialog-overlay";
          $("body").append(overlay);
          changelink = $("#cw-folders-namechange"+folderid).siblings(".ui-dialog-buttonpane").children().children().first();
          nameinput = $("#cw-folders-namechange"+folderid).children("input[name*='FolderName']");
          changelink.click(Folders_FoldersRenameFolderClickCallback);
        },
        close: function() {
        //Remove the overlay when the dialog closes
          $(".cw-dialog-overlay").remove();
        },
        modal: true,
        bgiframe: true,
      });
  }

  $(".cw-folders-addresource").click(Folders_FoldersAddResourceButtonClickCallback);
  $(".cw-folders-removeresource").click(Folders_FoldersRemoveResourceButtonClickCallback);
  $(".cw-folders-addallsearch").click(Folders_FoldersAddAllSearchButtonClickCallback);

  // align tags
  var width = 0;
  $(".cw-resourcesummary-resourcetype-tag").each(function(){
    width = Math.max($(this).width(), width);
  });
  $(".cw-resourcesummary-resourcetype-tag").css("width", width+"px");
});

function Folders_FoldersRenameFolderClickCallback(event)
{
  // ensure that we don't go straight to the href - we interupt and process via AJAX if
  //javascript is available
  event.preventDefault();

  FolderId = $(event.currentTarget).parent().parent().parent().children(".cw-folders-dialog-namechange").attr('data-folderid');
  FolderName = $(event.currentTarget).parent().parent().parent().children(".cw-folders-dialog-namechange").children("input").val();
  ChangeURL = $(event.currentTarget).parent().parent().parent().children(".cw-folders-dialog-namechange").attr('data-ajaxlink') + encodeURIComponent(FolderName);
  // need to append the root URL to ChangeURL
  ChangeURL = CWIS_BASE_URL + ChangeURL;

    $.ajax({type: "POST",
            url: String(ChangeURL),
            data: {folderid: FolderId, foldername: FolderName },
            dataType: 'text',
            success: function(data) {
              dataobject = data.replace('1', '');
              dataobject = jQuery.parseJSON(dataobject);
              response = dataobject["status"]["message"];
              if(response.length > 0){
                // if we have an error, show it
                $("#Folders_Errors" + FolderId).html("<br/>" + dataobject["status"]["message"] + "<br/><br/>");
                $("#Folders_Errors" + FolderId).css("color", "red");
              }
              else
              {
                //display the success message
                $("#cw-folders-namechange"+ FolderId).dialog("close");
                FoldersUpdateSidebarContent();
                $("#cw-folders-nametitle" + FolderId).text(FolderName);
              }
            },
            error: function(jqXHR, textStatus, errorThrown, data) {
              console.log(textStatus, errorThrown);
            }
        });
}

// respond to a click on a resource add button. Makes a call to the AddItem page, adds the
//item to the current folder, and updates the page with success or rejection message
function Folders_FoldersAddResourceButtonClickCallback(event)
{
  // ensure that we don't go straight to the href - we interupt and process via AJAX if
  //javascript is available
  event.preventDefault();

  // get relevent data from the button object
  ItemId = event.currentTarget.getAttribute('data-itemid');
  FolderId = event.currentTarget.getAttribute('data-parentfolderid');
  RemoveUrl = event.currentTarget.getAttribute('data-removeurl');
  ButtonClasses = event.currentTarget.getAttribute('data-buttonclasses');
  AddUrl = event.currentTarget.href;
  XUrl = event.currentTarget.getAttribute('data-xurl');
  PlusUrl = event.currentTarget.getAttribute('data-plusurl');
  ButtonLocation = $(event.currentTarget).offset();
  ButtonHeight = $(event.currentTarget).height();

  // make the Ajax call
    $.ajax({type: "POST",
            url: String(event.currentTarget.href),
            data: {itemid: ItemId },
            success: function(data) {
              dataobject = data;
              response = dataobject["status"]["message"];
              if(response.length > 0){
              // if we have an error, show it
                $("#Folders_ResourceResponse" + ItemId).html("<br/>" + dataobject["status"]["message"] + "<br/>");
                $("#Folders_ResourceResponse" + ItemId).css("color", "red");
              } else {
                //display the success message
                var message = "Item successfully added.";
                FoldersInsertConfirmationPopup("add", message, ItemId, ButtonLocation.left, ButtonLocation.top, ButtonHeight);

                AddRemove = "Remove";

                FoldersInsertNewButton(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl)
                // update sidebar content
                FoldersUpdateSidebarContent();
              }
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus, errorThrown);
            }
            });
}

//respond to a click on a resource remove button. Makes a call to the RemoveItem page, removes the
//item from the current folder, and updates the page with success or rejection message
function Folders_FoldersRemoveResourceButtonClickCallback(event)
{
  //ensure that we don't go straight to the href - we interupt and process via AJAX if
  //javascript is available
  event.preventDefault();

  //get relevent data from the button object
  ItemId = event.currentTarget.getAttribute('data-itemid');
  FolderId = event.currentTarget.getAttribute('data-parentfolderid');
  AddUrl = event.currentTarget.getAttribute('data-addurl');
  ButtonClasses = event.currentTarget.getAttribute('data-buttonclasses');
  RemoveUrl = event.currentTarget.href;
  XUrl = event.currentTarget.getAttribute('data-xurl');
  PlusUrl = event.currentTarget.getAttribute('data-plusurl');
  ButtonLocation = $(event.currentTarget).offset();
  ButtonHeight = $(event.currentTarget).height();

  //make the Ajax call
    $.ajax({type: "POST",
            url: String(event.currentTarget.href),
            data: {itemid: ItemId },
            success: function(data) {
              dataobject = data;
              response = dataobject["status"]["message"];
              if(response.length > 0){
              //if there is an error message, display it
                $("#Folders_ResourceResponse" + ItemId).html("<br/>" + dataobject["status"]["message"] + "<br/>");
                $("#Folders_ResourceResponse" + ItemId).css("color", "red");
              }
              else
              {
              //display the success message
              var message = "Item successfully removed.";
              FoldersInsertConfirmationPopup("remove", message, ItemId, ButtonLocation.left, ButtonLocation.top, ButtonHeight);

              AddRemove = "Add";

              FoldersInsertNewButton(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl)
              // update side bar contents
              FoldersUpdateSidebarContent();
              }
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus, errorThrown);
            }
            });
}

//process a call from the add all results button from the search page. Makes a call
//to the AddSearchResults page and returns a response
function Folders_FoldersAddAllSearchButtonClickCallback(event) {
  //ensure that we don't go straight to the href - we interupt and process via AJAX if
  //javascript is available
  event.preventDefault();

  //make the Ajax call
    $.ajax({type: "POST",
            url: String(event.currentTarget.href),
            data: {},
            success: function(data) {
              dataobject = data;
              response = dataobject["status"]["message"];
              var ButtonLocation = $(event.currentTarget).offset();
              var ButtonHeight = $(event.currentTarget).height();
              if(response.length > 0){
              //display the error if there is one
                FoldersInsertConfirmationPopup("add", response, "all", ButtonLocation.left, ButtonLocation.top, ButtonHeight);
                $(".cw-folders-confirmation-popup").css("color", "red");
              } else {
              //display the success message
              FoldersInsertConfirmationPopup("add", "Resources Successfully Added", "all", ButtonLocation.left, ButtonLocation.top, ButtonHeight);

              //remove all previous resource responses on the page
                $(".cw-folders-resourceresponse").html("");

              //update the buttons for all the resources on the page
                var tabs = $(event.currentTarget).parents(".ui-tabs-panel");
                var d;
                if (tabs.length > 0) {
                  d = tabs.children().find(".cw-folders-addresource");
                } else {
                  d = $(".cw-content-resourcesummary").find(".cw-folders-addresource");
                }

                $.each(d, function(a) {
                  ItemId = d[a].getAttribute('data-itemid');
                  FolderId = d[a].getAttribute('data-parentfolderid');
                  AddUrl = d[a].href;
                  ButtonClasses = d[a].getAttribute('data-buttonclasses');
                  RemoveUrl= d[a].getAttribute('data-removeurl');
                  XUrl = d[a].getAttribute('data-xurl');
                  PlusUrl = d[a].getAttribute('data-plusurl');
                  AddRemove = "Remove";
                  FoldersInsertNewButtonAll(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl)
                });

                //update the sidebar content
                FoldersUpdateSidebarContent();
              }
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus, errorThrown);
            }
            });
}

//updates the sidebar content following a folder action. Calls out to UpdateSidebarContent and
//replaces the current sidebar with what that function returns
function FoldersUpdateSidebarContent()
{
  //make the Ajax call
    $.ajax({type: "POST",
            url: CWIS_BASE_URL + "index.php?P=P_Folders_UpdateSidebarContent",
            data: {},
            dataType: "html",
            success: function(data) {
              if(data.length <= 0){
              //display an error message if we don't get any sidebar data back
                $("#AddAllResourcesResponse").html("<br/>We encountered an error loading the sidebar, please refresh the page.<br/>");
                $("#AddAllResourcesResponse").css("color", "red");
              } else {
              //replace the current sidebar with what the call returns
                $(".cw-folders-sidebar").replaceWith(data);
              }
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus, errorThrown);
            }
            });
}

function FoldersUpdateButton(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl)
{
  //Decide on messages and imagery/wording based on whether the new button will add or remove
  if(AddRemove === "Add")
  {
    ActionClass = "cw-folders-addresource";
    ActionUrl = AddUrl;
    ActionText = "Add this resource to the selected folder";
    ActionImageUrl = PlusUrl;
    CallbackFunction = Folders_FoldersAddResourceButtonClickCallback;
  }
  else
  {
    ActionClass = "cw-folders-removeresource";
    ActionUrl = RemoveUrl;
    ActionText = "Remove this resource from the selected folder";
    ActionImageUrl = XUrl;
    CallbackFunction = Folders_FoldersRemoveResourceButtonClickCallback;
  }

    //insert the add button
    $("#cw-folders-action" + ItemId).replaceWith(
      "<a class=\"" + ButtonClasses + ActionClass + "\"" +
         "href=\"" + ActionUrl + "\" " +
         "id=\"cw-folders-action" + ItemId + "\"" +
         "data-buttonclasses=\"" + ButtonClasses + "\" " +
         "data-removeurl=\"" + RemoveUrl + "\" " +
         "data-addurl=\"" + AddUrl + "\" " +
         "data-parentfolderid=\"" + FolderId + "\" " +
         "data-plusurl=\"" + PlusUrl + "\" " +
         "data-xurl=\"" + XUrl + "\"" +
         "title=\""+ ActionText + "\" data-parentfolderid=\"" + FolderId + "\"" +
         "data-itemid=\"" + ItemId +  "\">" +
         "<img class=\"cw-button-icon\" src=\"" + ActionImageUrl + "\" alt=\"\" />" +
         "Folder" +
      "</a>");

    //ensure all new buttons have the proper click bindings
      $("." + ActionClass).click(CallbackFunction);
}

function FoldersInsertNewButtonAll(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl)
{
    FoldersUpdateButton(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl);
}

function FoldersInsertNewButton(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl)
{
    FoldersUpdateButton(AddRemove, ItemId, FolderId, ButtonClasses, AddUrl, RemoveUrl, PlusUrl, XUrl);
}

function FoldersInsertConfirmationPopup(Action, Message, ItemID, LocX, LocY, ButtonHeight)
{
    const DEFAULT_SHOW_TIME = 2000;
    const POPUP_RIGHT_PADDING = 20;
    const POPUP_TIMER_KEY = "cw.folder.confirmation.pop.timer.key";
    const POPUP_ID = "#cw-folders-confirmation-popup-" + ItemID;

    // create a dummy node to reterive height and width
    var dummy = document.createElement("div");
    dummy.className = "cw-folders-confirmation-popup";
    dummy.id = "cw-folders-confirmation-popup-dummy";
    dummy.style.display = "none";
    $("body").append(dummy);
    var popupWidth = $("#cw-folders-confirmation-popup-dummy").css("width").replace(/[^-\d\.]/g, '');
    var popupHeight = $("#cw-folders-confirmation-popup-dummy").css("height").replace(/[^-\d\.]/g, '');
    $("#cw-folders-confirmation-popup-dummy").remove();

    // calculate popup location
    var PopupX = LocX - POPUP_RIGHT_PADDING - popupWidth;
    var PopupY = (LocY + 0.5 * ButtonHeight) - (0.5 * popupHeight);

    // if there is a pop that's currently showing, just update the content
    if ($(POPUP_ID).length) {
        $(POPUP_ID).html("<p>" + Message + "</p>");
        // we need to reset the timer here
        var currentTimer = $(POPUP_ID).data(POPUP_TIMER_KEY);
        if (currentTimer != null) {
            clearTimeout(currentTimer);
        }

        var newTimer = setTimeout(function(){
            if($(POPUP_ID).length) {
                $(POPUP_ID).remove();
            }
            if (Action == "remove") {
                // remove item on screen
                $(".cw-folders-resource[data-itemid=" + ItemID + "]").remove();
            }
        }, DEFAULT_SHOW_TIME);

        $(POPUP_ID).data(POPUP_TIMER_KEY, newTimer);
        return;
    }

    // create and append popup
    var popup = document.createElement("div");
    popup.id = "cw-folders-confirmation-popup-" + ItemID;
    popup.className = "cw-folders-confirmation-popup";
    $("body").append(popup);
    $(popup).html("<p>" + Message + "</p>");
    popup.style.left = (PopupX + "px");
    popup.style.top = (PopupY + "px");

    // setup timer to remove popup
    var timerHandle = setTimeout(function(){
        if($(POPUP_ID).length) {
            $(POPUP_ID).remove();
        }
        if (Action == "remove") {
            // remove item on screen
            $(".cw-folders-resource[data-itemid=" + ItemID + "]").remove();
        }
    }, DEFAULT_SHOW_TIME);
    $(POPUP_ID).data(POPUP_TIMER_KEY, timerHandle);
}
