// ---- validate at least one field -------------------------------------------- SRM
// Function: Checks to make sure at least ONE of the fields has a value
// Another quick validation tool to make sure at least one of the supplied fields
// has a value in it.
// 
// Usage:
//      formname = the form's name that contains the dropdown
//		fieldnames = the fields you wish to check
function atLeastOneField(formname,fieldnames) {
	bolResults=false;
	arrFields=fieldnames.split(",");
	for(t=0;t<arrFields.length;t++) {
		strValue=eval("document." + formname + "." + arrFields[t] + ".value");
		if(strValue != "" && strValue!= "0") {
			bolResults=true;
		}
		
	}
	return bolResults;
}
// ---- End Validate At Least One Field -----------------------------------------------------

// ---- ShowHideDivs ------------------------------------------------------------ SRM
// Function: change visibility of x number of DIVS passed in CSV
// This actually closes the div and returns used real estate
// Usage: 
//      flag = "none" or "off" to hide, "block" or "on" to show
//      divs = the name or names of divs to perform action.  CSV for multiple
function showhidedivs(flag,divs) {
	if (flag=="off") {
		flag="none";
	}
	if (flag=="on") {
		flag="block";
	}
	
	if (divs.indexOf(",") != -1) {
		arrValues=divs.split(",");
		for(t=0;t<arrValues.length;t++) {
			eval("document.getElementById('" + arrValues[t] + "').style.display='" + flag + "'");
		}
	} else {
		eval("document.getElementById('" + divs + "').style.display='" + flag + "'");
	}
}
// ---- End ShowHideDivs --------------------------------------------------------

// ---- Toggle Disabled ----------------------------------------------------------- SRM
// Function: change the disabled attribute of one or more form fields
// Usage: 
//      flag = "false" or "on" to enable, "true" or "off" to show
//      formname = what form the fields reside in
//      fields = form field or fields to perform action on.  CSV for multiple
// Note: Uses standard ITG CSS values 'forms' and 'formsDisabled'
//       to toggle the visual state of the field.  If you do not have this CSS
//       this function WILL throw an error.
function toggleDisabled(flag,formname,fields) {
	if (flag=="off") {
		flag="false";
		flagclass="forms";
	}
	if (flag=="on") {
		flag="true";
		flagclass="formsDisabled";		
	}
	
	if (fields.indexOf(",") != -1) {
		arrValues=fields.split(",");
		for(t=0;t<arrValues.length;t++) {
			eval("document." + formname + "." + arrValues[t] + ".disabled=" + flag + "");
			eval("document." + formname + "." + arrValues[t] + ".className='" + flagclass + "'");
		}
	} else {
		eval("document." + formname + "." + fields + ".disabled=" + flag + "");
		eval("document." + formname + "." + fields + ".className='" + flagclass + "'");		
	}
}
// ---- End Toggle Fields -------------------------------------------------------

// ---- Toggle Required --------------------------------------------------------- SRM
// Function: toggle fields required or not required and changes the required *
// to on or off as required based on ITG tool standards
// Usage:
//      flag = required "on" or "off" 
//      spans = span or spans holding the * character to show on or off. This works by making the * the color of the
//              background within the span.  You can put whatever you want in the span.
//            Note: You may leave this blank and it will not attempt to
//                  change any spans. CSV for multiple
//            Sample: <span id=spnFirstName name=spnFirstName>*</span>
//                  then you would pass spnFirstName as the span name to toggle
//      formname = the name of the form that contains the fields; 
//            NOTE: leave blank if there are no fields
//      fields = form field or fields to mark as required or not required
//            Note: You may leave this blank and it will not attempt to
//                  change any fields
function toggleRequired(flag,formname,spans,fields) {
	if (formname != "") {
		if (flag=="off") {
			flagfield="formsDisabled";
		}
		if (flag=="on") {
			flagfield="formsRequired";
		}
	}
	if (flagfield !="") {
		if (fields.indexOf(",") != -1) {
			// break the divs passed into an array
			arrValues=fields.split(",");
			for(t=0;t<arrValues.length;t++) {
				eval("document." + formname + "." + arrValues[t] + ".className='" + flagfield + "'");
			}
		} else {
			eval("document." + formname + "." + fields + ".className='" + flagfield + "'");
		}
	}
	if (spans != "") {
		if (spans.indexOf(",") != -1) {
			// break the divs passed into an array
			arrValues=spans.split(",");
			for(t=0;t<arrValues.length;t++) {
				eval("document.getElementById('" + arrValues[t] + "').className='required" + flag + "'");
			}
		} else {
			eval("document.getElementById('" + spans + "').className='required" + flag + "'");
		}	
	}	

}
// ---- End Toggle Required -----------------------------------------------------

// ---- Get Index Value --------------------------------------------------------- SRM
// Function: returns the VALUE of the selected list box
// Usage:
//      formname = the form's name that contains the dropdown
//      field = the drop down form field
function getIndexValue(formname,field) {
	return eval("document." + formname + "." + field + ".options[document." + formname + "." + field + ".selectedIndex].value");
}
// ---- End Get Index Value -----------------------------------------------------

// ---- Put Index Value --------------------------------------------------------- SRM
// Function: Populates a LISTBOX with the desired value
// Usage:
//      formname = the form's name that contains the dropdown
//      field = the drop down form field
//		setvalue = the VALUE of the item in the list box - THIS IS NOT THE TEXT
//
//		Example:
//		HTML CODE:
//		 <option value="1">Financial Services</option>
//		 <option value="2">Admin Services</option>
//		 <option value="test">This is just a test</option>

// 		 If you wanted to populate this drop down with ...
//		 Financial Services .... setvalue='2' ...
//		 Admin Services .... setvalue='3' ...
//		 This is just a test ... setvalue='text' ...

function putIndexValue(formname,field,setvalue) {
	eval("document." + formname + "." + field + ".value='" + setvalue +"';");
}
// ---- End Put Index Value -----------------------------------------------------

// ---- Validate Fields --------------------------------------------------------- SRM
// Function: checks to ensure all passed fields have SOMETHING in the field; returns true if all pass.
//         Note: There is no FIELD TYPE validation.  If there is anything in there, it passes the check
//               If you need specifics, use DW's ValidateForm behavior or couple this with your own code.
// Usage:
//      formname = the form's name that contains the dropdown
//      fields = the field or fields (CSV) to validate
function validateFields(formname,fields) {
	strTemp=true;
	if (fields.indexOf(",") != -1) {
		arrValues=fields.split(",");
		for(t=0;t<arrValues.length;t++) {
			strTempEval=eval("document." + formname + "." + arrValues[t] + ".value");
			if (strTempEval == "") {
				strTemp=false;
			}
		}
	} else {
		strTempEval=eval("document." + formname + "." + fields + ".value");
		if(strTempEval== "") {
			strTemp=false;
		}
	}
	return strTemp;
}
// ---- End Validate Fields -----------------------------------------------------

// ---- Validate A Field --------------------------------------------------------- SRM
// Function: Validate a SINGLE field against several possible types as well as
//           comparing against a not-equal value (think list box or radio box)
// Usage: 
//      type="email", "number" (integer), "alpha" (letters), "alphanum" (no symbols), "float" (floating num)
//      , "single" (one letter or number), "listbox" (if you're checking a listbox)
//      notequal = a value that the listbox cannot be equal to to pass validation (i.e. 0)
//                 Leave blank if not a listbox validation
//      formname = the form the field is in
//      field = name of field
function validateAField(type,notequal,formname,field) {

	strTemp=true;
	if(type=="listbox") {
		if(getIndexValue(formname,field) != notequal) {
			return true;
		} else {
			return false;
		}
	} else {
		strTempEval=eval("document." + formname + "." + field + ".value");
	  switch (type)
	  {
		case "email": { 
			strMatch=strTempEval.match(/^.+\@.+\..+$/);
		break;
		}
		case "number": { 
			strMatch=strTempEval.match(/^\d+$/);	
		break;
		}
		case "alpha": { 
			sstrMatch=strTempEval.match(/^[a-zA-Z]+$/);								
		break;
		}
		case "alphanum": { 
			strMatch=strTempEval.match(/^[a-zA-Z0-9]+$/);								
		break;
		}
		case "float": { 
			strMatch=strTempEval.match(/^((\d+(\.\d*)?)|((\d*\.)?\d+))$/);								
		break;
		}
		case "single": { 
			strMatch=strTempEval.match(/^([a-zA-Z]|\d)$/);								
		break;
		}	
	  }	
		return strMatch;
	}

}
// ---- End Validate A Field  ---------------------------------------------------

// ---- Center Window --------------------------------------------------------- SRM
// Function: Center the current window on any browser screen
// Usage: Call function
function centerWindow() {
//	intWinWidth=document.documentElement.clientWidth;
	intWinWidth=document.body.clientWidth;
	intWinHeight=document.body.clientHeight;
	intWidth=screen.width;
	intHeight=screen.height;
	window.moveTo((intWidth/2)-(intWinWidth/2),(intHeight/2)-(intWinHeight/2));
}
// ---- End Center Window -----------------------------------------------------

// ---- Centered PopUp Window --------------------------------------------------------- SRM

// Function: Opens a new window automatically positioned in the center of the screen
//           based on the browser size.
// Usage: 
//      url=URL to the page to open in the window
//      windowname = a valid window name (no spaces or special characters)
//      resize = No, Yes (optional)
//      scrollbars = No, Yes, Auto (optional)
//		width = window width
//		height = window height
//		misc = any misc parameter not covered (optional)
function centerPopup(url,windowname,width,height,scrollbars,resize,misc) {
	xoffset=parseInt((screen.width/2)-(width/2));
	yoffset=parseInt((screen.height/2)-(height/2));
	
	strParameters="";
		if (resize != "") {
			strParameters = strParameters + "resizable=" + resize + ",";
		}

		if (scrollbars != "") {
			strParameters = strParameters + "scrollbars=" + scrollbars + ",";
			xoffset=xoffset-7;
			yoffset=yoffset-7;
		}
		
		if (misc != "") {
			strParameters = strParameters + misc + ",";
		}

	if (yoffset<0) {
		yoffset=0;	
	}
		
	strParameters=strParameters + "width=" + width + ", height=" + height + ",";
	strParameters=strParameters + "left=" + xoffset + ", top=" + yoffset;
	//strParameters=strParameters+"'";

	window.open(url,windowname,strParameters);
}
// ---- End Center PopUp -----------------------------------------------------

// ---- PopupHelp --------------------------------------------------------- SRM

// Function: Opens a new help window centered on the screen
// Usage: 
//      helpid=ID of the help row in the database to display
function popupHelp(helpid) {
	centerPopup("/helptopic.asp?id=" + helpid,"HelpTopic",500,300,"yes","yes","");
}
// ---- End Center PopUp -----------------------------------------------------

// ---- CopytoClipboard -------------------------------------------------- SRM

// Function: copies passed text to clipboard
// Usage: 
//      formname=form name the field sits in
//		field= form field to copy to clipboard
//		responsetext= text to post in an alertbox after the copy takes place - leave blank for no response
// Note: This ONLY works on IE.
function copyToClipboard(formname,field,responsetext) {
copied=eval("document." + formname + "." + field + ".createTextRange()");
copied.execCommand("Copy");
	if (responsetext != "") {
		alert(responsetext);
	}
}
// ---- End CopyToClipboard -----------------------------------------------------

// ---- Get List Text --------------------------------------------------------- SRM
// Function: returns the requested TEXT of a form list box
// You can get back the TEXT value of an option by supplying either an INDEX number
// of the option you want or the VALUE of the option you want.  If you supply neither
// a value or index, then the text of the currently selected option will be returned.
// 
// Usage:
//      formname = the form's name that contains the dropdown
//		field = the listbox's name/id
//      index = the array number/location in the option list
//		value = the option VALUE you wish to return the corresponding text for
function getListText(formname,field,index,value) {
	// If index and value are passed, throw an error
	if (index!="" && value!="") {
		alert ("You cannot pass both index AND value.");
		return false;
	}

	// No specifics, return what's selected
	if (index=="" && value=="") {
		return eval("document." + formname + "." + field + ".options[document." + formname + "." + field + ".selectedIndex].text");
	}	
	// if an index is passed, return that index value's TEXT
	if (index!="") {
		return eval("document." + formname + "." + field + ".options[" + index + "].text");
	}

	// if an value is passed, return that index value value's TEXT
	if (value!="") {
		// get the length of the options array
		intLenLst=eval("document." + formname + "." + field + ".options.length");
		// go through all options until we get a match on value
		for(t=0;t<intLenLst;t++) {
			strTempval=eval("document." + formname + "." + field + ".options['" + t + "'].value")
			if (strTempval==value) {
				strReturn=eval("document." + formname + "." + field + ".options['" + t + "'].text");
			}	
		}		
		
		return strReturn;
	}
}
// ---- End Get Index Text -----------------------------------------------------

// ---- Put Index Text --------------------------------------------------------- SRM
// Function: Controls the text values of a list box - you can add, append, and change
// the text of a list box by passing the index of the option, the text of the existing
// option text, or by passing the value of the option to change.
// You can also use this function to create a NEW option - see below.
// Usage:
//      formname = the form's name that contains the dropdown
//      field = the drop down form field
//		newtext = The text to be added, appended, or created
//		action = what to do 1 - append, 2 - replace, 3 - create new
//		index = array index of option to affect (Action 1 or 2)
//		 *OR*	the location in the index array to create the new option (Action 3)
//				leave empty to append to END
//		value = value of option to affect (Action 1 or 2)
//		 *OR*	the value of the new option created (Action 3)
// 		oldtext = this is the option's current text value (Action 1 or 2)

function putIndexText(formname,field,newtext,action,index,value,oldtext) {
	// first we need to know how big the option array is
	intLenLst=eval("document." + formname + "." + field + ".options.length");
// based on what the action is ...
	switch(action){
		case '1': // append text to existing option's text
			// Get the existing text from the option
				// if they passed an index number, let's use that
				
				if (index!="") {
					strOldText=getListText(formname,field,index,'');
					// set the text field to the old + new
					eval("document." + formname + "." + field + ".options[" + index + "].text='" + strOldText + newtext + "'");
				// otherwise, let's assume they sent over a value
				} else {
					// We must be matching text for VALUE or TEXT property
					if (oldtext!="") { // If there is old text, we're matching TEXT
						for(t=0;t<intLenLst;t++) {
							strTempval=eval("document." + formname + "." + field + ".options['" + t + "'].text")
							if (strTempval==oldtext) {
								// set the text field to the old + new
								eval("document." + formname + "." + field + ".options[" + t + "].text='" + strTempval + newtext + "'");
							}	
						}		
					} else { // we are matching a VALUE
						for(t=0;t<intLenLst;t++) {
							strTempval=eval("document." + formname + "." + field + ".options['" + t + "'].value")
							if (strTempval==value) {
								// get the existing text
								strTempText=eval("document." + formname + "." + field + ".options[" + t + "].text");
								// set the text field to the old + new
								eval("document." + formname + "." + field + ".options[" + t + "].text='" + strTempText + newtext + "'");
							}	
						}
					}
				}
			
		break
		case '2': // replace text on existing option's text
			// Get the existing text from the option
				// if they passed an index number, let's use that
				if (index!="") {
					strOldText=getListText(formname,field,index,'');
					// set the text field to the old + new
					eval("document." + formname + "." + field + ".options[" + index + "].text='" + newtext + "'");
				// otherwise, let's assume they sent over a value
				} else {
					// We must be matching text for VALUE or TEXT property
					if (oldtext!="") { // If there is old text, we're matching TEXT
						for(t=0;t<intLenLst;t++) {
							strTempval=eval("document." + formname + "." + field + ".options['" + t + "'].text")
							if (strTempval==oldtext) {
								// set the text field to the old + new
								eval("document." + formname + "." + field + ".options[" + t + "].text='" + newtext + "'");
							}	
						}		
					} else { // we are matching a VALUE
						for(t=0;t<intLenLst;t++) {
							strTempval=eval("document." + formname + "." + field + ".options['" + t + "'].value")
							if (strTempval==value) {
								// get the existing text
								strTempText=eval("document." + formname + "." + field + ".options[" + t + "].text");
								// set the text field to the old + new
								eval("document." + formname + "." + field + ".options[" + t + "].text='" + newtext + "'");
							}	
						}
					}
				}
		break
		case '3': // create new option
			//
			elmOption=document.createElement("option");
			if (value!="") {
				elmOption.value=value;
			} else {
				elmOption.value=intLenLst+2;				
			}
			
			elmOption.text=newtext;
			if (index!="") {
				eval("document." + formname + "." + field + ".options.add(elmOption,"+ index +")");
			} else {
				eval("document." + formname + "." + field + ".options.add(elmOption)");				
			}
		break
	}

}
// ---- End Put Index Value -----------------------------------------------------

// ---- Delete List Option --------------------------------------------------------- SRM
// Function: Delete a listbox option based on index, value, or text
// If you leave index, value, and text BLANK, the CURRECTLY selected option will be deleted
// After deletion, the function sets the option index to ZERO, unless you pass a 1 for noreset.
// 
// Usage:
//      formname = the form's name that contains the dropdown
//		field = the listbox's name/id
//      index = the array number/location in the option list
//		value = the option VALUE of the option you wish to delete
//		text = the option TEXT of the option you wish to delete
//		noreset = make this a 1 if you don't want to reset the option to index zero after the delete

function deleteListOption(formname,field,index,value,text,noreset) {
    // first we need to know how big the option array is
	intLenLst=eval("document." + formname + "." + field + ".options.length");
	// if we have no criteria passed, nuke the selected one
	if (index=="" && value=="" && text=="") {
		intIndex=eval("document.getElementById('" + field + "').selectedIndex");
		eval("document." + formname + "." + field + ".remove(" + intIndex + ")");
		if (noreset=="") {
			eval("document." + formname + "." + field + ".options[0].selected=true");
		}
		return;
	}
	// if an index is passed, delete that one
	if (index!="") {
		eval("document." + formname + "." + field + ".remove(" + index+ ")");
		return;
	}
	// We must be matching text for VALUE or TEXT property
	// These will only delete the FIRST occurrance of the text/value
	if (text!="") { // If there is text, we're matching TEXT
		for(t=0;t<intLenLst;t++) {
			strTempval=eval("document." + formname + "." + field + ".options[" + t + "].text")
			if (strTempval==text) {
				// set the text field to the old + new
				eval("document." + formname + "." + field + ".remove(" + t + ")");
				t=intLenLst;
			}	
		}		
	} else { // we are matching a VALUE
		for(t=0;t<intLenLst;t++) {
			strTempval=eval("document." + formname + "." + field + ".options['" + t + "'].value")
			if (strTempval==value) {
				eval("document." + formname + "." + field + ".remove(" + t+ ")");
				t=intLenLst;
			}	
		}
	}

}
// ---- End Delete List Option -----------------------------------------------------

// Start Ajax functions

function getDataReturnText(url, callback)
{ 
  var XMLHttpRequestObject = false; 

  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new 
     ActiveXObject("Microsoft.XMLHTTP");
  }

  if(XMLHttpRequestObject) {
    XMLHttpRequestObject.open("GET", url); 

    XMLHttpRequestObject.onreadystatechange = function() 
    { 
      if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) { 
          callback(XMLHttpRequestObject.responseText); 
          delete XMLHttpRequestObject;
          XMLHttpRequestObject = null;
      } 
    } 

    XMLHttpRequestObject.send(null); 
  }
}

function getDataReturnXml(url, callback)
{ 
  var XMLHttpRequestObject = false; 

  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new 
     ActiveXObject("Microsoft.XMLHTTP");
  }

  if(XMLHttpRequestObject) {
    XMLHttpRequestObject.open("GET", url); 

    XMLHttpRequestObject.onreadystatechange = function() 
    { 
      if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) { 
          callback(XMLHttpRequestObject.responseXML); 
          delete XMLHttpRequestObject;
          XMLHttpRequestObject = null;
      } 
    } 

    XMLHttpRequestObject.send(null); 
  }
}

function postDataReturnText(url, data, callback)
{ 
  var XMLHttpRequestObject = false; 

  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new 
     ActiveXObject("Microsoft.XMLHTTP");
  }

  if(XMLHttpRequestObject) {
    XMLHttpRequestObject.open("POST", url); 
    XMLHttpRequestObject.setRequestHeader('Content-Type', 
      'application/x-www-form-urlencoded'); 

    XMLHttpRequestObject.onreadystatechange = function() 
    { 
      if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) {
          callback(XMLHttpRequestObject.responseText); 
          delete XMLHttpRequestObject;
          XMLHttpRequestObject = null;
      } 
    }

    XMLHttpRequestObject.send(data); 
  }
}

function postDataReturnXml(url, data, callback)
{ 
  var XMLHttpRequestObject = false; 

  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new 
     ActiveXObject("Microsoft.XMLHTTP");
  }

  if(XMLHttpRequestObject) {
    XMLHttpRequestObject.open("POST", url); 
    XMLHttpRequestObject.setRequestHeader('Content-Type', 
      'application/x-www-form-urlencoded'); 

    XMLHttpRequestObject.onreadystatechange = function() 
    { 
      if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) {
          callback(XMLHttpRequestObject.responseXML); 
          delete XMLHttpRequestObject;
          XMLHttpRequestObject = null;
      } 
    }

    XMLHttpRequestObject.send(data); 
  }
}
