$(document).ready(function() {
	
    // sets doubleclick tracker images to display none
    $("#page img[src^=http://ad.uk.doubleclick.net]").css('display', 'none');
    
	if ($("#menu").length) {
	
		var navigationTimeout = null
			logoTop = null,
			menuImageWidth = 182,
			menuItemsToShow = 5;
		
		// setup
		
		$("#menu").before('<div id="navigation"></div>');
		$("#navigation")		
			.append('<div id="left" class="arrow"></div>')
			.append('<div id="scroller"></div>')
			.append('<div id="right" class="arrow"></div>')
			.after('<div id="intro"></div>');
		$("#scroller").append($("#menu"));
	
		var numberOfMenuItems = $("#menu li").length;
		if (numberOfMenuItems <= menuItemsToShow) {
			$("#left, #right").hide();
			$("#scroller").css({
				paddingLeft: (9 + ((menuImageWidth / 2) * (menuItemsToShow - numberOfMenuItems))) + "px",
				width: (menuImageWidth * numberOfMenuItems) + "px"
			});
		} else {
			$("#scroller").css({
				width: (menuImageWidth * menuItemsToShow) + "px"
			});
		}
		
		$("#menu").css({
			overflow: "hidden",
			width: menuImageWidth * numberOfMenuItems,
			float: "left",
			display: "block"
		});
		
		
		// helpers
		
		var seenIntro = function () {
			document.cookie = "navigationshown=true; path=/";
		};
		
		var alreadySeenIntro = function () {
			return document.cookie.search(/navigationshown=true/) >= 0;
		};
		
		var activateArrows = function () {
			if ($("#scroller").length) {
				$("#left, #right").removeClass("inactive");
				if ($("#scroller")[0].scrollLeft <= 0) {
					$("#left").addClass("inactive");
				}
				if ($("#scroller")[0].scrollLeft >= menuImageWidth * (numberOfMenuItems - menuItemsToShow)) {
					$("#right").addClass("inactive");
				}
			}
		};
		activateArrows();
		
		// initial position
		
		$("#header").css({
			height: 92
		});
		$("#logo").css({
			clear: "left",
			marginLeft: 415
		}).show();
		$("#navigation").css({
			position: "absolute"
		}).hide();
		$("#intro").css({
			position: "absolute",
			top: "66px"
		});
		
		var positionNav = function() {
			// position menu over active item
			$("#menu li").each(function (index, li) {
				if ($(li).hasClass("active")) {
					$("#scroller").scrollLeft(menuImageWidth * (index - 2));
				}
			});
			positionNav = function() {};
		};
		
		// animate
		
		if (!alreadySeenIntro()) { // do intro animation
			var so = new SWFObject("/en-row/img/250/nav-intro.swf", "intro-rollower-movie", "216", "25", "9", "#000000");
			so.addParam("scale", "noscale");
			so.addParam("salign", "tl");
			so.addParam("wmode", "transparent");
			so.write("intro");
			$("#intro").css("display", "block");
			seenIntro();
		} else { // show static dude
			$("#intro").show();
		}
		
		$("#header").hover(function() { // show/hide on hover
			if (!logoTop) logoTop = $("#logo").position().top;
			$("#intro embed, #intro object").hide();
			$("#logo, #intro").fadeOut();
			$("#navigation")
				.css("top", logoTop + 10 + "px")
				.fadeIn("normal", activateArrows);
			window.clearTimeout(navigationTimeout);
			GUINNESS.track("conversionStart", "Navigation on", "On");
			positionNav();
		}, function() {
			navigationTimeout = window.setTimeout(function() {
				$("#navigation").fadeOut();
				$("#logo, #intro").fadeIn();
			}, 500);
			GUINNESS.track("conversionEnd", "Navigation on", "On");
		});
		
		$("#right").click(function() {
			$("#scroller").animate({
				scrollLeft: "+=" + menuImageWidth
			}, 500, "swing", activateArrows);
			GUINNESS.track("manual", "Navigation", "Right");
		});
		$("#left").click(function() {
			$("#scroller").animate({
				scrollLeft: "-=" + menuImageWidth
			}, 500, "swing", activateArrows);
			GUINNESS.track("manual", "Navigation", "Left");
		});
		
		// search
		
		$("#search").click(function () {
			if ($("#search-form").length == 0) {
				$(this).after(
					'<form id="search-form" action="search.html" method="get">' +
						'<input type="text" name="keyword" id="search-box">' +
						'<input type="image" src="/en-row/img/250/trans.png" class="submit">' +
					'</form>'
				).hide();
			} else {
				$(this).hide();
				$("#search-form").show();
			}
			$("#search-box")
				.focus()
				.focus(function() {
					$(this).addClass("focus");
				}).blur(function () {
					$(this).removeClass("focus");
				});
			$("#search-box").blur(function () {
				if ($(this).val() == "") {
					$("#search-form").hide();
					$("#search").show();
				}
			});
			return false;
		});
		
		// webstore link magic
		$("#menu span:contains('Webstore')").parent().click(function () {
			var country = document.cookie.match(/gwCountry=([A-Z]+)/);
			if (country) {
				switch (country[1]) {
				case "AT":
				case "DK":
				case "DE":
				case "GR":
				case "IE":
				case "IT":
				case "NL":
				case "PT":
				case "ES":
				case "GB":
					document.location = "http://www.guinnesswebstore.co.uk/";
					return false;
				}
			}
		});
		
	}
	
});

if (!GUINNESS) var GUINNESS = {};

GUINNESS.log = function (msg) {
    if (typeof console == "object" && typeof console.log == "function") {
        console.log(msg);
    }
}
GUINNESS.trackQueue = [];

GUINNESS.track = function (type, name, data, data2, data3) {
	
    // var analytics_api_key = 'UA-11104783-1';
	var explodedPath = document.location.pathname.split("/");
    
    if ($("#page.gateway").length == 1 && name.substr(0, 8) != "/gateway") { // gateway overlay shown, do not throw other tracking
        GUINNESS.log("Delaying tracking due to gateway being active: " + name);
        GUINNESS.trackQueue.push({ type: type, name: name, data: data, data2: data2, data3: data3 });
        return;
    }
    
	if (document.location.pathname.indexOf('html/form') == 1) {
        
		var replacement_locale = '';
		
		switch(explodedPath[3]) {
			case 'SG': 
				replacement_locale = 'en-sg';
				break;
			case 'MY':
				replacement_locale = "en-my";
				break;
			case 'CA':
				replacement_locale = "en-ca";
				break;
			case 'CAFR':
				replacement_locale = "fr-ca";
				break;
			case 'GB':
				replacement_locale = "en-gb";
				break;
			case 'IE':
				replacement_locale = "en-ie";
				break;
			case 'US':
				replacement_locale = "en-us";
				break;
			case 'AU':
				replacement_locale = "en-au";
				break;
			case 'IT':
				replacement_locale = "it-it";
				break;
			case 'JP':
				replacement_locale = "ja-jp";
				break;
			case 'RU':
				replacement_locale = "ru-ru";
				break;
			case 'ID':
				replacement_locale = "en-id";
				break;
			case 'IDBH':
				replacement_locale = "bh-id";
				break;
		}
		
		// replacement local based on gateway code
		explodedPath[1] = replacement_locale;
	}
    
	if (explodedPath[1]) {
		var namePrefix = "Guinness_" + explodedPath[1].replace("-", "_") + "_";
	} else {
		var namePrefix = "Guinness_EN_ROW_";
	}
    
    if (typeof name != "undefined") {
        name = name.replace(/[`~!@#$%^&*()=+\[\]\\;\'\"<.>?]/g, "");
    }
    if (typeof data != "undefined") {
        data = data.replace(/[`~!@#$%^&*()=+\[\]\\;\'\"<.>?]/g, "");
    }
    
    GUINNESS.log("Tracking: " + type + ", " + name);
    
	switch (type) {
	case "page":
        // data = categoryId
        // data2 = search term
        // data3 = number of search results
        // TO DO: tracking for search results
        // this is likely included in the page tracking, need to test.
        try {
            // var pageTracker = _gat._getTracker(analytics_api_key);
            pageTracker._setDomainName(".guinness.com");
            pageTracker._setAllowHash(false);
            pageTracker._trackPageview(location.pathname);
        } catch (err) {}
		break;
    case "url":
        // new tracking type for just tracking a URL has been accessed, should probably be used going forward rather than "page"
        if (typeof name != "undefined") {
            url = name;
        } else {
            url = location.pathname;
        }
        try {
            pageTracker._setDomainName(".guinness.com");
            pageTracker._setAllowHash(false);
            pageTracker._trackPageview(url);
        } catch (err) {}
		break;
	case "manual":
        // data = actionName
        try {
            // var pageTracker = _gat._getTracker(analytics_api_key);
            // _trackEvent(category, action, optional_label, optional_value)
            pageTracker._setDomainName(".guinness.com");
            pageTracker._setAllowHash(false);
            pageTracker._trackEvent(namePrefix + name, data);
        } catch (err) {}
		break;
	case "conversionStart":
        // data = eventCategoryId
        try {
            // var pageTracker = _gat._getTracker(analytics_api_key);
            if (!data2) data2 = 1;
            // _trackEvent(category, action, optional_label, optional_value)
            pageTracker._setDomainName(".guinness.com");
            pageTracker._setAllowHash(false);
            pageTracker._trackEvent(namePrefix + name, namePrefix + data, 'start_' + data2);
        } catch (err) {}
		break;
	case "conversionEnd":
        // data = eventCategoryId
        // data2 = points
        try {
            // var pageTracker = _gat._getTracker(analytics_api_key);
            if (!data2) data2 = 1;
            pageTracker._setDomainName(".guinness.com");
            pageTracker._setAllowHash(false);
            pageTracker._trackEvent(namePrefix + name, namePrefix + data, 'end_' + data2);
        } catch (err) {}
		break;
	case "element":
        // data = categoryId
        // data2 = elementId
        try {
            // var pageTracker = _gat._getTracker(analytics_api_key);
            pageTracker._setDomainName(".guinness.com");
            pageTracker._setAllowHash(false);
            pageTracker._trackEvent(namePrefix + name, data.replace(/[ .\(\)]/g, "").substr(0, 60), data2);
        } catch (err) {}
		break;
	}
	//console.log(name);
};

GUINNESS.dialog = function () {
	
	var show = function (hash, title, content, classname) {
		
		var oldHash = document.location.hash;
		if (hash) {
			document.location.hash = "#" + hash;
		}
		
		$("div#overlay, div#dialog").remove();
		$("body")
			.append('<div id="overlay"></div>')
			.append('<div id="dialog"' + (classname ? ' class="' + classname + '"' : '') + '>' +
			'<h2>' + title + '</h2>' +
			'<div id="dialog-content">' + content + '</div>' +
		'</div>');
		$("div#overlay").css({
			top: $("div#content").position().top + "px",
			height: $("div#content").height() + "px"
		});
		
		$("#dialog h2").click(function () {
			$("#overlay, #dialog").remove();
			document.location.hash = oldHash;
		});
		
		positionDialog();
		
	};
	
	var positionDialog = function () {
		var contentDiv = $("#content");
		var top = contentDiv.offset().top + contentDiv.height() / 2 - $("#dialog").height() / 2 - 5;
		if (top < 50) top = 50;
		$("#dialog").css({
			top: top + "px"
		});
	};
	
	return {
		show: show,
		reposition: positionDialog
	};
	
}();

GUINNESS.share = function () {
	
	var show = function (filename, mediaType, title, trackingName) {
		
		if (!filename) filename = {};
		if (!mediaType) mediaType = "other";
		if (!title) title = "Share this";
		if (!trackingName) trackingName = "Unknown";
		
		var content = '<form action="">' +
			'<ul class="tabs">' +
				'<li id="share-tab-email" class="email current"><a id="share-select-email" href=""><span>Email</span></a></li>' +
				(mediaType == "picture" ? '<li id="share-tab-embed" class="download"><a id="share-select-embed" href=""><span>Download</span></a></li>' : "") +
				(mediaType == "video" ? '<li id="share-tab-embed" class="embed"><a id="share-select-embed" href=""><span>Embed</span></a></li>' : "") +
				'<li id="share-tab-link" class="link"><a id="share-select-link" href=""><span>Link</span></a></li>' +
			'</ul>' +
			'<div></div>' +
		'</form>';
		
		GUINNESS.dialog.show(null, "Share this", content, "share");
		
		$("#dialog ul.tabs a").click(function () {
			$("#dialog ul.tabs li").removeClass("current");
			$("#dialog ul.tabs li#" + $(this).parent().attr("id")).addClass("current");
			switch ($(this).attr("id")) {
			case "share-select-email":
				showEmail();
				break;
			case "share-select-embed":
				if (mediaType == "picture") {
					showDownload();
				} else {
					showEmbed();
				}
				break;
			case "share-select-link":
				showLink();
				break;
			}
			return false;
		});
		
		var showEmail = function () {
			GUINNESS.track("page", trackingName + " Email Share", trackingName + "_share");
			GUINNESS.track("conversionStart", trackingName + " Email Share", trackingName + "_share");
			$("div#dialog form div").empty().append(
				'<p class="name">' +
					'<label for="name">Your name</label>' +
					'<input type="text" class="text" name="name" id="name" maxlength="30">' +
				'</p>' +
				'<p class="email">' +
					'<label for="from">Your email address</label>' +
					'<input type="text" class="text" name="from" id="from" maxlength="100">' +
				'</p>' +
				'<p>' +
					'<label for="recipients">Your friends\' email addresses <span>(separate addresses with commas)</span></label>' +
					'<input type="text" class="text" name="recipients" id="recipients">' +
				'</p>' +
				'<p>' +
					'<label for="message">Your message <span>(150 max.)</span></label>' +
					'<textarea name="message" id="message" cols="45" rows="6">I found something great and thought you\'d like it.</textarea>' +
				'</p>' +
				'<p>' +
					'<label>' +
						'<input type="checkbox" name="age" id="age" class="checkbox">' +
						'I certify that all recipients are over the legal alcohol purchase age and consented to receipt of this email.' +
					'</label>' +
				'</p>' +
				'<p class="legal">' +
					'By clicking on the <strong>SEND NOW</strong> button, you agree to the <a href="terms-and-conditions.html" title="Terms &amp; Conditions">Terms &amp; Conditions</a> and <a href="privacy.html" title="Privacy Policy">Privacy Policy</a>.' +
				'</p>' +
				'<div id="buttons">' +
					'<div class="cancel"><span>Cancel</span></div>' +
					'<input src="/en-row/img/trans.png" type="image" class="send" alt="Send now">' +
				'</div>'
			);
			$("div#dialog form div.cancel").click(function () {
				$("#overlay, #dialog").remove();
				document.location.replace("#");
			});
			$("div#dialog form").submit(function () {
				var errors = false;
				$("div#dialog form input, div#dialog form textarea, div#dialog form label").removeClass("error");
				if ($("input#name").val() == "") {
					errors = true;
					$("input#name").addClass("error");
				}
				if ($("input#from").val() == "" || !$("input#from").val().match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]{2,}\.[a-zA-Z]{2,}$/)) {
					errors = true;
					$("input#from").addClass("error");
				}
				if ($("input#recipients").val() == "" || !$("input#recipients").val().match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]{2,}\.[a-zA-Z]{2,}( *, *[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]{2,}\.[a-zA-Z]{2,}){0,4}$/)) {
					errors = true;
					$("input#recipients").addClass("error");
				}
				if ($("textarea#message").val().length > 150) {
					errors = true;
					$("textarea#message").addClass("error");
				}
				if (!$("input#age")[0].checked) {
					errors = true;
					$("input#age").parent().addClass("error");
				}
				if (!errors) { // do mail send!
					try {
                        var url = "/share.html";
						var data = {
							FromEmailId: "noreply@guinness.com",
							ToEmailId: $("input#recipients").val(),
							Subject: "Take a look at this from Guinness.com",
							UserName: $("input#name").val(),
							UserEmailId: $("input#from").val(),
							Comments: $("textarea#message").val(),
							CurrPageUrl: document.location.pathname + document.location.hash
						};
						$.get(url, data);
						$("#dialog").addClass("detail");
						$("#dialog-content").empty().append(
							'<h4>E-mail sent - thanks for sharing.</h4>' +
							'<p>Remember, you can quickly and easily show your mates interesting discoveries from the site wherever you see the SHARE symbol.</p>' +
							'<div id="buttons"><input src="/en-row/img/trans.png" type="image" class="send-again"></div>'
						);
						GUINNESS.track("page", trackingName + " Email Share Success", trackingName + "_share");
						GUINNESS.track("conversionEnd", trackingName + " Email Share", trackingName + "_share");
					} catch (e) {
						$("#dialog").addClass("detail");
						$("#dialog-content").empty().append(
							'<h4>Sorry!</h4>' +
							'<p>There was a problem sending your message. Give it another try?</p>' +
							'<div id="buttons"><input src="/en-row/img/trans.png" type="image" class="send-again"></div>'
						);
						GUINNESS.track("page", trackingName + " Email Share Error", trackingName + "_share");
					}
					$("#dialog-content input.send-again").click(function () {
						GUINNESS.share.show(filename, mediaType, title, trackingName);
						return false;
					});
				}
				return false;
			});
		};
		
		var showDownload = function () {
			GUINNESS.track("page", trackingName + " Download Share", trackingName + "_share");
			$("div#dialog form div").empty().append(
				'<p>Please choose the size you would like to download:</p>' +
				'<ul class="downloads">' +
					'<li class="small"><a href="' + filename.small + '" target="_blank">Small</a></li>' +
					'<li class="medium"><a href="' + filename.medium + '" target="_blank">Medium</a></li>' +
					'<li class="large"><a href="' + filename.large + '" target="_blank">Large</a></li>' +
				'</ul>' +
				'<p class="legal">' +
					'By clicking on one of the download links, you agree to the <a href="terms-and-conditions.html" title="Terms &amp; Conditions">Terms &amp; Conditions</a> and <a href="privacy.html" title="Privacy Policy">Privacy Policy</a>.' +
				'</p>' +
				'<p class="legal">' +
					'This image download is for personal, non-commercial use only. It must not be distorted or manipulated so that the context, nature or situation of the subject is altered in any way. Additionally, pornographic, defamatory or otherwise unlawful usage is expressly forbidden.' +
				'</p>');
			$("div#dialog form ul.downloads a").click(function () {
				GUINNESS.track("manual", "Share Download", $(this).attr("href"));
				GUINNESS.track("conversionEnd", $(this).attr("href") + " Download Share", trackingName + "_share");
			});
		};
		
		var showEmbed = function () {
			GUINNESS.track("page", trackingName + " Embed Share", trackingName + "_share");
			$("div#dialog form div").empty().append(
				'<p>' +
					'<label for="embed-code">Copy this code to embed this in your blog</label>' +
					'<textarea id="embed-code" rows="10" cols="45" name="embed-code">' +
						'&lt;object width="528" height="396"&gt; &lt;param name="allowfullscreen" value="true"&gt;\n' +
							'\t&lt;param name="allowscriptaccess" value="samedomain"&gt;\n' +
							'\t&lt;param name="scale" value="noscale"&gt;\n' +
							'\t&lt;param name="salign" value="t1"&gt;\n' +
							'\t&lt;param name="basePath" value=""&gt;\n' +
							'\t&lt;param name="videoFileName" value="' + filename + '"&gt;\n' +
							'\t&lt;param name="movie" value="http://www.guinness.com/en-row/img/250/swf/videoplayer.swf"&gt;\n' +
							'\t&lt;embed src="http://www.guinness.com/en-row/img/250/swf/videoplayer.swf" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="samedomain" salign="t1" scale="noscale" basePath="" videoFileName="' + filename + '" width="528" height="396"&gt;&lt;/embed&gt;\n' +
						'&lt;/object&gt;' +
					'</textarea>' +
				'</p>' +
				'<p class="legal">' +
					'By embedding this item, you agree to the <a href="terms-and-conditions.html">Terms &amp; Conditions</a> and <a href="privacy.html">Privacy Policy</a> of this website.' +
				'</p>'
			);
		};
		
		var showLink = function () {
			GUINNESS.track("page", trackingName + " Link Share", trackingName + "_share");
			var url = document.location.protocol + "//" + document.location.host + document.location.pathname + document.location.hash;
			$("div#dialog form div").empty().append(
				'<p>' +
					'<label for="url">URL</label>' +
					'<input readonly="readonly" type="text" class="text" name="url" id="url" value="' + url + '">' +
				'</p>' +
				'<p class="label">Bookmark with this link</p>' +
				'<ul class="bookmarks clearfix">' +
			  		'<li class="delicious">' +
						'<a target="_blank" href="http://del.icio.us/post?url=' + encodeURIComponent(url) + '&title=' + encodeURIComponent(document.title) + '" title="Del.icio.us">Del.icio.us</a>' +
					'</li>' +
					'<li class="facebook">' +
						'<a target="_blank" href="http://www.facebook.com/sharer.php?u=' + encodeURIComponent(url) + '" title="Facebook">Facebook</a>' +
					'</li>' +
					'<li class="stumbleupon">' +
						'<a target="_blank" href="http://www.stumbleupon.com/submit?url=' + encodeURIComponent(url) + '" title="Stumbleupon">Stumbleupon</a>' +
					'</li>' +
					'<li class="myspace">' +
						'<a target="_blank" href="http://www.myspace.com/index.cfm?fuseaction=postto&t=' + encodeURIComponent(document.title) + '&u=' + encodeURIComponent(url) + '" title="MySpace">MySpace</a>' +
					'</li>' +
					'<li class="technorati">' +
						'<a target="_blank" href="http://technorati.com/faves?add=' + encodeURIComponent(url) + '" title="technorati.com">technorati.com</a>' +
					'</li>' +
				'</ul>' +
				'<p class="legal">' +
					'By embedding this item, you agree to the <a href="terms-and-conditions.html" title="Terms &amp; Conditions">Terms &amp; Conditions</a> and <a href="privacy.html" title="Privacy Policy">Privacy Policy</a>.' +
				'</p>'
			);
			$("div#dialog form div input").click(function () {
				$(this).select();
			});
			$("div#dialog form ul.bookmarks a").click(function () {
				GUINNESS.track("manual", "Share Link", $(this).attr("title"));
			});
		};
		
		$("#dialog h2").unbind().click(function () {
			GUINNESS.track("page", trackingName, trackingName);
			$("#overlay, #dialog").remove();
		});
		
		showEmail();
		
		return false;
	};
	
	return {
		show: show
	}
	
}();


try { /* IE6 flickering image fix */
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}
