// $Id: listMaint.js,v 1.63 2009/11/17 17:09:44 sshyu Exp $

function addCommittees() {
  var thenewvalue = "";

  for (i = 0; i < document.listForm.committee.options.length; i++) {
    if (document.listForm.committee.options[i].selected == true) {
      thenewvalue = document.listForm.committee.options[i].value;

      if (document.listForm.displayvalue.options.length == 1) {
        if (document.listForm.name.value == "") {
          document.listForm.displayvalue.options[0].value = thenewvalue;
        } else {
          document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
        }
      } else {
        document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
      }

      document.listForm.value.value = document.listForm.value.value + " " + thenewvalue;
    }
  }

  for (i = 0; i < document.listForm.subcommittee.options.length; i++) {
    if (document.listForm.subcommittee.options[i].selected == true) {
      thenewvalue = document.listForm.subcommittee.options[i].value;

      if (document.listForm.displayvalue.options.length == 1) {
        if (document.listForm.name.value == "") {
          document.listForm.displayvalue.options[0].value = thenewvalue;
        } else {
          document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
        }
      } else {
        document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
      }

      document.listForm.value.value = document.listForm.value.value + " " + thenewvalue;
    }
  }

  document.listForm.dispatch.value = "new";

  document.listForm.displayvalue.focus();
  document.listForm.submit();
}


// on the bill list stand-alone wizard, if a bill list is chosen...add it to the value field
function chooseBillList() {
  var theindex = document.listForm.mylists.selectedIndex;
  if (theindex == 0)
    return; // do nothing
  // if the index is greater than the size of the list set, then assume
  // that the request is a global list set request...
  var thenewvalue = "";
  if (theindex > thelist.length) {
    var i = theindex - (thelist.length + 4);
    if (theglobalblist[i])
      thenewvalue = URLDecode(theglobalblist[i]);
  } else {
    thenewvalue = URLDecode(thelist[theindex - 1]);
    // fill in the name if it is blank
    if (document.listForm.name.value == "") {
      document.listForm.name.value = document.listForm.mylists.options[theindex].text;
    }
  }
  document.listForm.value.value = (document.listForm.value.value.length == 0 ?
      thenewvalue :
      document.listForm.value.value + " " + thenewvalue);
  document.listForm.value.focus();
}

// this is a specialized version of chooseListLoad targeted at the new word list fields.
// listSelector is the select control of the lists that can be selected.
// listValueArea is the text area for the word list value.
// listExcludeField is the text field for the exclude words
// idPrefix is the string prefix for the ids of the radio buttons specifying how the word list is to be used.
// if appendValues is present and true, then the selected values are appended instead of overwriting the current values
// list name field is the optional field name where the list name gets populated
// set the values of all the controls based on the selected list
function chooseWordList(listSelector, listValueArea, listExcludeField, idPrefix, appendValues, listNameField) {
  var theindex = listSelector.selectedIndex;
  var selectedValue = URLDecode(thewlist[theindex - 1]);
  if (appendValues) {
    listValueArea.value = listValueArea.value + " " + selectedValue;
  } else {
    listValueArea.value = selectedValue;
  }
  if (wordListRelatedValues[theindex - 1]) {
    listExcludeField.value = wordListRelatedValues[theindex - 1];
  } else {
    listExcludeField.value = "";
  }
  var valueMode = "0";
  if (wordListValueModes[theindex - 1]) {
    valueMode = wordListValueModes[theindex - 1];
  }
  var rbToSelect = document.getElementById(idPrefix + valueMode + "id");
  rbToSelect.checked = true;
  // if a listNameField was specified AND that field is blank, fill it in with the name of the selected list
  if (listNameField) {
    if (listNameField.value == "") {
      listNameField.value = listSelector.options[theindex].text;
    }
  }
}

// a list is chosen...set the value of the specified field to the list's value
// where the list's value is retrieved from the array thelistset
function chooseListLoad(theindex, thefield, thelistset, thegloballistset, append) {
  if (theindex == 0)
    return; // do nothing
  // if the index is greater than the size of the list set, then assume that
  // the request is a global list set request...
  var thenewvalue = "";
  if (theindex > thelistset.length) {
    var i = theindex - (thelistset.length + 4);
    if (thegloballistset[i])
      thenewvalue = URLDecode(thegloballistset[i]);
  } else {
    thenewvalue = URLDecode(thelistset[theindex - 1]);
  }
  if (append)
    thefield.value = thefield.value + " " + thenewvalue;
  else
    thefield.value = thenewvalue;
  
  thefield.focus();
}

// specialization of chooseListLoad that includes ability to validate and dedupe bills
function chooseListLoadBills(theindex, thefield, thelistset, thegloballistset, append, validate, dedupe) {
  chooseListLoad(theindex, thefield, thelistset, thegloballistset, append);
  
  if (validate) {
    var validatedBills = validateBillNumbers(thefield.value);
    if (validatedBills != null)
      thefield.value = validatedBills;
  }
  
  if (dedupe) {
    var billsArray = thefield.value.split(" ");
    var dedupedBillsArray = new Array();
    for (var n = 0; n < billsArray.length; n++) {
      var bFound = false;
      for (var l = 0; !bFound && l < dedupedBillsArray.length; l++) {
        if (billsArray[n] == dedupedBillsArray[l]) {
          bFound = true;
        }
      }
      if (!bFound) {
        dedupedBillsArray[dedupedBillsArray.length] = billsArray[n];
      }
    }
    var dedupedString = "";
    for (var n = 0; n < dedupedBillsArray.length; n++) {
      dedupedString = dedupedString + (n > 0 ? " " : "") + dedupedBillsArray[n];
    }
    thefield.value = dedupedString;
  }
}

// a list is chosen...select the corresponding values in the list.
function chooseListSelectValues(listSelect, valueSelect) {
  var selectedListName = listSelect.options[listSelect.selectedIndex].value;

  if (listSelect.selectedIndex == 0)
    return; // do nothing
  if (selectedListName == "")
    return; // do nothing

  // Unselect all values
  var options = valueSelect.options;
  for (var i=0; i<options.length; i++) {
    options[i].selected = false;
  }

  // Now select the values based on the list.
  var listValues = "";

  for (var i=0; i<theclistnames.length; i++) {
    if (theclistnames[i] == selectedListName)
      listValues = URLDecode(theclist[i]).split(" ");
  }
  if (listValues == "") {
    for (var i=0; i<theglobalclistnames.length; i++) {
      if (theglobalclistnames[i] == selectedListName)
        listValues = URLDecode(theglobalclist[i]).split(" ");
    }
  }

  var options = valueSelect.options;
  for (var i=0; i<listValues.length; i++) {
    var value = listValues[i];
    for (var j=0; j<options.length; j++) {
      if (options[j].value == value)
        options[j].selected = true;
    }
  }
}


// a list is chosen...set the value of the specified field to the list's value
// where the list's value is retrieved from the array thegloballistset
function chooseGlobalListLoad(theindex, thefield, thegloballistset) {
  if (theindex == 0)
    return; // do nothing

  var i = theindex - 4;
  if (thegloballistset[i])
    thefield.value = URLDecode(thegloballistset[i]);

  thefield.focus();
}

function doCancel(type) {
  if (confirm("Are you sure you want to cancel? (Changes will not be saved)"))
    window.location.href="editlist.do?dispatch=new&type=" + type;
}

function doEditWindow() {
  // open the popup window
  popup = open("lists/popupWordList.html", "PopupWordList", 
       "dependent=yes,scrollbars=yes,width=600,height=400,resizable=yes");
}

// returns false if the form doesn't validate
function validate() {
  // validate based on type of list
  if (document.listForm.type.value == 'BILL') {
    // make sure there is a value
    if (document.listForm.value.value == "") {
      alert("You must enter a value for your bill list.");
      return false;
    }

    var normbills = validateBillNumbers(document.listForm.value.value);
    if (normbills == null)
      return false;
    document.listForm.value.value = normbills;
  } else if (document.listForm.type.value == 'WORD') {
    // make sure the value is not empty and is less than 3000
    if (document.listForm.value.value == "") {
      alert("You must enter a value for your word list.");
      return false;
    }
    if (document.listForm.value.value.length > 3000) {
      alert("Your word list is " + document.listForm.value.value.length +
          " characters long.  It cannot be more than 3000 characters long.");
      return false;
    }
  } else if (document.listForm.type.value == 'MEMBER') {
    if (document.listForm.value.value == "") {
      alert("You must select at least one member for your member list.");
      return false;
    }
  } else if (document.listForm.type.value == 'COMMITTEE') {
    if (document.listForm.value.value == "") {
      alert("You must select at least one committee for your committee list.");
      return false;
    }    
  } else if (document.listForm.type.value == 'VOTE') {
    if (!document.listForm.value || document.listForm.value.value == "") {
      alert("You must select at least one vote for your vote list.");
      return false;
    }
  } else if (document.listForm.type.value == 'LAW') {
    // must have at least one entry
    var el;
    var n = 0;
    var countVal = 0;
    while (countVal < (lcLim + 1)) {
      el = document.getElementById("cite" + n + "editf");
      if (el == null)
        break;
      if (el.value != "")
        ++countVal;
      ++n;
    }
    if (countVal == 0) {
      alert("You must specify at least one entry for your law list.");
      document.listForm.cite.focus();
      return false;
    }
    if (countVal > lcLim) {
      alert("We're sorry, you cannot have more than " + lcLim + " sections in your list.");
      return false;
    }
  }

  // make sure we have a valid save name
  validateNoSpecialCharacters(document.listForm.name, "List Name");
  // make sure there is a name
  if (document.listForm.name.value == "") {
    alert("You must name your list.");
    document.listForm.name.focus();
    return false;
  }

  if (!checkForOverwrite()) {
    if (!confirm("You already have a list named " + document.listForm.name.value +
        ".  Are you sure you want to replace it with this list?")) {
      return false;
    }
  }

  // make sure the comment isn't too long
  if (document.listForm.description.value.length > 1999) {
    alert("Your description cannot be more than 2000 characters.");
    return false;
  }

  return true;
}

function save() {
  if (!validate())
    return;
  document.listForm.dispatch.value = 'save';
  document.listForm.submit();
}

function checkForOverwrite() {
  // check to see if list already exists
  var checkforName = document.listForm.name.value;
  if (document.listForm.name.value == document.listForm.oldname.value)
    checkforName = ""; // don't check if we're saving over...
  if (checkforName != "") {
    var listnamecheck;
    if (document.listForm.mylists)
      listnamecheck = document.listForm.mylists; // use list loader (e.g. word)
    else
      listnamecheck = document.listForm.loadlist; // use list filter (e.g. member)
    for (n = 1; n < listnamecheck.options.length; n++) {
      if (listnamecheck.options[n].text == checkforName) {
        return false;
      }
    }
  }
  return true;
}

function rename() {
  // do regular validation
  if (!validate())
    return;

  // verify name change
  if (document.listForm.name.value == document.listForm.oldname.value) {
    alert("Renaming the list requires that you change the list name.");
    return;
  }
  if (!checkForOverwrite()) {
    alert("A list named " + document.listForm.name.value +
        " already exists, please choose a different name.");
    return;
  }

  document.listForm.action = "editlist.do?dispatch=rename";
  document.listForm.submit();
}

// this function compares bill1 to bill2 and returns true if bill2 is
// greater than bill1
function compareBills(bill1, bill2) {
  var n1 = bill1.search(thesuffixre);
  if (n1 == -1)
    return false;
  var pref1 = bill1.substring(0, n1);
  var thenum1 = Number(bill1.substring(n1));

  var n2 = bill2.search(thesuffixre);
  if (n2 == -1)
    return false;
  var pref2 = bill2.substring(0, n2);
  var thenum2 = Number(bill2.substring(n2));

  if (bprefixes[pref2] < bprefixes[pref1]) {
    return true;
  } else if (bprefixes[pref2] == bprefixes[pref1] &&
    thenum2 < thenum1) {
    return true;
  }
  return false;
}

// this function sorts the document.listForm.value.value as bills
function doBillSort() {
  var splitre = new RegExp("[ ,\n\r\t.;]+");
  var theswap;
  var normbills = validateBillNumbers(document.listForm.value.value);
  if (normbills == null)
    return;
  document.listForm.value.value = normbills;
  var thebills = document.listForm.value.value.split(splitre);
  var count = 0;
  do {
    // in case of unexpected problem, bail out
    if (count++ > 2000) {
      alert("Couldn't complete bill sort.");
      break;
    }
    changed = false;
    for (n = 1; n < thebills.length; n++) {
      if (compareBills(thebills[n-1], thebills[n])) {
        // need to swap
        theswap = thebills[n - 1];
        thebills[n - 1] = thebills[n];
        thebills[n] = theswap;
        changed = true;
      }
    }
  } while (changed);
  
  // thebills is sorted, convert back to string and store
  var thesortedvalue = "";
  for (n = 0; n < thebills.length; n++)
    thesortedvalue = (thesortedvalue.length == 0 ? thebills[n] :
        thesortedvalue + " " + thebills[n]);
  document.listForm.value.value = thesortedvalue;
}

function deleteList(listname, listtype, timestamp) {
  if (confirm("Are you sure you want to delete your list named: " + listname
    + "?")) {
    window.location.href = "editlist.do?dispatch=delete&name=" + listname +
        "&type=" + listtype + "&ts=" + timestamp;
  }
}

// this function called when the user selects one or more "filters" for
// loading list data....
function doFilter() {
  // put all the displayvalue items into the hidden value
  var displayvalue = "";
  // only do this IF we have a displayvalue input
  if (document.listForm.displayvalue) {
    for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
      if (document.listForm.displayvalue.options[n].value != "anonymous") {
        displayvalue = displayvalue + (n == 0 ? "" : " ") +
            document.listForm.displayvalue.options[n].value;
      }
    }
    document.listForm.value.value = displayvalue;
  }
  
  if (document.listForm.loadlist.value != 'anonymous')
    document.listForm.name.value = document.listForm.loadlist.value;
  
  document.listForm.dispatch.value = 'filter';
  document.listForm.submit();
}

// this function called when the congress on a wizard is changed
function changeCongress() {
  document.listForm.dispatch.value = "chgcong";
  document.listForm.submit();
}

// remove the selected displayvalue items from value
function removeItems() {
  document.listForm.loadlist.value = "anonymous";
  document.listForm.dispatch.value = "removeitems";
  // gather the items to remove
  var itemstoremove = "";
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    if (document.listForm.displayvalue.options[n].selected) {
      itemstoremove = itemstoremove + "," +
        document.listForm.displayvalue.options[n].value;
    }
  }
  document.listForm.itemstoremove.value = itemstoremove;
  document.listForm.submit();
}

// remove all the displayvalue items from value
function removeAllItems() {
  // select all items and call removeItems
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    document.listForm.displayvalue.options[n].selected = true;
  }
  removeItems();
}

function removeAllMembers() {
  // select all items and call removeItems
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    document.listForm.displayvalue.options[n].selected = true;
  }
  removeItems();
  document.listForm.displayvalue.options[0] = new Option("No Members Selected", "anonymous");
}

function removeAllCommittees() {
  // select all items and call removeItems
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    document.listForm.displayvalue.options[n].selected = true;
  }
  removeItems();
  document.listForm.displayvalue.options[0] = new Option("No Committees Selected", "anonymous");
}

/////////////////////////////////////////////////////////////////////////////
// this function is invoked by the continue button on the member list
// wizard to generate an anon list
function doContMember()
{
  document.listForm.makeAnonymous.value = 'true';
  document.listForm.name.value = '';
  document.listForm.description.value = '';
  document.listForm.dispatch.value = 'save';
  document.listForm.submit();
}

/////////////////////////////////////////////////////////////////////////////
// this function is used by the vote list wizard and vote report wizard in
// response to the positions/captions button.  It is also used by the show
// bills title link on the edit bill list wizard.
function loadHitList(theform, pageIntegSource) {
  if (pageIntegSource) {
    theform.pageIntegSource.value = pageIntegSource;
  }
  theform.dispatch.value = 'loadlist';
  theform.submit();
}

/////////////////////////////////////////////////////////////////////////////
// This function is used by the vote and bill list wizards to jump to the
// alternate advanced search forms.
function jumpToSearch() {
  document.listForm.dispatch.value = 'jumpto';
  document.listForm.submit();
}

// globals
var bprefixes = new Array("S","SJRES","SCONRES","SRES","HR","HJRES",
    "HCONRES", "HRES","DSAPPS","DS","DSJRES","DSCONRES","DSRES","DHAPPS",
    "DHR","DHJRES","DHCONRES","DHRES");
bprefixes["S"] = 0;
bprefixes["SJRES"] = 1;
bprefixes["SCONRES"] = 2;
bprefixes["SRES"] = 3;
bprefixes["DSAPPS"] = 4;
bprefixes["DS"] = 5;
bprefixes["DSJRES"] = 6;
bprefixes["DSCONRES"] = 7;
bprefixes["DSRES"] = 8;
bprefixes["HR"] = 9;
bprefixes["HJRES"] = 10;
bprefixes["HCONRES"] = 11;
bprefixes["HRES"] = 12;
bprefixes["DHAPPS"] = 13;
bprefixes["DHR"] = 14;
bprefixes["DHJRES"] = 15;
bprefixes["DHCONRES"] = 16;
bprefixes["DHRES"] = 17;
var thesuffixre = new RegExp("[0-9]{1,4}$");

/* START OF MYSTUFF JS */

DocumentManager = {};

DocumentManager.closeOpenWidgets = function()
{
	closeSaveToFolderWidget();
	closeAddNoteToDocWidget();
}

DocumentManager.events = {};
DocumentManager.events.methods = {};
DocumentManager.util = {};
DocumentManager.promptTextFieldInitialized = false;
DocumentManager.currentClickHandler = null;
DocumentManager.folder = {};
DocumentManager.note = {};


DocumentManager.events.initialize = function()
{
	DocumentManager.util.initCookie();
	
	var doc = DocumentManager.cookie.getPair('doc');
	var lastAction = DocumentManager.cookie.getPair('lastAction');
	
	if(doc == window.location.href && lastAction != null)
	{
		var message;

		// display confirmation based on lastAction
		switch(lastAction)
		{
			case 'docSave':
				message = 'Document saved.  You can view your folders on the <a href="/mycq.do#proj">MyCQ page</a>.'
			break;
		
			case 'noteDelete':
				message = 'Note deleted.';
			break;
			
			case 'noteEdit':
				message = 'Changes to note saved.';
			break;
			
			default:
				message = '';
			break;
		}
		
		if(message != '')
		{
			DocumentManager.box.showMessage(message);
		}
	}
	
	// unset doc and last action
	DocumentManager.util.unsetLastAction();
	
	// Init any inline-editable fields
	var inlineFieldOpts = new Array();
	if($('document-note') != null && $('document-note').hasClassName('inline-editable'))
	{
		inlineFieldOpts.push({
			field : $('document-note'),
			onEdit : DocumentManager.note.edit
		}); 
	}

	if($('folder-description') != null && $('folder-description').hasClassName('inline-editable'))
	{
		inlineFieldOpts.push({
			field : $('folder-description'),
			onEdit : DocumentManager.folder.description.edit
		});
	}
  
  if($('folder-name') != null && $('folder-name').hasClassName('inline-editable'))
  {
    inlineFieldOpts.push({
      field : $('folder-name'),
      onEdit : DocumentManager.folder.name.edit
    });
  }
	
	if(inlineFieldOpts.length > 0)
	{
		for(var i = 0; i < inlineFieldOpts.length; i++)
		{
			DocumentManager.util.initInlineEditableField(inlineFieldOpts[i]);		
		}
	}

}

DocumentManager.events.doc = {};

DocumentManager.events.doc.onSave = function()
{
	DocumentManager.util.initCookie();
	DocumentManager.util.setLastAction('docSave');
	window.location.reload();	
}

DocumentManager.events.note = {};

DocumentManager.events.note.onAdd = function()
{
	window.location.reload();
};

DocumentManager.events.note.onDelete = function()
{
  document.addNoteToDocForm.note.value = ""; // clear out the edit note field
	DocumentManager.util.initCookie();
	DocumentManager.util.setLastAction('noteDelete');
	window.location.reload();
};

DocumentManager.events.note.onEdit = function()
{
	DocumentManager.util.initCookie();
	DocumentManager.util.setLastAction('noteEdit');
	window.location.reload();
};


DocumentManager.note.edit = function()
{
	closeDocNoteWidget();
	$('addNoteToDocWidget').show();
};

DocumentManager.note.cancelEdit = function()
{
	showDocNoteWidget();
	$('addNoteToDocWidget').hide();
};

DocumentManager.util.updateNoteLinkLabel = function()
{
	var el = $('showDocNoteLinkId');
	var label = 'Show Note';

	if($('showDocNoteWidget').style.display == 'block')
	{
		label = 'Hide Note';
	}
	
	el.innerHTML = label;
};

DocumentManager.note.closeEditWindow = function()
{
	closeDocNoteWidget();
	$('addNoteToDocWidget').hide();
};

/* FOLDER - NAME, DESCRIPTION */
DocumentManager.folder.name = {};
DocumentManager.folder.description = {};

DocumentManager.folder.description.edit = function()
{
	// show edit form and hide description display
	$('folder-description-container').hide();
	$('edit-folder-description').show();
}

DocumentManager.folder.description.cancelEdit = function()
{
	// hide edit form and show description
	$('folder-description-container').show();
	$('edit-folder-description').hide();
}

DocumentManager.folder.description.validate = function()
{
	var val = document.saveFolderForm.description.value;
	if(val.length > 3000)
	{
		alert('Sorry, but your description must be 3000 characters or less.')
		return false;
	}
	
	return true;
};

DocumentManager.folder.description.remove = function()
{
	if(!confirm("Are you sure you want to delete the folder description?"))	{ return; }	
	
	var id = $F(document.saveFolderForm.id);
	var path = window.location.protocol + '//' + window.location.host + window.location.pathname + '?dispatch=save&id=' + id;
	window.location.replace(path);
}

// folder name stuff
DocumentManager.folder.name.edit = function()
{
  $('editFoldernameWidget').show();
  $('folder-name').hide();
};

DocumentManager.folder.name.cancelEdit = function()
{
  $('editFoldernameWidget').hide();
  $('folder-name').show();
};

DocumentManager.folder.name.submitEditForm = function()
{
	if(DocumentManager.folder.name.validate() && DocumentManager.folder.description.validate())
	{
		document.saveFolderForm.submit();
	}
}

DocumentManager.folder.name.validate = function()
{
	var val = document.saveFolderForm.newFolderName.value;
	if(val.length <= 0)
	{
		alert('Please enter a name for this folder.')
		return false;
	}
	
	if(val.length > 30)
	{
		alert('Sorry, but the name of the folder must be 30 characters or less.')
		return false;
	}
  validateNoSpecialCharacters(document.saveFolderForm.newFolderName, "Folder Name");
	
	return true;
};
// End of foldername stuff


DocumentManager.events.onWidgetOpen = function()
{
	DocumentManager.util.unsetMenuHandler(); // if widget is closed another way, handler may not be unset
	
	if(DocumentManager.ie6click != null && DocumentManager.ie6click.clicked) // ugly IE6 hack to deal with clicking on doc mgr link
	{
		DocumentManager.ie6click.clicked = false;
		DocumentManager.events.methods.close[DocumentManager.ie6click.menu]();
		return false;
	}
	else
	{
		DocumentManager.closeOpenWidgets();
		return true;
	}
}

DocumentManager.box = {};

DocumentManager.box.showMessage = function(message)
{
	$('doc-mgr-message').innerHTML = message;
	$('doc-mgr-message-box').show();
};

DocumentManager.box.hide = function()
{
	$('doc-mgr-message-box').hide();
};

DocumentManager.util.initCookie = function()
{
	DocumentManager.cookie = new Cookie('cqdocmgr','',1);
};

DocumentManager.util.setLastAction = function(action)
{
	if(DocumentManager.cookie == null) { return; }
	DocumentManager.cookie.setPair('doc',window.location.href);
	DocumentManager.cookie.setPair('lastAction',action);
};

DocumentManager.util.unsetLastAction = function()
{
	if(DocumentManager.cookie == null) { return; }
	DocumentManager.cookie.unset();
};


DocumentManager.util.setMenuHandler = function(menu)
{
	var menu = menu;

	var f = function(event)
	{
		if(!DocumentManager.util.handleClick(event,menu))
		{
			DocumentManager.closeOpenWidgets();
			DocumentManager.util.unsetMenuHandler();
		}
	}

	//Event.observe(document,'click',f);
	document.onclick = f;
	DocumentManager.currentClickHandler = f; // so that we can unset this with Prototype later
}

DocumentManager.util.unsetMenuHandler = function()
{
	//Event.stopObserving(window,'click',DocumentManager.currentClickHandler);
	document.onclick = null; // stopObserving doesn't always work?
	DocumentManager.currentClickHandler = null;
}

DocumentManager.util.initInlineEditableField = function(opts)
{
	if(typeof(opts.field) == 'undefined' && typeof(opts.onEdit) != 'function')
	{
		return;
	}
	
	var field = opts.field;
	var f = function()
	{
		var name = 'inline-editable-highlight';
		if(field.hasClassName(name))
		{
			field.removeClassName(name);			
		}
		else
		{
			field.addClassName(name);
		}
	}
	
	opts.field.observe('mouseover',f);
	opts.field.observe('mouseout',f);
	opts.field.observe('click',opts.onEdit);
}

DocumentManager.util.handleClick = function(event,menu)
{
	var target;

	// event.target from quirksmode.org
	if (!event)
	{
		event = window.event;
	}
	if(event.target)
	{
		target = event.target;
	}
	else if(event.srcElement)
	{
		target = event.srcElement; // IE6
	} 
	if(target.nodeType == 3) // defeat Safari bug
	{
		target = target.parentNode;
	}
	
	// if user clicked document link do not check for boundary
	var elClass = target.className;
	if(elClass.match(/doc\-mgr\-link/) == null)
	{
		return DocumentManager.util.targetIsInBoundary(target,menu);		
	}
	else
	{ 
		if(target.click) // IE6
		{
			DocumentManager.ie6click = { clicked: true, menu : menu }; // hack to deal with IE6 weirdness - temporary until better solution is implemented
		}
		else
		{
			target.onclick();
		}
	}
}

DocumentManager.util.targetIsInBoundary = function(target,boundary)
{
	var element = target;
	var boundary = $(boundary);

	if(element == null|| boundary == null)
	{
		return null;
	}
	
	while(true)
	{
		if(element == boundary)
		{
			return true;
		}
		else if(element == document)
		{
			return false;
		}
		else
		{
			element = element.parentNode;
		}
	}
};

// invoked to show the save to folder control for a document
function showSaveToFolderWidget() {
  var el = document.getElementById("saveToFolderLinkId");
  var popup = document.getElementById("saveToFolderWidget");
	if(popup.style.display == 'block')
	{
		closeSaveToFolderWidget();
		return;
	}

	if(!DocumentManager.events.onWidgetOpen()) //ugly hack to deal with IE6
	{
		return;
	}
  var fromLeft = el.offsetLeft;
  var IE = document.all?true:false;
  if (IE) {
    fromLeft = el.offsetLeft+el.offsetParent.offsetLeft;
  }
  popup.style.left = fromLeft+'px';
  popup.style.display = "block";
	DocumentManager.util.setMenuHandler('saveToFolderWidget');
	// check to see if field has been initialized already
	if(DocumentManager.promptTextFieldInitialized != true)
	{
		PromptTextField.init('doc-save-form','folder-name'); 	/* folder save form prompt text box */
		DocumentManager.promptTextFieldInitialized = true;
	}

	// hack to deal with Firefox's Windows Media plugin; it does not respect windowlessvideo property
	if(typeof(video) == 'object' && typeof(video.hide) == 'function')
	{
		video.hide();
	}
}

// close the save to folder control
function closeSaveToFolderWidget() {
	// hack to deal with Firefox's Windows Media plugin; it does not respect windowlessvideo property
	if(typeof(video) == 'object' && typeof(video.show) == 'function' && _floorVideoWindow == null)
	{
		video.show();
	}

  document.saveToFolderForm.newFolderName.value = '';
	PromptTextField.switchText('folder-name');
  document.saveToFolderForm.folderName.selectedIndex = 0;
  document.getElementById("saveToFolderWidget").style.display = "none";
  document.getElementById("saveToFolderWidgetSaved").style.display = "none";
  document.getElementById("saveToFolderWidgetPleaseWait").style.display = "none";
}

// function that adds this document to the user specified doc list in the widget, makes ajax call
function addDocToDocListFromWidget() {
  var isAjaxAvailable = Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
      ) || false;
  if (!isAjaxAvailable) {
    alert("We're sorry, cannot save your document using this browser.  Please contact the Hotline.");
  } else {
		// clear prompt text box value if nothing was specified
		PromptTextField.onFormSubmit('folder-name');
		
    // what is the list name?
    if (document.saveToFolderForm.newFolderName.value == "") {
      alert("You must type a new folder name or select an existing folder before adding this document.");
			PromptTextField.switchText('folder-name');
      return;
    }
    validateNoSpecialCharacters(document.saveToFolderForm.newFolderName, "List Name");
    var listName = document.saveToFolderForm.newFolderName.value;

    var waitImg = document.getElementById("saveToFolderWidgetPleaseWait");
    waitImg.style.display = "block";

    // what is the value to add?
    var valueToAdd = document.saveToFolderForm.recordid.value;

    var params = 'class=DocListSaver&method=save&param0=' + listName + '&param1=' + valueToAdd +
        '&param2=' + document.saveToFolderForm.productId.value;
    var ajaxCall = new Ajax.Request(document.saveToFolderForm.contextPath.value + '/ajax/get.do',
        { method: 'get', parameters: params, onComplete: documentAddedToDocListFromWidget } );
  }
}

// similar to addDocToDocListFromWidget but used to create an empty folder
function createEmptyFolder() {
  // what is the list name?
  var listName = document.createFolderForm.newFolderName.value;
  if (listName == "") {
    alert("You must type a new folder name.");
    return;
  }
  validateNoSpecialCharacters(document.createFolderForm.newFolderName, "List Name");

  var fromMycq = "false";
  if (window.location.href.indexOf("mycq") > -1)
    fromMycq = "true";
  document.createFolderForm.fromMycq.value = fromMycq;

  document.createFolderForm.submit();
}

// handles return from ajax call to save document to a doc list form the widget
function documentAddedToDocListFromWidget(originalRequest) {
  document.getElementById("saveToFolderWidgetPleaseWait").style.display = "none";

  // check the response for a size error
  var root = originalRequest.responseXML.documentElement;
  var responseNodes = root.getElementsByTagName("message");
  var sizeExceeded = false;
  for (var n = 0; n < responseNodes.length; n++) {
    if (responseNodes[n].firstChild.nodeValue == "SIZEEXCEEDED")
      sizeExceeded = true;
  }

  if (sizeExceeded) {
    alert("Error: you tried to save too many documents to this folder.");
  } else {
		DocumentManager.events.doc.onSave(); // reload page and show confirmation message
		/*
    document.getElementById("saveToFolderWidgetSaved").style.display = "block";
    // update list of folders in case a new one was created...
    if (document.saveToFolderForm.newFolderName.value != '') {
      document.saveToFolderForm.folderName.options[document.saveToFolderForm.folderName.length] =
          new Option(document.saveToFolderForm.newFolderName.value, document.saveToFolderForm.newFolderName.value);
    }
     */
  }
}

// delete the specified folder and return
function deleteFolder(folderName, folderId) {
  if (confirm("Are you sure you want to delete " + folderName + " and all of its contents?")) {
    var fromMycq = "false";
    if (window.location.href.indexOf("mycq") > -1)
      fromMycq = "true";
    window.location.href="deletefolder.do?id=" + folderId + "&fromMycq=" + fromMycq;
  }
}

// invoked to show the add note to doc control
function showAddNoteToDocWidget() {
  var el = document.getElementById("addNoteToDocLinkId");
  var popup = document.getElementById("addNoteToDocWidget");
	if(popup.style.display == 'block')
	{
		closeAddNoteToDocWidget();
		return;
	}

	if(!DocumentManager.events.onWidgetOpen()) //ugly hack to deal with IE6
	{
		return;
	}
  var fromLeft = el.offsetLeft;
  var IE = document.all?true:false;
  if (IE) {
    fromLeft = el.offsetLeft+el.offsetParent.offsetLeft;
  }
  popup.style.left = fromLeft+'px';
  popup.style.display = "block";
	//DocumentManager.util.setMenuHandler('addNoteToDocWidget');
}

// close the add note to doc widget
function closeAddNoteToDocWidget() {
  document.getElementById("addNoteToDocWidget").style.display = "none";
  document.getElementById("addNoteToDocWidgetSaved").style.display = "none";
  document.getElementById("addNoteToDocWidgetPleaseWait").style.display = "none";
}

// function that add a note to the current document, makes ajax call
function addNoteToDocFromWidget() {
	if(document.addNoteToDocForm.note.value.length <= 0)
	{
		alert("Please enter a note.")
		return;
	}
  if (document.addNoteToDocForm.note.value.length > 3000) {
    alert("We're sorry.  Your note cannot be more than 3000 characters long.");
    return;
  }

  var isAjaxAvailable = Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
      ) || false;
  if (!isAjaxAvailable) {
    alert("We're sorry, cannot add a note to a document using this browser.  Please contact the Hotline.");
  } else {
    // what is the list name? -- check only if user is not editing a note (form field will not exist if user is editing a note)
			if(typeof(document.addNoteToDocForm.newFolderName) != 'undefined')
			{
		    var listName = document.addNoteToDocForm.newFolderName.value;
		    if (listName == "") {
		      alert("You must type a new folder name or select an existing folder before adding a note to this document.");
		      return;
			}
      validateNoSpecialCharacters(document.addNoteToDocForm.newFolderName, "List Name");
    }

    var waitImg = document.getElementById("addNoteToDocWidgetPleaseWait");
    waitImg.style.display = "block";

    // what is the value to add?
    var valueToAdd = escape(document.addNoteToDocForm.note.value);

    // list name for note list is based on recordid
    var noteListName = document.addNoteToDocForm.recordid.value;

    var params = 'class=NoteListSaver&method=save&param0=' + noteListName + '&param1=' + valueToAdd;
    var ajaxCall = new Ajax.Request(document.saveToFolderForm.contextPath.value + '/ajax/get.do',
        { method: 'get', parameters: params, onComplete: noteAddedToDocFromWidget } );
  }
}

// handles return from ajax call to add a note to a document
function noteAddedToDocFromWidget(originalRequest) {
  // note saved, now save the doc to a project -- only if adding a note.  if editing,
	// field won't be there, so we need to skip the AJAX call in that case
	
	if (typeof(document.addNoteToDocForm.newFolderName) != 'undefined')
	{
  // what is the list name?
  var listName = document.addNoteToDocForm.newFolderName.value;
  // what is the value to add?
  var valueToAdd = document.addNoteToDocForm.recordid.value;

  var params = 'class=DocListSaver&method=save&param0=' + listName + '&param1=' + valueToAdd +
      '&param2=' + document.addNoteToDocForm.productId.value;
  var ajaxCall = new Ajax.Request(document.saveToFolderForm.contextPath.value + '/ajax/get.do',
      { method: 'get', parameters: params, onComplete: documentAddedToDocListAfterNoteSave } );
  }
	else
	{
		documentAddedToDocListAfterNoteSave();
	}
		
}

// handles return from ajax call to save doc to doc list after a note is saved
function documentAddedToDocListAfterNoteSave(originalRequest) {
	if($F('doc-mgr-note-form-type') == 'edit')
	{
		DocumentManager.events.note.onEdit();
	}
	else
	{
		DocumentManager.events.note.onAdd();
	}
	/*
  document.getElementById("addNoteToDocWidgetPleaseWait").style.display = "none";
  document.getElementById("addNoteToDocWidgetSaved").style.display = "block";
  */
}

// invoked to show a note on a document
function showDocNoteWidget() {
  var el = document.getElementById("showDocNoteLinkId");
  var popup = document.getElementById("showDocNoteWidget");
	if(popup.style.display != 'none')
	{
		closeDocNoteWidget();
		return;
	}

  DocumentManager.note.closeEditWindow(); // edit window open?  close it.
  
/*
	if(!DocumentManager.events.onWidgetOpen()) //ugly hack to deal with IE6
	{
		return;
	}
  var fromLeft = el.offsetLeft;
  var IE = document.all?true:false;
  if (IE) {
    fromLeft = el.offsetLeft+el.offsetParent.offsetLeft;
  }
 */
  //popup.style.left = fromLeft+'px';
  popup.style.display = "block";
	DocumentManager.util.updateNoteLinkLabel();
	//DocumentManager.util.setMenuHandler('showDocNoteWidget');
}

// close the add note to doc widget
function closeDocNoteWidget() {
  document.getElementById("showDocNoteWidget").style.display = "none";
	DocumentManager.util.updateNoteLinkLabel();
}

// invoked when the user chooses doc ag function from the folder display page
function folderDocAg() {
	// check to see if there are any selected docs
	if($(document.controlFolderForm).serialize().indexOf('desiredHits') < 0)
	{
		alert('No documents have been selected.  Please select one or more documents and try again.');
		return;
	}

  document.controlFolderForm.submit();
}

// invoked when the user chooses remove function from the folder display page
function folderRemoveDocs() {
	// check to see if there are any selected docs
	if($(document.controlFolderForm).serialize().indexOf('desiredHits') < 0)
	{
		alert('No documents have been selected.  Please select some documents and try again.');
		return;
	}
	
	if (confirm("Are you sure you want to remove the selected document(s) from this folder?"))
	{
	  document.controlFolderForm.dispatch.value = "remove";
	  document.controlFolderForm.submit();		
	}
}

// delete the specified note and return
function deleteNote(noteListId) {
  if (confirm("Are you sure you want to delete this note?")) {

    var isAjaxAvailable = Try.these(
        function() {return new ActiveXObject('Msxml2.XMLHTTP')},
        function() {return new ActiveXObject('Microsoft.XMLHTTP')},
        function() {return new XMLHttpRequest()}
        ) || false;
    if (!isAjaxAvailable) {
      alert("We're sorry, cannot delete this note using this browser.  Please contact the Hotline.");
    } else {
      var waitImg = document.getElementById("deletingNoteWidgetPleaseWait");
      waitImg.style.display = "block";

      var params = 'class=DocNoteDeleter&method=delete&param0=' + noteListId;
      var ajaxCall = new Ajax.Request(document.saveToFolderForm.contextPath.value + '/ajax/get.do',
          { method: 'get', parameters: params, onComplete: noteDeletedFromWidget } );
    }
  }
}

function noteDeletedFromWidget(originalRequest) {
	DocumentManager.events.note.onDelete();
	/*
  document.addNoteToDocForm.note.value = ""; // clear out the edit note field
  document.getElementById("showDocNoteLinkId").style.display = "none";
  closeDocNoteWidget();
  */
}

// when user chooses an existing folder from the drop list
function folderNameSelected(f) {
  if (f.folderName.selectedIndex == 0) {
    f.newFolderName.value = "Default";
  } else {
    f.newFolderName.value = f.folderName.options[f.folderName.selectedIndex].value;
  }

	PromptTextField.switchText('folder-name');
}

DocumentManager.events.methods.close = 
	{
		saveToFolderWidget : closeSaveToFolderWidget,
		addNoteToDocWidget : closeAddNoteToDocWidget,
		docNoteWidget : closeDocNoteWidget,
		showDocNoteWidget : closeDocNoteWidget
	};

/*
 * Need to use window.onload for legacy docdisplay, because prototype.js is loaded *after* this file loads.
 * With new docdisplay, window.onload does not work for some reason.  Until root cause is determined, 
 * using this method:
 */
if(typeof(Event) != 'undefined' && typeof(Event.observe) != 'undefined')
{
	Event.observe(window,'load',DocumentManager.events.initialize);
}
else
{
	window.onload = DocumentManager.events.initialize;
}

// this function is called as the page displays to fetch any current documents (non archive)
function fetchFolderSavedDocuments(folderid) {
  var isAjaxAvailable = Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
      ) || false;
  if (!isAjaxAvailable) {
    alert("We're sorry, we cannot display your folder using this browser.  Please contact the Hotline.");
  } else {
    var params = 'class=DocManagerSearcher&method=get&param0=' + folderid + "&param1=current";
    var ajaxCall = new Ajax.Request('/ajax/get.do',
          { method: 'get', parameters: params, onComplete: folderSavedDocumentsReady } );
  }
}

// the documents (current) for the folder are ready for display
function folderSavedDocumentsReady(originalRequest) {
  document.getElementById("pleaseWaitPrimaryDataId").style.display = "none";
  document.getElementById("folderSavedDocumentsCurrentId").innerHTML = originalRequest.responseText.replace("&apos;","'");
  if (originalRequest.responseText.indexOf("DocManagerSearcher:FOUNDARCHIVE") > -1) {
    fetchFolderArchiveDocuments(document.saveFolderForm.id.value);
  } else {
    fetchFolderDeletedDocuments(document.saveFolderForm.id.value);
  }
}

// this function is called if archive documents need to be searched for
function fetchFolderArchiveDocuments(folderid) {
  document.getElementById("pleaseWaitArchiveDataId").style.display = "block";
  var params = 'class=DocManagerSearcher&method=get&param0=' + folderid + "&param1=archive";
  var ajaxCall = new Ajax.Request('/ajax/get.do',
        { method: 'get', parameters: params, onComplete: folderArchiveDocumentsReady } );
}

// the documents (current) for the folder are ready for display
function folderArchiveDocumentsReady(originalRequest) {
  document.getElementById("pleaseWaitArchiveDataId").style.display = "none";
  document.getElementById("folderSavedDocumentsArchiveId").innerHTML = originalRequest.responseText.replace("&apos;","'");
  fetchFolderDeletedDocuments(document.saveFolderForm.id.value);
}

// this function is called to retrieve deleted doc info
function fetchFolderDeletedDocuments(folderid) {
  document.getElementById("pleaseWaitCheckDeletedId").style.display = "block";
  var params = 'class=DocManagerSearcher&method=getUnavailable&param0=' + folderid;
  var ajaxCall = new Ajax.Request('/ajax/get.do',
        { method: 'get', parameters: params, onComplete: folderDeletedDocumentsReady } );
}

// the deleted documents are ready for display
function folderDeletedDocumentsReady(originalRequest) {
  document.getElementById("pleaseWaitCheckDeletedId").style.display = "none";
  var root = originalRequest.responseXML.documentElement;
  var docNodes = root.getElementsByTagName("doc");
  var buffer = "";
  for (var n = 0; n < docNodes.length; n++) {
    if (n == 0) {
      document.getElementById("folderDeletedDocumentsId").style.display = "block";
    }
    var title = docNodes[n].getElementsByTagName("title")[0].firstChild.nodeValue;
    var notes = docNodes[n].getElementsByTagName("note");
    var note = "";
    var noteid = "";
    if (notes[0]) {
      note = notes[0].firstChild.nodeValue;
      noteid = notes[0].getAttribute("id");
    }
    var docid = docNodes[n].getElementsByTagName("docid")[0].firstChild.nodeValue;

    buffer = buffer + "<tr><td class='title'>" + title + "</td><td class='note'>" +
      (note != "" ?
          (note + "(<a class='delete-note' href=\"javascript:deleteNote('" + noteid + "')\" title='Delete Note'>delete</a>)")
          : "&nbsp;") +
      "</td><td class='options'><a class='delete-doc' href='displayfolder.do?dispatch=rembyrecid&amp;id=" + document.saveFolderForm.id.value +
      "&amp;recid=" + docid + "' title='Remove document from folder'>Remove document</a></td></tr>";
  }
  document.getElementById("folderDeletedDocumentsContentId").innerHTML = buffer;
}

/* END OF MYSTUFF JS */
