// ----------------------------------------------------------------
// ----------------------------------------------------------------
//  Copyright 2003 (c) Peach Computers (All rights reserved)
//  MODULE  : validation.js
//  DATE    : 01.01.2004
//  AUTHOR  : Sonal Shah
// ----------------------------------------------------------------
// ----------------------------------------------------------------

//isNS4 = (document.layers) ? true : false;
//isIE = (document.all) ? true : false;
//isNS6 = (document.getElementById && (!document.all)) ? true : false;

function openBrWindow(theURL,winName,features) 
{ 
	window.open(theURL,winName,'top=50,left=50,status=no,scrollbars=yes,resizable=yes,width=600,height=480,titlebar=no');
}	

function openDialogWindow(url, width, height,title)
{
	optionStr = "dialogWidth:" +  width + "px;dialogHeight:" + height + "px;help=no;status:no"
	var retValue = window.showModalDialog(url,title, optionStr);
}


//To validate email address, ready made script
function isValidEmail(strField, msg)
{
	var str=strField.value;	//document.validation.emailcheck.value;
	//var filter = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|\W*|\w*(\.[A-Za-z]\w*)+)$/;
	//orig var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	  var filter= /^.+\@.+\..+$/;
	//var filter= /^(\".*\"|[A-Za-z]\w*)$/i; 
	//@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	
	if (filter.test(str))
		testresults=true;
	else
	{
		alert(msg);
		strField.focus();
		testresults=false;
	}
	return (testresults);
}

//To validate email address, ready made script
function OLDisValidEmail(strField, msg)
{	
	if (strField.value!="")
	{
     emailStr=strField.value;     
    // var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|\W*|\w*(\.[A-Za-z]\w*)+)$/;
	// var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\-\w*(\.[A-Za-z]\w*)+)$/;
var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
		var matchArray = emailStr.match(emailPat);
		if (matchArray == null) 		
		{
			alert(msg);
			strField.focus();
			return false;		
		}
		var IPArray = matchArray[2].match(/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/);
		if (IPArray != null) 
		{
 		  for (var i=1;i<=4;i++) 
  		  {
   		     if (IPArray[i]>255)
     	  	 { 
     	  		alert(msg);
     	  		strField.focus();
				return false;
		     }
 		  }
		}
	}
	return true;	
}

//****************************************************
//Function checks that the the object has value or not
//**************************************************** 
  function isEmpty(txtBox, msg)
  {
	alert("ssss");
    if (trim(txtBox.value) == "")
    {
		alert(msg);
		txtBox.focus();		
		return true;
	}
	return false;
  }
  
   //Function checks the entered value is numeric or not
  function isNumber(obj)
  {   
	if (obj.value != "")
	{
		return (!(isNaN(obj.value)));
	}
	return false;
  }

  //Function checks the entered value is numeric or not
  function isNumberPositive(obj)
  {
    if (isNumber(obj))
    {
		return (eval(obj.value) > 0)
    } 
    return false;
  }

   //Function validates number Object
  function validateNumericObject(frmobj, txtobj)
  {
	if (isNumber(txtobj))
	{
		if (isNumberPositive(txtobj))
		{   
			return true;
		}
	}
	if (txtobj.value != "")
	{
		alert("Please enter valid Number.");
		txtobj.focus();
		txtobj.value = "";	
		return false;
	}
  }

  function isNumberNegative(obj)
  {
    if (isNumber(obj))
    {
		return (eval(obj.value) < 0)
    } 
    return false;
  }

  // Function for formatting the Number
  function FormatNumber(expr, decplaces) 
  {

	var str = "" + Math.round(eval(expr) * Math.pow(10,decplaces));

	while (str.length <= decplaces) 
	{
		str = "0" + str;
	}

	var decpoint = str.length - decplaces;
	return str.substring(0,decpoint) + "." + str.substring(decpoint, str.length);

   } //End function FormatNumber 
   
function MakeAll(Form)
{
	if(Form.selone.value == "SelectAll")
	{
		for (i=0;i< Form.length;i++)		
			if (Form[i].type == "checkbox" )
				Form[i].checked = 1;
		return false;
	}
	if(Form.selone.value == "DeselectAll")
	{
		for (i=0;i< Form.length;i++)		
			if (Form[i].type == "checkbox")
				Form[i].checked = 0;
		return false;
	}
	return true;
}

//------------------------------------------------------------------
// Check all fields which type is text, password and list.
// also check if the back or skip button, return true
//------------------------------------------------------------------

function validation(str)
{
	ret = 0;
	for(var i = 0; i < str.length; i++)
	{
		if ( str[i].type == "hidden" )
		{
			if( str[i].value == "Back" || str[i].value == "Skip" || str[i].value == "Cancel" )
				return true;
		}
	}
	for(var i = 0; i < str.length; i++)
	{
		if (str[i].type == "text" || str[i].type =="password" || 
			str[i].type =="select-one" || str[i].type=="textarea" )
		{
			if(!Check(str[i], str))		return false;
		}
	}
	return true;
}

//------------------------------------------------------------------
// Check if the control has to do validation or not. 
// If yes, to do validation and return error if invalid.  
//------------------------------------------------------------------

function Check(str,fm)
{
	for (var i=0; i < str.id.length; i++)
	{
		var ch = str.id.substring(i, i+1);		
		if( ch == "R" && trim(str.value) == "" )
		{
			alert("Please enter " + str.label );
			str.focus();
			return false;
		}
		else if( ch == "R" && str.type == "select-one" && str.value == "--Select One--" )
		{
			alert("Please select " + str.label );
			str.focus();
			return false;
		}		
		else if ( ch == "P" && !CheckPhoneFormat(str.value) )
		{
			alert("Invalid " + str.label + " format.\nUse one of the following number formats:\n" +
				  "XXXXXXXXXX or XXX-XXX-XXXX or XXX XXX XXXX or (XXX)XXX-XXXX or (XXX)XXX XXXX\n" );
			str.focus();
			return false;
		}
		else if ( ch == "M" && !CheckMailFormat(str.value))
		{
			alert(str.label + ": Invalid Email format!");
			str.focus();
			return false;
		}
		else if ( ch == "Z" && !CheckZipCodeFormat(str.value) )
		{
			alert( str.label + ": Invalid Zip Code format!");
			str.focus();
			return false;
		}
		else if ( ch == "F" && !CheckFederalID(str.value) )
		{
			alert( str.label + ": Invalid federal ID format!");
			str.focus();
			return false;
		}
		else if ( ch == "C"&& !CheckCreditCard(str.value,fm) )
		{
			if(fm.lstMethod.value == "ACH")
			{
				alert( "Account Number is invalid!");
				str.focus();
				return false;
			}
			alert( str.label + ": Invalid credit card number format!\n Valid number should not include any white space and characters.");
			str.focus();
			return false;
		}
		else if ( ch == "E" && !CheckExpirationDate(str.value,fm) )
		{
			if(fm.lstMethod.value == "ACH")
			{
				if(str.value.substring(0,1) =="X")
					return true;
					
				alert( "Routing Number is invalid!");
				str.focus();
				return false;
			}
			alert( str.label + ": Invalid expiration date format!");
			str.focus();
			return false;
		}
		else if ( ch == "I" && !IsNumeric(str.value) )
		{
			alert( str.label + ": Invalid number!");
			str.focus();
			return false;
		}
		
		else if ( ch == "X")
		{
			if (isNaN(str.value) || eval(str.value) <= 0)
			{
				alert( str.label + ": Invalid number!");
				str.focus();
				return false;
			}
		}
		else if (ch == "L" )
		{
			if (str.type == "textarea" && str.value.length > eval(str.id.substring(i+1, i + 1 + str.id.length)) )
			{
				alert( str.title + " is too long. It should be less than " + str.id.substring(i+1, i + 1 + str.id.length + 1) + " characters.");
				str.focus();
				return false;
			}
			if ( str.type != "textarea" && str.value.length < eval(str.id.substring(i+1, str.id.length)) )
			{
				alert( str.label + ": should be at least " + eval(str.id.substring(i+1, str.id.length)) + " characters!");
				str.focus();
				return false;
			}
		}
		else if (ch == "D" ) 
		{
			var ch1 = str.id.substring(i+1, i+2);
			if (ch1 == "1" && !CheckDateFormat1(str.value) )
			{
				alert( str.label + ": Invalid Date Format!");
				str.focus();
				return false;
			}
			if (ch1 == "2" && !CheckIfDateOnlyGreaterThanToday(str.value))
			{
				alert( str.label + ": Invalid Date! Format is mm/dd/yy.");
				str.focus();
				return false;
			}
		}
		else if (ch == "Y" ) 
		{
			var ch1 = str.id.substring(i+1, i+2);
			if (ch1 == "B" && !CheckYearBefore(str.value) )
			{
				alert( str.label + ": Invalid Year Format or year over this year!");
				str.focus();
				return false;
			}
			else if (ch1 == "A" && !CheckYearAfter(str.value) )
			{
				alert( str.label + ": Invalid Year Format or year over this year!");
				str.focus();
				return false;
			}
		}
		else if ( ch == "T")
		{
            if(isNaN(str.value)){
			    alert( str.label + ": Invalid number!");
			    str.focus();
			    return false;
			 }
		}
		else if ( ch == "H")
		{
		var hh = str.value.substring(0,2); //hour
		var mm = str.value.substring(3,5); //minute
			if ( str.value.length != 5 || !IsNumeric(hh) || !IsNumeric(mm))
			{
				alert ("Please enter a correct time.\nFormat should be 'hh:mm' e.g. 23:59");
				str.focus();
				return false;
			 }  
			else 
			{
				if ( (str.value.substring(2,3) != ":") || (parseInt(hh) > 23) || (parseInt(mm) >59) ){
			 	alert ("The time you have entered is invalid.\nThe correct format is 'hh:mm' e.g. 22:45.");
			 	str.focus();
			 	return false;
			}
			}
		}
	}
	if (str.name == "txtRePwd")
	{
		if(fm.txtPwd.value != fm.txtRePwd.value)
		{
			alert("New and Re-Typed passwords dont match !");
			return false;
		}
	}
	return true;
}

//------------------------------------------------------------------
// Check the year before this year.  
//------------------------------------------------------------------

function CheckYearBefore(str)
{
	if ( str.length == 0 )
		return true;
	else if(str.length == 4 )
	{
		if ( IsNumeric(str) ) 
		{
			var d = new Date();
			return str <= d.getFullYear();
		}
	}
	return false;
}

//------------------------------------------------------------------
// Check the year after this year.  
//------------------------------------------------------------------

function CheckYearAfter(str)
{
	if ( str.length == 0 )
		return true;
	else if(str.length == 4 )
	{
		if ( IsNumeric(str) ) 
		{
			var d = new Date();
			return str >= d.getFullYear();
		}
	}
	return false;
}

//------------------------------------------------------------------
// Check Phone number format.  
//------------------------------------------------------------------

function CheckPhoneFormat(str)
{
	if(str.length == 10)
	{
		return IsNumeric(str);
	}
	else if (str.length == 12 ) 
	{
		if( IsNumeric(str.substring(0,3)) && IsNumeric(str.substring(4,7)) && IsNumeric(str.substring(8,12)) )
		{
			return ((str.substring(3,4)=="-" || str.substring(3,4) == " ") && (str.substring(7,8)=="-" || str.substring(7,8) == " "));
		}
		return false;
	}
	else if (str.length == 13 ) 
	{
		if( IsNumeric(str.substring(1,4)) && IsNumeric(str.substring(5,8)) && IsNumeric(str.substring(9,13)) )
		{
			return (str.substring(0,1)=="(" && str.substring(4,5) == ")" && (str.substring(8,9)=="-" || str.substring(8,9) == " "));
		}
		return false;
	}
	else if (str.length == 0)
		return true;
		
	return false;
}
//------------------------------------------------------------------
// Check Email format.  
//------------------------------------------------------------------

function CheckMailFormat(str)
{
	var flagAT = 0;
	var flagDOT = 0;
	var ch;
	if (str == "") return true;
	for (var i=0; i < str.length; i++)
	{
		var ch = str.substring(i, i+1);
		if(ch == "@") flagAT++;
		else if (ch == ".")flagDOT++;
	}
	return ( flagAT == 1 && flagDOT != 0);
}

//------------------------------------------------------------------
// Check Expiration date format.  
//------------------------------------------------------------------

function CheckDateFormat1(str)
{
	if( str.length != 8 )
		return false;
	if(!IsNumeric(str.substring(0,2)))
		return false;
	if(str.substring(2,3) != "/" )
		return false;
	if ( !IsNumeric(str.substring(3,5)) )
		return false;
	if(str.substring(5,6) != "/" )
		return flase;
	if ( !IsNumeric(str.substring(6,8)) )
		return false;
	return true;
}

//------------------------------------------------------------------
// Check Expiration date format.  
//------------------------------------------------------------------

function CheckExpirationDate(str,fm)
{
	if(fm.lstMethod.value == "ACH")
		return IsNumeric(str);
	if( str.length != 5 )
		return false;
	if(!IsNumeric(str.substring(0,2)))
		return false;
	if(str.substring(2,3) != "/" )
		return flase;
	if ( !IsNumeric(str.substring(3,5)) )
		return false;

	var today = new Date();
	
	var i = str.substring(3,5)-(today.getYear()-2000).toString(10);
	if ( i > 5 || i < 0 )
		return false;
	if ( i == 0 && today.getMonth() > (str.substring(0,2)-1) )
		return false;
	return true;
}

//------------------------------------------------------------------
// Check Credit card format.  
//------------------------------------------------------------------

function CheckCreditCard(str,fm)
{
	if(fm.lstCreditCard == "undefined")
	{
		alert( str.label + ": undefined");
		return false;
	}
	if(str.substring(0,1) =="X")
		return true;
	if(fm.lstMethod.value == "ACH")
		return IsNumeric(str);
	return checkCard(fm.lstCreditCard.value, str); 
}

//------------------------------------------------------------------
// Check Federal ID format.  
//------------------------------------------------------------------

function CheckFederalID(str)
{
	return (str.length == 10 && IsNumeric(str));
}

//------------------------------------------------------------------
// Check Zip code format.  
//------------------------------------------------------------------

function CheckZipCodeFormat(str)
{
	if(str.length == 5 && IsNumeric(str))
		return true;
	else if(str.length == 10 && ValidExtCode(str) )
		return true;
	return false;
}

//------------------------------------------------------------------
// Check Extention phone number format.  
// the string length should not be 0
//------------------------------------------------------------------

function ValidExtCode(str)
{
	var ch;
	for (var i=0; i < str.length; i++)
	{
		var ch = str.substring(i, i+1);
		if( i != 5 && (ch < "0" || ch > "9" ))
			return false;
		else if( i == 5 && ch != "-")
			return false;
	}
	return true;
}

//------------------------------------------------------------------
// Check if numeric.  
//------------------------------------------------------------------

function IsNumeric(str)
{
	var dotcount;
	var ch;
	dotcount=0;
	
	if (isNaN(str))
		return false;
	else
		return true;
	/*
	for (var i=0; i < str.length; i++)
	{
		var ch = str.substring(i, i+1);
		if (ch == " ")
			return false;
		if( ( ch < "0" || ch > "9" || ch != ".") && dotcount > 1)
			{
			return false;
			}
		if(ch==".") dotcount++;
	}*/
	return true;
}

//-------------------------------------------------------------------
// Check whether the number is a decimal or not    
//-------------------------------------------------------------------
function IsDecimal(str)
{
	var ch;	
	for (var i=0; i < str.length; i++)
	{
		var ch = str.substring(i, i+1);		
		if (ch == " ")
			return false;
		if(ch < "0" || ch > "9")
		//if( (ch < "0" || ch > "9") && (ch != ".") )
			return false;
	}
	return true;
}

//------------------------------------------------------------------
// Subroutine for Email format checking.  
//------------------------------------------------------------------

function Invalid(str)
{
	var flagAT = 0;
	var flagDOT = 0;
	for (var i=0; i < str.length; i++)
	{
		var ch = str.substring(i, i+1);
		if(ch == "@") flagAT++;
		else if (ch == ".")flagDOT++;
	}
	return ( flagAT != 1 || flagDOT == 0);
}

//------------------------------------------------------------------
// Check credit card.  
//------------------------------------------------------------------
//----------------------------------------------------------------------
// Function to validate categories selected  (09.10.00 tchu)
//----------------------------------------------------------------------
function roundOff(value)
	{
	if(IsNumeric(value))
	{
	result = Math.round(value * Math.pow(10,2));
	result = result / 100;
	return result;
	}
	else
	return 0;
	}

//---------------------------------------------------------------------
// Clears All input boxes (even if boxes are pre-populated) (09.08.00 tchu)
//---------------------------------------------------------------------
function ClearAll()
{
		var form = document.rfpwizardform;
		for (i=0;i< form.length;i++)		
			if (form[i].type == "text" || form[i].type == "textarea")
				form[i].value = "";
}

//-------------------------------------------------------------
// The foll. functions (IsLeapYear, GetAbsoluteDay, IsValidDay) 
// were copied from flooringstep1.asp
//
//-------------------------------------------------------------

   function IsLeapYear(nYear){
        return (nYear % 4 == 0 && nYear % 100 != 0 || nYear % 400 == 0);
    }

//-------------------------------------------------------------
//-------------------------------------------------------------

    function GetAbsoluteDay(sMonth, sDay, sYear){
        var sDays = 0;
        for(i=1;i<sMonth;i++){
            if((i==1) || (i==3) || (i==5) || (i==7) || (i==8) || (i==10) || (i==12))
                sDays = sDays + 31;
            if(i==2){
                if(IsLeapYear(sYear))
                    sDays = sDays + 29;
                else
                    sDays = sDays + 28;
            }
            if((i==4) || (i==6) || (i==9) || (i==11))
                sDays = sDays + 30;
        }
        return sDays;
    }

//-------------------------------------------------------------
//-------------------------------------------------------------

    function IsValidDay(sMonth, sDay, sYear){
        if((sMonth==1) || (sMonth==3) || (sMonth==5) || (sMonth==7) || (sMonth==8) || (sMonth==10) || (sMonth==12)){
            if(sDay > 31)
                return false;
        }
        if(sMonth==2){
            if(IsLeapYear(sYear)){
                if(sDay > 29)
                    return false;
            }
            else{
                if(sDay > 28)
                    return false;
            }
        }
        if((sMonth==4) || (sMonth==6) || (sMonth==9) || (sMonth==11)){
            if(sDay > 30)
                return false;
        }
        if(sMonth>12)
            return false;
        return true;
    }


//-------------------------------------------------------------
// function CheckFinish(objFrm) - validation when the finish button
// is clicked
//-------------------------------------------------------------

function CheckFinish(objFrm)
{
	var i;
	for (i=0; i<=1; i++)
	{
		if (objFrm.ServiceRequest[i].checked)
		{	
			if ((objFrm.ServiceRequest[i].value == "ASR") || (objFrm.ServiceRequest[i].value == "NSR"))
			{
				var strFirstChoiceDate = objFrm.FirstChoiceDate.value;
				var strFirstChoiceTime = objFrm.FirstChoiceTime[objFrm.FirstChoiceTime.selectedIndex].value;
				//alert(objFrm.FirstChoiceTime.selectedIndex);

                //DGD 12/31/2000. Commeted the the 3 conditions to check if the date is greater that today, 
                //since the check was performed on the onChange event of the control.
/*				if (!CheckIfDateTimeGreaterThanToday(strFirstChoiceDate, strFirstChoiceTime))
					{
					alert("Please enter Date/Time greater than current Date/Time");
					objFrm.FirstChoiceDate.focus();
					return false;
					}
*/
				var strSecondChoiceDate = objFrm.SecondChoiceDate.value;
				var strSecondChoiceTime = objFrm.SecondChoiceTime[objFrm.SecondChoiceTime.selectedIndex].value;
				if ((strSecondChoiceDate != "") && (strSecondChoiceTime != ""))
				{	
/*					if (!CheckIfDateTimeGreaterThanToday(strSecondChoiceDate, strSecondChoiceTime))
					{
					alert("Please enter Date/Time greater than current Date/Time");
					objFrm.SecondChoiceDate.focus();
					return false;
					}
*/
				}
	
				var strThirdChoiceDate = objFrm.ThirdChoiceDate.value;
				var strThirdChoiceTime = objFrm.ThirdChoiceTime[objFrm.ThirdChoiceTime.selectedIndex].value;
				if ((strThirdChoiceDate != "") && (strThirdChoiceTime != ""))
				{
/*					if (!CheckIfDateTimeGreaterThanToday(strThirdChoiceDate, strThirdChoiceTime))
						{
						alert("Please enter Date/Time greater than current Date/Time");
						objFrm.ThirdChoiceDate.focus();
						return false;
						}
*/
				}

				if ((strSecondChoiceDate != "") | (strThirdChoiceDate !=""))
				{
				if (((strFirstChoiceDate == strSecondChoiceDate) & (strFirstChoiceTime == strSecondChoiceTime)) | 
				    ((strFirstChoiceDate == strThirdChoiceDate) & (strFirstChoiceTime == strThirdChoiceTime)) |
				    ((strSecondChoiceDate == strThirdChoiceDate) & (strSecondChoiceTime == strThirdChoiceTime)))
				{
					alert("Please enter different Date/Time for the different choices");
					objFrm.SecondChoiceDate.focus();
					return false;
				}
				}
			}
			else
			{
				if (!CheckPhoneFormat(objFrm.PhoneNumber.value))
				{
					//alert("Please check Phone Number format");
					//objFrm.PhoneNumber.focus();
					//return false;
				}
			}
		}
	}	
	return true;	
}


//-------------------------------------------------------------
// function CheckIfDateTimeGreaterThanToday - validation
// to check if the date/time entered is greater than current
// date/time.
//-------------------------------------------------------------

function CheckIfDateTimeGreaterThanToday(str, str2)
{
	var now = new Date();
	var currentMonth = now.getMonth()+1;
	var currentDay = now.getDate();
	var currentYear = now.getYear();
	var currentHour = now.getHours();
	var currentMinute = now.getMinutes();
	var currentSecond = now.getSeconds();

	var strDay, strMonth, strYear, strHour, strMinute, strSecond;
	strMonth = str.substring(0,2);
	strDay = str.substring(3,5);
	strYear = "20" + str.substring(6,8);
    
    // Checking if he has not selected time
	if(str2 == "")
	   return false;
	   
	strHour = str2.substring(0,2);
	strMinute = str2.substring(3,5);
	strSecond = str2.substring(6,8);
	
	currentMonth = MakeTwoDigitFormat(currentMonth);
	currentDay = MakeTwoDigitFormat(currentDay);
	currentHour = MakeTwoDigitFormat(currentHour);
	currentMinute = MakeTwoDigitFormat(currentMinute);
	currentSecond = MakeTwoDigitFormat(currentSecond);
	
	var currentDate = currentMonth + "/" + currentDay + "/" + currentYear + " " + currentHour + ":" + currentMinute + ":" + currentSecond;
	var strDate = strMonth + "/" + strDay + "/" + strYear + " " + strHour + ":" + strMinute + ":" + strSecond;
	
	if (strDate <= currentDate) 
	{	
// <!--		alert("Please enter a later Date/Time");	 -->
		return false;
	}
	return true;
}

//-------------------------------------------------------------
// function CheckIfDateOnlyGreaterThanToday - check
// for date only ---- NOT time. (tchu)
//-------------------------------------------------------------

function CheckIfDateOnlyGreaterThanToday(str)
{
	if( str.length != 8 )
		return false;
	if(!IsNumeric(str.substring(0,2)))
		return false;
	if(str.substring(2,3) != "/" )
		return false;
	if ( !IsNumeric(str.substring(3,5)) )
		return false;
	if(str.substring(5,6) != "/" )
		return flase;
	if ( !IsNumeric(str.substring(6,8)) )
		return false;

	var now = new Date();
	var currentMonth = now.getMonth()+1;
	var currentDay = now.getDate();
	var currentYear = now.getYear();

	var strDay, strMonth, strYear, strHour, strMinute, strSecond;
	strMonth = str.substring(0,2);
	strDay = str.substring(3,5);
	strYear = "20" + str.substring(6,8);
	
	currentMonth = MakeTwoDigitFormat(currentMonth);
	currentDay = MakeTwoDigitFormat(currentDay);
	
	var currentDate = currentYear + "/" + currentMonth + "/" + currentDay;  //flip for better check
	var strDate = strYear + "/" + strMonth + "/" + strDay;
	
	//alert ( "strDate " + strDate + " currentDate " + currentDate);
	
	if (strDate < currentDate) 
	{	
		//alert("Please enter a later Date/Time");	 
		return false;
	}
	
	return true;
}



//-------------------------------------------
// MakeTwoDigitFormat(str) - used by CheckIfDateTimeGreaterThanToday
//
//-------------------------------------------

function MakeTwoDigitFormat(str)
{
	str = str + "";
	if (str.length == 1)
	{	
		str = "0" + str;
	}
	return str;
}



//-------------------------------------------
// CompareDateDateTime( - for RfP Wizard. Ensures that time is greater than
// current time if StartDate & Bid deadline date are equal.
// Start date should be later to the Bid Deadline date
//-------------------------------------------

function CompareDateDateTime(form)
	{
		var hh = form.txtTime.value.substring(0,2); //hour
		var mm = form.txtTime.value.substring(3,5); //minute
		if ( form.txtTime.value.length != 5 || !IsNumeric(hh) || !IsNumeric(mm))
		{
			alert ("Please enter a correct time.\nFormat should be 'hh:mm' e.g. 23:59");
			form.txtTime.focus();
			return false;
		}  
		else
		{
			if ( (form.txtTime.value.substring(2,3) != ":") || (parseInt(hh) > 23) || (parseInt(mm) >59) )
			{
		 	alert ("The time you have entered is invalid.\nThe correct format is 'hh:mm' e.g. 22:45.");
		 	str.focus();
		 	return false;
		 	}
		}

		var startDate = form.txtStartDate.value
		var bidDate = form.txtDate.value

    	        var now = new Date();
		var currentMonth = now.getMonth()+1;
		var currentDay = now.getDate();
		var currentYear = now.getYear();
		var currentHour = now.getHours();
		var currentMinute = now.getMinutes();

		var startDay, startMonth, startYear
		startMonth = startDate.substring(0,2);
		startDay = startDate.substring(3,5);
		startYear = "20" + startDate.substring(6,8);
		
		var bidDay, bidMonth, bidYear
		bidMonth = bidDate.substring(0,2);
		bidDay = bidDate.substring(3,5);
		bidYear = "20" + bidDate.substring(6,8);		
		  
		currentMonth = MakeTwoDigitFormat(currentMonth);
		currentDay = MakeTwoDigitFormat(currentDay);
		currentHour = MakeTwoDigitFormat(currentHour);
		currentMinute = MakeTwoDigitFormat(currentMinute);		  		  
			
		var currentDate = currentYear + "/" + currentMonth + "/" + currentDay;
		var startDate = startYear + "/" + startMonth + "/" + startDay;
		var bidDate = bidYear + "/" + bidMonth + "/" + bidDay;
		  
		if ( startDate == bidDate )
		{

		  if ( currentDate == startDate )
		  {
			var currentTime = currentHour + ":" + currentMinute
			var strTime = hh + ":" + mm
		  	
			if (strTime < currentTime)
			{
			alert("Time entered is before the current time. This is not allowed because the 'Start Date' and\n'Bid Date' is set to current date. Please change either dates or time.");
			form.txtTime.focus();
  			return false;
			}
		   }
		} 
   	 }
   	 

//-------------------------------------------
// CheckOtherDate - for RfP Wizard. Make sure 'Start date'
// is before bid deadline.
//------------------------------

function CheckOtherDate(form, f)
{
var startDate = form.txtStartDate.value;
var bidDate = form.txtDate.value;
	if (f==1)
	{
	  var dateSplit = startDate.split("/");
	  if(!IsValidDay(dateSplit[0], dateSplit[1], '20'+dateSplit[2]))
	  {
	    alert("Project Start Date: This is an invalid date. \n Please Enter a Date In Correct Format (mm/dd/yy).");
	    form.txtStartDate.focus();
	    return false;
	  }
	  if ( !CheckIfDateOnlyGreaterThanToday(startDate) )
	  {
	    alert("Project Start Date: This Date should be later than Today.\n Please Enter a Date In Correct Format (mm/dd/yy).");
	    form.txtStartDate.focus();
	    return false;
	  }
	  else
	  {
   	    var startDay, startMonth, startYear
	    startMonth = startDate.substring(0,2);
	    startDay = startDate.substring(3,5);
	    startYear = startDate.substring(6,8);
	  
	    startDate = startYear + "/" + startMonth + "/" + startDay;
	    
	    //alert("Now check there's a bid date");
	    if ( bidDate != "" )
	    {
		  //alert ("bidDate is: " + bidDate);
		  if ( !CheckIfDateOnlyGreaterThanToday(bidDate) )
		  {
		    //alert("Don't do anything & just continue.");
		  }
		  else
		  {
		    //alert ("bidDate is in good format. Now check if less than start date.");
		    var bidDay, bidMonth, bidYear
			bidMonth = bidDate.substring(0,2);
			bidDay = bidDate.substring(3,5);
			bidYear = bidDate.substring(6,8);
			
			bidDate = bidYear + "/" + bidMonth + "/" + bidDay;
		    
		    if ( bidDate > startDate )
		    {
		      alert ("Start Date must be later than\nBid Submission Deadline Date.");
		      return false;
		    }
		  }
	    }
	  }
	}
	
	if (f==2)
	{
	  var dateSplit = bidDate.split("/");
	  if(!IsValidDay(dateSplit[0], dateSplit[1], '20'+dateSplit[2]))
	  {
	    alert("Bid Deadline Date: This is an invalid date. \n Please Enter a Date In Correct Format (mm/dd/yy).");
	    form.txtDate.focus();
	    return false;
	  }
	  if ( !CheckIfDateOnlyGreaterThanToday(bidDate) )
	  {
	    alert("Bid Deadline Date: This Date should be later than Today.\n Please Enter a Date\nIn Correct Format (mm/dd/yy).");
	    form.txtDate.focus();
	    return false;
	  }
	  else
	  {
   	    var bidDay, bidMonth, bidYear
	    bidMonth = bidDate.substring(0,2);
	    bidDay = bidDate.substring(3,5);
	    bidYear = bidDate.substring(6,8);
	  
	    bidDate = bidYear + "/" + bidMonth + "/" + bidDay;
	    
	    //alert("Now check if there's a Start date");
	    if ( startDate != "" )
	    {
		  //alert ("startDate is: " + startDate);
		  if ( !CheckIfDateOnlyGreaterThanToday(startDate) )
		  {
		    //alert("Don't do anything & just continue.");
		  }
		  else
		  {
		    //alert ("startDate is in good format. Now check if greater than bid date.");
		    var startDay, startMonth, startYear
			startMonth = startDate.substring(0,2);
			startDay = startDate.substring(3,5);
			startYear = startDate.substring(6,8);
			
			startDate = startYear + "/" + startMonth + "/" + startDay;
		    
		    if ( bidDate > startDate )
		    {
		      alert ("Start Date must be later than\nBid Submission Deadline Date.");
		      form.txtDate.focus();
		    }
		  }
	    }
	  }
	}
return true;	
}

function XMLEncode(sInput)
{ 
    if (sInput != "")
    {
		sResult = sInput;
		sResult = sResult.replace(/&apos;/g, "__apos__");
		sResult = sResult.replace(/&quot;/g, "__quot__");
        sResult = sResult.replace(/&amp;/g, "__amp__");        
        sResult = sResult.replace(/&lt;/g, "__lt__");
        sResult = sResult.replace(/&gt;/g, "__gt__");
        sResult = sResult.replace(/&/g, "&amp;");
        sResult = sResult.replace(/""/g, "&quot;");
        //sResult = sResult.replace(/'/g, "&apos;");        
        sResult = sResult.replace(/</g, "&lt;");
        sResult = sResult.replace(/>/g, "&gt;");
        sResult = sResult.replace(/__apos__/g, "&apos;");
        sResult = sResult.replace(/__quot__/g, "&quot;");
        sResult = sResult.replace(/__amp__/g, "&amp;");
        sResult = sResult.replace(/__lt__/g, "&lt;");
        sResult = sResult.replace(/__gt__/g, "&gt;");
        return sResult;
    }
    return;
}

function trim(str)
{
	for(i = 0; i < str.length; i++)
	{
		if (str.charAt(i) != " ")
		{
			if (i == 0)
			{
				firstidx = 0;
				break;
			}
			else
			{
				firstidx = i;
				break;
			}
		}
	}
	for(j = str.length - 1; j >= 0; j--)
	{
		if (str.charAt(j) != " ")
		{
			if (j == str.length)
			{
				lastidx = str.length;
				break;
			}
			else
			{
				lastidx = j;
				break;
			}
		}
	}

	if (i > j)
		str = "";
	else
		str = str.substring(firstidx,lastidx + 1);
	return str;
}

function selectAll(chkName)
{
	if (chkName.length != null)
	{
		for (j=0; j< chkName.length; j++)
		{
			chkName[j].checked = true;
		}
	}
	else
		chkName.checked = true;
}

function deSelectAll(chkName)
{
	if (chkName.length != null)
	{
		for (j=0; j< chkName.length; j++)
		{
			chkName[j].checked = false;
		}
	}
	else
		chkName.checked = false;
}

function checkAtleastOneChecked(chkName, msg)
{
	if (chkName.length != null)
	{
		for (j=0; j< chkName.length; j++)
		{
			if (chkName[j].checked)
				return true;
		}
	}
	else
	{
			if (chkName.checked)
				return true;
	}
	alert(msg);
	return false;
}

function replace(szBuf, szFind, szReplace, lStart) {
  var lFind = 0;
  if (!lStart) lStart = 0;
  
  while (lFind != -1)   {
    lFind = szBuf.indexOf(szFind, lStart);    
    if (lFind != -1)     {
      szBuf = szBuf.substring(0,lFind) + szReplace + szBuf.substring(lFind + szFind.length);
      lStart = lFind + szReplace.length;
    }
  }
  return szBuf;
}

function pmt(rate, nper, pv, fv) {
  var rVal;
  if (rate==0)   {
    rVal=-(fv + pv)/nper;
  }   else   {
    ir=Math.pow(1 + rate,nper);
    rVal=-((rate * (fv + ir * pv))/(ir-1));
  }
  return rVal;
}

function cleanNumber(strNum) {
  if (!strNum) return strNum;
  strNum = replace(strNum, '$', '', 0);
  strNum = replace(strNum, ',', '', 0);
  strNum = replace(strNum, '%', '', 0);	
  return strNum;
}

function format(value, lead, sep) {
  var strValue = new String(value);
  var len = strValue.length;
  var n;
  var strRet = '';
  var ctChar = 3 - (len%3);

  if (ctChar == 3) ctChar =0;

  for (n=0; len > n; n++)   {
    if (ctChar == 3)     {
      strRet += sep;
      ctChar = 0;
    }
    ctChar++;
    strRet += strValue.substring(n,n+1);
  }

  if (lead == '%')   {
    return strRet + lead;
  }   else   {   	return lead + strRet;
  }
}

function numFormat(elem, lead, sep) {
  if (elem.value == '')   {		elem.value = format('0', lead, sep);
		return true;
  }
  
  var value = parseInt(cleanNumber(elem.value), 10);
  
  if (lead == '')   {
    if (0 > value)     {
      alert('You have exceeded the range for the interior size.\nPlease check your information and try again.');
      value = 0;
    }    
    if (value > 99999)     {
      alert('You have exceeded the range for the interior size.\nPlease check your information and try again.');
      value = 99999;
	}
  }
  
  if (lead == '$')   {
    if (0 > value)     {
      alert('You have exceeded the range for the price.\nPlease check your information and try again.');
      value = 0;
    }
    
    if (value > 100000000)     {
      alert('You have exceeded the range for the price.\nPlease check your information and try again.');
      value = 100000000;
    }
  }
	
  if (isNaN(value))   {
    alert('You have entered an incorrect character on this field. \nPlease check your information and try again.');
    elem.value = format('0', lead, sep);
    elem.focus();
    return false;
  }
  elem.value = format(value, lead, sep);
  return true;
}

function percentrate(elem, lead) {
  
  if (elem.value == '') return true;  
  var strRet = '';
  var value = parseFloat(cleanNumber(elem.value));
  if (0 > value) value = 0;
  if (value > 100) value = 99.999;
  if (isNaN(value))   {
    alert('You may have entered an incorrect character or exceeded the range for some information on this tab. \nPlease check your information and try again.');
    elem.value = '';
    elem.focus();
    return false;
  }
  var strvalue = new String(value);
  if (value > 9.9999)
	{
		if(strvalue.length > 6)
		{
			strRet = strvalue.substr(0, 6);
        }
		else
        {
			if(strvalue.length == 5)
            {
              strRet = strvalue + '0';
            }
			else
            {
				if(strvalue.length == 4)
                {
                  strRet = strvalue + '00';
                }
				else
                {
                  if (strvalue.length == 2)                  
                      strRet = strvalue + '.000';                    
                  else
					  strRet = strvalue;                    
                }
            }
        }
    }
	else
    {
      if(strvalue.length > 5)    
          strRet = strvalue.substr(0, 5);        
      else
      {
			if(strvalue.length == 4)      
				strRet = strvalue + '0';            
			else
			{
				if(strvalue.length == 3)          
					strRet = strvalue + '00';                
              else
              {
				if (strvalue.length == 1)                
                    strRet = strvalue + '.000';
				else
					strRet = strvalue;
              }
			}
        }
    }
	elem.value = strRet + lead;
	return true;
}

function CalculatePayment(frmObj, fErrors) {
  if (frmObj == null) return;

  var price = cleanNumber(frmObj.ap.value);
  var priceErr = false;

  var downpayment = cleanNumber(frmObj.dp.value);
  var downpaymentErr = false;

  var interest = cleanNumber(frmObj.ir.value);
  var interestErr = false;

  var numpayments = 360; // 30 Years Fixed Mortgage  

  var errMessage = "Please check the following fields:\n";
  if ((isNaN(price) || price.length == 0) && (fErrors != 0))   {
    priceErr = true;
    errMessage = errMessage + "Purchase Price\n";
  }
  	
  if ((isNaN(downpayment) || downpayment.length == 0) && (fErrors != 0))   {
    downpaymentErr = true;
    errMessage = errMessage + "Down Payment\n";
  }

  if ((isNaN(interest) || interest.length == 0) && (fErrors != 0))   {
    interestErr = true;
    errMessage = errMessage + "Interest Rate\n";
  }

  if (priceErr || downpaymentErr || interestErr)   {
    alert(errMessage);
    return;
  }
	
  numFormat(frmObj.ap,'$',',');
  numFormat(frmObj.dp,'$',',');
  percentrate(frmObj.ir, '%');

  if ((price == 0) && (fErrors != 0))   {
    alert('Please enter an asking price that is greater than zero.');
    frmObj.ep.value = '';
  }  else if ((eval(price) <= eval(downpayment)) && (fErrors != 0))   {
    alert('To calculate a monthly payment, you must enter a down payment that is less than the asking price.');
    frmObj.ep.value = '';
  }   else   {
    var payment = parseInt(-pmt(interest/1200, numpayments, price - downpayment,0));
    if (payment < 0)     {
      frmObj.ep.value = '';
    }     else     {
      frmObj.ep.value = payment;
      numFormat(frmObj.ep,'$',',');
    }
  }    
}

function isInteger(numberValue, msg){
	var j;	str="0123456789";
	for (j=0;j<numberValue.length;j++)
	{
		if (str.indexOf(numberValue.charAt(j)) < 0)
		{
			if (msg != '') 
				alert(msg);			return false;
		}		
	}
	return true;}

 function validateZipCodes(frmobj)
 {
 	if (frmobj.txtZip1.value != '')
	{
		if (frmobj.txtZip1.value.length < 5)
		{
			alert('Please enter 5 digit zip code.');
			frmobj.txtZip1.focus();
			return false;
		}
		if (!isInteger(frmobj.txtZip1.value, "Please enter valid zip code")) 
		{
			frmobj.txtZip1.focus();
			return false;
		}
	}

	if (frmobj.txtZip2.value != '')
	{
		if (frmobj.txtZip2.value.length < 4)
		{
			alert('Please enter 4 digit zip code.');
			frmobj.txtZip2.focus();
			return false;
		}
		if (!isInteger(frmobj.txtZip2.value, "Please enter valid zip code")) 
		{
			frmobj.txtZip2.focus();
			return false;
		}
	}
 } 
