/**
 * add multiple JavaScript onload functions
 * @function
 */ 
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

/**
 * include other JavaScript files
 * @function
 */ 
function includeJS(scriptPath) {
	document.write('<script type="text/javascript" src="' + scriptPath + '" language="javascript"></script>');
	return false;
}

/**
 * Global variables
 */
var teamList = ['titan','world','jotech','jd','mpm', 'rsr', 'rockstar'];
var sectionList = ['drag','drift','road','schedule','news'];
var pagePath = window.location.pathname;
var currentSection = '';
var currentTeam = '';

/**
 * Initialization functions
 */
function initialize() {
	
	// Get name of team, if any, whose page is being viewed
	var parsedPath = pagePath.match(/(.*)[\/\\]([^\/\\]+)\.\w+$/);
	var path = parsedPath?parsedPath[1]:'';
	var file = parsedPath?parsedPath[2]:'';
	var fileParts = file.split('_');
	fileParts.each(function(part) {
		if (teamList.indexOf(part) > -1) {
			currentTeam = part;
		}
	});
	var fileParts2 = path.split('/');
	fileParts2.each(function(part) {
		if (sectionList.indexOf(part) > -1) {
			currentSection = part;
		}
	});

	// Initialize navs
	var thisNavController = new NavController;
	var navGlobalRollover = new Rollover('navGlobal');

}
addLoadEvent(initialize);


/**
* dropdown script for all standard linear dropdowns (not for drag)
*/
var timeout	= 10;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = $(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) 
	{
		ddmenuitem.style.visibility = 'hidden';
	}
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose; 
	
/*  end linear dropdowns scripts */


	
/**
 * Adapted from...
 * Unobtrusive image rollover with Prototype library, v1.0
 * 
 * Created by Herryanto Siatono
 * Copyright (c) 2007 Pluit Solutions <www.pluitsolutions.com>
 * 
 * This script is freely distributable under the terms of an MIT-style license.
 /*------------------------------------------------------------------------------*/

var Rollover= Class.create();
Rollover.prototype = {
	// provide the container id containing image links to be rolled over.
	initialize: function(id, options) {
		this.id = id;
		this.images = {};
		this.setOptions(options);
		this.observeLinks();
	},
		
	setOptions: function(options) {
		this.options = {
			offSuffix: 'off',
			overSuffix: 'over',
			onSuffix: 'on',
			suffixseparator: '_'
		};
		Object.extend(this.options, options || {});
	},
		
	observeLinks: function() {
		this.links = $$('#' + this.id + ' a');
		for (i=0; i<this.links.length; i++) {
			// don't add standard event handlers for images in "on" state
			if (!this.links[i].firstChild.src.match(this.options.suffixseparator + this.options.onSuffix)) {
				this.links[i].observe('mouseover', this.rolloverImage);
				this.links[i].observe('mouseout', this.rollbackImage);
			}
		}
		
		images = $$('#' + this.id + ' img');
		for (i=0; i<images.length; i++) {
			imageId = images[i].id 
			if (!imageId) {
				imageId  = this.id + i;
				images[i].id = imageId;
			}
			
			this.images[imageId] = images[i].src;
			images[i].imageRollover = this;
			
			// preload rollover image (but not if it's a logo)
			if (!images[i].src.match('logo')) {
				var newImage = new Image();
				newImage.src = this.parseRolloverImage(images[i]);
				newImage.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + newImage.src + "', sizingMethod='scale')";
			}	  
			
		}
	},
		
	rolloverImage: function(e) {
		var image = Event.element(e);
		if(image.imageRollover != undefined)
		{
			image.imageRollover.images[image.id] = image.src;
			image.src = image.imageRollover.parseRolloverImage(image);
		}
	},
		
	rollbackImage: function(e) {
		var image = Event.element(e);
		if(image.imageRollover != undefined)
		{
			image.src = image.imageRollover.images[image.id];
		}
	},
	
	parseRolloverImage: function(image) {
		ext = image.src.substr(image.src.lastIndexOf('.'));
		path = image.src.match(/(.*)\/(.*\.(png|gif|jpg))/)[1]
		filename = image.src.gsub(path, '')
		filename = filename.replace('_off','');
		filename = filename.replace('_on','');
		basename = this.parseBasename(filename);
		basename = this.parseBasename(basename, this.options.suffixseparator + this.options.overSuffix);
		return path + basename + this.options.suffixseparator + this.options.overSuffix + ext;
	},
		
	parseBasename: function(name, separator) {
		separator = separator || '.';
		found = name.lastIndexOf(separator);
		if (found > 0) {
			return name.substr(0, found);
		} else {
			return name;
		}
	}

}

/**
* Controller for navigation sets
* Highlight current section in global nav, highlight current team in team nav
*/
var NavController= Class.create();
Object.extend(NavController.prototype, Rollover);
NavController.prototype = {

	initialize: function(){
		this.section = null;
		this.team = null;
		this.setGlobalNav();
		this.setTeamNav();
		this.setTeamSubNav();
		this.setFooterTeamLinks();
	},
	
	getFilename: function(image) {
		imagePath = image.src.match(/(.*)\/(.*\.(png|gif|jpg))/)[1];
		filename = image.src.gsub(imagePath, '');
		return filename;		
	},
	
	setGlobalNav: function() {
		// global nav images
		globalImages = $$('#navGlobal img');
		for (i = 0; i < globalImages.length; i++) {
			thisImage = globalImages[i];
			filename = this.getFilename(thisImage);
			// get image section from image name (except for logo)
			imageSection = '';
			if (!filename.match('logo')) {
				imageSection = filename.substring(12, (filename.length-8));
				// compare image section to page section
				if (pagePath.match(imageSection)) {
					this.section = imageSection;
					thisImage.src = '/pub-share/scionracing/images/nav_global_' + this.section + '_on.gif';
				}
			}
		}
	},
	
	setTeamNav: function() {
		// set up mouse functions
		if (document.getElementsByClassName('navTeam')){
			
			/** TEMPORARY:: only use this dropdown script setup on drag section **/
			var localTeam = currentSection;
			if(localTeam == "drag")
			{
				teamLinks = $$('.navTeam a.navTeamLink');
				for (i = 0; i < teamLinks.length; i++) {
					thisLink = teamLinks[i];
					bgImageURL = thisLink.getStyle('backgroundImage');
					bgImagePath = bgImageURL.match(/url\((.*)\/(.*\.(png|gif|jpg))/)[1] + '/';
					bgImageFile = (bgImageURL.gsub(bgImagePath, '')).match(/url\((.*)\)/)[1];
					// get image section from image name (except for logo)
					bgImageTeam = bgImageFile.substring(9, (bgImageFile.length - 9));
					var isMSIE = /*@cc_on!@*/false;
					if (isMSIE) {
						bgImageTeam = bgImageFile.substring(9, (bgImageFile.length - 10));
					}
					// add event handler to show dropdowns
					Event.observe(thisLink, 'mouseover', this.showTeamDropdown.bind(this));
					// compare image section to page section
					if (currentTeam.match(bgImageTeam)) {
						this.team = bgImageTeam;
						thisLink.firstChild.src = '/pub-share/scionracing/images/nav_' + currentSection + '_' + this.team + '_on.png';
					}
				}
			}
			// turn 'on' nav section for pages that use pageSection var
			try {
				if(pageSection) {
				var linkImage;
				switch(pageSection) {
					case "rsr":
						linkImage = $('nav_drift_rsr_img');
					break;	
					case "rockstar":
						linkImage = $('nav_drift_rockstar_img');
					break;	
					case "jd":
						linkImage = $('nav_road_jd_img');
					break;
					case "world":
						linkImage = $('nav_road_world_img');
					break;	
					case "mpm":
						linkImage = $('nav_road_mpm_img');
					break;	
				}
				if(linkImage) {
					var offSource = linkImage.src;
				  	var onSource = offSource.gsub('_off.', '_on.');
				  	linkImage.src = onSource;
				}
				// set up main team nav rollovers for those pages
				roadLinks = $$('#navRoad .navTeamLink');
				if(roadLinks) {
					$A(roadLinks).each(function(link) {
						var linkImage = link.getElementsByTagName("IMG")[0];
						var offSource = linkImage.src;
						var onSource = offSource.gsub('_off.', '_over.');
						Event.observe(link, 'mouseover', function(e) { linkImage.src = onSource }.bind(this));
						Event.observe(link, 'mouseout', function(e) { linkImage.src = offSource  }.bind(this));
					});
				}
				driftLinks = $$('#navDrift .navTeamLink');
				if(driftLinks) {
					$A(driftLinks).each(function(link) {
						var linkImage = link.getElementsByTagName("IMG")[0];
						var offSource = linkImage.src;
						var onSource = offSource.gsub('_off.', '_over.');
						Event.observe(link, 'mouseover', function(e) { linkImage.src = onSource }.bind(this));
						Event.observe(link, 'mouseout', function(e) { linkImage.src = offSource  }.bind(this));
					});
				}
			}
			}catch(e){
				// do nothing
			}
			
		}
		if ($('.navBtnOver')) {
			var dropDowns = document.getElementsByClassName('navBtnOver');
			$A(dropDowns).each(function(dropDown) {
			  Event.observe(dropDown, 'mouseout', function(e) {
					var borderWidth = 5;
					var dimensions = dropDown.getDimensions();
					var position = dropDown.cumulativeOffset();
					var dropDownXMin = position.left + borderWidth;
					var dropDownXMax = position.left + dimensions.width - borderWidth;
					var dropDownYMin = position.top + borderWidth;
					var dropDownYMax = position.top + dimensions.height - borderWidth;
					if( e.clientX < dropDownXMin || e.clientX > dropDownXMax || e.clientY < dropDownYMin || e.clientY > dropDownYMax ) {
						dropDown.style.display = "none";
					}
				}.bind(this));
			});
		}
		// set up dropdown navigation mouse events
		if (document.getElementsByClassName('dropDownItem')) {
			var dropDownNavLinks = document.getElementsByClassName('dropDownItem');
			$A(dropDownNavLinks).each(function(dropDownLink) {
			  var linkImage = dropDownLink.getElementsByTagName("IMG")[0];
			  var offSource = linkImage.src;
			  var onSource = offSource.gsub('_off.gif', '_over.gif');
				Event.observe(dropDownLink, 'mouseover', function(e) { linkImage.src = onSource }.bind(this));
				Event.observe(dropDownLink, 'mouseout', function(e) { linkImage.src = offSource  }.bind(this));
			});
		}
			
		return this.team;
	},
	
	
	showTeamDropdown: function(e) {
		
		try{
			$('navDragTitanOver').style.display = "none";
			$('navDragWorldOver').style.display = "none";
			$('navDragJotechOver').style.display = "none";
		} catch(e) {
			// do nothing -- this is just to facilitate trying to get the nav to be less 'sticky'
		}
		
		var image = Event.element(e);
		if(image.tagName.toUpperCase() != "IMG") 
		{
			var childImages = image.getElementsByTagName("IMG");
			image = childImages[0];
		}
		var containerDiv = image.parentNode.parentNode;
		var dropDownId = containerDiv.id + "Over";
		var dropDown = $(dropDownId);

		if(dropDown) {
			dropDown.style.display = "block";
			dropDown.style.visibility = "visible";
		}
	},
	
	setTeamSubNav: function() {
		// set subnav links for drag
		if (document.getElementById('subnavDrag') || document.getElementById('subnavRoad') || document.getElementById('subnavDrift')) {
			document.getElementById('subGear').href = '/pub/scionracing/drag/gear_' + currentTeam + '.html';
			document.getElementById('subSchedule').href = '/pub/scionracing/schedule/index.html';
			document.getElementById('subGallery').href = '/scionracing/drag/gallery_' + currentTeam + '_video.html';
			document.getElementById('subAsk').href = 'ask_' + currentTeam + '.html';
		}
	},
	
	setFooterTeamLinks: function() {
		// set footer links for team pages
		if (document.getElementById('footerLinksTeam')) {
			document.getElementById('footerGear').href = '/pub/scionracing/' + currentSection + '/gear_' + currentTeam + '.html';
			document.getElementById('footerGallery').href = '/pub/scionracing/' + currentSection + '/gallery_' + currentTeam + '_video.html';
			document.getElementById('footerAsk').href =  'ask_' + currentTeam + '.html';
		}		
	}
	
}

// set nav on/off states for road

function setSubNavRoad(id)
{
document.getElementById('subnavRoad').className = 'subnavRoad' + id;
}


/** Form validation scripts **/
function submitGalleryEmailForm(form) {
// Get Form elements

	var senderName = form.senderName.value;
	var senderEmail = form.senderEmail.value;
	var friendEmail = form.friendEmail.value;
	var message = form.message.value;
	var link = form.link.value;
	var passed = true;
	var errorMessage = "";
	
	if( !isNotEmptyField(senderName) ) {
		errorMessage += "Please enter your name.<br />";
		passed = false;
	}
	
	if( !isValidEmail(senderEmail) ) {
		errorMessage += "Please enter a valid email address.<br />";
		passed = false;
	}
	
	if( !isValidEmail(friendEmail) ) {
		errorMessage += "Please enter a valid email address for your friend.<br />";
		passed = false;
	}
	
	if (lengthRestriction(senderName, 128) ) {
		errorMessage += "There is a limit of 128 characters for your name.<br />";
		passed = false;
	}
	
	if (lengthRestriction(message, 256) ) {
		errorMessage += "There is a limit of 256 characters for your message.<br />";
		passed = false;
	}
	
	
	if(passed) {	
		//form.submit();
		$('galleryEmailMessage').update("");
		
		// Construct URL
		var url = '/scion/ssl/scionracing/emailFriend.do?senderName=' + senderName + '&senderEmail=' + senderEmail + '&friendEmail=' + friendEmail + '&link=' + link + '&message=' + message;
		// Call Service
			new Ajax.Request(url, {
				method: 'post',
				onSuccess: galleryFormCallBack,
				onFailure: galleryEmailProcessFailure,
				onComplete: processComplete
			});
		
	} else {
		$('galleryEmailMessage').update(errorMessage);
	}
}


function galleryFormCallBack(transport) {	
	var message = "Thanks, your email has been sent.";
	$('galleryEmailMessage').update(message);
	try{
		$('galleryEmailForm').senderName.value = "";
		$('galleryEmailForm').senderEmail.value = "";
		$('galleryEmailForm').friendEmail.value = "";
		$('galleryEmailForm').message.value = "";
	} catch(e) {
		// do nothing... this is just cosmetic
	}
}

function galleryEmailProcessFailure(transport) {
	var errorMessage = "Sorry, there has been an error.  Please check the form and try again, or try again later.";
	$('galleryEmailMessage').update(errorMessage);
}

function submitAskDriverForm(form) {
// Get Form elements
	var driverId = form.driverId.value;
	var firstName = form.firstName.value;
	var lastName = form.lastName.value;
	var email = form.email.value;
	var question = form.question.value;
	var passed = true;
	var errorMessage = "";
	
	if( !isNotEmptyField(firstName) ) {
		errorMessage += "Please enter your first name.<br />";
		passed = false;
	}
	
	if( !isNotEmptyField(lastName) ) {
		errorMessage += "Please enter your last name.<br />";
		passed = false;
	}
	
	if( !isValidEmail(email) ) {
		errorMessage += "Please enter a valid email address.<br />";
		passed = false;
	}
	
	if( !isNotEmptyField(question) ) {
		errorMessage += "Please enter a question.<br />";
		passed = false;
	}
	
	if(passed) {	
		//form.submit();
		$('askFormMessage').update("");
		
		// Construct URL
		var url = '/scion/ssl/scionracing/submitQuestion.do?driverId=' + driverId + '&firstName=' + firstName + '&lastName=' + lastName + '&email=' + email + '&question=' + question;
		// Call Service
			new Ajax.Request(url, {
				method: 'post',
				onSuccess: askFormCallBack,
				onFailure: askFormProcessFailure,
				onComplete: processComplete
			});
		
	} else {
		$('askFormMessage').update(errorMessage);
	}
}

function askFormCallBack(transport) {	
	var message = "Thanks, your question has been received.";
	$('askFormMessage').update(message);
	try{
		$('askDriverForm').firstName.value = "";
		$('askDriverForm').lastName.value = "";
		$('askDriverForm').email.value = "";
		$('askDriverForm').question.value = "";
	} catch(e) {
		// do nothing... this is just cosmetic
	}
}

function askFormProcessFailure(transport) {
	var errorMessage = "Sorry, there has been an error.  Please check the form and try again, or try again later.";
	$('askFormMessage').update(errorMessage);
}

function processComplete(transport) {
	//alert('complete');
}

function submitEmailOptInForm(form) {
	var email = form.email.value;
	var source = "scionracing";
	if(form.source) source = form.source.value;
	
	var passed = true;
	var errorMessage = "";
	
	if( !isValidEmail(email) ) {
		errorMessage += "Please enter a valid email address.<br />";
		passed = false;
	}
	if(passed) {	
		var url = '/scion/ssl/scionracing/emailOptin.do?email=' + email + '&source=' + source;
		// Call Service
			new Ajax.Request(url, {
				method: 'post',
				onSuccess: emailFormCallBack,
				onFailure: emailFormProcessFailure,
				onComplete: processComplete
			});
		$('emailOptInFormMessage').update("");
		$('emailOptInFormMessage').style.visibility = "hidden";
	} else {
		$('emailOptInFormMessage').update(errorMessage);
		$('emailOptInFormMessage').style.visibility = "visible";
	}
	
}

function emailFormCallBack(transport) {	
	var message = "Thanks, we'll keep you updated.";
	$('emailOptInFormMessage').style.visibility = "visible";
	$('emailOptInFormMessage').update(message);
	try{
		$('emailInputField').value = "";
	} catch(e) {
		// do nothing... this is just cosmetic
	}
}

function emailFormProcessFailure(transport) {
	var errorMessage = "Sorry, there has been an error.";
	$('emailOptInFormMessage').update(errorMessage);
}


function isValidEmail(email) {
	if (email.search(  /^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/  ) == -1)
	{
		return false;
	} else {
		return true;
	}
}

function isNotEmptyField(value) {
	if (value == "" || value == null || value == undefined)
	{
		return false;
	} else {
		return true;
	}
}

function lengthRestriction(value, max){
	if(value.length > max){
		return true;
	}else{
		return false;
	}
}



// links to schedule, passing team-specific designation
function goToSchedule(passedTeamName) {
	var team = "";
	var scheduleURL = "";
	var currentURL = "";
	
	currentURL = window.location.toString();
	
	if(currentURL.substring(0,5) == 'https') {
		// we're currently in ssl, so redirect to pub
		scheduleURL = "/pub/scionracing/schedule/index.html";
	} else {
		scheduleURL = "/scionracing/schedule/index.html";
	}
	// set the currentTeam based on existing vars
	if(this.currentTeam != "") {
		team = this.currentTeam
	} else {
		try {
			team = pageSection;
		} catch(e) {
			// do nothing
		}
	}
	
	// handle the fact that in some places, 'world' is used as team name
	// but there are two 'world' teams
	if(team == 'world') {
		if(currentSection == 'drag') {
			team = 'worldMotor';
		} else {
			team = 'worldRacing';
		}
	}
	
	// if a team name is specifically passed as an arguent to this function, it overrides the current team name variable
	if(passedTeamName != undefined && passedTeamName != null && passedTeamName != "") team = passedTeamName;
	if(team != "") {
		scheduleURL += "?team=" + team;
	}
	window.location = scheduleURL;
}

// prevent user from selecting html text
// corrects the bug w/ the scrollbar in IE (white box displays upon text selection or scrolling)

function disabletext(e){  
return false  
}  
  
function reEnable(){  
return true  
}  
  
//if the browser is IE4+

function stopSelection(id) {
	document.getElementById(id).onselectstart=new Function ("return false")  
	  
	//if the browser is NS6  
	if (window.sidebar){  
	document.getElementById(id).onmousedown=disabletext  
	document.getElementById(id).onclick=reEnable  
	}
}

/*
addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
*/
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

// lightbox code for Drift Landing page


var LaunchDriftWebisodeOverlay = Class.create();

//debugger;

LaunchDriftWebisodeOverlay.prototype = {
	initialize: function() {
		this.backdrop = new ModalBackdrop();
		this.bodyStyleCounter = 0;
	}, 
	
	/**
	* displays a given gallery, based on the variable name passed
	*/
	show: function() {
		// turn on the lightbox modal backdrop effect
		this.backdrop.enable();
		// show the overlay
		$('webisodeOverlay').style.display = 'block';		
	},
	
	/**
	* closes the gallery
	*/
	close: function() {
		this.backdrop.disable();
		$('webisodeOverlay').style.display = 'none';
		this.resetGallery();
	},
	
	/**
	* resets url after user closes the gallery
	*/
	resetGallery: function() {
		window.location = String (document.location).split ('?')[0];
	},
	
	/**
	* this is a bug fix to work around an issue in the remote
	* 'addThis' library
	*/
	checkBodyStyle: function() 
	{
		new PeriodicalExecuter(function(pe) 
		{
			if( document.body.style.visibility == "hidden" )
			{
				document.body.style.visibility = "visible";
				pe.stop();
			}
			if (this.bodyStyleCounter >= 4)
			{
				pe.stop();
			}
		}.bind(this), 1);
		this.bodyStyleCounter ++;
	}
}

// Toggle Overlays
function toggle(x) {
	if ($(x).style.visibility == 'visible') {
		$(x).style.visibility = 'hidden';
	} else {
		$(x).style.visibility = 'visible';
	}
}

// Get Link URL value
function webisodeURL(){
	document.write('<input type="text" class="overlayInput" id="webisodeURL" value=""/>');
}

// Get Link Embed value
function webisodeEmbed(){
	document.write('<input type="text" class="overlayInput" id="webisodeEmbed" value""/>');
}