/*
'-----------------------------------------------------------------------------------------------
'-----------------------------------------------------------------------------------------------
'	Module Description
'	------------------
'
'	This module contains all the javascript functions used for validations
'
'   Revision History
'   ----------------
'   Module				Validations.js
'   Author              Sanjeeva Reddy C.
'   Modified By         Sanjeeva Reddy C.   

*/
//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 image file extensions
function checkSupportFile(field)
{
		var path,extn,dotposn
		path=trimText(field)
		dotposn=path.lastIndexOf(".")
		if (dotposn==-1)
		{
			alert("Invalid file selected for support files upload. Only the following types of files are allowed ...\n*.pdf, *.xls, *.txt, *.doc, *.rtf")
			return false
		}
		else 
		{
			extn=path.substring(dotposn,path.length).toLowerCase()
			if (!(extn==".pdf" || extn==".xls" || extn==".txt" || extn==".doc" || extn==".rtf"))
			{
				alert("Invalid file selected for support files upload. Only the following types of files are allowed ...\n*.pdf, *.xls, *.txt, *.doc, *.rtf")
				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 (false);
	}
}
*/

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;
}


//Working but takes lot of time!
function checkEmail(field,msgx){
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(field.value)) return true;
	//alert(msgx);
	field.focus();
	field.select();
	return false;
}



//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));
		alert (st )
		//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 
          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 )
		  {
			theField.focus();
			theField.select();
			return false;
		  }
		  else
			return true
		
}

//checking for a Valid character String
function isValidURL(theField,strval)
{
		 validCharsString=/^[a-zA-Z0-9.]+$/;
		  if (validCharsString.test(strval)==false )
		  {
			alert("Please enter valid URL")
			theField.focus();
			theField.select();
			return false;
		  }
	      else{
			return true	
		  }
		/*var chk
		 for (i = 0; i < strval.length; i++)
		 {   
			var c = strval.charAt(i);
			alert(c)
			if (c.match("."))
			{
				chk = true
				break;
			}
			else
			{
				chk=false
			}
		}
		if chk=true
			return true	
		else	
			return false*/
}

//checking for a Valid character String
function isValidNameString(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 jobs applied for String (Employment Application)
function isValidPositionsString(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 number
function isNumber(numVal)
{
	
		if (isNAN(numVal)==false)
		{
			theField.focus();
			theField.select();
			return false;
		}
		else
			return true
		
}
//checking for a Valid jobs applied for String (Employment Application)
function isValidStateString(theField,strval)
{
		  if (strval.length<2)
		  {
			  return false
		  }
		  validCharsString=/^[a-zA-Z]+$/;
		  if (validCharsString.test(strval)==false )
		  {
			theField.focus();
			theField.select();
			return false;
		  }
		  else
			return true
}
//checking for a Valid wages expected per String (Employment Application)
function isValidWageString(theField,strval)
{
		  validCharsString=/^[a-zA-Z]+$/;
		  if (validCharsString.test(strval)==false )
		  {
			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
		
}

function isValidtoolURLString(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,strFieldName) 
{
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    
    if (matchArray == null) {
        showAlert(strField,"Please enter date in mm/dd/yyyy format.")
		return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { 
        showAlert(strField,"Month must be between 1 and 12 for " + strFieldName);
        return false;
    }

    if (day < 1 || day > 31) {
        showAlert(strField,"Day must be between 1 and 31 for " + strFieldName);
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	 showAlert(strField,"Month "+month+" doesn't have 31 days for " + strFieldName)
        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)) {
            showAlert(strField,"February " + year + " doesn't have " + day + " days for " + strFieldName);
            return false;
        }
    }
	year = parseInt(year)
	//alert(year.length)
	if(year < 1000 )
	{
	   showAlert(strField,"Please enter a valid Year (Year should be in yyyy format)")
        return false;
	}

	if(year < 1900 )
	{
	   showAlert(strField,"Please enter a valid Year (Year should be greater or above 1900)")
        return false;
	}
	//if(year )


    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;
}

function compareDates(dtStr1,dtStr2)
{
	
	var dt1 = new Date(dtStr1);
	var dt2 = new Date(dtStr2);
	var currDate  = new Date();
	dt1.setHours(currDate.getHours());
	dt1.setMinutes(currDate.getMinutes());
	dt1.setSeconds(currDate.getSeconds());
	dt1.setMilliseconds(currDate.getMilliseconds());
	
	
	dt2.setHours(currDate.getHours());
	dt2.setMinutes(currDate.getMinutes());
	dt2.setSeconds(currDate.getSeconds());
	
	dt2.setMilliseconds(currDate.getMilliseconds());
	
	
	
	if (dt1.toString() > dt2.toString())
	{
		return false;
	}
	else
	{
		return true;
	}
	
	
}
function checkCurrentDate(dateStr)
{
	var givenDate = new Date(dateStr);
	var currDate  = new Date();
	givenDate.setHours(currDate.getHours());
	givenDate.setMinutes(currDate.getMinutes());
	givenDate.setSeconds(currDate.getSeconds());
	givenDate.setMilliseconds(currDate.getMilliseconds());
	
	
	if(givenDate < currDate)
	{
		return false;
	}
	return true;

}
function fnChkRad(theRad1,theRad2,theRad3,theRad4,intQno)
{
	var blnFlg = true;
	var blnchk = true;
	var arr = new Array(4)
	for(j=0;j<4;j++)
	{
		
		for(i=0;i<4;i++)
		{
			
			if(j==0)
				blnchk = theRad1[i].checked
			else if(j==1)
				blnchk = theRad2[i].checked
			else if(j==2)
				blnchk = theRad3[i].checked
			else if(j==3)
				blnchk = theRad4[i].checked
			
			if(blnchk)
			{
				if(j==0)
					arr[j] = theRad1[i].value
				else if(j==1)
					arr[j] = theRad2[i].value
				else if(j==2)
					arr[j] = theRad3[i].value
				else if(j==3)
					arr[j] = theRad4[i].value
				blnFlg = false
			}
		}
		if(blnFlg)
		{
			alert("An option in Question " + intQno +" is not answered. Please answer it.")	
			showFocus(theRad1[0])
			return false;
		}
		
		blnFlg = true	
	}
	for(l=0;l<4;l++)
	{
		for(b=l+1;b<4;b++)
		{
			if(arr[l] == arr[b])
			{
				alert("The answers are not unique for the Question " + intQno + ".")
				showFocus(theRad1[0])
				return false;
			}
									
		}
	}	
	return true;

}

function SelectedChkBoxValues(frm,chkBoxName)
{
	var ids=""
	for (var i=0;i<frm.elements.length;i++)
		if (frm.elements[i].name == chkBoxName)
			if (frm.elements[i].checked == true)
				ids=ids + frm.elements[i].value + ","
	return ids;
}		
//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;
}
		
