/****************************************************************

  Traction Software, Inc. Confidential and Proprietary Information

  Copyright (c) 1996-2005 Traction Software, Inc.
  All rights reserved.

****************************************************************/

// PLEASE DO NOT DELETE THIS LINE -- make copyright depends on it.

/**
 * This source file depends upon the presence of the following additional
 * JavaScript source files:
 *   - /images/modern/js/shared.js
 */


/**
 * Encapsultes the dynamic style manipulations and associated data for
 * a print version window.  It is tightly bound to the implementation
 * details of the SDL template com/traction/sdl/modern/print.sdl, but
 * the skin configuration file controls what abstract numeric font
 * sizes are supported, how the abstract font sizes are defined for
 * different relative font size classifications (such as "small" or
 * "large"), and what abstract sizes should be used for the the
 * various types of elements within the printable content.
 */
var CollectorWindow = {


  COLLECTOR_VIEW_URL: FORM_ACTION_READ_WRITE + "?type=collector",


  COLLECTOR_WINDOW_NAME: "CollectorWindow",


  ACTION_WINDOWS: new Array(),


  memberIDs: new Array(),


  /*****************************************************************************
   *                                                                           *
   * Form Submission Dispatchers                                               *
   *                                                                           *
   *   These functions are invoked, probably directly by a user's button       *
   *   click, in order to trigger a form submission representing various       *
   *   operations associated with creating or editing an article.              *
   *                                                                           *
   ****************************************************************************/


  action: "",


  createNewCollection: function() {
    CollectorWindow.action = "new";
    go("custom_action", document.fm);
  },


  switchCollection: function() {
    CollectorWindow.action = "makecurrent";
    go("custom_action", document.fm);
  },


  clearCollection: function() {
    CollectorWindow.action = "clear";
    go("custom_action", document.fm);
  },


  deleteCollection: function() {
    CollectorWindow.action = "delete";
    go("custom_action", document.fm);
  },


  saveCollectionState: function() {
    CollectorWindow.action = "save";
    go("custom_action", document.fm);
  },


  saveCopy: function() {
    CollectorWindow.action = "savecopy";
    go("custom_action", document.fm);
  },


  executeStandardAction: function() {
    CollectorWindow.action = "standardaction";
    go("custom_action", document.fm);
  },


  sort: function() {
    CollectorWindow.action = "sort";
    go("custom_action", document.fm);
  },


  executeJournalAction: function() {
    CollectorWindow.action = "journalaction";
    go("custom_action", document.fm);
  },


  /*****************************************************************************
   *                                                                           *
   * Event Handlers                                                            *
   *                                                                           *
   *   These functions are called by various other functions or event          *
   *   listeners in order to effect various changes in the form state.         *
   *                                                                           *
   ****************************************************************************/


  /**
   * This function is executed when the type=collector view loads.
   */
  onLoad: function() {
    /**
     * This function is invoked by the wait-for-load /
     * multi-submit-prevention module in order to allow the form
     * submission procedure to include a validation step that occurs only
     * after the module has verified that the page has finished loading
     * and that the form has not already been submitted.
     */
    waitforload_onsubmit = CollectorWindow.onFormValidate;
    register_resize("modern_collector_", document.fm.entryid, document.body, 1, 1, 200, 100);
    window.onresize = handle_resize;
    handle_resize();
    waitforload_ready();
  },


  onsubmitfunctions: new Array(),


  onFormValidate: function() {
    var submitfn = CollectorWindow.onsubmitfunctions[CollectorWindow.action];
    if (submitfn != null) {
      return submitfn();
    } else {
      return true; // no validation required for this action
    }
  },


  onNew: function() {
    document.fm.collector_action.value = "new";
    document.fm.target = "_top";
    return true;
  },


  onMakeCurrent: function() {
    document.fm.collector_action.value = "makecurrent";
    document.fm.target = "_top";
    return true;
  },


  onClear: function() {
    if (confirm( new MessageFormat(i18n("Collector_confirm_Clear", "Clear {0}?")).format(document.fm.collection.value)) ) {
      document.fm.collector_action.value = "clear";
      document.fm.target = "_top";
      return true;
    } else {
      return false;
    }
  },


  onDelete: function() {
    if (confirm(i18n("Collector_confirm_delete_collection",
		     "Are you sure you want to permanently delete this collection?"))) {
      document.fm.collector_action.value = "delete";
      document.fm.target = "_top";
      return true;
    } else {
      return false;
    }
  },


  onSave: function() {
    if (!CollectorWindow.confirmSaveOver()) {
      return false;
    }
    document.fm.collector_action.value = "save";
    CollectorWindow.saveCollectionMembers();
    return true;
  },


  onSaveCopy: function() {
    if (!CollectorWindow.confirmSaveOver()) {
      return false;
    }
    document.fm.collector_action.value = "savecopy";
    CollectorWindow.saveCollectionMembers();
    return true;
  },


  onSubmit: function() {
    return CollectorWindow.onDefaultAction();
  },


  onDefaultAction: function() {
    return CollectorWindow.onSave();
  },


  onExecuteStandardAction: function() {

    var actionname = currentSelValue(document.fm.action);
    var doPost = true;
    var actionWindow = ACTION_WINDOWS[actionname];

    if (actionWindow && actionWindow.url && actionWindow.url != "") {
      doPost = !CollectorWindow.executeActionURL(actionname,
						 actionWindow.url,
						 actionWindow.name,
						 actionWindow.features);
    }
   
    if (doPost) {
      document.fm.target = "_blank";  // send this to a new window
      document.fm.collector_action.value = "standardaction";
      document.fm.submit();
    }

    return false;

  },


  onSort: function() {
    document.fm.collector_action.value = "sort";
    document.fm.target = "_top";
    CollectorWindow.saveCollectionMembers();
    return true;
  },


  moveSelectionUp: function() {
    selShiftUp(document.fm.entryid);
    CollectorWindow.renumber();
    CollectorWindow.makeDirty();
  },


  droppedSomethingOnCollectorTR: function(features) {
    CollectorWindow.showCollector(features);
    document.collectordrop.entriesurl.value = event.dataTransfer.getData("text");
    document.collectordrop.collector_action.value = "addurlentries";
    document.collectordrop.submit();
  },


  droppedSomethingOnCollectorSELECT: function() {
    document.fm.entriesurl.value = event.dataTransfer.getData("text");
    document.fm.collector_action.value = "addurlentries";
    document.fm.target = "_top";
    document.fm.submit();
    window.focus();
  },


  collectPage: function(features) {
    CollectorWindow.showCollector(features);
    document.fm.target = "CollectorWindow";
    document.fm.action.value = "CollectAdd";
    document.fm.submit();
  },


  collectNewspage: function() {
    CollectorWindow.showCollector();
    document.fm.target = "CollectorWindow";
    document.fm.action.value = "CollectNewspage";
    document.fm.submit();
  },


  createCollector: function(features) {

    // added default to use ua() function [ajm 03.Feb.2002]
    if (!features) {
      features = ua("modern_collector_window_features") +
      getSizeAndPosition( ua("modern_collector_window_width"), 
			  ua("modern_collector_window_height") );
    }
    var win = do_window_open(CollectorWindow.COLLECTOR_URL,
			     CollectorWindow.COLLECTOR_WINDOW_NAME,
			     features);
    return win;
  },


  collector_window_: null,


  null_collector_window: function() {
    collector_window_ = null;
  },


  getCollector: function(features) {
    return CollectorWindow.createCollector(features);  // create will return the existing window if the window already exists
  },


  showCollector: function(features) {
    var collector = getCollector(features);
    if (collector) {
      collector.focus();
    }
    return collector;
  },


  renumber: function() {
    var opts = document.fm.entryid;
    var txt, idx, sel;
      // start at one, because you can't move the top one up...
    for(var i=0; i<opts.length; i++) {
      txt = opts[i].text;
      idx = txt.indexOf('.');
      if (idx != -1) {
	sel = opts[i].selected;  // make sure we don't loose the selection
	opts[i].text = (i + 1) + txt.substring(idx);
	opts[i].selected = sel;
      }
    }
  },


  moveSelectionDown: function() {
    selShiftDown(document.fm.entryid);
    CollectorWindow.renumber();
    CollectorWindow.makeDirty();
  },


  selectAllIDs: function() {
    var sel = document.fm.entryid;
    var sz = sel.options.length;
    for (var i=0; i<sz; i++) {
      sel.options[i].selected = true;
    }
  },


  removeSelected: function() {
    // get all the selected items and add them to the selected list
    var opts = document.fm.entryid;
    var i=0;
    while(i<opts.length) {
      if (opts[i].selected) {
	opts[i] = null;
      } else {
	i++;
      }
    } 
    CollectorWindow.renumber();
    CollectorWindow.makeDirty();
  },


  confirmSaveOver: function() {

    // check for overwrite
    var overwrite;
    var newtitle = document.fm.newtitle.value;
    var sel = document.fm.collection;

    // if the title is in the list, but not currently selected, prompt for overwrite
    if (selectContains(sel, newtitle) && newtitle != currentSel(sel)) {
      overwrite = confirm(new MessageFormat(i18n("Collector_confirm_Overwrite", "Overwrite {0}?")).format(newtitle));
    } else {
      overwrite = true;
    }

    if (!overwrite) {
      return false;
    }

    document.fm.overwrite.value = "true";
    document.fm.target = "_top";

    return true;

  },


  getEntryIDs: function() {
    return document.fm.selectiononly.checked ? CollectorWindow.getSelectedIDs() : CollectorWindow.getAllIDs();
  },


  getSelectedIDs: function() {
    var sel = document.fm.entryid;
    var sz = sel.options.length;

    var set = '';
    
    for (var i=0; i<sz; i++) {
      if (sel.options[i].selected) {
	set += ','+sel.options[i].value;
      }
    }
    if (set.length > 0) {
      return set.substring(1);
    } else {
      CollectorWindow.getAllIDs();
    }
  },


  getAllIDs: function() {
    var sel = document.fm.entryid;
    var sz = sel.options.length;
    if (sz > 0) {
      var set = sel.options[0].value;
      for (var i=1; i<sz; i++) {
	set += ','+sel.options[i].value;
      }
      return set;
    }
  },


  makeDirty: function() {
    document.fm.savelist.disabled = false;
    document.fm.savecopy.disabled = (document.fm.newtitle.value == currentSel(document.fm.collection));
  },


  saveCollectionMembers: function(action) {
    var idOptions = document.fm.entryid.options;
    var sz = idOptions.length;
    var idsStr;
    if (sz > 0) {
      idsStr = idOptions[0].value;
      for (var i = 1; i < sz; i ++) {
	idsStr += "," + idOptions[i].value;
      }
    } else {
      idsStr = "";
    }
    document.fm.memberids.value = idsStr;
  },


  checkOnlyOneCollector: function() {

    if (window.name != CollectorWindow.COLLECTOR_WINDOW_NAME && navigator.userAgent.indexOf( "Safari" ) == -1 ) { // window.name is always null in safari?!
      alert(i18n("Collector_warning_only_one_collector_window_at_a_time", "Only one Collector window may be visible at a time."));
      document.location = "about:blank";

      // this prompts for confirmation and isn't really necessary.
      // most likely, someone typed C-n to create a new window, 
      // so give them a new window -- just point it at about:blank
      //    window.close();

      CollectorWindow.showCollector();
    }
  },


  toggleForSelectionOnly: function() {
    document.fm.selectiononly.checked = !document.fm.selectiononly.checked;
  },


  // taken from actionmenu.js (but removed the stuff for curitem and
  // curentry [ajm 23.Jan.2002]
  executeActionURL: function(action, windowUrl, windowName, windowFeatures) {

    if (action == null || trim(action) == "") {
      return false;
    }

    if (document.fm.type) {
      windowUrl = removeURLParameter( windowUrl, "origtype" ) + "&origtype=" + document.fm.type.value;
    }

    // hack on a cache id to compensate for sketchy reloading
    date = new Date();
    id = new String(date.getTime());
    windowUrl = removeURLParameter( windowUrl, "cacheid" ) + "&cacheid=" + id;
    windowUrl = removeURLParameter( windowUrl, "collection" ) + "&collection=" + encode_url_parameter(document.fm.collection.value);

    // 
    windowUrl = removeURLParameter( windowUrl, "selectiononly" ) + "&selectiononly=" + (document.fm.selectiononly.checked ? "true" : "false");

    // lastly, for the collector to execute the action, we need this trigger
    windowUrl = removeURLParameter( windowUrl, "collector_action" ) + "&collector_action=standardaction";

    // and (now lastly), for the collector to handle it, we need to specify it
    windowUrl = removeURLParameter( windowUrl, "form" ) + "&form=collector_new";

    // GET actions must URL encode their parameters; POST actions must not
    // [shep 27.Aug.2004] fix AKJ1926 and Server12352/Server12354
    windowUrl = removeURLParameter( removeURLParameter( removeURLParameter( windowUrl, "curentry" ), "curitem" ), "entryid" ) +
    "&curentry=&curitem=&entryid=" + encode_url_parameter(CollectorWindow.getEntryIDs());

    // Used to fix Server6235 [ajm 07.Feb.2003] by comparing length of
    // windowUrl at this point, but do_window_open addresses that
    // problem now.  [shep 26.Jul.2005]
    Debug.println("windowUrl: ", windowUrl);
    Debug.println("windowName: ", windowName);
    Debug.println("windowFeatures: ", windowFeatures);
    do_window_open(windowUrl, windowName, eval("\'" + windowFeatures + "\'"));

    return true;

  },


  toggleSortOptionsVisibility: function() {
    var sort_options = document.getElementById("sort_options");
    show_TABLE(sort_options.style.display == "none", sort_options);
    var collection_contents = document.getElementById("collection_contents");
    show_TABLE(collection_contents.style.display == "none", collection_contents);
  }


};


CollectorWindow.onsubmitfunctions = {
  "new" : CollectorWindow.onNew,
  "makecurrent" : CollectorWindow.onMakeCurrent,
  "clear" : CollectorWindow.onClear,
  "delete" : CollectorWindow.onDelete,
  "save" : CollectorWindow.onSave,
  "savecopy" : CollectorWindow.onSaveCopy,
  "standardaction" : CollectorWindow.onExecuteStandardAction,
  "journalaction" : null, // CollectorWindow.onExecuteJournalAction not yet supported
  "sort": CollectorWindow.onSort
};
