//-----------------------------------------------------------------------------------------------------------
//  Global JavaScript variables
//-----------------------------------------------------------------------------------------------------------
var HelpSearch = false;		// Enables the Search button in Aprimo Help
var HelpSearchTech = false;	// Enables the Search button in Aprimo Tech Reference
var fieldPrefix = "field";
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// The namePrefix variable used to have a value of "_ctl0__ctl0_"
// this is being removed since we no longer get this prefix added by default
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
var namePrefix = "";
var DualSelectAvailSuffix = "_lbxAvailable";
var DualSelectSelSuffix = "_lbxSelected";
var AddEditTableRowPrefix = "tr";
var PostbackID = "_ctl0:_ctl0";
//-----------------------------------------------------------------------------------------------------------
//  Author:			Curt Knapp
//  Procedure Name:	FormFieldPrefix
//  Description:	Returns the Prefix used by .NET for a form field
//  Arguments:		(none)
//  Return Value:	String - the Prefix used by .NET for a form field
//  Comments:		This is needed because .NET prepends additional names to the name we give our control
//-----------------------------------------------------------------------------------------------------------
function FormFieldPrefix() {
	return namePrefix;
}

function FieldPrefix() {
	return fieldPrefix;
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Curt Knapp
//  Procedure Name:	FormFieldID
//  Description:	Returns the ID of a form field, given the Attribute ID
//  Arguments:		attrID - the Attribute ID of the Form Field you want to retrieve
//  Return Value:	String - the Form Field ID of the attribute
//  Comments:		This is needed because .NET prepends additional names to the name we give our control
//-----------------------------------------------------------------------------------------------------------
function FormFieldID(attrID) {
	return FormFieldPrefix() + fieldPrefix + attrID;
}

function DualSelectAvail(attrID) {
	return document.getElementById(DualSelectAvailID(attrID));
}

function DualSelectSel(attrID) {
	return document.getElementById(DualSelectSelID(attrID));
}

function DualSelectAvailID(attrID) {
	return FormFieldPrefix() + fieldPrefix + attrID + DualSelectAvailSuffix;
}

function DualSelectSelID(attrID) {
	return FormFieldPrefix() + fieldPrefix + attrID + DualSelectSelSuffix;
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Curt Knapp
//  Procedure Name:	FormField
//  Description:	Returns the actual form field object, given the Attribute ID
//  Arguments:		attrID - the Attribute ID of the Form Field you want to retrieve
//  Return Value:	Object - the Form Field for the attribute
//  Comments:		This is needed because .NET prepends additional names to the name we give our control
//-----------------------------------------------------------------------------------------------------------
function FormField(attrID) {
	return document.getElementById(FormFieldID(attrID));
}

function ContainedFormField(ContainerID, attrID) {
	return document.getElementById(FormFieldPrefix() + ContainerID + '_' + fieldPrefix + attrID);
}

function PageObject(ID) {
	return document.getElementById(PageObjectID(ID));
}

function PageObjectID(ID) {
	return FormFieldPrefix() + ID;
}

function GetTableRowIDByAttrID(ID) {
	return FormFieldPrefix() + AddEditTableRowPrefix + ID;
}

function GetTableRowByAttrID(ID) {
	return document.getElementById(GetTableRowIDByAttrID(ID));
}


function toggleRequired(attrID, bIsRequired) {	
	// find the control first
	var formField = FormField(attrID);
	
	if (formField != null) {	
		// Change the required property
		formField.required = bIsRequired;
		
		// Change the text of the required image
		var img = document.getElementById("img" + fieldPrefix + attrID);
		if (img != null) {
			if (bIsRequired) {	
				img.src = window.RelativePath + "images/required.gif";
			} else {
				img.src = window.RelativePath + "images/invisible.gif";
			}		
		}
		else
		{
			var lblcell = document.getElementById("L_" + attrID);
			if(lblcell != null && lblcell.childNodes.length > 0)
			{
				if(lblcell.childNodes[0].childNodes.length > 0)
				{
					if (bIsRequired) {	
						lblcell.childNodes[0].childNodes[0].className = "ed_LR";
					} else {
						lblcell.childNodes[0].childNodes[0].className = "ed_L";
					}		
				}
			}
		}
		// If a validator is found, mark it as valid and update the display
		var validator = document.getElementById(namePrefix + "req" + fieldPrefix + attrID);
		if (validator != null) {
			validator.isvalid = true;
			ValidatorUpdateDisplay(validator);
		}
	}	
}
	
//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	bIsIE
//  Description:	Determines whether or not the current browser is Internet Explorer
//  Arguments:		(none)
//  Return Value:	Boolean - True if IE, False if any other browser
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function bIsIE() {
	var agent = "";
	var msie = "";

	//Determine the current user agent
	agent = window.navigator.userAgent;
    msie = agent.indexOf("MSIE");

	if (msie > 0) {
		return true;
	}
	else {
		return false;
	}

}


//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	Checkbox_onChange
//  Description:	Determines whether or not the current browser is Internet Explorer
//  Arguments:		field - name of the check box field that has changed
//  Return Value:	(none)
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function Checkbox_onChange(field) {
	var sfname = field.name;
	var sname = sfname.substring(5, sfname.length);
	var hidden = document.forms[0][sname];
	for (index=0; index < window.document.forms[0][sfname].length; index++) {
		if (window.document.frm[sfname](index) == field) {
			hidden = window.document.forms[0][sname](index);
			break;
		}
	}

	if (field.checked)
		hidden.value = field.value;
	else
		hidden.value = "0";

}


//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	clearform
//  Description:	Clears the contents of an HTML form
//  Arguments:		formname - the name of the form to be cleared
//  Return Value:	(none)
//  Comments:		This function will work correctly only if all HTML form fields
//					have a valid "type" identifier.  This identifier can be either
//					defined manually in the HTML template or created dynamically 
//					via common web code.
//-----------------------------------------------------------------------------------------------------------
function clearform(controlID) {

	//Loop through the form elements and clear all content
	for (i=0; i < document.forms[0].length; i++) {
		var field = document.forms[0].elements[i];
		// Don't clear out Dynamic Rows or Filter Fields
		if (field.id.indexOf("ROWYYY") < 0) {
			if ((field.type == "text") || (field.type == "password") || (field.type == "textarea")) {
				field.value = "";
			}
	
			if ((field.type == "checkbox") || (field.type == "radio")) {
				field.checked = false;
			}
	
			if (field.type == "select-one") {
				field.options.selectedIndex = 0;
			}
	
			if (field.type == "select-multiple") {
				field.options.selectedIndex = -1;
			} 
		}
	}
	
	//Call the clearpage function if it exists to perform any additional logic to clear the form
	if (window.clearpage != null) {
		clearpage();
	}
	
	// Call OnClear() for each javascript registered object
	ObjectManager.OnClear(controlID);
	
}


//-----------------------------------------------------------------------------------------------------------
//              Author: Douglas White							
//      Procedure Name: confirmpopup	          					
//         Description: Present a Pop-Up confirmation dialog with the given msg	
//           Arguments: msg - Text of the confirmation dialog - "Are yousure?	
//           		 URL - URL to navigate to if confirmed.				
//        Return Value: N/A								
//            Comments: Sample Use:							
//  <a href="javascript:confirmpopup('<WC@ResourceID9999>Message</WC@ResourceID9999>',
//  '<WC@DeleteAudncMbr></WC@DeleteAudncMbr>');"  class="none">			
//-----------------------------------------------------------------------------------------------------------
function confirmpopup(msg, URL) {
	if (confirm(msg))
	{ 
		var win = window;
		while(win.document.body.id !="pagebody")
		{
			win = win.parent;
		}
		if(IsMac())		
			GoToURL(URL,'',false,false);		
		else		
			win.GoToURL(URL);		
	}
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	disableall
//  Description:	Unformats a given HTML form field
//  Arguments:		fieldname - the name of the form field to be unformatted
//  Return Value:	(none)
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function DisableAll(formname, bDisable, bSelect) {
	for(i=0; i < document.forms[0].length; i++) 
	{
		var field = document.forms[0].elements[i]	
		if (field.name != "Cancel")
		{			
			if(!bSelect)
			{			
				if(!bDisable && field.disabled)									
					field.wasdisabled = true;
				DisableField(field, bDisable);
			}
			else
			{				
				if((bDisable || !field.wasdisabled) && field.name != "Apply")
					DisableField(field, bDisable);				
				field.wasdisaled = false;
			}																						
		}
	}
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	disablefield
//  Description:	Unformats a given HTML form field
//  Arguments:		fieldname - the name of the form field to be unformatted
//  Return Value:	(none)
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function disablefield(field, bDisable, bClearData, CssClass) 
{	
	if(field.disabled == bDisable)
		return;				
	field.disabled = bDisable;	
	if(!bIsIE())
	{	
		if(bDisable)
			field.onfocus = field.blur;		
		else
			field.onfocus = null;						
	}	
	field.className = CssClass;
	if(bClearData)
		field.value = "";
}
//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	disableform
//  Description:	Unformats a given HTML form field
//  Arguments:		fieldname - the name of the form field to be unformatted
//  Return Value:	(none)
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function disableform(formname, bDisable, bSelect) {	
	for(i=0; i < document.forms[0].length; i++) 
	{
		var field = document.forms[0].elements[i]	
		if(!bSelect)
		{			
			if(!bDisable && field.disabled)									
				field.wasdisabled = true;
			disablefield(field, bDisable);
		}
		else
		{				
			if((bDisable || !field.wasdisabled))
				DisableField(field, bDisable);				
			field.wasdisaled = false;
		}																		
	}
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Brian Tauke
//  Procedure Name:	resetform
//  Description:	Resets an HTML form
//  Arguments:		formname - the name of the form to be reset
//  Return Value:	(none)
//  Comments:		The loadfocus() function is called after the form is reset 
//					to reset page focus to the first valid HTML form field
//-----------------------------------------------------------------------------------------------------------
function resetform() 
{
	//Reset the form and restore focus to the first eligible field
	document.forms[0].reset();

	// find all dualselect boxes, and reset the original value stored in their corresponding arrays
	//for (var z=0; z < document.forms[0].length; z++) 
	//{
	//	var field = document.forms[0].elements[z];		
	//	if(field.type == "select-multiple" && field.selectAll != "false")
	//	{
	//		Combo_Reset(field);
	//	}
	//}
	
	// Call OnReset() for each javascript registered object
	ObjectManager.OnReset();
	
	//Call the resetpage function if it exists to perform any pre-processing steps
	if (window.resetpage != null) {
		resetpage();
	}
	// Validate all validators
	if (window.Page_Validators) {
		ValidatorReset();
	}	
	LoadFocus();
	if(Aprimo.Events.hasSubscribers("Form.Reset"))  
		Aprimo.trigger("Form.Reset");	
}

//Reset Password Field
function ResetPasswordField(field)
{
	if(typeof(field) != "object") //it is an ID
		field = document.getElementById(field);
		
	field.value = "********";
	disablefield(field, true);
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	round
//  Description:	Rounds a given number to the nearest hundreth
//  Arguments:		num - number to be rounded
//  Return Value:	A rounded number
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function round(num) 
{
	var decimal = "";

	num = (Math.round (num * 100)) / 100;
	
	if(num !=0)
	{
		num = (num + (num / Math.abs(num)) * (1/1000)) + '';
	}
	else
	{
		num = (num + (1/1000)) + '';
	}

	for(var i = 0; i < num.length; i++)
	{
		if(isNaN(num.charAt(i)))
		{
		   decimal = num.charAt(i); 		
		}
	}

	if (decimal == "") {
		return num + ".00";
	}
	else {
		return num.substring(0, num.indexOf(decimal) + 3);
	}
   
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Brian Tauke	
//  Procedure Name:	setfocus
//  Description:	Gives focus to an HTML form field
//  Arguments:		formname - the name of the HTML form
//					fieldname - the name of the field to receive focus
//  Return Value:	(none)
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function setfocus(fieldname) {

	//Give focus to the specified form field
	document.forms[0].elements[fieldname].focus();

}


//-----------------------------------------------------------------------------------------------------------
//  Author: 		Brian Tauke
//  Procedure Name:	submitform
//  Description:	Submits an HTML form
//  Arguments:		formname - the name of the form to be submitted
//  Return Value:	(none)
//  Comments:		The form is submitted only if the validateform() function below
//					returns true.  The submitpage() function is called if it 
//					exists to perform any required pre-processing.
//-----------------------------------------------------------------------------------------------------------
function submitform() {	
	
	var blnSuccess = true;

	if (!ObjectManager.AlreadySubmitted) {	
		//Call the submitpage function if it exists to perform any pre-validation steps
		if (window.submitpage != null) {
			submitpage();
		}
			
		// Call OnSubmit() for each javascript registered object
		ObjectManager.OnSubmit();
		
		//If any existing page validation returns true, submit the form
		blnSuccess = ValidatePageValidators();
		if (blnSuccess) {
			//select all dual select box items here
			selectcombos();

			// Call OnValidPage() for each javascript registered object
			ObjectManager.OnValidPage();
			
			// Call into the Object Manager to do the Submit
			blnSuccess = ObjectManager.Submit();
		}
	} else {
		blnSuccess = false;
		//alert(JSResourceID529);
	}		
	return blnSuccess;
}

function ValidatePageValidators() {
	// Check and see if the function Page_ClientValidate exists on the page, 
	// and if so, call it.  This function is found in webuivalidation.js.  However,
	// this file is only included on the page if a .NET validator is included on the
	// page.	
	// Call OnValidate() for each javascript registered object
	var valid = ObjectManager.OnValidate();	
	if (valid) {	
		if (window.Page_ClientValidate != null) {			
			valid = Page_ClientValidate();						
		} else {
			//Call the validatepage function if it exists to perform any further validation steps
			if (window.validatepage != null) {
				valid = validatepage();
			} else {
				// indicate that all validation passed		
				valid = true;	
			}
		}		
		if (valid) {
			// Trim all the textareas and textboxes on the form
			var i = 0;
			// Get all the textareas on the page	
			var fields = document.getElementsByTagName("textarea");
			for (i = 0; i < fields.length; i++) {
				// trim the field
				fields[i].value = trim(fields[i].value);
			}
			// Get all the textboxes on the page
			fields = document.getElementsByTagName("input");		
			for (i = 0; i < fields.length; i++) {
				if (fields[i].type == "text") {
					// trim the field
					fields[i].value = trim(fields[i].value);
				}	
			}
		}	
	}	
	
	if (!valid && !blnLoggedIntoPortal)
	{
		var w = window.top.WindowBar.GetWindow(LocalWindowName);
		if (w != null)
			w.ForceWindowClose = false;
	}
	
	return valid;		
}	

function submitcontinue(index) {
	var blnValidate;

	document.forms[0].action += ("&Continue=" + index);

	blnValidate = submitform();

	if (!blnValidate) {
		document.forms[0].action = document.forms[0].action.replace("&Continue=" + index, "");
	}
}

function submitformAndAddAnother() {
	var blnValidate;

	document.forms[0].action += "&AddAnother=1";

	blnValidate = submitform();

	if (!blnValidate) {
		document.forms[0].action = document.forms[0].action.replace("&AddAnother=1", "");
	}
}

function selectcombos()
{
	//select all dual select box items here
	for (var z=0; z < document.forms[0].length; z++) {
		var field = document.forms[0].elements[z];		
		if (field.type == "select-multiple") {
			if (field.selectAll != "false")
				Combo_SelectAll(field);
		}					
	}	
}
var selectedRange;
var selectedInputArea;
function TextArea_StoreCaret(textArea) {
	if (textArea.createTextRange) {
		textArea.selectedRange = document.selection.createRange().duplicate();
		textArea.selectedInputArea = textArea;
	}	
}

function TextArea_InsertAtCaret(textArea, text) {
	if(text !='' && text !='0')
	{
		if (IsMac()) {
			textArea.value += ' ' + text;
		} else {	
	       if (textArea.createTextRange && textArea.selectedRange) {
	         var caretPos = textArea.selectedRange;
	         caretPos.text = (caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text);
	       } else
	         textArea.value += text;
	     }
	}         
}
     
//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	TextArea_onInput
//  Description:	Unformats a given HTML form field
//  Arguments:		fieldname - the name of the form field to be unformatted
//  Return Value:	(none)
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function TextArea_onKeyPress(field)
{		
	var sInput = field.value;
	if(IsMac())
		sInput = Replace(sInput, "\n", "\r\n"); //length in Mac does not contain "\r"
	var maxLength = field.maxlength;
	if (maxLength > 0) 
	{
		if (sInput.length == maxLength)
			return false;		
		if(sInput.length > maxLength) 
		{
//		    window.document.onmousedown();
			popMessage(GetReplacementString(502) + " " + maxLength + " " + GetReplacementString(503), field);
			return false;
		}
	}	
	return true;
}
//-----------------------------------------------------------------------------------------------------------
//  Author:			Scott Dafforn
//  Procedure Name:	Text_onInput
//  Description:	Unformats a given HTML form field
//  Arguments:		field - the form field to be evaluated
//  Return Value:	boolean
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function Text_onKeyPress(field) 
{	
	var evt = Aprimo.Util.GetEventObject(arguments);
	if (IsMac()&& evt && (evt.keyCode == 8 || (evt.keyCode >= 63232 && evt.keyCode <=63235) || (evt.keyCode>=63272 && evt.keyCode<=63277)))//delete, arrow keys in Mac
		return true;
	if (field.type == "textarea")
		return TextArea_onKeyPress(field);			
	return NoEnter();
}


//-----------------------------------------------------------------------------------------------------------
//  Author:			Scott Dafforn
//  Procedure Name:	NoEnter
//  Description:	will not allow a form to be submitted if the user hits
//					the Enter key while in a text box
//  Arguments:		(none)
//  Return Value:	boolean
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function NoEnter() {
	var evt = Aprimo.Util.GetEventObject(arguments);
	if (!IsMac()) 
		return !(evt && evt.keyCode == 13);
	else 
	{
		if ((evt && evt.keyCode == 13) || (evt && evt.keyCode == 3)) 
			return false;
		else 
			return true;		
	}
}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	trim
//  Description:	Removes leading and trailing spaces from a string 
//  Arguments:		sInput - string to be trimmed of leading and trailing spaces
//  Return Value:	Modified string with no leading or trailing spaces
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
/*
function trim(sInput) {

	if (sInput != "") {
		while (sInput.charAt(0) == " ") {
			sInput = sInput.substring(1, sInput.length);
		}
		while (sInput.charAt(sInput.length - 1) == " ") {
			sInput = sInput.substring(0, sInput.length - 1);
		}
	}

	return sInput;
}
*/

//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	unformatfield
//  Description:	Unformats a given HTML form field
//  Arguments:		fieldname - the name of the form field to be unformatted
//  Return Value:	(none)
//  Comments:		This function assumes that the form field in question has
//					populated format, unformat and subtype attributes
//-----------------------------------------------------------------------------------------------------------
function unformatfield(fieldname) {
	var sInput = "";
	var format = "";
	var unformat = "";
	var subtype = "";

	//Read in the field value, format, unformat and subtype strings
	sInput = fieldname.value;
	format = fieldname.format;
	unformat = fieldname.unformat;
	subtype = fieldname.subtype;

	//Call the appropriate unformat function based on the field type
	fieldname.value = eval(subtype + "_Unformat(sInput, format, unformat)");

}


//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	unformatform
//  Description:	Unformats the data in an HTML form
//  Arguments:		formname - the name of the form to be unformatted
//  Return Value:	(none)
//  Comments:		This function will unformat any form field that is populated 
//					and has a specified format attribute.  This function assumes
//					that any form field that has a populated format attribute will
//					also have populated unformat and subtype attributes.
//-----------------------------------------------------------------------------------------------------------
function unformatform(formname) {

	//Loop through the form elements and unformat those that have specified formats
	for (z=0; z < document.forms[0].length; z++) {
		var field = document.forms[0].elements[z];
		if ((field.value != "") && (field.format)) {
			if (field.format != ""){
				unformatfield(field);
			}
		}
	}

}


//-----------------------------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	validateform
//  Description:	Validates the data of an HTML form
//  Arguments:		formname - the name of the form to be validated
//  Return Value:	Boolean - True if the form data is acceptable, False if an 
//					error is found
//  Comments:		This function will verify that all required fields have been
//					populated, ensure that all texarea fields do not exceed the 
//					maximum length, call the validatepage() function to perform
//					any page-specific validation, and will finally unformat all 
//					form fields
//-----------------------------------------------------------------------------------------------------------
function validateform(formname) {

	//Loop through the form fields and validate each one as needed
	for (var i=0; i < document.forms[0].length; i++) {
		var field = document.forms[0].elements[i];
		
		// Don't do any validation on hidden template fields (which have ROWYYY in their names)
		if (field.name.indexOf("ROWYYY") < 0) {
			if ((field.type == "text") || (field.type == "textarea")) {
				field.value = trim(field.value);
			}
	
			if (field.type == "textarea") {
				if (field.value.length > field.maxlength) {
					return false;
				}
			}
	
			if (field.subtype == "Date") {
				if (Date_Validate(field, false) == false) {
					return false;
				}
			}
			if (field.subtype == "Time") {
				if (Time_Validate(field, false) == false) {
					return false;
				}
			}
			
			if (field.subtype == "Number") {
				if (Number_Validate(field) == false) {
					return false;
				}
			}
			if (field.required && !field.disabled) {
				if ((field.type == "text" && trim(field.value) == "") || 
					(field.type == "textarea" && trim(field.value) == "") ||
					(field.type == "select-one" && field.length == 0) || 
					(field.type == "password" && trim(field.value) == "") ||
					(field.type == "select-one" && field.options[field.selectedIndex].value == "")) {
						sMsg = GetReplacementString(520);
						popMessage(sMsg, field);
						return false;
				}
				else {
					if ((field.type == "select-multiple") && (field.options.length == 0)) {
						sMsg = GetReplacementString(521);
						popMessage(sMsg, field);
						return false;
					}
				}
			}
		}	
	}

	//Call the validatepage function if it exists to perform any further validation steps
	if (window.validatepage != null) {
		if (validatepage() == false) {
			return false;
		}
	}		

	//Unformat the form fields
	unformatform(formname); 

	//If no errors have been found, return true
	return true;

}

//-----------------------------------------------------------------------------------------------------------
//  Author:			Tom Kashin
//  Procedure Name:	validatesort
//  Description:	Verifys that there are no duplicate sorting requirements 
//					defined on a given filter page
//  Arguments:		duplicatemsg - text to display if a duplicate sort is found
//					formname - name of the HTML form on the filter page
//  Return Value:	True or False (boolean)
//  Comments:		(none)
//-----------------------------------------------------------------------------------------------------------
function validatesort(duplicatemsg,formname) {
	var sel1=document.forms[0].lbxFirstSortFields.options.selectedIndex;
	//some pages may have less than three total filterable items
	if (document.forms[0].lbxSecondSortFields)
	{
		var sel2=document.forms[0].lbxSecondSortFields.options.selectedIndex;
	}
	if (document.forms[0].lbxThirdSortFields)
	{
		var sel3=document.forms[0].lbxThirdSortFields.options.selectedIndex;
	}

	if ((sel1==0 && sel2==0) || (sel2==0 && sel3==0) || (sel3==0 && sel1==0)) {
		return true;
	}
	else {
		if (sel1==sel2 || sel2==sel3 || sel3==sel1) {
			alert(duplicatemsg);
			return false;
		}
		else {
			return true;
		}
	}
}


//----------------------------------------------------------------------------------------------------------
//	Author:			Brian Tauke
//
// Procedure Name:	validateattributes
//
// Description:	Verifys that there are no duplicate attributes selected 
//					on a given filter page
//
// Arguments:		duplicatemsg - text to display if a duplicate attribute is found
//					formname - name of the HTML form on the filter page
//					prefix - the name prefix of the attribute fields in question
//
// Return Value:	True or False (boolean)
//
// Comments:		(none)
//----------------------------------------------------------------------------------------------------------
function validateAttributes(duplicatemsg, formname, prefix) {

	var SelectedAtts = new Array;
	var j = 0;

	//Loop through the elements on the form
	for (var i=0; i < document.forms[0].length; i++) {
		var sTemp = document.forms[0].elements[i].name;
		sTempSuffix = sTemp.substring(prefix.length);
		if ((prefix == sTemp.substring(0, prefix.length)) && (sTempSuffix == parseInt(sTempSuffix))) {

			Index = document.forms[0].elements[i].selectedIndex;
			SelVal = document.forms[0].elements[i][Index].value;

			for (var k=0; k < SelectedAtts.length; k++) {
				if ((SelectedAtts[k] == SelVal) && (SelVal != 0)) {
					//Duplicate error message
					alert(duplicatemsg);
					document.forms[0].elements[i].focus();
					return false;
				}
			}

			SelectedAtts[j] = SelVal;
			j = j + 1;

		}

	}

	//If no errors were found, return true
	return true;

}

//-----------------------------------------------------------------------------------------------------------
//     Author: Matt Kelsey, Doug Hobson (Updated for 6.0)
//	   Procedure Name: activityuncheckall														
//     Description: Uncheck all checkbox elements in a form and zero out the cookie				  
//     Arguments: formname - formname
//			      prefix - prefix of checkbox. Should be "chk"
//     Return Value: (none)																		
//     Comments: (none)	   			
//-----------------------------------------------------------------------------------------------------------
function uncheckAll(formname, prefix) {

	//Loop through the form and check all check boxes by prefix
	for (j=0; j < document.forms[0].length; j++) 
	{
		var controlname = document.forms[0].elements[j].name;
		if (controlname.substr(controlname.length-prefix.length,prefix.length) == prefix) 
		{
			document.forms[0].elements[j].checked = false;
		}
	}
	SetCookie("cboxstatus","","");
	SetCookie("selectinset","","SelectInSet=0");
	SetCookie("subfacilitys","","Subfacilitys=0");
}

//-----------------------------------------------------------------------------------------------------------
//     Author: Matt Kelsey, Doug Hobson (Update for 6.0)
//	   Procedure Name: checkAll														
//     Description: check all checkbox elements in a form and zero out the cookie				  
//     Arguments: formname - formname
//	   prefix - prefix of checkbox. Should be "chk"
//     Return Value: (none)																		
//     Comments: (none)	   			
//-----------------------------------------------------------------------------------------------------------
function checkAll(formname, prefix) 
{
	//Loop through the form and check all check boxes by prefix
	for (j=0; j < document.forms[0].length; j++) 
	{
		var controlname = document.forms[0].elements[j].name;
		if (controlname.substr(controlname.length-prefix.length,prefix.length) == prefix) 
		{
			if(document.forms[0].elements[j].name == "chkSubFacilitys" )
			{
				document.forms[0].elements[j].checked = false;
			}
			else
			{
				document.forms[0].elements[j].checked = true;
			}
		}
	}
}

//-----------------------------------------------------------------------------------------------------------
//     Author: Doug Hobson
//	   Procedure Name: toggleSelectAllInSet
//     Description: Toggles the mode of a paged list of checkboxes between all selected and none selected
//     Arguments: elemName - the uncoerced name of the checkbox that toggles the mode.
//     Return Value: (none)																		
//     Comments: (none)	   			
//-----------------------------------------------------------------------------------------------------------
function toggleSelectAllInSet(elemName)
{
	elemName = FieldPrefix() + elemName;

	var elem = document.forms[0].elements[elemName];

	if(elem.checked == true)
	{
		checkAll('','chk');
		SetCookie("selectinset","","SelectInSet=1");
	}
	else
	{
		uncheckAll('','chk');
		SetCookie("selectinset","","SelectInSet=0");
	}

	//Clear the cookies that save the Select All In Set state
	resetSelectAllInSet();
}
//-----------------------------------------------------------------------------------------------------------
//     Author: Matt Kelsey
//	   Procedure Name: ToggleSelectSubFacilities
//     Description: Toggles the mode of a paged list of checkboxes between all selected and none selected
//     Arguments: elemName - the uncoerced name of the checkbox that toggles the mode.
//     Return Value: (none)																		
//     Comments: (none)	   			
//-----------------------------------------------------------------------------------------------------------
function ToggleSelectSubFacilities(elemName)
{
 	elemName = FormFieldID(elemName);
	var elem = document.forms[0].elements[elemName];
	
	if(elem.checked == true)
	{
	        SetCookie("subfacilitys","","Subfacilitys=1");
	}
	else
	{
		SetCookie("subfacilitys","","Subfacilitys=0");
	}
}

//-----------------------------------------------------------------------------------------------------------
//     Author: Doug Hobson
//	   Procedure Name: resetSelectAllInSet
//     Description: Toggles the mode of a paged list of checkboxes between all selected and none selected
//     Arguments: elemName - the uncoerced name of the checkbox that toggles the mode.
//     Return Value: (none)																		
//     Comments: Called from the onClick of the Save button.
//-----------------------------------------------------------------------------------------------------------
function resetSelectAllInSet()
{
	SetCookie("cboxstatus","","");
} 

//-----------------------------------------------------------------------------------------------------------
//     Author: Matt Kelsey, Doug Hobson (6.0 Update)
//	   Procedure Name: saveCboxStatus														
//     Description: Saves the status of a checkbox				  
//     Arguments: The checkbox element that was clicked
//     Return Value: (none)																		
//     Comments: (none)	   			
//-----------------------------------------------------------------------------------------------------------
function saveCboxStatus(elem,checkForSubFacilities)
{
	//save the state of the checkboxes in the cboxstatus variable
	var currentpagechecked= "";
	var elem;
	var strid;
	var cboxstatus=GetCookie("cboxstatus");
	var strsearch;
	var chkbox;
	var subfacilitys;
	var SelectAll = document.forms[0].fieldSelectAllCB;

	var selectinset=GetCookie("selectinset");
	if (!selectinset) 
	{
		selectinset = "";
	}
	else 
	{
		selectinset = selectinset.replace(/SelectInSet=/gi,"")
	}

	if(checkForSubFacilities)
	{
		subfacilitys=GetCookie("subfacilitys");

		if (!subfacilitys) 
		{
		   subfacilitys = "";
		}
		else 
		{
			subfacilitys=subfacilitys.replace(/Subfacilitys=/gi,"");
		}
	      
		if(document.forms[0]._ctl0__ctl0_fieldchkSubFacilitys.checked == false)
		{
			subfacilitys ="Subfacilitys=0";
		}
		else
		{
			subfacilitys ="Subfacilitys=1";
		}
                
		SetCookie("subfacilitys","",subfacilitys);
	}		
	
	if(SelectAll == null || SelectAll.checked == false)
	{
		if (!cboxstatus) 
		{
			cboxstatus = "";
		}
		else 
		{
			cboxstatus = "," + cboxstatus.replace(/Ids=/gi,"")
		}

		strid = "," + elem.value;
		
		if (elem.checked) //Add it to the list of ids
		{
			if(cboxstatus.search(strid) == -1) 
			{ 
				cboxstatus+=strid
			}
		}
		else //the checkbox has been unchecked, remove it from the list of ids
		{
			strsearch = strid;

			if(cboxstatus.search(strsearch) != -1)
			{
				cboxstatus = cboxstatus.replace(strsearch,"")
			}
		}
		selectinset = "SelectInSet=0";
	}
	else //Select All is checked
	{
		if (!cboxstatus) 
		{
			cboxstatus = "";
		}
		else 
		{
			cboxstatus = "," + cboxstatus.replace(/Ids=/gi,"")
		}

		strid = "," + elem.value;
		
		if (!elem.checked) 
		{
			// add comma to end of each when searching so ",101,201" doesn't find entry for id = 1 or id = 2, etc
			if((cboxstatus + ',').search(strid + ',') == -1)  //Add it to the list of ids
			{
				cboxstatus+=strid;
			}
		}
		else //the checkbox has been unchecked, remove it from the list of ids
		{
			strsearch = strid + ',';

			if((cboxstatus + ',').search(strsearch) != -1)
			{
				cboxstatus = (cboxstatus + ',').replace(strsearch,",");
				// trim last character if it is comma since id removed was last one in string
				if (cboxstatus.substring(cboxstatus.length - 1) == ",")
					cboxstatus = cboxstatus.substring(0, cboxstatus.length - 1);
			}
		}
		selectinset = "SelectInSet=1";
	}

	// store it as a cookie that will expire in 1 hour
	var now=new Date();
	expdelay=1000*60*60; // persistence: 1 hour
	var expdate=new Date(Date.parse(now)+ expdelay);

	if(!cboxstatus)
	{
		cboxstatus = "IDs=" + cboxstatus.substring(1, cboxstatus.length);
	}

	//clean up extra commas and make sure IDs= is in the cookie
	if(cboxstatus.search("IDs=") == -1)
	{
		cboxstatus = "IDs=" + cboxstatus.substring(1, cboxstatus.length);
	}

	//alert(cboxstatus);
	//alert(selectinset);
	
	SetCookie("cboxstatus","",cboxstatus);
	SetCookie("selectinset","",selectinset);
}

//-----------------------------------------------------------------------------------------------------------
//     Author: Matt Kelsey, Doug Hobson (6.0 Update)
//	   Procedure Name: restoreCboxStatus														
//     Description: reads a cookie and restores the status of checkboxes on a page				  
//     Arguments: None
//     Return Value: (none)																		
//     Comments: (none)	   			
//-----------------------------------------------------------------------------------------------------------
function restoreCboxStatus(checkForSubFacilities)
{
	// search coockie:
	var cboxstatus=GetCookie("cboxstatus");//Get the status of all checkboxes
	var selectinset=GetCookie("selectinset");//Get selectinset cookie
	if(checkForSubFacilities)
	{
		var subfacilitys=GetCookie("subfacilitys"); //Get subfacility
    }
	if(!selectinset) 
	{
		selectinset = "";
	}

	selectinset=selectinset.replace(/SelectinSet=/gi,"");//Get numeric value for Selectinset

	if (!cboxstatus) 
	{
 		cboxstatus = "";
 	}
    if(checkForSubFacilities)
	{
 		if(!subfacilitys) 
 		{
	 		subfacilitys = "";
		}

		subfacilitys=subfacilitys.replace(/Subfacilitys=/gi,"");
	}
	
	var elem;
	var status;
	var j=0;
	var strIds;
	var re;
	var vntIds;
	var chkbox
	var hiddenelement;
 
	//Get the Ids of the checkboxes that have been checked.  Remove Ids=string.  Put in Array
	re = /Ids=/gi;
	strIds = cboxstatus;
	strIds = strIds.replace(re,"");
	vntIds = strIds.split(",")

	if(selectinset == 0) //want to check what is in cookie
	{
		for (var i=0;i<document.forms[0].elements.length;i++) //Loop through all the form elements
		{
			elem=document.forms[0].elements[i];
			if (elem.type=="checkbox")
			{
				if(elem.name != "fieldSelectAllCB")
				{
	   				hiddenelement = elem.value;
	   				for (var x=0;x<vntIds.length;x++)
					{
						if (vntIds[x] == hiddenelement) 
						{
							elem.checked = true;
						}
					}
   				}
  			}
		}
	}
	else //we want to check everything except what is in cookie
	{
		for (var i=0;i<document.forms[0].elements.length;i++) //Loop through all the form elements
		{
			elem=document.forms[0].elements[i];
			if (elem.type=="checkbox")
			{
				if(elem.name != "fieldSelectAllCB")
				{
					hiddenelement = elem.value;				

					for(var x=0; x < vntIds.length; x++)
					{
						if (vntIds[x] == hiddenelement) 
						{
							elem.checked = false;
							break;
						}
						else
						{
							elem.checked = true;
						}
					}
				}
			}
		}
	}

	if(document.forms[0].elements['fieldSelectAllCB'])
	{		
		if(selectinset == 1)
		{
			document.forms[0].elements['fieldSelectAllCB'].checked = true;
		}
		else
		{
			document.forms[0].elements['fieldSelectAllCB'].checked = false;
		}
	}
	if(checkForSubFacilities)
	{
		if(subfacilitys == 1)
		{
			document.forms[0].elements['fieldchkSubFacilitys'].checked = true;
		}
		else
		{
			document.forms[0].elements['fieldchkSubFacilitys'].checked = false;
		}
	}
}

//------------------------------------------------------------------------------------------------
//  Author:			Brian Tauke
//  Procedure Name:	nonblank
//  Description:	Determines whether or not an HTML form field contains a value.
//					If the field is empty, and error message is displayed in an 
//					alert box and page focus is given to the empty form field.
//  Arguments:		formname  - the name of the HTML form containing the input field
//					fieldname - the name of the form field being evaluated
//					errortext - the error text to be displayed if the field is empty
//  Return Value:	Boolean - True if the field contains a value, False if the 
//							  field is empty
//  Comments:		(none)
//------------------------------------------------------------------------------------------------
function nonblank(field, errortext) {
	
	var blnBlank = (trim(field.value) == "");

	//If the field value is blank, display the error message and give the field focus
	if (blnBlank == true) {
		popMessage(errortext, field);
	}

	//Return the result
	return !blnBlank;

}

//------------------------------------------------------------------------------------------------
//  Author:			F Baldoni
//  Procedure Name:	ValidateOneBoxChecked
//  Description:	Used for checkbox groups that are required. Makes sure that at least one
//					Check box is check
//  Arguments:		source  - 
//					arguments - 
//					
//  Return Value:	none
//
//  Comments:		This function is used by the checkbox custom validator to provide client side
//					validation. The id of the check box group is stored in the 
//					Value member of the arguments  argument.
//					See Aprimo.Web.EditControls.ApCheckBoxGroup.AddControls()
//------------------------------------------------------------------------------------------------

function ValidateOneBoxChecked(source , arguments)
{
	var value = ValidatorGetValue(source.controltovalidate);
	var intCnt = 0;
	// Check for a single checkbox first
	if (document.getElementById(FormFieldPrefix() + value) != null && 
	    document.getElementById(FormFieldPrefix() + value).tagName.toLowerCase() == "input") {
		if(document.getElementById(FormFieldPrefix() + value).checked)
			arguments.IsValid = true;
		else
			arguments.IsValid = false;
		
		return;
	}	
	
	//loop over the checkboxes in the group and return true if at lease one
	//checkbox is currently checked
	
	while(document.getElementById(FormFieldPrefix() + value + '_' + intCnt) != null )
	{
		if(document.getElementById(FormFieldPrefix() + value + '_' + intCnt).checked == true)
		{
			arguments.IsValid = true;
			return;
		} 
		intCnt++;
	}
	arguments.IsValid = false;
	return;
}

function cancelForm() {
	// If this is the only item in the history list, close the window
	// otherwise, go back to where we came from	
	if (window.history.length <= 0)
		window.close();
	else
		history.go(-1);
}

