//checking for a valid image file extensions
function checkFile(field)
{
		var path,extn,dotposn
		path=trimText(field)
		dotposn=path.lastIndexOf(".")
		if (dotposn==-1)
		{
			alert("Invalid file selected for image. Only the following types of files are allowed for images...\n*.gif, *.jpg, *.jpeg,*.tif,*.tiff,*.bmp,*.ico")
 			return false
		}
		else 
		{
			extn=path.substring(dotposn,path.length).toLowerCase()
			if (!(extn==".jpg" || extn==".jpeg" || extn==".gif" || extn==".ico" || extn==".tif" || extn==".tiff" || extn==".bmp" || extn==".png"))
			{
				alert("Invalid file selected for image. Only the following types of files are allowed for images...\n*.gif, *.jpg, *.jpeg,*.tif,*.tiff,*.bmp,*.ico,*.png")
				return false
			}
		}
		return true
}

//checking for a valid Email 
/*function checkEmail(fldName) 
{
      
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(fldName.value)){
		return (true);
		}
		else {
		return (true);
	}
}
*/

function checkEmail(strField,strFieldValue)
{
var emailStr = strFieldValue
/* 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. */
	strField.focus()
	strField.select()
	alert("Email address is 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
    strField.focus()
    strField.select()
    alert("The username is invalid. Please verify")
    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)
    {
		strField.focus()
		strField.select()
		alert("Destination IP address is invalid!")
		return false
	}
   }
   return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null)
{
	strField.focus()
	strField.select()
	alert("The domain name is invalid. Please verify")
    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. */
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.
   strField.focus()
   strField.select()
   alert("The Email 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 Email address is missing a hostname!"
   strField.focus()
   strField.select()
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}


//checking for a valid URL 
function checkURL(theField,strURL)
{
	if( strURL != '')
	{
		var i,len,f,test;
		len=strURL.length;
		f=false;
		var st=strURL.substring((len-4),(len));
		var l=strURL.substring((len-3),(len-2));	
		var last=strURL.substring((len-6),(len-5));
		//if( ((strURL.substring(0,7)=="http://")||(strURL.substring(0,4)=="www.")) &&((st==".com/") ||(st==".com")||(st==".net")||(st==".org")||(st==".mil")||(st==".edu")||(st==".fru")) )
		if((strURL.substring(0,7) != "http://")||(strURL.substring(0,4) != "www."))
		{
			theField.focus();
			alert("Invalid URL. Please re-enter.")
			return false;
		}
		if((strURL.substring(0,7)=="http://")||(strURL.substring(0,4)=="www."))
		{
			if((strURL.substring(0,7)=="http://")&&((strURL.substring(7,9)!="ww")||(strURL.substring(7,11)!="wwww")))
			{
					return true;
			}
			else if(strURL.substring(0,4)=="www.")
				return true;
			else
				{theField.focus();
				alert("Invalid URL. Please re-enter.")
				return false;}
		}
		else if(((strURL.substring(0,7)=="http://")||(strURL.substring(0,4)=="www."))&&((l==".")&&(last==".")))
		{
		return true;
		}
		else
		{theField.focus();
		alert("Invalid URL. Please re-enter.")
		return false;}
	}
	else
		return true;
}
//Trimming a String
function  trimText(fldName)
{
	var name=fldName.value;
	while(name.charAt(0)==' ')
	{
		name=name.substring(1,name.length);
	}
	while(name.charAt((name.length)-1)==' ')
		name=name.substring(0,(name.length)-1);
	return name;
}

// Check whether string  is empty.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}


//used in the function that checks for a Valid Zip Code
function isZIPCode (s)
{  if (isEmpty(s)) 
       if (isZIPCode.arguments.length == 1) return false;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) && 
            ((s.length == 5) ||
             (s.length == 9)))
}

//checking for a valid ZIP Code
function checkZIPCode (fldName)
{   
     var normalizedZIP = putChars(fldName.value, "-")
      if (!isZIPCode(normalizedZIP, false)) 
         return false//showAlert (fldName, "ZIP field must be a 5 or 9 digit code (like 94043). Please reenter it now.");
      else 
      {  
         fldName.value = reformatZIPCode(normalizedZIP)
         return true;
      }
    
}

//Reformats the ZIP Code as a String
function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}

//puts the specified characters(second argument) into the String 
function putChars (s, chars)

{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (chars.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//shows alert messages and puts the focus in the form element 
function showAlert(fldName, s)
{   
	alert(s)
	fldName.focus()
    fldName.select()
    return false
}

//checking for a Valid Phone Number
function checkPhone (fldName)
{   
      var normalizedPhone = putChars(fldName.value, "()- ")
       if (!isPhoneNumber(normalizedPhone, false)) 
          return false//showAlert (fldName, "Phone field must be a 10 digit number (like 4155551212). Please reenter it now.");
       else 
       {  
          fldName.value = reformatPhoneNumber(normalizedPhone)
          return true;
       }
    
}

//Used in the function that checks for a valid Phone number
function isPhoneNumber (s)
{   
    return (isInteger(s) && s.length == 10)
}


//Reformats the Phone Number as a String
function reformatPhoneNumber (PhoneNo)
{   return (reformat (PhoneNo, "(", 3, ") ", 3, "-", 4))
}


//Checking for a valid number
function isInteger (s)

{   
	var i;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    return true;
}

//Checking for a valid Digit
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}


//Reformats a String into a specific Format
function reformat (s)
{   
	var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

//Checking for a Valid Time Format
function checkTime(fldName)
{
	var strHours=fldName.value;
	len=strHours.length;
	as=1;
	if(strHours=="" || len>=6)
	{
		//alert(" Please enter Hour(s) After in format HH:MM")
		return false;
	}
	else
	{
		if(len<=4)
		{
			as=checkHours(strHours);
			if(as==2)
			{
				return true;
			}
			else
			{
				//alert(" Please enter Hour(s) After in format HH:MM")
				return false;
			}
		}
		if(len==5)
		{
			as=checkMinutes(strHours);
			if(as==2)
			{
				return true;
			}
			else
			{
				//alert(" Please enter Hour(s) After in format HH:MM")
				return false;
			}

		}

	}

}

//Used in the function that checks for a valid time
function checkHours(str)
{
	str1=str;valid=1;
	for(i=1;i<=9;i++)
	{  
		for(j=0;j<=5;j++)
		{ 
			for(k=0;k<=9;k++)
			{ 
				str2=""+i+":"+j+k;
		        if(str1==str2)
				{ 
					valid=2;
				}
			}
		 }
	}
	if(valid==2) 
	{
		return 2;
	}
	else
	{
		return 1;
	}
}	

//Used in the function that checks for a valid time
function checkMinutes(str)
{
	str1=str
	valid=1; 
 	for(l=0;l<=2;l++)
	{
		if(l==2) 
			ii=3;
		else
			ii=9;
		for(i=0;i<=ii;i++)
		{ 
			for(j=0;j<=5;j++)
			{
				 for(k=0;k<=9;k++)
		   		 {
					str2=""+l+i+":"+j+k;
 			        if(str1==str2)
					{ 
						valid=2;
					}
				 }
			 }
		}
	}

	if(valid==2) 
	{
		return 2;
	}
	else
	{
		return 1;
	}

} 

//checking for a Valid character String
function isValidCharsString(theField,strval)
{

		  validCharsString=/^[a-zA-Z0-9._\- ]+$/;
		  if (validCharsString.test(strval)==false )
		  {
			alert("You can enter only alphanumeric charcters,Dot(.),Hyphen(-) and space characters in this field ")
			theField.focus();
			theField.select();
			return false;
		  }
		  else
			return true
		
}

//checking for a Valid Password String
 function isValidPwdCharsString(theField,strval)
{

		  validCharsString=/^[a-zA-Z0-9_]+$/;
		  if (validCharsString.test(strval)==false )
		  {
			theField.focus();
			theField.select();
			return false;
		  }
		  else
			return true
		
}




//checking for a Valid Date
function isDate(dateStr,strField) 
{
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    
    if (matchArray == null) {
        alert("Please select valid date for "+strField);
        return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { 
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	 alert("Month "+month+" doesn't have 31 days For " + strField)
        return false;
    }

    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("February " + year + " doesn't have " + day + " days for " + strField);
            return false;
        }
    }
    return true; 
}

//Checking whether the selected date in greater than present date or not
function checkDate(month,date,year)
{

/*month = document.forms[0].month.options[document.forms[0].month.selectedIndex].value;
date=document.forms[0].date.options[document.forms[0].date.selectedIndex].value;
year=document.forms[0].year.options[document.forms[0].year.selectedIndex].value;*/

var workorderdate = new Date();

workorderdate.setMonth(month-1);
workorderdate.setDate(date);
workorderdate.setYear(year);

var currentdate=new Date();

if(workorderdate<currentdate)
	return false;
else
	return true;
}
//####
//Used to delete functionality in the forms
function Delete(strConfirmationMessage,strUncheckedMessage)
{
	if(SelectAtleastOne())
	{
		var blnDelConfirm = confirm(strConfirmationMessage);

		if (blnDelConfirm == true)
			{
				document.forms[0].hdnFormAction.value = "Delete";
				document.forms[0].submit();
			}
	}

	else
	{
		alert(strUncheckedMessage);
	}
}

function SelectAtleastOne()
{
	var selCount=0;

	for(i=0; i<document.forms[0].elements.length; i++) 
	{
		if (document.forms[0].elements[i].name=="chkUser")
		{
		if (document.forms[0].elements[i].checked == true)
		{
		selCount++;
		}
		}
	}
	if(selCount==0)
		return false;
	else
		return true;
}
// checking for a number is float or not
function isFloat(val)
{
     var template = "x.ff";
     nval = val/1;
     if(isNaN(nval)) return false;
     // we are sure that we have a numeric value, let's see if we can find a . somewhere
     if((pos=val.indexOf("."))>0)
     {
          templatepos = template.indexOf(".");
          tmpf = template.length-templatepos-1;
          valf = val.length-pos-1;
          if(valf>tmpf) return false;
          else return true;
     }
     return true;
}



 
