/* Function list:
	- addLoadEvent
	- ccCheck
	- finalizeError
	- fixCallOuts
	- isEmail
	- isNumber
	- isSelected
	- isString
	- luhnCheck
	- validate
*/

// 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
	Callouts.fix();
	attachWindowOpeners();
	Email.fixEmails();
	GoogleLinkTracker.init();
});


// Adjust widths of callouts depending on size of image within
var Callouts = {
	fix : function() {
		// Check for functionality
		if (!document.getElementById || !document.getElementsByTagName) return false;
		
		var arrBins = document.getElementsByTagName("*");
		var classRE = /call-?[lr]/gi;
		
		// Set div width = image width
		for (var i = 0; i < arrBins.length; i++) {
			if (classRE.test(arrBins[i].className)) {
				var images = arrBins[i].getElementsByTagName("img");
				if (images.length >= 1) {
					arrBins[i].style.width = images[0].offsetWidth + "px";
				}
			}
		}
		
		return false;
	}
};


// Attach window openers for documents
function attachWindowOpeners() {
	var links = document.getElementsByTagName("a");
	var fileTypes = new Array("doc", "pdf", "ppt", "xls");
	
	for (var i = 0; i < links.length; i++) {
		for (var j = 0; j < fileTypes.length; j++) {
			if (links[i].href.indexOf(fileTypes[j]) > -1) {
				links[i].onclick = function () {
					window.open(this.href, "scrollbars=1,resizable=1");
					return false;
				}
			}
		}
	}
}


// Validates credit card numbers format
function ccCheck(ccType, ccNumber, ccMonth, ccYear) {
	// Set some vars, find objects passed based on ID
	var isValid = true;
	var errMessage = "";
	var now = new Date();
	var objCardType = document.getElementById(ccType);
	var objCardNumber = document.getElementById(ccNumber);
	var objExpireMonth = document.getElementById(ccMonth);
	var objExpireYear = document.getElementById(ccYear);
	
	// Strip non digits from number
	var cardNumber = objCardNumber.value.replace(/\D/g, "");
	
	// Validate card number 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;
		case "diner's club": 	  // Diner's Club - length: 14, prefix: 300-305 or 36 or 38
			isValid = /^3(0[0-5]\d{11}|[68]\d{12})$/.test(cardNumber);
			break;
		case "discover": 	  	  // Discover - length: 16, prefix: 6011
			isValid = /^6011\d{12}$/.test(cardNumber);
			break;
		case "enroute": 	  	  // enRoute - length: 15, prefix: 2014 or 2149
			isValid = /^2(014|149)\d{11}$/.test(cardNumber);
			break;
		case "JCBCard": 	  	  // JCBCard - length: 16 with prefix: 3, length: 15 with prefix: 2131 or 1800
			isValid = /^3\d{15}|(2131|1800)\d{11}$/.test(cardNumber);
			break;
		default:
			isValid = true;
	}
	
	// Validate card number via Luhn formula
	if (isValid) isValid = luhnCheck(cardNumber, objCardType); 
	
	// If field is invalid, add to error message
	if (!isValid) { errMessage += "- Card number is invalid.\n"; }
	
	// Validate expiration date (no earier than this month/year)
	if (parseInt(objExpireMonth.value) < now.getMonth() && parseInt(objExpireYear.value) == now.getFullYear()) {
		errMessage += "- The expiration date cannot be a date older than the current month and year.\n";
	}
}


// Finlizes error message
function finalizeError(errMessage) {
	if (errMessage != "") {
		newErrMessage  = "_____________________________________________________________\n\n";
		newErrMessage += "The form was not submitted because of the following error(s).\n";
		newErrMessage += "Please correct resubmit.\n";
		newErrMessage += "_____________________________________________________________\n\n";
		newErrMessage += errMessage;
		alert(newErrMessage);
		return false;
	}
	
	return true;
}


// 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 numeric value
function isNumber(strValue) {
	return (!isNaN(strValue) && 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 string value
function isString(strValue) {
	return (typeof strValue == "string" && strValue != "" && isNaN(strValue));
}


// Luhn check - Reference: http://www.beachnet.com/~hstiles/cardtype.html
function luhnCheck(num, cardType) {
	var c = 0;
	var digits = "";
	var sum = 0;
	
	if (cardType != "enroute") {
		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);
	} else {
		return true;
	}
}


// Validate various types
function validate(arrFields) {
	var errMessage = "";
	
	for (var i = 0; i < arrFields.length; i++) {
		var isValid = true;
		// 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 field is invalid, add to error message
		if (!isValid) { errMessage += "- " + strLabel + " is missing or invalid.\n"; }
	}
	
	return errMessage;
}


/*--------------------------------------------------------------------------------------------+
 | Finds all email links with the class name "email-link" and reverses the innerHTML and href |
 | Also removes the "email-link" class so the style sheet won't reverse the innerHTML         |
 +--------------------------------------------------------------------------------------------*/
var Email = {
	fixEmails : function () {
		var links = document.getElementsByTagName("a");
		
		for (var i = 0; i < links.length; i++) {
			if (links[i].className.indexOf("email-link") > -1) {
				var emailAddr = links[i];
				var emailLink = emailAddr.href.replace("mailto:", "");
				emailAddr.href = "mailto:" + Email.reverseString(emailLink);
				emailAddr.innerHTML = Email.reverseString(emailLink);
				emailAddr.className = emailAddr.className.replace("email-link", "");
			}
		}
	},

	// Takes in a string and returns the reverse of it
	reverseString : function(sourceString) {
		var reversedString = "";
		
		for(var i = sourceString.length - 1; i >= 0; i--) {
			reversedString += sourceString.charAt(i);
		}
		
		return reversedString;
	}
}


/*-----------------------------------------------------------------------------------------+
 | GoogleLinkTracker - Add click tracking for Google Analytics to files and outgoing links |
 +-----------------------------------------------------------------------------------------*/
var GoogleLinkTracker = {
	init : function() {
		var links = document.getElementsByTagName("a");
		
		for (var i = 0; i < links.length; i++) {
			var theLink = links[i];
			var theURL = theLink.href.toLowerCase();
			
			if (typeof(pageTracker) != "undefined")
			{
				if (/\.(bmp|doc|docx|gif|jpg|pdf|png|xls|xlsx|ppt|pptx|zip)/.test(theURL)) {
					var func = function () { if (pageTracker) pageTracker._trackPageview("/files/" + this.href); };
					
					if (typeof(jQuery) != "undefined")
						jQuery(theLink).click(func);
					else
						theLink.onclick = func;
				}
					
				if (theURL.indexOf("chicagopubliclibraryfoundation.org") == -1) {
					var func = function () { if (pageTracker) pageTracker._trackPageview("/outbound/" + this.href); };
					
					if (typeof(jQuery) != "undefined")
						jQuery(theLink).click(func);
					else
						theLink.onlick = func;
				}
			}
		}
	}
};