/**
 * 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'];
try {
	var pagePath = window.location.pathname;
} catch (e) {
	// permissions?
}
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')";
				//newImage.src = '/scionracing/images/x.gif';
			}	  
			
		}
	},
		
	rolloverImage: function(e) {
		image = Event.element(e);
		image.imageRollover.images[image.id] = image.src;
		image.src = image.imageRollover.parseRolloverImage(image);
	},
		
	rollbackImage: function(e) {
		image = Event.element(e);
		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 = '/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 = '/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 (document.getElementsByClassName('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 and road
		if (document.getElementById('subnavDrag') || document.getElementById('subnavRoad')) {
			document.getElementById('subGear').href = '/scionracing/' + currentSection + '/gear_' + currentTeam + '.html';
			document.getElementById('subSchedule').href = '/scionracing/schedule/index.html';
			document.getElementById('subGallery').href = '/scionracing/' + currentSection + '/gallery_' + currentTeam + '_video.html';
			document.getElementById('subAsk').href = '/ssl/scionracing/' + currentSection + '/ask_' + currentTeam + '.html';
		}
	},
	
	setFooterTeamLinks: function() {
		// set footer links for team pages
		if (document.getElementById('footerLinksTeam')) {
			document.getElementById('footerGear').href = '/scionracing/' + currentSection + '/gear_' + currentTeam + '.html';
			document.getElementById('footerGallery').href = '/scionracing/' + currentSection + '/gallery_' + currentTeam + '_video.html';
			document.getElementById('footerAsk').href = '/ssl/scionracing/' + currentSection + '/ask_' + currentTeam + '.html';
		}		
	}
	
}

// set nav on/off states for road

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

// 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(team == 'world')  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  
	}
}

//  Common MM Image swapping code... this should eventually be removed and done with pure CSS

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
 
