// JavaScript Document

window.addEvent('domready', function() {	
	timer.init();
	nav.init();
	columns.init();
	
//	if(speedcast.bDev) {
//		speedcast.init_dev();
//	} else {
		speedcast.init();
//	}
});

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');
		if(overItem) this.fixEnd(overItem);
		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";
					thiz.checkEnd(this,"_over");
				},
				mouseout: function () {
					item.src = up;	
					thiz.checkEnd(this,"");
				}
			});
						
		});
	},
	
	checkEnd: function (el,sSuffix)	{
		switch(el.id) {
			case "navitem_scca" :
				$('series_cap').className = "cap" + sSuffix;
//				($('series').getElement('.cap').className == "cap") ? $('series').getElement('.cap').className = "cap_over" : $('series').getElement('.cap_over').className = "cap";
			break;
//			case "navitem_speedcast" :
//				($('tracktype').getElement('.cap')) ? $('tracktype').getElement('.cap').className = "cap_over" : $('tracktype').getElement('.cap_over').className = "cap";
//			break;
			
		}
	},
	
	fixEnd: function (el) {
		switch(el.id) {
			case "navitem_nasa" :
				$('series').getElement('.cap').className = "cap_over";
			break;
//			case "navitem_speedcast" :
//				$('tracktype').getElement('.cap').className = "cap_over";
//			break;
		}
	}
}

timer = {
	target: "",
	path: "/images/timer/",
	clockTimer: null,
	
	init: function () {
		//this.update();
		if($('timer')) {
			this.target = this.getTarget();
			clockTimer = setInterval(this.update, 1000);
		}
	},
	
	getClock: function () {
		var diff = this.target-new Date();
		
		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,
	
	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();
	},
	
	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(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);
//		}
		
	},

	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) {				
						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")) {
							//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);
						}
						
						var scroll = new Fx.Scroll(window).toElement($("tracktype"));
					}
				}).send();
			}
		});

		elDiv.fade("out");
	},
	

	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();
							}
						}
					}).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();								
							}

							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();
	},
	
	goFullScreen: function(vidID) {
		var winSize = speedcast.winDimensions();

		new Request({
			url: "/mods/doFullScreenVideo.php",
			data: { width: winSize[0], height: winSize[1], videoID: vidID },
			method: "post",
			onSuccess: function(responseText) {				

				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(){ $("vidContainer").setStyle("display","none"); this.overlay.destroy();  }.bindWithEvent(this));
			}
		}).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);
				}
			}
		}).send();
	}
}

