/*
Copyright Reazon Systems, Inc.  All rights reserved.

This code is protected by US and International Copyright laws.  Reproduction, distribution, 
display, modification and use of the code without written permission of the Reazon Systems, Inc. is prohibited..  
*/

// flag if the form has changed.  This flag is set manually upon a 
// document recall (due to add/del row actions) or by other manual
// operations (e.g. setting the onchange event of FileUpload input
// to do that...
// in order to flag if the form has changed, please do this
//		formChanged["someformname"] = false
//	
var formChanged = new Array();  

// save all initial values of all forms in the document,
// for each form element, its value will be saved in the 
// formVars["formNames__elementname"]
var formVars = new Array();

/**
 * (REQUIRES Form hidden var nextaction)
 * set the value of form.nextaction variable to showDialog.  This action will be passed as
 * a form variable to classlistpost and will be passed back to this template as a URL param.  
 * This template will then execute nextaction.  Hint: value of nextaction is a javascript 
 * command that is run when this template is loaded. 
 */
	function saveListAndLoad(formName, loadURL) {
	var curForm = document.forms[formName];
	 
  if (hasChangedFormVars(formName, false)) {  //if form data has changed, save next action and submit form
    curForm.nextaction.value = "showDialogEdit('" + loadURL + "')";
    curForm.cmd.value = 'save';
	  curForm.submit();
	}  
	else { //form vars haven't changed, don't need to submit form... show edit dialog directly
	  //showDialogEdit(loadURL);
		document.location.href = loadURL;
	}
}

/**
 * OBSOLETE CODE
 *
 * (REQUIRES Form hidden var nextaction)
 * set the value of form.nextaction variable to confirmDelete.  This action will be passed as
 * a form variable to classlistpost and will be passed back to this template as a URL param.  
 * This template will then execute nextaction.  Hint: value of nextaction is a javascript 
 * command that is run when this template is loaded. 
 */
function saveListAndDelete(delId, delDesc, delType, delFile) {
  if (hasChangedFormVars(false)) {  //if form data has changed, save next action and submit form
    document.formdataentry.nextaction.value = 
	    "confirmDelete('" + delId + "','" + delDesc  + "','" + delType + "','" + delFile +"')";
    document.formdataentry.cmd.value = 'save';
	  document.formdataentry.submit();
	}
	else { //form vars haven't changed, don't need to submit form... confirm delete directly
	  confirmDelete(delId, delDesc, delType, delFile);
	}
}

function confirmDeleteSimple() {
	return confirmDeleteSimple("Are you sure you want to delete?");
}

function confirmDeleteSimple(msg) {
	if (! msg) //if msg is undefined
		msg = "Are you sure you want to delete?";
	var agree=confirm(msg);
	if (agree)
		return true ;
	else
		return false ;
}

function confirmDeleteMessage(msg) {

	var agree=confirm(msg);
	if (agree)
		return true ;
	else
		return false ;
}

/**
 *
 */
function confirmDelete(formName, delId, delDesc, delType, delFile) {
	
  var dlgWin = 
	  showDialog('ConfirmDeleteWindow', 
							 'deleteaskc.cfm?id=' + delId + '&desc=' + delDesc + '&type=' + delType + '&delFile=' + delFile, 
							 '400', 
							 '300', 
							 'Yes', 
							 'Yes');
							 
/*  var dlgWin = showDialog('ConfirmDeleteWindow', '__blank.htm', '400', '300', 'Yes', 'Yes');
	
	with (dlgWin.document) {
    open();
    writeln('<html><body><Form name="formdataentry" action="deleteaskc.cfm" method="post">');
		writeln('<input type="hidden" name="id" value="' + delId + '">');
		writeln('<input type="hidden" name="desc" value="' + delDesc + '">');
		writeln('<input type="hidden" name="Type" value="' + delType + '">');
		writeln('<input type="hidden" name="delFile" value="' + delFile + '">');
		writeln('<input type="submit" name="ok" value="">');
		writeln('Please Wait...');
		writeln('</form></body></html>');
		close();

		formdataentry.submit();
	}
	*/

}

/**
 *
 */
function validateAndSubmit(formName) {
	var curForm = document.forms[formName];
	
  if (validateForm(formName)) {
	  curForm.submit();
	}
}

/**
 *
 */
function validateForm(formName) {
 var curForm = document.forms[formName];
 
 if (curForm) {
  var isValid = true;
	var validateMsg = "REQUIRED FIELDS:\n\n";
	
  for (i = 0; i < curForm.elements.length; i++) {
		var curEl = curForm.elements[i];
		
	  if (curEl.required) {
		 if (curEl.value == "") {
		   isValid = false;
			 
		   if (curEl.message) {
  		   validateMsg = validateMsg + curEl.message + "\n\n";
			 }
			 else {
			   validateMsg = validateMsg + curEl.name + 
				               " is invalid...\n\n";
			 }
		 }
		}
  }
  
	if (! isValid) {
	  alert(validateMsg);
	}

	return isValid;
 }
}

/**
 * save all form vars in all forms to the formVars array.
 */
function saveFormVars() {
 var curForm; 	// current form 
 var curFormName;	// current form name
 var el;			// current form element
 
 for (k = 0; k < document.forms.length; k++) {
 
 	// get current form 
   curForm = document.forms[k];

	 if (curForm) {
	 	 // get current form's name
		 if (curForm.name)
			curFormName = curForm.name;
		 else 
			curFormName = "";
			
		// save all form elements in the current form to
		// formVars array
		for (i = 0; i < curForm.elements.length; i++) {
			el = curForm.elements[i];
			switch (el.type)  {
				//no need to save buttons and hidden vars for future comparisons			
				case "button":
				case "hidden":
				case "reset":
				case "submit":
				case "fileupload":  //fileupload is "undefined" initially but is set to empty string 
														// later on.  (too much work, set the formChanged flag instead)
					doSave = false;
					break;
					
				//save all dataentry fields
				case "radio":
					//don't save a radio button unless it's checked (to guarantee only one button is saved)
					doSave =  (el.checked);
					break;
					
				case "checkbox":
				case "text":
				case "textarea":
				case "password":
				case "select-one":
				case "select-many":
					doSave = true;
					
			} //end switch
				
			if (doSave)
				formVars[curFormName + "__" + el.name] = el.value;
		}  
	 }
 }
}

/**
 *
 */
function doCancel(formName) {

  if (hasChangedFormVars(formName, false)) {
	  showDialog('ConfirmCancelWindow', 'cancelaskc.cfm', '400', '300', 'Yes', 'Yes');
	}
	else {
	  close();
	}
	
}

/**
 */
function hasChangedFormVars(formName, verbose) {
	var curForm = document.forms[formName];
	var curFormName;
	var curEl;

	 // get current form's name
	 if (curForm.name)
		curFormName = curForm.name;
	 else 
		curFormName = "";
	
  for (i = 0; i < curForm.elements.length; i++) {
		curEl = curForm.elements[i];
	
    switch (curEl.type)  {
		  //no need to compare buttons and hidden vars 
			case "button":
			case "hidden":
			case "reset":
			case "submit":
			case "fileupload":
			  doCompare = false;
        break;

      //compare dataentry values
			case "radio":
			  //don't compare a radio button unless it's checked
			  doCompare =  (curEl.checked);
				break;
			  
			case "checkbox":
			case "text":
			case "textarea":
			case "password":
			case "select-one":
			case "select-many":
			  doCompare = true;
				
		} //end switch
	
	  if (doCompare) {
		  if (curEl.value != formVars[curFormName + "__" + curEl.name]) {
				  if(verbose) {
					  alert(curEl.name + ' has changed from ' + 
						      formVars[curFormName + "__" + curEl.name] + ' to ' + 
									curEl.value
								 );
					}
	      return true;		   
			} 
		}
	}  
	if (verbose) {
	  alert('no change');
	}
	return false;
}


/**
 * OBSOLETE CODE
 */
function setChangedFlag(formName) {
  
  if (!docChanged) {
	  document.bgColor = "whitesmoke";
	  window.status = "Document has been modified!  Don't forget to save...";
    if (document.all) {
		  visualModifiedFlag.className = "menuitemon";
		}
		else {
		  layerObjs["visualModifiedFlag"].objSetBgColor("red");
			for (i=-800; i < 10; i++) {
			  layerObjs["visualModifiedFlag"].objSetTop(i);
			}
		}
	}

	docChanged = true;
}


/**
 * save x and y coordinate of document within window in two form vars docX and doxY.  These
 * values are used upon submit and recall of the form to scroll back to the previous position.
 *
 * TODO: Testthis
 */
function saveXY(formName){
  //docX and docY must be included in form as hidden vars
	var curForm = document.forms[formName];
	
  if (document.all) {
 	  curForm.docX.value = document.body.scrollLeft;
	  curForm.docY.value = document.body.scrollTop;
	}
	else {
 	  curForm.docX.value = window.pageXOffset;
	  curForm.docY.value = window.pageYOffset;
	}
}

/**
 *
 */
function showPopup(name, pageName, width, height, resizable, scrollbars, menubar, toolbar) {
	var dlgWindow = 
	  window.open(pageName,name,"width=" + width + ",height=" + height + 
		            ",resizable=" + resizable + ",scrollbars=" + scrollbars +
					",menubar=" + menubar+ ",toolbar=" + toolbar
					);
		
	//make sure the new widnow has a link back to opener window (current window).
	if ((document.window != null) && (!dlgWindow.opener))
		dlgWindow.opener = document.window;
			
	dlgWindow.focus();
	
	return dlgWindow;
}


/**
 *
 */
function showDialog(name, pageName, width, height, resizable, scrollbars) {
	return showPopup(name, pageName, width, height, resizable, scrollbars, 'no', 'no');
}

/**
 *
 */
function showDialogWin(winName, pageName) {
  showDialog(winName, pageName, "520", "400", "yes", "yes")
}

/**
 *
 */
function showDialogEdit(pageName) {
  showDialog("EditWindow", pageName, "520", "400", "yes", "yes")
}

/**
 *
 */
function showDialogConfirm(pageName) {
  showDialog("ConfirmWindow", pageName, "520", "350", "yes", "yes")
}

/**
 *
 */
function showHelp(pageName) {
  showDialog("HelpWindow", pageName, "520", "325", "yes", "yes")
}

/**
 *
 * TODO: Test this
 */
//<!--- this function takes a title from the user and adds it to a select drop down list --->
function getSelectItem(formName, linkName, titleLinkName, promptTitle, promptDefault) {
  //<!--- get new value to be added to select box from user --->
  var title =  prompt(promptTitle, promptDefault);
	
  var isInList = false;

  //<!--- add the item to select options if its not null or blank --->
	if (title > "") {
	
   //<!--- create a reference to the select box--->
   var selectList = eval("document." + formName + "." + linkName);

	 
   //<!--- make sure the new value is not already in list --->
	 for (i = 0; i < selectList.options.length; i++) {
	  if (selectList.options[i].text.toUpperCase() == title.toUpperCase()) {
		  isInList = true;
			break;
		}
	 }
	
	 if (isInList) {
	   alert('The value you just entered is already in list:\n' + title)
	 }
	 else {
	 	var insertIndex = selectList.options.length;
	 	if ( insertIndex > 0) {
			if (selectList.options[insertIndex - 1].value == 0) 
				insertIndex = insertIndex - 1;	// replace the previously inserted item
		}
 	  newOption = new Option(title, 0, true, true);
	  selectList.options[insertIndex] = newOption;

	  //<!--- set the value of hidden field to be passed on to the next template which will add 
	  // a record with this title to the appropriate table --->
    var titleElement = eval("document." + formName + "." + titleLinkName);
	  titleElement.value = title;
	 
	  if (!document.all) {
	   //<!--- for navigator resize the screen to force it to refresh the select box --->
	   //outerHeight++;
		 //outerHeight--;
	  }
	 }
	}
}

/** OBSOLETE
 * when a page number from a select box is selected, this function set href of current doc
 * to the given URL and sets the page number to the select boxes selected value
 * 
 * selectBox: the select box object
 * URL: url to call
 * 
 * Prereq:  URL must contain CF URL Token
 * OBSOLETE
 */
function gotoPageNum(selectBox, url) {
  document.location.href = url + "&page=" + selectBox.value;
}

function DoubleList_Add(formName, srcList, descList) {
	DoubleList_Add(formName, srcList, descList, false);
}

function DoubleList_AddAll(formName, srcList, descList) {
	DoubleList_Add(formName, srcList, descList, true);
}


/*
 add all selected item from source list to the destination list
*/
function DoubleList_Add(formName, srcList, descList, isAddAll) {
	var curForm = document.forms[formName];
	var src = curForm[srcList];
	desc = curForm[descList];

	var k = src.selectedIndex;
	
	var firstSelectedIndex = -1;
	k = 0;
	while (k < src.options.length) {
		if (!src.options[k].selected && !isAddAll) 
			k = k + 1;
		else {
			if (firstSelectedIndex < 0)
				firstSelectedIndex = k;
				
			desc.options[desc.options.length] = new Option(src.options[k].text, src.options[k].value);
			src.options[k] = null;
		}
	}
	
	if (firstSelectedIndex < 0) {
		alert('please select an item in the left list'); 
		return;
	} else if (src.options.length > 0)  {
		if (firstSelectedIndex < src.options.length)
			src.selectedIndex = firstSelectedIndex;
		else 
			src.selectedIndex = src.options.length-1;
	}
}

/*
 remove all selected item from destination list to the source list
 */
function DoubleList_Remove(formName, srcList, descList) {
	DoubleList_Add(formName, descList, srcList);
}



/*
 remove all selected item from destination list to the source list
 */
function DoubleList_RemoveAll(formName, srcList, descList) {
	DoubleList_AddAll(formName, descList, srcList);
}

function List_SelectAll(formName, list) {
	var curForm = document.forms[formName];
	var srcList = curForm[list];
	
	k = 0;
	while (k < srcList.options.length) {
		srcList.options[k].selected = true;
		k = k + 1;
	}
}
