
//<form name='frm' method='post' action='' 
//onSubmit='return theValidatorNew(this,"Input1,Input3,temp,ta,rad","Name,Zip Code,Template,Comments,University/Non-University",",Y,,,",",,,,",",,,,");'>


function theValidatorNew(theForm,theControl,theMessage,theKind,theLenght)
{
	var theControls = new Array();
	var theMessages = new Array();
	var theKinds = new Array();
	var theLenghts = new Array();
	theControls=theControl.split(",");
	theMessages=theMessage.split(",");
	theKinds=theKind.split(",");
	theLenghts=theLenght.split(",");
	//alert(theLenghts);
	for (var i=0; i < theForm.elements.length; i++){
	//alert("Type: " + theForm.elements[i].type);
		for(var counter=0;counter < theControls.length; counter++)
		{
			if (theForm.elements[i].name == theControls[counter])
			{
				if (theForm.elements[i].type == 'file')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '')
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;	
					}
				}
				
				 if(theForm.elements[i].type == 'radio' && !requireRadio(theForm[theForm.elements[i].name]))
   				 {  alert(status); 
				 	theForm.elements[i].focus(); 
					return false; }
				
				if (theForm.elements[i].type == 'text')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '')
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;	
					}
					// lenght value check
					//alert(theLenghts[counter]);
					//alert(theForm.elements[i].value.length);
					if(theLenghts[counter] != '' )
					{
						formvalue = trim(theForm.elements[i].value);
						//alert(formvalue.length);
						if(formvalue.length < theLenghts[counter])
						{
							alert(theMessages[counter] + " should be " + theLenghts[counter] + " char length" );
							theForm.elements[i].focus();
							return false;	
						}
					}
					
					// Kind validation
					// N - numeric
					if (trim(theForm.elements[i].value) != '' && theKinds[counter] == "N")
					{
						if(isNaN(trim(theForm.elements[i].value)))
						{
							alert(theMessages[counter] + " should be numeric.");
							theForm.elements[i].focus();
							return false;	
						}
						if(trim(theForm.elements[i].value)<= 0 )
						{
							alert(theMessages[counter] + " should be greater than 0");
							theForm.elements[i].focus();
							return false;	
						}
				
					}
					// E -  Email
					if (trim(theForm.elements[i].value) != '' && theKinds[counter] == "E")
					{
						//if(!emailcheck(theForm.elements[i],"Please enter a valid email address."))  return false;
						if(!echeck(trim(theForm.elements[i].value)))
						{
							alert("Please enter a valid email address.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Username
					if (trim(theForm.elements[i].value) != '' && theKinds[counter] == "U")
					{
						usernamevalue = trim(theForm.elements[i].value);
						//alert(usernamevalue.length);
						if(usernamevalue.length < 4)
						{
							alert("Username can not be shorter then 4 chars.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// U - URL
					if (trim(theForm.elements[i].value) != '' && theKinds[counter] == "Y")
					{
						if(!validateURL(trim(theForm.elements[i].value)))
						{
							alert(" Invalid URL \n Should be http://www.domain.com");
							theForm.elements[i].focus();
							return false;	
						}
					}
					// D - validateUSDate( strValue )
					if (trim(theForm.elements[i].value) != '' && theKinds[counter] == "D")
					{
						if(!validateUSDate(trim(theForm.elements[i].value)))
						{
							alert("Invalid date format");
							theForm.elements[i].focus();
							return false;
						}
					}
				}
				// Password Validation
				if (theForm.elements[i].type == 'password')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '')
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;	
					}
				}	

				// Confirm Password Validation
				//alert(theForm.elements[i].type);
				//alert(theConfirmPassword[counter]);
				if (theForm.elements[i].type=='password' &&  theKinds[counter] == "P")
				{
					if (theForm.elements[i].value!=theForm.elements[i-1].value)
					{
						alert(theMessages[counter] + " is not same.");
						theForm.elements[i].focus();
						return false;	
					}
				}	
				
			
			//Select box validation
				if (theForm.elements[i].type == "select-one")
				{
					var selIndex,selValue;
					selIndex=theForm.elements[i].selectedIndex;
					var theObject=theForm.elements[i];
					selValue = theObject[selIndex].value;
					//if( trim(selValue) == "" || trim(selValue) == "0")
					if( trim(selValue) == "")
					{
						alert("You must select " + theMessages[counter] + ".");
						theForm.elements[i].focus();
						return false;	
					}
				}

			// Text Area Validation

				if (theForm.elements[i].type == "textarea")
				{
					var txtAreaValue;
					txtAreaValue=theForm.elements[i].value;
					if( trim(txtAreaValue) == "")
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;	
					}
				}
	
			}

		}
	}
	
	return true;
}

function requireRadio(radios)
{ // require at least one radio in this group to be checked
  if(!radios.length) return true; // invalid parameter
  var visible= false, enabled= false;
  for(var i= 0; i < radios.length; i++)
  {
    if(!enabled) enabled= !radios[i].disabled;
    if(radios[i].checked) return true;
    else if(radios[i].offsetWidth == undefined || radios[i].offsetWidth > 0) visible= true;
  }
  if(!visible||!enabled) return true; // no visible/enabled options in this group
  status= 'You must select one of the '+radios[0].name+' options.';
  return false;
}

function getRadioButtonValue(theForm,theControl)
{
	var i;
	alert("Hello " + theForm + " control.length: " + theControl.length);
	for( i=0; i< theControl.length; ++i)
	{
alert(theForm[i].checked);
		if( theControl[i].checked)
		{
		
			return theControl[i].value;
		}
	}

	// default (non selected)
	return -1;
}

function ltrim ( s )
{
	return s.replace( /^\s*/, "" )
}

function rtrim ( s )
{
	return s.replace( /\s*$/, "" );
}

function trim ( s )
{
	return rtrim(ltrim(s));
}

function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

 		 return true					
	}



function emailcheck(object,str)
{
var email=object.value;
var matcharray=email.match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) 
	if(matcharray==null){
	alert(str)
	 	object.focus();
		object.select();
	return false;
	}
	else return true
}	

function validateEmail(email){
	
	// This function is used to validate a given e-mail 
	// address for the proper syntax
	
	if (email == ""){
		return false;
	}
	badStuff = ";:/,' \"\\";
	for (i=0; i<badStuff.length; i++){
		badCheck = badStuff.charAt(i)
		if (email.indexOf(badCheck,0) != -1){
			return false;
		}
	}
	posOfAtSign = email.indexOf("@",1)
	if (posOfAtSign == -1){
		return false;
	}
	if (email.indexOf("@",posOfAtSign+1) != -1){
		return false;
	}
	posOfPeriod = email.indexOf(".", posOfAtSign)
	if (posOfPeriod == -1){
		return false;
	}
	if (posOfPeriod+2 > email.length){
		return false;
	}
	return true
}

function validateURL(url){
	
	// This function is used to validate a given 
	// address for the proper syntax
	url="http://"+url;
	var re;
	re = new RegExp("(http|ftp|https)://[-A-Za-z0-9._/]+");
	if (re.test(url)==false)
		return false;

	posOfAtSign = url.indexOf(".")

	if (posOfAtSign == -1){
		return false;
	}
	return true;
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function confirmdelete(theform,startElement,endElement)
{
	var flag=0;
	for(i=startElement;i<theform.length-endElement;i=i+1)		  //confirmation message for delete
	{
		if(theform.elements[i].checked==true)
		{
			 flag=1;
			 if (confirm("Are you sure you want remove this record?"))
				return true;
			else
				return false;
		}
	}
	if(flag==0)
	{
		alert("Please select the checkbox before pressing the delete button");
		return false;
	}
}

 function confirmCatDelete(theform)	//orderdetail.php
 {
 	
	 if (confirm("Are you sure you want remove this record?"))
		{
			formName=eval("document."+theform)
			formName.flag.value=1;
			formName.submit();
		}		
}
 
 
 function checkdate(theform,dd,mm,yy,dd1,mm1,yy1)
 {

   day1=theform.dd.options[theform.dd.selectedIndex].value;
   mon1=theform.mm.options[theform.mm.selectedIndex].value;
   year1=theform.yy.options[theform.yy.selectedIndex].value;
   day2=theform.dd1.options[theform.dd1.selectedIndex].value;
   mon2=theform.mm1.options[theform.mm1.selectedIndex].value;
   year2=theform.yy1.options[theform.yy1.selectedIndex].value;
	
	var fromdate = new Date(year1,mon1,day1);
	var todate=new Date(year2,mon2,day2);
	
	if(fromdate >todate)
	 {
		alert("from date should be less than to date");
		return false;
	 }
	 return true;
 }

function validate (field, maxlen)
{	
	
	if (field.value.length > maxlen)
	{
		alert ("Field length exceeded.\nAllowed: "+maxlen+" characters,\nEntered: "+field.value.length+" characters.");
		field.focus();
		return  false;
	}
	return true;
}
function fileextension(object,str)
{
	var s=object.value;
	if (s!="")
	{
		array=s.split("\\");
		len=array.length;
		filename=array[len-1];
		array1=filename.split(".");
		tempimage=array1[1];
		if(tempimage!="jpg" && tempimage!="jpeg" && tempimage!="gif" && tempimage!="GIF" && tempimage!="JPG" && tempimage!="JPEG")
		{
			alert(str);
			object.focus();
			return false;
		}
	}
	
	return true;
}

function checkphone(x)
{
 var regexp=/^(\d{3}-\d{3}-\d{4}|\d{10}|\(\d{3}\)\d{3}-\d{4}|\d{6}|\d{7}|\d{8})$/;
// var regexp=/^(\d{3}-\d{3}-\d{4}|\d{10}|\(\d{3}\)\d{3}-\d{4})$/;
 return regexp.test(x);
 }

var msg = "";
 msg = "Please Enter the Correct Phone Number";
 msg = msg +  "\n The correct forms are : ";
 msg = msg + "\n xxx-xxx-xxxx";
 msg = msg + "\n (xxx)xxx-xxxx";
 msg = msg + "\n xxxxxxxxxx (10 digited Mobile no)";
 msg = msg + "\n xxxxxx (6 digits no)";
 msg = msg + "\n xxxxxxx (7 digits no)";
 msg = msg + "\n xxxxxxxx (8 digits no)";

 
 /*******************************************************************************

  VALIDATION FUNCTIONS:
  
  validateEmail - checks format of email address
  validateUSPhone - checks format of US phone number
  validateNumeric - checks for valid numeric value
  validateInteger - checks for valid integer value
  validateNotEmpty - checks for blank form field
  validateUSZip - checks for valid US zip code
  validateUSDate - checks for valid date in US format
  validateValue - checks a string against supplied pattern
  
  FORMAT FUNCTIONS:
  
  rightTrim - removes trailing spaces from a string
  leftTrim - removes leading spaces from a string
  trimAll - removes leading and trailing spaces from a string
  removeCurrency - removes currency formatting characters (), $ 
  addCurrency - inserts currency formatting characters
  removeCommas - removes comma separators from a number
  addCommas - adds comma separators to a number
  removeCharacters - removes characters from a string that match passed pattern

*******************************************************************************/

function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid email pattern. 
  
 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
   
REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp  = /(^[a-z0-9]([a-z0-9_\.]*)@([a-z0-9_\.]*)([.][a-z0-9]{3})$)|(^[a-z0-9]([a-z0-9_\.]*)@([a-z0-9_\.]*)(\.[a-z0-9]{3})(\.[a-z0-9]{2})*$)/i;
 
  //check for valid email
  return objRegExp.test(strValue);
}

function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern. 
  Ex. (999) 999-9999 or (999)999-9999
  
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
 
  //check for valid us phone with or without space between 
  //area code
  return objRegExp.test(strValue); 
}

function  validateNumeric( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; 
 
  //check for numeric characters 
  return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid integer number.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;
 
  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }  
   return false;
}

function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.

*************************************************/
var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
 
  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid dates with 2 digit month, 2 digit day, 
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and 
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
   
REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
  {
    return false; //doesn't match pattern, bad date
  }
  else{
    var strSeparator = strValue.substring(2,3) //find date separator
    var arrayDate = strValue.split(strSeparator); //split date into month, day, year
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
    var intDay = parseInt(arrayDate[1], 10);

    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }

    //check for February
    var intYear = parseInt(arrayDate[2]);
    var intMonth = parseInt(arrayDate[0]);
     if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
       return true; //Feb. had valid number of days
  }

  return false; //any other values, bad date
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.
    
PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.
      
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);
 
 //check if string matches pattern
 return objRegExp.test(strValue);
}


function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed.  
      
RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}

function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed
   
RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/ 
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }
    
   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from 
  source string.
  
PARAMETERS: 
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';
 
  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }
  
  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS: 
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid 
  numeric value in the rounded to 2 decimal 
  places.  If not, returns original value.
*************************************************/
  var objRegExp = /-?[0-9]+\.[0-9]{2}$/;
   
    if( objRegExp.test(strValue)) {
      objRegExp.compile('^-');
      strValue = addCommas(strValue);
      if (objRegExp.test(strValue)){
        strValue = '(' + strValue.replace(objRegExp,'') + ')';
      }
      return '$' + strValue;
    }
    else
      return strValue;
}

function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS: 
  strValue - Source string from which commas will 
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally
 
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS: 
  strValue - source string containing commas.
  
RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is 
  returned.
  
REMARKS: Used with integers or numbers with
  2 or less decimal places.
*************************************************/
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})'); 

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match, 
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS: 
  strValue - source string containing number.
  
RETURNS: String modified with characters
  matching search pattern removed
  
USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd', 
                                '\s*')
*************************************************/
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );
 
 //replace passed pattern matches with blanks
  return strValue.replace(objRegExp,'');
}

 


