PeriodicalExecuter.prototype.registerCallback = function() {
	this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
};
  
PeriodicalExecuter.prototype.stop = function() {
	clearInterval(this.intervalID);
};

var currentSeries;

var setSelectByValue = function(select, value) {
	select = $(select);
	
	var opt = $A(select.getElementsByTagName('option')).find( function(option) {
		return(option.value == value);
	});
	
	if (opt !== null) {
		opt.selected = 'selected';
	}
};

var months = [];
months[1]  = "January";
months[2]  = "February";
months[3]  = "March";
months[4]  = "April";
months[5]  = "May";
months[6]  = "June";
months[7]  = "July";
months[8]  = "August";
months[9]  = "September";
months[10]  = "October";
months[11] = "November";
months[12] = "December";

function createCookie(name,value,days) {
	if (days) {
		    var date = new Date();
		    date.setTime(date.getTime()+(days*24*60*60*1000));
		    var expires = "; expires="+date.toGMTString();
	}

	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i=0;i < ca.length;i++) {
		    var c = ca[i];
		    while (c.charAt(0)==' ') c = c.substring(1,c.length);
		    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// query string parser, from shiva
function QueryString(key) {
    var value = null;

    for (var i=0;i<QueryString.keys.length;i++) {
        if (QueryString.keys[i]==key) {
            value = QueryString.values[i];
			
            break;
        }
  	}
	
    return value;
}

 

QueryString.keys = [];

QueryString.values = [];

function QueryString_Parse() {
    var query = window.location.search.substring(1);

    var pairs = query.split("&");

    for (var i=0;i<pairs.length;i++) {
        var pos = pairs[i].indexOf('=');

        if (pos >= 0) {
            var argname = pairs[i].substring(0,pos);

            var value = pairs[i].substring(pos+1);

            QueryString.keys[QueryString.keys.length] = argname;

            QueryString.values[QueryString.values.length] = value;                  
        }
    }
}
     
sfHover = function() {
	var sfEls = $("topnav").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		Event.observe(sfEls[i], 'mouseover', function(e) {
			var liNode = Event.element(e).parentNode;
			Element.addClassName(liNode, 'sfhover');
			Element.addClassName(liNode.parentNode.parentNode, 'sfhover');
			// get the child ul
			if (liNode.parentNode.parentNode.tagName == 'LI') {
				ul = liNode.parentNode;
			} else {
				ul = liNode.getElementsByTagName('ul')[0];
			}
			if (ul) {
				deployHideFrame(ul);
			}
			
		}, false);
		
		Event.observe(sfEls[i], 'mouseout', function(e) {
			var liNode = Event.element(e).parentNode;
			Element.removeClassName(liNode, 'sfhover');
			Element.removeClassName(liNode.parentNode.parentNode, 'sfhover');
			sheathHideFrame();
		}, true);
	}
};
Event.observe(window, 'load', sfHover, false);

var deployHideFrame = function(el) {
	// get the hideFrame element
	var hideFrame = $('hideFrame');
	
	// give it properties
	
	
	// clone the element we want to hide behind
	Position.clone(el, hideFrame);
	
	// show the hideFrame
	Element.show(hideFrame);
	
};

var sheathHideFrame = function() {
	Element.hide('hideFrame');
};

var commentInit = function() {
	Event.observe('show_disclaimer', 'click', showDisclaimer, true);
	Event.observe('send_comment', 'click', submitComment, true);
	Event.observe('close_disclaimer', 'click', hideDisclaimer, true);
	

	Event.observe('expert_question', 'focus', clearOnce);
	Event.observe('expert_email', 'focus', clearOnce);
	
	function clearOnce(e) {
		var el = Event.element(e);
		if (el._cleared) {return;}
		
		Field.clear($(el));
		el._cleared = true;
	}

};
var showDisclaimer = function(e) {
	// set the position and show the element
	var top = (Position.realOffset(document.body)[1] + 100) + 'px';
	var left = (document.body.scrollWidth/2 - 260) + 'px';
	Element.setStyle($('disclaimer'), {'left': left, 'top': top, 'display': 'block'});
	
	Event.stop(e);
	return false;
};
var hideDisclaimer = function(e) {
	Element.hide('disclaimer');
		
	Event.stop(e);
	return false;
};

var submitComment = function(e) {
	var url = '/toyotaSite/xmlSubmitComment.do';
	var options = {
		method: 'get',
		parameters: Form.serialize('home_expert'),
		onComplete: function(req) {
			// mutate the poll
			// wipe out the inputs from the form
			var inputs = $A($('home_expert').getElementsByTagName('input'));
			inputs.each( function(input, index) {
				Element.remove(input);
			});
			Element.remove($('expert_submit'));
			Element.remove($('show_disclaimer'));
			
			// put in a thank you message
			var message = "<p><strong>Thank you for your question!</strong></p>";
			new Insertion.Bottom('home_expert', message);
		},
		onException: function(reqObj, exception) {alert(exception);}
	};
	
	if (emailCheck($F('expert_email'))) {
		var pollReq = new Ajax.Request(url, options);
	} else {
		alert('Please enter a valid email address.');
		return false;
	}

	Event.stop(e);
	return false;
};

// if the poll is on the page
pollInit = function() {
	// creat the poll object
	var pollObj = function() {
		return {
			submit: function(e, thisObj) {
				var url = '/toyotaSite/xmlSubmitPollResponse.do';
				var options = {
					method: 'get',
					parameters: Form.serialize('home_poll'),
					onComplete: function(req) {
						createCookie(pollId, pollId, 30);
						thisObj.getResults();
					},
					onException: function(reqObj, exception) {alert(exception);}
				};
				
				var pollReq = new Ajax.Request(url, options);
				
				Event.stop(e);
			},
			getResults: function () {
				var url = '/toyotaSite/xmlViewSinglePollResults.do';
				var options = {
					method: 'get',
					parameters: Form.serialize('home_poll'),
					onComplete: function(req) {
						// get the responses
						var responses = $A(req.responseXML.getElementsByTagName('response'));
						
						// wipe out the inputs from the form
						var inputs = $A($('home_poll').getElementsByTagName('input'));
						inputs.each( function(input, index) {
							Element.remove(input);
						});
						Element.remove($('poll_submit'));
						
						// spit out the response voting stats
						responses.each( function(response, index) {
							var responseItem = $(response.getAttribute('code'));
							if (responseItem) {
								var img = document.createElement('img');
								img.src = '/motorsports/images/global/percent.gif';
								responseItem.appendChild(img);
								Element.setStyle(img, {'height': '10px'});
								var width = Math.floor(response.getAttribute('percent')*1.5) + 'px';
								Element.setStyle(img, {'width': width});
								Element.addClassName(img, 'votePercent');
								
								var voteCount = '<span class="voteCount">' + Math.round(response.getAttribute('percent')) + '%</span>';
								new Insertion.Bottom(responseItem, voteCount);
							}
						});
						
					},
					onException: function(reqObj, exception) {alert(exception);}
				};
				
				var pollReq = new Ajax.Request(url, options);
			}
		};
	}();
	
	if (readCookie(pollId)) {
		pollObj.getResults();
	} else {
		Event.observe('poll_submit', 'click', function(e) {pollObj.submit(e, pollObj);}, true);
	}
	
};

hideLoading = function() {
	loadAnimation = new PeriodicalExecuter(function() {
		Element.hide($('loading'));
		this.stop();
	}, 1);
};
Event.observe(window, 'load', hideLoading, false);
// failsafe in case onload never fires
new PeriodicalExecuter(function() {
	Element.hide($('loading'));
	this.stop();
}, 10);

var scheduleInit = function(args) {
	// initialize the series drop down
	
	// if this is the main page, assign the go button to the swap function
	if (args.page && (args.page == 'main')) {
		// call scheduleSwap to account for browsers preserving select position on refresh
		scheduleSwap();
		Event.observe('schedule_go_btn', 'click', function(e) {scheduleSwap(e);} );
	} else {
		// initialize the month drop down
		QueryString_Parse();
		if (QueryString('month')) {
			setSelectByValue('select_month', QueryString('month'));
		}
		
		// parse the argument
		seriesScheduleSwap();
		// otherwise, assign the go btn to the navigate function
		Event.observe('schedule_go_btn', 'click', function(e) {seriesScheduleSwap(e);} );
	}
};
var scheduleSwap = function(e) {
	// get the series divs
	var seriesDivs = $A(document.getElementsByClassName('schedule_series', 'schedule'));
	
	seriesDivs.each( function(series, index) {
		if (($F('select_series') !== '') && ($F('select_series')!= series.id)) {
			Element.hide(series.id);
		} else {
			Element.show(series.id);
		}
	});
	
	// cancel default behavior
	if (e) {
		Event.stop(e);
	}
	return false;
};
var seriesScheduleSwap = function(e) {
	// if select_series is set to a different series
	if ($F('select_series') !== '') {
		// redirect to specified page
		var url = '/motorsports/' + $F('select_series') + '/schedule.html';
		
		if ($F('select_month') !== '') {
			url += '?month=' + $F('select_month');
		}
			
		window.location = url;
	} else {
		//set the series month header
		var currentMonth = ($F('select_month') !== '')?(months[$F('select_month')]):('');
		$('schedule_table_hd').getElementsByTagName('h2')[0].innerHTML = currentMonth.toUpperCase() + ' SERIES SCHEDULE';
		
		// get the month divs
		var monthDivs = $A(document.getElementsByTagName('tbody'));
		
		monthDivs.each( function(month, index) {
			monthId = 'month_' + $F('select_month');
			if (($F('select_month') !== '') && (monthId !== month.id)) {
				Element.hide(month.id);
			} else {
				Element.show(month.id);
			}
		});
	}
	
	// cancel default behavior
	if (e) {
		Event.stop(e);
	}
	return false;
};



var interstitialInit = function(e) {
	Event.observe($('close_btn'), 'click', hideInterstitial, false);
};
var showInterstitial = function(link) {
	var interstitial = $('interstitial');
	
	// set the outbound link
	$('outbound_link').href = link;
	
	// set the position
	var top = (Position.realOffset(document.body)[1] + 100) + 'px';
	var left = (document.body.scrollWidth/2 - 260) + 'px';
	Element.setStyle(interstitial, {'left': left, 'top': top, 'display': 'block'});
	
	return false;
};
var hideInterstitial = function(e) {
	Element.hide('interstitial');
	 
	if (e) {
	 	Event.stop(e);
	}
	return false;
};
Event.observe(window, 'load', interstitialInit, false);


var resultsInit = function(args) {
	// if this is the main page, assign the go button to the swap function
	if (args.page && (args.page == 'main')) {
		// call scheduleSwap to account for browsers preserving select position on refresh
		resultsSwap();
		Event.observe('results_go_btn', 'click', function(e) {resultsSwap(e);} );
	} else {
		// initialize the year drop down
		setSelectByValue('select_year', args.year);
		
		// parse the argument
		seriesResultsSwap();
		
		// otherwise, assign the go btn to the navigate function
		Event.observe('results_go_btn', 'click', function(e) {seriesResultsSwap(e);} );
	}
};
var resultsSwap = function(e) {
	
	// show/hide the correct season
	var years = $A(document.getElementsByClassName('results_year'));
	years.each( function(year) {
		if (($F('select_year') !== '') && ($F('select_year') !== year.id)) {
			Element.hide(year.id);
		} else {
			Element.show(year.id);
				
			// get the series divs
			var seriesDivs = $A(document.getElementsByClassName('results_series', year));
			seriesDivs.each( function(series, index) {
				var seriesDiv = $F('select_series') + '_' + year.id;
				if (($F('select_series') !== '') && (seriesDiv != series.id)) {
					Element.hide(series.id);
				} else {
					Element.show(series.id);
				}
			});
		}
	});

	
	// cancel default behavior
	if (e) {
		Event.stop(e);
	}
	
	return false;
};
var seriesResultsSwap = function(e) {
	
	//set the season header
	$('results_table_hd').getElementsByTagName('h2')[0].innerHTML = $F('select_year') + ' RESULTS';
	
	// show/hide the correct season
	var years = $A(document.getElementsByClassName('results_table_bd'));
	var selectedYear = $F('select_year');
	var selectedRace = $F('select_race');
	years.each( function(year) {
		if ((selectedYear !== '') && (selectedYear !== year.id)) {
			Element.hide(year.id);
		} else {
			Element.show(year.id);
			
			// get the race divs for this season
			var raceDivs = $A(document.getElementsByTagName('tbody', 'results'));
			selectedRaceId = selectedRace + "_" + selectedYear;
			raceDivs.each( function(race, index) {
				if ((selectedRace !== '') && (selectedRaceId !== race.id)) {
					Element.hide(race.id);
				} else {
					Element.show(race.id);
				}
			});
		}
	});
	
	// cancel default behavior
	if (e) {
		Event.stop(e);
	}
	
	// cancel default behavior
	return false;
};


var standingsInit = function(args) {
	// initialize the year drop down
	setSelectByValue('select_year', args.year);
	
	// if this is the main page, assign the go button to the swap function
	if (args.page && (args.page == 'main')) {
		// call scheduleSwap to account for browsers preserving select position on refresh
		standingsSwap();
		Event.observe('standings_go_btn', 'click', function(e) {standingsSwap(e);} );
	} else {
		// parse the argument
		seriesStandingsSwap();
		// otherwise, assign the go btn to the navigate function
		Event.observe('standings_go_btn', 'click', function(e) {seriesStandingsSwap(e);} );
	}
};
var standingsSwap = function(e) {
	//set the season header
	$('standings_table_hd').getElementsByTagName('h2')[0].innerHTML = $F('select_year') + ' SEASON STANDINGS';
	
	// show/hide the correct season
	var years = $A(document.getElementsByClassName('standings_table_bd', 'standings'));
	var selectedYear = $F('select_year');
	years.each( function(year) {
		if ((selectedYear !== '') && (selectedYear !== year.id)) {
			Element.hide(year.id);
		} else {
			Element.show(year.id);
			
			var seriesDivs = $A(year.getElementsByTagName('tbody'));
			var selectedSeries = $F('select_series');
			seriesDivs.each( function(series, index) {
				seriesId = selectedSeries + '_' + year.id;
				if ((selectedSeries !== '') && (series.id != seriesId)) {
					Element.hide(series.id);
				} else {
					Element.show(series.id);
				}
			});
		}
	});
	
	
	// cancel default behavior
	if (e) {
		Event.stop(e);
	}
	
	return false;
};
var seriesStandingsSwap = function(e) {
	//set the season header
	$('standings_table_hd').getElementsByTagName('h2')[0].innerHTML = $F('select_year') + ' STANDINGS';
	
	// show/hide the correct season
	var years = $A(document.getElementsByClassName('standings_table_bd'));
	years.each( function(year) {
		if (($F('select_year') !== '') && ($F('select_year') !== year.id)) {
			Element.hide(year.id);
		} else {
			Element.show(year.id);
		}
	});
	
	// cancel default behavior
	if (e) {
		Event.stop(e);
	}
	
	// cancel default behavior
	return false;
};


var emailCheck = function(emailStr) {
	
	/* The following variable tells the rest of the function whether or not to verify that the address ends in a two-letter country or well-known TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;

 	/* The following is the list of known TLDs that an e-mail address must end with. */
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

	/* The following pattern is used to check if the entered e-mail address fits the user@domain format.  It also is used to separate the username from the domain. */
	var emailPat=/^(.+)@(.+)$/;

	/* The following string represents the pattern for matching all special characters.  We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	/* The following string represents the range of characters allowed in a  username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";

	/* The following pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";

	/* The following pattern applies for domains that are IP addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';

	/* The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";

	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	/* The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	/* Finally, let's start trying to figure out if the supplied address is valid. */

	/* Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);
	
	
	if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */
		// alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	
	var user=matchArray[1];
	
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).
	
	 
	
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			// alert("Ths username contains invalid characters.");
			return false;
		}
	}
	
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			//alert("Ths domain name contains invalid characters.");
			return false;
	   }
	}
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		//alert("The username doesn't seem to be valid.");
		return false;
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	
	if (IPArray!=null) {
		// this is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				//alert("Destination IP address is invalid!");
				return false;	
			}
		}
		return true;
	}

	// Domain is symbolic name.  Check if it's valid.
	var rfc2821Pat=new RegExp("^[a-zA-Z0-9\\-]+$");
	
	var domArr=domain.split(".");
	
	var len=domArr.length;
	
	for (i=0;i<len;i++) {
		if (domArr[i].search(rfc2821Pat)==-1) {
			// alert("The domain name does not seem to be valid.");
			return false;
		}
	}
	
	/* domain name seems valid, but now make sure that it ends in a known top-level domain (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		// alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
		// alert("This address is missing a hostname!");
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
};

function openPDF(pdfURL){
	pdfWin = window.open(pdfURL,'pdfWin','height=500,width=750,top=10,left=10,resizable=1,scrollbars=1,menubar=1');
	pdfWin.focus();
}

function showHidden(id) {
	if ($(id).style.display == "" || $(id).style.display == "none") {
		$(id).style.display = "block";
		$(id+"_img").src = "/motorsports/images/global/arrow_up.gif";
	} else if ($(id).style.display == "block") {
		$(id).style.display = "none";
		$(id+"_img").src = "/motorsports/images/global/arrow_down.gif";
	}
}

function seToggleMenu(id) {
	if ($(id).style.display == "none") {
		$(id).style.display = "block";
	} else {
		$(id).style.display = "none";
	}
}