/**
* This function evaluates the input string for a correct E-Mail format.
* It calls a function isEmpty to find whether the input string is Empty.
* @param strValue string value.
* @return true, if the Format is right || false otherwise.
*/
function isEmail(objField){
	if(objField.value.length > 0){
		if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(objField.value)){
			return true;
		}
	}
	alert("Invalid E-mail Address! Please re-enter.(i.e. username@domainname.com)");
	objField.select();
	return false;
}
//<!----------------------------------------------------------------

/**
* Checks the input string parameter for null and empty. 
* This function also validates the input string for whitespace.
* @param strData string input value.
* @return true if the text is null or empty string
* @return false if the text is not null or empty string
*/
function isEmpty(strData){
	if ((strData.length == 0)||(strData == null)){
		return true;
	}

	//Regular expression refers any 0 or more white space with any alphabets.
	//If that expression matches with the input string it returns true, false otherwise.
	if (/^\s*(?=\w)/.test(strData)){
		return false;
	}
    return true;
}
//<!------------------------------------------------------------------!>

/**
* Validate the input for a proper file name.
* @param strFile string File name.
* @return true || false
*/
function isFile(strFile){
	if(isEmpty(strFile)){
		return false;
	}

	var strFind = new String(strFile);
	var intPos = strFind.lastIndexOf("\\");

	if (/^[a-zA-Z]*[^\/:*?"<;>;|]+(?=\.\w{3,4})/.test(strFind.substring(intPos+1,strFile.length))){
		return true;	
	}
	return false;
}
//<!------------------------------------------------------------------!>

/**
* This function evaluates the input string for Whitespace.
* @param strValue string value.
* @return true, if it finds whitespaces || false otherwise.
*/
function isImage(strFile){
	if (!isFile(strFile)){
		return false;
	}

	var strFName = new String(strFile);
	var intIndx = strFName.lastIndexOf('.');
	var strExn = strFName.substring(intIndx+1,strFName.length).toLowerCase();

	if(/^\S*(gif|jpg|bmp)/.test(strExn)){
		return true;
	}
	return false;
}
//<!----------------------------------------------------------------

/**
* This function is used to validate the Phone number field.
* @param obField Form field object.
* @param strField Form field name.
* @return true, if it is in number || false otherwise.
*/
function isPhone(obField, strField){
	var strData = new String(obField.value);
	
	for (var i=0; i < strData.length; i++){
		if ((strData.charAt(i) != '-')&&(strData.charAt(i) < '0') || (strData.charAt(i) > '9')){
			alert("Numeric value is required for the field "+ strField);
			obField.select();
			return false;
		}
	}
	return true;
}
//<!----------------------------------------------------------------

/**
 * addState function populates the US states.
 */
function addState(obElem,sSel){
	var US_state = new Array('Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming');

	for(var i=1;i<US_state.length; ++i){
		if(US_state[i].match(sSel) != null){
			obElem.options[i] = new Option(US_state[i],US_state[i],'',false);
			obElem.options[i].selected = true;
		}
		else
			obElem.options[i] = new Option(US_state[i],US_state[i],'',false);
	}
}


/**
* This function is used to restrict the non-numeric value.
* @return false if non-numeric keycode
*/
function forceNumber(event){
  var keyCode = event.keyCode ? event.keyCode : event.charCode;	
  // backspace keyCode = 8
  // tab keyCode = 9  
  // left arrow keyCode = 37  
  // right arrow keyCode = 39    
  // delete keyCode = 46      
  // refresh(F5) keyCode = 116        
  if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 9 && keyCode != 37 && keyCode != 39 && keyCode != 46 && keyCode != 116) 
	  return false;
}
//<!----------------------------------------------------------------

/**
* This function is used to restrict the non-numeric value.
* @return false if non-numeric keycode
*/

function forcePhone(event){
  var keyCode = event.keyCode ? event.keyCode : event.charCode;	
  // backspace keyCode = 8
  // tab keyCode = 9  
  // left arrow keyCode = 37  
  // right arrow keyCode = 39    
  // delete keyCode = 46      
  // refresh(F5) keyCode = 116        
  if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 9 && keyCode != 37 && keyCode != 39 && keyCode != 46 && keyCode != 116) 
	  return false;
}

/**
 * It forces the user to input only characters
 * @return ture or false
 */
function forceChar(event){
  var keyCode = event.keyCode ? event.keyCode : event.charCode;	
  // backspace keyCode = 8
  // tab keyCode = 9  
  // left arrow keyCode = 37  
  // right arrow keyCode = 39    
  // delete keyCode = 46      
  // refresh(F5) keyCode = 116  	
	if((keyCode > 57 || keyCode == 32) && keyCode != 8 && keyCode != 9 && keyCode != 37 && keyCode != 39 && keyCode != 46 && keyCode != 116)
		return true;	
	return false;
}


/**
* This function is used to restrict the non-numeric value except space.
* @return false if non-numeric keycode
*/
function forceNumSpace(event){
  var keyCode = event.keyCode ? event.keyCode : event.charCode;	
  // backspace keyCode = 8
  // tab keyCode = 9  
  // space keyCode = 32
  // left arrow keyCode = 37  
  // right arrow keyCode = 39    
  // delete keyCode = 46      
  // refresh(F5) keyCode = 116  
  if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 9 && keyCode != 32 && keyCode != 37 && keyCode != 39 && keyCode != 46 && keyCode != 116) 
	  return false;  
}
//<!----------------------------------------------------------------

/**
* This function is used to restrict the non-numeric value.
* @return false if non-numeric keycode
*/
function forceMoney(event,obField){
	var str = obField.value;
	
	var keyCode = event.keyCode ? event.keyCode : event.charCode;	
	// backspace keyCode = 8
	// tab keyCode = 9  
	// left arrow keyCode = 37  
	// right arrow keyCode = 39    
	// delete keyCode = 46      
	// refresh(F5) keyCode = 116 	

	if((keyCode<48 || keyCode>58) && keyCode != 8 && keyCode != 9 && keyCode != 37 && keyCode != 39 && keyCode != 46 && keyCode != 116) 
		return false;

	if(keyCode==46){
		for(var intI = 0; intI < str.length; intI++){
			if(str.charAt(intI) == "."){
				return false;
			}
		}
	}
}
//<!----------------------------------------------------------------

/**
* Creates a window object and loads the Document file.
* @param url refers the file to be loaded
*/
//<!----------------------------------------------------------------
function openDoc(url,wd,hg,resize){
	var strFeature = "left=0,top=0,width="+wd+", height="+hg+", scrollbars=yes,resizable="+resize;
	var obWin = window.open(url,"newWin",strFeature);
	obWin.focus();
	if(!obWin.opener) obWin.opener = self;
}

/**
* Creates a window object and loads the image file.
* @param url refers the file to be loaded
*/
//<!----------------------------------------------------------------
function openImg(url){
	var obWin = window.open(url,"imgWin","left=0,top=0,width=300,height=250");
	obWin.focus();
	if(!obWin.opener) obWin.opener = self;
}


/**====================================================================
 * NAME		:	datecmp(obDate1,obDate2)
 * DESC		:	Compares two date value, returns whether the second date is greater or equal.
 * PARAM	:	obDate1 start date
 *				obDate2 End date
 * RETURN	:	second date property as, 
 *				1 	= greater
 *				0	= Equal
 *				-1	= smaller	
 *====================================================================*/
 function datecmp(obDate1,obDate2){
	var dtStart, dtEnd;
	dtStart = obDate1[0].value +"/"+ obDate1[1].value +"/"+ obDate1[2].value;
	dtEnd = obDate2[0].value +"/"+ obDate2[1].value +"/"+ obDate2[2].value;
	
	var dtFirst = new Date(dtStart);
	var dtSec = new Date(dtEnd);
	var intFtime = Math.floor(dtFirst.getTime()/(24*60*60));
	var intStime = Math.floor(dtSec.getTime()/(24*60*60));
	var intDiff = (intStime-intFtime);
	if(intDiff < 1){
		return 0;
	}
	else if(intDiff >= 1){
		return 1;
	}
 }

	/**
	* Opens a the page in a popup window.
	*/
 	function popUpPage(sPage,iWd,iHg){
		var obWin;
		//alert(sPage);
		obWin = window.open(sPage,"popWin","width="+iWd+", height="+iHg+",statusbar=no");
		if(!obWin.opener) obWin.opener = _self;
		obWin.focus();
	}


	/*
	* This function is used to highlight the selected row
	*/
	function rollOver(obElem){
		//alert(obElem);
		//alert(obElem.style.backgroundColor);
		document.getElementById("svr1").style.backgroundColor = "red";
		//document.getElementById("svr1").style.backgroundColor = "#C3D8FB";
		//}
	}


	/**
	 * This function is used to check the deblicate user name in the database
	 *
  	 */
	function authenticate(sTarget){
		var bFlag = 0;
		var obXttp;
		
		if(window.ActiveXObject){
			obXttp = new ActiveXObject("Microsoft.XMLHTTP")
		}
		else{
			obXttp = new XMLHttpRequest();
		}
		
		obXttp.open("GET",sTarget,false);
		obXttp.send();
		
		if(obXttp.readyState == 4){
			if(obXttp.status == 200){
				bFlag = obXttp.responseText;
			}
		}
		
		return bFlag;
	}

/**
* strComp function compares two input strings and return result in boolean value.
* @param strFirst base text on which the other string is compared
* @param strSec compared string
* @return True || False.
*/
function strComp(strFirst,strSec){
	if (strFirst.length == strSec.length){
		var strResult = new String(strFirst);

		if (strResult.search(strSec) != -1){
			return true;
		}
	}
	return false;
}

//<!----------------------------------------------------------------
/**
 * Function setCaption displays and hides a caption for the text field according to the users onfocus and blur event.
 */
 function setCaption(obElement,blnSts){
	if(obElement.value == obElement.defaultValue){
		if(blnSts == 1)
			obElement.value = "";
		else
			obElement.value = obElement.defaultValue;
	}
 }
 
	/**
	 * getFile identifies the file name from the physical path and returns the separated file.
	 */
	function getFile(fileName){
		var strRaw = new String(fileName);		
		var strFile = "";
		var intLpos = strRaw.lastIndexOf("\\");
	
		strFile = strRaw.substr(intLpos+1,(strRaw.length - intLpos));
	
		return strFile;
	}

	/**
	 * This function is to check the selected file is a document.	
	 */
	function isDocument(obElem){
		var strExt = obElem.value.split("\.").pop();
		
		if(strExt.match("doc") || strExt.match("pdf"))
			return true;
		else{
			alert("Please select only .doc or .pdf files");
			obElem.select();
			return false;
		}
	}


	/**
	* ImageFrame 
	* Resize the window based on the image size
	*/
	function imageFrame(){
		var obImg = document.images[0];
		var intHg = document.body.clientHeight;
		var intWd = document.body.clientWidth;

		intHg = obImg.height - intHg;
		intWd = obImg.width - intWd;

		window.resizeBy(intWd, intHg);
		self.focus();
	}
 
 /**=============================================================================
 * NAME		:	getDefault()
 * DESC		:	This function clears the default value of the control when the focus is move on it.
 * PARAM	:	obElem - Element object
 * =============================================================================
 */
 
 	function getDefault(obElem){
		if(obElem.defaultValue.match(obElem.value) != null){
			obElem.value = "";
		}
	}

/**=============================================================================
 * NAME		:	setDefault()
 * DESC		:	This function sets the default value of the form controls.
 *				It sets the default focus when the control is empty on last focus event.
 * PARAM	:	Form form name
 * =============================================================================
 */
	function setDefault(Form){
		for(var i = 0; i < Form.elements.length; i++){
			if(isEmpty(Form.elements[i].value)){
				Form.elements[i].value = Form.elements[i].defaultValue;
			}
		}
	}
 
 /**=============================================================================
 * NAME		:	defaultFocus()
 * DESC		:	This function sets the focus to the first field of the form.
 * PARAM	:	Form form name
 * =============================================================================
 */
	function defaultFocus(){
		var F = document.forms[0];
		if(F){
			if(F.elements[0] && !F.elements[0].disabled){
				F.elements[0].focus();
			}
		}
	}
	
	/*==============================================================================
	 * NAME		:	setTarget(page)	
	 * DESC		:	This function sets the target page for the form action property.
	 * PARAM	: 	Page string page name
	 *==============================================================================*/
 	function setTarget(page){
		var F = document.forms[0];
		
		F.method = "post";
		F.action = page;
		F.submit();
	}
 
 	
	/*==============================================================================
	 * NAME		:	printPage()	
	 * DESC		:	This function calls the window.print() function.
	 *==============================================================================*/
	function printPage(){
		if(window.print){
			window.print();	
		}
	}
	
	/**
	 *  Add to Favorite function adds the webpage to the Favorite collections.
	 */
	function addFavorite(){
		window.external.addFavorite(location.href,document.title);
	}

	/**
	 *  setImg function sets the image in the image placeholder.
	 */
	function setImg(path,obImg){
		if(path != ''){
			obImg.src = path;	
			obImg.style.display = "block";
		}
		else{
			obImg.style.display = "none";
		}
		
	}
	
	/**
	 *  setImg function sets the image in the image placeholder.
	 */
	function control(Form,bFlag){
		for(var i=0; i<Form.elements.length; i++){
			if(Form.elements[i].type != "submit" && Form.elements[i].type != "button"){	
				Form.elements[i].disabled = bFlag;
			}
		}
	}
	

	function isLeapYear(year){
		if((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0))
			return true;
		else
			return false;
	}
	
	
	function monthDays(obElement){
		var Mon	= obElement[0].value;
		var Day = obElement[1].value;
		var Year = obElement[2].value;
		
		if(Mon == 4 || Mon == 6 || Mon == 9 || Mon == 11){
			if(Day > 30){
				obElement[1].value = 30;
			}
		}
		else {
			if(Mon == 2){
				if(isLeapYear(Year)){
					if(Day > 29){
						obElement[1].value = 29;
					}
				}
				else{
					if(Day > 28){
						obElement[1].value = 28;
					}
				}
			}
		}
	}
	
	
	
	function listing(obElem){
		obElem.style.backgroundColor="#507688";
		obElem.style.cursor='hand';
	}
	
	
	function listing_hover(obElem){
		obElem.style.backgroundColor="#A5B8C1";
	}
	
	
	function set_target(sDest){
		window.location.href = sDest;
		window.focus();
	}
	
	function trim(objField){//Params: field to trim
		//This removes all the leading and trailing spaces from the field.
		while(''+objField.charAt(0)==' ')
			objField=objField.substring(1,objField.length);
		while(''+objField.charAt(objField.length-1)==' ')
			objField=objField.substring(0,objField.length-1);
	}
	
	
	function isURL(objField){
		trim(objField);
		var truth = 1;
//		var strPattern = /^http:\/\/[A-Za-z\-_0-9\.]+\.[A-Za-z]{2,3}|^http:\/\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/
		var strPattern = /^(http|https):\/\/[A-Za-z\-_0-9\.]+\.[A-Za-z]{2,3}/;
		truth = strPattern.test(objField)

		strPattern1 = /^[^A-Za-z0-9_]|\s+/
		truth1 = strPattern1.test(objField)

		if (truth == 0 || truth1 != 0){
			return true;
		}
	}
	
//Date validate
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function isDate(day,month,year,fulldate){
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;
	
	var dtStr;
	if(fulldate){
		dtStr = fulldate
	}
	else{
		dtStr = month+'/'+day+'/'+year
	}

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false;
	}
return true;
}

/**
 *  This function is used to get mod value .
 */

function Mod(X, Y) 
{ 
	return X - Math.floor(X/Y)*Y 
}


/**
* This function is used to force to display numeric value with decimal.
* @return false if non-numeric
*/

function formatDecNumber(field, decplaces) {
    num = parseFloat(field);
    if (!isNaN(num)) {
        var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        var decpoint = str.length - decplaces;
        return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}

 /**====================================================================
 * NAME		:	datecmp(obDate1,obDate2)
 * DESC		:	Compares two date value, returns whether the second date is greater or equal.
 * PARAM	:	obDate1 start date
 *				obDate2 End date
 * RETURN	:	second date property as, 
 *				1 	= greater
 *				0	= Equal
 *				-1	= smaller	
 *====================================================================*/
 function datecom(objDate1,objDate2){
	var dtStart, dtEnd;
	//alert(objDate2);
	var obDate1 = objDate1.split("-");
	var obDate2 = objDate2.split("-");
	
	dtStart = obDate1[0] +"/"+ obDate1[1] +"/"+ obDate1[2];
	dtEnd = obDate2[0] +"/"+ obDate2[1] +"/"+ obDate2[2];
	
	var dtFirst = new Date(dtStart);
	var dtSec = new Date(dtEnd);
	var intFtime = Math.floor(dtFirst.getTime()/(24*60*60));
	var intStime = Math.floor(dtSec.getTime()/(24*60*60));
	var intDiff = (intStime-intFtime);
	//alert (intDiff);
	if(intDiff < 0){
		return -1;
	}
	else if(intDiff == 0){
		return 0;
	}
	else if(intDiff >= 1){
		return 1;
	}
 }


/**
* This function is used to force to display numeric value with decimal.
* @return false if non-numeric
*/

function forceDecNumber(field, decplaces) {
    num = parseFloat(field.value);
    if (!isNaN(num)) {
        var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        var decpoint = str.length - decplaces;
		//alert(str.substring(0,decpoint) + "." + str.substring(decpoint,str.length));
        field.value = str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}
