//	This software is the unpublished, confidential, proprietary, intellectual
//	property of Kim David Software, LLC and may not be copied, duplicated, retransmitted
//	or used in any manner without expressed written consent from Kim David Software, LLC.
//	Kim David Software, LLC owns all rights to this work and intends to keep this
//	software confidential so as to maintain its value as a trade secret.

//	Copyright 2004-2009, Kim David Software, LLC.
	
//	File Last Changed:		$LastChangedDate$
//	File Revision Number:	$Revision$

String.prototype.trim = function () {
	return this.replace(/^\s*|\s*$/,"");
}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

// formatPhone
// Takes a phone field and validates that the value of the field is a phone number.
// First, it strips out all but numbers. The value must have at least 10 digits. Any
// digits after the first 10 are the extension. Removes 1 if it is the first digit.
// If it is still a valid phone number (10 or more digits), it is formatted as
// (999) 999-9999 x9999
//
function formatPhone(phoneField,countryField,showAlert) {
	if (phoneField.disabled) {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
	if (countryField == null) {
		countryId = "1000";
	} else {
		countryId = countryField.options[countryField.selectedIndex].value;
	}
	if (countryId != "1000" && countryId != "1001") {
		return true;
	}
 	num = "";
	if (phoneField.value.length == 0) {
		return true;
	}
	for (var x=0;x<phoneField.value.length;x++) {
		thisChar = phoneField.value.charAt(x);
		if ((thisChar >= "0" && thisChar <= "9" && (x>0 || thisChar != "1")) || (num.length > 10 && (thisChar == "*" || thisChar == "#"))) {
			num = num + phoneField.value.charAt(x);
		}
	}
	if (num.length == 7) {
		tempPhone=num.replace(/(\d{3})(\d{4})/,'$1'+'-'+'$2');
		phoneField.value = tempPhone;
	} else if (num.length < 10) {
		if (showAlert) {
			alert('Invalid phone number. Enter 10 digits (plus optional extension)');
		}
		setTimeout("document." + phoneField.form.name + "." + phoneField.name + ".focus()",100);
		return false;
	} else {
		tempPhone=num.replace(/(\d{3})(\d{3})(\d{4})/,'('+'$1'+') '+'$2'+'-'+'$3'+' x');
		if (tempPhone.charAt((tempPhone.length - 1)) == "x") {
			tempPhone = tempPhone.substr(0,tempPhone.length - 2);
		}
		phoneField.value = tempPhone;
	}
	return true;
}

// formatSSN
// Takes a ssn field and validates that the value of the field is a social security number.
// First, it strips out all but numbers. The value must have 9 digits.
// If it is a valid ssn, it is formatted as 999-99-9999
//
function formatSSN(ssnField,showAlert) {
	if (ssnField.disabled) {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
 	num = "";
	if (ssnField.value.length == 0) {
		return true;
	}
	for (var x=0;x<ssnField.value.length;x++) {
		thisChar = ssnField.value.charAt(x);
		if (thisChar >= "0" && thisChar <= "9") {
			num = num + ssnField.value.charAt(x);
		}
	}
	if (num.length == 4) {
		ssnField.value = "X" + "X" + "X" + "-" + "X" + "X" + "-" + num;
		return true;
	}
	if (num.length != 9) {
		if (showAlert) {
			alert('Invalid social security number. Enter 9 digits');
		}
		setTimeout("document." + ssnField.form.name + "." + ssnField.name + ".focus()",100);
		return false;
	} else {
		tempSSN=num.replace(/(\d{3})(\d{2})(\d{4})/,'$1'+'-'+'$2'+'-'+'$3');
		ssnField.value = tempSSN;
	}
	return true;
}

// formatDate
// Takes a date field and validates that it is a valid date. After entry, the date
// is formatted as according to the dateFormat. The default format is mm/dd/yy
//
function formatDate(dateField,dateFormat,minimumValue,maximumValue,showAlert,ignoreYear) {
	if (dateField.disabled) {
		return true;
	}
	if (ignoreYear == null) {
		ignoreYear = false;
	}
	if (dateFormat == null) {
		dateFormat = "m/d/y";
	}
	var todayDate = new Date();
	if (showAlert == null) {
		showAlert = true;
	}
	dtStr = dateField.value;
	if (dtStr.length == 0) {
		return true;
	}
	var daysInMonth = DaysArray(12);
	if (dtStr.length == 3 && !isNaN(dtStr)) {
		dtStr = "0" + dtStr + todayDate.getFullYear();
	}
	if (dtStr.length == 3 && isNaN(dtStr)) {
		dtStr = "0" + dtStr.substring(0,1) + "0" + dtStr.substring(2,3);
	}
	if (dtStr.length == 4 && !isNaN(dtStr)) {
		dtStr = dtStr + todayDate.getFullYear();
	}
	if (dtStr.length == 5 && !isNaN(dtStr)) {
		dtStr = "0" + dtStr;
	}
	if (dtStr.length == 4 || dtStr.length == 5) {
		dtStr = dtStr + "/" + todayDate.getFullYear();
	}
	if (dtStr.length == 6 && !isNaN(dtStr)) {
		dtStr = dtStr.substring(0,2) + "/" + dtStr.substring(2,4) + "/" + dtStr.substring(4,6);
	}
	if (dtStr.length == 8 && !isNaN(dtStr)) {
		dtStr = dtStr.substring(0,2) + "/" + dtStr.substring(2,4) + "/" + dtStr.substring(4,8);
	}
	if (dtStr.length == 10 && dtStr.substring(4,5) == "-" && dtStr.substring(7,8) == "-") {
		dtStr = dtStr.substring(5,7) + "/" + dtStr.substring(8,10) + "/" + dtStr.substring(0,4);
	}
	dtStr = dtStr.replace(/-/g, "/");
	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);
	if (strYear.length==2) {
		if (strYear > 20) {
			strYear = "19" + strYear;
		} else {
			strYear = "20" + strYear;
		}
	}
	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){
		if (showAlert) {
			alert("The date format should be: '" + dateFormat + "'");
		}
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		if (showAlert) {
			alert("Please enter a valid month");
		}
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		if (showAlert) {
			alert("Please enter a valid day");
		}
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		if (showAlert) {
			alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		}
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		if (showAlert) {
			alert("Please enter a valid date");
		}
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return false;
	}
	checkDate = year + "-";
	if (month < 10) {
		checkDate = checkDate + "0";
	}
	checkDate = checkDate + month + "-";
	if (day < 10) {
		checkDate = checkDate + "0";
	}
	checkDate = checkDate + day;

	if (ignoreYear && maximumValue != null && maximumValue.length == 10 && minimumValue != null && minimumValue.length == 10) {
		minMonth = minimumValue.substring(5,7) - 0;
		minDay = minimumValue.substring(8,10) - 0;
		maxMonth = maximumValue.substring(5,7) - 0;
		maxDay = maximumValue.substring(8,10) - 0;

		if (month > minMonth || (month == minMonth && day > minDay)) {
			minimumValue = year + "" + minimumValue.substring(4,10);
		}
		if ((month < minMonth || (month == minMonth && day < minDay)) && (month < maxMonth || (month == maxMonth && day <= maxDay))) {
			minimumValue = (year - 1) + "" + minimumValue.substring(4,10);
		}
		if (maxMonth < minMonth || (minMonth == maxMonth && maxDay < minDay)) {
			maximumValue = (minimumValue.substring(0,4) - 0 + 1) + "" + maximumValue.substring(4,10);
		} else {
			maximumValue = minimumValue.substring(0,4) + "" + maximumValue.substring(4,10);
		}
	}
	if (maximumValue != null && maximumValue.length == 10) {
		if (checkDate > maximumValue) {
			if (showAlert) {
				alert("Invalid date. Must be less than " + sqlToDisplayDate(maximumValue));
			}
			setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
			return false;
		}
	}
	if (minimumValue != null && minimumValue.length == 10) {
		if (checkDate < minimumValue) {
			if (showAlert) {
				alert("Invalid date. Must be greater than " + sqlToDisplayDate(minimumValue));
			}
			setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
			return false;
		}
	}

	var thisDate = new Date(year,month - 1,day);
	
	newValue = thisDate.format(dateFormat);
	dateField.value = newValue;
	return true;
}

function sqlToDisplayDate(sqlDate,useFullDate) {
	if (useFullDate == null) {
		useFullDate = false;
	}
	if (sqlDate == null || (sqlDate.length != 10 && sqlDate.length != 19)) {
		return "";
	}
	var displayDate = sqlDate.substring(5,7) + "/" + sqlDate.substring(8,10) + "/" + (useFullDate ? sqlDate.substring(0,4) : sqlDate.substring(2,4));
	return displayDate;
}

function sqlToDisplayTime(sqlDate) {
	if (sqlDate == null || sqlDate.length != 19) {
		return "";
	}
	var hour = sqlDate.substring(11,13) - 0;
	var minute = sqlDate.substring(14,16) - 0;
	var second = sqlDate.substring(17,19) - 0;
	if (second == 0) {
		second = null;
	}
	var ampm = "am";
	if (hour > 12) {
		ampm = "pm";
		hour -= 12;
	}
	var timeString = hour + ":" + (minute < 10 ? "0" : "") + minute + (second == null ? "" : ":" + (second < 10 ? "0" : "") + second) + " " + ampm;
	return timeString;
}

function hoursToTime(hours,useSeconds) {
	if (useSeconds == null) {
		useSeconds = false;
	}
	if (hours == null || hours.length == 0) {
		return "";
	}
	hours = hours - 0;
	if (hours == 0) {
		return "";
	}
	var hour = Math.floor(hours);
	minutes = Math.round((hours - hour) * 100) * (60 / 100);
	var minute = Math.floor(minutes);
	var second = Math.round((((hours - hour) * 60) - minute) * 60);
	var timeString = hour + ":" + (minute < 10 ? "0" : "") + minute + (!useSeconds || second == 0 ? "" : ":" + (second < 10 ? "0" : "") + second);
	return timeString;
}

function displayToSqlDate(displayDate) {
	if (displayDate == null || (displayDate.length != 8 && displayDate.length != 10)) {
		return "";
	}
	if (displayDate.length == 8) {
		var sqlDate = "20" + displayDate.substring(6,8) + "-" + displayDate.substring(0,2) + "-" + displayDate.substring(3,5);
	} else {
		var sqlDate = displayDate.substring(6,10) + "-" + displayDate.substring(0,2) + "-" + displayDate.substring(3,5);
	}
	return sqlDate;
}

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 stripCharsNotInBag(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 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 formatTime(timeField,showAmPm,showAlert) {
	if (timeField.disabled || timeField.value == "") {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
	if (showAmPm == null) {
		showAmPm = true;
	}
	var timeStr = timeField.value;
	if (timeStr == "") {
		return true;
	}
	var justInteger = true;
	for (i = 0; i < timeStr.length; i++) {
		strChar = timeStr.charAt(i);
		if (strChar < "0" || strChar > "9") {
			justInteger = false;
			break;
		}
	}

	var timePat = /^(\d{1,3}):(\d{1,2})(:(\d{1,2}))?(\s?(AM|am|PM|pm|p|a|P|A))?$/;
	var alternateTimePat = /^(\d{1,3}) (\d{1,2})( (\d{1,2}))?(\s?(AM|am|PM|pm|p|a|P|A))?$/;

	if (justInteger) {
		var matchArray = new Array();
		matchArray[1] = timeStr;
		matchArray[2] = 0;
	} else {
		var matchArray = timeStr.match(timePat);
		if (matchArray == null) {
			matchArray = timeStr.match(alternateTimePat);
		}
		if (matchArray == null) {
			if (showAlert) {
				alert("Time must be in the format hh:mm[:ss]" + (showAmPm ? " am/pm" : ""));
			}
			setTimeout("document." + timeField.form.name + "." + timeField.name + ".focus()",100);
			return false;
		}
	}
	var hour = matchArray[1] - 0;
	var minute = matchArray[2] - 0;
	var second = matchArray[4];
	if (second == undefined) {
		second = "";
	} else {
		second = second - 0;
	}
	var ampm = matchArray[6];
	if (!showAmPm) {
		ampm = "";
	} else {
		if (ampm != "" && ampm != undefined) {
			ampm = ampm.toLowerCase();
		} else {
			ampm = null;
		}
	
		if (second == "") {
			second = null;
		}
		if (ampm == "") {
			ampm = null;
		}
	
		if (ampm == null && hour > 12 & hour <= 24) {
			ampm = "pm";
			hour -= 12;
		}
		if (ampm == "p") {
			ampm = "pm";
		}
		if (ampm == "a") {
			ampm = "am";
		}
		if (ampm == null) {
			if (hour > 6 && hour < 12) {
				ampm = "am";
			} else {
				ampm = "pm";
			}
		}
	}
	if (hour < 0 || (hour == 0 && showAmPm) || (hour > 12 && showAmPm)) {
		if (showAlert) {
			alert(hour + ", Hour must be between 1 and 12.");
		}
		setTimeout("document." + timeField.form.name + "." + timeField.name + ".focus()",100);
		return false;
	}
	if (minute < 0 || minute > 59) {
		if (showAlert) {
			alert ("Minute must be between 0 and 59.");
		}
		setTimeout("document." + timeField.form.name + "." + timeField.name + ".focus()",100);
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
		if (showAlert) {
			alert ("Second must be between 0 and 59.");
		}
		setTimeout("document." + timeField.form.name + "." + timeField.name + ".focus()",100);
		return false;
	}
	timeString = hour + ":" + (minute < 10 ? "0" : "") + minute + (second == null ? "" : ":" + (second < 10 ? "0" : "") + second) + (showAmPm ? " " + ampm : "");
	timeField.value = timeString;
	return true;
}

// formatInteger
// Takes a number field and a money flag and validates that it is a valid number. Strips out all but digits
// and formats the number with commas and a dollar sign, if the money flag is true.
//
function formatInteger(numberField,moneyFlag,minimumValue,maximumValue,noCommas,showAlert) {
	if (numberField.disabled) {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
	strString = numberField.value;
	var strValidChars = "-$0123456789,.";
	var strChar;

	if (strString.length == 0) {
		return true;
	}

	newString = "";
	for (i = 0; i < strString.length; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			if (showAlert) {
				alert("Invalid number. Only chars '0123456789,' are allowed");
			}
			if ("name" in numberField.form) {
				setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
			}
			return false;
		}
		if (strChar == ".") {
			break;
		}
		if (strChar == "-" && newString.length == 0) {
			newString += "-";
		}
		if (strChar >= "0" && strChar <= "9") {
			newString += strChar;
		}
	}
	if (newString == "-") {
		newString = "0";
	}
	newString = newString - 0;
	if (minimumValue == null) {
		minimumValue = -2147483648;
	}
	if (maximumValue == null) {
		maximumValue = 2147483647;
	}
	if (newString < minimumValue || newString > maximumValue) {
		if (showAlert) {
			if (minimumValue == maximumValue) {
				alert("Invalid value... the only valid value is " + minimumValue);
			} else {
				alert("Invalid value... must be between " + minimumValue + " and " + maximumValue);
			}
		}
		if ("name" in numberField.form) {
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
		}
		return false;
	}
	if (noCommas == null || !noCommas) {
		newString = addCommas(parseInt(newString) + "");
	}
	numberField.value = (moneyFlag ? "$" : "") + newString;
	return true;
}

// showSignificant
// takes a number field and strips insignificant digits
//
function showSignificant(inputValue,decimalPlaces,showComma) {
	if (decimalPlaces == null) {
		decimalPlaces = 0;
	}
	if (showComma == null) {
		showComma = false;
	}
	inputValue += "";
	while (inputValue.length > 0 && inputValue.charAt(0) == "0") {
		inputValue = inputValue.substring(1);
	}
	if (inputValue.indexOf(".") != -1) {
		while (inputValue.length > 0 && inputValue.charAt(inputValue.length - 1) == "0") {
			inputValue = inputValue.substring(0,inputValue.length - 1);
		}
	}
	if (inputValue.charAt(inputValue.length - 1) == ".") {
		inputValue = inputValue.substring(0,inputValue.length - 1);
	}
	if (inputValue.length == 0) {
		inputValue = "0";
	}
	if (showComma) {
		inputValue = addCommas(inputValue) + "";
	}
	if (decimalPlaces > 0) {
		if (inputValue.indexOf(".") == -1) {
			inputValue += ".";
		}
		while (inputValue.length < (inputValue.indexOf(".") + decimalPlaces + 1)) {
			inputValue += "0";
		}
		while (inputValue.indexOf(".") < (inputValue.length - decimalPlaces - 1)) {
			inputValue = inputValue.substring(0,inputValue.length - 1);
		}
	}
	if (inputValue.charAt(0) == ".") {
		inputValue = "0" + inputValue;
	}
	return inputValue;
}

// takes a formatted number and makes it a number that can be used in math by stripping all but
// digits, the period, and the negative number.
function makeUsableNumber(strString) {
	var strValidChars = "-0123456789.";
	var strChar;
	strString += "";

	if (strString == null || strString.length == 0) {
		return 0;
	}

	var newString = "";
	var foundDecimal = false;
	for (var i = 0; i < strString.length; i++) {
		var strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			continue;
		}
		if (strChar == "-" && newString.length == 0) {
			newString += "-";
		}
		if ((strChar >= "0" && strChar <= "9") || (strChar == "." && !foundDecimal)) {
			if (strChar == ".") {
				foundDecimal = true;
			}
			newString += strChar;
		}
 	}

	if (newString == "-" || newString.length == 0) {
		newString = "0";
	}
	newString = newString - 0;
	return newString;
}

// formatFloat
// Takes a number field and a money flag and validates that it is a valid number. Strips out all but digits
// and formats the number with commas and a dollar sign, if the money flag is true.
//
function formatFloat(numberField,moneyFlag,decimals,minimumValue,maximumValue,noCommas,showAlert,onlySignificant) {
	if (numberField.disabled) {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
	if (onlySignificant == null) {
		onlySignificant = false;
	}
	var strString = numberField.value;
	var strValidChars = "-$0123456789,.";
	var strChar;

	if (strString.length == 0) {
		return true;
	}

	var newString = "";
	if (decimals == null) {
		decimals = 0;
	}
	var foundDecimal = false;
	var totalDecimals = 0;

	for (i = 0; i < strString.length; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			if (showAlert) {
				alert("Invalid number. Only chars '0123456789,.' are allowed");
			}
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
			return false;
		}
		if (strChar == "-" && newString.length == 0) {
			newString += "-";
		}
		if ((strChar >= "0" && strChar <= "9") || (strChar == "." && !foundDecimal)) {
			if (strChar == ".") {
				foundDecimal = true;
				newString += strChar;
			} else if ((foundDecimal && totalDecimals < decimals) || !foundDecimal) {
				if (foundDecimal) {
					totalDecimals++;
				}
				newString += strChar;
			}
		}
	}
	if (newString == "-") {
		newString = "0";
	}
	newString = newString - 0;
	if (minimumValue == null) {
		minimumValue = -2147483648;
	}
	if (maximumValue == null) {
		maximumValue = 2147483647;
	}
	minimumValue = makeUsableNumber(minimumValue);
	maximumValue = makeUsableNumber(maximumValue);
	if (newString < minimumValue || newString > maximumValue) {
		if (showAlert) {
			if (minimumValue == maximumValue) {
				alert("Invalid value... the only valid value is " + minimumValue);
			} else {
				alert("Invalid value... must be between " + minimumValue + " and " + maximumValue);
			}
		}
		setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
		return false;
	}
	if (noCommas == null || !noCommas) {
		newString = (moneyFlag ? "$" : "") + addCommas(newString);
	} else {
		newString = (moneyFlag ? "$" : "") + newString;
	}
	if (decimals > 0) {
		if (newString.indexOf(".") == -1) {
			newString += ".";
		}
		var maxDecimals = 0;
		while (newString.substring(newString.length - decimals - 1,newString.length - decimals) != "." && maxDecimals < decimals) {
			newString += "0";
			maxDecimals++;
		}
	}
	if (onlySignificant) {
		newString = showSignificant(newString,0,!noCommas);
	}
	numberField.value = newString;
	return true;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function checkColor(colorField,showAlert) {
	if (colorField.disabled) {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
	var str = colorField.value;
	str = str.toUpperCase();
	if (str.length == 0) {
		return true;
	}
	if (str.length != 6) {
		if (showAlert) {
			alert("Invalid color... should be 6 characters, 0-9, A-F.");
		}
		setTimeout("document." + colorField.form.name + "." + colorField.name + ".focus()",150);
		return false;
	}
	for (var x=0;x<str.length;x++) {
		strChar = str.charAt(x);
		if (strChar < "0" || (strChar > "9" && strChar < "A") || strChar > "F") {
			if (showAlert) {
				alert("Invalid color... should be 6 characters, 0-9, A-F.");
			}
			setTimeout("document." + colorField.form.name + "." + colorField.name + ".focus()",150);
			return false;
		}
	}
	colorField.value = str;
	return true;
}

// checkEmail
// validates that the email field has a valid email address in it.
//
function checkEmail(emailField,showAlert) {
	if (emailField.disabled) {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
	var str = emailField.value;
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);

	if (lstr == 0) {
		return true;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr ||
		str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr ||
		str.indexOf(at,(lat+1))!=-1 || str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot ||
		str.indexOf(dot,(lat+2))==-1 || str.indexOf(" ")!=-1) {
		if (showAlert) {
			alert("Invalid E-mail Address");
		}
		setTimeout("document." + emailField.form.name + "." + emailField.name + ".focus()",150);
		return false;
	}
	return true;
}

// checkPassword
// Take the first and second password field and validate that they are the same and that they contain
// the right number and type of characters.
//
function checkPassword(passwordField,password2Field,showAlert) {
	if (passwordField.disabled) {
		return true;
	}
	if (showAlert == null) {
		showAlert = true;
	}
	if (passwordField.value == "" && password2Field.value == "") {
		return true;
	}
	if (password2Field != null) {
		if (passwordField.value.length > 0 && password2Field.value.length > 0 && passwordField.value != password2Field.value) {
			if (showAlert) {
				alert("Passwords are not the same...try again");
			}
			passwordField.value = "";
			password2Field.value = "";
			setTimeout("document." + passwordField.form.name + "." + passwordField.name + ".focus()",100);
			return false;
		}
	}
	if (passwordField.value.length > 0 && passwordField.value.length < 6) {
		if (showAlert) {
			alert("Password must be 6 or more characters and contain at least 1 letter & 1 number");
		}
		passwordField.value = "";
		if (password2Field != null) {
			password2Field.value = "";
		}
		setTimeout("document." + passwordField.form.name + "." + passwordField.name + ".focus()",100);
		return false;
	}
	password = passwordField.value.toLowerCase();
	if (password.search(/[a-z]/) == -1 || password.search(/[0-9]/) == -1) {
		if (showAlert) {
			alert("Password must be 6 or more characters and contain at least 1 letter & 1 number");
		}
		passwordField.value = "";
		if (password2Field != null) {
			password2Field.value = "";
		}
		setTimeout("document." + passwordField.form.name + "." + passwordField.name + ".focus()",100);
		return false;
	}
	return true;
}

// showInfo
// take some text and display it in a small window
//
infoWindow=null;
function showInfo(infoCode,tableName) {
	if (tableName == null) {
		tableName = "";
	}
	var windowWidth=700;
	var windowHeight=400;
	if (infoWindow != null && !infoWindow.closed)
		infoWindow.close();
	windowOptions = 'resizable=yes,scrollbars=yes,width=' + windowWidth + ',height=' + windowHeight + ',screenX=' + Math.floor(screen.width - windowWidth) / 2 + ',left=' + Math.floor(screen.width - windowWidth) / 2 + ',screenY=' + Math.floor(screen.height - windowHeight) / 2 + 'top=' + Math.floor(screen.height - windowHeight) / 2;
	infoWindow = window.open("","",windowOptions);
  	infoWindow.document.location = "shared/moreinfo.php?code=" + infoCode + "&table=" + tableName;
}

// showImage
// display an image in a small window
//
imageWindow=null;
function showImage(keyValue,tableName,fieldName,keyName) {
	if (tableName == null) {
		tableName = "";
	}
	if (fieldName == null) {
		fieldName = "";
	}
	if (keyName == null) {
		keyName = "";
	}
	if (keyValue == null) {
		keyValue = "";
	}
	if (tableName != "" && fieldName == "" && keyName == "" && keyValue == "") {
		keyValue = tableName;
		tableName = "";
		fieldName = "";
		keyName = "";
	}
	if (imageWindow != null && !imageWindow.closed)
		imageWindow.close();
	windowOptions = 'resizable=yes,scrollbars=yes,width=700,height=700,screenX=' + Math.floor(screen.width - 525) / 2 + ',left=' + Math.floor(screen.width - 525) / 2 + ',screenY=' + Math.floor(screen.height - 400) / 2 + 'top=' + Math.floor(screen.height - 400) / 2;
	imageWindow = window.open("","",windowOptions);
	imageWindow.document.location = "getimage.php?table=" + tableName + "&field=" + fieldName + "&key=" + keyName + "&value=" + keyValue;
}

function checkKey(keyField,setUppercase) {
	if (keyField.disabled) {
		return true;
	}
	newValue = "";
	if (setUppercase == null) {
		setUppercase = true;
	}
	for(var x=0;x<keyField.value.length;x++) {
		if (setUppercase) {
			thisChar = keyField.value.charAt(x).toUpperCase();
		} else {
			thisChar = keyField.value.charAt(x).toLowerCase();
		}
		if (thisChar.search(/[A-Z]/) >= 0 || thisChar.search(/[a-z]/) >= 0 || thisChar.search(/[0-9]/) >= 0 || "_-/".indexOf(thisChar) >= 0) {
			newValue = newValue + thisChar;
		}
		if (thisChar == " ") {
			newValue = newValue + "_";
		}
	}
	keyField.value = newValue;
}

// validateCreditCardNumber
// takes the number field and validates the credit card according to industry standards.
//
function validateCreditCardNumber(numberField,showAlert)
{
	if (showAlert == null) {
		showAlert = true;
	}
	var ccNum = numberField.value;
	if (ccNum.substring(0,12) == "XXXXXXXXXXXX") {
		return true;
	}
	if (numberField.value.length > 0 && numberField.value.charAt(0) != "*") {
		var newValue = "";
		for(var x=0;x<numberField.value.length;x++) {
			thisChar = numberField.value.charAt(x).toUpperCase();
			if (thisChar.search(/[0-9]/) >= 0) {
				newValue = newValue + thisChar;
			}
		}
		numberField.value = newValue;
		ccNum = newValue;
		if (!isInteger(ccNum)) {
			if (showAlert) {
				alert('Please enter only numbers (no dashes or spaces) for the Credit Card number');
			}
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",150);
			return false;
		}

		if (!LuhnCheck(ccNum) || !validateCreditCardType(numberField)) {
			if (showAlert) {
				alert('Invalid credit card number');
			}
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
			return false;
		}
	}
	return true;
}

// validateCreditCardType
// validate the credit card number
//
function validateCreditCardType(numberField) {
	var numType = "";
	var ccNum = numberField.value;
	var cardLen = ccNum.length;
	var firstdig = ccNum.substring(0,1);
	var seconddig = ccNum.substring(1,2);
	var first4digs = ccNum.substring(0,4);

	if (((cardLen == 16) || (cardLen == 13)) && (firstdig == "4")) {
		numType = "VISA";
	} else if ((cardLen == 15) && (firstdig == "3") && ("47".indexOf(seconddig)>=0)) {
		numType = "AMEX";
	} else if ((cardLen == 16) && (firstdig == "5") && ("12345".indexOf(seconddig)>=0)) {
		numType = "MC";
	} else if ((cardLen == 16) && (first4digs == "6011")) {
		numType = "DISC";
	} else if ((cardLen == 14) && (firstdig == "3") && ("068".indexOf(seconddig)>=0)) {
		numType = "DINERS";
	}

	if (numType == "") {
		return false;
	}

	return true;
}

function LuhnCheck(str) {
	var result = true;

	var sum = 0;
	var mul = 1;
	var strLen = str.length;

	for (i = 0; i < strLen; i++) {
		var digit = str.substring(strLen-i-1,strLen-i);
		var tproduct = parseInt(digit ,10)*mul;
		if (tproduct >= 10)
			sum += (tproduct % 10) + 1;
		else
			sum += tproduct;
		if (mul == 1)
			mul++;
		else
			mul--;
	}
	if ((sum % 10) != 0)
		result = false;

	return result;
}

function addSelect(selectField,chosenField) {
	selectArray=new Array();
	nextOption = 0;
	for (x=chosenField.options.length;x>0;x--) {
		selectArray[selectArray.length] = chosenField.options[x-1].value;
		chosenField.options[x-1]=null;
	}
	for (x=0;x<selectField.options.length;x++) {
		useIt = selectField.options[x].selected;
		selectField.options[x].selected = false;
		if (!useIt) {
			for (y=0;y<selectArray.length;y++) {
				if (selectArray[y] == selectField.options[x].value) {
					useIt = true;
				}
			}
		}
		if (useIt) {
			var option1 = new Option(selectField.options[x].text,selectField.options[x].value);
			chosenField.options[nextOption++]=option1;
		}
	}
}

function removeSelect(chosenField,removeButton) {
	for (x=chosenField.options.length;x>0;x--) {
		if (chosenField.options[x-1].selected) {
			chosenField.options[x-1]=null;
		}
	}
	removeButton.disabled = true;
}

function checkSelect(chosenField,removeButton) {
	foundOne = false;
	for (x=chosenField.options.length;x>0;x--) {
		if (chosenField.options[x-1].selected) {
			foundOne = true;
			break;
		}
	}
	removeButton.disabled = !foundOne;
}

presentationWindow=null

function setToday(dateField,shortYear) {
	var today = new Date();
	day = today.getDate();
	month = today.getMonth() + 1;
	year = today.getFullYear();
	if (shortYear) {
		year = (year + "").substring(2,4);
	}
	newValue = day + "/";
	if (newValue.length < 3) {
		newValue = "0" + newValue;
	}
	newValue = month + "/" + newValue
	if (newValue.length < 5) {
		newValue = "0" + newValue;
	}
	if (newValue.length < 8) {
		newValue = "0" + newValue;
	}
	dateField.value = newValue + year;
}

function addDays(dateField,numberDays) {
	var oneDay = 3600 * 1000 * 24
	dtStr = dateField.value;
	if (dtStr.length == 10) {
		fullYear = true;
	} else {
		fullYear = false;
	}
	if (dtStr.length == 0) {
		var today = new Date();
		day = today.getDate();
		month = today.getMonth() + 1;
		year = today.getFullYear();
		year = (year + "").substring(2,4);
		newValue = day + "/";
		if (newValue.length < 3) {
			newValue = "0" + newValue;
		}
		newValue = month + "/" + newValue
		if (newValue.length < 5) {
			newValue = "0" + newValue;
		}
		if (newValue.length < 8) {
			newValue = "0" + newValue;
		}
		dtStr = newValue + year;
	}
	try {
		var thisDate = Date.parse(dtStr);
	} catch (err) {
		return;
	}
	var msTime = thisDate + (oneDay * numberDays) + 3600001;
	if (isNaN(msTime)) {
		return;
	}
	var newDate = new Date(msTime);
	var month = newDate.getMonth()
	var day = newDate.getDate()
	var year = newDate.getFullYear() + "";

	month = (((month + 1) < 10) ? "0" : "") + (month + 1);
	day = ((day < 10) ? "0" : "") + day;
	if (!fullYear) {
		year = year.substring(2,4);
	}
	dateField.value = month + "/" + day + "/" + year;
}

function addMonths(dateValue,numberMonths) {
	if (dateValue.length == 10) {
		fullYear = true;
	} else {
		fullYear = false;
	}
	if (dateValue.length == 0) {
		var today = new Date();
		day = today.getDate();
		month = today.getMonth() + 1;
		year = today.getFullYear();
		year = (year + "").substring(2,4);
		newValue = day + "/";
		if (newValue.length < 3) {
			newValue = "0" + newValue;
		}
		newValue = month + "/" + newValue
		if (newValue.length < 5) {
			newValue = "0" + newValue;
		}
		if (newValue.length < 8) {
			newValue = "0" + newValue;
		}
		dateValue = newValue + year;
	}
	try {
		var thisDate = Date.parse(dateValue);
	} catch (err) {
		return;
	}
	var newDate = new Date(thisDate);
	var month = newDate.getMonth() + 1;
	var day = newDate.getDate()
	var year = newDate.getFullYear();

	month = makeUsableNumber(month) + makeUsableNumber(numberMonths);
	while (month < 1 || month > 12) {
		if (month < 1) {
			year--;
			month += 12;
		} else {
			year++;
			month -= 12;
		}
	}
	month = ((month < 10) ? "0" : "") + month;
	day = ((day < 10) ? "0" : "") + day;
	if (!fullYear) {
		year = (year + "").substring(2,4);
	}
	return month + "/" + day + "/" + year;
}

function addNote(noteField,addNoteField,initials,appendNotes,addBullet) {
	if (appendNotes == null) {
		appendNotes = false;
	}
	if (addBullet == null) {
		addBullet = false;
	}
	if (addNoteField.value != "") {
		var noteValue = noteField.value;
		while (noteValue.charCodeAt(noteValue.length-1) == 10 || noteValue.charCodeAt(noteValue.length-1) == 13) {
			noteValue = noteValue.substr(0,(noteValue.length - 1));
		}
		if (noteValue.length > 0) {
			noteValue += "\n";
		}
		var today = new Date();
		day = today.getDate();
		month = today.getMonth() + 1;
		year = today.getFullYear() + "";
		newValue = day + "";
		if (newValue.length < 2) {
			newValue = "0" + newValue;
		}
		newValue = month + "/" + newValue + "/" + year.substring(2,4);
		if (newValue.length < 8) {
			newValue = "0" + newValue;
		}
		addNoteValue = addNoteField.value;
		if (appendNotes) {
			noteField.value = noteValue + (addBullet ? String.fromCharCode(8226) + " " : "") + addNoteValue + '  [' + initials + ", " + newValue + "]\n";
		} else {
			noteField.value = (addBullet ? String.fromCharCode(8226) + " " : "") + addNoteValue + '  [' + initials + ", " + newValue + "]\n" + noteValue;
		}
		noteField.value += "\n";
		addNoteField.value = "";
		addNoteField.focus();
	}
}

var Crc32Tab = new Array( /* CRC polynomial 0xEDB88320 */
/*
  C/C++ language:

  unsigned long Crc32Tab[] = {...};
*/
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,
0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,
0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,
0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,
0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,
0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,
0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,
0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,
0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,
0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,
0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,
0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,
0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,
0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,
0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,
0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D);

function Crc32Add(crc,c) {
  return Crc32Tab[(crc^c)&0xFF]^((crc>>8)&0xFFFFFF);
}

function Crc32Str(str) {
  var n;
  var len=str.length;
  var crc;

  crc=0xFFFFFFFF;
  for (n=0; n<len; n++)
  {
	var code = str.charCodeAt(n);
	if (code == 13 && n<(len - 1) && str.charCodeAt(n+1) == 10) {
		continue;
	}
	if (code > 122) {
		continue;
	}
	if (code < 32) {
		code = 32;
	}
    crc=Crc32Add(crc,code);
  }
  return crc^0xFFFFFFFF;
}

function Hex32(val)
/*
  Convert value as 32-bit unsigned integer to 8 digit hexadecimal number prefixed with "0x".
*/
{
  var n;
  var str1;
  var str2;

  n=val&0xFFFF;
  str1=n.toString(16).toUpperCase();
  while (str1.length<4)
  {
    str1="0"+str1;
  }
  n=(val>>>16)&0xFFFF;
  str2=n.toString(16).toUpperCase();
  while (str2.length<4)
  {
    str2="0"+str2;
  }
  return str2+str1;
}

var globalIE = document.all?true:false;
var globalMouseX = 0;
var globalMouseY = 0;
function getMouseXY(e) {
	if (globalIE) {
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	} else {
		tempX = e.pageX;
		tempY = e.pageY;
	}  
	if (tempX < 0) {
		tempX = 0;
	}
	if (tempY < 0) {
		tempY = 0;
	}
	globalMouseX = tempX;
	globalMouseY = tempY;
}

function dateKeyHandler(dateField,e) {
	var keynum;
	var keyCode;

	if (window.event) {
		e = window.event;
		keynum = e.keyCode;
	} else if (e.keyCode == e.which) {
		keynum = null;
	} else if (e.charCode != e.which) {
		keynum = void 0;
	} else {
		keynum = e.which;
	}

	if (keynum == 46 || (keynum == 43 && dateField.value == "") || (keynum == 61 && dateField.value == "") || (keynum == 45 && dateField.value == "")) {
		if (!dateField.readOnly) {
			manualChangesMade = true;
		}
		var today = new Date();
		day = today.getDate();
		month = today.getMonth() + 1;
		year = today.getFullYear();
		year = (year + "").substring(2,4);
		newValue = day + "/";
		if (newValue.length < 3) {
			newValue = "0" + newValue;
		}
		newValue = month + "/" + newValue
		if (newValue.length < 6) {
			newValue = "0" + newValue;
		}
		if (!dateField.readOnly) {
			dateField.value = newValue + year;
		}
		e.returnValue = false;
		return false;
	}
	if (keynum == 43 || keynum == 61) {
		if (!dateField.readOnly) {
			manualChangesMade = true;
		}
		if (!dateField.readOnly) {
			addDays(dateField,1);
		}
		e.returnValue = false;
		return false;
	}
	if (keynum == 45) {
		if (!dateField.readOnly) {
			manualChangesMade = true;
		}
		if (!dateField.readOnly) {
			addDays(dateField,-1);
		}
		e.returnValue = false;
		return false;
	}
	return true;
}

function makeHttpRequest(url, callback_function) {
	var http_request = false;
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	
	if (!http_request) {
		alert('Unfortunately your browser doesn\'t support this feature. Please contact Customer Service.');
		return false;
	}
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				eval(callback_function + '(http_request)');
			}
		}
	}
	http_request.open('GET', url, true);
	http_request.send(null);
}

function makeHttpPostRequest(url, callback_function, params) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Unfortunately your browser doesn\'t support this feature. Please contact Customer Service.');
		return false;
	}
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				eval(callback_function + '(http_request)');
			}
		}
	}
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.send(params);
}

function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1)
				c_end=document.cookie.length
			return decodeURIComponent(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function checkTabKey(e) {
	var keynum;
	if(BrowserDetect.browser == "Explorer") { // IE
		keynum = e.keyCode;
		if (!window.event.ctrlKey && !window.event.altKey) {
			return true;
		}
	} else if (e.which) { // Netscape/Firefox/Opera
		keynum = e.which;
		if (!e.ctrlKey && !e.altKey) {
			return true;
		}
	}
	if (keynum >= 49 && keynum <= 57) {
		keynum = keynum - 48;
		setTabNumber(keynum, true);
		return false;
	} else {
		return true;
	}
}

function ignoreDeleteKey(e) {
	var keynum;
	if(BrowserDetect.browser == "Explorer") { // IE
		keynum = e.keyCode;
	} else if (e.which) { // Netscape/Firefox/Opera
		keynum = e.which;
	}
	if (keynum == 8) {
		return false;
	} else {
		return true;
	}
}

var lastModifierWasShift = false;
var lastKeyWasTab = false;
var lastKeyWasEnter = false;
var lastKeyWasDelete = false;
var lastKeyWasUp = false;
var lastKeyWasDown = false;
var lastKeyWasRight = false;
var lastKeyWasLeft = false;
var lastKeyWasEscape = false;
var lastKeyWasPageUp = false;
var lastKeyWasPageDown = false;
var lastKeynum = 0;

function storeLastKey(e) {
	var keynum;
	lastModifierWasShift = false;
	if(BrowserDetect.browser == "Explorer") { // IE
		keynum = event.keyCode;
		if (window.event.shiftKey) {
			lastModifierWasShift = true;
		}
	} else {
		keynum = e.which;
		if (e.shiftKey) {
			lastModifierWasShift = true;
		}
	}
	lastKeyWasTab = (keynum == 9);
	lastKeyWasEnter = (keynum == 13 || keynum == 10);
	lastKeyWasDelete = (keynum == 8 || keynum == 46);
	lastKeyWasLeft = (keynum == 37);
	lastKeyWasUp = (keynum == 38);
	lastKeyWasRight = (keynum == 39);
	lastKeyWasDown = (keynum == 40);
	lastKeyWasEscape = (keynum == 27);
	lastKeyWasPageUp = (keynum == 33);
	lastKeyWasPageDown = (keynum == 34);
	lastKeynum = keynum;
}

function isInArray (value,thisArray,caseSensitive) {
// Returns true if the passed value is found in the
// array. Returns false if it is not.
	var i;
	for (i=0; i < thisArray.length; i++) {
// use === to check for Matches. ie., identical (===),
		if (caseSensitive) { //performs match even the string is case sensitive
			if (thisArray[i].toLowerCase() == value.toLowerCase()) {
				return true;
			}
		} else {
			if (thisArray[i] == value) {
				return true;
			}
		}
	}
	return false;
};

function rejectEnter(e) {
	var keynum;
	if(BrowserDetect.browser == "Explorer") { // IE
		keynum = e.keyCode;
	} else if (e.which) { // Netscape/Firefox/Opera
		keynum = e.which;
	}
	if (keynum == 13 || keynum == 10) {
		return false;
	}
	return true;
}

function findPos(obj) {
	var curleft = 0;
	var curtop = 0;
	var tableTopAmountToRemove = 0;
	var tableLeftAmountToRemove = 0;
	var divTopAmountToRemove = 0;
	var divLeftAmountToRemove = 0;
	var tableFound = (BrowserDetect.browser == "Safari");
	var divFound = false;
	if(obj.offsetParent) {
		while(1) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			if (obj.tagName == "TABLE" && !tableFound) {
				tableFound = true;
				tableTopAmountToRemove = obj.offsetTop;
				tableLeftAmountToRemove = obj.offsetLeft;
			}
			if (obj.tagName == "DIV") {
				if (obj.className == "dhtmlwindow") {
					divTopAmountToRemove = obj.offsetTop;
					divLeftAmountToRemove = obj.offsetLeft;
				}
				divFound = true;
			}
			if (!obj.offsetParent) {
				break;
			}
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
		curtop += obj.y;
	}
	if (divFound) {
		curleft -= tableLeftAmountToRemove;
		curtop -= tableTopAmountToRemove;
		curleft -= divLeftAmountToRemove;
		curtop -= divTopAmountToRemove;
	}
	return [curtop,curleft];
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function arrayLength(thisArray) {
	var l = 0;
	for (var k in thisArray) {
		l++;
	}
	return l;
}

function roundNumber(num, dec) {
	if (dec == null) {
		dec = 2;
	}
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

selectAllTimeout = null;
selectAllField = null;

function selectAll(field) {
	if (selectAllField == null) {
		selectAllField = field;
		selectAllTimeout = setTimeout("doSelectAll()",20);
	} else {
		selectAllField = null;
		clearTimeout(selectAllTimeout);
		selectAllTimeout = null;
	}
}

function doSelectAll() {
	if (selectAllField != null) {
		selectAllTimeout = null;
		selectAllField.focus();
		selectAllField.select();
		selectAllField = null;
    }
}

lookupArray = new Array();
lookupArray['inactive'] = new Array();

var customFieldAddWindow = null;
function customFieldAddNew(addScript) {
	if (customFieldAddWindow != null && !customFieldAddWindow.closed) {
		customFieldAddWindow.close();
	}
	var windowWidth=800;
	var windowHeight=600;
	windowOptions = 'menubar=yes,resizable=yes,scrollbars=yes,width=' + windowWidth + ',height=' + windowHeight + ',screenX=' + Math.floor(screen.width - windowWidth) / 2 + ',left=' + Math.floor(screen.width - windowWidth) / 2 + ',screenY=' + Math.floor(screen.height - windowHeight) / 2 + ',top=' + Math.floor(screen.height - windowHeight) / 2;
	customFieldAddWindow = window.open("","customFieldAddWindow",windowOptions);
	customFieldAddWindow.document.location = addScript;
}

function customFieldAdded(fieldName) {
	document.getElementById(fieldName).value=getCookie('added_id');
	document.getElementById(fieldName + "$lookup_text").value=decodeURIComponent(getCookie('added_description'));
}

var customDropdownLookupField = "";
function customFieldMove(fieldName,lookaheadOnly,allowMultiple) {
	if (lookaheadOnly != true) {
		lookaheadOnly = false;
	}
	if (allowMultiple != true) {
		allowMultiple = false;
	}
	if (lastKeyWasUp) {
		if (document.getElementById('select_options').options.length > 0) {
			if (document.getElementById('select_options').selectedIndex > 0) {
				document.getElementById('select_options').selectedIndex--;
			} else {
				document.getElementById('select_options').selectedIndex = 0;
			}
		}
	}
	if (lastKeyWasDown) {
		if (document.getElementById('select_options').options.length > 0) {
			if (document.getElementById('select_options').selectedIndex == -1) {
				document.getElementById('select_options').selectedIndex = 0;
			} else if (document.getElementById('select_options').selectedIndex < (document.getElementById('select_options').options.length - 1)) {
				document.getElementById('select_options').selectedIndex++;
			}
		}
	}
	if (lastKeyWasPageUp) {
		if (document.getElementById('select_options').options.length > 0) {
			if (document.getElementById('select_options').selectedIndex > 5) {
				document.getElementById('select_options').selectedIndex -= 5;
			} else {
				document.getElementById('select_options').selectedIndex = 0;
			}
		}
	}
	if (lastKeyWasPageDown) {
		if (document.getElementById('select_options').options.length > 0) {
			if (document.getElementById('select_options').selectedIndex == -1) {
				document.getElementById('select_options').selectedIndex = 0;
			} else if (document.getElementById('select_options').selectedIndex < (document.getElementById('select_options').options.length - 5)) {
				document.getElementById('select_options').selectedIndex += 5;
			} else {
				document.getElementById('select_options').selectedIndex = (document.getElementById('select_options').options.length - 1);
			}
		}
	}
	return false;
}

function customFieldImage(fieldName,lookupField) {
	if (lookupField == null) {
		lookupField = true;
	}
	document.edit[fieldName + (lookupField ? "$lookup_text" : "")].focus();
	setTimeout("customFieldKeyup('image','" + fieldName + "'," + (lookupField ? "false" : "true") + ")",200);
}

function customFieldKeyup(e,fieldName,lookaheadOnly,lookupIndex,allowMultiple) {
	if (e == "image") {
		lastModifierWasShift = false;
		lastKeyWasTab = false;
		lastKeyWasEnter = false;
		lastKeyWasDelete = false;
		lastKeyWasUp = false;
		lastKeyWasDown = true;
		lastKeyWasRight = false;
		lastKeyWasLeft = false;
		lastKeyWasEscape = false;
		lastKeyWasPageUp = false;
		lastKeyWasPageDown = false;
		lastKeynum = 0;
	}
	if (lookupIndex == null || lookupIndex == "") {
		lookupIndex = fieldName;
	}
	if (lookaheadOnly != true) {
		lookaheadOnly = false;
	}
	if (allowMultiple != true) {
		allowMultiple = false;
	}
	if (lastKeyWasEnter) {
		return false;
	}
	if (lastKeyWasRight || lastKeyWasLeft || lastKeyWasUp || lastKeyWasTab || lastKeyWasPageDown || lastKeyWasPageUp) {
		return true;
	}
	if (lastKeyWasDown && document.getElementById("select_options_div").style.visibility != "hidden") {
		return true;
	}
	if (lastKeyWasEscape) {
		customFieldHideDiv(fieldName);
		return true;
	}
	var keynum;
	if (e != "image") {
		if (BrowserDetect.browser == "Explorer") {
			keynum = e.keyCode;
		} else if (e.which) {
			keynum = e.which;
		}
	} else {
		keynum = 32;
		lastKeyWasDown = true;
	}
	if (keynum == undefined || ((keynum < 32 || keynum > 127) && customDropdownLookupField.length == document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).value.length)) {
		return true;
	}
	customDropdownLookupField = document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).value.toUpperCase();
	if (allowMultiple) {
		var tmpArray = customDropdownLookupField.split(",");
		if (tmpArray.length != 0) {
			customDropdownLookupField = tmpArray[tmpArray.length - 1].replace(/^\s*|\s*$/,"");
		}
	}
	if (customDropdownLookupField.length == 0 && !lastKeyWasDown) {
		return true;
	}
	var originalValue = "";
	if (!lastKeyWasDown) {
		var originalValue = document.getElementById(fieldName).value;
		if (!lookaheadOnly) {
			document.getElementById(fieldName).value = "";
		}
	}
	document.getElementById("select_options").selectedIndex = 0;
	for (x = document.getElementById("select_options").length; x >= 0; x--) {
		document.getElementById("select_options")[x] = null;
	}
	var selectedIndex = -1;
	var thisIndex = 0;
	for (var i in lookupArray[lookupIndex]) {
		if (lastKeyWasDown || customDropdownLookupField == " " || lookupArray[lookupIndex][i].description.toUpperCase().indexOf(customDropdownLookupField) !=  -1) {
			document.getElementById("select_options").options[document.getElementById("select_options").length] = new Option(lookupArray[lookupIndex][i].description, (lookaheadOnly ? lookupArray[lookupIndex][i].description : lookupArray[lookupIndex][i].key_value));
			document.getElementById("select_options").options[document.getElementById("select_options").length - 1].className = 'admin-field-text';
			if (selectedIndex == -1 && lookupArray[lookupIndex][i].description.toUpperCase() >= customDropdownLookupField) {
				selectedIndex = thisIndex;
			}
			thisIndex++;
		}
	}
	if (!lookaheadOnly) {
		if (!lastKeyWasDown && customDropdownLookupField != " ") {
			if (document.getElementById("select_options").length == 1) {
				document.getElementById("select_options").selectedIndex = 0;
				document.getElementById(fieldName + "$lookup_text").value = document.getElementById("select_options")[document.getElementById("select_options").selectedIndex].text;
				document.getElementById(fieldName).value = document.getElementById("select_options")[document.getElementById("select_options").selectedIndex].value;
				customFieldHideDiv(fieldName);
				try {
					eval("onChange_" + fieldName + "();");
				} catch (e) {}
				return;
			}
			if (document.getElementById("select_options").length == 0) {
				if (originalValue == "") {
					customFieldHideDiv(fieldName);
					try {
						eval("onChange_" + fieldName + "();");
					} catch (e) {}
					document.getElementById(fieldName + "$lookup_text").value = "";
				} else {
					customFieldHideDiv(fieldName);
					var foundValue = false;
					for (var i in lookupArray[lookupIndex]) {
						if (lookupArray[lookupIndex][i].key_value == originalValue) {
							document.getElementById(fieldName).value = originalValue;
							document.getElementById(fieldName + "$lookup_text").value = lookupArray[lookupIndex][i].description;
							foundValue = true;
							break;
						}
					}
					if (!foundValue) {
						document.getElementById(fieldName + "$lookup_text").value = "";
						document.getElementById(fieldName).value = "";
					}
				}
				return;
			}
		}
	} else {
		if (document.getElementById("select_options").length == 0) {
			customFieldHideDiv(fieldName);
			return true;
		}
	}
	customFieldShowDiv(fieldName,lookaheadOnly,lookupIndex,allowMultiple);
	if (selectedIndex >= 0) {
		setTimeout("document.getElementById('select_options').selectedIndex = " + selectedIndex,50);
	}
}

function customFieldShowDiv(fieldName,lookaheadOnly,lookupIndex,allowMultiple) {
	if (lookupIndex == null || lookupIndex == "") {
		lookupIndex = fieldName;
	}
	if (lookaheadOnly != true) {
		lookaheadOnly = false;
	}
	if (allowMultiple != true) {
		allowMultiple = false;
	}
	var thisPos = findPos(document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")));
	document.getElementById("select_options_div").style.top = (thisPos[0] + 22) + "px";
	document.getElementById("select_options_div").style.left = (thisPos[1] + 1) + "px";
	document.getElementById("select_options_div").style.width = document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).offsetWidth + "px";
	document.getElementById("select_options").style.width = document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).offsetWidth + "px";
	document.getElementById("select_options_div").style.visibility = "visible";
	document.getElementById("select_options_div").style.display = "block";
}

function customFieldHideDiv(fieldName) {
	document.getElementById("select_options_div").style.visibility = "hidden";
	document.getElementById("select_options_div").style.display = "none";
}

function customFieldSelectValue(fieldName,lookaheadOnly,lookupIndex,allowMultiple) {
	if (lookaheadOnly != true) {
		lookaheadOnly = false;
	}
	if (allowMultiple != true) {
		allowMultiple = false;
	}
	if (document.getElementById("select_options_div").style.visibility == "hidden" || document.getElementById("select_options_div").style.display == "none") {
		return;
	}
	if (document.getElementById("select_options").selectedIndex >= 0) {
		if (document.getElementById("select_options").value != "") {
			customDropdownLookupField = document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).value.toUpperCase();
			if (allowMultiple) {
				while (document.getElementById(fieldName).value != "" && document.getElementById(fieldName).value.substring(document.getElementById(fieldName).value.length - 1) != ",") {
					document.getElementById(fieldName).value = document.getElementById(fieldName).value.substring(0,document.getElementById(fieldName).value.length - 1);
				}
			}
			document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).value = (allowMultiple ? document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).value : "") + document.getElementById("select_options")[document.getElementById("select_options").selectedIndex].text + (allowMultiple ? "," : "");
		} else {
			document.getElementById(fieldName + (lookaheadOnly ? "" : "$lookup_text")).value = "";
		}
		if (!lookaheadOnly) {
			document.getElementById(fieldName).value = document.getElementById("select_options")[document.getElementById("select_options").selectedIndex].value;
		}
	}
	customFieldHideDiv(fieldName);
	try {
		eval("onChange_" + fieldName + "();");
	} catch (e) {}
}

function customFieldSetText(fieldName,lookupKey) {
	if (lookupKey == null) {
		lookupKey = fieldName;
	}
	try {
		var originalValue = document.getElementById(fieldName).value;
		if (originalValue == "") {
			document.getElementById(fieldName + "$lookup_text").value = "";
		} else {
			var foundValue = false;
			for (var i in lookupArray[lookupKey]) {
				if (lookupArray[lookupKey][i].key_value == originalValue) {
					document.getElementById(fieldName).value = originalValue;
					document.getElementById(fieldName + "$lookup_text").value = lookupArray[lookupKey][i].description;
					foundValue = true;
					break;
				}
			}
			if (!foundValue) {
				try {
					for (var i in lookupArray['inactive'][lookupKey]) {
						if (lookupArray['inactive'][lookupKey][i].key_value == originalValue) {
							document.getElementById(fieldName).value = originalValue;
							document.getElementById(fieldName + "$lookup_text").value = lookupArray['inactive'][lookupKey][i].description;
							foundValue = true;
							break;
						}
					}
				} catch (e) {}
			}
			if (!foundValue) {
				document.getElementById(fieldName + "$lookup_text").value = "";
				document.getElementById(fieldName).value = "";
			}
		}
	} catch (e) {alert(e)}
}

function ae_getElementsByClassName(clsName){
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

function ae_addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent){ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}

function ae_getStyle(el, style) {
   if(!document.getElementById) return;
   
     var value = el.style[ae_toCamelCase(style)];
   
    if(!value)
        if(document.defaultView)
            value = document.defaultView.getComputedStyle(el, "").getPropertyValue(style);
       
        else if(el.currentStyle)
            value = el.currentStyle[ae_toCamelCase(style)];
    
    if(value.length>0){
   		value = ((value.charAt(value.length-1,1) == "x") ? parseInt(value.substring(0,value.length-2)) : value);
   	}
    return value;
}

function ae_toCamelCase( sInput ) {
	sInput = sInput.replace('_','-')
    var oStringList = sInput.split('-');
    if(oStringList.length == 1)   
        return oStringList[0];
    var ret = sInput.indexOf("-") == 0 ?
       oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
    for(var i = 1, len = oStringList.length; i < len; i++){
        var s = oStringList[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1)
    }
    return ret;
}

var autoExpand = function(t)
{
	var textarea = t;
	var __minHeight = textarea.offsetHeight;
	var a = parseInt(ae_getStyle(textarea, 'min-height'));
	if (a>0) __minHeight = a;

	// adjust the textarea
	textarea.style.overflow = 'hidden';
	textarea.style.overflowX = 'auto';
	// set the width and height to the correct values
	textarea.style.width = ae_getStyle(textarea, 'width')+'px';
	textarea.style.height = ae_getStyle(textarea, 'height')+'px';
	
	// create a new element that will be used to track the dimensions
	var dummy_id = Math.floor(Math.random()*99999) + '_dummy';
	var div = document.createElement('div');
	div.setAttribute('id',dummy_id);
	document.body.appendChild(div);
	var dummy = document.getElementById(dummy_id);

	// match the new elements style to the textarea
	dummy.style.fontFamily = ae_getStyle(textarea, 'font-family');
	dummy.style.fontWeight = ae_getStyle(textarea, 'font-weight');
	dummy.style.fontSize = ae_getStyle(textarea, 'font-size')+'px';
	dummy.style.width = ae_getStyle(textarea, 'width')+'px';
	dummy.style.padding = ae_getStyle(textarea, 'padding')+'px';
	dummy.style.margin = ae_getStyle(textarea, 'margin')+'px';
	dummy.style.overflowX = 'auto';
	// hide the created div away
	dummy.style.position = 'absolute';
	dummy.style.top = '0px';
	dummy.style.left = '-9999px';
	dummy.innerHTML = '&nbsp;42';
	
	var __lineHeight = dummy.offsetHeight;
	var checkExpand = function(){
		var html = textarea.value;
		html = html.replace(/\n/g, '<br/>new');
		if (dummy.innerHTML != html)
		{
			dummy.innerHTML = html;
			var __dummyHeight = dummy.offsetHeight;
			var __textareaHeight = textarea.offsetHeight;
			ae_debug('Textarea: '+ __textareaHeight);
			ae_debug('Dummy: '+ __dummyHeight);
			if (__textareaHeight != __dummyHeight)
			{
				if (__dummyHeight > __minHeight)
				{
					if (__dummyHeight > 80) {
						__dummyHeight = 80;
						textarea.style.overflow = "auto";
					}
					textarea.style.height = (__dummyHeight+__lineHeight) + 'px';
				}
				else 
				{
					textarea.style.height = __minHeight+'px';
				}
			}
		}
	}
	
	var ae_startExpand = function()
	{
		interval = window.setInterval(function() {checkExpand()}, 500);
	}
	var ae_stopExpand = function()
	{
		clearInterval(interval);
	}
	
	var ae_debug = function(str)
	{
		if(ae_debug==true) document.getElementById('debug').innerHTML += '<br />'+str;
	}
	
	ae_addEvent(textarea, 'focus', ae_startExpand);
	ae_addEvent(textarea, 'blur', ae_stopExpand);
	checkExpand();
}

Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar])
			returnStr += replace[curChar].call(this);
		else
			returnStr += curChar;
	}
	return returnStr;
};

Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() {
		var thisMonth = this.getMonth() + 1;
		if (thisMonth > 11) {
			thisMonth = 0;
		}
		var thisDate = new Date(this.getFullYear(),thisMonth,1);
		msTime = thisDate.getTime() - (3600 * 1000 * 24);
		thisDate = new Date(msTime);
		return (thisDate.getDate() < 10 ? '0' : '') + thisDate.getDate();
	},
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
}

function moveRow(rowNumber,fieldName,maxRows,skipNumber) {
	if (skipNumber == null) {
		skipNumber = 1;
	}
	try {
		var rowIndex = document.getElementById("row_number_" + rowNumber).rowIndex;
		var tableObject = document.getElementById("row_number_" + rowNumber).parentNode.parentNode;
		if (lastKeyWasUp) {
			if (rowIndex <= 1) {
				return;
			}
			rowIndex -= skipNumber;
		} else {
			if (rowIndex >= maxRows) {
				return;
			}
			rowIndex += skipNumber;
		}
		var newRowNumber = tableObject.rows[rowIndex].id.substring(11);
		if (document.getElementById("row_number_" + newRowNumber).style.display == "none") {
			moveRow(newRowNumber,fieldName,maxRows);
		} else {
			document.edit[fieldName + "_" + newRowNumber].focus();
		}
	} catch (e) {alert(e)}
}

function autoCaps(field,addressField) {
	if (field.value == "") {
		return;
	}
	for (x=0;x<field.value.length;x++) {
		if ((field.value.charAt(x)+'').charCodeAt(0) >= 65 && (field.value.charAt(x)+'').charCodeAt(0) <= 90) {
			return;
		}
	}
	if (addressField == null) {
		addressField = false;
	}
	var words = field.value.split(" ");
	var newValue = ""
	for (var x in words) {
		if (newValue != "") {
			newValue += " ";
		}
		if (addressField && (words[x].toUpperCase() == "PO" || words[x].toUpperCase() == "RR" || words[x].toUpperCase() == "SE" || words[x].toUpperCase() == "NE" || words[x].toUpperCase() == "SW" || words[x].toUpperCase() == "NW")) {
			words[x] = words[x].toUpperCase();
		}
		if (words[x].toUpperCase() != "AND" && words[x].toUpperCase() != "OR") {
			newValue += words[x].charAt(0).toUpperCase() + words[x].substring(1);
		} else {
			newValue += words[x];
		}
	}
	field.value = newValue;
}

controlWindow=null;
function goToProgram(programName) {
	var windowWidth=1000;
	var windowHeight=750;
	if (controlWindow != null && !controlWindow.closed)
		controlWindow.close();
	windowOptions = 'resizable=yes,scrollbars=yes,width=' + windowWidth + ',height=' + windowHeight + ',screenX=' + Math.floor(screen.width - windowWidth) / 2 + ',left=' + Math.floor(screen.width - windowWidth) / 2 + ',screenY=' + Math.floor(screen.height - windowHeight) / 2 + 'top=' + Math.floor(screen.height - windowHeight) / 2;
	controlWindow = window.open("","",windowOptions);
  	controlWindow.document.location = "gotoprogram.php?code=" + programName;
}

var popupDateField = null;
var popupDateMinimumValue = null;
var popupDateMaximumValue = null;
var popupTimeout = null;

function showCalendar(dateField,minimumValue,maximumValue) {
	if (!formatDate(dateField,'m/d/y',null,null,false)) {
		return;
	}
	popupDateField = dateField;
	popupDateMinimumValue = minimumValue;
	popupDateMaximumValue = maximumValue;
	var thisPos = findPos(document.getElementById("popup_date_image_" + dateField.name));
	document.getElementById("date_field_popup").style.top = (thisPos[0]) + "px";
	document.getElementById("date_field_popup").style.left = (thisPos[1]) + "px";
	var displayDate = new Date();
	if (dateField.value != "") {
		var dateValue = dateField.value;
		var month = 0;
		var day = 0;
		var year = 0;
		if (dateValue.length == 10) {
			month = dateValue.substring(0,2) - 0;
			year = dateValue.substring(6,10) - 0;
		}
		if (dateValue.length == 8) {
			month = dateValue.substring(0,2) - 0;
			year = dateValue.substring(6,8) - 0;
			if (year > 20) {
				year = year + 1900;
			} else {
				year = year + 2000;
			}
		}
		if (year > 0) {
			day = 1;
		}
		displayDate = new Date(year,month - 1,day);
	}
	document.getElementById("popup_date_month_text").innerHTML = displayDate.format("F Y");
	document.getElementById("popup_date_month").value = displayDate.format("m/Y");
	for (var x=1;x<=42;x++) {
		document.getElementById("pd_" + x).innerHTML = "";
		document.getElementById("pdv_" + x).value = "";
		document.getElementById("pdc_" + x).style.backgroundColor = "";
		document.getElementById("pd_" + x).style.color = "";
	}
	month = displayDate.format("m");
	year = displayDate.format("Y");
	day = 1;
	var todayDate = new Date();
	var newDate = new Date(year,month - 1,day);
	var endOfMonth = new Date(year,month,day);
	var seconds = endOfMonth.getTime() - (86400 * 1000);
	endOfMonth.setTime(seconds);
	var lastDate = parseInt(endOfMonth.format("d"));
	var startDay = newDate.getDay();
	var currentDate = 0;
	for (var x=1;x<=42;x++) {
		if (currentDate == 0) {
			var thisDay = x - 1;
			if (thisDay < startDay) {
				continue;
			}
		}
		currentDate++;
		document.getElementById("pd_" + x).innerHTML = currentDate;
		var thisSqlDate = (new Date(year,month - 1,currentDate)).format("Y-m-d");
		if (todayDate.format("Y-m-d") > thisSqlDate) {
			document.getElementById("pd_" + x).style.color = "#AAAAAA";
		}
		if (popupDateMinimumValue == null || thisSqlDate >= popupDateMinimumValue) {
			document.getElementById("pdv_" + x).value = (new Date(year,month -1,currentDate)).format("m/d/y");
		} else {
			document.getElementById("pdc_" + x).style.backgroundColor = "#CCCCCC";
		}
		if (currentDate >= lastDate) {
			break;
		}
	}
	document.getElementById("date_field_popup").style.display = "";
	try {
		clearTimeout(popupTimeout);
	} catch (e) {}
	popupTimeout = setTimeout("document.getElementById(\"date_field_popup\").style.display = \"none\"",10000);
}

function popupDatePreviousMonth() {
	var dateValue = document.getElementById("popup_date_month").value;
	var month = dateValue.substring(0,2) - 0;
	var year = dateValue.substring(3,7) - 0;
	month--;
	if (month == 0) {
		month = 12;
		year--;
	}
	var day = 1;
	var displayDate = new Date(year,month - 1,day);
	document.getElementById("popup_date_month_text").innerHTML = displayDate.format("F Y");
	document.getElementById("popup_date_month").value = displayDate.format("m/Y");
	for (var x=1;x<=42;x++) {
		document.getElementById("pd_" + x).innerHTML = "";
		document.getElementById("pdv_" + x).value = "";
		document.getElementById("pdc_" + x).style.backgroundColor = "";
		document.getElementById("pd_" + x).style.color = "";
	}
	var todayDate = new Date();
	var endOfMonth = new Date(year,month,day);
	var seconds = endOfMonth.getTime() - (86400 * 1000);
	endOfMonth.setTime(seconds);
	var lastDate = parseInt(endOfMonth.format("d"));
	var startDay = displayDate.getDay();
	var currentDate = 0;
	for (var x=1;x<=42;x++) {
		if (currentDate == 0) {
			var thisDay = x - 1;
			if (thisDay < startDay) {
				continue;
			}
		}
		currentDate++;
		document.getElementById("pd_" + x).innerHTML = currentDate;
		var thisSqlDate = (new Date(year,month -1,currentDate)).format("Y-m-d");
		if (todayDate.format("Y-m-d") > thisSqlDate) {
			document.getElementById("pd_" + x).style.color = "#AAAAAA";
		}
		if (popupDateMinimumValue == null || thisSqlDate >= popupDateMinimumValue) {
			document.getElementById("pdv_" + x).value = (new Date(year,month -1,currentDate)).format("m/d/y");
		} else {
			document.getElementById("pdc_" + x).style.backgroundColor = "#CCCCCC";
		}
		if (currentDate >= lastDate) {
			break;
		}
	}
	document.getElementById("date_field_popup").style.display = "";
	try {
		clearTimeout(popupTimeout);
	} catch (e) {}
	popupTimeout = setTimeout("document.getElementById(\"date_field_popup\").style.display = \"none\"",10000);
}

function popupDateNextMonth() {
	var dateValue = document.getElementById("popup_date_month").value;
	var month = dateValue.substring(0,2) - 0;
	var year = dateValue.substring(3,7) - 0;
	month++;
	if (month > 12) {
		month = 1;
		year++;
	}
	var day = 1;
	var displayDate = new Date(year,month - 1,day);
	document.getElementById("popup_date_month_text").innerHTML = displayDate.format("F Y");
	document.getElementById("popup_date_month").value = displayDate.format("m/Y");
	for (var x=1;x<=42;x++) {
		document.getElementById("pd_" + x).innerHTML = "";
		document.getElementById("pdv_" + x).value = "";
		document.getElementById("pdc_" + x).style.backgroundColor = "";
		document.getElementById("pd_" + x).style.color = "";
	}
	var todayDate = new Date();
	var endOfMonth = new Date(year,month,day);
	var seconds = endOfMonth.getTime() - (86400 * 1000);
	endOfMonth.setTime(seconds);
	var lastDate = parseInt(endOfMonth.format("d"));
	var startDay = displayDate.getDay();
	var currentDate = 0;
	for (var x=1;x<=42;x++) {
		if (currentDate == 0) {
			var thisDay = x - 1;
			if (thisDay < startDay) {
				continue;
			}
		}
		currentDate++;
		document.getElementById("pd_" + x).innerHTML = currentDate;
		var thisSqlDate = (new Date(year,month -1,currentDate)).format("Y-m-d");
		if (todayDate.format("Y-m-d") > thisSqlDate) {
			document.getElementById("pd_" + x).style.color = "#AAAAAA";
		}
		if (popupDateMinimumValue == null || thisSqlDate >= popupDateMinimumValue) {
			document.getElementById("pdv_" + x).value = (new Date(year,month -1,currentDate)).format("m/d/y");
		} else {
			document.getElementById("pdc_" + x).style.backgroundColor = "#CCCCCC";
		}
		if (currentDate >= lastDate) {
			break;
		}
	}
	document.getElementById("date_field_popup").style.display = "";
	try {
		clearTimeout(popupTimeout);
	} catch (e) {}
	popupTimeout = setTimeout("document.getElementById(\"date_field_popup\").style.display = \"none\"",10000);
}

function sPd(dateNumber) {
	if (document.getElementById("pdv_" + dateNumber).value == "") {
		return;
	}
	if (!popupDateField.readOnly) {
		popupDateField.value = document.getElementById("pdv_" + dateNumber).value;
	}
	popupDateField.focus();
	try {
		clearTimeout(popupTimeout);
	} catch (e) {}
	document.getElementById("date_field_popup").style.display = "none";
}

function MakeArray(n){
	this.length=n;
	for(var i=1; i<=n; i++) this[i]=i-1;
	return this
}

hex=new MakeArray(16);
hex[11]="A"; hex[12]="B"; hex[13]="C"; hex[14]="D"; 
hex[15]="E"; hex[16]="F";

function toHex(x) {   // Changes a int to hex (in the range 0 to 255)
	var high=x/16;
	var s=high+"";        //1
	s=s.substring(0,2);   //2 the combination of these = trunc funct.
	high=parseInt(s,10);  //3
	var left=hex[high+1]; // left part of the hex-value
	var low=x-high*16;    // calculate the rest of the values
	s=low+"";             //1
	s=s.substring(0,2);   //2 the combination of these = trunc funct.
	low=parseInt(s,10);   //3
	var right=hex[low+1]; // right part of the hex-value
	var string=left+""+right; // add the high and low together
	return string;
}

function toDec(x) {
	var part1 = x.substring(0,1);
	var part2 = x.substring(1,2);
	var num1 = 0;
	var num2 = 0;
	for (var x=1;x<=16;x++) {
		if (hex[x] == part1) {
			num1 = x - 1;
		}
		if (hex[x] == part2) {
			num2 = x - 1;
		}
	}
	return (num1 * 16) + num2;
}

function fadeout(fieldId) {
	var field = document.getElementById(fieldId);
	var originalColor = field.style.color;
	var currentColor = originalColor;
	if (currentColor == "") {
		if (field.currentStyle) {
			currentColor = field.currentStyle["color"];
		} else if (window.getComputedStyle) {
			currentColor = window.getComputedStyle(field, "").getPropertyValue("color");
		}
	}
	if (currentColor == "") {
		currentColor = "000000";
	}
	if (currentColor.substring(0,3) == "rgb") {
		var colors = currentColor.substring(4,currentColor.length - 1).replace(" ","").replace(" ","").replace(" ","").split(",");
		currentColor = toHex(colors[0]) + "" + toHex(colors[1]) + "" + toHex(colors[2]);
	}
	field.style.color = "#" + currentColor;
	var part1 = currentColor.substring(0,2);
	var part2 = currentColor.substring(2,4);
	var part3 = currentColor.substring(4,6);
	var num1 = toDec(part1);
	var num2 = toDec(part2);
	var num3 = toDec(part3);
	var pauseTime = Math.ceil(500 / (Math.max(num1,Math.max(num2,num3))));
	fadeoutPart(fieldId,originalColor,num1,num2,num3,pauseTime);
}

function fadeoutPart(fieldId,originalColor,num1,num2,num3,pauseTime) {
	if (num1 < 255) num1+=5;
	if (num1 > 255) num1=255;
	if (num2 < 255) num2+=5;
	if (num2 > 255) num2=255;
	if (num3 < 255) num3+=5;
	if (num3 > 255) num3=255;
	var currentColor = toHex(num1) + "" + toHex(num2) + "" + toHex(num3);
	document.getElementById(fieldId).style.color = "#" + currentColor;
	if (num1 < 255 || num2 < 255 || num3 < 255) {
		setTimeout("fadeoutPart('" + fieldId + "','" + originalColor + "'," + num1 + "," + num2 + "," + num3 + "," + pauseTime + ")",pauseTime);
	} else {
		document.getElementById(fieldId).innerHTML = "";
		document.getElementById(fieldId).style.color = (originalColor == "" ? "" : "#") + originalColor;
	}
}

function goToLink(linkUrl,linkTitle,separateWindow) {
	if (separateWindow == null) {
		separateWindow = false;
	}
	if (linkUrl == "") {
		return false;
	}

// check to see if still logged in. If not, present dialog to log back in

	try {
		if (separateWindow) {
			var infoWindow=null;
			var windowWidth=window.innerWidth;
			var windowHeight=window.innerHeight;
			windowOptions = 'toolbar=yes,location=yes,menubar=yes,resizable=yes,scrollbars=yes,width=' + windowWidth + ',height=' + windowHeight + ',screenX=' + Math.floor(screen.width - windowWidth) / 2 + ',left=' + Math.floor(screen.width - windowWidth) / 2 + ',screenY=' + Math.floor(screen.height - windowHeight) / 2 + 'top=' + Math.floor(screen.height - windowHeight) / 2;
			infoWindow = window.open("","",windowOptions);
			infoWindow.document.location = linkUrl;
		} else {
			document.edit.g_next_location.value = linkUrl;
			if (changesMade()) {
				showModal('box');
				return;
			}
			document.location = linkUrl;
		}
	} catch (e) {
		document.location = linkUrl;
	}
	return false;
}

var commonPasswords = new Array('password', 'pass', '1234', '1246','asdf','qwerty');
var minimumLength = 6;
var recommendedLength = 8;
var numbers = "0123456789";
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var punctuation = "!@#$%^&*()_+=-{}[]|\:';,./?><`~";
var strength_label = Array( 'Too short, common or repetitive', 'Weak', 'Fair', 'Medium', 'Strong', 'Very Strong');
var strength_color = Array( 'FF0000', 'FF9900', 'FFCC33', '99CC99', 'ffd801', '3bce08');

function checkPasswordStrength(passwordField,usernameField) {
	var password = passwordField.value;
	var fieldName = passwordField.name;
	var strengthPoints = 0;
	var strengthIndex = 0;
	try {
		if (password.length == 0) {
			document.getElementById(fieldName + "_strengthBar").style.backgroundColor = "";
			document.getElementById(fieldName + "_strengthBarLabel").innerHTML = "";
			return strengthIndex;
		}

		if (usernameField != null) {
			var username = usernameField.value;
			if (password.length >= username.length && password.indexOf(username) == 0) {
				password = password.substring(username.length);
			}
		}
		for (var i=0;i<commonPasswords.length;i++) {
			if (password.length >= commonPasswords[i].length && password.indexOf(commonPasswords[i]) == 0) {
				password = password.substring(commonPasswords[i].length);
			}
		}
		strengthPoints += password.length;
		strengthPoints += (contains(password, numbers) > 0 ? 30 : 0);
		strengthPoints += (contains(password, lowercase) > 0 ? 10 : 0);
		strengthPoints += (contains(password, uppercase) > 0 ? 20 : 0);
		strengthPoints += (contains(password, punctuation) > 0 ? 40 : 0);
		if (password.length > 2) {
			strengthPoints += (contains(password.substring(1,password.length - 1), punctuation) > 0 ? 20 : 0);
		}
		if (password.length > 2) {
			strengthPoints += (contains(password.substring(1,password.length - 1), numbers) > 0 ? 20 : 0);
		}
		if (password.length >= recommendedLength) {
			strengthPoints += 10;
		} else if (password.length >= minimumLength) {
			strengthPoints += 5;
		} else {
			strengthPoints = 0;
		}
		if (isCommonPassword(password)) {
			strengthPoints = 0;
		}
		if (contains(password, numbers + lowercase + uppercase + punctuation) < 3) {
			strengthPoints = 0;
		}
	
		var percentage = strengthPoints / 100;
		var friendlyPercentage = Math.min(Math.round(percentage * 100), 100);
	
		document.getElementById(fieldName + "_strengthBar").style.width = friendlyPercentage + "%";

		if (percentage > .85) {
			strengthIndex = 5;
		} else if (percentage > .7) {
			strengthIndex = 4;
		} else if (percentage > .55) {
			strengthIndex = 3;
		} else if (percentage > .4) {
			strengthIndex = 2;
		} else if (percentage > .25) {
			strengthIndex = 1;
		} else {
			strengthIndex = 0;
		}
		document.getElementById(fieldName + "_strengthBar").style.backgroundColor = "#" + strength_color[strengthIndex];
		document.getElementById(fieldName + "_strengthBarLabel").innerHTML = strength_label[strengthIndex];
	} catch (e) {
		alert(e);
	}
	return strengthIndex;
}

function isCommonPassword(password) {

    for (i = 0; i < commonPasswords.length; i++) {
        var commonPassword = commonPasswords[i];
        if (password == commonPassword) {
            return true;
        }
    }

    return false;

}

function contains(password, validChars) {
    count = 0;
    var usedChars = "";
    for (i = 0; i < password.length; i++) {
        var thisChar = password.charAt(i);
        if (validChars.indexOf(thisChar) > -1 && usedChars.indexOf(thisChar) == -1) {
            count++;
            usedChars += thisChar;
        }
    }

    return count;
}

function setStyleProperty(className,propertyName,propertyValue) {
	var CSSRules;
	if (document.all) {
		CSSRules = 'rules';
	}
	else if (document.getElementById) {
		CSSRules = 'cssRules';
	}
	var foundProperty = false;
	for (var x in document.styleSheets) {
		for (var i = 0; i < document.styleSheets[x][CSSRules].length; i++) {
			if (document.styleSheets[x][CSSRules][i].selectorText == ("." + className)) {
				document.styleSheets[x][CSSRules][i].style[propertyName] = propertyValue;
				foundProperty = true;
				break;
			}
		}
		if (foundProperty) {
			break;
		}
	}
}

function resetTimeoutClock() {
	if (timeoutMinutes < 5 || timeoutMinutes < (maxTimeoutMinutes - 5)) {
		makeHttpRequest("resettimer.php", "handleResetTimeoutClock");
	}
	UnTip();
}

function handleResetTimeoutClock(xmlhttp) {
	var timeoutArray = JSON.parse(xmlhttp.responseText);
	timeoutMinutes = timeoutArray['minutes'];
	try {
		clearInterval(timeoutIntervalId);
	} catch (e) {}
	displayTimeoutClock();
    timeoutIntervalId = setInterval("displayTimeoutClock()",59800);
}

var displayUnder = 15;
var displayHeaderTimeoutClock = false;

function displayTimeoutClock() {
	try {
		var timeoutMessage = "";
		if (timeoutMinutes <= 0) {
			timeoutMessage = "You have been logged out. If you have changes that need to be saved, click the save button and immediately sign back in.";
		} else if (timeoutMinutes <= displayUnder) {
			var hours = Math.floor(timeoutMinutes / 60);
			var minutes = timeoutMinutes - (hours * 60);
			timeoutMessage = "Your session will timeout in " + timeoutMinutes + " minutes";
		}
		document.getElementById("header_center").innerHTML = timeoutMessage;
		if (timeoutMessage != "") {
			document.getElementById("header_center").style.color = "#CC0000";
			document.getElementById("header_center").onmouseover = function(){document.body.style.cursor='pointer';Tip('Click to reset the timer')};
			document.getElementById("header_center").onmouseout = function(){document.body.style.cursor='';UnTip()};
			document.getElementById("header_center").onclick = function(){resetTimeoutClock()};
			document.getElementById("header_center").style.fontSize = "12px";
			document.getElementById("header_center").style.fontWeight = "bold";
		} else {
			document.getElementById("header_center").onmouseover = function(){};
			document.getElementById("header_center").onmouseout = function(){};
			document.getElementById("header_center").onclick = function(){};
		}
		var timeoutClock = "";
		if (displayHeaderTimeoutClock) {
			var hours = Math.floor(timeoutMinutes / 60);
			var minutes = timeoutMinutes - (hours * 60);
			timeoutClock = hours + ":" + (minutes < 10 ? "0" : "") + minutes + "&nbsp;|";
		}
		document.getElementById("timeout_clock").innerHTML = timeoutClock;
		timeoutMinutes--;
	} catch (e) {}
}

function formatExpirationDate(dateField) {
	if (dateField.value == "") {
		return;
	}
	var dateValue = stripCharsNotInBag(dateField.value,"0123456789");
	if (dateValue.length == 4) {
		dateValue = dateValue.substring(0,2) + "/" + dateValue.substring(2,4);
	} else if (dateValue.length == 3) {
		dateValue = "0" + dateValue.substring(0,1) + "/" + dateValue.substring(1,3);
	} else {
		dateValue = "";
	}
	if (dateValue != "") {
		var month = makeUsableNumber(dateValue.substring(0,2));
		if (month < 1 || month > 12) {
			dateValue = "";
		}
	}
	if (dateValue != "") {
		var today = new Date();
		var thisMonth = today.getMonth() + 1;
		var thisYear = today.getFullYear();
		var month = makeUsableNumber(dateValue.substring(0,2));
		var year = makeUsableNumber("20" + dateValue.substring(3,5));
		if (year < thisYear || (year == thisYear && month < thisMonth)) {
			dateValue = "";
		}
	}
	dateField.value = dateValue;
	if (dateValue == "") {
		alert("Invalid expiration date");
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
	}
}

function validateZipCode(zipField) {
	if (zipField.value == "") {
		return;
	}
	var zipValue = stripCharsNotInBag(zipField.value,"0123456789");
	if (zipValue.length != 5) {
		alert("Invalid zip code");
		zipValue = "";
		setTimeout("document." + zipField.form.name + "." + zipField.name + ".focus()",100);
	}
	zipField.value = zipValue;
}

function validateCCV(ccvField) {
	if (ccvField.value == "") {
		return;
	}
	var ccvValue = stripCharsNotInBag(ccvField.value,"0123456789");
	if (ccvValue.length != 4 && ccvValue.length != 3) {
		alert("Invalid CCV code");
		ccvValue = "";
		setTimeout("document." + ccvField.form.name + "." + ccvField.name + ".focus()",100);
	}
	ccvField.value = ccvValue;
}

var ccvHelpWindow=null

function showCCVHelp() {
	if (ccvHelpWindow == null || ccvHelpWindow.closed) {
		var windowWidth=550;
		var windowHeight=600;
		windowOptions = 'resizable=yes,scrollbars=yes,menubar=yes,width=' + windowWidth + ',height=' + windowHeight + ',screenX=' + Math.floor(screen.width - windowWidth) / 2 + ',left=' + Math.floor(screen.width - windowWidth) / 2 + ',screenY=' + Math.floor(screen.height - windowHeight) / 2 + ',top=' + Math.floor(screen.height - windowHeight) / 2;
		ccvHelpWindow = window.open("","",windowOptions);
	} else {
		ccvHelpWindow.focus();
	}
	ccvHelpWindow.document.location = "ccvhelp.php";
}
