/**
 * @Code by Faiz <faiz777@gmail.com>
 * @Code by Bineesh<binbee13@gmail.com>
 * @Code by Renish<arenishr@gmail.com>
 * For Sesame Software Solution Pvt Ltd, Calicut
 * (c) All Rights Reserved
 * Last Updated on 2009 January 20
 */
window.onload = attachFormHandlers;
var scripts = document.getElementsByTagName('script')[0];
spath = scripts.src; 
spath=spath.replace("/validate.js","");//alert(spath);
if(spath == "validate.js")
{
	spath = "";
}
else
{
	spath=spath + "/";
}

var gShow; //variable holding the id where feedback will be sent to.
var sUrl = spath+"formvalidation.php?validationtype=ajax&val=";//url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
var gErrors = 0; //number of errors is set to none to begin with
var http = getHTTPObject();//don't worry about this
var obj;
var ErrCount=0;
var errStr="";
var solve;
var form2;
document.write('<link href="'+spath+'ajax2.css" rel="stylesheet" type="text/css" />');

function attachFormHandlers()
{
	if (document.getElementsByTagName)//make sure were on a newer browser
	{
		objInput = document.getElementsByTagName('input');
		for (var iCounter=0; iCounter<objInput.length; iCounter++)
		objInput[iCounter].onblur = function(){return validateMe(this);} //attach the onchange to each input field
		
		objInputSelect = document.getElementsByTagName('select');
		for (var iCounter1=0; iCounter1<objInputSelect.length; iCounter1++)
		objInputSelect[iCounter1].onblur = function(){return validateSelector(this);} //attach the onchange to each input field
		
		objInputSelect = document.getElementsByTagName('textarea');
		for (var iCounter1=0; iCounter1<objInputSelect.length; iCounter1++)
		objInputSelect[iCounter1].onblur = function(){return validateSelector(this);} //attach the onchange to each input field
	}
	//form.onsubmit = function(){return validate();} //attach validate() to the form

	
}
/*validateMe is the function called with onblur each time the user leaves the input box
passed into it is the value entered, the rules (which you could create your own), and the id of the area the results will show in*/
function validateSelector(objInputSelect) {
	obj=objInputSelect;
	
	if(obj.lang =='required')
	{
			sVal = obj.value;
			sName = obj.name;
			brwIE =/MSIE (\d+\.\d+);/.test(navigator.userAgent);//Check the Browser is  IE or not
			if (!brwIE)
			 {
				var numericExpression = /#/;
				if(sVal.match(numericExpression)){
					objInput.value = objInput.value.replace("#","");
					//objInput.value = objInput.value.replace("#","");
					//alert('# is not allowed in Firefox!');
					//return false;
				}
			 }
			 
			if(obj.title =="")
			{
				sTitle = obj.name; // Getting Title of Field
			}
			else
			{
				sTitle = obj.title; // Getting Title of Field	
			}
			
			sRequired = 'required'; // determines if field is required or not
			sTypeCheck = "none"; //typecheck are additional validation rules (ie. email, phone, date)
			gShow = "usermsg"; //gShow is the td id where feedback is sent to
			
			http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck + "&sTitle=" + sTitle, true);
			//http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck + "&sTitle=" + sTitle + "&sName=" + sName , true);
			http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
			http.send(null);
			
		
	}
}

function validateMe(objInput) {
	obj=objInput;
	sVal = objInput.value;//get value inside of input field
	brwIE =/MSIE (\d+\.\d+);/.test(navigator.userAgent);//Check the Browser is  IE or not
	if (!brwIE)
	 {
		 
			var numericExpression = /#/;
			if(sVal.match(numericExpression)){
				objInput2.value = objInput2.value.replace("#","");
				//objInput.value = objInput.value.replace("#","");
				//alert('# is not allowed in Firefox!');
				//return false;
			}
	 }
	
	if(objInput.alt != ''){
		
		sName = objInput.name;
		//sTitle = objInput.title; // Getting Title of Field
		if(objInput.title =="")
		{
			sTitle = objInput.name; // Getting Title of Field
		}
		else
		{
			sTitle = objInput.title; // Getting Title of Field	
		}
		
		sRules = objInput.alt.split('|'); // get all the rules from the input box alt values//classname
		switch(sRules[0])
		{
			case 'email' 	:
								req = 'email';
								ftype = "email";
								msgtype = "emailmsg";
								break;
			case 'password' :
								req = 'password';
								ftype = "password";
								msgtype = "msg";
								break;
								
			case 'number'   :
								req = 'number';
								ftype = "number";
								msgtype = "msg";
								break;
								
			case 'amount'   :
								req = 'amount';
								ftype = "amount";
								msgtype = "msg";
								break;
			
			case 'alphanumeric'   :
								req = 'alphanumeric';
								ftype = "alphanumeric";
								msgtype = "msg";
								break;
			case 'username' :
								req = 'username';
								ftype = "username";
								msgtype = "msg";
								break;						
			case 'date' :
								req = 'date';
								ftype = "date";
								msgtype = "msg";
								break;
			case 'limit18' :
								req = 'limit18';
								ftype = "limit18";
								msgtype = "msg";
								break;
			
			case 'required' :		
								if(sRules[1]== 'email')
								{
									req = 'required';
									ftype = "email";
									msgtype = "emailmsg";
								}
								else if(sRules[1]== 'limit18')
								{
									req = 'required';
									ftype = "limit18";
									msgtype = "msg";
								}
								else if(sRules[1]== 'amount')
								{
									req = 'required';
									ftype = "amount";
									msgtype = "msg";
								}
								else if(sRules[1]== 'password')
								{
									req = 'required';
									ftype = "password";
									msgtype = "msg";
								}
								else if(sRules[1]== 'number')
								{
									req = 'required';
									ftype = "number";
									msgtype = "msg";
									
								}
								else if(sRules[1]== 'date')
								{
									req = 'required';
									ftype = "date";
									msgtype = "msg";
									
								}
								else if(sRules[1]== 'username')
								{
									req = 'required';
									ftype = "username";
									msgtype = "msg";
									
								}
								else if(sRules[1]== 'alphanumeric')
								{
									req = 'required';
									ftype = "alphanumeric";
									msgtype = "msg";
									
								}
								else
								{
									req = 'required';
									ftype = "none";
									msgtype = "usermsg";
								}
							break;
				default  :
								req = 'required';
								ftype = "none";
								msgtype = "usermsg";
		}
		
		sRequired = req; // determines if field is required or not
		sTypeCheck = ftype; //typecheck are additional validation rules (ie. email, phone, date)
		gShow = msgtype; //gShow is the td id where feedback is sent to.
	  
		//sends the rules and value to the asp page to be validated
		http.open("GET",sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck + "&sTitle=" + sTitle, true);
		
		//http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck + "&sTitle=" + sTitle + "&sName=" + sName , true);
	  	http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
		http.send(null);  
	}
}


function handleHttpResponse() 
{
	//if the process is completed, decide to do with the returned data
	if (http.readyState == 4) 
  	{
		sResults = http.responseText.split(","); //results is now whatever the feedback from the asp page was
		var spans = obj.parentNode.getElementsByTagName('span');
		var numspans=spans.length;
		for (var a = 0; a < numspans; ++a) {
			obj.parentNode.removeChild(spans[a]);
		} 	
		var newdiv = document.createElement('span');
		
		if (sResults[0] =='Accepted')
		{
			newdiv['className']="ajax-SesameForm-success";
		}
		else if (sResults[0] =='')
		{
		
		}
		else
		{
			newdiv['className']="ajax-SesameForm-error";
		}
		
		newdiv.innerHTML = sResults[0];
		obj.parentNode.appendChild(newdiv);
		
  	}
}

function validate(fname)
{
	//alert(fname);
	//var frmname = fname.id;//alert((fname)[3]);
	var frmname = fname;
	
	/*objInput = document.forms[frmname].getElementsByTagName('input');
	alert(objInput.length);*/
	//objInput = document.fo;alert(objInput.length);
	err_count =0;
	
	
	
	//var form = document.getElementsByTagName('form')[0] ;//alert(form);//Getting form Name
	//var form = document.getElementById('form') ;alert(form);
	if (document.forms[frmname].getElementsByTagName)//make sure were on a newer browser
	{
		var emsg = "";
		//objInput33 = document.forms[frmname].getElementsByTagName('form');
		//alert(objInput33.length);
		objInput = document.forms[frmname].getElementsByTagName('input');
		objInput1 = document.forms[frmname].getElementsByTagName('select');
		objInput2 = document.forms[frmname].getElementsByTagName('textarea');
		pagename = document.getElementsByTagName('title');
		
		pname = pagename[0].innerHTML;
		var field_type ; //= true;
		for (var iCounter=0; iCounter<objInput.length; iCounter++)
		{
			
			//sTitle = objInput[iCounter].title;
			if(objInput[iCounter].title == "")
			{
				sTitle = objInput[iCounter].name;
			}
			else
			{
				sTitle = objInput[iCounter].title;
			}
			altval = objInput[iCounter].alt.split('|');
			field_req = altval[0];
			
			
		if(field_req != "required")
		  {
			field_type = submitvalidation(field_req,objInput[iCounter].value);
			if(field_type == false)
			 {
			 	  err_count = err_count +1;
				  emsg = emsg +'<img src="'+spath+'images/unchecked.gif" style="border:none;" />&nbsp;'+ sTitle+'&nbsp;'+"Required<br>";
								  
			 }
			 
		  }	
			
			
		else if(field_req == "required" && altval[1] == "")
		  {
			 if(field_req == "required" && objInput[iCounter].value =="" || objInput[iCounter].value =="0000-00-00" )
			 {
			 	  err_count = err_count +1;
				  emsg = emsg +'<img src="'+spath+'images/unchecked.gif" style="border:none;" />&nbsp;'+ sTitle+'&nbsp;'+"Required<br>";
								  
			 }
			  
		  }
		else if(field_req == "required" && altval[1] != "" )
		 {
			
		  	field_type = submitvalidation(altval[1],objInput[iCounter].value);
			if(field_req == "required" && objInput[iCounter].value =="" || objInput[iCounter].value =="0000-00-00" || field_type == false)
			 {
			 	  err_count = err_count +1;
				  emsg = emsg +'<img src="'+spath+'images/unchecked.gif" style="border:none;" />&nbsp;'+ sTitle+'&nbsp;'+"Required<br>";
								  
			 }
			 
		  }
		 
		  
			
			
			
		} 
		
		for (var iCounter1=0; iCounter1<objInput1.length; iCounter1++)
		{
			//sTitle1 = objInput1[iCounter1].title;
			if(objInput1[iCounter1].title == "")
			{
				//sTitle = objInput[iCounter].name;
				sTitle1 = objInput1[iCounter1].name;
			}
			else
			{
				sTitle1 = objInput1[iCounter1].title;
			}
			langval = objInput1[iCounter1].lang;
			if(langval == "required" && objInput1[iCounter1].value =="")
			{
				err_count = err_count +1;
				 emsg = emsg +'<img src="'+spath+'images/unchecked.gif" style="border:none;" />&nbsp;'+ sTitle1+'&nbsp;'+"Required<br>";
				
			}
		
		} 
		for (var iCounter2=0; iCounter2<objInput2.length; iCounter2++)
		{
			//sTitle2 = objInput2[iCounter2].title;
			if(objInput2[iCounter2].title == "")
			{
				
				sTitle2 = objInput2[iCounter2].name;
			}
			else
			{
				sTitle2 = objInput2[iCounter2].title;
			}
			langval2 = objInput2[iCounter2].lang;
			if(langval2 =="required" && objInput2[iCounter2].value =="")
			{
				err_count = err_count +1;
				emsg = emsg +'<img src="'+spath+'images/unchecked.gif" style="border:none;" />&nbsp;'+sTitle2+'&nbsp;'+"Required<br>";
			}
			
		} 
		
		if(err_count >0){ 
		
				 var width = document.documentElement.clientWidth + document.documentElement.scrollLeft;
				  var layer = document.createElement('div');
				  layer.style.zIndex = 2;
				  layer.id = 'layer';
				  layer.style.position = 'absolute';
				  layer.style.top = '0px';
				  layer.style.left = '0px';
				  layer.style.height = document.documentElement.scrollHeight + 'px';
				  layer.style.width = width + 'px';
				  layer.style.backgroundColor = 'transparent';
				  layer.style.opacity = '.6';
				  layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
				  document.body.appendChild(layer);
				
				  var div = document.createElement('div');
				  div.style.zIndex = 3;//3
				  div.id = 'box';
				  div.style.position = (navigator.userAgent.indexOf('MSIE 6') > -1) ? 'absolute' : 'fixed';
				 
				 
				  div.style.top = '80px';
				  //div.style.left = (width / 2) - (400 / 2) + 'px'; 
				  //div.style.left = '200px'; 
				  div.style.right = '300px'; 
				  // div.style.height = hi;
				  div.style.width = '300px';
				  div.style.backgroundColor = '#FFFFCC';
				  div.style.border = '1px solid silver';
				  div.style.padding = '3px';
				  
				  document.body.appendChild(div);
				 //hh = '&nbsp;&nbsp;&nbsp;'+pname+'';
				 hh = '&nbsp;&nbsp;&nbsp;Error Summary';
				 ht ='<table width=100%><tr>';
				 ht+='<td valign="top" align="left" style="text-align:left;font-size:12px;color:#0000CC;vertical-align:text-top;">'+hh+'</td>';
				 ht+='<td id="closetd" valign="top" align="right" style="text-align:right;font-size:12px;color:#0000CC;vertical-align:text-top;cursor:pointer;">Close</td>';
				 ht+='</tr></table>';
				  var c = document.createElement('span');
				 // c.innerHTML = '<div style="text-align:right;font-size:12px;color:#0000CC;vertical-align:text-top;"><b>Close</b></div>';
				  c.innerHTML = ht;
				  div.appendChild(c);
				  
				  var d = document.getElementById('closetd');
				  d.href = 'javascript:void(0)';
				  d.onclick = function()
				  {
					document.body.removeChild(document.getElementById('layer'));
					document.body.removeChild(document.getElementById('box'));
				  };
				  
				  var p = document.createElement('span');
				  p['className']="error";
				  //h = '<div style="text-align:left"><img src="images/error1.gif" />&nbsp;&nbsp;&nbsp;<b>'+pname+'</b></div><br>';
				  h = '<div style="text-align:center;padding-right:30px;font-size:14px"><img src="'+spath+'images/error2.gif" style="border:none;" />&nbsp;&nbsp;Following errors are occured!</div>';
				 // h += 'Following errors are occured!';
				  p.innerHTML = h;
				  div.appendChild(p);
				  
				  var a = document.createElement('span');
				  iht ='<table width=90%><tr>';
				  iht+='<td valign="top" align="right">&nbsp;&nbsp;&nbsp;</td>';
				  iht+='<td valign="top" align="left" style="padding-left:25px;font-size:12px;">'+emsg+'</td>';
				  iht+='</tr></table><br>';
				 
				  a['className']="error";
				  //a.innerHTML = '<br>'+emsg;
				   a.innerHTML = iht;
				  div.appendChild(a);
				  
				  return false;
			}
		
		
		
	}

}


function submitvalidation(content,inputval)
{

			if(inputval =="")
			 {
				  return true;
			 }
			  
			 	switch(content)
			  	{ 
				  case 'email' :  
								  
								  
								  var emailFilter=/^.+@.+\..{2,3}$/;
									if (!(emailFilter.test(inputval)))
									{ 
									  // field_type =false;
									   return false;break;
									}
									else
									{
										//test email for illegal characters
										var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/;
										if (inputval.match(illegalChars)) 
										{
											 //field_type =false;break;
											 return false;break;
										}
									}
				 					return true;
				  case 'password' :  
								   
										var illegalChars = /[\W_]/;
										a = inputval;
									    if ((a.length < 5 )|| (a.length > 18)) 
										{
											 //field_type =false;break;
											 return false;break;
										}
										else if (illegalChars.test(inputval))
										//if (objInput[iCounter].value.match(illegalChars)) 
										{
											 //field_type =false;break;
											 return false;break;
										}
										return true;
				case 'username' :  
								   
										var illegalChars = /\W/; 
										a = inputval;
									    if ((a.length < 5)) 
										{
									       //field_type =false;break;
										   return false;break;
    									}
										else if(illegalChars.test(a))
										{
											 //field_type =false;break;
											 return false;break;
										}
										return true;
										
				case 'limit18' :  
								   
									a = inputval;
									d = a.split('-');
									var cur_date = new Date()
									var cur_year = cur_date.getFullYear();
									var cur_month = cur_date.getMonth();
									var cur_day = cur_date.getDate();
									
									
									var year_dif = cur_year - d[0];
									var month_dif = cur_month - d[1];
									var day_dif = cur_day - d[2];
									
									/*for (i = 0; i < d[0].length; i++)
									{   
											// Check that current character is number.
											var c = d[0].charAt(i);
											if(c < 0 || c >9)
											{
												 return false;break;
											}
											
									}*/
									
									if(day_dif < 0 || month_dif < 0)
									{
										age = year_dif -1;
									}
									else
									{
										age = year_dif;
									}
									
									if ((a.length != 10)) 
									{
									     //field_type =false;break;
										 return false;break;
    								}
									
									/*if((d[0].length != 4))
									{
										return false;break;
									}*/
									
									if(age < 18)
									{
										return false;break;
									}
								
											
										
										
				case 'alphanumeric' :  
								   
										var numaric = inputval;
										for(var j=0; j<numaric.length; j++)
										{
											 var alphaa = numaric.charAt(j);
											 var hh = alphaa.charCodeAt(0);
											 if((hh > 47 && hh<58) || (hh > 64 && hh<91) || (hh > 96 && hh<123))
											  {
												  	//field_type =true;break;
													return true;break;
											  }
											else
											{
												 //field_type =false;break;
												 return false;break;
											}
										}
									 return true;
				case 'date' :  
								   																	
									a = inputval;
									if ((a.length != 10)) 
									{
									       //field_type =false;break;
										   return false;break;
    								}
									else
									{
										d = a.split('-');
										for (i = 0; i < d[0].length; i++)
										{   
											// Check that current character is number.
											var c = d[0].charAt(i);
											if(c < 0 || c >9)
											{
												 return false;break;
											}
											else if(d[0].length != 4)
											{
												 return false;break;
											}
										}
									}
																		
									return true;
										
					
					case 'amount' :  
								   
										a = inputval;
										for (i = 0; i < a.length; i++)
										{   
											// Check that current character is number.
											var c = a.charAt(i);
											
											if(c != ".")
											{
												if (( (c < "0") || (c > "9") ))
												{
												 	//field_type =false;break;
													 return false;break;
												}
											}
											
										}
									return true;
					
								
					case 'number' :  
								   
										a = inputval;
										for (i = 0; i < a.length; i++)
										{   
											// Check that current character is number.
											var c = a.charAt(i);
											if (((c < "0") || (c > "9")))
											{
												 //field_type =false;break;
												 return false;break;
											}
											
										}
									return true;
									
									
			  
			 //
			}



}



function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try 
		{
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
		xmlhttp = false;
		}
	}
	return xmlhttp;
}

