
/*
	globalFunctions.js 
	
    Description:
        Functions invoked throughtout application
    
	Functions:
		AutoTab()
		IsEmail()
		IsEmailList(EmailAddress,Delimiters)
		IsNumericList()
		SetCSSClass()
		PercentFormat()
		PremiumFromSchedule()
		popWin()
		popWinCenter()
		ReadCookie()
		SetCookie()
		showHide()
		StripCurrency()
		StripPercent()
		
	JavaScript version of ColdFusion functions, refer to ColdFusion documentation:	
		Compare()
		CompareNoCase()		
		DateFormat() // by matt kruse
		DollarFormat()
		Find()
		FindNoCase()
		IsDate()
		IsNumeric()
		Left()
		Len()
		LCase()
		ListAppend()
		ListDeleteAt()
		ListFind()
		ListFindNoCase()
		ListGetAt()
		ListLen()
		LTrim()
		Mid()
		Replace()
		ReplaceNoCase()
		Reverse()
		Right()
		Round()
		RTrim()
		Trim()
		UCase()
		URLDecode()
		URLEncodedFormat()		

*/

function AutoTab(theField, theID, numChars) {
    if (document.getElementById) {
        if (theField.value.length >= numChars)
            document.getElementById(theID).focus();
    }
}

function Compare(str1,str2){
	if (str1 == str2)	{ return 0;}
	if (str1 > str2)	{ return 1;}	
	else 				{ return -1;}
}

function CompareNoCase(str1,str2){
	var str1 = UCase(str1);
	var str2 = UCase(str2);
	return Compare(str1,str2);
}

// by matt kruse
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

function DateFormat(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}

	
function DecimalFormat(theNumber, Precision){
	if(!Precision){ var Precision = 2;}
	var theNumber = Number(theNumber);
	return theNumber.toFixed(Precision);	
}

function DollarFormat(num) {
	var num = num.toString().replace(/\$|\,/g,'');
	num = num.toString().replace('(','-');
	num = num.toString().replace(')','');
	if(isNaN(num)){
		num = "0";
	}
	var	sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
	var	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 + ((sign)?'':')'));
}

function Find(sb,s){
	return s.toString().indexOf(sb) + 1;
}
	
function FindNoCase(sb,s){		
	return this.Find(sb.toUpperCase(),s.toUpperCase());
}

function IsDate(dateStr) {
	var datePat 	= /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray 	= dateStr.match(datePat);	
	if (matchArray == null) {
		return false;
	}	
	var month 	= matchArray[1];
	var day 	= matchArray[3];
	var year 	= matchArray[5];	
	if (month < 1 || month > 12) { 
		return false;
	}	
	if (day < 1 || day > 31) {
		return false;
	}	
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}	
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day > 29 || (day==29 && !isleap)) {
				return false;
			}
	}
	if (year < 1753) { // sql server 200 and 2005 do not allow dates below 1753 
		return false;
	}
	return true; 
}

function IsEmail(str) {
    if (str.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1){
        return true;
	} else { 
        return false;
	}
}

function IsEmailList(str,delimiters){
		var returnVal 	= true;
		if (delimiters == undefined) var delimiters = ",";
		var EmailAddr 	= str.split(delimiters);
		for (var i in EmailAddr){
		  	if(!IsEmail(EmailAddr[i])){
				returnVal = false;
				break;
			}
		}
	return returnVal;
}

function IsNumeric(num){
	if (isNaN(num) || num.length == 0){
		return false;
	} else {
		return true;
	}
}

function IsNumericList(theList){

	// Regular expressions for hard returns and commas, the only two supported list delimiters at this time
	var reReturn 	= /\r\n/gi;
	var reComma 	= /[,]/gi;
	
	//Strip hard returns and commas then trim the string to make one very big number
	var newList 	= theList.toString().replace(reReturn, "");
	var newList		= newList.replace(reComma, "");
	var thisList 	= Trim(newList);

	// if the string has no length or is not a number it is not a numeric list, return false
	if (Len(thisList) == 0 || isNaN(thisList)){
		return false;
	} else {
		return true; // string is a numeric list, return true
	}
}

function Left(str,count){
	var i = 0;
	var count = count - 1;
	var returnStr = new String(); 	
	for (i; i <= count; i ++){
		returnStr = returnStr + str.charAt(i);
	}
	return returnStr;
}

function Len(str){
	return str.length;
}

function LCase(str){
	return str.toLowerCase();
}

function ListAppend(list, value, delimiters){
	if (delimiters == undefined) var delimiters = ",";
	var returnVal 	= "";
	if (ListLen(list)){
		returnVal = list + delimiters + value;
	} else {
		returnVal = value;
	}
	return returnVal;
}

function ListDeleteAt(list, position, delimiters){
	if (delimiters == undefined) var delimiters = ",";
	var returnVal 		= "";
	var listToArray 	= list.split(delimiters);
	var posInArray		= position - 1;
	var i,posInList;
	var loopTo 			= ListLen(list);
	var thisDelimiter 	= "";

	for(i = 0; i < loopTo; i++){
	
		if (i != posInArray){
			posInList = i + 1;
			if (Len(returnVal)){
				thisDelimiter 	= delimiters;
			}
			returnVal = returnVal + thisDelimiter + ListGetAt(list, posInList, delimiters);
		}
	}
	return returnVal;
}

function ListFind(list,value,delimiters){
	if (delimiters == undefined) var delimiters = ",";
	var returnVal 	= 0;
	var listToArray = list.split(delimiters);
	var loopTo		= ListLen(list);
	for (var i=0; i < loopTo; i++){		
		if (listToArray[i] == value){
			returnVal = i + 1;
			break;
		}
	}
	return returnVal;
}

function ListFindNoCase(list,value,delimiters){
	if (delimiters == undefined) var delimiters = ",";
	return ListFind(UCase(list), UCase(value), delimiters);
}

function ListGetAt(list, position, delimiters){
	if (delimiters == undefined) var delimiters = ",";
	var returnVal 	= "";
	var listToArray = list.split(delimiters);
	var posInArray	= position - 1;
	return listToArray[posInArray];
}

function ListLen(list,delimiters){
	if (delimiters == undefined) var delimiters = ",";
	var count = Len(list);
	var returnNum = 0;
	if (count != 0){
		returnNum = 1;
	} 
	for (i = 0; i <= count; i ++){
		if (list.charAt(i) == delimiters){
			returnNum = returnNum + 1;
		}
	}
	return returnNum;
}

function LTrim(str){
	var str = str.replace(/^\s*/, '');
	return str;
}

function Mid(str,start,count){
	var start  = start - 1;
	var endPos = start + count;	
	return str.slice(start,endPos);
}

function PercentFormat(theValue,thePlaces){
	var rePercent = /[,|%]/gi;	
	var theValue  = theValue.toString().replace(rePercent, "");
	if (!isNaN(theValue)){
		return Round(theValue,thePlaces) + '%';
	} else {
		return theValue;
	}
}

function popWin(theURL,theWidth,theHeight){
	window.open(theURL.replace('#', '%23'), 'PopUp', 'status=yes,scrollbars=yes,resizable=yes,width=' + theWidth + ',height=' + theHeight);
}

function popWinCenter(theURL,theWidth,theHeight){
	var w = 480;
	var h = 340;
	if (document.all || document.layers) {
	   w = screen.availWidth;
	   h = screen.availHeight;
	}
	var popW = theWidth;
	var popH = theHeight;
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;	
	window.open(theURL.replace('#', '%23'), 'popup', 'status=yes,scrollbars=yes,resizable=yes,width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos);
}

function PremiumFromSchedule(ListAmount, ListMultiplier, PerEvery, Amount){

/* PremiumFromSchedule() function
	
	' 07/09/2005
	
	' Description
	' A Calculator that takes a schedule of dollar ranges, a range of multipliers, a loan amount and cost per x 
	' and then calculates a premium
	
	' Arguments:
	' ListAmount - A quoted list of numbers. To represent 0 to $100, $100 to 500 one would pass in "100,500" These are dollar ranges in real world
	' ListMultiplier - A quoted list of numbers to multiply by. These are dollar amounts in real world which is the fee for each range
	' PerEvery - A numeric amount that tells the multiplier "for each of this dollar amount" determine the result
	' Amount - A numeric amount that will fall somewhere in the dollar ranges which is used to determine the total result
	
	
	' Example Usage
	' You have to determine the tax on a $150,000 loan. The tax schedule says between $0 and $100,000 there is to be 
	' $2 tax per every $1000 and between $100,000 and $500,000 there is to be $5 tax per every $1000
	' In this case one would write:
	' result = PremiumFromSchedule("100000,500000","2,5",1000,150000)

*/
	
	
	// turn our two lists arguments, ListAmount and ListMultiplier, into Arrays
	// aAmount is an array of the ListAmount argument
	// ex. aAmount = ListAmount.split(','); is aAmount[0] = 100 aAmount[1] = 500 
	
	var aAmount = ListAmount.split(',');
	var aMulti  = ListMultiplier.split(',');
	

	// amtToSubtract is the previous dollar amount or amounts to take out of total loan amount since we did that math
	var amtToSubtract = 0;
	
	// Need to remember the lower end of the dollar range so we only tax the amount between the lower range and end range
	var LastLowerRange = 0;
	
	// run a counter in the loop so we know which index to get in the aMulti array
	var counter = 0;
	
	// variable to keep our running result which we will add to
	var result = 0;
	
	var AmountToUse = 0;
	
	// Loop over the ListAmount ranges which is the aAmount Array
	for (thisVal in aAmount){
	
		// set this value to the value in the split range Amount array index
		thisVal = aAmount[thisVal];
		
		// set how much money is left to work with
		AmtLeft = Amount - amtToSubtract;
		
		// if the amount left is greater than 0 we have work to do
		if (AmtLeft > 0){
	
			// set the Amount to Use in the formula by default to the high end of the range minus the low end of the range
			AmountToUse = thisVal - LastLowerRange;
			
			
			// if the Amount Left is less than the amount to use lets change the amount to use in the formula to the amount left 
			if (AmtLeft < AmountToUse){ 			
				AmountToUse = AmtLeft;	
			} 
		
			// forumla to add to our result 
			result = result + (aMulti[counter] * (AmountToUse / PerEvery));
		}
		
		// lets remember the Amount to Subtract for the next cycle of the loop
		amtToSubtract = amtToSubtract + AmountToUse;
		
		// lets remember the lower end of the range for the next cycle
		LastLowerRange = thisVal;
		
		// and finally lets add one to the counter
		counter =  counter + 1;
	}
	
	// return the running total formated to two decimal places
	return result.toFixed(2);
}

function Replace(str,substr1,substr2){
	return str.toString().replace(substr1,substr2);
}

function ReadCookie(cookieName) {
	 var theCookie 	= "" + document.cookie;
	 var ind 		= theCookie.indexOf(cookieName);	 
	 if (ind==-1 || cookieName=="") return ""; 
	 var ind1		= theCookie.indexOf(';',ind);	 
	 if (ind1==-1) ind1=theCookie.length; 
	 return unescape(theCookie.substring(ind + cookieName.length+1, ind1));
}

function ReplaceNoCase(s,sb1,sb2,sc){
	if(!sc || sc.toUpperCase() != "ALL"){
		sc = "i";
	} else {
		sc ="gi";
	} 	
	var re = new RegExp(sb1,sc);
	return s.toString().replace(re,sb2);
}

function Reverse(str){
	var i = Len(str);
	var returnStr = new String();	
	for (i; 0 <= i; i--){	
		var returnStr = returnStr + str.charAt(i);	
	}	
	return returnStr;
}

function Right(str,count){
	var returnStr = Reverse(str);
	var returnStr = Left(returnStr,count);
	var returnStr = Reverse(returnStr);	
	return returnStr;
}

function Round(theNum,Places) {
	var rePercent = /[,|%]/gi;
	var theNum = theNum.toString().replace(rePercent, '');
	x = Number(theNum);
	if (!isNaN(x.toFixed(Places))){
		return x.toFixed(Places);
	} else {
		return theNum;
	}
}

function RTrim(str){
	var str = str.replace(/\s*$/, ''); 
	return str;
}

function SetCookie(Name,Value,nDays) {	
	 var today = new Date();
	 var expire = new Date();
	 if (nDays==null || nDays==0){
	  	var nDays=1;
	 }
	 expire.setTime(today.getTime() + 3600000 * 24 * nDays);
	 document.cookie = Name + "=" + escape(Value) + ";expires=" + expire.toGMTString();
}

function SetCSSClass(ID, className){
	if (document.getElementById){
		document.getElementById(ID).className = className;
	}
}

function showHide(theID, dspValue){
	document.getElementById(theID).style.display = dspValue;
}

// strips currency formating (removes commas and dollar sign)
function StripCurrency(theNumber){
	var num = theNumber.toString().replace(/[,|$]/gi,''); 
	num = num.toString().replace('(','-');
	num = num.toString().replace(')','');
	return num;
}

// strips percent formating (removes commas and percent sign)
function StripPercent(theNumber){
	return theNumber.replace(/[,|%]/gi,'');
}

function Trim(s){
	return s.toString().replace(/^\s*|\s*$/g,'');
}

function UCase(str){
	return str.toUpperCase();
}

function URLDecode(str){
	return unescape(str);
}

function URLEncodedFormat(str){
	return escape(str);
}