
var blnUseDollar = false;
var blnUseParenthesis = false;
var blnUseNegative = false;
var VALIDATION_TYPE_NULL = 1;
var VALIDATION_TYPE_INTEGER = 2;
var VALIDATION_TYPE_DECIMAL = 3;
var VALIDATION_TYPE_CURRENCY = 4;
var VALIDATION_TYPE_DATE = 5;
 
//Validates null fields.
function validateNull(frm, flds) {
	var ss = document.getElementById('sessionLanguage').value;
	var bln = true;
	var message = '';
	var fcs = null;
	for(key in flds) {
		var objFld = frm.elements[key];
		if(typeof(objFld) != 'undefined') {
			var strCheck = '';
			if(objFld.type == "select-one" && objFld.options.length > 0) 
				strCheck = objFld.options[objFld.selectedIndex].value;
			else strCheck = objFld.value; 
			strCheck = trim(strCheck);
			if(strCheck == "" || strCheck == null) {
				if(ss == 'fr')
					message = message + "Entrez s'il vous plaît une valeur pour le " + flds[key] + " champ.\n";
				else
					message = message + "Please enter a value for the " + flds[key] + " field.\n";
				if(fcs == null) { fcs = 1; objFld.focus(); }
				bln = false;
			}
		}
	}
	if(message != '') alert(message);
	return bln;
}

function validateEmail(fld) {
    var tfld = trim(fld.value); // value of field with whitespace trimmed off
    var emailFilter = /^[\w\.-]+@[\w\.-]+\.\w+$/i;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/;
    if (fld.value == "") {
    	alert("* You didn't enter an email address.\n");
			fld.focus();
			return false;
    } 
		else if (!emailFilter.test(tfld)) {  //test email for illegal characters
    	alert("* Please enter a valid email address.\n");
			fld.focus();
			return false;
    } 
		else if (fld.value.match(illegalChars)) {
    	alert("* The email address contains illegal characters.\n");
			fld.focus();
			return false;
	} 
		else { return true; }
}


function isValidCreditCard(type, ccnum) {
	var bln = true;
	try {
		//alert(card_type.name+', '+card_number.name+','+card_type.value+', '+card_number.value);
		// Remove all dashes for the checksum checks to eliminate negative numbers
		ccnum = ccnum.split("-").join("");
		// Remove all empty spaces in card no for the checksum checks.
		ccnum = ccnum.split(" ").join("");
		var re;
		if (type == "V") {
			// Visa: length 16, prefix 4, dashes optional.
			re = /^4\d{3}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/;
		} 
		else if (type == "M") {
			// Mastercard: length 16, prefix 51-55, dashes optional.
			re = /^5[1-5]\d{2}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/;
		} 
		else if (type == "Disc") {
			// Discover: length 16, prefix 6011, dashes optional.
			re = /^6011[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/;
		} 
		else if (type == "AX") {
			// American Express: length 15, prefix 34 or 37.
			re = /^3[4,7]\d{13}$/;
		} 
		else if (type == "DC") {
			// Diners: length 14, prefix 30, 36, or 38.
			re = /^3[0,6,8]\d{12}$/;
		}
		else {re = /^$/; }
		if (!re.test(ccnum))  {
			alert('Credit Card No. is not valid.');
			document.getElementById('card_number').focus();
			bln = false;
		}

		if (bln == true) {
			var checksum = 0;
			//var str = '';
			var m = 1;
			for (var n=ccnum.length-1; n>=0; n--) {
				var dg = parseInt(ccnum.charAt(n)) * m;
				if(parseInt(dg) > 9) {
					dg = dg - 9;
				}
				checksum += dg;
				if (m == 1) {m = 2;} else {m = 1;} //str += '\n'+n+' - '+ccnum.charAt(n)+'('+dg*m+') : '+dg;
			}
			//alert(str); alert('checksum = '+checksum);
			if ((checksum % 10) == 0) { 
				bln = true;
			}
			else {
				alert('Credit Card # is not valid.');
				card_number.focus();
				bln = false;
			}
		}
	} 
	catch(e){ alert(e.message); bln = false; }
	return bln;
}





//Validates fields of the specified type.
function validateType(frm, flds, strVldChrs, blnCurrency) {
	var blnValidChar = false;
	resetGlobalVars();	
	for(key in flds) {
		var objFld = frm.elements[key];
		if(typeof(objFld) != 'undefined') {
			var strCheck = '';
			if(objFld.type == "select-one")
				strCheck = new String(objFld.options[objFld.selectedIndex].value);
			else 
				strCheck = new String(objFld.value);	
			for(j = 0; j < strCheck.length; j++) {
				var ch = strCheck.charAt(j);
				for(k = 0; k < strVldChrs.length; k++) {
					if (ch == strVldChrs.charAt(k)) {
						blnValidChar = true;
						break;
					}
				}
				blnValidChar = checkValidChar(ch, strCheck.length, j, blnValidChar, blnCurrency);
				if(!blnValidChar) {
					alert("You have entered an unacceptable character in the " + flds[key] + " field.");
					objFld.focus();
					return false;
				}
				blnValidChar = false;
			}
			if(!checkValidString(strCheck)) {
				alert("You have entered an invalid string in the " + flds[key] + " field.");
				objFld.focus();
				return false;
			}
			if(blnCurrency)
				prepareMoneyField(objFld);
		}
	}	
	return true;
}

//Validates date fields.
function validateDate(frm, flds) {
	for(key in flds) {
		var objFld = frm.elements[key];
		if(typeof(objFld) != "undefined") {
			var dateValue = trim(new String(frm.elements[key].value));
			if(!validDate(dateValue) && dateValue != "") {
				alert("You have entered an invalid date format in the " + flds[key] + " field.");
				return false;				
			}
		}
	}
	return true;
}

//Checks the specified character to ensure that it is valid.
function checkValidChar(ch, chkStrLength, j, blnValidChar, blnCurrency) {
	if((j == 0) && (ch == "$") && (blnCurrency)) {
		blnUseDollar = true;
		blnValidChar = true;
	}
	else if((j == 0) && (ch == "-")) {
		blnUseNegative = true;
		blnValidChar = true;
	}
	else if((j == 0) && (ch == "(")) {
		blnUseParenthesis = true;
		blnValidChar = true;
	}
	else if((j == 1) && (blnUseNegative) && (ch == "$") && (blnCurrency)) {
		blnValidChar = true;
	}
	else if((j == 1) && (blnUseDollar) && (ch == "-")) {
		blnValidChar = true;
	}
	else if((j == 1) && (blnUseDollar) && (ch == "(")) {
		blnUseParenthesis = true;
		blnValidChar = true;
	}
	if((j == (chkStrLength - 1)) && (blnUseParenthesis) && (ch == ")"))
		blnValidChar = true;
	else if((j == (chkStrLength - 1)) && (blnUseParenthesis) && (ch != ")"))
		blnValidChar = false;
	return blnValidChar;
}

//Validates the current string.
function checkValidString(strCheck) {
	var arrResults;
	//Check some obvious invalid strings
	if((strCheck == "$") || (strCheck == "-") || (strCheck == "(")  || (strCheck == "."))
		return false;
	else if((strCheck == "-$") || (strCheck == "$-") || (strCheck == "$.") || (strCheck == "()"))
		return false;
	else if((strCheck == "$()") || (strCheck == "(.)"))
		return false;
	//Check if there is more than one decimal
	arrResults = strCheck.match(/\./g);
	if(arrResults != null)
	if(arrResults.length > 1)
	return false;
	//Check for correct formatting of commas
	arrResults = strCheck.match(/,/g);
	if(arrResults != null) {
		var arrCommaResults, strValidate, i, j;
		strValidate = strCheck.replace("$", "");
		strValidate = strValidate.replace("-", "");
		strValidate = strValidate.replace("(", "");
		strValidate = strValidate.replace(")", "");
		arrResults = strValidate.split(".");
		for(i = 0; i < arrResults.length; i++) {
			if(i == 0) {
				arrCommaResults = arrResults[i].split(",");
				for(j = 0; j < arrCommaResults.length; j++) {
					if((arrCommaResults[0].length > 3) || (arrCommaResults[0].length == 0))
						return false;
					else if((j > 0) && (arrCommaResults[j].length != 3))
						return false;
				}
			}
			else {
				arrCommaResults = arrResults[i].match(/,/g);
				if(arrCommaResults != null)
				return false;
			}
		}
	}	
	return true;
}

//Resets the global variables to false.
function resetGlobalVars() {
	blnUseDollar = false;
	blnUseParenthesis = false;
	blnUseNegative = false;
}
	
function formatPhone(fld) {
/**
var phone = fld.value;
replaceChars = Array("(", ")", "-", " ", ".", ",", "[", "]", "{", "}", "|", ";", ":");
for(var i = 0; i < replaceChars.length; i++) {
phone = replaceChar(phone, replaceChars[i], "");
}
fld.value = phone;
*/
}

function replaceChar(text, find, repl) {
	var strText = new String(text);
	var newText = "";
	for(var i = 0; i < strText.length; i++) {
		if(strText.charAt(i) == find)
			newText += repl;
		else 
			newText += strText.charAt(i);
	}
	return newText;	
}

function formatMoney(s) {
	var strMoney = trimToNumbers(s);
	if(strMoney != "") {
		var decPos = strMoney.indexOf(".");
		if(decPos == -1) {
			strMoney += ".00";
		}
		else if(decPos == strMoney.length - 2) {
			strMoney += "0";
		}
		else if(decPos == strMoney.length - 1) {
			strMoney += "00";
		}
	}
	else {
		return "$0.00";
	}
	// Add commas	
	var strNumbers = strMoney.substring(0, strMoney.indexOf("."));
	var strDecimals = strMoney.substring(strMoney.indexOf(".") + 1, strMoney.length);
	var strReverseNumbers = "";
	var strNewNumbers = "";
	if(strNumbers.length > 3) {
		var counter = 1;
		for(var i = strNumbers.length - 1; i > -1; i--) {
			strReverseNumbers += strNumbers.charAt(i);
			if(counter % 3 == 0 && i > 0) {
				strReverseNumbers += ",";
			}
			counter++;
		}
		for(var i = strReverseNumbers.length - 1; i > -1; i--) {
			strNewNumbers += strReverseNumbers.charAt(i);
		}		
	}
	else {
		strNewNumbers = strNumbers;
	}
	strMoney = "$" + strNewNumbers + "." + strDecimals;
	return strMoney;
}

/**
* Removes all non-numeric characters from the specified string.
*/
function trimToNumbers(value) {
	var s = new String(value);
	retVal = "";
	var arrNumbers = Array("0","1","2","3","4","5","6","7","8","9",".");
	var addChar = false;
	for(var i = 0; i < s.length; i++) {
		for(j = 0; j < arrNumbers.length; j++) {
			if(s.charAt(i) == arrNumbers[j]) {
				retVal += s.charAt(i);
				break;
			}
		}
	}
	return retVal;
}

function unformatMoney(strValue) {
	while(strValue.indexOf("$") >= 0)
	strValue = strValue.replace(/\$/, "");
	while(strValue.indexOf(",") >= 0)
	strValue = strValue.replace(/,/, "");
	return strValue;
}

function prepareMoneyField(fld) {
	fld.value = trimToNumbers(fld.value);
}

function round(number,X) {
	// rounds number to X decimal places, defaults to 2
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

function removeAssArrayItem(a, remKey) {
	var b = Array();
	for(key in a) {
		if(key != remKey)
			b[key] = a[key];	
	}
	return b;
}

/*******************************
* Start Date Validation Functions
********************************/
/**
* Validates a string as a date.
* 
* @param dateIn String the date to validate.
* @return True if this is a valid date, otherwise false.
*/

function validDate(/*String*/ dateIn) {
	var errMsg = "";
	var arrDate = dateIn.split("/");
	if(arrDate.length!=3)
		return false;
	var day = arrDate[1];
	var month = arrDate[0];
	var year = arrDate[2];
	if(month.length==2 && month.charAt(0)== '0') {
		month = month.charAt(1);		
	}
	if(day.length==2 && day.charAt(0)== '0') {
		day = day.charAt(1);		
	}	
	if(arrDate.length != 3) {
		return false;
	}
	if(!(isInt(month) && parseInt(month) > 0 && parseInt(month) <= 12 )) {
	errMsg = "Not a valid month";
	return false;
	}
	if(!(isInt(year) && parseInt(year) > 1850 && parseInt(year) <= 2100)) {
	errMsg = "Not a valid year";
	return false;
	}	
	if(!(isInt(day) && parseInt(day) > 0 && parseInt(day) <= daysInMonth(month, year))) {
	errMsg = "Not a valid day";
	return false;
	}
	return true;
}

function isInt(/*String*/ strin) {
	var validDigits = "0123456789";
	for(var i = 0; i < strin.length; i++) {
		if(validDigits.indexOf(strin.charAt(i)) < 0)
			return false;
	}
	return true;
}

//must take a valid month as String or Int: two digit  01, 02 ...12 or one digit 1,2 ...12
function daysInMonth(/*String*/month, year) {
	var m = parseInt(month)
	if(m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10  || m == 12) {
		return 31;
	}
	else if(m == 4 || m == 6 || m == 9 || m == 11) {
		return 30;
	} 
	else if(m == 2) {
		if(isLeapYear(year)) {
			return 29;
		}
		else {
			return 28;
		}		
	}
}

function isLeapYear(/*String*/ year) {
	year = year + "";
	if(year.length == 2) {
		//placeholder for if we handle 2 digit dates in the future
	}
	if(year.length == 4) {
		if((parseInt(year) % 4 == 0) && (!(parseInt(year) % 100 == 0) || (parseInt(year) % 400 == 0)))
			return true;
	}
	return false;
}

/****************************
* End Date Validation Functions
******************************/
function validateField(validation_type, fld, field_name, field_caption) {
	var frm = fld.form;
	var strName = new String(fld.name).toString();
	var strCaption = new String(field_caption);
	var flds = Array();
	flds[field_name] = field_caption;
	//NULL VALIDATION
	if(validation_type == VALIDATION_TYPE_NULL) {
		if(!validateNull(frm, flds))
			return false;
	}
	else if(validation_type == VALIDATION_TYPE_DATE) {
		if(!validateDate(frm, flds))
			return false;
	}
	else if(validation_type == VALIDATION_TYPE_INTEGER) {
		strVldChrs = "0123456789,";
		if(!validateType(frm, flds, strVldChrs, false))
			return false;
	}
	else if(validation_type == VALIDATION_TYPE_DECIMAL) {
		strVldChrs = "0123456789.,";
		if(!validateType(frm, flds, strVldChrs, false))
			return false;
	}
	else if(validation_type == VALIDATION_TYPE_CURRENCY) {	
		strVldChrs = "0123456789.,";
		if(!validateType(frm, flds, strVldChrs, true))
			return false;
	}
	return true;
}

function dp(number, X) {
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

function updateHiddenField(hid, src) {
	hid.value = src.value;
}

function autoFormatPhoneNumber(fld) {
	var phone = trimPhoneNumber(fld.value);
	var newPhone = "";
	if(phone.length == 10) {
		newPhone = "(" + phone.substring(0, 3) + ") " + phone.substring(3, 6) + "-" + phone.substring(6, 10);
		fld.value = newPhone;
	}
}

/**
* Removes all non-numeric characters from the specified string.
*/
function trimPhoneNumber(value) {
	var s = new String(value);
	retVal = "";
	var arrNumbers = Array("0","1","2","3","4","5","6","7","8","9");
	var addChar = false;
	for(var i = 0; i < s.length; i++) {
		for(j = 0; j < arrNumbers.length; j++) {
			if(s.charAt(i) == arrNumbers[j]) {
				retVal += s.charAt(i);
				break;
			}
		}
	}
	return retVal;
}


