/* Budweiser.com Utils JavaScript file */

Footer = {
	footerStylesLoaded: false,
	linksRegex: /\/info\/links.aspx$/,
 	
	/**
	 * If this gets much more traction then what is already going on inside of rewrite links, it should be refactored to be more observer like.
	 */
	afterLoad: function() {
		Footer.show();
		Footer.hideLoader();
		Footer.rebindCloseButton();
		$("#info-content").scrollTop(0);
		BudOmniture.trackAjaxPageLoad();
	},

	show: function(e) {
		$(window).scrollTop(0);
		var container = $("#footer-content-container");
		container.fadeOut(0);

		Footer.showLightBoxMask();		
		
		container.fadeIn("fast", function(){
			LinkHandler.rewriteLinksExternal();
		});
	},

	showLightBoxMask: function() {
		var container = $("#footer-content-container");
		$('#prompt-mask').css('width', $(document).width()+'px');
		$('#prompt-mask').css('height', $(document).height()+'px');
		$(container).css('top', ($(window).height()/2)-($(container).height()/2)+'px');
		$(container).css('left', ($(window).width()/2)-($(container).width()/2)+'px');
		$('#prompt-mask').show();
		$('#prompt-mask').click(Footer.close);
		Cufon.replace('.font-set-1', {hover: true, fontFamily: 'TradeGotBolConTwe'});
		container.fadeIn("fast", function(){
			LinkHandler.rewriteLinksExternal();
		});
	},

	showLoader: function() {
		if ($("#footer-loader").length > 0) {
			$("#footer-loader").show();
		} else {
			$("body").append('<div id="footer-loader"></div>');
			$("#footer-loader").css('left', ($(window).width()/2)-($("#footer-loader").width()/2)+'px');
		}
	},

	hideLoader: function() {
		var f = $("#footer-loader");
		f.hide();
	},
	
	
	close: function(e){
		$("#footer-content-container").fadeOut("fast", function(){
			$('#prompt-mask').hide();

			if (!($.browser.msie && ($.browser.version < 7))) {
				window.location.hash="#";
			}
			
			return false;			
		});
		e.preventDefault();
		return false;
	},
		
	rebindCloseButton: function() {
		var close = $('#info-close-button');

		if (!($.browser.msie && ($.browser.version < 7))) {
			close.attr('href', '#');
		}
		
		close.click(Footer.close);
	},

	linksTabs: function(e) {
        $(".helpTitle,.goTop").remove();
        //Tabs Functionality
        $("#tabs").addClass("ui-tabs");
        $(".ui-tabs-nav li:eq(0)").addClass("ui-tabs-selected ui-state-active");
        $(".ui-tabs-nav li:gt(1)").addClass("ui-state-default");
        $("#tabs div:not(#anheuser-busch,.linksBusch)").css('display', 'none');
        $(".ui-tabs-nav li").click(function(event) {
			$(".ui-tabs-nav li").removeClass("ui-tabs-selected ui-state-active");
			$(this).addClass("ui-tabs-selected ui-state-active");
			$("#tabs div:not(.linksBusch)").css('display', 'none');
			var link = $(".ui-tabs-selected a:first").attr("href");
			link = link.substr(link.indexOf('#')); // fix IE7 
			$(link).css('display', 'block');
			event.preventDefault();
		});
	},

	footerLinkClicked: function (e) {
		DeepLinker.convertedDeepUrls = true; 
		if (!Footer.footerStylesLoaded) {
			$("head").append('<link rel="stylesheet" type="text/css" href="/css/info.css">');
			Footer.footerStylesLoaded = true;
		}
		var f = $("#footer-content-container");
		var afterLoad = Footer.afterLoad;
		
		if (Footer.linksRegex.exec(this.href)) {
			afterLoad = function() {
				Footer.linksTabs();
				Footer.afterLoad();
			};
		}
		Footer.showLoader();
		f.load(this.href+" #info-container", "", afterLoad);
		var loc = this.href.substr((window.location.protocol + "//" + window.location.host).length, this.href.length-5);

		if (!($.browser.msie && ($.browser.version < 7))) {
			window.location.hash = loc;
		}

		e.preventDefault();
		
		return false;
	}
};


LinkHandler = {
	rewriteLinksInternal: function() {
		var footerStylesLoaded = false;
		$('#footer-content-container').hide();
			
		$('#footer a.internal').bind('click', Footer.footerLinkClicked);
	},
	rewriteLinksExternal: function() {
		$('a.external').bind('click', function (e) {
			$(this).attr('target', '_blank');
		});
	},
	rewriteLinks: function() {
		LinkHandler.rewriteLinksInternal();
		LinkHandler.rewriteLinksExternal();
	}
}

BudSpotlight = {
	spotClick: function(type, cat){
		var axel = Math.random() + "";
		var num = axel * 1000000000000000000;
		var tag_url = new Image();
		tag_url.src = 'http://ad.doubleclick.net/activity;src=1316334;type='+ type +';cat='+ cat +';ord=1;num='+num+'?';
	},
	spotClickFlash: function(url, type, cat){
		window.open(url);
		BudSpotlight.spotClick(type, cat);
	},
	initClicks: function(){
		$('.spot-nba').bind('click', function(){BudSpotlight.spotClick('budwe377', 'nbasw404')});
	}
}



BudOmniture = {
	ajaxInfo: false,

	/**
	 * Set up page parameters for an ajax page
	 */
	setAjaxPageInfo: function(pageName, channel) {
		var infoObj = { "pageName": pageName, "channel": channel };
		
		if (BudOmniture.ajaxInfo === false) {
			BudOmniture.ajaxInfo = infoObj;
		} else {
			throw { "exception": "Cannot set Ajax page tracking info, Information already set",
					"existing" : BudOmniture.ajaxInfo,
					"new"      : infoObj };
		}
	},
	
	/**
	 * Function to Track ajax pageload if applicable.
	 */
	trackAjaxPageLoad: function() {
		BudOmniture.injectOmnitureData();
		
		if (BudOmniture.ajaxInfo) {
			BudOmniture.trackPageLoad(BudOmniture.ajaxInfo.pageName, BudOmniture.ajaxInfo.channel);
			BudOmniture.ajaxInfo = false;
		} else {
				//throw "Cannot Track AJAX page load, BudOmniture.ajaxInfo variable not set!";
		}
	},

	/**
	 * Because jQuery strips all script tags in incoming html ajax data, we need to html serialize our data.
	 */
	injectOmnitureData: function() {
		var pageName = $("#omniture-data #pageName");
		var channel = $("#omniture-data #channel");

		if ((1 == pageName.length) && (1 == channel.length)) {
			BudOmniture.setAjaxPageInfo(pageName[0].innerHTML, channel[0].innerHTML);
		}
	},		

	trackPageLoad: function (page, channel) {
		s.pageName=page;
		s.channel=channel;
		s.pageType="";
		s.prop1="";
		s.prop2="";
		s.prop3="";
		s.prop4="";
		s.prop5="";
		s.campaign="";
		s.state="";
		s.zip="";
		s.events="";
		s.products="";
		s.purchaseID="";
		s.eVar1="";
		s.eVar2="";
		s.eVar3="";
		s.eVar4="";
		s.eVar5="";
		void(s.t()); // re-track omniture with the new page and channel.
	},

	trackPageLoadWithVars: function(page, channel, newS) {
		// first initialize the omniture s object 
		s.pageName=page;
		s.channel=channel;
		s.pageType="";
		s.prop1="";
		s.prop2="";
		s.prop3="";
		s.prop4="";
		s.prop5="";
		s.campaign="";
		s.state="";
		s.zip="";
		s.events="";
		s.products="";
		s.purchaseID="";
		s.eVar1="";
		s.eVar2="";
		s.eVar3="";
		s.eVar4="";
		s.eVar5="";

		// then merge the passed in s object with it
		for(element in newS) {
			s[element] = newS[element];
		}
		
		void(s.t()); // re-track omniture with the new page and channel.

	},
	
	trackVideo: function(file, action, currentTime, duration) {
		BudOmniture.trackPageLoadWithVars(file, "video", {"eVar1": action, "eVar2": currentTime, "eVar3": duration});
	},

	trackAudio: function(file, action) {
		BudOmniture.trackPageLoadWithVars(file, "ringtone", {eVar1: action});
	},
		
	trackAddThisClickItem: function(e) {
		var sharitIconClicked = $(this).attr('class').match(/at15t_[a-zA-Z_0-9-]+/);
		BudOmniture.trackPageLoad(sharitIconClicked, "share");
	},
	
	trackShareIt: function() {
		var hover = function() { BudOmniture.trackPageLoad("hoverShare","share") };
		var click = function() { BudOmniture.trackPageLoad("clickedShare","share") };
		$('#page-addthis').hover(hover);
		$('#page.addthis').click(click);

		$('#page.addthis').click(BudOmniture.injectShareTracking);
		$('#page-addthis').hover(BudOmniture.injectShareTracking);
	},

	/**
	 * Inject omniture tracking into share it
	 * This is kinda silly, because it depends on a timeout, but it works.
	 */
	injectShareTracking: function() {
		setTimeout(function() {
			$('.at15t').each(function (element) {
				$(this).click(BudOmniture.trackAddThisClickItem);
			});
		}, 500);
	}

};

/**
 * External Interface for flash tracking
 * Just an alias to trackPageLoad for now.
 */
BudOmniture.trackFlash = BudOmniture.trackPageLoad;


QualitySwitcher = {
	upgrade: function() {
		 $('.high-quality').each(function(i) {
		 	 var that = $(this);
			 var oldImage = $(this).css("background-image");
		 	 var imageNewUrl = $(this).css("background-image").replace(/-low\./,'-high.');
		 	 var imageNew = '<img src='+imageNewUrl.replace(/^url|[\(\)]/g, '').replace('http://'+window.location.hostname, '')+' />';

			 var loadFunction = function(){
				 // check to make sure we are not loading a different image into the background.
				 // this condition happens in the clydesdales page.
				 if (that.css("background-image") == oldImage) {
					 that.css("background-image", imageNewUrl);
				 } 
			 };
			 
			 $(imageNew).load(loadFunction);
		});
		
	}
};

Flash = {
	minVersion: "10",

	/**
	 * Determine whether or not we have a working flash.
	 */
	isWorking: function() {
		return (swfobject && (swfobject.hasFlashPlayerVersion) && (swfobject.hasFlashPlayerVersion(Flash.minVersion)));
	},

	/**
	 * Determine whether or not we want to nag the user to upgrade flash.
	 * If the user doens't have ANY flash installed, don't nag them. If they have less then the minimum, then nag them.
	 */
	showNag: function() {
		
		return( swfobject && swfobject.getFlashPlayerVersion && (swfobject.getFlashPlayerVersion().major > 0) && (!swfobject.hasFlashPlayerVersion(Flash.minVersion))); 
	},
	
	upgradeFlashCheck: function() {
		if(Flash.showNag()) {
			if (Cookie.get('budFlashCheck')!=1) {
				$('#prompt-mask').css('width', $(document).width()+'px');
				$('#prompt-mask').css('height', $(document).height()+'px');
				$('#prompt').css('top', ($(window).height()/2)-($('#prompt').height()/2)+'px');
				$('#prompt').css('left', ($(window).width()/2)-($('#prompt').width()/2)+'px');
				$('#prompt-mask').show();
				$('#prompt').fadeIn('slow');
				$("#prompt li.no").bind('click', function(){
					Cookie.set('budFlashCheck', 1, 30);
					$('#prompt').fadeOut('fast', function(){
						$('#prompt-mask').hide();
					});
				});
			}
		}	
	},
	
	hideShowIfFlashEnabled: function(hideSelector, showSelector) {
		if (Flash.isWorking()) {
			if (hideSelector) {
				$(hideSelector).css("display", "none");
			}
			if (showSelector) {				
				$(showSelector).css("display", "block");
			}
		} else {
			if (hideSelector) {
				$(hideSelector).css("display", "block");
			}
			if (showSelector) {				
				$(showSelector).css("display", "none");
			}
		}
	},

	/**
	 * SRSLY.  For whatever reason, IE 6 and 7 is exhibiting some kind of peekaboo behavior.
	 * give the flash feature object (if availbale) some kind of layout, and everything is fine.
	 */
	fixPeekaboo: function() {
		if ($.browser.msie) {			
			var parentHeight = $('#content-container').height();

			$('#feature-flash-container').height(parentHeight);
		}
	},

	/**
	 * IE 6 isn't properly resizing the flash movies.  Probably related to the previous bug.
	 */
	fixResizing: function() {
		$('#feature-flash-container').height($('#content-container').height());
		$('#feature-flash-container').width($('#content-container').width());
	}
}

AddthisCustomize = {
	DELAY_TIME: 1000,
	disclaimerHoverStyle: null,
	showViewState: false,
	addthisEventsInitialized: false,
	
	init: function() {
			/*
		$("#page-addthis").mouseenter(AddthisCustomize.delay(AddthisCustomize.mouseOver));
		$("#page-addthis").mouseleave(AddthisCustomize.mouseOut);
			*/
		$("#page-addthis").mouseenter(AddthisCustomize.bindEventsToAddThis);
		AddthisCustomize.addEventsToElement("#page-addthis");
		AddthisCustomize.addEventsToElement("#addthis-disclaimer");
				
		AddthisCustomize.disclaimerHoverStyle = {
			right: $("#addthis-disclaimer").css("right"), 
			top: $("addthis-disclaimer").css("top")
		}
	},
	bindEventsToAddThis: function(e) {
		// A set timeout is used to make sure the events get attached properly
		// because the addthis component might not exist on the page yet.
		setTimeout(function() {  
			AddthisCustomize.addEventsToElement("#at15s");
		}, 500); 
		
		$("#page-addthis").unbind("mouseenter", AddthisCustomize.bindEventsToAddThis);
	},
	addEventsToElement: function(el) {
		$(el).mouseenter(AddthisCustomize.mouseOver);
		$(el).mouseleave(AddthisCustomize.mouseOut);
	},
	
	mouseOver: function(e) {
		AddthisCustomize.showViewState = true;
		$("#addthis-disclaimer").show("slow");
	},
	mouseOut: function(e) {
		AddthisCustomize.showViewState = false;
		setTimeout(function() {
			if (!AddthisCustomize.showViewState) {
				$("#addthis-disclaimer").hide("slow");
			}}, AddthisCustomize.DELAY_TIME); // for setTimeout		   
	},
	click: function(e) {
		$("#ddthis-disclaimer").show("slow");
	},
	delay: function(f) {
		return function(e) {
			setTimeout(function() { f(e)}, AddthisCustomize.DELAY_TIME);
		}
	}
}

	//$(AddthisCustomize.init);  //temporarily deactivated.

ActiveHash = {
	INTERVAL_TIME: 500,
	timer: false,
	listeners: [],
	
	init: function() {
		if (false === ActiveHash.timer) {
			ActiveHash.timer = setInterval(ActiveHash.checkHash, ActiveHash.INTERVAL_TIME);
		} else {
			clearInterval(ActiveHash.timer);
			ActiveHash.timer = setInterval(ActiveHash.checkHash, ActiveHash.INTERVAL_TIME);
		}
			
	},
	
	checkHash: (function() {
		var lastHash = window.location.hash;

		return function() {
			if (window.location.hash !== lastHash) {
				ActiveHash.callChangeListeners();
				lastHash = window.location.hash;
			}
		}
	})(),

	addChangeListener: function(listener) {
		if (typeof listener === "function") {
			ActiveHash.listeners.push(listener)
		} else {
			throw "ActiveHash.addChagneListener can only accept functions as a listener!";
		}
	},
	
	callChangeListeners: function() {
		for (var i = 0; i < ActiveHash.listeners.length; i++) {
			ActiveHash.listeners[i]();
		}
	}
	
}


$(ActiveHash.init);
$(function() {
	ActiveHash.addChangeListener(
		function() {
			$('#page-addthis').remove();
			$('#addthis-container').html('<a class="addthis" id="page-addthis" href="#"><img src="/media/images/transparent.gif"></a>');
			addthis.button('#page-addthis', {}, {url: DeepLinker.parseFullUrl(window.location.hash), title: "Budweiser" });
			BudOmniture.trackShareIt();
		}
	);
});


$(window).load(function() {
	$('.vertical-center').each(function() {
		var parent = $("#content-container");
		var height = $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
		var centerPoint = (parent.height() / 2) - (height /2);
		$(this).css('margin-top', centerPoint);
	});
	BudSpotlight.initClicks();
	
});