// Add event handler to body when window loads
function addLoadEvent(func) {
	var oldonload = window.onload;
	
	if (typeof window.onload != "function") {
		window.onload = func;
	} else {
		window.onload = function () {
			oldonload();
			func();
		}
	}
}

addLoadEvent(function () {
	// More code to run on page load
	
});

function launchWin(helpURL, size){
	// size string should have the format of 'width=#,height=#'
	var firstEqual = size.indexOf("=") + 1;
	var comma = size.indexOf(",") + 1;
	var secondEqual =  size.lastIndexOf("=") + 1;
	var sizeLen = size.length;
	
	var w = parseInt(size.substring(firstEqual, comma));
	var h = parseInt(size.substring(secondEqual, sizeLen));
	
	var xPos = (screen.height - h) / 2;
	var yPos = (screen.width - w) / 2;
	remote = window.open(helpURL, "", size+",toolbar=1,scrollbars=1,resizable=1,left="+yPos+",top="+xPos);
	remote.focus();
}

// Validate string value
function isString(strValue) {
	return (typeof strValue == "string" && strValue != "" && isNaN(strValue));
}

// Validate numeric value
function isNumber(strValue) {
	return (!isNaN(strValue) && strValue != "");
}


// Validate email address
function isEmail(strValue) {
	var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;
	return (strValue != "" && objRE.test(strValue));
}

// Validate select box selection
function isSelected(objField) {
	if ((objField.multiple && objField.selectedIndex == -1) || (!objField.multiple && objField.selectedIndex == 0)) {
		return false;
	} else {
		return true;
	}
}

// Validate various types
function validate(arrFields) {
	var isValid = true;
	
	for (var i = 0; i < arrFields.length; i++) {
		// arrTheField: [label, id, type, required]
		var arrTheField = arrFields[i].split("|");
		var strLabel = arrTheField[0];
		var objField = document.getElementById(arrTheField[1]);
		var strType = arrTheField[2];
		var req = arrTheField[3];
		
		// Check if field is required or not required and not empty
		if (req == "true" || (req == "false" && objField.value != "")) {
			switch (strType) {
				case "string":
					isValid = isString(objField.value.replace(/^\s*|\s*$/g, ''));
					break;
				case "number":
					isValid = isNumber(objField.value);
					break;
				case "email":
					isValid = isEmail(objField.value);
					break;
				case "select":
					isValid = isSelected(objField);
					break;
				case "any":
					isValid = (objField.value == "" ? false : true);
					break;
				default:
					isValid = true;
			}
		}
		
		if (!isValid) {
			// If field is invalid, alert user, stop validating
			var errMessage = "";
			errMessage = "The information you provided for \"" + strLabel + "\" is invalid.\n";
			errMessage += "Please correct this and submit again.";
			alert(errMessage);
			
			if (objField.nodeName.toLowerCase() != "select") {
				objField.select();
			}
			
			objField.focus();
			return false;
		}
	}
	
	return true;
}

// Validates credit card numbers format
function ccCheck(ccType, ccNumber) {
	// Set some vars, find objects passed based on ID
	var isValid = true;
	var objCardType = document.getElementById(ccType);
	var objCardNumber = document.getElementById(ccNumber);
	
	// Strip non digits from number
	var cardNumber = objCardNumber.value.replace(/\D/g, "");
	
	// Validate format
	switch (objCardType.value.toLowerCase()) {
		case "american express":  // American Express - length: 15, prefix: 34 or 37
			isValid = /^3[4,7]\d{13}$/.test(cardNumber);
			break;
		case "mastercard":        // Mastercard - length: 16, prefix: 51-55
			isValid = /^5[1-5]\d{14}$/.test(cardNumber);
			break;
		case "visa":              // Visa - length: 16, prefix: 4
			isValid = /^4\d{15}$/.test(cardNumber);
			break;
		default:
			isValid = true;
	}
	
	// Check Luhn formula
	if (isValid) isValid = luhnCheck(cardNumber); 
	
	// Return error message if anything is invalid
	if (!isValid) {
		var errMessage = "";
		errMessage = "The credit card number you provided is invalid.\n";
		errMessage += "Please correct this and submit again.";
		alert(errMessage);
		objCardNumber.select();
		objCardNumber.focus();
		return false;
	}
	
	return true;
}

// Luhn check - Reference: http://www.beachnet.com/~hstiles/cardtype.html
function luhnCheck(num) {
	var c = 0;
	var digits = "";
	var sum = 0;
	
	for (var i = num.length; i > 0; i--) {
		if (c % 2 != 0) {
			digits = parseInt(num.charAt(i - 1)) * 2 + "";
			for (var j = 0; j < digits.length; j++) {
				sum += parseInt(digits.charAt(j));
			}
		} else {
			sum += parseInt(num.charAt(i - 1));
		}
		c++;
	}
	
	return (sum % 10 == 0 ? true : false);
}