//Checks for blanks
//Pass the field name 
//returns false if the conditions are not met and true if it is met

function checkblank(field)
{
	str_Value=field.value;
	if(str_Value.length==0)
	{
		int_Flag=0;
	}
		
	for(var i=1;i<=str_Value.length ;i++)
	{
		if(str_Value.charAt(i-1) == " ")
		{
			int_Flag=0;
		}
		else
		{
			int_Flag = 1;
			break;
		}
	}
	if(int_Flag != 1)
	{
		field.value = "";
		return false;
	}
	
	return true;			
}


function checkblank_File(field)
{
	str_Value=field.value;
	if(str_Value.length==0)
	{
		int_Flag=0;
	}
	//alert("+"+int_Flag+"+");		
	for(var i=1;i<=str_Value.length ;i++)
	{
		if(str_Value.charAt(i-1) == " ")
		{
			int_Flag=0;
		}
		else
		{
			int_Flag = 1;
			break;
		}
	}
	if(int_Flag != 1)
	{
		//field.value = "";
		return false;
	}
	
	return true;			
}

//validation for space
function checkspace(field)
{
        s_val = field.value;
        for(count = 0; count < s_val.length; count++)
        {
                if(s_val.charAt(count) == ' ')
                {
                        //alert("Space not allowed!");
                        //alert(sSpaceNotAllowed);
                        return false;
                }
        }
        return true;
}


//Validation for port number before & after comma
function checkcomma(field,sCommaNotAllowed)
{
	s_val = field.value;
	len = s_val.length;
        if(s_val.indexOf(",") > -1)
        {
                if(s_val.charAt(0) == ',' || s_val.charAt(len-1) == ',')
                {
                        //alert("Please enter a port number");
                          alert(sCommaNotAllowed);
                        return false;
                }
        }
	return true;
}


//Prevents any other characters except numbers being entered - Works only with IE
//call the function on onkeypress of the textfield
function numKeyPress()
{
		if(event.keyCode >= 48 && event.keyCode <= 57)
		{
			return true;	
		}
		else return false;
}

//Checks for a valid number
//Pass the type,field name 
//if type = "+" it will validate for +ve numbers any other type will validate for all numbers
//returns false if the conditions are not met and true if it is met

function checknumber(type,field)
{
	object_value = field.value;
	var start_format = "";
        
    //Returns true if value is a number defined as  having an optional leading + or -.
    //   having at most 1 decimal point. otherwise containing only the characters 0-9.
	if (type == "+")
	{
		start_format = ".+0123456789";
	}
	else
	{
		start_format = ".+-0123456789";
	}
	var number_format = ".0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;

    //The first character can be + - .  blank or a digit.
	check_char = start_format.indexOf(object_value.charAt(0))
    
    //Was it a decimal?
	if (check_char == 1)
	    decimal = true;
	else if (check_char < 1)
		return false;
        
	//Remaining characters can be only . or a digit, but only one decimal.
	
	for (var i = 1; i < object_value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0)
			return false;
		else if (check_char == 1)
		{
			if (decimal)		// Second decimal.
				return false;
			/*else
			{
				decimal = true;
			}*/
		}
		else if (check_char == 0)
		{
			if (decimal || digits)	
				trailing_blank = true;
    
        // ignore leading blanks

		}
	        else if (trailing_blank)
			return false;
		else
			{
				digits = true;
			}
	}	
    //All tests passed, so...
	return true;
}


//checks for decimal point
function checkfordecimal(field)
{
	var num = field.value;
	if(num.indexOf(".") > -1)
	{
			//alert("Only whole numbers are allowed!");
			return false;
	}
	return true;
}

//Checks for special characters
//Pass the form field and a list of special characters you want to check against
//returns false if the conditions are not met and true if it is met

function checkspecial(field,s_spl)
{
	obj_val = field.value;
	for(var i=0; i<obj_val.length; i++)
	{
		check_char = s_spl.indexOf(obj_val.charAt(i))
		//Returns value 1 if the special character listed in splChar is found
		if(check_char >= 0)
		{
			return false;
		}
	}

	return true;
}

//checks for two characters after the period in decimal numbers
function check_decimal(field)
{
	num = field.value;
	numvals = num.split(".");
	if(!numvals[1])
	{
		return true;
	}
	if(numvals[1].length > 2 )
	{
		alert("More than two characters are not allowed after the period")
		return false;
	}
	return true;
}	

//Checks for numbers in the beginning of mailid
//Checks for @ and . in mailid
//Checks if the consecutive characters are @.
//Checks for more than one @
function checkmailid(field,s_spl)
{
	/*obj_val = field.value;
	num = 0;
	var flag;
	if(obj_val.charAt(0).indexOf("0") > -1 
	|| obj_val.charAt(0).indexOf("1") > -1 
	|| obj_val.charAt(0).indexOf("2") > -1 
	|| obj_val.charAt(0).indexOf("3") > -1 
	|| obj_val.charAt(0).indexOf("4") > -1 
	|| obj_val.charAt(0).indexOf("5") > -1 
	|| obj_val.charAt(0).indexOf("6") > -1 
	|| obj_val.charAt(0).indexOf("7") > -1 
	|| obj_val.charAt(0).indexOf("8") > -1 
	|| obj_val.charAt(0).indexOf("9") > -1)
	{
			flag = true;
	}
	for(var i=0; i<s_spl.length; i++)
	{
			check_char = obj_val.indexOf(s_spl.charAt(i))
			if(check_char < 1)
			{
					flag = true;
			}
	}
	if(obj_val.charAt(check_char) == '.' && obj_val.charAt(--check_char) == '@')
	{
			flag = true;
	}
	for(c=0; c < obj_val.length; c++)
	{
			if(obj_val.charAt(c) == '@')
			{
					num++;
			}
	}
	if(num > 1)
	{
			flag = true;
	}
	if(flag == true)
	{
			//alert("Mail id is invalid");
			return false;
	}
	return true;*/

	emailStr = field.value;
		
	/*if (emailStr.indexOf("_") == 0 || emailStr.indexOf("-") == 0)
		return false;*/

	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
		//alert("Email address seems incorrect (check @ and .'s)")
		return false;
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    //alert("The username doesn't seem to be valid.")
	    return false;
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        //alert("Destination IP address is invalid!")
				return false;
		    }
	    }
	    return true;
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.");
	    return false;
	}

	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	 
	//Amer Asked for change the domain to accept the domains as  .travel, .atom etc...
	
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	 
	/*if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   //alert("The address must end in a three-letter domain, or two letter country.");
	   return false;
	}*/

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This address is missing a hostname!"
	   //alert(errStr)
	   return false;
	}

	// If we've gotten this far, everything's valid!
	return true;


}

//validation for URL
function checkurl(field)
{
	var strValue = field.value;
	var count;
	var len;
	var slashlast;
	var strBase;
	var s_spl;
	var lStart;
	if(strValue.indexOf(".") == -1)
	{
			return false;
	}
	if(strValue.indexOf("..") != -1)
	{
			return false;
	}	
	if(strValue.indexOf(" .") != -1)
	{
			return false;
	}	
	else
	{
		count = strValue.lastIndexOf(".");
		len = strValue.length - 1;
		if(count >= len)
		{
				return false;
		}
		slashlast = strValue.lastIndexOf("/");
		if (slashlast == -1)
			slashlast = strValue.length;
		strBase = strValue.substring(0, slashlast);
		
		if (strBase.indexOf(":") >= 0)
		{
			if (strBase.substring(0, 7) != "http://" && strBase.substring(0, 8) != "https://")
				return false;
		}
		
		s_spl =  " `~!@#$%^&*()+={}[]|\\;\"\'<>,?";
		for(var i=0; i<strBase.length; i++)
		{
			check_char = s_spl.indexOf(strBase.charAt(i))
			//Returns value 1 if the special character listed in splChar is found
			if(check_char >= 0)
			{
				return false;
			}
		}
		
		lStart = strValue.indexOf("http://");
		if (lStart !=0)
			lStart = strValue.indexOf("https://");

		strValue = strValue.substr(lStart+1, 1);	/*next letter to http:// must be character or digit*/
		s_spl =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
			
		if (s_spl.indexOf(strValue) == -1)
			return false;
		
		return true;
		
	}
}


/*function checkurl(field)
{
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	//var regexp = /(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(field.value);
}
*/
function isValidDate(dateStr) {
	// Checks for the following valid date formats:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	// Also separates date into month, day, and year variables

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

	// To require a 4 digit year entry, use this line instead:
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		//alert("Date is not in a valid format.");
		return 1;
	}
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		//alert("Month must be between 1 and 12.");
		return 2;
	}
	if (day < 1 || day > 31) {
		//alert("Day must be between 1 and 31.");
		return 3;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		//alert("Selected Month doesn't have 31 days!");
		return 4;
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			//alert("Invalid day for the month February.");
			return 5;
		}
	}
	return 0;  // date is valid
}




function jf_Trim(str)/***	PURPOSE: Remove trailing and leading blanks from our string.   IN: str - the string we want to Trim RETVAL: A Trimmed string! ***/
{
	trim_str = jf_RTrim(jf_LTrim(str));return trim_str;
}
function jf_LTrim(str)/*** PURPOSE: Remove leading blanks from our string.IN: str - the string we want to LTrim RETVAL: An LTrimmed string!***/
{
    var whitespace = new String(" \t\n\r");
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(0)) != -1) {// We have a string with leading blank(s)...
        var j=0, i = s.length;
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1) // Iterate from the far left of string until we // don't have any more whitespace...
            j++;
        s = s.substring(j, i);// Get the substring from the first non-whitespace     // character to the end of the string...
    }
    return s;
}
function jf_RTrim(str)/*** PURPOSE: Remove trailing blanks from our string.IN: str - the string we want to RTrim RETVAL: An RTrimmed string! ***/
{
    var whitespace = new String(" \t\n\r");// We don't want to trip JUST spaces, but also tabs, line feeds, etc.  Add anything else you want to "trim" here in Whitespace
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
        var i = s.length - 1;       // Get length of string // We have a string with trailing blank(s)...
        
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)// Iterate from the far right of string until we  don't have any more whitespace...
            i--;
        s = s.substring(0, i+1);// Get the substring from the front of the string to where the last non-whitespace character is...
    }
    return s;
}

function jf_CheckLength(sTxt,iLen,sErrMsg)
{
	
	if(sTxt != "" )
	{
		for (var i=0, count=0; i<sTxt.length; i++, count++)
		{
			if ((sTxt.substr(i, 1) == " ") || (sTxt.substr(i, 1) == "\n") || (sTxt.substr(i, 1) == "\t"))
				count=0;
			if (count > iLen)
			{
				alert(sErrMsg);
				return false;
			}
		}
	}
	return true;
}

function jf_CheckPhoneNo(sData)
{
	var sAllowed = "0123456789-";
	var iPos = sData.indexOf("-");
	if (iPos == 0)
		return false;
	if (sData.indexOf("-", iPos+1) != -1)
		return false;	
	for(var i=0; i < sData.length; i++)
	{
		if(sAllowed.indexOf(sData.charAt(i)) == -1 )
			return false;
	}
	
	return true;
}

//Validates for floating point data's

function is_Number(obj,msg){
	var str = obj.value;
	var iPos;
	var str_length = str.length;
	//alert(str_length)
	var c;
	var  splitvalue,temp;
	splitvalue=str;
	var temp = new Array();
	temp = splitvalue.split(".");
//alert(temp[1].length)
	if((temp.length)>2||temp.length=="0")
	{
		alert(msg)
		obj.select();
		stat=1;
		return false;
	}
	if(temp.length=="0")
	{
		alert(msg)
		obj.select();
		stat=1;
		return false;
	}
	if(temp.length == 2)//only two decimal places allowed
	{
		if(temp[1].length > 2)
		{
			alert(msg)
			obj.select();
			stat=1;
			return false;		
		}
	}
	if(length==1 && str == ".")
	{
		alert(msg)
		obj.select();
		stat=1;
		return false;
	}
	
	var stat=0;
	for(counter=0;counter<length;counter++){
		ascii=str.charCodeAt(counter);
		//alert(ascii)
		if(ascii < 46 || ascii > 58){
			alert(msg)
			obj.select();
			stat=1;
			break;
		}
	}
	return stat?false:true;
}

/*function replaceAll( str, replacements ) {
    for ( k = 0; k < replacements.length; k++ ) {
        var idx = str.indexOf( replacements[k][0] );

        while ( idx > -1 ) {
            str = str.replace( replacements[k][0], replacements[k][1] ); 
            idx = str.indexOf( replacements[k][0] );
        }

    }

    return str;
}
*/

//Check for valid search string
function jf_ChkValidSearchStr(sValue)
{
	var sNotAllowed = " `~!@#$%^&*()_-+={}[]|\\;:\"\'<>,.?\/";//"`~!@#$%^&*()_-+=[{]}\|;:',<.>/?\" ";//
			
	for(var i=0; i<sValue.length; i++)
	{
		//alert("--"+sValue.substr(i, 1)+"--")
		if (sNotAllowed.indexOf(sValue.substr(i, 1)) == -1)
			return true;
	}
	return false;
}

function WholeNumber(sText)

{
   var ValidChars = "12345677890abcdefghijklmnopqrstuvwxyzABCDEFGHIKLMNOPQRSTUVWXYZ-,./ ";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
   
   
   

function checkblank_det(field)
{
	str_Value=field;
	if(str_Value.length==0)
	{
		int_Flag=0;
	}
		
	for(var i=1;i<=str_Value.length ;i++)
	{
		if(str_Value.charAt(i-1) == " ")
		{
			int_Flag=0;
		}
		else
		{
			int_Flag = 1;
			break;
		}
	}
	if(int_Flag != 1)
	{
		field.value = "";
		return false;
	}
	
	return true;			
}
function checkspecial_admin(field,s_spl)
{
	obj_val = field;
	//alert(obj_val)
	for(var i=0; i<obj_val.length; i++)
	{
		check_char = s_spl.indexOf(obj_val.charAt(i))
		//Returns value 1 if the special character listed in splChar is found
		if(check_char >= 0)
		{
			return false;
		}
	}

	return true;
}


function WholeNumber_Admin(sText)

{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }