Array.prototype.contains = function(element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) return true;
	}
	return false;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,'');
}

function addClickEvent(elem, func, followLink) {
	// If the element has an onclick event handler already, capture it; otherwise create an empty anonymous function
	var oldonclick = (typeof elem.onclick == 'function') ? elem.onclick : function () {};
	// Set the element's onclick function to do the original function first, then the new one
	elem.onclick = function () {
		oldonclick(); // doesn't matter if original onclick had return true/false, though we could capture the result and override followLink if we wanted
		func(elem);
		return followLink;
	};
}

function getCookie(cookieName) {
	var cookies = document.cookie.split(';');
	for (var i = 0; i < cookies.length; i++) {
		var crumbs = cookies[i].split('=');
		if (crumbs[0].trim() == cookieName && cookies.length > 1) return unescape(crumbs[1].trim());
	}
	return null; // cookieName not found
}

function isSurveyTime() {
	// Build array of testing periods (start and stop); there should be twelve pairs, one per month for a year, but not all are known yet
	// mmm dd yyyy hh24:00 PST
	// 20090416 akohler: test periods from Apr 2009 thru ??? 2009 should be PDT, not realized until too late for Apr 16 test
	var testTimes = [
		[Date.parse("Nov 21 2008 09:00 PST"), Date.parse("Nov 21 2008 11:00 PST")]
	,	[Date.parse("Dec 10 2008 14:00 PST"), Date.parse("Dec 10 2008 16:00 PST")]
	,	[Date.parse("Jan 20 2009 10:00 PST"), Date.parse("Jan 20 2009 12:00 PST")]
	,	[Date.parse("Feb 27 2009 14:00 PST"), Date.parse("Feb 27 2009 16:00 PST")]
	,	[Date.parse("Mar 09 2009 12:00 PST"), Date.parse("Mar 09 2009 14:00 PST")]
	,	[Date.parse("Apr 16 2009 08:00 PST"), Date.parse("Apr 16 2009 10:00 PST")]
	,	[Date.parse("May 13 2009 12:00 PDT"), Date.parse("May 13 2009 14:00 PDT")]
	,	[Date.parse("Jun 25 2009 15:00 PDT"), Date.parse("Jun 25 2009 17:00 PDT")]
	,	[Date.parse("Jul 08 2009 09:00 PDT"), Date.parse("Jul 08 2009 11:00 PDT")]
	,	[Date.parse("Aug 14 2009 09:00 PDT"), Date.parse("Aug 14 2009 11:00 PDT")]
	,	[Date.parse("Sep 03 2009 11:00 PDT"), Date.parse("Sep 03 2009 13:00 PDT")]
	,	[Date.parse("Oct 08 2009 15:00 PDT"), Date.parse("Oct 08 2009 17:00 PDT")]
	];
	var now = new Date().getTime();
	for (var testTime in testTimes) {
		var start = testTimes[testTime][0];
		var stop = testTimes[testTime][1];
		if ( (start <= now) && (now < stop) ) return true;
	}
	return false;
}

function isDomainSurveyable(link) {
	// Returns true if entire domain is eligible for survey, instead of just specific pages
	if (link == null) var link = window.location;
	var domain = link.hostname;
	var surveyable = false;
	switch (domain) {
		case 'catalog.library.ucla.edu' :
		case 'digital.library.ucla.edu' :
			surveyable = true;
			break;
	}
	return surveyable;
}
	
function isPageSurveyable(link) {
	// Returns true if link is potentially eligible for library usage survey
	if (link == null) var link = window.location; 
	var surveyable = false;
	var domain = link.hostname;
	var pathname = link.pathname;
	// If necessary (IE...) prepend '/' to pathname to be consistent with Firefox (and the standard)
	if (pathname.indexOf('/') != 0) pathname = '/' + pathname;
	var search = link.search;
	switch (domain) {
		// only certain pages on these are surveyable
		case 'www2.library.ucla.edu' :
			var validPaths = ['/erdb_stats.cfm']; // there might be more...
			if (validPaths.contains(pathname)) surveyable = true;
			break;
	}
	return surveyable;
}

function isLibraryDomain(domain) {
	// Returns true if domain contains library.ucla.edu (case insensitive)
	return(domain.toUpperCase().indexOf('LIBRARY.UCLA.EDU') >= 0);
}

function redirectLink(obj) {
	if (obj == null) return false;
	// IE and FF treat obj.getAttribute('href') differently; use obj.href for consistency
	var link = obj.href;
	if (!link) return false;
	link = escape(link); // or encodeURIComponent?
	var target = 'http://www2.library.ucla.edu/cf_modules/lcas_router.cfm';
	target += '?target=' + link;
	window.location = target;
}

function hookLinks() {
	var thisDomain = window.location.hostname;
	var links = document.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		var link = links[i];
		var domain = link.hostname;
		// bail out on special cases
		if (link.href.indexOf('erdb_record.cfm') >= 0) continue;
		if (domain == null) continue;
		// hook into surveyable links, but exclude ones on the same domain
		if (isPageSurveyable(link) || (isDomainSurveyable(link) && (thisDomain != domain)) || (! isLibraryDomain(domain)) ) {
			addClickEvent(link, redirectLink, false);
		}
		// addEvent(link, 'click', redirectLink); //works, except link is still followed
		// Can't use generic addEvent() because we need to change link.onclick, not just add a new event to it
		// Must ensure that onclick returns false so the original link is not followed
	}
}

// If it's time for the survey, hook relevant links to redirect to the survey system
// added TEST cookie to allow deployment & testing on production site; remove this check before the real survey
//if (isSurveyTime() && getCookie('LIBCOSTSURVEY_TEST')) {
if (isSurveyTime()) {
	// If this is a library page we care about, and survey cookies aren't already set, redirect to the survey
	if ( (isDomainSurveyable() || isPageSurveyable()) && (! getCookie('LIBCOSTSURVEY_EXPIRES') || ! getCookie('LIBCOSTSURVEY_SESSIONID'))) {
		redirectLink(parent.location); // pick up framed content correctly, instead of window.location which is current frame only
	}
	addEvent(window, 'load', hookLinks);
}
