//Form validations	
var isW3C = (document.getElementById) ? true : false;
var isAll = (document.all) ? true : false;
var sumMsg = "";
var _reqC = new Array();
var _reqM = new Array();

function GetControl(elemID) 
{
    var elem = (isW3C) ? document.getElementById(elemID) : ((isAll) ? document.all[elemID] : null);
    
    return elem;
}

function reqAdd(ctl, msg)
{
	var len = _reqC.length;
	
	_reqC[len] = ctl;
	_reqM[len] = msg;
}

function validateReqs()
{
	var retval = false;
	var errmsg = "";
	
	if (_reqC.length == _reqM.length)
	{
		for (var i=0; i<_reqC.length; i++)
		{
			var cntl =  GetControl(_reqC[i]);
			if (cntl == "undefined" || cntl.value == null || cntl.value.length == 0 || isBlank(cntl.value))
			{
				errmsg += "- " + _reqM[i] + "\n";
			}
		}
		
		if (errmsg != "")
		{
			errmsg = sumMsg + errmsg;
			alert(errmsg);
			Page_IsValid = false;
		}
		else
		{
			Page_IsValid = true;
			retval = true;
		}
	}
	else
	{
		alert("!!ERROR cannot validate nulls");
	}
	
	return retval;
}


function FindErrorDiv()
{	var sDivName;
	for(i=0;i<document.getElementsByTagName("div").length;i++)
	{
		sDivName=document.getElementsByTagName("div")[i].id;
		if (sDivName.indexOf('_errorMsg') != -1)
			return document.getElementsByTagName("div")[i];
	}
}
function daysInFebruary (year){
     // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
     for (var i = 1; i <= n; i++) {
          this[i] = 31;
          if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
          if (i==2) {this[i] = 29;}
   } 
   return this;
}

function CheckDate(sControlId){
	var dtCh= "/";
	var minYear=2004;
	var maxYear=2100;
	var dtStr=document.forms[0].elements[sControlId].value;
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		return "The date format should be : mm/dd/yyyy";
		}
	if (strMonth.length<1 || month<1 || month>12){
		return "Please enter a valid month";
		}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return "Please enter a valid day";
		}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return "Please enter a valid 4 digit year between "+minYear+" and "+maxYear;
		
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return "Please enter a valid date";
		}
return "";
}

//Added for only for wwwroot
function ValidationObject()
{   
	this.id='0'; 
	this.required = false;   
	this.type = 'element';   
	this.range_1 = 0;  
	this.range_2=0; 
	this.dependant=null; 
	this.name = 'test';  
	this.customscript = '';  
	this.formatstring='';
	this.minlength=0; 
	this.maxlength=0; 
	this.compare_operator=''; 
}


function DisplayError(sMessage,objErrorDiv)
{
	objErrorDiv.className="ReqHdr1";
	objErrorDiv.style.visibility="hidden";
	objErrorDiv.innerHTML=sMessage;
	objErrorDiv.style.visibility="visible";
	window.scrollTo(0,0); //scrolls page to the error label
}

function CheckFormatString(objControl)
{
	if (this["obj_valid_" + objControl.id]==null || objControl.value=='' || this["obj_valid_" + objControl.id].formatstring == '')
		return false;
	if (objControl.value.search(this["obj_valid_" + objControl.id].formatstring)==-1)
		return false;
	else
		return true;
}

function CheckMinLength(objControl)
{
	if (this["obj_valid_" + objControl.id]==null || objControl.value=='' || this["obj_valid_" + objControl.id].minlength==0)
		return false;
	if (objControl.value.length < this["obj_valid_" + objControl.id].minlength)
		return true;
	else
		return false;
}

function CheckMaxLength(objControl)
{
	if (this["obj_valid_" + objControl.id]==null || objControl.value=='' || this["obj_valid_" + objControl.id].maxlength==0)
		return false;
	if (objControl.value.length > this["obj_valid_" + objControl.id].maxlength)
		return true;
	else
		return false;
}

function CheckRange(objControl)
{
	if (this["obj_valid_" + objControl.id]==null || objControl.value=='' || this["obj_valid_" + objControl.id].range_1==0)
		return false;
	if ((objControl.value < this["obj_valid_" + objControl.id].range_1) || (objControl.value > this["obj_valid_" + objControl.id].range_2))
			return true;
	else
			return false;
}

function CheckComparison(objControl)
{
	if (this["obj_valid_" + objControl.id]==null || objControl.value=='' || this["obj_valid_" + objControl.id].comp_operator==null)
		return false;
	return !eval("'" + objControl.value + "' " + this["obj_valid_" + objControl.id].comp_operator + " '" + document.forms[0].elements[this["obj_valid_" + objControl.id].dependant].value + "'");
}

function ColorRed(objControl)
{
	var obj_label=document.getElementById(objControl.id + "_label");
	if (obj_label==null)
		return;
	obj_label.style.color='red';
}

function ValidateAllControls(sFormName)
{
 
var objControl;
var bInValid=false;
var iReqFailures=0;
var iCustFailures=0;
var objErrorDiv;
var sCustomError="";
var sCombinedRequired="";

	sumMsg="";
	objErrorDiv=FindErrorDiv();
	//reset the color for all labels before validating
	
	for(y=0;y<document.forms.length;y++)
	{   
	   for(i=0;i<document.forms[y].elements.length;i++)
	   {
	      var obj_label=document.getElementById(document.forms[y].elements[i].id + "_label") ;
	      if (obj_label != null)
		  {
		  	 obj_label.style.color='';
		  }
	   }
	}
	
	for(j=0;j<document.forms.length;j++)
	{
		if(sFormName!=null && document.forms[j].name!=sFormName)
			continue;	 
	for(i=0;i<document.forms[j].elements.length;i++)
	{	
		objControl=document.forms[j].elements[i];
		
		switch (objControl.type)
		{
			case 'text':case 'password': case 'textarea': case 'hidden':
				bInValid=false;
				bInValid=ValidateRequired(objControl,false);
				if (bInValid)
				{ 
					iReqFailures++;
					if (sCombinedRequired=="")
						sCombinedRequired=this["obj_valid_" + objControl.id].parent;
					else if (sCombinedRequired.indexOf(this["obj_valid_" + objControl.id].parent)==-1)
					{
						sCombinedRequired=sCombinedRequired + " and " + this["obj_valid_" + objControl.id].parent;
					}
					ColorRed(objControl);

					if (this["dual_controls"])
						sumMsg=sumMsg + "Please enter your " + this["obj_valid_" + objControl.id].title + " for the " + this["obj_valid_" + objControl.id].parent + ".<br/>";
					else
						sumMsg=sumMsg + "Please enter your " + this["obj_valid_" + objControl.id].title + ".<br/>";
				}
				else
				{	
					bInValid=CheckMinLength(objControl);
					if (bInValid)
					{	
						ColorRed(objControl);
						if (this["dual_controls"])
							  sumMsg=sumMsg + this["obj_valid_" + objControl.id].parent + ": ";
							sumMsg=sumMsg + "The " + this["obj_valid_" + objControl.id].title + " should be at least " + this["obj_valid_" + objControl.id].minlength + " characters for the " + this["obj_valid_" + objControl.id].parent + ".<br/>";
						continue;
					}
					bInValid=CheckMaxLength(objControl);
					if (bInValid)
					{	ColorRed(objControl);
						if (this["dual_controls"])
							sumMsg=sumMsg + this["obj_valid_" + objControl.id].parent + ": ";
						sumMsg=sumMsg + "The " + this["obj_valid_" + objControl.id].title + " should not be greater than " + this["obj_valid_" + objControl.id].maxlength + " characters.<br/>";
						continue;
					}
					bInValid=CheckFormatString(objControl);
					if (bInValid)
					{	
						ColorRed(objControl);
						if (this["dual_controls"])
							sumMsg=sumMsg + this["obj_valid_" + objControl.id].parent + ": ";
						sumMsg=sumMsg + "The " + this["obj_valid_" + objControl.id].title + " is not in the correct format.<br/>";
						continue;
					}
					bInValid=CheckRange(objControl);
					if (bInValid)
					{	ColorRed(objControl);
						if (this["dual_controls"])
							sumMsg=sumMsg + this["obj_valid_" + objControl.id].parent + ": ";
						sumMsg=sumMsg + "The " + this["obj_valid_" + objControl.id].title + " does not fall in the expected range.<br/>";
						continue;
					}
					sCustomError=ValidateCustomized(objControl);
					if (sCustomError.length > 0)
					{	
						ColorRed(objControl);
						if (this["dual_controls"])
						{
							sumMsg=sumMsg + sCustomError + " for the " + this["obj_valid_" + objControl.id].parent + ".<br/>";
						}
						else
						{
							sumMsg=sumMsg + sCustomError + "<br/>" ;
						}
						continue;
					}
					bInValid=CheckComparison(objControl);
					if (bInValid)
					{	ColorRed(objControl);
						sCompText="";
						switch(this["obj_valid_" + objControl.id].comp_operator)
						{case "==":
							sCompText=" you entered do not match. Please re-enter your ";
							break;
						case "<=":
							sCompText=" not less than or equal to ";
							break;
						case "!=":case "<>":
							sCompText=" is equal to ";
							break;
						case ">=":
							sCompText=" not greater than or equal to ";
							break;	
						case "<":
							sCompText=" not less than ";
							break;
						case ">":
							sCompText=" not greater than ";
							break;
						}
						sCompText=sCompText + this["obj_valid_" + this["obj_valid_" + objControl.id].dependant].title;
						ColorRed(document.forms[0].elements[this["obj_valid_" + objControl.id].dependant]);
						if (this["dual_controls"])
							sumMsg=sumMsg + "The " + this["obj_valid_" + objControl.id].parent + ": ";
						sumMsg=sumMsg + "The " + this["obj_valid_" + objControl.id].title + sCompText + " .<br/>";
						continue;
					}
				}	
			break;
			
			case 'select-one': case 'select-multiple':
				bInValid=ValidateRequired(objControl,true);
				if (bInValid)
				{
					ColorRed(objControl);
					iReqFailures++;
					if (sCombinedRequired=="")
						sCombinedRequired=this["obj_valid_" + objControl.id].parent;
					else if (sCombinedRequired.indexOf(this["obj_valid_" + objControl.id].parent)==-1)
					{
						sCombinedRequired=sCombinedRequired + " and " + this["obj_valid_" + objControl.id].parent;
					}

					if (this["dual_controls"])
					{
						sumMsg=sumMsg + "Please enter your " + this["obj_valid_" + objControl.id].title + " for the " + this["obj_valid_" + objControl.id].parent + ".<br/>";
					}
					else
					{
						sumMsg=sumMsg + "Please enter your " + this["obj_valid_" + objControl.id].title + ".<br/>";
					}

					continue;
				}
				sCustomError=ValidateCustomized(objControl);
				
				if (sCustomError.length > 0)
				{	ColorRed(objControl);
					sumMsg=sumMsg + sCustomError + "<br/>" ;
					continue;
				}
			break;

			case 'radio':
					
				var objCtlInfo=this["obj_valid_" + objControl.id];
				if(objCtlInfo !=null && objCtlInfo.required==true) //If required
				{
					var elementlength = eval("document.forms[j]." + objControl.name + ".length");
					var check = 0;
					var arrObj = eval("document.forms[j]." + objControl.name);
					
					for(k=0;k < elementlength ;k++)
					{
							
						if (arrObj[k].type != 'radio') //recheck it is radio
						{
							break;
						}
						else
						{
							if (arrObj[k].checked)
							{
								check++;
							}
							if (k+1 == elementlength)
							{
								break;
							}
						}
					}
					
					if (check == 0)
					{ 
						//turn label red
						ColorRed(objControl);
						
						iReqFailures++;
						if (sCombinedRequired=="")
						sCombinedRequired=this["obj_valid_" + objControl.id].parent;
						else if (sCombinedRequired.indexOf(this["obj_valid_" + objControl.id].parent)==-1)
						{
							sCombinedRequired=sCombinedRequired + " and " + this["obj_valid_" + objControl.id].parent;
						}

						if (this["dual_controls"])
						{
							sumMsg=sumMsg + "Please select your " + this["obj_valid_" + objControl.id].title + " for the " + this["obj_valid_" + objControl.id].parent + ".<br/>";
						}
						else
						{
							sumMsg=sumMsg + "Please select your " + this["obj_valid_" + objControl.id].title + ".<br/>";
						}

					continue;
					}
				}
				
				sCustomError=ValidateCustomized(objControl);
			
				if (sCustomError.length > 0)
				{	ColorRed(objControl);
					sumMsg=sumMsg + sCustomError + "<br/>" ;
					continue;
				}			
			break;
		
			case 'checkbox':					
								
				var objCtlCBInfo = this["obj_valid_" + objControl.id]; 
				
				if(objCtlCBInfo !=null && objCtlCBInfo.required==true) //If required
				{
				    iReqFailures++;
				    
				    sCustomError=ValidateCustomized(objControl);
				}		
				
				sCustomError=ValidateCustomized(objControl);			
								    
				if (sCustomError.length > 0)
				{	ColorRed(objControl);
					sumMsg=sumMsg + sCustomError + "<br/>" ;
					continue;
				}
			break;
			
			default:
				
		}
	  } //end first for loop
		
	}
	if (iReqFailures > 1)
			{
			DisplayError("Please enter your " + sCombinedRequired.toLowerCase() + ".",objErrorDiv);
			return false;
			}
	
	if (sumMsg !="")
		{//DisplayError("Please correct the following before continuining:<br/>" + sumMsg,objErrorDiv);
		DisplayError(sumMsg,objErrorDiv);
		return(false);
		}
	return true;
	/*if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
		{if(parseInt(navigator.appVersion)==5)
			__doPostBack(objSubmit.name.replace(':','$'),'');
		}
	else
		__doPostBack(objSubmit.id,'');*/
}

function ValidateCustomized(objControl)
{
	if (objControl.value ==null || objControl.value =='' || objControl.selectedIndex==0)
		return "";
	var objCtlInfo=this["obj_valid_" + objControl.id];
		if(objCtlInfo==null || objCtlInfo.customscript=='' )
			return "";
		else
			{	return eval(objCtlInfo.customscript);
			}
	
}

function ValidateRequired(objControl,bSelection)
{
		var objCtlInfo=this["obj_valid_" + objControl.id];
		if(objCtlInfo==null || objCtlInfo.required==false)
			return false;
		else
			if (bSelection)
				{if (objControl.selectedIndex<=0 || objControl.options[objControl.selectedIndex].value==null || objControl.options[objControl.selectedIndex].value=='')
					return true;
				else
					return false;
				}
			else
				return(isBlank(objControl.value));
			
}

function SubmitForm(ispagevalid,nextpage)
{
	if (ispagevalid.toLowerCase() == "true")
	{
		document.Form.action = nextpage;
		document.Form.submit();
	}
}

// Validate phone number format.  Each part of the phone must be the proper
// length and be numeric in value
function isPhone(inPhone1, inPhone2, inPhone3)
{
    // If any part of the phone number is not a number then return false
	if((isNaN(inPhone1) == true)||(isNaN(inPhone2) == true)||(isNaN(inPhone3) == true))
	{
	    return false;
	}

	len = inPhone1.length;
	num = parseInt(inPhone1);
	
	if (len == 3 && (num == 0 || num > 0))
	{
	    len = inPhone2.length;
		num = parseInt(inPhone2);
		
		if (len == 3 && (num == 0 || num > 0))	  
		{
		    len = inPhone3.length;
			num = parseInt(inPhone3);
			
			// if the phone number has repeated digits
			if (isRepeated(inPhone1 + inPhone2 + inPhone3))
			return false;
			
			if (len == 4 && (num == 0 || num > 0))	  
			{
				return true;
			}
			else
			{
			 	return false;
			}
		}   
		else
		{
		    return false;
		}
	} 
	else
	{
	    return false;
 	}
} // End isPhone function


function isBlank(s)
{
	
	var i;
	var blanks = " \t\n\r";
	if ((s == null) || (s.length == 0))
		return true;

	for (i=0; i<s.length; i++)
	{   
		var c = s.charAt(i);
		if (blanks.indexOf(c) == -1) 
		return false;
	}
	return true;
}
	
function stripNonDigits(s) {
	var i;
	var returnString = "";
	var digits = "0123456789";
	
	// Search through string's characters one by one;
	// if character is in bag, append to returnString
	for (i = 0; i < s.length; i++)
	{   
		// Check that current character isn't blank
		var c = s.charAt(i);
		if (digits.indexOf(c) != -1) 
			returnString += c;
	}
	return returnString;
}

function isInteger(s) {
	// skip leading + or -
	if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
		var i = 1;
	else
		var i = 0;

	// Search through string's chars one by one until we find a 
	// non-numeric char, then return false; if we don't, return true
	for (i; i<s.length; i++)
	{   
		// Check that current character is number
		var c = s.charAt(i);
		if (!((c >= "0") && (c <= "9"))) 
			return false;
	}
	// All characters are numbers
	return true;
}

function isUSPhoneNumber(s) 
{ 
	
	if (isBlank(s) || s.charAt(0) == "0" || s.charAt(0) == "1") 
		return false;
	s = stripNonDigits(s);
	return (isInteger(s) && (s.length == 10) && (!isRepeated(s)));
}


function autoTab(chk,len,next)
{
	if (window.event)
	{
		keyPress = window.event.keyCode;
		if((chk.value.length == len) && (keyPress != 16) && (keyPress != 9)){next.focus();}
	}
}

function isRepeated(data)
{	
	// if atleast more than 1 character present 
	// could compare, otherwise no need to compare.
	if (data != null && data.length > 1)
	{
		var cChar = data.charAt(0);
		for (var i=1; i<data.length; i++)
		{
			if (cChar != data.charAt(i))
				return false;
		}
		
		return true;
	}
	
	// if data is null or if one character present
	return false;
	
}
