// JavaScript Document

window.addEvent('domready', function() {	
	timer.init();
	nav.init();
	columns.init();
	
//	if(speedcast.bDev) {
//		speedcast.init_dev();
//	} else {
		speedcast.init();
//	}
	Asset.images(["/images/nav/road_over.png","/images/nav/karting_over.png","/images/nav/dirt_over.png","/images/nav/paved_over.png","/images/nav/forum_over.png","/images/nav/speedcast_over.png","/images/nav/series_nasa_over.png","/images/nav/series_scca_over.png","/images/nav/series_wctv_over.png","/images/nav/series_ote_over.png"]);
});

window.addEvent('load', function() {	
	//columns.init();
});

nav = {
	init: function () {
		$('nav') ? this.addEvents() : null;
		$('seriesNav') ? this.addSeriesNavEvents() : null;
		$('seriesNav2') ? this.addSeriesNavEvents() : null;
	},
	
	addEvents: function () {
		var navItems = $('nav').getElements('img.nav_up');
		var overItem = $('nav').getElement('img.nav_over');

		var thiz = this;
		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;	
				}
			});
						
		});
	},
	
	addSeriesNavEvents: function() {
		objNav = $('seriesNav2') ? $('seriesNav2') : $('seriesNav');
		objNav.getElements("img").each(function(item,index) {
			item.addEvents({
				mouseenter: function () {
					var sID = item.get("id");
					item.src = "/images/nav/" + sID + "_over.png";
					if(item.hasClass(sID)) {
						item.addClass(sID + "_over");
					}
				},
				mouseout: function () {
					var sID = item.get("id");
					item.src = "/images/nav/" + sID + ".png"
					item.removeClass(sID + "_over");
				}
			});
		});
	}
}

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) {
/*			var myFx = new Fx.Scroll($(document.body), {
				onComplete: function() {
					alert("You forgot some necessary information.  Please fill out the required fields to continue.");
				}
			});
			
			if(firstMissing != null) {
				myFx.toElement(firstMissing);
			}
*/
			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;
	},
	
	sameAsBilling: function() {
		frmFields = new Array("_firstname","_lastname","_address1","_address2","_city","_state","_zip","_phone","_fax","_email");
		frmFields.each(function(fld) {
			$("shipping" + fld).value = $("billing" + fld).value;
		});
		$("sameAsBilling").checked = false;
	},


	submitForm: function(formID) {
		if(this.checkFields()) {
			$(formID).submit();
//			alert("the form checks out");
		}
	},

	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.setStyle("height",elDiv.getScrollSize().y);
			
			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");
//							var myFx = new Fx.Scroll($(document.body));
//							myFx.toElement(elDiv);
						}
					}).send();
				}
			});

			elDiv.fade("out");
//			clearInterval(clockTimer);
		} 
	}
}

speedMovie = {

	fullscreen: function() {
		$("SpeedCastMovie").fullScreen = true;	
	},
	
	trouble: function() {
		$("freeLogin").setStyle("display","block");	
	}
	
}

basicContact = {
	sendForm: function () {
		var formError = false;
		var query = $('contactform').toQueryString();
		if($('name').value == "") {
			this.setRequired($('name'));
			formError = true;
		}
		
		if($('email').value == "") {
			this.setRequired($('email'));
			formError = true;
		}

		if(!$('email').value.match("@")){
			this.setRequired($('email'));
			formError = true;
		}
		
		if($('comments').value == ""){
			this.setRequired($('comments'));
			formError = true;
		}
		
		if(!formError){
			//console.log("Ready to send");
			//$('form_cont').fade('out');;
			var fx = new Fx.Tween('contactform')
			fx.start('opacity', 1, 0);
			
			var req = new Request({method: 'post', url:"/sendEmail.php", onSuccess:this.completeHandler, onFailure:this.showFailure}).send(query);
		}else {
			
		}
	},
	setRequired: function (el) {
		el.highlight();
	},
	completeHandler: function () {
		$('contactform').setStyle('display', 'none');
		$('thanks').setStyle('opacity', 0);
		$('thanks').setStyle('display', 'block');
		$('thanks').morph({'opacity': 1});
	},
	showFailure: function () {
		alert("There was a problem with the request");
	}
}

speedcast = {
	category: 'home',
	curPanel: 'featured',
	sections: ["home","road","karting","dirt","paved","speedcast"],
	panels: ["featured","video","races","schedule","driver","drivers","article","news","subscribe"],
	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 == "speedcast") {
							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|profile|forgot_pass|about|faq|advertising|feedback|terms)(\/[^\/]+)?/ // the regexp to match "page-index(0)"
			);
		
		HistoryManager.start();

//		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($("flashspace")) {
//			speedcast.initFlashMovie();	
//		}

		speedcast.loadVideo();
	},
	
	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 "profile":
					speedcast.memberProfile();
					break;
					
				case "forgot_pass":
					speedcast.forgotPass();
					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;
	},

	refreshCaptcha: function() {
		$("captchaImg").src = "/mods/captchaImage.php?x=" + Math.random();
	},

	memberProfile: function() {
		oData = { action: "memberProfile", panel: "member_profile" };
		
		speedcast.history.setValue(0,"profile");
		speedcast.updateRacePanel(oData);
	},

	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);
	},

	subscribe: function() {
		if($("referral")) {
			if($("referral").value != "") {
				//alert($("video_title").value);
			
				new Request({
					url: "/mods/doSetReferral.php",
					data: { ref: $("referral").value, video: $("video_title").value },
					method: "post",
					onSuccess: function(responseText) {
						speedcast.doSubscribe();
					}
				}).send();
				
			} else {
				speedcast.doSubscribe();	
			}
		} else {
			speedcast.doSubscribe();
		}
	},
	
	doSubscribe: function() {
		if(window.location.protocol != 'https:') {
			document.location = "https://www.speedcasttv.com/subscribe";	
		} else {

			oData = {action: "subscribe", panel: "subscribe" };
			
			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($("mediaspace")) {
							speedcast.initSilverlightMovie();
							//alert("go time");
						}
						
						// Flash stream
						if($("flashspace")) {
							speedcast.initFlashMovie();
						}
						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",
				stretch: "fill",
				"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",
				deblocking: "0",
				stretch: "fill"
			};
			
			
		}
		
		if($("playerImage")) {
			speedcast.flashVars.image = "/raceImages/" + $("playerImage").value;
		}
		
		speedcast.params = {
			allowscriptaccess: "always",
			wmode: "window",
			bgcolor: "#000000",
			allowfullscreen: "true"
		}

		if($("box_login")) {
			//alert("login");
			speedcast.params.allowfullscreen = "false";
		}
		
		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 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);
		
		var adDiv = new Element('div', {'id': 'fullScreenAds', 'styles': {'width': iMovieWidth, 'left': iMovieLeft}}).inject('fullscreenOverlay');
		adDiv.innerHTML = $("fullScreenAdLayout").innerHTML;
		var adTable = adDiv.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));							   
													   
//		this.overlay.addEvent('click',function(){ 
//			speedcast.closeFlashFakeFullScreen();
//		}.bindWithEvent(this));
		
				
//		document.getElementById("speedmovie").height = iMovieHeight;
//		document.getElementById("speedmovie").width = iMovieWidth;
		
		speedcast.swfMoviePlayerBIG = new Swiff("/mediaplayer/player-licensed.swf", {
			id: "speedmovieBIG",
			width: iMovieWidth,
			height: iMovieHeight,
			params: speedcast.params,
			vars: speedcast.flashVars});
			
		$("fullscreenOverlay").grab(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 = "";
		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 "speedcast":
	//				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;
								}
								
//								if(elName == "viewSchedule") {
//									$("viewSchedule") = el;
//								}
							});
	
							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;
			});
		});
	},
	
	loadMemberInfo: function() {
		elDiv = $("loginBox");
		elDiv.set("tween",{
			duration: "short",
			onComplete: function() {
				new Request({
					url: "/memberInfoFetcher.php",
					method: "post",
					onSuccess: function(responseText) {				
						elDiv.innerHTML = responseText;							
						elDiv.set("tween",{onComplete: function() {}});

						elDiv.fade("in");
					}
				}).send();
			}
		});

		elDiv.fade("out");
	},
	
	doLogin: function() {
		if($("moduleusername").value != "" && $("userpass").value != "") {
			elDiv = $("loginBox");
//			elDiv.setStyle("height",elDiv.getScrollSize().y);
			
			elDiv.set("tween",{
				duration: "short",
				onComplete: function() {
					$("loginForm").set("send", {
						method: "post",
						onSuccess: function(responseText) {
							elDiv.innerHTML = responseText;							
							elDiv.set("tween",{onComplete: function() {}});

							elDiv.fade("in");
						}
					}).send();
				}
			});
			
			elDiv.fade("out");
		} else {
			alert("A username and password are required");
		}
	},

	doPanelLogin: function() {
		if($("panelusername").value != "" && $("paneluserpass").value != "") {

			if($("mediaspace")) {
				speedcast.ply.sendEvent("STOP");
				clearInterval(speedcast.ply.model.timeint);
				speedcast.ply = null;
			}

			elDiv = $("racePanel");
//			elDiv.setStyle("height",elDiv.getScrollSize().y);
			
			elDiv.set("tween",{
				duration: "short",
				onComplete: function() {
					$("panelLoginForm").set("send", {
						method: "post",
						onSuccess: function(responseText) {
							elDiv.innerHTML = responseText;
							
							elDiv.set("tween",{onComplete: function() {}});

							elDiv.fade("in");
							if($("videoBox") || $("racePanelContent")) {
								speedcast.loadMemberInfo();								
							}

							speedcast.loadVideo();

//							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);
//							}
						}
					}).send();
				}
			});
			
			elDiv.fade("out");
		} else {
			alert("A username and password are required");
		}
	},

	doLogout: function() {
		elDiv = $("loginBox");
//			elDiv.setStyle("height",elDiv.getScrollSize().y);
		
		elDiv.set("tween",{
			duration: "short",
			onComplete: function() {
				new Request({
					url: "/doModuleLogout.php",
					onSuccess: function(responseText) {
						elDiv.innerHTML = responseText;							
						elDiv.set("tween",{onComplete: function() {}});

						elDiv.fade("in");
						
						speedcast.goSection("home","featured");
					}
				}).send();
			}
		});
		
		elDiv.fade("out");
	},
	
	viewImage: function(picIndex,sGallery) {
		milkbox.showGallery({gallery: sGallery, index: picIndex});	
	},
	
	selectMembership: function(e) {
		if(e.value == "Bronze") {
			$("chargeInfo").setStyle("display","none");
			new Fx.Morph($("billingDiv"), {
				duration: "normal"
			}).start({
				"height": 0,
				"opacity": 0
			});

			if($("captchaDiv")) {
				$("captchaDiv").setStyle("display","block");
			}
		} else {
			if($("captchaDiv")) {
				$("captchaDiv").setStyle("display","none");
			}
			
			new Request.JSON({
				url: "/mods/doCalculateTotal.php",
				data: { membership: e.value, promo: $("promo_code").value },
				method: "post",
				onSuccess: function(responseObj) {
					
					$("total").innerHTML = "$" + responseObj.total;
					$("chargeInfo").setStyle("display","inline");
//					if(responseObj.prorate) {
//						$("prorate").innerHTML = responseObj.prorate;
//					} else {
//						$("prorate").innerHTML = "";
//					}

					var scrollInfo = $("billingContent").getScrollSize();
		
					new Fx.Morph($("billingDiv"), {
						duration: "normal"
					}).start({
						"height": scrollInfo.y,
						"opacity": 1
					});
				}
			}).send();
		}
	},
	
	subscribeSubmit: function() {
		aFields = new Array("email","username","password","password_confirm");
//		aFieldsBilling = new Array("first_name","last_name","address","city","zip","card_number");
		aFieldsBilling = new Array("first_name","last_name","address","city","zip");
		bMissingFields = false;
		firstMissing = null;
		
		if(!$("membership_bronze").checked && !$("membership_silver").checked && !$("membership_gold").checked) {
			alert("Please select your preferred membership.");
			return false;
		}
		
		if($("membership_silver").checked || $("membership_gold").checked) {
			aFields.combine(aFieldsBilling);
			//alert("paid membership");
		}
		
		sMissingFields = "";
		aFields.each(function(fldName) {
//			fld = $("subscribeForm").getElementById(fldName);
			fld = $(fldName);
//			fld = document.getElementById(fldName);
			if(fld.value == "") {
				bMissingFields = true;
				sMissingFields += " - " + fldName;
				
				fld.store("originalClass",fld.className);
				fld.className = "field_missing";

				if($("title_" + fldName)) {
					var elTitle = $("title_" + fldName);
					elTitle.store("originalClass",elTitle.className);
					elTitle.className = "fieldTitleRequired";
						
					if(firstMissing == null) {
						firstMissing = $("title_" + fldName);	
					}
				}
			}
		});
		
		
		if(bMissingFields) {
			var myFx = new Fx.Scroll($(document.body), {
				onComplete: function() {
					alert("You forgot some necessary information.  Please fill out the required fields to continue." + sMissingFields);
				}
			});
			
			if(firstMissing != null) {
				myFx.toElement(firstMissing);
			}

//			alert("You forgot some necessary information.  Please fill out all fields to continue.");
			return false;
		}

		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;
		}
		
		elDiv = $("subscribeFormDiv");
//			elDiv.setStyle("height",elDiv.getScrollSize().y);
		
		elDiv.set("tween",{
			duration: "short",
			onComplete: function() {
				$("subscribeForm").set("send", {
					method: "post",
					onSuccess: function(responseText) {		
						elDiv.innerHTML = responseText;							
						elDiv.set("tween",{onComplete: function() {}});
						

						elDiv.fade("in");
//							var myFx = new Fx.Scroll($(document.body));
//							myFx.toElement(elDiv);

						// update login if info was correct
						if($("memberInfoReceipt")) {
							speedcast.loadMemberInfo();
						}
					}
				}).send();
			}
		});

		elDiv.fade("out");
	},
	
	submitUploadForm: function() {
//			$("docUploaderFrame").fade("out");
			//mcdcIntranet.upFrame.fade("out");
		if(losForms.checkFields()) {
			window.frames['updateFrame'].doUpload();
		}
	},
	
	doForgotPass: function() {
		if($("forgotPassUsername").value == "" && $("forgotPassEmail").value == "") {
			alert("You must enter either a username or password");
		} else {
			losForms.submitAjaxForm("forgotPassForm","forgotPassFormContainer");
		}
	},
	
	fetchPromoCode: function() {
		sMembership = "Bronze";
		["membership_bronze","membership_silver","membership_gold"].each( function(item, index) {
			if($(item).checked) {
				sMembership = $(item).value;
			}
		});
		
		new Request.JSON({
			url: "/mods/doCalculateTotal.php",
			data: { membership: sMembership, promo: $("promo_code").value },
			method: "post",
			onSuccess: function(responseObj) {
				$("total").innerHTML = "$" + responseObj.total;
				
				if(responseObj.race) {
					$("promoCodeReport").innerHTML = "<strong class=\"orange\">" + responseObj.race + "</strong><br /><em>Free Access</em>";
				}

				if(responseObj.title) {
					sMsg = "<strong class=\"orange\">" + responseObj.title + "</strong><br /><em>" + responseObj.discount + "% off " + responseObj.membership + " membership</em>";
					$("promoCodeReport").innerHTML = sMsg;
				}
				
				if(!responseObj.discount) {
					$("promoCodeReport").innerHTML = "";	
				}
			}
		}).send();
	},
	
	goVideoFullScreen: function(vidID) {
		if(Browser.Engine.trident) {
			$("WindowsMediaPlayer1").fullScreen = true;
		} else {
			var winSize = speedcast.winDimensions();
	
			new Request({
				url: "/mods/doFullScreenVideo.php",
				data: { width: winSize[0], height: winSize[1], videoID: vidID },
				method: "post",
				onSuccess: function(responseText) {				
					$("videoBox").innerHTML = "";
					
					this.overlay = new Element('div', { 'id':'fullscreenOverlay','styles':{ 'visibility':'visible','height':0,'overflow':'hidden' }}).inject($(document.body));
					this.overlay.innerHTML = responseText;
					$("vidContainer").setStyle("opacity", 1);
			
					var scrollSize = $(window).getScrollSize().y;
					var scrollTop = $(window).getScroll().y;
						
					this.overlay.setStyles({'height':scrollSize+scrollTop, 'top':-scrollTop });
					
					$(window.document).addEvent('keydown',function(e){
						if(e.key == 'esc'){
							this.overlay.destroy();
						}
					}.bindWithEvent(this));										   
																   
	
					this.overlay.addEvent('click',function(){
						speedcast.resizeVideo(vidID,$("qualitySelect"));
						$("vidContainer").setStyle("display","none");
						this.overlay.destroy();
					}.bindWithEvent(this));
				}
			}).send();
		}
	},
	
	
	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();
	}
}

sccaAds = {
	adSets: null,
	aAdSlots: new Array("Banner1","Button","Banner2"),
//	aAdSlots: new Array("Banner1","Banner2"),
	aAdElements: new Object(),
	aTimeouts: { Banner1: null, Banner2: null, Button:  null, Ads: null },
//	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()",180000);
//				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"];
//			if(iDoubleClick > 0) {
//				var linky = new Element("a", { href: sccaAds.adSets["SCCA_" + iDoubleClick]["click"], target: "_blank" });
//				var oDate = new Date();
//				var oneXone = new Element("img", {src: sccaAds.adSets["SCCA_" + iDoubleClick]["image"] + oDate.toTimeString() + "?" });
//			} else {
//			}
			
			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);
			
			// 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].clone().inject("scca" + sCat);
		
		// Fullscreen, if available
		if($("fullscreenOverlay")) {
			$("sccaFullscreen" + sCat).set("html","");
			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;
			}
			
			// Rotate Ads
			$("scca" + sCat).set("html","");
			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"]].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()",180000);
//		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"]);	
	}
}

