// allow me to use console.log in firefox while not giving errors in other browsers
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

var siteseerUser = {
	
	username: null,
	skymiles: null,
	miles: 0,
	watched: new Array(),
	voted: new Array(),
	loginInProgress: false,

	flagLogin: false,
	flagWatched: false,
	flagVoted: false,
	flagSkyMiles: false
}

var siteseerVotingInterface = {
	
	destination: 4,
	city: "dubai",
	voteTab: "", //"tabDubai",
	islocked: false,

	init: function()
	{
		$("#voteLock").hide();
		$("#voteLockContent").hide();
		$.getJSON("api/getCurrentUser.php?"+Math.round(Math.random()*100000000),{},function(json)
		{
			if(json.anonymous != "true")
			{
				siteseerVotingInterface.setUser(json);
				siteseerVotingInterface.updateWatched(json);	
				//console.log(siteseerUser.watched);
				siteseerVotingInterface.refreshWatched();

			}
			siteseerVotingInterface.refresh();
		});
	},

	updateWatched: function(json)
	{
		$.each(json.watched, function(destination,teams) {
			if(destination == siteseerVotingInterface.destination) {
				//console.info("destination",destination);
				if(!siteseerUser.watched[destination]) {
					siteseerUser.watched[destination] = new Array();
				}
				$.each(teams,function(i,team) {
					//console.info("i",i);
					//console.info("team",team);
					if(siteseerUser.watched[destination].toString().indexOf(team.toString()) < 0) {
						siteseerUser.watched[destination].push(team.toString());
					}
					// set the video.playhead = true
					$.each(siteseerVideos, function(i,video) {
						//console.info(siteseerUser.watched[destination]);
						if(video.team == team && video.destination == siteseerVotingInterface.city) {
							//console.info("Setting playhead = true",video.team,video.destination);
							video.playhead = "true";
						}
					});
				});
			}
		});
	},

	resetWatched: function()
	{
		$.each(siteseerVideos, function(i,video) {
			//console.info(siteseerUser.watched[destination]);
			if(video.type == "team" && video.destination == siteseerVotingInterface.city) {
				//console.info("Setting playhead = true",video.team,video.destination);
				video.playhead = "false";
			}
		});
	},

	setUser: function(json)
	{
		siteseerUser.username = json.username;
		siteseerUser.skymiles = (json.skymiles != null && json.skymiles != "") ? json.skymiles : null;
		siteseerUser.watched = json.watched;
		siteseerUser.voted = json.voted;
		siteseerUser.flagLogin = true;
		if(siteseerUser.watched.length > this.destination)
		{
			if(siteseerUser.watched[this.destination].length + this.destination == 6)
			{
				siteseerUser.flagWatched = true;
			}
		}
		//if(siteseerUser.voted.length > this.destination)
		//{
			if(siteseerUser.voted[this.destination] && siteseerUser.voted[this.destination].length > 0)
			{
				siteseerUser.flagVoted = true;
			}
		//}
		siteseerUser.flagSkyMiles = (siteseerUser.skymiles != null);
		// count miles earned
		if(siteseerUser.flagSkyMiles == true) {
			$.each(siteseerUser.voted, function(i,n) {
				if(i>0) {
					siteseerUser.miles += 250;
				}
			});
		}
	},

	resetUser: function()
	{
		siteseerUser.username = null;
		siteseerUser.skymiles = null;
		siteseerUser.miles = 0;
		siteseerUser.watched = new Array();
		siteseerUser.voted = new Array();
		siteseerUser.flagLogin = false;
		siteseerUser.flagWatched = false;
		siteseerUser.flagVoted = false;
		siteseerUser.flagSkyMiles = false;
		siteseerUser.formsLocked = false;
	},

	submitLogin: function()
	{
		if(siteseerVotingInterface.locked()) { return false; }

		if($("#votingLoginUsername").val() != "" && $("#votingLoginPassword").val() != "")
		{
			siteseerVotingInterface.lockForms();
			$("span#votingLoginError:visible").hide();
			$("label#label-username").removeClass("error");
			$("label#label-password").removeClass("error");
		
			$.getJSON("login.php",{username:$("#votingLoginUsername").val(),password:$("#votingLoginPassword").val(),randomizer:Math.round(Math.random()*100000000)},function(json) {
				if(json.success == 1)
				{
					$("#votingLoginUsername").val("");
					$("#votingLoginPassword").val("");
					siteseerVotingInterface.setUser(json);
					siteseerVotingInterface.updateWatched(json);
					siteseerVotingInterface.refreshWatched();
					siteseerVotingInterface.refresh();
					trackMe("engagement");
				} 
				else 
				{
					$("span#votingLoginError").show();
					$("label#label-username").addClass("error");
					$("label#label-password").addClass("error");
				}
				siteseerVotingInterface.unlockForms();
			});
		}
		else
		{
			$("span#votingLoginError").show();
			$("label#label-username").addClass("error");
			$("label#label-password").addClass("error");
		}
	},

	submitLogout: function()
	{
		if(siteseerVotingInterface.locked()) { return false; }
		siteseerVotingInterface.lockForms();

		var player = siteseerVideoInterface.getPlayer();
		if(player && player.tellFlashStopVideo != null && typeof(player.tellFlashStopVideo) != "undefined") { player.tellFlashStopVideo(); }
		$.post("logout.php",{randomizer:Math.round(Math.random()*100000000)},function(json) {
			//clearInterval(cookieCheck);
			siteseerVotingInterface.resetUser();
			siteseerVotingInterface.resetWatched();
			siteseerVotingInterface.refreshWatched();
			siteseerVotingInterface.refresh();
			siteseerVotingInterface.unlockForms();
		});
		
		
	},

	submitVote: function()
	{
		if(siteseerVotingInterface.locked()) { return false; }
		
		var team = 0;
		($("#votingVoteTeam1").attr("checked") == true) ? team = 1 : null;
		($("#votingVoteTeam3").attr("checked") == true) ? team = 3 : null;
		($("#votingVoteTeam4").attr("checked") == true) ? team = 4 : null;
		($("#votingVoteTeam5").attr("checked") == true) ? team = 5 : null;
		if(team != 0 && $("#votingVoteCitizen").attr("checked") == true)
		{
			siteseerVotingInterface.lockForms();
			$("#votingVoteError").hide();
			$.getJSON("api/setUserVote.php/destination/"+this.destination+"/team/"+team+"/?"+Math.round(Math.random()*100000000),{},function(json) {
				if(json.success == 1)
				{
					siteseerUser.flagVoted = true;
					siteseerUser.voted[siteseerVotingInterface.destination] = [team];
					//siteseerVotingInterface.init();
					if(siteseerUser.flagSkyMiles == true) {
						siteseerUser.miles += 250;
					}
					siteseerVotingInterface.refresh();
				}
				siteseerVotingInterface.unlockForms();
			});
		} else {
			if(team == 0)
			{
				$("#votingVoteError").text("Choose a team.");
			} else {
				$("#votingVoteError").text("US Residency Required.");
			}
			$("#votingVoteError").show();
		}
	},

	submitSkyMiles: function()
	{
		if(siteseerVotingInterface.locked()) { return false; }
		
		if($("#votingSkyMilesNumber").val().search(RegExp("^[0-9]{10}$","i")) != -1)
		{
			siteseerVotingInterface.lockForms();
			$("span#votingSkyMilesError").hide();
			$.getJSON("api/setUserSkyMiles.php/"+$("#votingSkyMilesNumber").val()+"/?"+Math.round(Math.random()*100000000),{},function(json) {
				if(json.success == 1)
				{
					siteseerUser.flagSkyMiles = true;
					siteseerUser.skymiles = $("#votingSkyMilesNumber").val();
					$("#votingSkyMilesNumber").val("");
					siteseerUser.miles = 0;
					//console.info(siteseerUser.voted);
					$.each(siteseerUser.voted, function(i,n) {
						if(i>0 && typeof(n) != "undefined") {
							//console.log(i,n)
							siteseerUser.miles += 250;
						}
					});
					siteseerVotingInterface.refresh();
				} 
				else 
				{
					$("span#votingSkyMilesError").show();
				}
				siteseerVotingInterface.unlockForms();
			});
		} else {
			$("span#votingSkyMilesError").show();
		}
		
	},

	skipSkyMiles: function()
	{
		siteseerUser.flagSkyMiles = true;
		siteseerVotingInterface.refresh();
	},
	
	setWatched: function(video)
	{
		if(siteseerUser.flagLogin && video != null && video.type == "team")
		{
			if(video.destination == siteseerVotingInterface.city)
			{
				video.playhead = "true";
				$.getJSON("api/setWatchedVideo.php/destination/"+siteseerVotingInterface.destination+"/team/"+video.team+"/?"+Math.round(Math.random()*100000000));
				if(!siteseerUser.watched[this.destination]) {
					siteseerUser.watched[this.destination] = new Array();
				}
				
				//siteseerUser.watched[this.destination].push(video.team.toString());
				//console.info("two arrays", siteseerUser.watched[this.destination],[video.team.toString()]);
				$.merge(siteseerUser.watched[this.destination],[video.team.toString()]);
				//console.info("watched videos", siteseerUser.watched);
				this.refreshWatched();
				this.refresh();
				
			}
		}
	},

	refreshWatched: function()
	{	
		$("img.check").attr("src","img/p1-chk-off.gif");
		
		if(siteseerUser.flagLogin && siteseerUser.watched[this.destination]) {
		//console.log(siteseerUser);
		//if(siteseerUser.watched[this.destination])
		//{
			var watched = siteseerUser.watched[this.destination];
			//console.log(watched);
			$.each(watched,function(i,n) {
				$("div#"+siteseerVotingInterface.city+"-team-"+n+" img.check").attr("src","img/p1-chk-on.gif");
			});
			$("#votingWatchedCurrent").text(watched.length.toString());
			$("img#votingWatchedProgress").attr("src","img/"+siteseerVotingInterface.city+"/p1-vtProg-"+watched.length+"-duba.gif");
			$("#votingWatchedCopy").show();
			if(watched.length + this.destination == 6)
			{
				siteseerUser.flagWatched = true;
				$("#votingWatchedCopy").hide();
			}
		} else {
			$("#votingWatchedCurrent").text("0");
			$("img#votingWatchedProgress").attr("src","img/"+siteseerVotingInterface.city+"/p1-vtProg-0-duba.gif");
			$("#votingWatchedCopy").show();
		}
	},

	refresh: function()
	{
		var user = siteseerUser;
		//$("#voteLock:visible").hide();
		//$("#voteLockContent:visible").hide();
		//$("#flashVideo").show();
		if(user.flagLogin)
		{
			$("#voteLock:visible").hide();
			$("#voteLockContent:visible").hide();
			$(".flashVideo").show();

			$("#loginProfileUsername").text(user.username);
			//$("#loginProfileMiles").text(user.miles.toString());
			$("#loginProfileProfile").attr("href","http://challenge.delta.com/people/"+user.username+"?view=profile");
			if($("#loginRegister:visible").length > 0) {
				$("#loginRegister:visible").animate({opacity:'hide'},'fast','easeout',function() {
					$("#loginProfile").animate({opacity:'show'},'fast','easein');
				});
			} else if($("#loginForm:visible").length > 0) {
				$("#loginForm:visible").animate({opacity:'hide'},'fast','easeout',function() {
					$("#loginProfile").animate({opacity:'show'},'fast','easein');
				});
			} else {
				$("#loginForm").hide();
				$("#loginProfile").show();
			}
			//$("#loginProfile").animate({opacity:'show'},'fast','easein');
			
		}
		else
		{
			// only do this if the voting tab is up
			if(siteseerTabs.active == this.voteTab) {
				$("#voteLock:hidden").show();
				$("#voteLockContent:hidden").show();
				$(".flashVideo").hide();
			}

			// only do the transition if it's displayed
			if($("#loginProfile:visible").length > 0) {
				$("#loginProfile:visible").animate({opacity:'hide'},'fast','easeout',function() {
					$("#loginForm").animate({opacity:'show'},'fast','easein');
				});
			} else {
				$("#loginForm").show()
			}
			
		}
		if(siteseerTabs.active == this.voteTab) {
		if(!user.flagLogin)
		{
			//this.transition("#votingLogin");
			this.transition("#votingWatched");
		} 
		else if(!user.flagWatched) 
		{
			this.transition("#votingWatched");
		} 
		else if(!user.flagVoted) 
		{
			this.transition("#votingVote");
		} 
		else if(!user.flagSkyMiles) 
		{
			this.transition("#votingSkyMiles");
		}
		else
		{	
			if(user.skymiles != null)
			{
				$("#votingThanksMiles").show();
			}
			else
			{
				$("#votingThanksMiles").hide();
			}
			this.transition("#votingThanks");
		}
		}
	},

	transition: function(module)
	{	
		var active = null;
		$(".voter").each(function(i) {
			if($(this).css("display") != "none")
			{
				active = $(this).attr('id');
			}
		});
		if(active != null)
		{
			$("#"+active).animate({opacity:'hide'},'slow','easeout',function() {
				$(module).animate({opacity:'show'},'slow','easein', function() {
					if(!$.browser.msie) {
						$(this).css("opacity","");	
					}	
				});
				
			});
			$("#"+active+'Title').animate({opacity:'hide'},'slow','easeout',function() {
				$(module+'Title').animate({opacity:'show'},'slow','easein', function() {
					if(!$.browser.msie) {
						$(this).css("opacity","");	
					}
				});
			});
		}
	},

	locked: function() 
	{
		return siteseerVotingInterface.islocked;
	},

	lockForms: function()
	{
		//console.info("Locking Forms");
		siteseerVotingInterface.islocked = true;
	},

	unlockForms: function()
	{
		//console.info("Unlocking Forms");	
		siteseerVotingInterface.islocked = false;
	}
}

var siteseerVideoInterface = {
	
	lastPlayed: null,

	playVideo: function(args)
	{
		var video = this.getVideo(args);
		//console.info(args,video);
		if(video != null)
		{
			var destination = (video.destination == "intro") ? null : video.destination;
			var hostid = (video.hostId == null) ? null : video.hostId;
			if(video.destination != siteseerVotingInterface.city) {
				var playhead = "true";
			} else {
				// if this video was already watched - let them fast forward
				var playhead = (typeof(video.playhead) == "undefined") ? "false" : video.playhead;
			}
				
			var autoplay = (args.autoplay == null) ? "true" : args.autoplay;
			var streamFile = "/siteseer/video/flv/"+video.flv;
			var player = this.getPlayer();
			//console.log(player);
			if(player != null && player.tellFlashNextVideo) {
				//console.info("getting next video");
				player.tellFlashNextVideo(autoplay,streamFile,video.caption,video.type,destination,hostid,playhead);
			} else {
				//console.info("loading the player");
				//console.info(autoplay,streamFile,video.caption,video.type,destination,hostid,playhead);
				this.loadPlayer(autoplay,streamFile,video.caption,video.type,destination,hostid,playhead);
			}
			this.lastPlayed = video;
			if(video.type == "team")
			{
				trackMe("/video/"+video.destination+"/team"+video.team+"/play");
				trackMe("engagement");
			}
		}
	},

	playVideoFromId: function(id)
	{
		var args = id.split("-");
		if(args[1] != "team")
		{
			this.playVideo({type:args[1],destination:args[0]});
		} else {
			this.playVideo({type:args[1],destination:args[0],team:args[2]});
		}
	},

	playVideoFromCarousel: function(el)
	{
		this.playVideoFromId(el.id);
	},

	playNextVideo: function() 
	{
		if(this.lastPlayed != null && this.lastPlayed.next != null)
		{
			this.playVideoFromId(this.lastPlayed.next);
		}
	},
	
	getVideo: function(args)
	{
		//console.info('looking for', args);
		for(var i=0; i < siteseerVideos.length; i++)
		{	//console.info('testing',siteseerVideos[i]);
			if(args.type == siteseerVideos[i].type)
			{ //console.info('found',args.type);
				if(args.destination == siteseerVideos[i].destination)
				{	//console.info('found',args.destination);
					if(args.type != "team")
					{
						return siteseerVideos[i];
					} else {
						if(args.team == siteseerVideos[i].team)
						{
							return siteseerVideos[i];
						}
					}
				}
			}
		}
		return null;
	},

	getPlayer: function()
	{
		//var isIE = navigator.appName.indexOf("Microsoft") != -1;
		//return player = (isIE) ? window["siteseerplayer"] : document["siteseerplayer"];
		return $("#siteseerplayer")[0];
	},

	loadPlayer: function(autoplay,streamFile,caption,type,destination,hostid,playhead)
	{
		var so = new SWFObject("siteseerplayer-20070912-4.swf", "siteseerplayer", "320", "292", "8", "#FFFFFF");
		so.addParam("allowScriptAccess", "sameDomain");
		so.addParam("allowFullScreen", "true");
		so.addParam("quality","high");
		so.addVariable("bufferSecs", "15");
		so.addVariable("streamPath", "rtmp://cp36627.edgefcs.net/ondemand");
		so.addVariable("streamFile", streamFile);
		so.addVariable("streamCaption", caption);
		so.addVariable("streamVideoType", type);
		so.addVariable("streamDestinationName", destination);
		so.addVariable("hostVideoId", hostid);
		so.addVariable("playheadAllowed", playhead);
		so.addVariable("autoplay", autoplay);
		if(!so.write("flashVideo"))
		{
			$(".flashVideo p").show();
		}
	}
}

// JS function called by the flash video player
function getNextVideoData() 
{
	siteseerVideoInterface.playNextVideo();
}

// JS function called by the flash video player
function curVideoPlayedCompletely()
{
	siteseerVotingInterface.setWatched(siteseerVideoInterface.lastPlayed);
	trackMe("/video/"+siteseerVideoInterface.lastPlayed.destination+"/team"+siteseerVideoInterface.lastPlayed.team+"/complete");
	trackMe("engagement");
}

var siteseerTabs = {
	
	active: null,
	first: true,
	
	onClick: function(el) 
	{
		// reset all tabs
		$("img.tab").each(function(i) {
			var src = $(this).attr("src").split("-");
			$("#"+src[src.length-2]).hide();
			$("#"+src[src.length-2]+"Footer").hide();
			$(this).attr("src",$(this).attr("src").replace(/-on\./i,"-off."));
			$(this).attr("src",$(this).attr("src").replace(/-over\./i,"-off."));
			$(this).addClass("off");
			$(this).bind("mouseover",function() {
				$(this).attr("src",$(this).attr("src").replace(/-off\./i,"-over."));
			});
			$(this).bind("mouseout",function() { 
				$(this).attr("src",$(this).attr("src").replace(/-over\./i,"-off."));
			});
			$(this).show();
		});

		// set active tab
		var src = $(el).attr("src").split("-");
		$("#"+src[src.length-2]).show();
		$("#"+src[src.length-2]+"Footer").show();
		this.active = src[src.length-2];
		$(el).attr("src",$(el).attr("src").replace(/-off\./i,"-on.")).removeClass("off").unbind("mouseover").unbind("mouseout");
		$(el).show();

		// on teams tab click
		if(el == "img#tabImgTeams" || el.id == "tabImgTeams")
		{
			this.hideVoting();
			
			siteseerVideoInterface.playVideo({type:"host",destination:"intro",autoplay:"false"});
			if(!this.first)
			{
				trackMe("/teams.htag");
			}
		}

		// on budapest tab click
		if(el == "img#tabImgBudapest" || el.id == "tabImgBudapest")
		{
			this.hideVoting();
			siteseerVideoInterface.playVideo({type:"host",destination:"budapest",autoplay:"false"});
			if(!this.first)
			{
				trackMe("/budapest.htag");
			}
		}

		// on buenos aires tab click
		if(el == "img#tabImgBuenosAires" || el.id == "tabImgBuenosAires")
		{
			//console.info("Buenos Aires Tab Accessed");
			this.hideVoting();
			siteseerVideoInterface.playVideo({type:"host",destination:"buenos_aires",autoplay:"false"});
			if(!this.first)
			{
				trackMe("/buenos_aires.htag");
			}
		}

		// on copenhagen tab click
		if(el == "img#tabImgCopenhagen" || el.id == "tabImgCopenhagen")
		{
			//console.info("Copenhagen Tab Accessed");
			this.hideVoting();
			siteseerVideoInterface.playVideo({type:"host",destination:"copenhagen",autoplay:"false"});
			if(!this.first)
			{
				trackMe("/copenhagen.htag");
			}
		}

		// on dubai tab click
		if(el == "img#tabImgDubai" || el.id == "tabImgDubai")
		{
			//console.info("Dubai Tab Accessed");
			this.hideVoting();
			siteseerVideoInterface.playVideo({type:"host",destination:"dubai",autoplay:"false"});
			if(!this.first)
			{
				trackMe("/dubai.htag");
			}
		}
			
		//siteseerCarousel.init(); // re-init the new carousel
		this.first = false;
	},

	hideVoting: function()
	{
		$("div#voteLock:visible").hide();
		$("div#voteLockContent:visible").hide();
		$(".flashVideo").show();
		$("div#votingModule:visible").hide();
		if($.browser.msie)
		{
			$("div.contentHomeTop").css("height","357px");
			$("div.contentHomeTop > div.container").css("height","337px");
			$("div#bgStampBottomLeft").css("bottom","0");
			$("div#bgStampBottomLeft").css("bottom","177px");
			$("div#bgStampBottomRight").css("bottom","0");
			$("div#bgStampBottomRight").css("bottom","100px");
		} else {
			$("div.contentHomeTop").css("height","354px");
			$("div.contentHomeTop > div.container").css("height","334px");
		}
	},

	showVoting: function()
	{
		// if we're not logged in, we need to show the vote lock
		if(!siteseerUser.flagLogin) {
			$("div#voteLock:hidden").show();
			$("div#voteLockContent:hidden").show();
			$(".flashVideo").hide();
		} else {
			$("div#voteLock:visibile").hide();
			$("div#voteLockContent:visibile").hide();
			$(".flashVideo").show();
		}
		$("div#votingModule").show();
		if($.browser.msie)
		{
			$("div.contentHomeTop").css("height","439px");
			$("div.contentHomeTop > div.container").css("height","419px");
			$("div#bgStampBottomLeft").css("bottom","0");
			$("div#bgStampBottomLeft").css("bottom","177px");
			$("div#bgStampBottomRight").css("bottom","0");
			$("div#bgStampBottomRight").css("bottom","100px");
		} else {
			$("div.contentHomeTop").css("height","439px");
			$("div.contentHomeTop > div.container").css("height","419px");
		}
	}
}

var siteseerCarousel = {
	
	animators: new Array(),
	carousel: null,

	init: function() 
	{
		
		$(".carousel").each(function(j) {
			//console.log(this); 
			siteseerCarousel.carousel = this.id;
			//if(siteseerTabs.active != siteseerCarousel.carousel) {
				// let's only run the animation when we're in its tab
				//console.info("not stepping", carousel);
				//return false;
			//}

			$(this).attr("carousel",siteseerCarousel.carousel);
			siteseerCarousel.animators[siteseerCarousel.carousel] = {interval:50,tick:1,direction:null,last:1,animator:null,top:0,bottom:0};
			$("#"+siteseerCarousel.carousel+" div.item").each(function(i) {
				$(this).attr("carousel",siteseerCarousel.carousel);
				var csstop = {}
				csstop.position = "absolute";
				csstop.top = (i*58)+"px";
				$(this).css(csstop);
				$(this).bind("mouseover",function() {
					siteseerCarousel.stop(this);
					$(this).children("div").css({backgroundColor:"#d9e8f0"});
				});
				$(this).bind("mouseout",function() {
					//siteseerCarousel.start(this,0,1);
					$(this).children("div").css({backgroundColor:"#ecf4f8"});
				});
				$(this).bind("click",function() {siteseerVideoInterface.playVideoFromCarousel(this);});
			});
			$("#"+siteseerCarousel.carousel+" img.carouselUp").each(function(i) {
				$(this).attr("carousel",siteseerCarousel.carousel);
				$(this).bind("mouseover",function() {
					siteseerCarousel.start(this,1,7);
				});
				$(this).bind("mouseout",function() {
					//siteseerCarousel.start(this,1,1);
					siteseerCarousel.stop(this);
				});
			});
			$("#"+siteseerCarousel.carousel+" img.carouselDown").each(function(i) {
				$(this).attr("carousel",siteseerCarousel.carousel);
				$(this).bind("mouseover",function() {
					siteseerCarousel.start(this,2,7);
				});
				$(this).bind("mouseout",function() {
					//siteseerCarousel.start(this,2,1);
					siteseerCarousel.stop(this);
				});
			});
			// why are we starting all these right away????
			//siteseerCarousel.start(this,1,1);
		});
	},

	start: function(el,direction,tick)
	{
		this.stop(el);
		var carousel = $(el).attr("carousel");
		var animator = siteseerCarousel.animators[carousel];
		(direction == 0) ? direction = animator.last : direction = direction;
		animator.direction = animator.last = direction;
		animator.tick = tick;
		animator.stepper = window.setInterval(function() {siteseerCarousel.step(carousel);},animator.interval);
	},

	stop: function(el)
	{
		//console.log($(el));
		var carousel = $(el).attr("carousel");
		var animator = siteseerCarousel.animators[carousel];
		animator.direction = null;
		window.clearInterval(animator.stepper);
	},

	step: function(carousel)
	{
		if(siteseerTabs.active != carousel) {
			// let's only run the animation when we're in its tab
			//console.info("not stepping", carousel);
			return false;
		}
		var animator = siteseerCarousel.animators[carousel];
		if(animator.direction != null)
		{
			$("#"+carousel+" div.item").each(function(i) {
				var csstop = {}
				var currtop = $(this).css("top").substr(0,$(this).css("top").length-2);
				if(animator.direction == 1)
				{
					csstop.top = (parseInt(currtop)-parseInt(animator.tick))+"px";
				}
				if(animator.direction == 2)
				{
					csstop.top = (parseInt(currtop)+parseInt(animator.tick))+"px";
				}
				$(this).css(csstop);
			});
			siteseerCarousel.findStackEdges(carousel);
			var items = new Array();
			$("#"+carousel+" div.item").each(function(i) {
				items.push(this);
			});
			items.sort(siteseerCarousel.sortByTop);
			if(animator.direction == 2)
			{
				items.reverse();
			}
			$.each(items,function(i) {
				var csstop = {}
				var currtop = $(this).css("top").substr(0,$(this).css("top").length-2);
				if(animator.direction == 1 && currtop < -58)
				{
					csstop.top = (animator.bottom)+"px";
					$(this).css(csstop);
					siteseerCarousel.findStackEdges(carousel);
				}
				if(animator.direction == 2 && currtop > 200)
				{
					csstop.top = (animator.top)+"px";
					$(this).css(csstop);
					siteseerCarousel.findStackEdges(carousel);
				}
				$(this).css(csstop);
			});
		}
		//console.info("carousel items",items);
	},

	sortByTop: function(a,b)
	{
		var a = parseInt($(a).css("top").substr(0,$(a).css("top").length-2));
		var b = parseInt($(b).css("top").substr(0,$(b).css("top").length-2));
		if(a < b) {
			return -1;
		} else if(a > b) {
			return 1;
		}
		return 0;
	},

	findStackEdges: function(carousel)
	{
		var animator = siteseerCarousel.animators[carousel];
		animator.bottom = animator.top = 0;

		$("#"+carousel+" div.item").each(function(i) {
			var currtop = $(this).css("top").substr(0,$(this).css("top").length-2);
			if(parseInt(currtop)-58 < animator.top)
			{
				animator.top = parseInt(currtop)-58;
			}
			if(parseInt(currtop)+58 > animator.bottom) {
				animator.bottom = parseInt(currtop)+58;
			}
		});
	}
}

var siteseerShare = {
	
	locked: false,
	htmlErrorIcon: '<img src="img/p1-arrow-RedError.gif" class="errorIcon" style="width:19px;height:13px;margin-right:5px;position:relative;top:3px;" alt="" /> ',

	onClick: function(el)
	{
		this.open(el);
	},

	submit: function(el)
	{
		if(!this.locked)
		{
			if(this.validate())
			{	
				this.lock();
				var shareParams = {};
				shareParams.senderName = $("#senderName").get(0).value;
				shareParams.senderEmail = $("#senderEmail").get(0).value;
				shareParams.sendeeName = $("#sendeeName").get(0).value;
				shareParams.sendeeEmail = $("#sendeeEmail").get(0).value;
				shareParams.message = $("#message").get(0).value;
				trackMe("/share_this_site/submit.htag");
				trackMe("engagement");
				$.getJSON("../php/share.php",shareParams,function(json) {
					siteseerShare.completed(json);
				});
			}
		}
	},

	validate: function()
	{	
		var valid = true;
		var focus = null;
		var vRuleName = new RegExp("^[ A-Z-]{2,}$","i");
		var vRuleEmail = new RegExp("^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$");
		if($("#sendeeEmail").get(0).value.search(vRuleEmail) == -1)
		{
			this.showError("#sendeeEmailLabel");
			focus = $("#sendeeEmail").get(0);
			valid = false;
		} else {
			this.hideError("#sendeeEmailLabel");
		}
		if($("#sendeeName").get(0).value.search(vRuleName) == -1)
		{
			this.showError("#sendeeNameLabel");
			focus = $("#sendeeName").get(0);
			valid = false;
		} else {
			this.hideError("#sendeeNameLabel");
		}
		if($("#senderEmail").get(0).value.search(vRuleEmail) == -1)
		{
			this.showError("#senderEmailLabel");
			focus = $("#senderEmail").get(0);
			valid = false;
		} else {
			this.hideError("#senderEmailLabel");
		}
		if($("#senderName").get(0).value.search(vRuleName) == -1)
		{
			this.showError("#senderNameLabel");
			focus = $("#senderName").get(0);
			valid = false;
		} else {
			this.hideError("#senderNameLabel");
		}
		if(!valid)
		{
			this.showMessage("#shareError");
			if(focus != null)
			{
				focus.focus();
			}
		} else {
			this.showMessage(null);
		}
		this.open($("img.share"));
		return valid;
	},

	completed: function(response)
	{
		if(response.success == true)
		{
			$("#shareForm").hide();
			$("#shareConfirm").show();
			this.open($("img.share"));
		} else {
			this.showMessage("#shareServer");
		}
		$("#senderName").get(0).value = "";
		$("#senderEmail").get(0).value = "";
		$("#sendeeName").get(0).value = "";
		$("#sendeeEmail").get(0).value = "";
		this.unlock();
	},

	lock: function()
	{
		$("#senderName").get(0).disabled = "disabled";
		$("#senderEmail").get(0).disabled = "disabled";
		$("#sendeeName").get(0).disabled = "disabled";
		$("#sendeeEmail").get(0).disabled = "disabled";
		$("#message").get(0).disabled = "disabled";
		this.locked = true;
	},

	unlock: function()
	{
		$("#senderName").get(0).disabled = "";
		$("#senderEmail").get(0).disabled = "";
		$("#sendeeName").get(0).disabled = "";
		$("#sendeeEmail").get(0).disabled = "";
		$("#message").get(0).disabled = "";
		this.locked = false;
	},
	
	showMessage: function(message)
	{
		$(".shareMessaging").hide();
		if(message != null)
		{
			$(message).show();
		}
	},
	
	showError: function(label)
	{
		$(label+" > img").remove();
		$(label).prepend(this.htmlErrorIcon);
		$(label).get(0).style.color = "#c03";
	},

	hideError: function(label)
	{
		$(label+" > img").remove();
		$(label).get(0).style.color = "#333";
	},

	open: function(el)
	{
		$("div#compShare").css({"left":$(el).offset().left+$(el).width() - $("div#compShare").outerWidth()+"px","top":$(el).offset().top - $("div#compShare").outerHeight() - 3 +"px"});
        $("div#compShare").css({"visibility":"visible"});
	},
	
	close: function()
	{
		$("#shareForm").show();
		$("#shareConfirm").hide();
		$("#compShare").css({"visibility":"hidden"});
	},

	reset: function()
	{
		$("#shareForm").show();
		$("#shareConfirm").hide();
		this.open($("img.share"));
	},

	charCount: function()
	{	
		var max = 500;
		var r = 500 - $("#message").get(0).value.length;
		if(r >= 0)
		{
			$("#charMessaging").get(0).innerHTML = r+" characters remaining.";
		} else {
			$("#charMessaging").get(0).innerHTML = "Some information will be lost, please revise your entry.";
		}
	}
}

function trackMe(action)
{	
	var trackBase = "http://www.delta.com/tracking/htmltag.gif?Log=1&rand="+Math.round(Math.random()*100000000)+"&DL_U_S=/marketing/siteseer_challenge";
	var doubleClickTag = "http://ad.doubleclick.net/activity;src=383639;type=delta767;cat=sscha471;ord="+Math.round(Math.random()*100000000);
	if(action == "load")
	{	
		if(location.pathname == null || location.pathname == "" || location.pathname == "/")
		{
			$("#trackingPixelVS").get(0).src = trackBase+"/index.php";
		} else {
			$("#trackingPixelVS").get(0).src = trackBase+location.pathname;
		}
	} 
	if(action == "engagement")
	{
		$("#trackingPixelDC").get(0).src = doubleClickTag;
	}
	if(action != "load" && action != "engagement")
	{
		$("#trackingPixelVS").get(0).src = trackBase+action;
	}
}

function gotoAnchorLink(index)
{
	if(index != null && index != "")
	{
		var locationString = document.location.href;
		var locationArray = locationString.toString().split('#');
		document.location.href = locationArray[0] + "#" + index;
	}
}

function ajaxError(request,settings,exception)
{
	console.error("AJAX Errors");
	console.error(request);
	console.error(settings);
	console.error(exception);
}

//window.onload = function() {
$(function() {
	
	// we should see if they are accepting cookies
	createCookie("test","forCookies");
	if(readCookie("test") == null) {
		//console.error("COOKIES NOT ENABLED");
		if(window.location.href.indexOf("sub-requirements.php") < 0) {
			window.location = "sub-requirements.php?e=c"; 
		}
	} else {
		//console.info("COOKIES ENABLED");
	}

	$.ajaxSetup({
		error: ajaxError,
		type:"POST"
	});

	// navigation rollovers
	$("img.rollover").each(function(i) {
        $(this).bind("mouseover",function() {
			$(this).attr("src",$(this).attr("src").replace(/-off\./i,"-over."));
		});
        $(this).bind("mouseout",function() { 
			$(this).attr("src",$(this).attr("src").replace(/-over\./i,"-off."));
		});
    });

	// content tabs
	$("img.tab").each(function(i) {
		$(this).bind("click",function() {
			siteseerTabs.onClick(this);
		});
	});
	
	// video player/tab initialization
	if(typeof($("#flashVideo").get(0)) != "undefined") { 
		if($("#flashVideo").get(0).id) {
			siteseerTabs.onClick('img#tabImgDubai');
		}
	}
	//siteseerTabs.onClick('img#tabImgCopenhagen');
	
	$("a.launchCopenhagenTab").bind("click", function() {
		siteseerTabs.onClick('img#tabImgCopenhagen');
	});

	// expanding modules
	$("div.pageModulesSmall div.moduleJoin").each(function(i) {
		$(this).bind("click",function() {
			$("div.pageModules div.moduleNews:visible").hide();
			$("div.pageModules div.moduleJoin:hidden").show();
		});
	});

	$("div.pageModulesSmall div.moduleNews").each(function(i) {
		$(this).bind("click",function() {
			$("div.pageModules div.moduleJoin:visible").hide();
			$("div.pageModules div.moduleNews:hidden").show();
		});
	});
	
	$("img.moduleClose").each(function(i) {
		$(this).bind("click",function() {
			$("div.pageModules div.moduleJoin").hide();
			$("div.pageModules div.moduleNews").hide();
		});
	});

	// share this site
	$("img.share").each(function(i) {
		$(this).bind("click",function() {
			siteseerShare.onClick(this);
			trackMe("/share_this_site/click.htag");	
		});
	});

	$("#shareSubmit").bind("click",function() {
		siteseerShare.submit();
	});

	$("#shareClose").bind("click",function() {
		siteseerShare.close();
	});

	$("#shareDone").bind("click",function() {
		siteseerShare.close();
	});

	$("#shareSendAnother").bind("click",function() {
		siteseerShare.reset();
	});

	$("#message").bind("keyup",function() {
		siteseerShare.charCount();
	});
	
	//siteseerVotingInterface.init();
	// carousel initialization
	siteseerCarousel.init();

	// hijack the login form
	/*
	$("form#flogin").bind("submit", function() {
		siteseerVotingInterface.submitLogin();
		return false;
	});
	// make ie respect enter to submit the form - silly MicroSoft
	$('form#flogin input').keydown(function(e){
      if (e.keyCode == 13) {
          $(this).parents('form').submit();
          return false;
      }
  });
	*/	
	/*
	$("input.votingLoginSubmit").each(function() {
		$(this).bind("click",function(e) {
			siteseerVotingInterface.submitLogin();
		});	
	});
	*/

	$("img.votingVoteSubmit").bind("click",function() {
		siteseerVotingInterface.submitVote();
	});

	$("img.votingSkyMilesSubmit").bind("click",function() {
		siteseerVotingInterface.submitSkyMiles();
	});

	$("img.votingSkyMilesSkip").bind("click",function() {
		siteseerVotingInterface.skipSkyMiles();
	});

	$("a.loginProfileLogout").bind("click",function() {
		siteseerVotingInterface.submitLogout();
	});

	// tracking
	trackMe("load");
	
	$("a.trackPlanFlight").bind("click",function() {
		trackMe("/plan_flight.htag");
	});

	$("a.trackRegisterLink").bind("click",function() {
		trackMe("/register.htag");
		trackMe("engagement");
	});

	$("a.trackEngagement").bind("click",function() {
		trackMe("engagement");
	});

	/* skymiles logo in footer */
	// http://www.delta.com/tracking/htmltag.gif?Log=1&rand=72933458&DL_U_S=/marketing/siteseer_challenge/about_skymiles.htag
	$("a.trackSkyMiles").bind("click", function() {
		trackMe("/about_skymiles.htag");
	});
	
	/*
	$("a.showLogin").bind("click", function() {
		if($("#loginRegister:visible").length > 0) {
				$("#loginRegister:visible").animate({opacity:'hide'},'fast','easeout',function() {
					$("#loginForm").animate({opacity:'show'},'fast','easein');
				});
			} else {
				$("#loginRegister").hide();
				$("#loginForm").show();
			}
	});
	*/

	// hijack the scoop form
	$("form#scoopForm").bind("submit", function() {
		//siteseerVotingInterface.submitLogin();
		//return false;
		siteseerGetTheScoop.submit();
		return false;
	});
	// make ie respect enter to submit the form - silly MicroSoft
	$('form#scoopForm input').keydown(function(e){
      if (e.keyCode == 13) {
          $(this).parents('form').submit();
          return false;
      }
  });

});

var siteseerGetTheScoop = {

	submit: function() {
		
		var email = $('input#scoopEmailAddress').val();
		var emailRegex = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$","i");
		$('p.scoopMessaging').hide();
		if(!email.match(emailRegex)) {
			// we have an invalid email addy
			$('p#scoopError').show();
			$("#label-scoopEmail").addClass("error");
		} else {
			$.getJSON(
				'php/scoop.php',
				{ 'scoopEmailAddress':  email},
				siteseerGetTheScoop.results
			);
		}
		return false;
	},
	results: function(r) {
		if(r.success) {
			$("#label-scoopEmail").removeClass("error");
			$('input#scoopEmailAddress').val("");
			$('p#scoopConfirm').show();
		} else {
			$("#label-scoopEmail").addClass("error");
			$('p#scoopServer').show();
		}
	}

}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
