//***********************************************************************************************************
//	Javscript client side validation, navigation, formatting
//	5/31/2005 - Spantech Software, Inc.
//
//	Modified:	date - by
//	Reason:		
//
//***********************************************************************************************************

//rose color constant
var INVALID_FIELD_BACKGROUND = "#ffcccc";
var VALID_FIELD_BACKGROUND = "#ffffff";
var DIRTY_FIELD_BACKGROUND = "#EEE8AA";
//use this to determine if page has been modified or not
var _dirty=false;

//***********************************************************************************************************
//	Javascript Field Length validation
//	2/1/2003 - Spantech Software, Inc.
//
//	Input:	Control (textbox) object
//	Example:	onchange="javascript:CheckLength(this,10);"
//
//	Modified:	date - by
//	Reason:		
//
//***********************************************************************************************************
function CheckLength(obj,len)
{
	//obj.style.background=VALID_FIELD_BACKGROUND;
	if(obj.value.length > len)
	{
		//obj.style.background=INVALID_FIELD_BACKGROUND;
		obj.focus();
		alert("This field can only be " + len + " characters long.  You have entered " + obj.value.length + " characters.");
	}	
}


//***********************************************************************************************************
//	Javascript Date validation
//	2/1/2003 - Spantech Software, Inc.
//
//	Input:	Control (textbox) object
//	Example:	onblur="javascript:CheckDate(this);"
//	If it's null, change background color to "rose" (maybe this should be for required fields?)
//	If it's not a date, alert user, clear contents, reset focus, and change background color
//	If it is a valid number, set background color to white
//
//	Modfied:	2/2/2003 - Spantech Software, Inc.
//	Reason:		Do not alert user and do not clear contents.
//
//	Modfied:	7/30/2004 - Spantech Software, Inc.
//	Reason:		for AFM, alert user, clear contents, and reset focus
//
//***********************************************************************************************************
function CheckDate(obj) 
{		
	//obj.style.background=VALID_FIELD_BACKGROUND;
	if (obj.value != "" ) 
	{		
		//pass value to validation routine
		if (!isDate(obj.value))
		{			
			obj.focus();
			//obj.style.background=INVALID_FIELD_BACKGROUND;			
			//alert("Not a valid date, please try again.");	
			//return false;
			//obj.value = "";	
			//set focus and change background									
		}		
	}
	//return true;
}

function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
	valid dates with 2 digit month, 2 digit day, 
	4 digit year. Date separator can be ., -, or /.
	Uses combination of regular expressions and 
	string parsing to validate date.
	Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
		
PARAMETERS:
	strValue - String to be tested for validity
		
RETURNS:
	True if valid, otherwise false.
		
REMARKS:
	Avoids some of the limitations of the Date.parse()
	method such as the date separator character.
		
ACKNOWLEDGEMENTS: http://www.rgagnon.com/jsdetails/js-0063.html
*************************************************/
	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
	var objRegExp2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/;  //test if 2 or 4 digit year
	
	//check to see if in correct format
	//if(!objRegExp.test(strValue) && !objRegExp2.test(strValue)){
	if(!objRegExp2.test(strValue)){
		//alert("FAILED HERE");
		return false; //doesn't match pattern, bad date
	}
	else{
	var strSeparator = "/" //RGuidi: forcing separator strValue.substring(2,3); //find date separator
	var arrayDate = strValue.split(strSeparator); //split date into month, day, year
	//create a lookup for months not equal to Feb.
	var arrayLookup = { '1' : 31,'3' : 31,'4' : 30,'5' : 31,'6' : 30,'7' : 31,
						'8' : 31,'9' : 30,'10' : 31,'11' : 30,'12' : 31};
	var intDay = parseInt(arrayDate[1],10); 
		//alert(parseInt(arrayDate[0],10));
		//alert(arrayLookup[arrayDate[0]]);
	//check if month value and day value agree
	if(arrayLookup[parseInt(arrayDate[0],10)] != null) {
	//  if(arrayLookup[intMonth] != null) {
		if(intDay <= arrayLookup[parseInt(arrayDate[0],10)] && intDay != 0){
		//alert("SUCEEDED 1");
		return true; //found in lookup table, good date
		}
	}
		
	//check for February
	var intYear = parseInt(arrayDate[2],10);
	var intMonth = parseInt(arrayDate[0],10);
	if (intDay.length == 1){intDay = '0' && intDay};
	if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0){
		return true; //Feb. had valid number of days
		}
	}
	return false; //any other values, bad date
}

//***********************************************************************************************************
//	Javascript Validation
//	2/1/2003 - Spantech Software, Inc.
//
//	Input:		form object
//	Example:	Call from submit
//	Loop through all controls on form.
//	If any have background color of "rose" ("#ffcccc") INVALID_FIELD_BACKGROUND
//	Return false, o/w return true
//
//	Modfied:	Date modified - Modified by
//	Reason:		
//
//***********************************************************************************************************
function ValidateAndSave()
{	
	for (i=0;i<document.WebForm.elements.length;i++)
	{
		
		with(document.WebForm.elements[i])
		{
			if(type=="text"||type=="textarea")
			{
				if(style.background==INVALID_FIELD_BACKGROUND)
				{
					//encapsulate focus() call in error handler
					//if it blows up (field is hidden for example), silently clear value and continue processing
					try
					{
						focus();
						alert("One or more fields are not in a valid format.  Please check red fields and try again.");
						return false;
					}
					catch(e)
					{
						value="";
					}					
				}												
			}		
		}
	}	
	_dirty = false;
	return true;
	
}

function IsDirty()
{
	return(_dirty==true);
}

function MakeDirty()
{
	_dirty = true;
}

function MakeClean()
{
	_dirty = false;
}

//***********************************************************************************************************
//	Javascript Print Contents
//	6/7/2003 - Spantech Software, Inc.
//
//	Set focus to the iframe and print contents
//
//	Modfied:	Date modified - Modified by
//	Reason:		
//
//***********************************************************************************************************
function PrintWindow()
{	
			
	document.all.imgPrint.style.display='none';
	try
	{
		document.all.spnProtectedArea.style.display='none';
	}
	catch(e)
	{
	}	
	window.print();
	document.all.imgPrint.style.display='';
	try
	{
		document.all.spnProtectedArea.style.display='';
	}
	catch(e)
	{
	}
}
//call from onchange event so they know a change has been made
//usage:  onChange="javascript:markDirty(this);
function markDirty(obj)
{
	obj.style.background=DIRTY_FIELD_BACKGROUND;
}

function SetDivTop(val) 
{
	//store the scroll position for divMaster
	//Need to add the call to SetDivTop in the onclick event of divMaster on each page
	//Replace smartNavigation
	try
	{
		document.all.WindowYPos.value = val;
	}
	catch(e)
	{
	}
}
function ScrollDivTop() 
{
	//scroll to the saved position
	try
	{
		if (document.all.WindowYPos.value!=0)
		{
			divMaster.scrollTop = document.all.WindowYPos.value;			
		}					
	}
	catch(e)
	{
	}							
}		
function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		//if(cents<10)
		//	cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	//return (((sign)?'':'-') + '$' + num + '.' + cents);
	//return (((sign)?'':'-') + '$' + num);
	//return (((sign)?'':'-') + num);
	if(cents=='0')
	{
		return (((sign)?'':'-') + num);
	}
	else
	{
		return (((sign)?'':'-') + num + '.' + cents);
	}
}


//Need this fn to convert numbers to plain numbers before trying to do math!
function formatNumber(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
	return (((sign)?'':'-') + num);
}				
function ResumeUpload(url) 
{
	window.open(url,'win','menubar=0,scrollbars=1,height=800,width=900,location=0,menubar=0,directories=0,resizable=0');
}			

//***********************************************************************************************************
//	Javascript Main Navigation
//	6/7/2003 - Spantech Software, Inc.
//
//	Pass querystring path to main page to change iframe contents
//
//	Modfied:	Date modified - Modified by
//	Reason:		
//
//***********************************************************************************************************
function NavigateMain(path)
{
	try
	{
		parent.window.location=path;
	}
	catch(e)
	{
	}
}

function SetTopID(top, name)
{	
	name = xreplace(name, "|", "'");
	
	//document.all.txtTopID.value=top;	
	//document.all.txtTopPage.value=name;
}

function xreplace(checkMe,toberep,repwith){
	var temp = checkMe;
	var i = temp.indexOf(toberep);
	while(i > -1)
		{
			temp = temp.replace(toberep, repwith);
			i = temp.indexOf(toberep, i + repwith.length + 1);
		}
	return temp;
}

function VerifyData()
			{
				var vEMail
				var vPassword
				
					vEmail = document.all.txtEmail.value
					vPassword = document.all.txtPassword.value
			
				if(vEmail == "" ||  (vPassword == "") )
				{
					alert("Please be sure to enter a UserID (i.e. email address) and a Password.")
					return false
				}

				return true
			}
				
			function emailCheck (emailStr) {
					/* The following pattern is used to check if the entered e-mail address
						fits the user@domain format.  It also is used to separate the username
						from the domain. */
					var emailPat=/^(.+)@(.+)$/
					/* The following string represents the pattern for matching all special
						characters.  We don't want to allow special characters in the address. 
						These characters include ( ) < > @ , ; : \ " . [ ]    */
					var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
					/* The following string represents the range of characters allowed in a 
						username or domainname.  It really states which chars aren't allowed. */
					var validChars="\[^\\s" + specialChars + "\]"
					/* The following pattern applies if the "user" is a quoted string (in
						which case, there are no rules about which characters are allowed
						and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
						is a legal e-mail address. */
					var quotedUser="(\"[^\"]*\")"
					/* The following pattern applies for domains that are IP addresses,
						rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
						e-mail address. NOTE: The square brackets are required. */
					var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
					/* The following string represents an atom (basically a series of
						non-special characters.) */
					var atom=validChars + '+'
					/* The following string represents one word in the typical username.
						For example, in john.doe@somewhere.com, john and doe are words.
						Basically, a word is either an atom or quoted string. */
					var word="(" + atom + "|" + quotedUser + ")"
					// The following pattern describes the structure of the user
					var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
					/* The following pattern describes the structure of a normal symbolic
						domain, as opposed to ipDomainPat, shown above. */
					var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


					/* Finally, let's start trying to figure out if the supplied address is
						valid. */

					/* Begin with the coarse pattern to simply break up user@domain into
						different pieces that are easy to analyze. */
					var matchArray=emailStr.match(emailPat)
					if (matchArray==null) {
						/* Too many/few @'s or something; basically, this address doesn't
							even fit the general mould of a valid e-mail address. */
						alert("Email address seems incorrect (check @ and .'s)")
						return false
					}
					var user=matchArray[1]
					var domain=matchArray[2]

					// See if "user" is valid 
					if (user.match(userPat)==null) {
							// user is not valid
							alert("The username doesn't seem to be valid.")
							return false
					}

					/* if the e-mail address is at an IP address (as opposed to a symbolic
						host name) make sure the IP address is valid. */
					var IPArray=domain.match(ipDomainPat)
					if (IPArray!=null) {
							// this is an IP address
							for (var i=1;i<=4;i++) {
								if (IPArray[i]>255) {
										alert("Destination IP address is invalid!")
							return false
								}
							}
							return true
					}

					// Domain is symbolic name
					var domainArray=domain.match(domainPat)
					if (domainArray==null) {
						alert("The domain name doesn't seem to be valid.")
							return false
					}

					/* domain name seems valid, but now make sure that it ends in a
						three-letter word (like com, edu, gov) or a two-letter word,
						representing country (uk, nl), and that there's a hostname preceding 
						the domain or country. */

					/* Now we need to break up the domain to get a count of how many atoms
						it consists of. */
					var atomPat=new RegExp(atom,"g")
					var domArr=domain.match(atomPat)
					var len=domArr.length
					if (domArr[domArr.length-1].length<2 || 
							domArr[domArr.length-1].length>3) {
						// the address must end in a two letter or three letter word.
						alert("The address must end in a three-letter domain, or two letter country.")
						return false
					}

					// Make sure there's a host name preceding the domain.
					if (len<2) {
						var errStr="This address is missing a hostname!"
						alert(errStr)
						return false
					}

					// If we've gotten this far, everything's valid!
					return true;
			}
function formatCurrency(num) 
{	
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		//if(cents<10)
		//	cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	//return (((sign)?'':'-') + '$' + num + '.' + cents);
	//return (((sign)?'':'-') + '$' + num);
	//return (((sign)?'':'-') + num);
	if(cents=='0')
	{
		return (((sign)?'':'-') + num);
	}
	else
	{
		return (((sign)?'':'-') + num + '.' + cents);
	}
}	

//Need this fn to convert numbers to plain numbers before trying to do math!
function formatNumber(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
	return (((sign)?'':'-') + num);
}
function CompareNet(net,obj)
{	
	try
	{
		if (CheckNumber(obj))
		{
			if (parseFloat(formatNumber(obj.value)) > parseFloat(formatNumber(net.value)))
			{
				obj.focus();
				//obj.style.background=badfieldbackground;			
				alert("Cannot be greater than total net worth.");
			}
		}				
	}
	catch(e)
	{
	}
}
function CompareLiquid(liquid,obj)
{	
	try
	{
		if (CheckNumber(obj))
		{
			if (parseFloat(formatNumber(liquid.value)) > parseFloat(formatNumber(obj.value)))
			{
				obj.focus();
				//obj.style.background=badfieldbackground;			
				alert("Cannot be less than liquid assets.");
			}
		}	
	}
	catch(e)
	{
	}
}
function CheckNumber(obj)
{		
	var retVal=true;
	if(obj.value != "")
	{
		if(isNaN(formatNumber(obj.value)))
		{
			//set focus and change background									
			obj.focus();
			//obj.style.background=badfieldbackground;	
			retVal=false;		
			alert("Not a valid number, please try again.");
			//obj.value="";
			//obj.focus;			
		}
		if (formatNumber(obj.value) < 0)
		{
			//set focus and change background									
			obj.focus();			
			retVal=false;
			alert("Must be greater than 0, please try again.");
		}
		//_dirty=true;
		//else
		//{		
	//	}
	}
	else
	{
		obj.value=0;
	}
	obj.value = formatCurrency(obj.value);
	return retVal;
}		

function confirmNavigateAway()
{
	if(_dirty){	
		event.returnValue = "Changes will be lost.";
	}
}
function ToggleSpan(spn)
{
	if (spn.style.display == "")
	{
		spn.style.display="none";			
	}
	else
	{
		spn.style.display="";		
	}	
}
function DisableMe(btn)
{
	//hide upload button, show div wait, change to hourglass
	try
	{
		btn.style.display = 'none';
		document.all.divWait.style.display = '';
		document.body.style.cursor = 'wait';		
		document.all.lblError.style.display = 'none';
		//showMsg('Please wait, processing file...');
		//btn.disabled = true;
	}
	catch(e)
	{
	}
}
//used on app, set focus to first control
//for radio buttons it's item 3
function ApplicationFocus()
{
	try
	{
		document.frmMain.elements[1].focus();
	}
	catch(e)
	{
		try
		{
			document.frmMain.elements[3].focus();		
		}
		catch(e)
		{
		}		
	}
}
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; 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 stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

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 isDate(dtStr){
	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){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}