//for navigating to different pages from home page
function onPageSubmit(pageName){
	var objForm = document.forms[0];
	objForm.action=pageName;
	objForm.submit();
}

function isAlphaAray(objArray,pMsgArray){
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var val = null;
	for(var i=0;i<objArray.length;i++){
		val =Trim(document.getElementById(objArray[i]).value);
		if(!isValid(val,lwr+upr+' ', "Invalid " + pMsgArray[i] + ". Valid " + pMsgArray[i] + " should contain only Alphabets (a-z)(A-Z).")){
			return false;
		}
	}
	return true;
}

/*******************************************************************************
 * Function: isAlphaArayPopup Arguments: element Value-parm, validation
 * value-val, error message-pMsg Return: true/false Purpose:This is a generic
 * function used to check whether the given element value is within the limits
 * of the validation value & returns false if it violates the validation value.
 * Notes: Author: Prakash Date: 01/27/2010
 ******************************************************************************/
function isAlphaArayPopup(objArray,pMsgArray, errorBoxId){
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var val = null;
	for(var i=0;i<objArray.length;i++){
		val =Trim(document.getElementById(objArray[i]).value);
		if(!isValidPopup(val,lwr+upr+' ', "Invalid " + pMsgArray[i] + ". Valid " + pMsgArray[i] + " should contain only Alphabets (a-z)(A-Z).", errorBoxId)){
			return false;
		}
	}
	return true;
}

	function isDoubleArray (objArray,pMsgArray) {
		var status = true;
	 	var isDecimal_re = /^\s*(\+|-)?((\d+(\.\d{0,2})?)|(\.\d{0,2}))\s*$/;
		for( var i = 0; i < objArray.length; i++ ){
			var val = document.getElementById(objArray[i]).value;
	 		status = String(val).search (isDecimal_re) != -1;
			if (!status) {
				displayError("Invalid "+ pMsgArray[i] +". Valid " + pMsgArray[i] +" should contain digits(Numbers (0-9) or Decimal 00.00)");
				return status;
			}
		}
		return status;
	}

/*******************************************************************************
 * Function: isValid Arguments: element Value-parm, validation value-val, error
 * message-pMsg Return: true/false Purpose:This is a generic function used to
 * check whether the given element value is within the limits of the validation
 * value & returns false if it violates the validation value. Notes: Author:
 * Nithin Date: 12/29/2008
 ******************************************************************************/

function isValid(parm,val,pMsg) {
	if (parm.length==0) return true;
	for (var i=0; i<parm.length; i++) {
		if (val.indexOf(parm.charAt(i),0) == -1) {
			displayError(pMsg);
			return false;
		}
	}
	return true;
}

/*******************************************************************************
 * Function: isValidPopup Arguments: element Value-parm, validation value-val,
 * error message-pMsg Return: true/false Purpose:This is a generic function used
 * to check whether the given element value is within the limits of the
 * validation value & returns false if it violates the validation value. Notes:
 * Author: Prakash Date: 01/27/2010
 ******************************************************************************/

	function isValidPopup(parm,val,pMsg, errorBoxId) {
		if (parm.length==0) return true;
		for (var i=0; i<parm.length; i++) {
			if (val.indexOf(parm.charAt(i),0) == -1) {
				displayErrorPopup(pMsg,errorBoxId);
				return false;
			}
		}
		return true;
	}

// for navigating to different pages from home page
function navigate(form,pageName){
	onPageSubmit(pageName);
}

function clearContorls(){
	clearControls();
}

function clearControls(){
	document.forms[0].reset();
	// clearing select box content
	/*
	 * if( document.getElementById("spanSelectBox") ){
	 *
	 * var controlName = document.getElementById("spanSelectBox") ;
	 * if(controlName && isNaN(controlName.length)) { controlName.innerHTML =
	 * "&lt;------- Select ------&gt;"; }else{ for(var i=0;i<controlName.length;i++) {
	 * var strContent = document.getElementById(controlName[i]);
	 * strContent.innerHTML = "&lt;------- Select ------&gt;"; } } }
	 */
	var selectArr = document.getElementsByTagName("select");
	for (i=0; i  < selectArr.length; i++) {
		var listBox = selectArr[i];
		var tmp = listBox.parentNode.childNodes;
		for(k=0; k < tmp.length; k++) {
			if( tmp[k].nodeName == 'SPAN' ){
					tmp[k].innerHTML = listBox.options[listBox.selectedIndex].text ;
				break;
			}
		}
	}
	document.getElementById("idErrorBox").style.display="none";
}

function confirmDelete() {
	if(confirm(" Do you really want to delete this record ? ")){
		return true;
	} else{
		return false;
	}
}

/*******************************************************************************
 * Function: isEmpty Arguments: String Return: Boolean Purpose: Function to
 * check if the string is empty or contains space as first character Notes: This
 * Function only works for IE and any other browsers Author: Keshav Date:
 * 01/11/2007
 ******************************************************************************/
	function isEmpty(StrName) {
		StrName = Trim(StrName);
		if(StrName == null || StrName.length == 0)
			 return false;
		// check for space as first char
		var  c = StrName.charAt(0) ;
		if (c==" ") return false ;
			return true;
	}

/*******************************************************************************
 * Function: Trim Arguments: String Return: String Purpose: Function to remove
 * empty spaces from left and right hand side of the string. Internally calls
 * LTRIm and RTrim functions. Notes: Author: Balaji Date: 01/13/2007
 ******************************************************************************/
	function Trim(pString) {
		return RTrim(LTrim(pString));
	}

/*******************************************************************************
 * Function: LTrim Arguments: String Return: String Purpose: Function to remove
 * empty spaces from left hand side of the string Notes: Author: Balaji Date:
 * 01/13/2007
 ******************************************************************************/
	function LTrim(pString) {
		var whitespace = new String(" \t\n\r");
	    var oString = new String(pString);
	    if (whitespace.indexOf(oString.charAt(0)) != -1) {
			var jCount = 0
			var iCount = oString.length;
			while (jCount < iCount && whitespace.indexOf(oString.charAt(jCount)) != -1)
			   jCount++;
			oString = oString.substring(jCount, iCount);
	    }
	    return oString;
	}

/*******************************************************************************
 * Function: RTrim Arguments: String Return: String Purpose: Function to remove
 * empty spaces to the right hand side of the string Notes: Author: Balaji Date:
 * 01/13/2007
 ******************************************************************************/
	function RTrim(pString) {
		var whitespace = new String(" \t\n\r");
	    var oString = new String(pString);
	    if (whitespace.indexOf(oString.charAt(oString.length-1)) != -1) {
			var iCount = oString.length-1;
			while (iCount >= 0 && whitespace.indexOf(oString.charAt(iCount)) != -1)
			   iCount--;
			oString = oString.substring(0, iCount+1);
	    }
	    return oString;
	}

/*******************************************************************************
 * Function: displayError Arguments: String - Error message Return: Purpose:
 * Sets the error message for a error DIV Notes: Author: Vadiraj Date:
 * 01/13/2007
 ******************************************************************************/
	function displayError(psErrMsg) {
		var objIdErrorBox = document.getElementById('idErrorBox');
		objIdErrorBox.className = 'error';
		objIdErrorBox.innerHTML="";
		if(psErrMsg != "") {
			objIdErrorBox.innerHTML="<li>"+psErrMsg+" !</li>";
			objIdErrorBox.style.display='';
		}
		try{
			var objIdErrorBox1 = document.getElementById('idErrorBoxbottom');
			objIdErrorBox1.innerHTML="";
			if(psErrMsg != "") {
				objIdErrorBox1.innerHTML="<li>"+psErrMsg+"</li>";
				objIdErrorBox1.style.display='';
			}
		}catch(error){}
	}

	function displaySuccess(psErrMsg) {
		var objIdErrorBox = document.getElementById('idErrorBox');
		objIdErrorBox.className = 'messageBox';
		objIdErrorBox.innerHTML="";
		if(psErrMsg != "") {
			objIdErrorBox.innerHTML="<li>"+psErrMsg+"</li>";
			objIdErrorBox.style.display='';
		}
		try{
			var objIdErrorBox1 = document.getElementById('idErrorBoxbottom');
			objIdErrorBox1.innerHTML="";
			if(psErrMsg != "") {
				objIdErrorBox1.innerHTML="<li>"+psErrMsg+"</li>";
				objIdErrorBox1.style.display='';
			}
		}catch(error){}
	}


	function displayErrorPopup(psErrMsg, errorBoxId) {
		var objIdErrorBox = document.getElementById(errorBoxId);
		objIdErrorBox.innerHTML="";
		if(psErrMsg != "") {
			objIdErrorBox.innerHTML="<li>"+psErrMsg+"</li>";
			objIdErrorBox.style.display='';
		}
	}

/*******************************************************************************
 * Function: checkMandatory Arguments: arralist of mandatory elements, string -
 * error message Return: String Purpose: Function checks for all mandatory
 * fileds in the form and return true if all are valid otherwise displays error
 * message Notes: Author: Balaji Date: 01/13/2007
 ******************************************************************************/
	function checkMandatory(objArray,strMandatoryMessage) {
		for(var i=0;i<objArray.length;i++) {
			var strContent = document.getElementById(objArray[i]);
			var strContentValue = Trim(strContent.value);
			if(!isEmpty(strContentValue)) {
				if(strMandatoryMessage != null && strMandatoryMessage.length > 0)
					displayError(strMandatoryMessage);
				return false;
			} else {
				strContent.value = strContentValue;
			}
		}
		return true;
	}

	/***************************************************************************
	 * Function: checkMandatoryDetailed Arguments: arralist of mandatory
	 * elements, arralist of mandatory elements Labels Return: String Purpose:
	 * Function checks for all mandatory fileds in the form and return true if
	 * all are valid otherwise displays error message specifying the field Name.
	 * Notes: Date: 11/01/2009
	 **************************************************************************/
	function checkMandatoryDetailed(objArray,objArrayNames) {
		for(var i=0;i<objArray.length;i++) {
			var strContent = document.getElementById(objArray[i]);
			var strContentValue = Trim(strContent.value);
			if(!isEmpty(strContentValue)) {
				if(objArrayNames[i] != null && objArrayNames.length > 0)
					displayError(objArrayNames[i]+ " is Mandatory.");
				return false;
			} else {
				strContent.value = strContentValue;
			}
		}
		return true;
	}

	function checkMandatoryDetailedPopup(objArray,objArrayNames, errorBoxId) {
		for(var i=0;i<objArray.length;i++) {
			var strContent = document.getElementById(objArray[i]);
			var strContentValue = Trim(strContent.value);
			if(!isEmpty(strContentValue)) {
				if(objArrayNames[i] != null && objArrayNames.length > 0)
					displayErrorPopup(objArrayNames[i]+ " is Mandatory.",errorBoxId);
				return false;
			} else {
				strContent.value = strContentValue;
			}
		}
		return true;
	}

	/***************************************************************************
	 * Function: checkMandatoryCheckElements NOTE**: Elements of type Checkbox
	 * and RadioButton Arguments: arralist of mandatory elements '**name',
	 * arralist of mandatory elements Labels Return: String Purpose: Function
	 * checks for all mandatory fileds in the form and return true if all are
	 * valid otherwise displays error message specifying the field Name. Notes:
	 * Date: 11/01/2009
	 **************************************************************************/
	function checkMandatoryCheckElements(objArray,objArrayNames) {
		if(objArray != null && objArray.length > 0
				&& objArrayNames != null && objArrayNames.length > 0){
			for(var i=0;i<objArray.length;i++) {
				var isChecked = false;
				var strElements = document.getElementsByName(objArray[i]);
				if(strElements){
					for(var j=0;j<strElements.length;j++){
						if(strElements[j].checked == true)
							isChecked = true;
					}
					if(!isChecked){
						displayError(objArrayNames[i]+ " is Mandatory.");
						return false;
					}
				}
			}
		}
		return true;
	}


/*******************************************************************************
 * Function: checkLetters Arguments: String and Character set as String Return:
 * Boolean Purpose: Function returns False if Name contains any special
 * characters, else returns True Notes: Author: Keshav Date: 01/11/2007
 ******************************************************************************/
	function checkLetters(StrName,pMsg) {
		var letter = "0123456789+-/ ";
		var i ;
		for(i = 0 ; i < StrName.length ; i++) {
		 	var  Char = StrName.charAt(i) ;
			if (letter.indexOf(Char) == -1) {
				displayError(pMsg);
				return false ;
			}
		}
		return true ;
	}

/*******************************************************************************
 * Function: isValidRadio Arguments: Name of the control Return: Boolean
 * Purpose: Control could be single checkbox/radio or group of checkbox/radio.
 * If control(chk/radio) is single it returns the value of the control. If its a
 * radio group then returns the selcted radio value and returns the comma
 * seperated values if its checkbox group. Notes: This Function only works for
 * IE and any other browsers Author: Keshav Date: 01/11/2007
 ******************************************************************************/
	function getSelectedValue(pName) {
		sValue="";
		if(document.frmPage[pName]){
			var objFormElement = document.frmPage[pName];
			if(objFormElement != null && isNaN(objFormElement.length)) {
				if(objFormElement.checked) {
					sValue = objFormElement.value;
					return sValue;
				}
			} else {
				if(objFormElement[0].type=="checkbox") {
					sValue="";
					for(var i=0;i<objFormElement.length;i++) {
						if(objFormElement[i].checked) {
							if(sValue == "")
								sValue = objFormElement[i].value;
							else
								sValue = sValue + "," + objFormElement[i].value;
						}
					}
					return sValue;
				} else if(objFormElement[0].type=="radio") {
					for(var i=0;i<objFormElement.length;i++) {
						if(objFormElement[i].checked) {
							sValue = objFormElement[i].value
							return sValue;
						}
					}
				}
			}
		}
		return sValue;
	}

/*******************************************************************************
 * Function: truncateString Arguments: Name of the control, Length of the field
 * value to be restricted Purpose: This function truncates the value of a given
 * string value to the restricted number and sets the same back to the control
 * before save. Author: Vivek Date: 05/03/2007
 ******************************************************************************/
	function truncateString( fieldName, truncateByLength ) {
		var objFormElement = document.frmPage[fieldName];
		var fieldValue = objFormElement.value;
		if( fieldValue.length > truncateByLength ) {
			objFormElement.value = fieldValue.substring( 0, truncateByLength-1 );
		}
	}

	// getting unSelected checkbox values
	function getUnselectedValue(pName) {
		var sValue="";
		var objFormElement = document.frmPage[pName];
		if(isNaN(objFormElement.length)) {
			if(!objFormElement.checked){
				sValue = objFormElement.value;
				return sValue;
			}
		} else{
			if(objFormElement[0].type == "checkbox") {
				for(var i=0;i<objFormElement.length;i++){
					if(!objFormElement[i].checked){
						if(sValue == "")
							sValue = objFormElement[i].value;
						else
							sValue = sValue + "," + objFormElement[i].value;
					}
				}
				return sValue;
			}
		}
		return sValue;
	}
/*******************************************************************************
 * Function: isNumeric Arguments: String - value of the control Return: Boolean
 * Purpose: Checks if the entered value is numeric or not, returns false for
 * non-numeric, true otherwise. Notes: Author: Keshav Date: 01/11/2007
 ******************************************************************************/

	function isNumeric(StrName) {
		var letter = "0123456789";
		var i ;
		for(var i = 0 ; i < StrName.length ; i++) {
		 	var  Char = StrName.charAt(i) ;
			if (letter.indexOf(Char) == -1) {
				return false ;
			}
		}
		return true ;
	}

	/***************************************************************************
	 * Function: isNumberAray Arguments: arralist of elements to be validated,
	 * arralist of label msgs of elements to be validated Return: true/false
	 * Purpose:This is function used to check whether the given element is
	 * number or not, this function internally calls the generic isValid
	 * function passing number argument as validation range, which returns
	 * true/false for the given element. This functions loops each element in
	 * the objArray to validate each element & show an error msg as per label of
	 * the element. Notes: Author: Nithin Date: 12/29/2008
	 **************************************************************************/
	function isNumberAray(objArray,pMsgArray) {
		var numb = '0123456789';
		var val= null;
		for(var i=0;i<objArray.length;i++){
			val =Trim(document.getElementById(objArray[i]).value);
			if(!isValid(val,numb,"Invalid " + pMsgArray[i] + ". Valid " + pMsgArray[i] + " contains only Numbers (0-9).")){
				return false;
			}
		}
		return true;
	}

/*******************************************************************************
 * Function: validatePassword Arguments: New Password String and Retype Password
 * String Return: Boolean Purpose: function to compare new password and retype
 * password, returns false if passwords do not match Notes: Author: Keshav Date:
 * 01/11/2007
 ******************************************************************************/

	function validatePassword(StrNewPwd,StrRetPwd,strErrorMessage) {
		var invalid = " "; // Invalid character is a space
		var minLength = 8; // Minimum length

		// check for minimum length
		if (StrNewPwd.length < minLength) {
			displayError('Password must be atleast ' + minLength + ' characters long. Try again.');
			return false;
		}
		// check for spaces
		if (StrNewPwd.indexOf(invalid) > -1) {
			displayError('Password cannot have space in it. Try again.');
			return false;
		} else {
			// compare the passwords
			if (StrNewPwd != StrRetPwd) {
				displayError (strErrorMessage);
				return false;
			} else {
				return true;
		    }
		}
	}

/*******************************************************************************
 * Function: isValidEmail Arguments: Email as String Return: Boolean Purpose:
 * Function to validate email address entered. Notes: Author: Keshav Date:
 * 01/11/2007
 ******************************************************************************/

	function isValidEmail(psEmail,errMsg) {
		psEmail = Trim(psEmail)
		var regExp = /^[a-zA-Z0-9]+[.a-zA-Z0-9_-]+@[a-zA-Z0-9_.-]+\.[a-zA-Z]+$/;
		var regExp1 = /^[a-zA-Z]+@[a-zA-Z0_.-]+\.[a-zA-Z]+$/;
		var temp = new String(psEmail);
		if(psEmail!="") {
			if((regExp.test(psEmail)) || (regExp1.test(psEmail))) {
				if((temp.charAt(temp.length-1)!='.') && (!isNumeric(temp.charAt(temp.length-1)))) {
					return true;
				} else {
					displayError(errMsg);
					return false;
				}
			} else {
				displayError(errMsg);
			    return false;
			}
		} else {
			displayError(errMsg);
		    return false;
		}
	}

/*******************************************************************************
 * Function: checkDate Arguments: Date as string Return: Boolean Purpose:
 * Function to validate date and date format Notes: Author: Keshav Date:
 * 01/11/2007
 ******************************************************************************/

	function isValidDate(strDate,strErrMsg) {
		// var strDate = strDate.replace(/^\s+/g, '').replace(/\s+$/g, '');
		// alert(strDate);
		var validformat = /\b\d{2}[\/-]\d{2}[\/-]\d{4}\b/;
		// var validformat=/^\d{4}\-\d{2}\-\d{2}$/ //Basic check for format
		// validity
		if (!validformat.test(strDate)) {
			displayError("Invalid Date Format. Please correct and submit again.");
			return false;
		} else { // Detailed check for valid date ranges
			var yearfield=strDate.split("-")[2];
			var monthfield=strDate.split("-")[0];
			var dayfield=strDate.split("-")[1];
			var dayobj = new Date(yearfield, monthfield-1, dayfield);
			if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield)) {
				displayError("Invalid "+strErrMsg +" Please correct and submit again.");
				return false;
			} else {
				return true;
			}
		}
	}

/*******************************************************************************
 * Function: checkDate Arguments: FromDate as String and ToDate as String
 * Return: Boolean Purpose: Function to validate ToDate is greater than FromDate
 * Notes: Author: Keshav Date: 01/11/2007
 ******************************************************************************/
	function checkDate(fromDate,toDate) {
		// Getting the Start Date and split in to pieces by giving "-" symbol
		var str1 = new String(fromDate);
		// Getting the End Date and split in to pieces by giving "-" symbol
		var str2 = new String(toDate);
		if(str1!="" && str2!="") {
			str1 = str1.split("-");
			if(str1.length == 1) {
				str1 = new String(fromDate);
				str1 = str1.split("/");
			}
			str2 = str2.split("-");
			if(str2.length == 1) {
				str2 = new String(toDate);
				str2 = str2.split("/");
			}
			if (str2[2] > str1[2]) {
				return true;
			} else if (str2[2] ==  str1[2]) {
				if (str2[0] >  str1[0]) {
					return true;
				} else if (str2[0] ==  str1[0]) {
					if(str2[1].length == 1) {
						str2[1] = '0' + str2[1];
					}
					if(str1[1].length == 1) {
						str1[1] = '0' + str1[1];
					}
					if (str2[1] > str1[1]) {
						return true;
					} else if (str2[1] == str1[1]) {
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return true;
		}
	}

/*******************************************************************************
 * Function: isValidTime Arguments: Time as String Return: Boolean Purpose:
 * Function to validate Time Entered is in the "HH:MM:SS" pattern. Seconds are
 * optional Notes: Author: Keshav Date: 01/11/2007
 ******************************************************************************/
	function isValidTime(timeStr) {
		var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?$/;
		var matchArray = timeStr.match(timePat);
		if (matchArray == null) {
			// alert("Time is not in a valid format.");
			return false;
		}
		hour = matchArray[1];
		minute = matchArray[2];
		second = matchArray[4];
		if (second=="") {
			second = null;
		}
		if (hour < 0  || hour > 23) {
			// alert("Hour must be between 0 and 23.");
			return false;
		}
		if (minute<0 || minute > 59) {
			// alert ("Minute must be between 0 and 59.");
			return false;
		}
		if (second != null && (second < 0 || second > 59)) {
			// alert ("Second must be between 0 and 59.");
			return false;
		}
		return true;
	}


	/*******************************************************************************
	 * Function: isValidTimeIn12HrFormat Arguments: Time as String Return: Boolean Purpose:
	 * Function to validate Time Entered is in the "HH:MM:SS" pattern. Seconds are
	 * optional Notes: Author: Keshav Date: 01/11/2007
	 ******************************************************************************/
		function isValidTimeIn12HrFormat(timeStr) {
			var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?$/;
			var matchArray = timeStr.match(timePat);
			if (matchArray == null) {
				// alert("Time is not in a valid format.");
				return false;
			}
			hour = matchArray[1];
			minute = matchArray[2];
			second = matchArray[4];
			if (second=="") {
				second = null;
			}
			if (hour < 1  || hour > 12) {
				// alert("Hour must be between 0 and 23.");
				return false;
			}
			if (minute<0 || minute > 59) {
				// alert ("Minute must be between 0 and 59.");
				return false;
			}
			if (second != null && (second < 0 || second > 59)) {
				// alert ("Second must be between 0 and 59.");
				return false;
			}
			return true;
		}

/*******************************************************************************
 * Function: moveData Arguments: List box objects Return: Purpose: Function to
 * move selected option from combobox to a listbox and to move selected options
 * from listbox to combobox Notes: This Function only works for IE and any other
 * browsers Author: Keshav Date: 01/11/2007
 ******************************************************************************/

	function moveData(objList1, objList2) {
	     var arrobjList1 = new Array();
	     var arrobjList2 = new Array();
	     var arrLookup = new Array();
	     var i;

		 for(i=0; i<objList2.options.length; i++) {
	          arrLookup[objList2.options[i].text] = objList2.options[i].value;
	          arrobjList2[i] = objList2.options[i].text;
	     }

		 var iList1Length = 0;
	     var iList2Length = arrobjList2.length

	     for(i=0; i<objList1.options.length; i++) {
	          arrLookup[objList1.options[i].text] = objList1.options[i].value;
	          if(objList1.options[i].selected && objList1.options[i].value != "") {
	               arrobjList2[iList2Length] = objList1.options[i].text;
	               iList2Length++;
	          } else {
	               arrobjList1[iList1Length] = objList1.options[i].text;
	               iList1Length++;
	          }
	     }
	     arrobjList1.sort();
	     arrobjList2.sort();
	     objList1.length = 0;
	     objList2.length = 0;
	     var c;

	     for(c=0; c<arrobjList1.length; c++) {
	          var no = new Option();
	          no.value = arrLookup[arrobjList1[c]];
	          no.text = arrobjList1[c];
	          objList1[c] = no;
	     }

	     for(c=0; c<arrobjList2.length; c++) {
	     	var no = new Option();
	     	no.value = arrLookup[arrobjList2[c]];
	     	no.text = arrobjList2[c];
	     	objList2[c] = no;
	     }
	}

	// Added by balaji for Check and Uncheck All the check box.
	function Toggle(e,f) {
		f = document.getElementById(f);
		f.checked=e.checked?AllChecked(e.name):false;
    }

    function ToggleByName(childname,f,checked) {
		f = document.getElementById(f);
		f.checked=checked?AllChecked(childname):false;
    }

    function ToggleAll(e,name) {
    	if(e.checked)
    		CheckAll(e,name)
		else
	    	ClearAll(e,name);
    }
    function CheckAll(f,name) {
		for (var i = 0; i <document.frmPage.elements.length; i++) {
	    	var e = document.frmPage.elements[i];
	    	if (e.name ==name )
				e.checked=true;
		}
		f.checked = true;
    }
    function ClearAll(f,name) {
		for (var i = 0; i <document.frmPage.elements.length; i++) {
		    var e = document.frmPage.elements[i];
		    if (e.name == name)
				e.checked=false;
		}
		f.checked = false;
    }
    function AllChecked(name) {
		ml = document.frmPage;
		for(var i = 0 ; i < document.frmPage.elements.length ; i++) {
		    if (ml.elements[i].name == name && !ml.elements[i].checked)
				return false;
		}
		return true;
	}

	function resort(id,name) {
		var strSortby = document.frmPage.SortBy.value;
		var strOrderby = document.frmPage.OrderBy.value;
		if(strOrderby==id) {
			if(strSortby=="desc") {
				document.frmPage.SortBy.value="asc";
			} else {
				document.frmPage.SortBy.value="desc";
			}
		} else {
			document.frmPage.SortBy.value="asc";
		}
		document.frmPage.OrderBy.value=id;
		document.frmPage.submit();
	}

	function insert_image(applicatinContext) {
		var strSortby = document.frmPage.SortBy.value;
		var strOrderby = document.frmPage.OrderBy.value;
		if(strOrderby=="") {
			if(document.getElementById('name')) {
				var objName = document.getElementById('name');
				var strContent = objName.innerHTML;
				var strImage = 	"&nbsp;<img src=\""+applicatinContext+"/images/sort_icn.gif\"/>";
				strContent = strContent+strImage;
				objName = strContent;
			}
		} else {
			if(document.getElementById(strOrderby)) {
				var objOrderBy = document.getElementById(strOrderby);
				if(objOrderBy.type!='hidden') {
					var strContent = objOrderBy.innerHTML;
					var strImage="";
					if(strSortby=="asc") {
						strImage = 	"&nbsp;<img src=\""+applicatinContext+"/images/sort_up_icn.gif\"/>";
					} else {
						strImage = 	"&nbsp;<img src=\""+applicatinContext+"/images/sort_icn.gif\"/>";
					}
					strContent= strContent+strImage;
					objOrderBy.innerHTML = strImage;
				}
			}
		}
	}

	function doLoginOnEnterClick(e) {
		// the purpose of this function is to allow the enter key to
		// point to the correct button to click.
		var key;

		if(window.event)
              key = window.event.keyCode;     // IE
         else
              key = e.which;     // firefox

        if (key == 13) {
            // Get the button the user wants to have clicked
            var btn = document.getElementById('login');
            if (btn != null) { // If we find the button click it
                btn.click();
                event.keyCode = 0;
            }
        }
   }

function disableAllControls() {
	var objArray = document.frmPage.elements;
	for(i=0;i<objArray.length;i++) {
		objArray[i].disabled=true;
	}
}

  function ToggleSearch(searchTable,searchToggleImage,applicatinContext){
		if(document.getElementById(searchTable).style.display=='none'){
			document.getElementById(searchTable).style.display='';
			document.getElementById(searchToggleImage).src=applicatinContext+"/images/open.gif";
		} else {
			document.getElementById(searchTable).style.display='none';
			document.getElementById(searchToggleImage).src=applicatinContext+"/images/closed.gif";
		}
  }

  /***************************************************************************
	 * Function: clearFields Arguments: table-id Return: Purpose: This function
	 * clears all the data from the text-box and select-box fields under the
	 * given table. Notes: Author: Yasaswi Pakala Date: 06/Feb/2009
	 **************************************************************************/
function clearFields_old(tableId) {
	var tableBody = document.getElementById(tableId).tBodies[0];
	var trChild = null;
	var tdChild = null;
	var element = null;

	for(var i=0; i<tableBody.childNodes.length; i++) {
		trChild = tableBody.childNodes[i];
		for(var j=0; j<trChild.childNodes.length; j++) {
			tdChild =  trChild.childNodes[j];

			for(k=0; k<tdChild.childNodes.length; k++) {
				element = tdChild.childNodes[k];

				if(element.type == "text" || element.nodeName == "SELECT" || element.type == "textarea") {
					element.value = "";
				}
			}
		}
	}
}

  /***************************************************************************
	 * Function: clearFields Arguments: table-id Return: void Purpose: This
	 * function will reset all the controls within the given table. Author:
	 * Kishore Pothireddy Date: 18/Nov/2009
	 **************************************************************************/
  function clearFields(tableId) {
	  if(document.getElementById(tableId)){
		  var tbl = document.getElementById(tableId);
		  var inputs =  tbl.getElementsByTagName("input");
		  var lists =  tbl.getElementsByTagName("select");
		  var txtareas =  tbl.getElementsByTagName("textarea");


		  for(var k=0; k < inputs.length; k++) {
			  if(inputs[k].type == 'text' || inputs[k].type == 'file')
				  inputs[k].value = '';
			  else if(inputs[k].type == 'checkbox' || inputs[k].type == 'radio')
				  inputs[k].checked = false;
		  }
		  for(var i=0; i < lists.length; i++){
			  lists[i].value = '';
			  try{
			  $(lists[i]).parent().find('#spanSelectBox').html('');
			  }catch(e){}
		  }
		  for(var j=0; j < txtareas.length; j++)
			  txtareas[j].value = '';
	  }
  }

/*******************************************************************************
 * Function: isAlphaNumericSpecial Arguments: arralist of elements to be
 * validated, arralist of label msgs of elements to be validated and speacial
 * characters set Return: true/false Purpose:This function is used to check
 * whether the given element is alphaNumeric containing the only specified
 * special characters. This function internally calls the generic isValid
 * function passing alphaNumeric argument as validation range, which returns
 * true/false for the given element. This functions loops each element in the
 * objArray to validate each element & show an error msg as per label of the
 * element. Notes: Date: 06/04/2009
 ******************************************************************************/
function isAlphaNumericSpecial(objArray,pMsgArray,splChars){
		var numb = '0123456789';
		var lwr = 'abcdefghijklmnopqrstuvwxyz';
		var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		var spChar = splChars;
		var str = lwr+upr+numb+spChar;
		var val=null;
		for(var i=0;i<objArray.length;i++){
		 val =Trim(document.getElementById(objArray[i]).value);
		if(!isValid(val,str,"Invalid " + pMsgArray[i] + ". Valid " + pMsgArray[i] + " should contain only Alphabets (a-z)(A-Z), Numbers (0-9) and Special Characters (" +spChar+ ").")){
			return false;
		}
		}
		return true;
}

/*******************************************************************************
 * Function: isNameAlphaSpecial Arguments: arralist of elements to be validated,
 * arralist of label msgs of elements to be validated Return: true/false
 * Purpose:This is function used to check whether the given element is
 * aplanumeric plus the allowed special characters or not, this function
 * internally calls the generic isValid function passing alphaNumeric argument
 * as validation range, which returns true/false for the given element. This
 * functions loops each element in the objArray to validate each element & show
 * an error msg as per label of the element. Notes: Date: 01/23/2009
 ******************************************************************************/
function isNameAlphaSpecial(objArray,pMsgArray) {
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var spChar = ' '+'_-(),';
	var str = lwr+upr+spChar;
	var val  =null;

	for(var i=0;i<objArray.length;i++) {
		val =Trim(document.getElementById(objArray[i]).value);
		if(!isValid(val,str,"Invalid " + pMsgArray[i] + ". Valid " + pMsgArray[i] + " should contain only Alphabets (a-z)(A-Z), Special Characters ( _-(), ) and Spaces.")) {
			return false;
		}
	}
	return true;
}

/*******************************************************************************
 * Function: checkPhoneNumber Arguments: arralist of elements to be validated,
 * arralist of label msgs of elements to be validated Return: true/false
 * Purpose:This is function used to check whether the given element is a valid
 * phone number or not. Notes: Date: 01/27/2008
 ******************************************************************************/
function checkPhoneNumber(objArray,pMsgArray) {
	var numb = '0123456789-() ';
	var val= null;

	for(var i=0;i<objArray.length;i++) {
		val =Trim(document.getElementById(objArray[i]).value);

		if(!isValid(val,numb,"Invalid " + pMsgArray[i] + ". Valid " + pMsgArray[i] + " should contain only Numbers (0-9) and -().")) {
			return false;
		}
	}
	return true;
}

/*******************************************************************************
 * Function: isLong Arguments: element Value-parm, error message-pMsg Return:
 * true/false Purpose:This is function used to check whether the given element
 * is Long or not, this function internally calls the generic isValid function
 * passing number argument as validation range, which returns true/false for the
 * given element. Notes: Date: 01/11/2009
 ******************************************************************************/
function isLong(parm,pMsg) {
	var numb = '0123456789';
	var val =Trim(document.getElementById(parm).value);
	if(val <= 0) {
		displayError("Invalid " + pMsg + ". Valid " + pMsg + " should be greater than zero");
		return false;
	}
	else
		return isValid(val,numb,"Invalid " + pMsg + ". Valid " + pMsg + " should contain only Numbers (0-9)");
}

function isLongArray(parmArr,pMsgArr) {
	var numb = '0123456789';
	for(i=0;i<parmArr.length;i++)
	{
		if(! isLong(parmArr[i],pMsgArr[i]))
			return false;
	}

	return true;
}

function flashMovie(movieName) {
   	if(window.document[movieName])
		return window.document[movieName];
	else
		return document.getElementById(movieName);
}

/*******************************************************************************
 * Function: checkTextAreaMaxlength Arguments: objArray-arralist of elements to
 * be validated, maxLen, pMsgArray-arralist of mandatory elements Labels Return:
 * true/false Purpose:This is function used to check the maxlength of textarea.
 * Here we are checking the maxlength of each textarea in the screen and if it
 * exceeds maxlength, this function show an error msg as per label of the
 * element. Notes:
 ******************************************************************************/

function checkTextAreaMaxlength(objArray, maxLen, pMsgArray) {
	for(var i=0;i<objArray.length;i++){
		val =Trim(document.getElementById(objArray[i]).value);
		if(val!= null) {
			if(val.length > maxLen)	{
				displayError(" Length of " +pMsgArray[i]+" should not exceed "+maxLen+" Characters.");
				return false;
			}
		}
	}
	return true;
}


function removeTrailingComma ( ctrl ) {
	var txtValue = ctrl.value;
	while( txtValue.charAt(txtValue.length-1) == ',' || txtValue.charAt(txtValue.length-2) == ',' ) {
		txtValue = txtValue.substring(0,txtValue.lastIndexOf(','));
	}
	ctrl.value = txtValue;
}


	// Here is a JavaScript function to do currency formatting:
	function CurrencyFormatted(amount) {
		var i = parseFloat(amount);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + .005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return s;
	}
	// end of function CurrencyFormatted()


	function openCloseDiv(divId,toggleImgId,context) {
		if(document.getElementById(divId).style.display=='none'){
			document.getElementById(divId).style.display='';
		}
		else {
			document.getElementById(divId).style.display='none';
		}
	}


	function fnMoveItems(lstbxFrom,lstbxTo) {
	 var varFromBox = document.getElementById(lstbxFrom);
	 var varToBox = document.getElementById(lstbxTo);
	 if ((varFromBox != null) && (varToBox != null)) {
	  if(varFromBox.length < 1) {
	   alert('There are no items in the source ListBox');
	   return false;
	  }
	  if(varFromBox.options.selectedIndex == -1) // when no Item is selected the index will be -1
	  {
	   alert('Please select an Item to move');
	   return false;
	  }
	  while ( varFromBox.options.selectedIndex >= 0 ) {
	   var newOption = new Option(); // Create a new instance of ListItem

	   newOption.text = varFromBox.options[varFromBox.options.selectedIndex].text;
	   newOption.value = varFromBox.options[varFromBox.options.selectedIndex].value;
	   varToBox.options[varToBox.length] = newOption; // Append the item in
														// Target Listbox

	   varFromBox.remove(varFromBox.options.selectedIndex); // Remove the item
															// from Source
															// Listbox
	  }
	 }
	 return false;
	}


	//If you want to disable form submission when enter key is pressed in an input field,
	//you must use the function above on the OnKeyPress:
	function disableEnterKey(e)
	{
	     var key;
	     if(window.event)
	          key = window.event.keyCode; //IE
	     else
	          key = e.which; //firefox

	     return (key != 13);
	}

	function moaFileBrowser (field_name, url, type, win) {
	  // alert("Field_Name: " + field_name + "\nURL: " + url + "\nType: " + type + "\nWin: " + win); // debug/testing
	   /*
	    var cmsURL = window.location.toString();    // script URL - use an absolute path!
	    if (cmsURL.indexOf("?") < 0) {
	        cmsURL = cmsURL + "?type=" + type;
	    }
	    else {
	        cmsURL = cmsURL + "&type=" + type;
	    }*/
	    var filePath = '', winTitle='',wh=620,ht=410;

		if( type == 'image'){
			filePath =  '/moa/rteditor/listEditorImages.moa';
			winTitle =  'MOA Image Browser';
			ht=410;
		} else {
			filePath =  '/moa/rteditor/listEditorMedia.moa';
		    winTitle =  'MOA Media Browser';
		    wh=800;
		    ht=420;
		}
	    tinyMCE.activeEditor.windowManager.open({
	        file : filePath,
	        title : winTitle,
	        width : wh,
	        height: ht,
	        resizable: 'yes',
	        inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
	        close_previous : "no",
	        popup_css :false
	    }, {
	        window : win,
	        input : field_name,
	        flashv : 'flash_flashvars',
	        wid : 'width',
	        hei : 'height'
	    });
	    return false;
	  }

	//function to unhide a div
	function showdiv(div)
	{
	   var mydiv = document.getElementById(div);
	   if (mydiv != null)
	   {
		   //div found
		   //mydiv.style.visibility="visible";
		   mydiv.style.display="block";
	   }
	}
	//function to hide a div
	function hidediv(div)
	{
	   var mydiv = document.getElementById(div);
	   if (mydiv != null)
	   {
		   //div found
		   //mydiv.style.visibility="hidden";
		   mydiv.style.display="none";
	   }
	}


	function validatePrice(fieldName,fieldLabel)
	{
		var reFloat =/^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
		var testResult = null;
		var fieldValue = Trim(document.getElementById(fieldName).value);
		if(fieldValue.length > 0)
		{
			testResult=reFloat.test(fieldValue);
			if(!testResult){
				displayError("Invalid "+fieldLabel+" found. The "+fieldLabel+" should contain digits(Numbers (0-9) or Decimal 00.00)");
				return false;// Abort
			}
	  	}else{
	  		displayError("Invalid "+fieldLabel+" found. The "+fieldLabel+" should contain digits(Numbers (0-9) or Decimal 00.00)");
	  		return false;// Abort
		}
	  	return true;
	}
