/*
    -===============-
    |azcat_panels.js|
    -===============-
    - This file is intended for use where ever azcat panels appear.  Specifically,
    that is anywhere the admin widget appears, for folder contents and pages based
    on folder contents, admin template navigation (for multiupload and about azcat)
    and edit form for versions actions.
*/

/*global AZCAT,YAHOO,recursivePurgeAndRemove,deleteItem,addMember,deleteMember,
         disableMember,enableMember,sendWelcomeEmail,renameItem,addPageItem,
         doTransition,sortContent,clipboard,doInfo,portal_url,exportContent,
         window,urllib_quote,sortCollections */

/*jslint unparam: true, sloppy: true, nomen: true, indent: 2 */

AZCAT.namespace("dialog");

AZCAT.Dialog = (function () {
  function convertToPixels(value) {
    return parseInt(value, 10);
  }

  function onResizeOrRenderPanel(e) {
    var maxHeight, maxWidth, scrollTop, height, width, newWidth;
    YAHOO.util.Dom.setStyle(this.body, "overflow", "auto");
    if (this.id !== "waitStatus" && this.element) {
      maxHeight = YAHOO.util.Dom.getViewportHeight() - 100;
      if (!this.has_an_overriding_width) {
        maxWidth = YAHOO.util.Dom.getViewportWidth() - 100;
        scrollTop = this.body.scrollTop;
        if (YAHOO.env.ua.ie === 6) {
          YAHOO.util.Dom.setStyle(this.body, "width", "auto");
        } else {
          YAHOO.util.Dom.setStyle(this.innerElement, "width", "auto");
        }
      }
      YAHOO.util.Dom.setStyle(this.body, "height", "auto");
      if (!this.has_an_overriding_width) {
        width = this.body.scrollWidth + (convertToPixels(YAHOO.util.Dom.getStyle(this.body, 'padding-left')) + convertToPixels(YAHOO.util.Dom.getStyle(this.body, 'padding-right')));
        YAHOO.util.Dom.setStyle(this.innerElement, "width", (width > maxWidth ? maxWidth : width) + "px");
        if (YAHOO.env.ua.ie === 6) {
          newWidth = (width > maxWidth ? maxWidth : width) - 20;
          newWidth = newWidth > 0 ? newWidth : 0;
          YAHOO.util.Dom.setStyle(this.body, "width", newWidth + "px");
        }
      }
      height = this.body.scrollHeight - (convertToPixels(YAHOO.util.Dom.getStyle(this.body, 'padding-top')) + convertToPixels(YAHOO.util.Dom.getStyle(this.body, 'padding-bottom'))) + 1;
      YAHOO.util.Dom.setStyle(this.body, "height", (height > maxHeight ? maxHeight : height) + "px");
      if (scrollTop) {
        this.body.scrollTop = scrollTop;
      }
    }
    this.resizeEvent.fire(this);
  }

  function onResizeOrRenderPanelFull(e) {
    var maxHeight, maxWidth;
    maxWidth = YAHOO.util.Dom.getViewportWidth() - 100;
    maxHeight = YAHOO.util.Dom.getViewportHeight() - 100;
    YAHOO.util.Dom.setStyle(this.body, "overflow", "auto");
    if (YAHOO.env.ua.ie === 6) {
      YAHOO.util.Dom.setStyle(this.body, "width", maxWidth + 'px');
    } else {
      YAHOO.util.Dom.setStyle(this.innerElement, "width",  maxWidth + 'px');
    }
    YAHOO.util.Dom.setStyle(this.body, "height", maxHeight + 'px');
    this.center();
    this.resizeEvent.fire(this);
  }

  function onBeforeHidePanel() {
    var myels = YAHOO.util.Dom.getElementsByClassName('bd', 'div', this.element);
    YAHOO.util.Dom.setStyle(myels[0], 'overflow', 'hidden');
    /* We subscribe destroy to hideEvent here, rather during
       initialization, because there are other functions that
       must run before destroy that are subscribed to hideEvent
       after the initialization.
       Also, if animation is not enabled, hideEvent is fired immediately after
       hiding the contents of the Dialog in the DOM. If we subscribe
       this.destroy to the hide event, events that are fired after the
       hideEvent are removed while YUI expects them to be there, causing
       errors. We subscribe to configChangedEvent instead, as this is the last
       event run after hiding if there are no animations.
    */
    if (this.cfg.getProperty("effect")) {
      this.hideEvent.subscribe(this.destroy);
    } else {
      this.cfg.configChangedEvent.subscribe(
        function (event_type, config_changes, context) {
          var x, xlen, config_change;
          for (x = 0, xlen = config_changes.length; x < xlen; x += 1) {
            config_change = config_changes[x];
            if (config_change.length === 2 &&
                config_change[0] === "visible" &&
                config_change[1] === false) {
              this.destroy();
            }
          }
        },
        this,
        true
      );
    }
    myels = null;
  }

  function destroy() {
    YAHOO.widget.Panel.prototype.destroy.call(this);
    this.unsubscribeAll();
    YAHOO.util.Event.removeListener(window, "resize", onResizeOrRenderPanel);
    YAHOO.util.Event.removeListener(window, "resize", onResizeOrRenderPanelFull);
    if (this.dd) {
      recursivePurgeAndRemove(this.dd._domRef);
      this.dd._domRef = null;
    }
    this.close = null;
    this.innerElement = null;
    this.focusableElements = null;
    this.resizeMonitor = null;
  }

  function goFullScreen() {
    YAHOO.util.Event.removeListener(window, "resize", onResizeOrRenderPanel, this);
    this.changeBodyEvent.unsubscribe(onResizeOrRenderPanel, this);
    YAHOO.util.Event.addListener(window, "resize", onResizeOrRenderPanelFull, this, true);
    this.changeBodyEvent.subscribe(onResizeOrRenderPanelFull, this, true);
    onResizeOrRenderPanelFull.call(this);
  }

  function unFullScreen() {
    YAHOO.util.Event.removeListener(window, "resize", onResizeOrRenderPanelFull, this);
    this.changeBodyEvent.unsubscribe(onResizeOrRenderPanelFull, this);
    YAHOO.util.Event.addListener(window, "resize", onResizeOrRenderPanel, this, true);
    this.changeBodyEvent.subscribe(onResizeOrRenderPanel, this, true);
    onResizeOrRenderPanel.call(this);
  }

  function focusCloseButton() {
    if (this.close) {
      this.close.focus();
    }
  }

  return function (isMultiUpload, id, config) {
    var that, x, has_an_overriding_width,
      azcatConfig = {width: "30em",
                     fixedcenter: true,
                     constraintoviewport: true,
                     underlay: "none",
                     close: true,
                     visible: false,
                     draggable: true,
                     modal: true
                     };
    if (YAHOO.util.Anim) {
      azcatConfig.effect = {effect: YAHOO.widget.ContainerEffect.FADE, duration: 0.25};
    }
    for (x in config) {
      if (config.hasOwnProperty(x)) {
        azcatConfig[x] = config[x];
        if (x === "width") {
          has_an_overriding_width = true;
        }
      }
    }

    that = new YAHOO.widget.Panel(id || "azcat_dialog", azcatConfig);
    if (has_an_overriding_width) {
      that.has_an_overriding_width = true;
    }
    that.renderEvent.subscribe(onResizeOrRenderPanel, that, true);
    that.renderEvent.subscribe(that.center, that, true);
    that.showEvent.subscribe(focusCloseButton, that, true);
    YAHOO.util.Event.on(window, "resize", onResizeOrRenderPanel, that, true);
    that.changeBodyEvent.subscribe(onResizeOrRenderPanel, that, true);
    that.beforeHideEvent.subscribe(onBeforeHidePanel, that, true);
    that.headerleft = '<div class="tl"></div><span>';
    that.headerright = '</span><div class="tr"></div>';
    that.footerleft = '<div class="bl"></div><span>';
    that.footerright = '</span><div class="br"></div>';
    that.destroy = destroy;
    that.goFullScreen = goFullScreen;
    that.unFullScreen = unFullScreen;
    that.confirmEvent = new YAHOO.util.CustomEvent('confirm_dialog_event');
    that.denyEvent = new YAHOO.util.CustomEvent('deny_dialog_event');
    that.closeEvent = new YAHOO.util.CustomEvent('close_dialog_event');
    that.resizeEvent = new YAHOO.util.CustomEvent('resize_dialog_event');
    return that;
  };
}());

AZCAT.dialog.actionCode = {
  'delete': function (e, dialogParams) {
    deleteItem(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'addMember': function (e, dialogParams) {
    addMember(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'deleteMember': function (e, dialogParams) {
    deleteMember(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'disableMember': function (e, dialogParams) {
    disableMember(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'enableMember': function (e, dialogParams) {
    enableMember(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'welcomeEmail': function (e, dialogParams) {
    var x, xLen;
    dialogParams.cmf_uids = [];
    for (x = 0, xLen = dialogParams.ids.length; x < xLen; x += 1) {
      dialogParams.cmf_uids.push(AZCAT.siteman.dataView.getCMFUIDfromPath(dialogParams.ids[x]));
    }
    sendWelcomeEmail(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'rename_items' : function (e, dialogParams) {
    renameItem(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'addpage' : function (e, dialogParams) {
    addPageItem(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'sortcontent' : function (e, dialogParams) {
    sortContent(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'sortcollections' : function (e, dialogParams) {
    sortCollections(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'retract' : function (e, dialogParams) {
    doTransition(e, 'retract', dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'publish' : function (e, dialogParams) {
    doTransition(e, 'publish', dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'submit' : function (e, dialogParams) {
    doTransition(e, 'submit', dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'reject' : function (e, dialogParams) {
    doTransition(e, 'reject', dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'pastehere' : function (e, dialogParams) {
    AZCAT.siteman.dataView.pasteHere(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'cut' : function (e, dialogParams) {
    var x, xLen;
    clipboard.items = [];
    for (x = 0, xLen = dialogParams.ids.length; x < xLen; x += 1) {
      clipboard.items.push(AZCAT.siteman.dataView.getCMFUIDfromPath(dialogParams.ids[x]));
    }
    clipboard.action = 'cut';
    AZCAT.siteman.dataView.insertPasteAction();
    YAHOO.util.Event.stopEvent(e);
  },
  'copy' : function (e, dialogParams) {
    var x, xLen;
    clipboard.items = [];
    for (x = 0, xLen = dialogParams.ids.length; x < xLen; x += 1) {
      clipboard.items.push(AZCAT.siteman.dataView.getCMFUIDfromPath(dialogParams.ids[x]));
    }
    clipboard.action = 'copy';
    AZCAT.siteman.dataView.insertPasteAction();
    YAHOO.util.Event.stopEvent(e);
  },
  'revert' : function (e, dialogParams) {
    AZCAT.editForm.image.doRevert(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'info' : function (e, dialogParams) {
    doInfo(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'preformat' : function (e, dialogParams) {
    var obj, onclickParams, y, yLen, powerFilter, staticData, dynamicData, attr, objAttr;
    YAHOO.util.Event.stopEvent(e);
    if (dialogParams.ids.length) {
      obj = AZCAT.siteman.dataView.getCMFUIDfromPath(dialogParams.ids[0]);
      obj = dialogParams.callback_scope._parent.data.getData(obj);
      onclickParams = null;
      for (y = 0, yLen = obj.actions.length; y < yLen; y += 1) {
        if (obj.actions[y].id === "preformat") {
          onclickParams = JSON.parse(obj.actions[y].onclick.replace("javascript:", ""));
          break;
        }
      }
      if (!onclickParams) {
        throw "No onclickParams found for preformat action for " + obj.portal_type + ".";
      }
      if (onclickParams.power_filter) {
        powerFilter = ["_submit_=1"];
        staticData = onclickParams.power_filter.staticData;
        if (staticData) {
          for (attr in staticData) {
            if (staticData.hasOwnProperty(attr)) {
              powerFilter.push(attr + "=" + urllib_quote(staticData[attr]));
            }
          }
        }
        dynamicData = onclickParams.power_filter.dynamicData;
        for (attr in dynamicData) {
          if (dynamicData.hasOwnProperty(attr)) {
            objAttr = obj[dynamicData[attr]];
            if (objAttr === "undefined") {
              throw "dynamicData values through a power_filter preformat that do not exist as columns is not implemented.  Attribute requested was " + attr + " on " + obj.cmf_uid + ".";
            }
            powerFilter.push(attr + "=" + urllib_quote(objAttr));
          }
        }
        YAHOO.util.Cookie.set("prefilter", JSON.stringify(powerFilter.join("&")), {"path" : "/"});
        YAHOO.util.Cookie.set("prefilter_type", "power_filter", {"path" : "/"});
      } else {
        YAHOO.util.Cookie.set("prefilter", obj.title, {"path" : "/"});
      }
      window.location.href = ([portal_url, "/site_manager#", onclickParams.fragment]).join("");
    }
  },
  'exportContent' : function (e, dialogParams) {
    AZCAT.exportContent = AZCAT.ExportContent(e, dialogParams);
    YAHOO.util.Event.stopEvent(e);
  },
  'upload': function (e) {
    AZCAT.uploader.openUploadDialog();
    YAHOO.util.Event.stopEvent(e);
  },
  'emailUsers': function (e, dialogParams) {
    YAHOO.util.Event.stopEvent(e);
    var cmf_uid, cmf_uidlen, row, action, actionlen, extraArgs;
    for (cmf_uid = 0, cmf_uidlen = dialogParams.cmf_uids.length; cmf_uid < cmf_uidlen; cmf_uid += 1) {
      row = dialogParams.callback_scope._parent.data.getData(dialogParams.cmf_uids[cmf_uid]);
      for (action = 0, actionlen = row.actions.length; action < actionlen; action += 1) {
        if (row.actions[action].id === "emailUsers") {
          extraArgs = JSON.parse(row.actions[action].onclick.replace("javascript:", ""));
          // assume that we are dealing with the same portal type.
          break;
        }
      }
    }
    AZCAT.emailer.openEmailDialog(e, YAHOO.lang.merge(dialogParams, extraArgs));
  },
  'getImportTemplate': function (e) {
      getImportTemplate();
      YAHOO.util.Event.stopEvent(e);
  },
  'importContent': function (e, dialogParams) {
      importContent(e, dialogParams);
      YAHOO.util.Event.stopEvent(e);
  }
};

AZCAT.dialog.actionConditions = {
  'delete': function (params) {
    if (params.id === "index_html") {
      return false;
    }
    if ((AZCAT.siteman.dataView.getViewType() === 'Tree' &&
         params.cmf_uid !== AZCAT.siteman.data.root_cmf_uid) ||
        AZCAT.siteman.dataView.getViewType() !== 'Tree') {
      return true;
    }
  },
  'cut': function (params) {
    if (params.id === "index_html") {
      return false;
    }
    if (AZCAT.siteman.dataView.getViewType() === 'Tree' &&
        params.cmf_uid !== AZCAT.siteman.data.root_cmf_uid) {
      return true;
    }
  },
  'copy': function (params) {
    if (params.id === "index_html") {
      return false;
    }
    if (AZCAT.siteman.dataView.getViewType() === 'Tree' &&
        params.cmf_uid !== AZCAT.siteman.data.root_cmf_uid) {
      return true;
    }
  }
};

