
////////////*********************************************************************************//////////
///// Script         : Indus Form Validation Library      ///////////////////////
///// Developed By   : Trilochan Nayak                   ///////////////////////
///////////////////////
////////////////////////////////////////////////////////////////////////
///*******Read the java script tutorial at http://www.netspade.com/articles/javascript   *****////////


///////////////////////////////////////////////////////////////////////////////////////////////
//// If you make the below var 1 than it will show data flow, it works perfectly as a debuger
var debug=0;
var max_error=20;
///////////////////////////////////////////////////////////////////////////////////////////////


var show_error=new Array();
var i,z,err,pat,er;
var error=0;
var send='';
var field_val,form_name;
var back_m=0;
var hi=new Array();
var temp_hi=new Array();
var tfname;
var tkname=new Array();
var process=1;

////////////////////////////////////////////////////////////
/// These are updated features to help avoid writing ///////
/// of initial lines now just make a call to these   ///////
/// functions instead.........                       ///////
////////////////////////////////////////////////////////////
														 ///
function start(obj)										 ///
{														 ///
show_error[0]='Please make note of following things :\n';///
form_name=obj.name;										 ///
return;													 ///
}														 ///
														 ///
function finish()										 ///
{														 ///
error_counter('1');										 ///
if(back_m==1){disable();back_m=0;return true;}			 ///
else{error_counter('2');error_counter('0');return false;}///
}														 ///
////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////
//////////// Text field validation code //////////////
//////////////////////////////////////////////////////

if(debug==1)alert("Validation In Testing Mode...\nPlease dont report bug for this\nFor Details : nayak_2k3@rediffmail.com");

function validate_text(field_id,field_name,field_type,min,max)
{	

	if(debug==1)alert("in validate text for " + field_id);
	var result=1;
	var message_x;
	////////////////////////////////////////////////////////////////////
	//////// Following pattern for a value to be upper char     ////////
	////////////////////////////////////////////////////////////////////
	var field_val=eval('document.'+form_name+'.'+field_id+'.value');
	if(field_type=='char_up')
	{
		//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[A-Z_-]+$/
			message_x=' should consist only of characters in upper case A - Z'
			if(field_val.match(pat)){result=0;}
			else{result=1;}

	}



	////////////////////////////////////////////////////////////////////
	//////// Following pattern for a value to be lower char     ////////
	////////////////////////////////////////////////////////////////////

	if(field_type=='char_low')
	{//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[a-z_-]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of characters in lower case a - z'

	}

	////////////////////////////////////////////////////////////////////
	//////// Following pattern for value to be mixtur low and up char //
	////////////////////////////////////////////////////////////////////

	if(field_type=='char')
	{//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[a-zA-Z\.]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of characters only a - z or A - Z'

	}

	////////////////////////////////////////////////////////////////////
	//////// Following pattern for value without symbols              //
	////////////////////////////////////////////////////////////////////

	if(field_type=='no_symbols')
	{//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[a-zA-Z0-9. -]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should not consist of any non character values'

	}
	////////////////////////////////////////////////////////////////////
	//////// Following pattern for html/htm file check    //////
	////////////////////////////////////////////////////////////////////

	if(field_type=='htmlform')
	{//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other extention than html or htm and - or _
		pat = /^.*\.(html)$/i;
		pat1 = /^.*\.(htm)$/i;
		//pat=/^[a-z-0-9\._]+$/
			if(field_val.match(pat)){result=0;}
			else if(field_val.match(pat1)){result=0;}
			else{result=1;}
			message_x=' should consist only of html or htm extention'

	}
	////////////////////////////////////////////////////////////////////
	//////// Following pattern for jpg/jpeg/gif file check    //////
	////////////////////////////////////////////////////////////////////

	if(field_type=='image')
	{//alert("Char type testing");//temp line
			//The regular expression mentioned below will look for any other extention than html or htm and - or _
		pat = /^.*\.(jpg)$/i;
		pat1 = /^.*\.(gif)$/i;
		pat2 = /^.*\.(jpeg)$/i;
		//pat=/^[a-z-0-9\._]+$/
			field_val1=field_val.toLowerCase();
			if(field_val1.match(pat)){result=0;}
			else if(field_val1.match(pat1)){result=0;}
			else if(field_val1.match(pat2)){result=0;}
			else{result=1;}
			message_x=' should consist only of JPG or GIF extention'

	}

	////////////////////////////////////////////////////////////////////
	//////// Following pattern for value to be a valid user id    //////
	////////////////////////////////////////////////////////////////////

	if(field_type=='user_id')
	{//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[a-z-0-9\._]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of characters in lower case or numbers 0 - 9'

	}

	////////////////////////////////////////////////////////////////////
	//////// Following pattern for value to be a valid password   //////
	////////////////////////////////////////////////////////////////////

	if(field_type=='password')
	{

		//alert("password type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[a-z-0-9_]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of characters in lower case or numbers 0 - 9'

	}
	////////////////////////////////////////////////////////////////////
	//////// Following pattern for value to be a valid phone number ////
	////////////////////////////////////////////////////////////////////

	if(field_type=='phone')
	{
		//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[0-9 \/ -]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of numbers 0-9, separate multiple numbers by /'
	}

	////////////////////////////////////////////////////////////////////
	//////// Following pattern for value to be a valid phone number ////
	////////////////////////////////////////////////////////////////////

	if(field_type=='mobile')
	{
		//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^[0-9+]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of characters 0-9 and +'
	}

	if(field_type=='mob_in')
	{
		//alert("Char type testing");//temp line
		//The regular expression mentioned below will look for any other value than a to z and - or _
		pat=/^\+91[0-9+]{10,10}$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should begin with +91 and\nconsist only of characters 0-9 for Indian mobiles'
	}


	if(field_type=='num_coma')
	{
			pat=/^[0-9,]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of numericals 0 - 9 and comma'

	}

	if(field_type=='float')
	{
			pat=/^[0-9.]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of 0 - 9 and .'

	}


	////////////////////////////////////////////////////////////////////
	//////// Following pattern for a value to be integer type   ////////
	////////////////////////////////////////////////////////////////////

	if(field_type=='int')
	{//alert("int type testing");//temp line
		//The regular expression mentioned below will look for any other value than 0 to 9 and - or _
		pat=/^[0-9]*$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of numbers 0 - 9'

	}

	////////////////////////////////////////////////////////////////////
	//////// Following pattern for a value to be char or int    ////////
	////////////////////////////////////////////////////////////////////

	if(field_type=='char_int')
	{//alert("Char and int type testing");//temp line
		//The regular expression mentioned will look for any other value than a to z, 0 to 9 and -or_
		//Specially for validating user id
		pat=/^[a-z0-9]+$/
			if(field_val.match(pat)){result=0;}
			else{result=1;}
			message_x=' should consist only of characters in lower case a - z or numericals 0 - 9'

	}

	////////////////////////////////////////////////////////////////////
	//////// Following pattern for a value to be string          ////////
	////////////////////////////////////////////////////////////////////

	/////////
	// Note : Improve this pattern further
	/////////

	if(field_type=='string')
	{
		if(debug==1)alert("in string pat init");//temp line
		var pat=/^[\s_.=]*$/
			if(field_val.match(pat)){result=1;}
			else{result=0;}
			message_x=' should not be left blank or should consist of some valid values'

	}


	////////////////////////////////////////////////////////////////////
	//////// Following pattern for a value to be email          ////////
	////////////////////////////////////////////////////////////////////


/* old version 
	if(field_type=='email')
	{
	if(debug==1)alert("in email pat init");//temp line
	var pat=/^[a-zA-Z][\w\.-_]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/
		

			if(field_val.match(pat)){result=0;
			
			}
			else{result=1;}
			message_x=' should contain a valid email address '

	}

	*/

	/* new version is below */


	if(field_type=='email')
	{
	if(debug==1)alert("in email pat init");//temp line
		

	if(emailCheck(field_val) == true){
					result=0;
	}
	else{
					result=1;
	}
			message_x=' should contain a valid email address '
	}


	////////////////////////////////////////////////////////////////////
	//////// Following code validates value after inheriting pattern ///
	////////////////////////////////////////////////////////////////////
	if(debug==1) alert('field empty validation started');
	var len=field_val.length;
	if(debug==1) alert('length is =' + len);
	if (len == 0 && min!=0) {
		send = "Please specify your "+field_name;
		hi[hi.length]=field_id;
		error_process(send);
	  return false;
	}

	if(debug==1) alert('field pattern validation started');
	if (result == 1 ) {
	if (min==0 && len==0){}else{
		send = field_name + message_x ;
		hi[hi.length]=field_id;
		error_process(send);
		return false;}
	}


	if(debug==1) alert('field max min validation started');
	// just test if max was defined or not
	if (max > 0 && ( (len < min) || (len > max) )  ) {
		// max is present
		send= 'Length of ' + field_name +' should be between '+min+ ' and ' + max  ;
		hi[hi.length]=field_id;
		error_process(send);
		return false;
	} else if (len < min )  {
		if(debug==1) alert('field min validation started');
		send= 'Length of ' + field_name +' should be more than '+min  ;
		hi[hi.length]=field_id;
		error_process(send);
		return false;
	}
	if(debug==1)alert('field validation ended');

	send='';
return true;
}



function validate_radio(radio_var,radio_name)
{
				if(debug==1)alert("validate radio called for " + radio_var);
				var rOpt = -1;


				// see if anything is checked by default  return true if so
				// without any further chekcing.

				var defchecked;
				
				defchecked = eval('document.'+form_name+'.'+radio_var+'.defaultChecked');

				if ( defchecked ) {

						return true;

				}

				for (var i=0; i < eval('document.'+form_name+'.'+radio_var+'.length'); i++) 
				{
								if (eval('document.'+form_name+'.'+radio_var+'['+i+'].checked') )
								{
												rOpt=i;
												if(debug==1)alert("found one radio selected hence increasing counter");
								}
				}

				if (rOpt==-1) 
				{	if(debug==1)alert('counter was not increased during validation process hence no radio selected');
								send="Please select one option for field "+radio_name;
								if(debug==1)alert("now sending error : "+send);
								error_process(send); 
								if(debug==1)alert("now returning radio valid false");
								return false
				}
				else
				{	if(debug==1)alert("counter was increased means that radio was selected hence return radio true");
								return (true);
				}
				if(debug==1)alert("exit radio validate");
}


function validate_dd(field_id,field_name)
{
	var str =  'document.'+form_name + '.' + field_id +'.options.selectedIndex'; 
	if(eval(str)==0)
	{
	  hi[hi.length]=field_id;
		send="Please select a option in dropdown for field "+field_name;
		error_process(send);
	}
}


function validate_list(field_id,field_name,min)
{
	var inc=0;	
	for(i=0;i<eval('document.'+form_name+'.'+field_id+'.options.length');i++)
	{
		if(eval('document.'+form_name+'.'+field_id+'.options['+i+'].selected')){
			inc++;if(inc==min){break;}
		}
	}


	if(inc<min)
	{
		hi[hi.length]=field_id;
		send="Please select at least "+min+" option in list "+field_name;
		error_process(send);
	}


}



function validate_checkBox(arr,disc,typ,min)
{
	var x=0;
	eval("var newAr=new Array("+arr+");");
	for(var px=0;px<eval('newAr.length');px++)
	{
		if(eval('document.'+form_name+'.'+newAr[px]+'.checked')==true)
		{
			x++;
		}

	}
	if(x<min)
	{

		if((x<min)&&(typ=='single'))
		{
			for(var w=0;w<newAr.length;w++)
			{
			hi[hi.length]=newAr[w];
			}
			send="You Must check "+disc+" Checkbox to submit this form";
			error_process(send);
		}

		if((x<min)&&(typ=='group'))
		{
			send="Please select at least " + min + " checkbox" + ( (min > 1) ? "es" : "" ) + " from " + disc;
			error_process(send);
		}

	}
}

function validate_confirm(field1,field2,disc)
{
	var field1_val=eval('document.'+form_name+'.'+field1+'.value');
	var field2_val=eval('document.'+form_name+'.'+field2+'.value');
	if(field1_val!=field2_val)
	{
		send="The value for field "+disc+" is not confirmed";
		hi[hi.length]=field1;hi[hi.length]=field2;
		error_process(send);
	}
}






////////////////////////////////////////////////////////////////////////////////////////////////
////////// This function must be called from main page with a intial line of alert /////////////
////////// like : Error Occured or Please make a note of following things or ..... /////////////
////////// This function is used to create a list of validation failures on a page /////////////
////////////////////////////////////////////////////////////////////////////////////////////////

function error_process(error_msg)
{
				if(process==1){
								if (error >= max_error) {

												return;

								}
								show_error[show_error.length] = '-- ' +  error_msg;
								error_counter('+');
				}
				if(process==0) {filter=1;}
}

function process_status(what)
{
				if(what=='start')				{
								process=1;
				}
				if(what=='stop'){
								process=0;
				}
				return;
}


//This function must be called from main page before starting validation process with 0 para
function error_counter(z)
{
	switch (z)
	{
		case '0'://alert("counter set 0");
			//Empty all the array variables and variables used for re-validation
			hi=new Array();
			error=0;break;

		case '1':
			if(error>0)
			{
					back_m=0;
			}
			else
			{
				back_m=1;
			}

		case '+'://alert("counter increased");
			error++;break;

		case '2':
			if(error>0)
			{
				show_error[0] = 'Please re-enter the following field(s) again:\n';
				show_error[show_error.length]='\nPlease correct the above problems and submit again.';
				thi=hi;

				tkname=thi;tfname=form_name;
				alert(show_error.join('\n'));
				hi=new Array();
				field_id='';
				field_name='';
				field_type='';
				min=0;
				field_val='';temp_hi=hi;
				show_error=new Array();
				break;
			}
			else
			{
				field_id='';
				field_name='';
				field_type='';
				min=0;
				field_val='';
				show_error=new Array();
				back_m=1;
				break;
			}

	}
}


////////////////////////////////////////////////////
///////////////Control disabling ///////////////////
////////////////////////////////////////////////////
// Note : execute only if validation achieved///////
////////////////////////////////////////////////////



function disable()
{

	if(debug==1)alert('Disabling process started');
	if (document.all||document.getElementById)
	{
		//screen thru every element in the form, and hunt down "submit" and "reset"
		for (i=0;i<eval('document.'+form_name+'.length');i++)
		{
			var tempobj=eval('document.'+form_name+'.elements[i]');
			if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset")
			{
				tempobj.disabled=true;
				if(tempobj.type.toLowerCase()=="submit")
				{
					tempobj.value='Please wait ..';
				}
			}


		}
	}
}

function high_light_clear()
{
	for(var k=0;k<tkname.length;k++)
	{	if(eval('document.'+tfname+'.'+tkname[k]+'.type')!='radio'&&'button'&&'hidden')
		{
			eval("document."+tfname+"."+tkname[k]+".style.backgroundColor=''");
		}
	}

}

function high_light()
{
	tkname=hi;
	tfname=form_name;

	high_light_clear();

	high_light_clear();
	for(var l=0;l<hi.length;l++)
	{
		if(eval('document.'+form_name+'.'+hi[l]+'.type')!='radio'&&'button'&&'hidden'){
			eval('document.'+form_name+'.'+hi[l]+".style.backgroundColor='fff79e'");}
	}
}

var bbg=0;var thi=new Array();
function blink_bg(bbg)
{
	if(bbg==0)
	{
		for(var l=0;l<thi.length;l++)
		{
			if(eval('document.'+form_name+'.'+thi[l]+'.type')!='radio'&&'button'&&'hidden'){
				eval('document.'+form_name+'.'+thi[l]+".style.backgroundColor='fff79e'");}
		}

		bbg=1;
	}
	else
	{
		for(var k=0;k<tkname.length;k++)
		{	if(eval('document.'+tfname+'.'+tkname[k]+'.type')!='radio'&&'button'&&'hidden')
			{
				eval("document."+tfname+"."+tkname[k]+".style.backgroundColor=''");
			}
		}

		bbg=0;

	}
}

///////////////////////////////////////////////////////////////
////// Email validation Adopted from another website //////////
///////////////////////////////////////////////////////////////

function emailCheck(emailStr) {

/* 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("Your Email address doesn't seems to be in proper format \""  +emailStr+ '" .')
	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. \""  +emailStr+ '"')
    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! \""  +emailStr+ '"')
		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. \""  +emailStr+ '"')
    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>4) {
   // the address must end in a two letter or three letter word.
   //alert("The address must end in a maximum of four-letter domain, or two letter country. \""  +emailStr+ '"')
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname! \""  +emailStr+ '"'
   //alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
	return true;
}

