// JavaScript Document

window.addEvent('domready', function() {	
	timer.init();
	nav.init();
	columns.init();
	
	speedcast.init();
	wctvNews.init();
	
	//var linky = new Element("a", { href: "www.google.com" });
});

window.addEvent('load', function() {	
	//columns.init();
});

nav = {
	init: function () {
		$('nav') ? this.addEvents() : null;
		
	},
	
	addEvents: function () {
		var navItems = $('nav').getElements('img.nav_up');
		var overItem = $('nav').getElement('img.nav_over');

		navItems.each(function(item,index) {
			var up = item.src;
			var pre = item.src.substring(0, up.length-4);
			
			item.addEvents({
				mouseenter: function () {
					item.src = pre + "_over.png";
				},
				mouseout: function () {
					item.src = up;	
				}
			});
						
		});
	}
}

timer = {
	target: "",
	current: "",
	machineDiff: "",
	path: "/images/timer/",
	clockTimer: null,
	
	
	init: function () {
		//this.update();
		if($('timer')) {
			//this.target = this.getTarget();
			this.target = new Date($("dateDiv").innerHTML);
			this.current = new Date($("currentDateDiv").innerHTML);
			this.machineDiff = this.current - new Date();
			//alert(this.machineDiff + new Date().valueOf());
			var clock = this.getClock();
			//alert(clock.days + ":" + clock.hours + ":" + clock.mins + ":" + clock.secs);
			clockTimer = setInterval(this.update, 1000);
		}
	},
	
	getClock: function () {
		//var diff = this.target- new Date();
		var diff = this.target - (this.machineDiff + new Date().valueOf());
		
		var clock = {days:0, hours: 0, mins: 0, secs: 0};
		
		diff = Math.floor(diff/1000);//kill the "milliseconds" so just secs

		clock.days=Math.floor(diff/86400);//days
		diff=diff%86400;

		clock.hours=Math.floor(diff/3600);//hours
		diff=diff%3600;

		clock.mins=Math.floor(diff/60);//minutes
		diff=diff%60;

		clock.secs=Math.floor(diff);//second
		
		return clock;
	},
	
	update: function ()	{
		if ($('timer')) {
			var secs = timer.splitNum(timer.getClock().secs);
			$('sec_1').src = timer.path+secs[0]+".png";
			$('sec_2').src = timer.path+secs[1]+".png";

			var mins = timer.splitNum(timer.getClock().mins);
			$('min_1').src = timer.path+mins[0]+".png";
			$('min_2').src = timer.path+mins[1]+".png";
			
			var hours = timer.splitNum(timer.getClock().hours);
			$('hour_1').src = timer.path+hours[0]+".png";
			$('hour_2').src = timer.path+hours[1]+".png";
			
			var days = timer.splitNum(timer.getClock().days);
			if(days[2]) {
				$('day_3').src = timer.path+days[0]+".png";
				$('day_1').src = timer.path+days[1]+".png";
				$('day_2').src = timer.path+days[2]+".png";
			} else {
				$('day_1').src = timer.path+days[0]+".png";
				$('day_2').src = timer.path+days[1]+".png";
			}
		} else {
			clearInterval(timer.clockTimer);	
		}
	},
	
	splitNum: function (num) {
		var str = num.toString();
		var arr = str.split("");
		if(arr.length < 2) arr.unshift('0');
		if(arr[0]=="-") arr = ["0", "0"];
		return arr; 
	},
	
	getTarget: function () {
		var d = new Date($("dateDiv").innerHTML);
		return d;
	}
}


columns = {
	init: function () {
		$('content_columns') ? this.fix() : null;
	},
	fix: function () {
		var heights = new Array();
		heights.push(parseInt($('box_news').getScrollSize().y) - 35);
		heights.push(parseInt($('box_profiles').getScrollSize().y) - 35);
		heights.push(parseInt($('box_races').getScrollSize().y) - 35);
		
		var ordered = heights.sort(function(a,b){return b - a});
		$('box_news').setStyle('height', ordered[0]);
		$('box_profiles').setStyle('height', ordered[0]);
		$('box_races').setStyle('height', ordered[0]);
	}
}

losForms = {
	reqFields: new Array(),

	setRequiredFields: function(sFields) {
		losForms.reqFields = sFields;
	},

	checkFields: function() {
		missingFields = false;
		firstMissing = null;
		
		var aFieldTypes = ["input","textarea","select"];

		aFieldTypes.each(function(fldType) {
			aFields = $$(fldType + "[class=field_required]");
	
			aFields.each(function(fld) {
				fldName = fld.getProperty("name");
				fldType = fld.getProperty("type")
				if(fldType == "checkbox" || fldType == "radio") {
					
					// Checkbox or Radio button
					aChkFields = $$("input[name=" + fldName + "]");
			
					if(aChkFields.length > 0) {
//						aChkFields = $$("input[name=" + fldName + "[]]");
					}
					
					
					var bAnythingChecked = false;
					
					aChkFields.each(function(chkFld) {
						if(chkFld.checked) {
							bAnythingChecked = true;
						}
					});
						
					if(!bAnythingChecked == true) {
						missingFields = true;

						if($("title_" + fldName)) {
							var elTitle = $("title_" + fldName);
							
							if(elTitle.className != "fieldTitleRequired") {
								elTitle.store("originalClass",elTitle.className);
								elTitle.className = "fieldTitleRequired";		
							}

							if(firstMissing == null) {
								firstMissing = $("title_" + fldName);	
							}
						}
					}
				} else {
					if(fld.value == "") {
						missingFields = true;

						if($("title_" + fldName)) {
							var elTitle = $("title_" + fldName);
							elTitle.store("originalClass",elTitle.className);
							elTitle.className = "fieldTitleRequired";
								
							if(firstMissing == null) {
								firstMissing = $("title_" + fldName);	
							}
						}
					}
				}
			});
		});
		
		if(missingFields) {
			alert("You forgot some necessary information.  Please fill out all fields to continue.");
			return false;
		}
		
		if($("password_confirm")) {
			if($("password").value != $("password_confirm").value) {
				$("title_password").className = "fieldTitleRequired";
				$("title_password_confirm").className = "fieldTitleRequired";
				
				alert("The passwords you entered do not match.");
				return false;
			}			
		}

		if($("email_confirm")) {
			if($("email").value != $("email_confirm").value) {
				$("title_email").className = "fieldTitleRequired";
				$("title_email_confirm").className = "fieldTitleRequired";
				
				alert("The email addresses you entered do not match.");
				return false;
			}
		}

		if($("billing_email_confirm")) {
			if($("billing_email").value != $("billing_email_confirm").value) {
				$("title_billing_email").className = "fieldTitleRequired";
				$("title_billing_email_confirm").className = "fieldTitleRequired";
				
				alert("The email addresses you entered do not match.");
				return false;
			}
		}

		return true;
	},
	

	submitForm: function(formID) {
		if(this.checkFields()) {
			$(formID).submit();
		}
	},

	resetRequired: function(sField) {
		if($("title_" + sField)) {
			var elTitle = $("title_" + sField);
			if(elTitle.className == "fieldTitleRequired") {
				elTitle.className = elTitle.retrieve("originalClass");
			}
		}
		
		$(sField).className = $(sField).retrieve("originalClass","field_required");
	},
	
	otherInput: function(e,sTitle) {
		if(e.value == "Other...") {
			$(sTitle).setStyle("display","inline");
		} else {
			$(sTitle).setStyle("display","none");
		}
	},
	
	submitRegForm: function(formID) {
		if(this.checkFields()) {
			$(formID).submit();
		}
	},
		
	submitAjaxForm: function(formID,updateDiv) {
		if(this.checkFields()) {
			elDiv = $(updateDiv);
			
			elDiv.set("tween",{
				duration: "short",
				onComplete: function() {
					$(formID).set("send", {
						method: "post",
						onSuccess: function(responseText) {		
							elDiv.innerHTML = responseText;							
							elDiv.set("tween",{onComplete: function() {}});

							elDiv.fade("in");
						}
					}).send();
				}
			});

			elDiv.fade("out");
		} 
	}
}

speedMovie = {
	fullscreen: function() {
		$("SpeedCastMovie").fullScreen = true;	
	},
	
	trouble: function() {
		$("freeLogin").setStyle("display","block");	
	}
	
}

speedcast = {
	category: 'home',
	curPanel: 'featured',
	sections: ["home","2011","2010","2009","2008","worldchallenge"],
	panels: ["featured","video","races","schedule","driver","drivers","article","news",],
	bNewSection: false,
	bDev: false,
	ply: null,
	swfMoviePlayer: null,
	
	init: function() {	
	
		activeSection = $('top').getElements('img.nav_over');
		if(activeSection) {
			activeSection.each(function(item,index) {
				speedcast.category = item.get("id").substr(8);
			});
		}

		HistoryManager.initialize();
		speedcast.history = HistoryManager.register(
				'panel',
				[0], // default, page 0
				function(values) {
					if(values[0] != 0) {
						speedcast.historyRedirect(values);
					} else if(speedcast.curPanel != "featured") {
						if(speedcast.category == "worldchallenge") {
							speedcast.goSubSection("about");
						} else {
							speedcast.viewFeatured(speedcast.category);
						}
					}
				},
				function(values) {
					sReturn = '/' + values[0];
					
					for(var n=1;n<2;n++) {
						if(values[n]) {
							if(values[n] != null) {
								sReturn += "/" + values[n];
							}
						}
					}
					return  sReturn;
				},
				/\/(races|news|schedule|drivers|about|faq|advertising|feedback|terms)(\/[^\/]+)?/ // the regexp to match "page-index(0)"
			);
		
		HistoryManager.start();

		if($("mediaspace")) {
			speedcast.initSilverlightMovie();
			//alert("go time");
		}
		
		// Flash stream
		if($("flashspace")) {
			speedcast.initFlashMovie();
		}
	},
	
	historyRedirect: function(values) {
		if(values[1] != null) {
			val = values[1].substring(1);
			switch(values[0]) {
				case "races":
					speedcast.watchVideo(val,speedcast.category);
					break;
					
				case "news":
					speedcast.readArticle(val);
					break;
					
				case "schedule":
					speedcast.viewSchedule(speedcast.category);
					break;
					
				case "drivers":
					speedcast.viewDriver(val);
					break;
			}
		} else {
			switch(values[0]) {
				case "races":
					speedcast.viewAllRaces(speedcast.category);
					break;
					
				case "news":
					speedcast.viewAllNews(speedcast.category);
					break;
					
				case "schedule":
					speedcast.viewSchedule(speedcast.category);
					break;
					
				case "drivers":
					speedcast.viewAllDrivers(speedcast.category);
					break;
					
				case "about":
				case "faq":
				case "feedback":
				case "advertising":
				case "terms":
					speedcast.goSubSection(values[0]);
					break;
					
				default:
					speedcast.viewFeatured(speedcast.category);
					break;
			}
			
		}
	},
	
	init_dev: function() {
		speedcast.bDev = true;
	},

	adjustAdHeight: function() {
		iHeight = window.frames.adFrame.goTime();
		speedcast.adFrame.setStyle("height",iHeight);	
	},
	
	watchVideo: function(raceID,category) {
		oData = {raceID: raceID, category: category, action: "video", titleKey: "video_key" };
		
		speedcast.history.setValues(["races",raceID]);
		speedcast.updateRacePanel(oData);
	},
	
	viewAllRaces: function(sSection) {
		oData = {action: "onDemand", section: sSection, panel: "videos" };
		
		speedcast.history.setValue(0,"races");
		speedcast.updateRacePanel(oData);
	},

	viewSchedule: function(sSection) {
		oData = {action: "schedule", panel: "schedule", section: sSection };
		
		speedcast.history.setValue(0,"schedule");
		speedcast.updateRacePanel(oData);
	},
	
	viewFeatured: function(sSection) {
		oData = {action: "featured", panel: "featured", section: sSection };
		
		speedcast.updateRacePanel(oData);
	},
	
	viewDriver: function(id) {
		oData = {driverID: id, action: "driverProfile", panel: "driver", titleKey: "driver_key" };
		
		speedcast.history.setValues(["drivers",id]);
		speedcast.updateRacePanel(oData);
	},

	viewAllDrivers: function(sSection) {
		oData = {action: "allDrivers", section: sSection, panel: "drivers"};
		
		speedcast.history.setValue(0,"drivers");
		speedcast.updateRacePanel(oData);
	},

	viewAllNews: function(sSection) {
		oData = {action: "allNews", section: sSection, panel: "news"};
		
		speedcast.history.setValue(0,"news");
		speedcast.updateRacePanel(oData);
	},

	readArticle: function(id) {
		oData = {newsID: id, action: "newsArticle", section: this.category, panel: "news", titleKey: "article_key" };
		
		speedcast.history.setValues(["news",id]);
		speedcast.updateRacePanel(oData);
	},

	forgotPass: function() {
		oData = {action: "forgotPass", panel: "forgot_password" };
		
		speedcast.history.setValue(0,"forgot_pass");
		speedcast.updateRacePanel(oData);
	},

	doSearch: function() {
		if($("search").value != "") {
			oData = {action: "search", searchData: $("search").value, panel: "search" };
			
			speedcast.updateRacePanel(oData);
		}
	},
	
	trackAjax: function(oData) {
//		if(oData.action) {
			var sPage = "";
			
			if(oData.section) {
				if(oData.section != "home") {
					sPage += "/" + oData.section;
				}
			}

			if(oData.subsection) {
				sPage += "/" + oData.subsection;
			}

			if(oData.panel) {
				sPage += "/" + oData.panel;
			}
			
			if(oData.titleKey) {
				if($(oData.titleKey)) {
					sPage += "/" + $(oData.titleKey).innerHTML;	
				}
			}
			
			pageTracker._trackPageview(sPage);
//			alert(sPage);
//		}
		
	},

	killPanelScripts: function() {
		
		// SCCA ad switcher
		if($("vidAds")) {
			sccaAds.killAds();
		}
	},

	updateRacePanel: function(oData) {
		if(speedcast.bDev) {
			oData.dev = true;	
		}
		
		if($("subnav") && !oData.subNav) {
			aNavs = $("subnav").getElements('img.nav_over');
			speedcast.resetSubRollovers(aNavs);
		}	
		
		if(timer.clockTimer != null) {
			clearInterval(timer.clockTimer);	
		}
	
		if($("mediaspace")) {
			speedcast.ply.sendEvent("STOP");
			clearInterval(speedcast.ply.model.timeint);
			speedcast.ply = null;
		}

		elDiv = $("racePanel");
		elDiv.set("tween",{
			duration: "short",
			onComplete: function() {
				new Request({
					url: "/racePanelFetcher.php",
					data: oData,
					method: "post",
					onSuccess: function(responseText) {				
						speedcast.killPanelScripts();

						elDiv.innerHTML = responseText;							
						elDiv.set("tween",{onComplete: function() {}});
						elDiv.fade("in");
						
						speedcast.curPanel = oData.panel;
						//speedcast.trackAjax(oData);
						
						///////////////////////////////////////
						// add history state - make sure things like member edits are covered,cuz anything that doesn't
						// match the reg expression forces a default to the featured video
						
						if(!milkbox.activated) {
							milkbox.reloadGalleries();
							if(milkbox.galleries.length > 0) {
								milkbox.initMilkbox();
								milkbox.saveOptions();
							}
						} else {
							milkbox.reloadGalleries();
						}

						if($("timer")) {
							timer.init();
						}
						
						if($("mediaspace")) {
							speedcast.initSilverlightMovie();
							//alert("go time");
						}
						
						// Flash stream
						if($("flashspace")) {
							speedcast.initFlashMovie();
						}

						
						if($("main_schedule")) {
							var aElements = $("main_schedule").getElements("tbody tr");
							aElements.each(function(item,index) {
								item.addEvents({
									mouseenter: function () {
										if(index + 1 != aElements.length) {
											item.addClass("highlight_over");
										}
									},
									mouseout: function () {
										item.removeClass("highlight_over");
									},
									click: function() {
										speedcast.watchVideo(item.getProperty("id").substr(5),speedcast.category);	
									}
								});
							});
						}

						var scroll = new Fx.Scroll(window).toElement($("tracktype"));
					}
				}).send();
			}
		});

		elDiv.fade("out");
	},

	loadVideo: function() {
		if($("mediaspace")) {
			speedcast.initSilverlightMovie();
			//alert("go time");
		}
		
		// Flash stream
		if($("flashspace")) {
			speedcast.initFlashMovie();
		}
	},
	
	initSilverlightMovie: function() {
		var cnt = document.getElementById("mediaspace");
		var src = '/mods/wmvplayer.xaml';
		var cfg = {
			file:$("vidUrl").value,
			height:$("vidHeight").value,
			width:$("vidWidth").value,
			stretch:"fit",
			autostart:"true"
		};
		
		if($("vidAds")) {
			cfg.usefullscreen  = "false";
		}
		
		speedcast.ply = new jeroenwijering.Player(cnt,src,cfg);

		if($("vidAds")) {
			sccaAds.init($("vidID").value);	
		}

	},
	
	initFlashMovie: function() {
		var sFile = $("vidUrl").value;
		//var sStreamer = ($("vidLive")) ? "rtmp://fms.131F.edgecastcdn.net/20131F" : "rtmp://fms.131F.edgecastcdn.net/00131F/" + $("vidPath").value + "/";
		//var sStreamer = ($("vidPath").value != "") ? "rtmp://fms.131F.edgecastcdn.net/00131F/" + $("vidPath").value + "/" : "rtmp://fms.131F.edgecastcdn.net/00131F/";
		
		if($("vidLive")) {
			speedcast.flashVars = {
				file: sFile,
				provider: "rtmp",
				streamer: "rtmp://fms.131F.edgecastcdn.net/20131F",
				autostart: "true",
				"rtmp.subscribe": "true"
			};
		} else {
			var sStreamer = ($("vidPath").value != "") ? "rtmp://fms.131F.edgecastcdn.net/00131F/" + $("vidPath").value + "/" : "rtmp://fms.131F.edgecastcdn.net/00131F/";
			
			speedcast.flashVars = {
				file: sFile,
				provider: "rtmp",
				streamer: sStreamer,
				autostart: "true",
				smoothing: "false",
				bufferlength: "5"

			};	
		}
		
		if($("playerImage")) {
			speedcast.flashVars.image = "/raceImages/" + $("playerImage").value;
		}
		
		speedcast.params = {
			allowscriptaccess: "always",
			wmode: "opaque",
			bgcolor: "#000000",
			allowfullscreen: "true"
		}
		
		if($("vidAds")) {
			speedcast.params.allowfullscreen = "false";
		}
		
		var attributes = {
			id: "speedmovie",
			name: "speedmovie"
		}
		
		speedcast.goEmbededFlash();
		
		if($("vidAds")) {
			sccaAds.init($("video_key").get("text"));	
		}
	},
	
	goEmbededFlash: function() {
		speedcast.swfMoviePlayer = new Swiff("/mediaplayer/player-licensed.swf", {
			id: "speedmovie",
			width: $("vidWidth").value,
			height: $("vidHeight").value,
			params: speedcast.params,
			vars: speedcast.flashVars});

		$("flashspace").grab(speedcast.swfMoviePlayer);
		$("flashspace").addEvent("click",function(e) { e.stopPropagation(); });
//		speedcast.swfMoviePlayer.addEvent("click",function(e) { e.stopPropagation(); });
	},
	
	goFullScreen: function(vidID) {
		var winSize = speedcast.winDimensions();
		var docBody = $(document.body);

		window.scrollTo(0,0);

		var iWinHeight = $(window).getSize().y;
		var iWinWidth = $(window).getSize().x;
		var iMovieHeight = iWinHeight - 80;
//		var iMovieWidth = Math.round(iWinHeight * $("vidWidth").value / $("vidHeight").value);
		var iMovieWidth = Math.round(iWinHeight * $("vidWidth").value / $("vidHeight").value);

		var iMovieLeft = Math.round((iWinWidth - iMovieWidth) / 2);

//		this.overlay = new Element('div', {
//			'id': 'fullscreenOverlay',
//			'styles': {
//				'visibility':'visible',
//				'width': iWinWidth,
//				'height': iWinHeight,
//				'top':'0px',
//				'overflow':'hidden'
//		}}).inject(docBody);
		
		this.overlay = "<div id=\"fullscreenOverlay\" style=\"visibility:visible;width:" + iWinWidth + ";height:" + iWinHeight + ";top:0px;overflow:hidden;\">";
		
				
//		var adDiv = new Element('div', {'id': 'fullScreenAds', 'styles': {'width': iMovieWidth, 'left': iMovieLeft}}).inject('fullscreenOverlay');
		
//		adDiv.innerHTML = $("fullScreenAdLayout").innerHTML;
		var adDiv = "<div id=\"fullScreenAds\" style=\"width:" + iMovieWidth + ";left:" + iMovieLeft + "\">" + $("fullScreenAdLayout").innerHTML + "</div>";
		this.overlay += adDiv + "</div>";

		docBody.innerHTML += this.overlay;
	
//		var adTable = adDiv.getFirst("table");
		var adTable = $("fullScreenAds").getFirst("table");
				
		adTable.set("width",iMovieWidth);
		
		docBody.setStyles({'height':iWinHeight,'width': iWinWidth,'overflow':'hidden'});
					
		$(window.document).addEvent('keydown',function(e){
			if(e.key == 'esc'){
				speedcast.closeFlashFakeFullScreen();
			}
		}.bindWithEvent(this));							   

		$("exitButtonTop").addEvent('click',function() {
			speedcast.closeFlashFakeFullScreen();
		}.bindWithEvent(this));
													   
//		this.overlay.addEvent('click',function(){ 
//			speedcast.closeFlashFakeFullScreen();
//		}.bindWithEvent(this));
		
				
//		document.getElementById("speedmovie").height = iMovieHeight;
//		document.getElementById("speedmovie").width = iMovieWidth;
		
		//$("fullscreenOverlay").innerHTML += "<div id=\"exitButton\"></div>";
		
		speedcast.swfMoviePlayerBIG = new Swiff("/mediaplayer/player-licensed.swf", {
			id: "speedmovieBIG",
			width: iMovieWidth,
			height: iMovieHeight,
			params: speedcast.params,
			vars: speedcast.flashVars});

		$("fullscreenOverlay").grab(speedcast.swfMoviePlayerBIG);
//		this.overlay += adDiv + speedcast.swfMoviePlayerBIG
		
		$("flashspace").innerHTML = "";
//		$("speedmovie").destroy();
		
		// Grab rotating ads
		for(var i in sccaAds.aAdSlots) {
			if(isNaN(i)) { continue; }

			sCat = sccaAds.aAdSlots[i];
			//alert($("fullScreenAds").get("html"));
			oAdDiv = $("fullScreenAds").getElement("td[id=tmp_sccaFullscreen" + sCat + "]");
			oAdDiv.set("id","sccaFullscreen" + sCat);
			oAdDiv = $("sccaFullscreen" + sCat);
			oAdDiv.set("html",$("scca" + sCat).get("html"));
		}
	},

	closeFlashFakeFullScreen: function() {
		$(document.body).setStyles({'height':'auto','width': 'auto','overflow':'visible'});

//		document.getElementById("speedmovie").height = $("vidHeight").value;
//		document.getElementById("speedmovie").width = $("vidWidth").value;
		
		speedcast.goEmbededFlash();
//		$("flashspace").grab(speedcast.swfMoviePlayer);
		$("fullscreenOverlay").innerHTML = "";
		$("fullscreenOverlay").set("display","none");
		document.getElementById("fullscreenOverlay").style.visiblity = "hidden";
		document.getElementById("fullscreenOverlay").style.display = "none";
		this.overlay.destroy();
		
		
	},
	
	goSection: function(sSection, sSubSection) {
		activeSection = $('top').getElements('img.nav_over');
		if(activeSection) {
			activeSection.each(function(item,index) {
				sectionName = item.get("id").substr(8);
				var src = "/images/nav/" + sectionName + ".png";
				var overSrc = "/images/nav/" + sectionName + "_over.png";
				item.src = src;
				item.className = "nav_up";
				
				var oldItem = $(item.get("id"));
//				oldItem.addEvent("mouseout",function() {
//					oldItem.src = src;	
//					oldItem.className = "nav_up";
//				});

				oldItem.addEvents({
					mouseenter: function () {
						oldItem.src = overSrc;
						oldItem.className = "nav_over";
						nav.checkEnd(this,"_over");
					},
					mouseout: function () {
						oldItem.src = src;	
						oldItem.className = "nav_up";
						nav.checkEnd(this,"");
					}
				});
				
			});

			if(sSection != 'nasa') {
				$("series_cap").className = "cap";
			}
		}
		
		if(sSection != 'home') {
			navItem = $("navitem_" + sSection);
			navItem.src = "/images/nav/" + sSection + "_over.png";
			navItem.className = "nav_over";
			navItem.removeEvents("mouseout");
			
		
			// Preload banner and title images so the animation is smoother
			switch (sSection) {
				case "dirt":
				case "road":
					var images = ["/images/header_bg/" + sSection + ".png","/images/titles/" + sSection + ".png"];
					break;

				case "nasa":
					var images = ["/images/header_bg/nasa.png","/images/titles/NASALogo.png"];
					break;
					
				case "karting":
					var images = ["/images/header_bg/karting.png","/images/titles/kart.png"];
					break;
	
				case "paved":
					var images = ["/images/header_bg/paved.png","/images/titles/pavement.png"];
					break;
	
				case "worldchallenge":
	//				var images = ["/images/nav/sub_about_over.png","/images/nav/sub_advertising.png","/images/nav/sub_faq.png","/images/nav/sub_feedback.png","/images/nav/sub_terms.png"];
					var images = ["/images/nav/sub_about_over.png"];	// mas rapido
					if(!sSubSection) {
						sSubSection = "about";	//default subpage
					}
					break;
					
			}
			
			var loader = new Asset.images(images, {  
				onComplete: function() {
					speedcast.loadSection(sSection,sSubSection);
				}  
			});  
		} else {
			if(sSubSection) {
				speedcast.loadSection("home",sSubSection);
			} else {
				speedcast.loadSection("home","featured");
			}
		}
	},

	goSpeedcastSection: function(sSection) {
		speedcast.history.setValue(0,sSection);
		speedcast.goSubSection(sSection);
	},
	
	resetSubRollovers: function(aLinks) {
		aLinks.each(function(item,index) {
			sectionName = item.get("id").substr(11);
			var src = "/images/nav/sub_" + sectionName + ".png";
			item.src = src;
			item.className = "nav_up";
			
			var oldItem = $(item.get("id"));
			oldItem.addEvent("mouseout",function() {
				oldItem.src = src;	
				oldItem.className = "nav_up";
			});		
		});
	},

	goSubSection: function(sSection) {
		if($('subnav')) {
			activeSection = $('subnav').getElements('img.nav_over');
			if(activeSection) {
				activeSection.each(function(item,index) {
					sectionName = item.get("id").substr(11);
					var src = "/images/nav/sub_" + sectionName + ".png";
					item.src = src;
					item.className = "nav_up";
					
					var oldItem = $(item.get("id"));
					oldItem.addEvent("mouseout",function() {
						oldItem.src = src;	
						oldItem.className = "nav_up";
					});		
				});
			}
			
			navItem = $("subnavitem_" + sSection);
			navItem.src = "/images/nav/sub_" + sSection + "_over.png";
			navItem.className = "nav_over";
			navItem.removeEvents("mouseout");
			
			oData = { action: sSection, subNav: true, section: "speedcast", subsection: sSection };
			speedcast.history.setValue(0,sSection);
			speedcast.updateRacePanel(oData);
						
		} else {
			speedcast.loadSection("speedcast",sSection);	
		}
	},

	loadSection: function(sSection, sSubSection) {
		//$("adFrame").src = "/adSenseFetcher.php?cat=" + sSection;
		
		var tmpBanner = $("tmpBanner");
		tmpBanner.src = "/images/header_bg/" + sSection + ".png";

		tmpBanner.set("tween",{
			duration: "long",
			onComplete: function() {
				$("top").className = "bg_" + sSection;
				tmpBanner.set("opacity",0);
			}
		});
		
		tmpBanner.fade("in");
		
		var darthFader = new Fx.Elements([$("racePanel"),$("onDemandPanel"),$("newsColumn"),$("driverColumn"),$("scheduleColumn"),$("pagetop")], {
			onComplete: function(responseText) {
				if($("onDemandPanel").get("opacity") == 0) {
					new Request.HTML({
						url: "/doPanelUpdate.php",
						data: {section: sSection, subSection: sSubSection },
						method: "post",
						onSuccess: function(responseTree,responseElements,responseHTML,responseJavaScript) {
							responseElements.each(function (el) {
								aPanels = new Array("pagetopInnards","racePanel","onDemandPanel","newsColumn","driverColumn","scheduleColumn");
								elName = el.get("id");
								if(aPanels.contains(elName)) {
									$(elName).innerHTML = el.innerHTML;
								}								
							});
	
							timer.init();
							columns.init();
						
							if(sSection == "speedcast") {
								speedcast.initSubNav();
							}
							
							ptHeight = $("pagetopInnards").getScrollSize().y;
							
							oData = { section: sSection, subsection: sSubSection };
							//speedcast.trackAjax(oData);
							
//							darthFader.set({"onComplete": function() {}});
							darthFader.start({
								'0': {'opacity': 1},
								'1': {'opacity': 1},
								'2': {'opacity': 1},
								'3': {'opacity': 1},
								'4': {'opacity': 1},
								'5': {'opacity': 1, 'height': ptHeight }
							});	
						
							if(!milkbox.activated) {
								milkbox.reloadGalleries();
								if(milkbox.galleries.length > 0) {
									milkbox.initMilkbox();
									milkbox.saveOptions();
								}
							} else {
								milkbox.reloadGalleries();
							}

							speedcast.loadVideo();
						}
					}).send();
				}
			}
		}).start({
			'0': {'opacity': 0},
			'1': {'opacity': 0},
			'2': {'opacity': 0},
			'3': {'opacity': 0},
			'4': {'opacity': 0},
			'5': {'opacity': 0}
		});	

	},
			
	initSubNav: function() {
		var navItems = $('subnav').getElements('img.nav_up');
		//alert(navItems.length);
		navItems.each(function(item,index) {
			var up = item.src;
			var pre = item.src.substring(0, up.length-4);
			
			item.addEvents({
				mouseenter: function () {
					item.src = pre + "_over.png";
				},
				mouseout: function () {
					item.src = up;
				}
			});
						
		});
		
		var downItems = $('subnav').getElements('img.nav_over');
		downItems.each(function(item,index) {
			var down = item.src;
			item.addEvent("mouseover",function() {
				item.src = down;
			});
		});
	},
		
	viewImage: function(picIndex,sGallery) {
		milkbox.showGallery({gallery: sGallery, index: picIndex});	
	},
		
	winDimensions: function() {
		var windowHeight = 0;
		var windowWidth = 0;

		if( typeof( window.innerWidth ) == 'number' ) {
			windowHeight = window.innerHeight;
			windowWidth = window.innerWidth;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			windowHeight = document.documentElement.clientHeight;
			windowWidth = document.documentElement.clientWidth;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			windowHeight = document.body.clientHeight;
			windowWidth = document.body.clientWidth;
		}
		
		return [windowWidth, windowHeight];
	},
	
	resizeVideo: function(id, e) {
		if($("mediaspace")) {
			speedcast.ply.sendEvent("STOP");
			clearInterval(speedcast.ply.model.timeint);
			speedcast.ply = null;
		}

		new Request({
			url: "/mods/doVideoResize.php",
			data: {videoID: id, videoSize: e.options[e.selectedIndex].value },
			method: "post",
			onSuccess: function(responseText) {				
				$("videoBox").innerHTML = responseText;

//				if($("mediaspace")) {
//					//alert("go time");
//					var cnt = document.getElementById("mediaspace");
//					var src = '/mods/wmvplayer.xaml';
//					var cfg = {
//						file:$("vidUrl").value,
//						height:$("vidHeight").value,
//						width:$("vidWidth").value,
//						stretch:"fit",
//						autostart:"true"
//					};
//					speedcast.ply = new jeroenwijering.Player(cnt,src,cfg);
//				}

				if($("mediaspace")) {
					speedcast.initSilverlightMovie();
					//alert("go time");
				}
				
				// Flash stream
				if($("flashspace")) {
					speedcast.initFlashMovie();
				}

			}
		}).send();
	}
}

wctvNews = {
	init: function() {
		if($("newsContainer")) {
			new Request({
				url: "/mods/doNewsFeed.php",
				data: {page: 1},
				method: "post",
				onSuccess: function(responseText) {				
					$("newsContainer").innerHTML = responseText;
					columns.fix();
				}
			}).send();
		}
	}
}

sccaAds = {
	adSets: null,
	aAdSlots: new Array("Banner1","Button","Banner2"),
	aAdElements: new Object(),
	aTimeouts: { Banner1: null, Banner2: null, Button:  null, Ads: null },
	
	init: function(id) {

		new Request.JSON({
			url: "/mods/doLoadAdsSCCA.php",
			data: {videoID: id },
			method: "post",
			onSuccess: function(jsonSets, responseText) {				
				sccaAds.adSets = jsonSets;
				//alert(responseText);
				
				for(var i in sccaAds.aAdSlots) {
					if(isNaN(i)) { continue; }	// Skip extra javascript properties like 'constructor'

					// Find latest ad set who's start time has already past
					var sCat = sccaAds.aAdSlots[i];
					var iCurrentTime = new Date();
					var	iFirstSet = "";

					// Find first ad set for each slot and load it
					for(var n in sccaAds.adSets[sCat]) {
						var iTime = new Date();
						iTime.setHours(sccaAds.adSets[sCat][n]["time"].substr(0,2),sccaAds.adSets[sCat][n]["time"].substr(3,2),00);

						if(iTime <= iCurrentTime) {
							iFirstSet = n;
						} else {
							if(iFirstSet != "") {
								iDiff = iTime - iCurrentTime;
								sccaAds.adSets[sCat]["nextSet"] = n;
								
								sccaAds.setSetTimer(sCat,iDiff);
								//alert("loading " + n + " into " + sCat + " in " + (iDiff / 1000) + " seconds");
								
								break;
							} else {
								iFirstSet = n;
							}
						}
					}
					
					sccaAds.loadSet(iFirstSet,sCat);					
				}
				
				// Start Ad Rotation
//				sccaAds.aTimeouts["Ads"] = setTimeout("sccaAds.rotateAds()",120000);
				sccaAds.aTimeouts["Ads"] = setTimeout("sccaAds.rotateAds()",2000);
			}
		}).send();
	},
	
	setSetTimer: function(sCat,iTime) {
		switch(sCat) {
			case "Banner1":
				sccaAds.aTimeouts[sCat] = setTimeout(function() { sccaAds.loadFreshSet("Banner1"); }, iDiff);
				break;
				
			case "Banner2":
				sccaAds.aTimeouts[sCat] = setTimeout(function() { sccaAds.loadFreshSet("Banner2"); }, iDiff);
				break;
				
			case "Button":
				sccaAds.aTimeouts[sCat] = setTimeout(function() { sccaAds.loadFreshSet("Button"); }, iDiff);
				break;
		}
	},
	
	loadSet: function(setID,sCat) {
		sccaAds.aAdElements[sCat] = new Array();
		
//		for(var n in sccaAds.adSets[sCat][setID]["ads"]) {
		for(var n=0; n<sccaAds.adSets[sCat][[setID]]["ads"].length;n++) {
			var iDoubleClick = sccaAds.adSets[sCat][setID]["ads"][n]["doubleclick"];
			
//			var linky = new Element("a", { href: sccaAds.adSets[sCat][setID]["ads"][n]["url"], target: "_blank" });
//			var pic = new Element("img", { src: "/raceAdImages/" + sccaAds.adSets[sCat][setID]["ads"][n]["image"] });
//			
//			linky.grab(pic);
			
			if(sccaAds.adSets[sCat][setID]["ads"][n]["url"] != "") {
				var linky = "<a href=\"" + sccaAds.adSets[sCat][setID]["ads"][n]["url"] + "\" target=\"_blank\"><img src=\"/raceAdImages/" + sccaAds.adSets[sCat][setID]["ads"][n]["image"] + "\" /></a>";
			}
						
			// Insert DoubleClick 1x1 image
//			if(iDoubleClick > 0) {
//				var oDate = new Date();
//				var oneXone = new Element("img", { src: sccaAds.adSets["SCCA_" + iDoubleClick]["image"] + oDate.getTime() + "?" });
//				linky.grab(oneXone);
//				
//				linky.store("doubleclick_num",iDoubleClick);
//			}
			
			sccaAds.aAdElements[sCat].push(linky);
		}
		
		// Draw first ads
		$("scca" + sCat).set("html",sccaAds.aAdElements[sCat][0]);
		//sccaAds.aAdElements[sCat][0].clone().inject("scca" + sCat);
		
		// Fullscreen, if available
		if($("fullscreenOverlay")) {
			$("sccaFullscreen" + sCat).set("html",sccaAds.aAdElements[sCat][0]);
			//sccaAds.aAdElements[sCat][0].clone().inject("sccaFullscreen" + sCat);
		}
		
		sccaAds.adSets[sCat]["currentAd"] = 0;
		sccaAds.adSets[sCat]["currentSet"] = setID;
		
	},
	
	loadFreshSet: function(sCat) {
		sNextSet = sccaAds.adSets[sCat]["nextSet"];
		sccaAds.loadSet(sNextSet,sCat);

		var bCurrent = false;
		var iDiff = 0;
		for(var sSetID in sccaAds.adSets[sCat]) {
			if(sSetID.substr(0,4) == "set_") {
				if(bCurrent) {
					var iCurrentTime = new Date();
					var iTime = new Date();
					iTime.setHours(sccaAds.adSets[sCat][sSetID]["time"].substr(0,2), sccaAds.adSets[sCat][sSetID]["time"].substr(3,2), 00);
					
					if(iTime > iCurrentTime) {
						sccaAds.adSets[sCat]["nextSet"] = sSetID;
						
						iDiff = iTime - iCurrentTime;
						sccaAds.setSetTimer(sCat,iDiff);
	
						break;
					}
				} else {
					
					if(sSetID == sNextSet) { bCurrent = true; }	
				}
			} else {
				//alert(sSetID + " is not a valid category");
			}
		}
		
//		sMsg = "loaded " + sNextSet + " into " + sCat;
//		sMsg += (iDiff == 0) ? "\nNo more sets to load for " + sCat : "\nLoading " + sSetId + " in " + (iDiff / 1000);
//		alert(sMsg);
	},
	
	rotateAds: function() {
		for(var i in sccaAds.aAdSlots) {
			if(isNaN(i)) { continue; }

			sCat = sccaAds.aAdSlots[i];
			sCurrentSet = sccaAds.adSets[sCat]["currentSet"];
			
			sccaAds.adSets[sCat]["currentAd"]++;
			if(sccaAds.adSets[sCat]["currentAd"] >= sccaAds.adSets[sCat][sCurrentSet]["ads"].length) {
				sccaAds.adSets[sCat]["currentAd"] = 0;
			}
			
//			alert("current ad: " + sccaAds.adSets[sCat]["currentAd"] + "\n" + sccaAds.adSets[sCat][sCurrentSet]["ads"].length );
			
			// Rotate Ads
			$("scca" + sCat).set("html",sccaAds.aAdElements[sCat][sccaAds.adSets[sCat]["currentAd"]]);
			//sccaAds.aAdElements[sCat][sccaAds.adSets[sCat]["currentAd"]].clone().inject("scca" + sCat);
			
			// Rotate fullscreen ads, if available
			if($("fullscreenOverlay")) {
				$("sccaFullscreen" + sCat).set("html",sccaAds.aAdElements[sCat][sccaAds.adSets[sCat]["currentAd"]]);
				//sccaAds.aAdElements[sCat][sccaAds.adSets[sCat]["currentAd"]].clone().inject("sccaFullscreen" + sCat);
			}
			
//			var iDoubleClick = sccaAds.aAdElements[sCat][sccaAds.adSets[sCat]["currentAd"]].retrieve("doubleclick_num");
//			if(iDoubleClick > 0) {
//				var oDate = new Date();
//				var sImageLink = sccaAds.adSets["SCCA_" + iDoubleClick]["image"] + oDate.getTime() + "?";
//
//				$("scca" + sCat).getFirst("a").getLast("img").setProperty("src",sImageLink);
//			}

		}
		
//		sccaAds.aTimeouts["Ads"] = setTimeout("sccaAds.rotateAds()",120000);
		sccaAds.aTimeouts["Ads"] = setTimeout("sccaAds.rotateAds()",2000);
	},
	
	killAds: function() {
		for(var i in sccaAds.aAdSlots) {
			if(isNaN(i)) { continue; }
			
			clearTimeout(sccaAds.aTimeouts[sccaAds.aAdSlots[i]]);
			clearTimeout(sccaAds.aTimeouts[sccaAds.aAdSlots[i]]);			
		}
		clearTimeout(sccaAds.aTimeouts["Ads"]);	
	}
}

