/* Portlet functionality */

(function($) {
  $.fn.portlet = function(options) {
    // build main options before element iteration
    $.fn.portlet.opts = $.extend({}, $.fn.portlet.defaults, options);

    //$("#portlet").height($("#portlet").height());  // Set the height so that columns within have correct 100% height.

    //
    // Make portlets sortable
    //
    return this.each(function() {
      $(this).sortable({
        items: 'div.userPortlet',
        connectWith: ['.portletColumnInner'],
        handle: 'div.portletHeader',
        placeholder: 'drop',
        forcePlaceholderSize: true,
        cursor: 'move',
        tolerance: 'pointer',
        start: StartDrag,
        stop: StopDrag
      });
    });
  };

  //
  // Start Drag
  //
  function StartDrag(e, ui) {
    //ui.item.find("iframe").css("display", "none");
    //$("#portlet").height('auto');    // Set the height to auto so that columns expand as needed.
  }

  //
  // Stop Drag
  //
  function StopDrag(e, ui) {
    //ui.item.find("iframe").css("display", "block");

    SaveChanges($.fn.portlet.opts.contentId);

    //$("#portlet").height($("#portlet").height());    // Set the height so that columns within have correct 100% height.
  }

  //
  // Get portlet data for a given column
  //
  function GetColumnPortlets(colNo) {
    var s = "";

    $("#pCol" + colNo + " div.userPortlet").each(function() {
      if (s != "") {
        s += ",";
      }
      var pId = $(this).attr("id").replace("portlet_", "");
      pId = pId.substring(0, pId.indexOf("_"));
      s += pId;
    });

    return s;
  }

  //
  // Save portlet changes
  //
  function SaveChanges(contentId) {
    var portletOrder = GetColumnPortlets(1) + '|' + GetColumnPortlets(2) + '|' + GetColumnPortlets(3);

    $.get("securearea/dashboard.ashx?contentId=" + contentId + "&data=" + portletOrder);
  }

  //
  // Remove a portlet
  //
  $.fn.portlet.RemovePortlet = function(uniquePortletId, portletId) {
    $('#' + uniquePortletId).remove();

    SaveChanges($.fn.portlet.opts.contentId);
     
    $('li#portletItem_' + portletId).removeClass("disable");
    
    return false;
  }

  //
  // plugin defaults
  //
  $.fn.portlet.defaults = {
    contentId: -1
  };

})(jQuery);