/*
 
 ****************************************************************************
 The eTM software, screen designs, functionality, software code, text and
 business logic are the exclusive property of eMagineWorks.  This
 document is provided  under eTM user license terms and conditions. No
 part of this document or file can be copied, modified, sold or
 re-produced in any form. This software is protected under U.S. and
 international copyright laws.  All rights reserved.
 ****************************************************************************
 
*/

//date validation
function checkDate(field,Item) {
	var dateString = field.value;
	var errormsg = "Please enter a valid date in the dd/mm/yyyy format " + Item
    if (dateString.indexOf("-")!=-1){
    	var sdate = dateString.split("-")
    	dateString = sdate[1] + "/" + sdate[0] + "/" + sdate[2];
    }else {
    	var sdate = dateString.split("/")
    	dateString = sdate[1] + "/" + sdate[0] + "/" + sdate[2];
    }
    if(sdate.length != 3){
    	alert(errormsg);
    	field.focus();
    	return false;
    }
    if(!testInt(sdate[0]) || !testInt(sdate[1]) || !testInt(sdate[2])){
    	alert(errormsg);
    	field.focus();
    	return false;
    }
    
    if (sdate[2].length != 1 && sdate[2].length != 2 && sdate[2].length != 4) {
        alert(errormsg);
        field.focus();
        return false;
    }
    if (sdate[2].length == 2) {
        if(1*sdate[2]<30){
            if (1*sdate[2] < 10) {
                sdate[2] = "200"+(1*sdate[2]);
            } else {
                sdate[2] = "20"+sdate[2]
            }
        	//dateString = sdate.join("/")
        	//alert(dateString);
        	//alert(datestring)
        	dateString = sdate[1] + "/" + sdate[0] + "/" + sdate[2];
        	
        } else if (1*sdate[2] < 100) {
            sdate[2] = "19" + sdate[2];
        }
    }
	
	var chkDate=new Date(Date.parse(dateString))
    var cmpDate=(chkDate.getMonth()+1)+"/"+(chkDate.getDate())+"/"+(sdate[2])
    //var cmpDate=(chkDate.getDate())+"/"+(chkDate.getMonth()+1)+"/"+(sdate[2])
    var newDate=(1*sdate[1])+"/"+(1*sdate[0])+"/"+(sdate[2])

    if ((""+newDate)!= (""+cmpDate) || isNaN(chkDate)){
		alert(errormsg);
    	field.focus();
    	return false;
    }
	else 
		return true;
}
//function used in date validation
function testInt(anum){
    numstr = "0123456789"
    for(var i=0;i<anum.length;i++){
    if(numstr.indexOf(anum.charAt(i)) == -1)return false
    }
    return true
}


//text validation
function testText(field,Item)
{
	var anum = field.value;
	if(anum == "")
	{
		alert("Please Enter valid " + Item);
		field.focus();
		return false;
	}
    return true
}


//integer validation
function testInteger(field,Item)
{
	var anum = field.value;
	if(anum == "")
	{
		alert("Please Enter valid " + Item);
		field.focus();
		return false;
	}
    numstr = "0123456789"
    for(var i=0;i<anum.length;i++){
		if(numstr.indexOf(anum.charAt(i)) == -1)
		{
			alert("Please Enter valid " + Item);
			field.focus();
			return false;
		}
    
    }
    return true
}

//float validation
function testFloat(field,Item)
{
	var anum = field.value;
	if(anum == "")
	{
		alert("Please Enter valid " + Item);
		field.focus();
		return false;
	}
	var Count = 0;
	numstr = "0123456789."
    for(var i=0;i<anum.length;i++){
    if(numstr.indexOf(anum.charAt(i)) == -1)
    {
		alert("Please Enter valid " + Item);
		field.focus();
		return false;
    }
    if(anum.charAt(i) == ".")
    {
		Count = Count + 1;
		if(Count > 1)
		{
			alert("Please Enter valid " + Item);
			field.focus();
			return false;
		}
		
	}
	
    }
    return true
}



function testPhone(field,Item)
{
	var anum = field.value;
	if(anum == "")
	{
		alert("Please Enter valid " + Item);
		field.focus();
		return false;
	}
	var Count = 0;
	numstr = "0123456789-()"
    for(var i=0;i<anum.length;i++){
    if(numstr.indexOf(anum.charAt(i)) == -1)
    {
		alert("Please Enter valid " + Item);
		field.focus();
		return false;
    }
    if(anum.charAt(i) == ".")
    {
		Count = Count + 1;
		if(Count > 1)
		{
			alert("Please Enter valid " + Item);
			field.focus();
			return false;
		}
		
	}
	
    }
    return true
}




//Email validation
function testEmail(field,Item,mandatory)
{
	var mailid = field.value;
	var errMsg = "Please Enter valid " + Item + "\n" + "( eg: mail@domain.com )";
	if(mandatory == "yes")
	{
		
		if(mailid == "")
		{
			alert(errMsg);
			field.focus();
			return false;
		}
	}
	if((mailid.indexOf("@") == -1)||(mailid.indexOf(".") == -1))
	{
		alert(errMsg);
		field.focus();
		return false;
	}	
	
	return true;
}

/*Added by Gupta*/
//This function allows the user to press the characters 0-9,a-z,A-Z and space
function _checkAlphaNum()
{
	var keyChar=String.fromCharCode(event.keyCode)
	if((keyChar>="0")  && (keyChar<="9"))
		return true
	if((keyChar>="a") && (keyChar<="z"))
		return true
	if((keyChar>="A") && (keyChar<="Z"))
		return true
	if(keyChar==" ")
		return true
	return false
}
//This function allows the user to press the characters 0-9
function _checkNum()
{
	var keyChar=String.fromCharCode(event.keyCode)
	if((keyChar>="0")  && (keyChar<="9"))
		return true
	return false
}
/* upto here */
/* Added by Gupta */
// This function replaces double quotes with html encode &quot;
	function replacedbQuote(s)
	{
		var vs;
		vs='';
		for(i=0;i<s.length;i++)
		{
			if(s.charAt(i)=='"')
				vs=vs + "&quot;"
			else
				vs=vs+s.charAt(i)
		}
		return vs
	}
//This function allows the user to press the characters 0-9,a-z,A-Z and space
function _checkAddress()
{
	var keyChar=String.fromCharCode(event.keyCode)
	if((keyChar>="0")  && (keyChar<="9"))
		return true
	if((keyChar>="a") && (keyChar<="z"))
		return true
	if((keyChar>="A") && (keyChar<="Z"))
		return true
	if(keyChar==" ")
		return true
	if(keyChar=="(")
		return true
	if(keyChar==")")
		return true
	if(keyChar=="/")
		return true
	if(keyChar=="'")
		return true
	if(keyChar==",")
		return true
	if(keyChar==".")
		return true
	if(keyChar==":")
		return true
	if(keyChar==";")
		return true
	if(keyChar=="!")
		return true
	if(keyChar=="@")
		return true
	if(keyChar=="#")
		return true
	if(keyChar=="$")
		return true
	if(keyChar=="&")
		return true
	if(keyChar=="*")
		return true
	if(keyChar=="-")
		return true

	return false
}
function _checkDD()
{
	var keyChar=String.fromCharCode(event.keyCode)
	if((keyChar>="0")  && (keyChar<="9"))
		return true
	if(keyChar=="-" || keyChar=="/")
		return true
	return false
}
function testDD(field,Item)
{
	var anum = field.value;
	if(anum == "")
	{
		alert("Please Enter valid " + Item);
		field.focus();
		return false;
	}
    numstr = "0123456789/-"
    for(var i=0;i<anum.length;i++){
		if(numstr.indexOf(anum.charAt(i)) == -1)
		{
			alert("Please Enter valid " + Item);
			field.focus();
			return false;
		}
    
    }
    return true
}

function fn_round(Amt)
{
	strAmt=new String(Amt)
	if(strAmt.indexOf(".")!=-1)
	{
		if(strAmt.substr(strAmt.indexOf(".")+3,strAmt.indexOf(".")+4)>5)
			strAmt=new String(parseFloat(strAmt)+ 0.001)
		if(strAmt.indexOf(".")!=-1)
			strAmt=strAmt.substr(0,strAmt.indexOf(".")+3)
	}
	return strAmt
}
/* till here */

/* upto here */
/* Added by Gupta */
//This function allows the user to press the characters 0-9
function _checkFloat()
{
	
	var keyChar=String.fromCharCode(event.keyCode)
	if(((keyChar>="0")  && (keyChar<="9")) || (keyChar == "."))
		return true
	return false
}

// added by nilesh on Aug 03
// check decimal for a number
function _checkDecimals(decCount,eleMent,eleDesc){
		
		var eleValue = eval(eleMent).value
	    if (eleValue.indexOf(".")<0) return true
		var dotIndex = eleValue.lastIndexOf(".")+1
		var decValue = eleValue.substr(dotIndex,eleValue.length)
		if (decValue.length>decCount){
			alert(msg.decimal(decCount + " decimals for " + eleDesc))
			eleMent.focus()
			eleMent.select()

			return false
		}
		return true
	}
	
	
function AlertMessages(){
	this.mandatory = function(eleDesc) {return eleDesc + " is left blank. \nYou have to fill-in this field."}
	this.firstblank = function(eleDesc) {return eleDesc + " does not allow a data with first character as a blank charactar. \nPlease re-enter the data."}
	this.email = function(eleDesc) {return "A valid e-mail address is required in " + eleDesc}
	this.integer = function(eleDesc) {return "Please enter a valid Integer value in " + eleDesc}
	this.numeric = function(eleDesc) {return "Only numerics values are allowed in " + eleDesc }
	this.date = function(eleDesc) {return "Please enter a valid date in the dd/mm/yyyy format " + eleDesc}
	this.nonzero = function(eleDesc) {return "Please enter a valid Non-Zero, Positive Integer in " + eleDesc}
	this.selected = function(eleDesc) {return "Please select " + eleDesc}
	this.decimal =  function(eleDesc) {return "Cannot enter more than " + eleDesc}
}
msg = new AlertMessages()	


function ValidateIntegers(input, control, compulsory)
{
	var Cont_Value = input;
	
	var Cont_Name =control;
	var Cont_Validate=compulsory;
	for(i=0;i<Cont_Value.length;i++)
	{
		var str=Cont_Value.charAt(i);
		if(isNaN(str))
		{
		
			alert("Only positive integers (eg. 777) less than 65536 are allowed in " + Cont_Name + ". Negative integer values are not allowed. Please re-enter correct data.");
			return false;
		}
	}
	if ((Cont_Value=="") && (Cont_Validate=="Y"))
	{
		alert (Cont_Name + " is left blank. You have to fill-in this field.")
		
		return false;
	}
	else if ((Cont_Validate=="Y") &&(Cont_Value.charAt(0)==" "))
	{
		alert (Cont_Name + " does not allow a data with first character as a blank character. Please re-enter the data.");
		
		return false;
	}
	else if ((Cont_Value.charAt(0)==" "))
	{
		alert (Cont_Name + " does not allow a data with first character as a blank character. Please re-enter the data.")
		
		return false
	}
	else if(isNumeric(Cont_Value)==false)
	{
		alert("Please enter a valid Integer value in " + Cont_Name + ".")
		
		return false;
	}
	else if((Cont_Value.charAt(0)=="+") || (Cont_Value.charAt(0)=="-"))
	{
		alert("Arithmetic characters are not allowed in " + Cont_Name + ". Please remove the arithmetic character and re-enter the data.")
		input.focus();		
		return false;
	}
	else if((parseInt(Cont_Value) < 0) || parseInt(Cont_Value) > 65536)
	{
		alert("Only positive integers (eg. 777) less than 65536 are allowed in " + Cont_Name + ". Negative integer values are not allowed. Please re-enter correct data.");
		
		return false;
	}
	else
		return true;	
}


// function to validate integers
//Added by takrim
function isNumeric(val)
{

	var re=/[^0-9]/;
	
	return !re.test(val);
}

//function to check numbers


function ValidateDigits(input, control, compulsory)
{
	var Cont_Value = input;
	var Cont_Name =control;
	var Cont_Validate=compulsory;
	
	if ((Cont_Value=="") && (Cont_Validate=="Y"))
	{
		alert (Cont_Name + " is left blank. You have to fill-in this field.")
		return false;
	}
	else if ((Cont_Validate=="Y") &&(Cont_Value.charAt(0)==" "))
	{
		alert (Cont_Name + " does not allow a data with first character as a blank character. Please re-enter the data.")
		return false
	}
	else if ((Cont_Value.charAt(0)==" "))
	{
		alert (Cont_Name + " does not allow a data with first character as a blank character. Please re-enter the data.")
		return false
	}
	else if((Cont_Value.charAt(0)=="+") || (Cont_Value.charAt(0)=="-"))
	{
		alert("Arithmetic characters are not allowed in " + Cont_Name + ". Please remove the arithmetic character and re-enter the data.")
		return false;
	}
	else if(!isPin(Cont_Value))
	{
		alert ("Please enter a valid number in "+ Cont_Name +  " NOTE: First character cannot be a zero and "  + Cont_Name + " allows only numbers greater than zero (eg. 12345). Please re-enter the data.")
		return false;
	}	
	else
		return true;
}

function isAddress(val)
{

	var re=/([^A-Za-z0-9._\-\)\(\\,; ])/;
	
	return !re.test(val);
}
function isPin(val){
	var re=/^-|[^0-9]/;
	return !re.test(val);
}

function checkFloat(input,control,compulsory)
{
	
	var Cont_Name =control;
	var Cont_Validate=compulsory;
	var Cont_Value = input;
	
	if ((Cont_Validate=="Y") &&(Cont_Value.length==0))
	{
		alert (Cont_Name + " is left blank. You have to fill-in this field.")
		return false
	}
	
	else if((Cont_Value.charAt(0)=="+") || (Cont_Value.charAt(0)=="-"))
	{
		alert("Less Than Zero and Arithmetic characters are not allowed in " + Cont_Name + ". Please remove the arithmetic character and re-enter the data.")
		return false;
	}
	else if (Cont_Value!="")
		{
			if(isNaN(Cont_Value) || (Cont_Value.charAt(0)==" "))
			{
				alert(Cont_Name + " can allow only values greater than Zero. Plese re-enter the data.")
				return false
			}	
			for(i=0;i<Cont_Value.length;i++)
			{
				var ch  = Cont_Value.charAt(i);
				if(ch=='.')
				 	 {
						var substr=Cont_Value.substring(i+1,Cont_Value.length);
					
						if(substr.length > 2)
							{
								alert(Cont_Name + " Can allow Only Two digits after decimal. Please re-enter data.")
					
								return false;
							}
				 		}
              }
			if(Cont_Value<=0)
			{
				alert("Only value greater than zero is allowed in " + Cont_Name + ". Please re-enter the data.")
				return false
			}	
						
		}
		else
		return true
}
	//////////////////////////////////////////////////////////////////////////////
	//	IsObject( obj )
	//////////////////////////////////////////////////////////////////////////////
	function IsObject( obj )
	{
		return typeof( obj ) == 'object';
	}	
	
	
	/*

replaceSubstring("hellothere", "l", "x") = "hexxothere"
replaceSubstring("this is a string", "is", "x") = "thx x a string"
replaceSubstring("Here is a long string", "", "xxx") = "Here is a long string"
replaceSubstring("Here is a long string", " ", "") = "Hereisalongstring"
' The slash is a literal character, so "\\" is a single slash
replaceSubstring("\\mysubdir\\mydatabase.nsf", "\\", "/") = "/mysubdir/mydatabase.nsf"
' If the string is "literal \s\w characters", it must be represented literally like "literal \\s\\w characters"
replaceSubstring("literal \\s\\w characters", "\\", "\\\\") = "literal \\s\\w characters"
replaceSubstring("Getting rid of unwanted words", "unwanted", "unneeded") = "Getting rid of unneeded words"*/
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function


function ValidateTextArea(input, control, compulsory,fieldlen)
{
	
	var Cont_Value = input;
	
	var Cont_Name =control;
	var Cont_Validate=compulsory;
	var Cont_Length=fieldlen;
	if ((Cont_Value=="") && (Cont_Validate=="Y"))
	{
		alert (Cont_Name + " is left blank. You have to fill-in this field.")
		return false;
	}
	else if ((Cont_Validate=="Y") && ((Cont_Value.charAt(0)==" ") || (Cont_Value.charCodeAt(0)=="13") || (Cont_Value.charCodeAt(0)=="32") ))
	{
		alert (Cont_Name + " does not allow a data with first character as a blank or a new line character. Please re-enter the data.")
		return false
	}
	else if ((Cont_Value.charAt(0)==" "))
	{
		alert (Cont_Name + " does not allow a data with first character as a blank character. Please re-enter the data.")
		return false
	}
	else if (Cont_Value.length > Cont_Length)
	{
		alert (Cont_Name + " Field Length Cannot be greater than " + Cont_Length + " Characters. Please enter data less than or equal to " + Cont_Length + "  characters.");
		return false;
	}
	
	else
		return true;	
}


// function to validate date in "dd/mm/yyyy" format and allows year from 1900 to current running year
 
function ValidateCurrentDate(input,control,compulsory,strSrvDate)
{
        var Cont_Value = input;
        var Cont_Name =control;
        var Cont_Validate=compulsory;
         
		alert(Cont_Value);
	        var date=new Date(strSrvDate);
        if ((Cont_Validate=="Y") &&(Cont_Value.length==0))
        {
                alert (Cont_Name + " is left blank. You have to fill-in this field.")
                return false
        }
        else if (Cont_Value!="")
        {
	
                var strdate=Cont_Value
                var intstart=0
                var intsep=0
                var intcount=0
                var intdate=new Array(2)
 
                while (intsep!=-1)
                {
                        intsep=strdate.indexOf("/",intstart);
                        if (intsep==-1)
                                intdate[intcount]=strdate.substr(intstart)
                        else
                                intdate[intcount]=strdate.substr(intstart,intsep-intstart)
                        intstart=intsep+1
                        intcount=intcount+1
                }
                var str = intdate[1]+"/"+intdate[0]+"/"+intdate[2];
	        var d=new Date(str)

                if ((intdate[0]!= d.getDate()) || (intdate[1]!= d.getMonth()+1) || (intdate[2]!=d.getFullYear()))
                {
                        alert("For " +  Cont_Name + " the value " + Cont_Value + " is not a valid date. Please enter a valid date in  dd/mm/yyyy (eg. 13/11/2002) format.")
                        return false
                }
	       if(intdate[0].length>2)
               {
                     alert("For " +  Cont_Name + " the value " + Cont_Value + " is not a valid date. Please enter a valid date in  dd/mm/yyyy (eg. 13/11/2002) format.")
                     return false
               }
	       if(intdate[1].length>2)
               {
                     alert("For " +  Cont_Name + " the value " + Cont_Value + " is not a valid date. Please enter a valid date in  dd/mm/yyyy (eg. 13/11/2002) format.")
                     return false
               }	
              	
              if(intdate[2].length>4 || intdate[2].length <4)
               {
                     alert("For " +  Cont_Name + " the value " + Cont_Value + " is not a valid date. Please enter a valid date in  dd/mm/yyyy (eg. 13/11/2002) format.")
                     return false
               }
	
             if((intdate[2]<1900))
                {
                alert("Only year greater than 1900 are allowed in "+ Cont_Name + " Please re-enter a valid year greater than 1900.");
                        return false;
                 }
          	
	    if(d>date)
		{
			var month = date.getMonth()+1;
			 alert(Cont_Name+ " cannot exceed current date. Please re-enter date less than or equal to " +date.getDate()+"/"+month+"/"+date.getFullYear()); 
			return false;
		}
	 
			
        }
        else
                return true
}  

