// HAJAX
// a simple and dirty little Ajax Processor
// handles multiple, simultanious Ajax requests
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind, either
// expressed or implied, including, but not limited to, the implied warranties
// of merchantability and fitness for a particular purpose. You expressly
// acknowledge and agree that use of this code is at your own risk.

// global settings
// allow multiple requests
// hajax_allowMultiple
// This setting will turn on/off the ability to allow mutilpe requests to be processed globally
// this means, if you turn it on then all ajax calls can be run simultaneously
// 		if you turn it off then if a request is currently being processed then all subsequent requests will be blocked
//		until the curren request has been completed
var hajax_allowMultiple = true;
// hajax may also be set on a call by call basis to allow/disallow mutiple simultaneous requests
//		see parameter blockMultiple
// for a discussion of allowing/disallowing multiple simultaneous requests on a funtion by function basis
// in your own functions see the discussion at the end of this document

// if you would like the default alert shown that a request has been blocked
// set the following variable to true
var hajax_showMultipleBlockedMessage = false;

// do not edit these, flag that hajax used to see if a process is currently running or temporarily blocked
var hajax_running = false;
var hajax_temp_blockMultiple = false;

function hajax(url, call_function, parameters, pass, method, blockMultiple) {
	
	// **********************************************************************************************************
	// url = url of the script file on the server
	// can be absolute or reletive from page or doc root
	// can include http://domain
	// absolute urls are best if this will be called from several different levels of a site 
	//
	// call_function is a variable that contains the javascript function that will process whatever is returned from url
	// more info on creating call_function below
	//
	// parameters (optional) are any variable/value pairs that need to be sent to the server
	// example 'x=2&amp;y=3'
	//
	// method = GET or POST (optional default = POST)
	// POST must be used for long argument lists (GET URL's are limited to 256 characters
	// POST may fail, depending on the server, if no parameters are sent
	//
	// pass (optional)
	// anything in pass will be passed to call_function without alteration
	// values in pass would be anything that the called function might need as 
	// parameters other than the server response
	// since it is unaltered, anything that can be passed in a javascript varaible can be passed to the called function
	// including other functions or arrays
	//
	// blockMultiple (optional)
	// This parameter, if set to true will temporarily turn off multiple simultaneous requests
	// This will block the current call from running if there is already a process in progress as well as
	// Prevent any further calls until the current call is completed
	// 			If you call hajax with blockMultiple set to true then if there is no process running the call will be allowed
	//			and subsequect calls will be blocked
	//			If there is already a process running then the current call will blocked as well
	//			for more flexibility in allowing/disallowing multiple simultaneous requests
	//			see the discussion at the end of this document
	//
	// of the above parameters only url and call_function are required. The other three are optional
	// (exception: added a default call_function/response handler - see below 
	//		so now the only required parameter is the URL as long as non-empty element with the id "hajax_default"
	//		is available in the document
	// **********************************************************************************************************
	
	// **********************************************************************************************************
	// returns (sends to call_function) paremeters in the following order
	// 	server_response, pass, httpConnection, httpStatus, statusText, readError
	// 		server_response = the data returned by the called url
	// 		httpConnection = true or false, indicates if an http connection was succesfully created
	// 		httpStatus = the last http status returned by the server. Could indicate errors
	// 		statusText = text of the above http status number
	// 		readError = any errors in reading the response
	// it is completely up to the user and call_function to decide what is done with any of the above values
	// error capturing and handling is completely up to the user to deal with
	// **********************************************************************************************************
	
	// **********************************************************************************************************
	// creating a function to be called when a response is recieved from the server
	// at its simplest, create function as follows
	//
	// var alert_this = function (what) { alert(what); }
	// the parameter "what" will contain whatever was returned by the server
	//
	// more complicated
	// var myfunction = function(server_response, pass, httpConnection, httpStatus, statusText, readError) {
	// 		all instructions for function here
	// }
	//
	// the above function "myfunction" will recieve all paremeters returned by hajax
	// see the discussion about returned values above	
	// **********************************************************************************************************
	
	// **********************************************************************************************************
	// calling hajax
	// simplest form
	// hajax('http://mysite.com/ajax.php', myfunction);
	// the url that is being called and the function that will process the response (see discusion of creating functions above)
	// no parameters are sent to the server, method will default to "GET", and nothing will be passed from the call to the called function
	//
	// more complicated
	// hajax('http://mysite.com/ajax.asp', myfunction, 'x=2&y=5', 'POST', extra_values);
	// url = 'http://mysite.com/ajax.asp'
	// function to process the response = myfunction (see discussion of creating functions above)
	// query string = 'x=2&y=5', values to send to url
	// 'POST' = method to use (can be POST or GET)
	// extra_values = anythig that will be passed, unaltered, to the called function
	// any value not needed may be set to null, for instance if you wish to send no query string and use the 
	// default method of GET but you need to pass values to the called function then call hajax like this
	// hajax('http://mysite.com/ajax.asp', myfunction, '', '', extra_values);
	// **********************************************************************************************************
	
	// **********************************************************************************************************
	// default response handler
	// the default response handler will check for errors and if none exist will simply
	// dump the entire server response into the innerHTML of the element whose id is passed to Hajax
	// no extra formating of the server response is performed
	//
	// example:
	// hajax('http://mysite.com/ajax.asp', hajax_default, 'x=2&y=5', 'POST', 'test_div');
	// call myfunction in the script http://mysite.com/ajax.asp using the POST method and parameters of 'x=2&y=5'
	// dump server response into the element that has the id "test_div"
	//
	// hajax default does not even need to be explicitly called
	// example:
	// hajax('http://mysite.com/ajax.asp', '', 'x=2&y=5', 'POST', 'test_div');
	// is the same as the above example
	// if you do not specify a destination element id the default elment with an id of "hajax_default" will be used
	// example
	// hajax('http://mysite.com/ajax.asp', '', 'x=2&y=5', 'POST');
	// 
	// putting this all together, if you want to call the default handler and us an elment with the id of "hajax_default"
	// and use all other default settings you simply nee to use:
	// hajax('http://mysite.com/ajax.asp');
	//
	// **********************************************************************************************************
	
	// set defaults if not passed to function will recieve all parameters passed by hajax
	// see discussion of returned values above
	// it is up to the user to decide what to do with these values.
	if (blockMultiple) {
		hajax_temp_blockMultiple = true;
	}
	
	// see if multiple requests are allowed and if hajax is running
	if ((hajax_allowMultiple && !hajax_temp_blockMultiple) || !hajax_running) {
		hajax_running = true;
		if (!method || method == '') {
			method = 'POST';
		}
		method = method.toUpperCase();
		if (!parameters) {
				var dt = new Date();
			parameters = 'dummy='+ dt.getTime();
		}
		if (!pass) {
			pass = false;
		}
		if (!call_function || call_function == '') {
			// call_function = 'hajax_default';
			call_function = false;
		}
		//if (call_function == 'hajax_default') {
		if (!call_function) {
			if (!pass) {
				pass = 'hajax_default';
			}
		}
		
		var httpConnection = false;
		var readError = false;
		var httpStatus = false;
		var statusText = false;
		var server_response = false;
		var xmlHttp = hajax_createXmlHttpRequestObject();
		hajax_process();
	} else {
		// multiple simultaneous requests blocked
		if (hajax_showMultipleBlockedMessage) {
			alert('There is already an Ajax Process Running.\nPlease Wait.');
		}
	}
	
	// **********************************************************************************************************
	// Functions to create connection, send request and recieve response
	// **********************************************************************************************************
	
	function hajax_createXmlHttpRequestObject() {
		// create new XMLHttpRequest Object
		xmlHttp == false;
		// will store the reference to the XMLHttpRequest object
		// this should work for all browsers except IE6 and older
		try {
			// try to create XMLHttpRequest object
			xmlHttp = new XMLHttpRequest();
		}
		catch(e) {
			// failed to create XMLHttpRequest object
			// assume IE6 or older
			var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
																			"MSXML2.XMLHTTP.5.0",
																			"MSXML2.XMLHTTP.4.0",
																			"MSXML2.XMLHTTP.3.0",
																			"MSXML2.XMLHTTP",
																			"Microsoft.XMLHTTP");
			// try every prog id until one works
			for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
				try { 
					// try to create XMLHttpRequest object
					xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
				} 
				catch (e) {}
				// failed to create object
				// do nothing and try the next
			}
		}
		// return the object
		// returns false if we were unable to create any object
		return xmlHttp;
	}
	
	function hajax_process() {
		// make request to server
		if (xmlHttp) {
			httpConnection = true;
			if (method == 'GET') {
				if (parameters != '') {
					url = url + '?' + parameters;
				}
				post_args = null;
			} else {
				post_args = parameters;
			}
			try {
				xmlHttp.open(method, url, true);
				xmlHttp.onreadystatechange = hajax_handleRequestStateChange;
				if (method == 'POST') {
					//Send the proper header information along with the request
					xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					xmlHttp.setRequestHeader("Content-length", post_args.length);
					xmlHttp.setRequestHeader("Connection", "close");
				}
				xmlHttp.send(post_args);
			}
			catch (e) {
				// unable error openenng connection
				statusText = 'Ajax Error sending request';
				if(call_function)
					call_function(server_response, pass, httpConnection, httpStatus, statusText, readError);
				hajax_temp_blockMultiple = false;
				hajax_running = false;
			}
		} else {
			// could not connect, call response handler
			if(call_function)
				call_function(server_response, pass, httpConnection, httpStatus, statusText, readError);
			hajax_temp_blockMultiple = false;
			hajax_running = false;
		}
	}
	
	function hajax_handleRequestStateChange()  {
		// wait for request to be complete and then process returned data
		readError = '';
		if (xmlHttp.readyState == 4) {
			// when readyState is 4 (done), we also read the server response
			// continue only if HTTP status is "OK"
			if (xmlHttp.status == 200)  {
				httpStatus = 200;
				statusText = xmlHttp.statusText;
				try {
					// read the message from the server
					server_response = xmlHttp.responseText;
				}
				catch(e) {
					// display error message
					//alert("Error reading the response: " + e.toString());
					readError = e.toString();
				}
			} else {
				// display status message
				//alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
				statusText = xmlHttp.statusText;
				httpStatus = xmlHttp.status;
			}
			// call the function to deal with the server response
			// pass status and errors to server response processor
			// it is up to that function to deal with any errors
			if(call_function)
				call_function(server_response, pass, httpConnection, httpStatus, statusText, readError);
			hajax_temp_blockMultiple = false;
			hajax_running = false;
		}
	}
}

// function to trim leading & trailing spaces
function trim(strText) { 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
} 

/*
1. PHONE NUMBER VALIDATION
Usage: 
Element  name of the control, like frm.phone
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

 if(!isValidPhone(frm.phone,'Phone Number','yes'))
 return;
*/

function isValidPhone(element, msg, required)
{	
	var VarPhone = element.value;
	if (VarPhone== "")
	{	
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}
	if (VarPhone != "")
	{
		var Phno;
		Phno=VarPhone;
		var valid = "-0123456789()";
		var hyphencount = 0;
		for (var i=0; i < Phno.length; i++) 
		{
			temp = "" + Phno.substring(i, i+1);
			if (valid.indexOf(temp) == "-1")
			{
				alert("Invalid characters in your "+msg+". Please try again.");
				element.focus();
				return false;
			}
		}
     } 
	 return true;      
}

/*
2. NUMBER VALIDATION
Usage:
Element  name of the control, like frm.number
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

 if(!isValidNumber(frm.num,'Roll Number','yes'))
 return;
*/
function isValidNumber(element, msg, required)
{  
	var VarNumber = element.value;
	if(VarNumber == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}
	if (VarNumber != "")
	{
		var Num;
		Num=VarNumber;
		var valid = "0123456789";
		var hyphencount = 0;
		
		for (var i=0; i < Num.length; i++) 
		{
			temp = "" + Num.substring(i, i+1);
			if (valid.indexOf(temp) == "-1")
			{
			  alert("Invalid characters in your "+msg+".  Please try again.");
			  element.focus();
			  return false;
			}
	   } // end for loop
	   
		if(VarNumber < 1)
		{
			alert(msg+" is not a valid number");
			element.focus();
			return false;
		}
    }   // end if
    return true; 
}  // end function

/*
3. EMAIL ADDRESS VALIDATION

Usage: 
Element  name of the control, like frm.email
Required  Set this to yes if the field is mandatory, otherwise no.

	 if(!isValidEmail(frm.email,'yes'))
	 return;
*/

function isValidEmail(element, required)
{
	var VarEmail = element.value;
	if(VarEmail == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter Email Address");
			element.focus();
			return false;
		}
	}	
	if(VarEmail != "")
	{
		var emailStr = VarEmail;
		 
		var emailPat=/^(.+)@(.+)$/
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
		var validChars="\[^\\s" + specialChars + "\]"
		var firstChars=validChars
		var quotedUser="(\"[^\"]*\")"
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
		var atom="(" + firstChars + validChars + "*" + ")"
		var word="(" + atom + "|" + quotedUser + ")"
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
		var matchArray=emailStr.match(emailPat)
		if (matchArray==null) 
		{
			 alert("Email address seems to be incorrect (check @ and .'s)");
			 element.focus();
			 return false;
		}
		var user=matchArray[1]
		var domain=matchArray[2]
		if (user.match(userPat)==null) 
		{
			alert("The username doesn't seem to be valid.");
			element.focus();
			return false;
		}
		
		var IPArray=domain.match(ipDomainPat)
		if (IPArray!=null) 
		{
			for (var i=1;i<=4;i++) 
			{
				if (IPArray[i]>255) 
				{
					 alert("Destination IP address is invalid!");
					 element.focus();
					 return false;
				}
			}
		}
		var domainArray=domain.match(domainPat)
		if (domainArray==null) 
		{
			alert("The domain name doesn't seem to be valid.");
			element.focus();
			return false;
		}
		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) 
		{
		   alert("The address must end in a three-letter domain, or two letter country.");
		   element.focus();
		   return false;
		}
		if (domArr[domArr.length-1].length==2 && len<2) 
		{
			var errStr = "This address ends in two characters, which is a country";
			errStr    += " code.  Country codes must be preceded by ";
			errStr	  += "a hostname and category (like com, co, pub, pu, etc.)";
			alert(errStr);
			element.focus();
			return false;
		}
		if(domArr[domArr.length-1] == 'ru')
		{
			alert("The domain name doesn't seem to be valid.");
			element.focus();
			return false;
		}
		if (domArr[domArr.length-1].length==3 && len<2) 
		{
			 var errStr="This address is missing a hostname!";
			 alert(errStr);
			 element.focus();
			 return false;
		}
	}
	return true;
}

/* 
4. ZIPCODE/PINCODE  VALIDATION

Usage:
	Element  name of the control, like frm.zipcode
	Required  Set this to yes if the field is mandatory, otherwise no.

	if(!isValidZipcode(frm.zip,'yes'))
	return;
*/
function isValidZipcode(element,required) 
{
	var valid = "0123456789-";
	var hyphencount = 0;
	var field = element.value;
	var str   = required;
	if(field == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter ZipCode");
			element.focus();
			return false;
		}
	}	
	if (field != "")
	{
		if (field.length!=6 && field.length!=5 && field.length!=10) 
		{
			alert("Zip code length should be 6( forIndia) , or 5 (without hyphens) or 10 with Including Hyphens ( for USA)....");
			element.focus();
			return false;
		}
		for (var i=0; i < field.length; i++) 
		{
			temp = "" + field.substring(i, i+1);
			if (temp == "-") hyphencount++;
			if (valid.indexOf(temp) == "-1")
			{
				alert("Invalid characters in your zip code.  Please try again.");
				element.focus();
				return false;
			}
			if ((hyphencount > 1) || ((field.length==10) && "" + field.charAt(5)!="-")) 
			{
				alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
				element.focus();
				return false;
			}
		}
	}
	return true;
}

/*
5. ALPHA VALIDATION
//to find if the field contains alphabets only
usage:
Element  name of the control, like frm.firstname
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

 if(!isValidAlphabet(frm.firstname,'First Name','yes'))
 return;
*/

function isValidAlphabet(element, msg, required)
{
	var i=0;
	var ValidData="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._- ";
	var Data=element.value;
	if(element.value == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}	
	if(element.value != "")
	{
		for(i=0;i<Data.length;i++)
		{
			if(ValidData.indexOf(Data.charAt(i))==-1)
			{
				alert("PLease enter Non-Numeric Data Only");
				element.focus();
				return false;
			}
		}
	}
    return true;
}

/*
6. ALPHANUMERIC VALIDATION
//to check if the field contains both alphabets and numbers
usage:
Element  name of the control, like frm.firstname
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

 if(!isValidAlphaNumeric(frm.firstname,'First Name','yes'))
 return;
*/

function isValidAlphaNumeric(element, msg, required)
{
	var i=0;
	var ValidData=". ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890/_- ";
	var Data=element.value;
	
	if(element.value == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}	
	if(element.value != "")
	{
		for(i=0;i<Data.length;i++)
		{
			if(ValidData.indexOf(Data.charAt(i))==-1)
			{
				alert("Invalid entry.\t\t");
				element.focus();
				return false;
			}
		}
	}
	return true;
}

function isValidAlphaNumericForNames(element, msg, required)
{
	var i=0;
	var ValidData=".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890/_- ";
	var Data=element.value;

	if(element.value == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}	
	if(element.value != "")
	{
		for(i=0;i<Data.length;i++)
		{
			if(ValidData.indexOf(Data.charAt(i))==-1)
			{
				alert("Invalid entry.\t\t");
				element.focus();
				return false;
			}
		}
	}
	return true;
}

/*
7. URL VALIDATION

Usage:
Element  name of the control, like frm.url
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

	 if(!isValidURL(frm.url, "URL", "yes")) 
	 return;
*/
function isValidURL(element, msg, required)
{
	if(element.value == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}
	if(element.value != "")
	{
		var oRegExp = /[^:]+:\/\/[^:\/]+(:[0-9]+)?\/?.*/;
		if (!oRegExp.test(element.value))
		{
			alert('\r\n The URL you have entered is invalid.\n Please check it for accuracy.');
			element.focus();
			element.select();
			return false;
		}
	}
	return true;
}

/*
8. DATE VALIDATION

Usage:
Element  name of the control, like frm.date
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

Valid date formats are MM-DD-YYYY, MM/DD/YYYY and MM.DD.YYYY  

	 if(!isValidDate(frm.startdate, "Started Date", "yes")) 
	 return;
*/
function isValidDate(element, msg, required) 
{
	var dateStr = element.value;
	var valid = "0123456789-/.";
	var temp = "";
	var hyphencount = 0 ;
	var slashcount = 0 ;
	var dotcount = 0 ;
	if(element.value == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}
	if(element.value != "")
	{
		for (var i=0; i < dateStr.length; i++)
		{
			temp = "" + dateStr.substring(i, i+1);
			 if  (temp == "-")  { hyphencount++; }
				else  if (temp == "/")  {  slashcount++; }
				   else  if (temp == ".") { dotcount++; }
			if ( ( hyphencount == 2 ) || ( slashcount == 2 ) || ( dotcount == 2 ) )
			{
				t=dateStr.substring(6,10);
				if(t.length==4)
				{
					if(t<1900)
					 {
						alert("the century of date should be greater than or equal to 1900.");
						element.focus();
						return false;
					 }
				}
			}          
			if (valid.indexOf(temp) == "-1")
			{
				alert("Invalid characters in your date.  Please try again.");
				element.focus();
				return false;
			}
		} //end of for loop   
		//alert ( "hyphen  " + hyphencount + " slash " + slashcount + " dot " + dotcount )  ; 
		if ( ( hyphencount== 2) & (slashcount !=2) && (dotcount !=2) ) {}
		else if ( ( hyphencount!= 2) & (slashcount ==2) && (dotcount !=2) ) {}
		else if ( ( hyphencount!= 2) & (slashcount !=2) && (dotcount ==2) ) {}
		else 
		{	
			alert("The hyphen or slashes character should be used with a properly formatted. Please try again.");
			element.focus();
			return false;
		}
		   
		if (dateStr.length == 8 || dateStr.length == 10 )
		{
			var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
			var matchArray = dateStr.match(datePat); // is the format ok?
			if (matchArray == null) 
				return true;
	
			month = matchArray[1]; // parse date into variables
			day = matchArray[3];
			year = matchArray[4];
			//alert(matchArray[1]);
			//alert(matchArray[3]);
			//alert(matchArray[4]);
			
			if (month < 1 || month > 12) 
			{ // check month range
				alert("Month must be between 1 and 12.");
				element.focus();
				return false; 
			}
			if (day < 1 || day > 31) 
			{
				alert("Day must be between 1 and 31.");
				element.focus();
				return false; 
			}
			if ((month==4 || month==6 || month==9 || month==11) && day==31) 
			{
				alert("Month "+month+" doesn't have 31 days!")
				element.focus();
				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!");
					element.focus();
					return false;
				}
			} // end of month = 2 condition
		} // end of date string length = 8 or length = 10 condition
		else 
		{
		   alert("Entered date is invalid format, Date should be 8 to 10 chars. length.");
		   element.focus();
		   return false;
		} 
	}
	return true;  // date is valid
}

/*
8. DATE VALIDATION - 2

Usage:
Element  name of the control, like frm.date
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

Valid date formats are DD-MM-YYYY, DD/MM/YYYY and DD.MM.YYYY  

	 if(!isValidDate(frm.startdate, "Started Date", "yes")) 
	 return;
*/
function isValidDate2(element, msg, required) 
{
	var dateStr = element.value;
	var valid = "0123456789-/.";
	var temp = "";
	var hyphencount = 0 ;
	var slashcount = 0 ;
	var dotcount = 0 ;
	if(element.value == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}
	if(element.value != "")
	{
		for (var i=0; i < dateStr.length; i++)
		{
			temp = "" + dateStr.substring(i, i+1);
			 if  (temp == "-")  { hyphencount++; }
				else  if (temp == "/")  {  slashcount++; }
				   else  if (temp == ".") { dotcount++; }
			if ( ( hyphencount == 2 ) || ( slashcount == 2 ) || ( dotcount == 2 ) )
			{
				t=dateStr.substring(6,10);
				if(t.length==4)
				{
					if(t<1900)
					 {
						alert("the century of date should be greater than or equal to 1900.");
						element.focus();
						return false;
					 }
				}
			}          
			if (valid.indexOf(temp) == "-1")
			{
				alert("Invalid characters in your date.  Please try again.");
				element.focus();
				return false;
			}
		} //end of for loop   
		//alert ( "hyphen  " + hyphencount + " slash " + slashcount + " dot " + dotcount )  ; 
		if ( ( hyphencount== 2) & (slashcount !=2) && (dotcount !=2) ) {}
		else if ( ( hyphencount!= 2) & (slashcount ==2) && (dotcount !=2) ) {}
		else if ( ( hyphencount!= 2) & (slashcount !=2) && (dotcount ==2) ) {}
		else 
		{	
			alert("The hyphen or slashes character should be used with a properly formatted. Please try again.");
			element.focus();
			return false;
		}
		   
		if (dateStr.length == 8 || dateStr.length == 10 )
		{
			var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
			var matchArray = dateStr.match(datePat); // is the format ok?
			if (matchArray == null) 
				return true;
	
			month = matchArray[3]; // parse date into variables
			day = matchArray[1];
			year = matchArray[4];
			//alert(matchArray[1]);
			//alert(matchArray[3]);
			//alert(matchArray[4]);
			
			if (month < 1 || month > 12) 
			{ // check month range
				alert("Month must be between 1 and 12.");
				element.focus();
				return false; 
			}
			if (day < 1 || day > 31) 
			{
				alert("Day must be between 1 and 31.");
				element.focus();
				return false; 
			}
			if ((month==4 || month==6 || month==9 || month==11) && day==31) 
			{
				alert("Month "+month+" doesn't have 31 days!")
				element.focus();
				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!");
					element.focus();
					return false;
				}
			} // end of month = 2 condition
		} // end of date string length = 8 or length = 10 condition
		else 
		{
		   alert("Entered date is invalid format, Date should be 8 to 10 chars. length.");
		   element.focus();
		   return false;
		} 
	}
	return true;  // date is valid
}

/*
9. SELETC VALIDATION

Usage:
Element  name of the control, like frm.firstname
Message  Field Name that we want to display in alert message.

if(!isValidSelect(frm.country,'Country'))
return;
*/
function isValidSelect(element,msg) 
{
	if(element.value == "0") 
	{
		alert("Please select "+msg+" from the list");
		element.focus();
		return false;
	}
	return true;
}

/*
10. FUNTION SELECTALL CHECK BOXES

Usage:
frm  name of the form

SelectAll(frm);
*/

function SelectAll(frm) {
	 //alert(frm.selectall.checked);
	   if(frm.selectall.checked == true) {
	   
		 for(sel=0;sel<frm.elements.length;sel++) {
		   if((frm.elements[sel].type == "checkbox") && (frm.elements[sel].name != "selectall")) {
			 frm.elements[sel].checked = true;
		   } // if statement
		 } // for loop
	   }
	   else if(frm.selectall.checked == false) {
		
		  for(sel=0;sel<frm.elements.length;sel++) {
			 if((frm.elements[sel].type == "checkbox") && (frm.elements[sel].name != "selectall")) {
			   frm.elements[sel].checked = false;
			 } // if statement
		  } // for loop
	   } // if - else - if condition
	} // closing the function SelectAll()
	
/*
11. IS LEAP YEAR

Usage:  Y  year
If the given year is a leap year, this function will return true. otherwise false.
isLeapYear('2004');

*/
function isLeapYear(y) 
{
	if( y % 4 == 0) 
	{
		if( y % 100 == 0 ) 
		{
			if( y % 400 == 0) 
			{
				return true;
			}
			else 
			{
				return false;
			}
		}
		else 
		{
			return true;
		}
	}
	else 
	{
		return false;
	}
} // closing the function isLeapYear()

/*
12. CONFIRM PASSWORD

Usage:
Element1 name of the first control like frm.password.
Element2 name of the second control like frm.confirmpassword.

if(!isValidConfirmPassword(frm.pwd, frm.conpwd))
return;
*/
function isValidConfirmPassword(element1,element2) 
{
	if(element1.value != element2.value)
	{
		alert("Retype Password doesn't match");
		element2.focus();
		return false;
	}
	else
		return true;
} // closing the function PassValidation()

/*
13. GET COUNT OF

Usage:
This can be used for any character validation.
For example in a valid date the count of - or / should not be more than 2
Likewise in a valid numer there should be only one.

*/
function getCountOf(vChr, txt)
{
	var i = 0;
	var iCount = 0;
	for( i=0; i < txt.length; i++ )
	{
		if( txt.charAt(i) == vChr )
		{
			iCount++;
		}
	}
	return iCount;
}

/*
14. IS BLANK
To check if trim(value) is blank
Usage:
	This fucntion can be used to check if a given text contains only spaces or 0 in length.

	INPUT: Text [txt]
				Minimum Length [minlen] optional
				Indicates that the text should be atleast 'minlen' in length


	OUTPUT: returns true if blank else false

*/	
function isBlank(txt, minlen)
{
	if( txt.length == getCountOf('\n', txt) )
	{
		// This condition avoids the entry of just newlines in text areas.
		return true;
	}
	if( txt.length == getCountOf(' ', txt) || txt.length == 0 )
	{
		return true;
	}
	else if( minlen > 0 )
	{
		if( txt.length < minlen )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
	return true;
}

/*
15. INCLUDE SPECIAL CHARACTER

In some cases, we want to validate whether a given value contains at 
least one special character or not. Below mentioned function will be useful 
for such situations.

Usage:
	Element  name of the control like frm.password.
	Message  Field Name that we want to display in alert message.

if(!isSplchar(frm.pwd, "Password"))
return;
*/
function isSplchar(element, msg)
{
	var alp = '!@#$%&*_1234567890';
	var count = 0;
	for (var i=0;i<element.value.length;i++)
	{
		temp=element.value.substring(i,i+1);
		if (alp.indexOf(temp)!= -1)
		{
			count = 1;
		}
	} // closing the for loop
	if(count == 0)
	{
	  alert(msg+" should contain atleast one special character (!,@,#,$,%,&,*, _  and numbers can be used).");
	  element.focus();
	  return false;
	}
	return true;
}
 
/*
16. isValidEntry

Usage:
	Element  name of the control like frm.password.
	Message  Field Name that we want to display in alert message.

if(!isValidEntry(frm.name, "Name"))
return;
*/
function isValidEntry(element,msg) 
{
	if(element.value.length == 0)
	{
		alert("Please enter the "+ msg);
		element.focus();
		return false;
	}
	else if(isBlank(element.value))
	{
		alert("Please enter the "+ msg);
		element.focus();
		return false;
	}
	return true;
} // closing the function GenValidation()

/*
17.  FUNCTION SPLCHARACTERS(element)
No speaicl Characters
This function will not accept any special characters.
Valid entries for this function are [a-z][A-Z][0-9][ _ ].
Usage:
	Element  name of the control like frm.password.

if(!noSplChars(frm.name))
return;
*/

function noSplChars(element) 
{
	var alp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
	for (var i=0;i<element.value.length;i++)
	{
		temp=element.value.substring(i,i+1);
		if (alp.indexOf(temp)==-1)
		{
			alert("No special characters\r\nValid entries are [a-z][A-Z][0-9][ _ ]");
			element.focus();
			return false;
		}
	} // closing the for loop
	 return true;
} // closing the function SplCharacters()

/*
18. SplCharactersSpace
Valid entries for this function are [a-z][A-Z][0-9][ space ].
Usage:
	Val  specify the value which we are going to validate.

if(!noSplCharsExSpace(frm.name.value))
return;
*/	
function noSplCharsExSpace(Val)
{
	var alp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";

	for (var i=0;i<Val.value.length;i++){
		temp=Val.value.substring(i,i+1);
		if (alp.indexOf(temp)==-1){
			alert("No special characters \nValid entries are [a-z][A-Z][0-9][ space ]");
			Val.focus();
			return false;
		}
	} // closing the for loop
	return true;
} // closing the function SplCharactersSpace()

/*

19. FUNCTION SPLNUMBERS(element) 

if(!SplNumbers(frm.num.value))
return;
*/
	
function SplNumbers(Val)
{
	var alp = "0123456789+-";
	for (var i=0;i<Val.value.length;i++)
	{
		temp=Val.value.substring(i,i+1);
		if (alp.indexOf(temp)==-1)
		{
			alert("No special characters \nValid entries are [0-9][ + - ]");
			Val.focus();
			return false;
		}
	} // closing the for loop
	return true;
} // closing the function SplNumbers()

/*
20.
	This function checks if the characters in a given text are part of a given character set.

	INPUT:	Text ti be verified [txt]
				String of character that forms the reference [charset]

	OUTPUT: Returns true if all of the characters in txt are part of charset, else false.

	USAGE:
	for example:

		checkInCharSet( "guru", "aeiouAEIOU" ) this fucntion returns false as "guru" contains 'g' and 'r'
		whcih are not part of "aeiouAEIOU".

		checkInCharSet( "abC", "abcdefABCDEF" ) this statement returns true as all "abC" contains characters
		that are present in "abcdefABCDEF"
*/
function checkInCharSet(txt, charset)
{
	var b = true;
	for(i = 0; i < txt.length; i++ )
	{
		if( charset.indexOf(txt.charAt(i)) == -1 )
		{
			b = false;
		}
	}
	return b;
}

/*
21. GET SELECTED INDEX
This can used while validating radio button groups. 
If none of the buttons is selected then the function	
returns -1 else the id.

E.g: frm is the name of a form and radSearchType is the radiobutton group name.

if( getSelectedIndex(frm.radSearchType) == -1 )
{
	alert("Please select search type." );
	frm.radSearchType[0].focus();
	return;
}

*/
function getSelectedIndex(radgroup)
{
	/* Returns back the id of selected radio button in a radio button group  */
	var re = -1;
 	if(radgroup.length)   
	{
		for( pe=0; pe < radgroup.length; pe++ )
		{
			if(radgroup[pe].checked)
			{
				re = pe;
			}
		}
	}
	return re;
}

/*
22. TextareaValidation(elem,msg,len)
This function can be used to validate the length of Text area's in forms.
For example...if the value of text area should not exceed 500 characters.

Arguments :
elem : The element(TextArea)
msg : Message to be alerted
	  For example "Description"
len : Noof characters not to be exceeded

E.g: frm is the name of a form and desc is a text area name.

Usage in form: 
if(!isValidTextarea(frm.desc,'Description',500))
return;
*/

function isValidTextarea(elem,msg,len) 
{
	if(elem.value.length > 0)
	{
		if(isBlank(elem.value)) 
		{
			alert("Please enter the value");
			elem.focus();
			return false;
		}
		else if(elem.value.length > len) 
		{
			alert(msg+" should not exceed "+len+" characters");
			elem.focus();
			return false;
		}	
	}
	return true;
} // closing the function TextareaValidation()

	/**
	 FUNCTION GENVALIDATION(element.message1,message2,spl) 
	 **/
	
	function GenValidation(Element,MessageLen0,MessageLen4,spl) {
		
		if(MessageLen0.length != 0)
		{
			if(Element.value.length == 0)
			{
				alert("Please Enter "+ MessageLen0+".");
				Element.focus();
				return 0;
			}
			else if(isBlank(Element.value))
			{
				alert("Please enter "+ MessageLen0+".");
				Element.focus();
				return 0;
			}
		}
	
		if(MessageLen4.length != 0)
		{
			if(Element.value.length < 4)
			{
				alert( MessageLen4 + " should be more than 4 characters");
				Element.focus();
				return 0;
			} // closing the if - else condtion for if(MessageLen4.length != 0)
		}
	
		if(spl == "spl")
		{
			if(SplCharacters(Element) == 0)
			return 0;
		}
		else if(spl == "space")
		{
			if(SplCharactersSpace(Element) == 0)
			return 0;
		}
	} // closing the function GenValidation()

function isValidPrice(element, msg, required)
{  
	var VarNumber = element.value;
	if(VarNumber == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}
	if (VarNumber != "")
	{
		var Num;
		Num=VarNumber;
		var valid = "0123456789.";
		var hyphencount = 0;
		
		for (var i=0; i < Num.length; i++) 
		{
			temp = "" + Num.substring(i, i+1);
			if (valid.indexOf(temp) == "-1")
			{
			  alert("Invalid characters in your "+msg+".  Please try again.");
			  element.focus();
			  return false;
			}
	   } // end for loop
	   
		if(VarNumber < 1)
		{
			alert(msg+" is not a valid number");
			element.focus();
			return false;
		}
    }   // end if
    return true; 
}  // end function

// for validation of radio buttons
function isRadioCheck(element,msg)
{
	flag = 0;
	for(var i = 0; i<element.length; i++)
	{
		if(element[i].checked == true)
		flag = 1 ;
	}
	if(!flag)
	{
		alert("Please choose the "+msg);
		return false;
	}
	else
		return true;
}

/*
ALPHA VALIDATION with out period(.)
//to find if the field contains alphabets only
usage:
Element  name of the control, like frm.firstname
Message  Field Name that we want to display in alert message.
Required  Set this to yes if the field is mandatory, otherwise no.

 if(!isValidPureAlphabet(frm.firstname,'First Name','yes'))
 return;
*/

function isValidPureAlphabet(element, msg, required)
{
	var i=0;
	var ValidData="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_- ";
	var Data=element.value;
	if(element.value == "")
	{
		var rval = trim(required);
		if (rval.toLowerCase() == "yes" || rval == 1)
		{
			alert("Please enter "+msg);
			element.focus();
			return false;
		}
	}	
	if(element.value != "")
	{
		for(i=0;i<Data.length;i++)
		{
			if(ValidData.indexOf(Data.charAt(i))==-1)
			{
				alert("PLease enter Non-Numeric Data Only");
				element.focus();
				return false;
			}
		}
	}
    return true;
}

function keypress_int(e) {
	var key;
	var keychar;
	var reg;
	
	if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = e.keyCode; 
	}
	else if(e.which) {
		// netscape
		key = e.which; 
	}
	else {
		// no event, so pass through
		//return true;
	}
  keychar = String.fromCharCode(key);
  if(key == 8 || typeof(key) == 'undefined')
  	return true;
  if(!isInteger(keychar))
    		return false; // cancel event otherwise
}

function isInteger(s){
	var alp = "0123456789";
	for (var i=0;i<s.length;i++)
	{
		var c = s.charAt(i);
		temp=c.substring(i,i+1);
		if (alp.indexOf(temp)==-1)
			return false;
	} // closing the for loop
	return true;
}

function isUrlType(obj) {
	var regexphttp = /(.){0,}?http:\/\/?(.){0,}/;
	var regexpwww = /(.){0,}?w{3}?(.){0,}/;
 	if(regexphttp.test(obj.value) || regexpwww.test(obj.value))
	{
		alert("Should not be Allow the URLs");
		obj.focus();
		return false;
	}
	return true;
}
//Contador de caracteres.
function checkChar(obj, msg, maxchars) 
{
  var longitud=maxchars - obj.value.length;
  if(longitud <= 0) 
  {
    alert(msg+" should not exceeded more than "+maxchars+" chars");
	obj.value=obj.value.substr(0,maxchars-1);
	return false;
  }
  return true;
}

function $(id) { return document.getElementById(id); }

function dataLoading(id,str){
	$(id).innerHTML = '<table align="center" width="80%" cellpaddin="0" cellspacing="0" border="0"><tr><td style="border:2px solid #336699; color:#FF8400; FONT-WEIGHT: bold; FONT-SIZE: 12px;" valign="middle" align="center" style="padding:5px;" height="50"><img src="images/loading.gif" width="25" title="Loading...." alt="Loading...." align="absmiddle">&nbsp;&nbsp;&nbsp;&nbsp;'+str+'</td></tr></table>';
}

//function to show or hide a div
function fnToggleDisplay(showdiv,hidediv)
{
	if(hidediv != '' && typeof(document.getElementById(hidediv)) != 'undefined' && document.getElementById(hidediv) != null)
		document.getElementById(hidediv).style.display = 'none';
	if(showdiv != '' && typeof(document.getElementById(showdiv)) != 'undefined' && document.getElementById(showdiv) != null)
		document.getElementById(showdiv).style.display = 'block';
}


function centerOfTheScreen(){
	if(window.innerWidth)
		scwidth = window.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth)
		scwidth = document.documentElement.clientWidth;
	else if (document.body)
		scwidth = document.body.clientWidth;
	
	var scro = getScrollXY();
	if(window.innerHeight)
		scheight = window.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		scheight = document.documentElement.clientHeight;
	else if (document.body)
		scheight = document.body.clientHeight;	
	var scdimensions = {'width':scwidth, 'height':parseInt(scro[1])+parseInt(scheight/2)};
	return scdimensions;
}


function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	var scrollArray = [scrOfX, scrOfY];
	
	return scrollArray;
}

var ZINDEX = 100;
function dragOBJPop(obj,e) {
	
	var pw = getObjectForDrag(obj);
	pw.style.zIndex = 10001;
	function drag(e) { 
	if(!stop) { 
 	wd = screenwidth();
  	ht = 800;
  	if(xyCoord(e,1) < 20 || xyCoord(e) < 20) return; 
	
	pw.style.top=(tX=xyCoord(e,1)+oY-eY+'px'); pw.style.left=(tY=xyCoord(e)+oX-eX+'px'); } }
  	var oX=parseInt(pw.style.left),oY=parseInt(pw.style.top),eX=xyCoord(e),eY=xyCoord(e,1),tX,tY,stop = 0;
  	document.onmousemove=drag; document.onmouseup=function(){ stop=1; document.onmousemove=''; document.onmouseup=''; };
}

function screenwidth()
{
	if(window.innerWidth)
  		wwidth = window.innerWidth;
 	else if (document.documentElement && document.documentElement.clientWidth)
  		wwidth = document.documentElement.clientWidth;
 	else if (document.body)
  		wwidth = document.body.clientWidth;	
  	return wwidth;
}

function getObjectForDrag(v) { return(document.getElementById(v)); }
function agentpop(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function xyCoord(e,v) { return(v?(agentpop('msie')?event.clientY+document.body.scrollTop:e.pageY):(agentpop('msie')?event.clientX+document.body.scrollTop:e.pageX)); }

function validate_login()
{
	frm = document.loginfrm1;
	if(frm.txtemail.value == '')
	  {
		alert("Please Enter User ID");
		frm.txtemail.focus();
		return false;
	  }
	  if(frm.txtemail.value.length < 3 )
	  {
		alert("Please Enter A Valid User ID, It Should be more than 2 characters");
		frm.txtemail.focus();
		return false;
	  }
	  
	 if(frm.txtpass.value == "")
	{
	alert("enter your Password ");
	frm.txtpass.focus();
	return false;
	}
	
	if(frm.txtpass.value.length < 3 )
	{
  		alert("Password should be more than 2 characters");
		frm.txtpass.focus();
		return false;
	}
	if(frm.txtcat.selectedIndex == 0)
	{
		alert("Select Your Login Category");
		frm.txtcat.focus();
		return false;
	}
return true;	
}
