﻿//v0.1 29 Sept 2010 (MRM london)

// if JavaScript is enabled, hide the 'no-script' list of links, and show the ajax-driven menu
// these two lines MUST be below the elements they reference in the DOM (towards the bottom of the page)
$(".no-script").hide();
$(".sections").hide();
var omniture_page_name;
var ie6 = false;
var ie7 = false;
var curTextDir = "";
var curTextDir = "";
var firstTime = true;
var default_country_name;
var default_country;
var DefaultLocale = 'en_US_01';
var redirectUrl = '';
var locale = null;
var country = null;
var backgroundImageList = new Array;
var backgroundInit = true;
var currentBackground = 0;

// namespace
if (typeof HAT === "undefined" || !HAT) {
    var HAT = {};
}

var GAAT40 = (typeof GAAT40 == "undefined" || !GAAT40) ? {} : GAAT40;
/*BEGIN Utility Functions */

function addMobileParam(url) {
    if (url.indexOf('?') > -1) {
        return url + '&r=f';
    }
}

function hasParameters(queryString) {
    return queryString.indexOf('?') > -1;
}

function getSynchronousHtml(requestUrl, successCallBack) {
    $.ajax({
        url: requestUrl,
        success: successCallBack,
        dataType: 'html',
        async: false
    });
}

function updateBackgroundImage() {
	if (backgroundImageList.length > 1) {

		// Fade the topmost background image so the bottom one shows
		if (!backgroundInit) {
			$("#ggw-background").css({opacity : 1});
			$("#ggw-background").animate({opacity : 0}, 1000);
		}

		// Set the top div to use the "current" background
		var previousBackground = (currentBackground == 0) ? backgroundImageList.length - 1 : currentBackground - 1;
		$("#ggw-background").removeClass('background' + previousBackground).addClass('background' + currentBackground);

		// Set the bottom div to use the "next" background
		var nextBackground = (currentBackground == (backgroundImageList.length - 1)) ? 0 : currentBackground + 1;
		$("#ggw").removeClass('background' + currentBackground).addClass('background' + nextBackground);

		// Increment the current background
		if (!backgroundInit) {
			currentBackground = nextBackground;
		}

		// Start the process again
		backgroundInit = false;
		setTimeout(updateBackgroundImage, 5000);
	} else {
		$("#ggw").addClass('background' + currentBackground);
	}
}

function parseCountryXML(xml) {
    var $xml = $(xml);
    var optionHtml = '<option value="" id="optionDis">' + $xml.find("locationtext").text() + '</option>';

    $('#optionDis').remove();
    $(optionHtml).attr('disabled', 'disabled').prependTo('#country-selector');

    function localize(selector, textnode, linknode) {
        $(selector).html($.trim($xml.find(textnode).text()) || "&nbsp;"); // insert a hard space even if item is empty, to preserve HTML layout
        if (linknode) { $(selector).attr('href', $xml.find(linknode).text()); }
    }

    // Update background image
    if ($xml.find("herobackground").text().length > 1) {
		backgroundImageList = $xml.find("herobackground").text().split(",");

		var bgClassList = '';
		$.each(backgroundImageList, function (i, path) {
			bgClassList += '.background' + i + ' { background-image: url(' + path + ') !important; }\n';
		});
		var backgroundClasses = $('<style type="text/css">'+ bgClassList +'</style>');
		$('head').append(backgroundClasses);

		// Preload background images
		$('<div class="no-print" style="display:none;position:absolute;left:-9999px;top:-9999px;height:0;width:0;overflow:hidden;"/>').appendTo('body').html('<img src="'+backgroundImageList.join('"/><img src="')+'"/>');

		updateBackgroundImage();
    }

	if ($xml.find("heroextra").text().length > 1) {
		$(".heroextra").html($xml.find("heroextra").text());
	}

    var $heroCtaXml = $xml.find("herocta");
    if ($heroCtaXml.length) {
        var $heroCtaHtml = $(".hero-cta a");

        $heroCtaHtml.
            html($heroCtaXml.attr('alt')).
            attr('title', $heroCtaXml.attr('alt')).
            attr('href', $heroCtaXml.attr('href')).
            css({
                'background-image': 'url("' + $heroCtaXml.attr('background') + '")',
                width: $heroCtaXml.attr('width'),
                height: $heroCtaXml.attr('height')
            }).
            hover(
                function () {
                    $heroCtaHtml.addClass('hover');
                },
                function () {
                    $heroCtaHtml.removeClass('hover');
                }
            ).
            click(function () {
                s = 's_gs()'; // What is this supposed to do? Leaving it in just in case.
                waCustomLink(this,'','e','wa_iid=' + $heroCtaXml.attr('iid'))
            });
    }

    localize(".section.work h1 a", "worktitle", "worklink");
    localize(".section.play h1 a", "playtitle", "playlink");
    localize(".section.products h1 a", "productstitle", "productslink");
    localize(".section.support h1 a", "supporttitle", "supportlink");
    localize(".section.about h1 a", "abouttitle", "aboutlink");
    localize(".section.work h2", "worksubtitle");
    localize(".section.play h2", "playsubtitle");
    localize(".section.products h2", "productssubtitle");
    localize(".section.support h2", "supportsubtitle");
    localize(".section.about h2", "aboutsubtitle");
    localize(".section.work .body", "workbody");
    localize(".section.play .body", "playbody");
    localize(".section.products .body", "productsbody");
    localize(".section.support .body", "supportbody");
    localize(".section.about .body", "aboutbody");
    $("#main-c").addClass("postload");
    $(".sections").show();
    //have to update this from selected in the select box

	// Script to change the li bullet of a highlighted link
	$(".contents li").hover(
		function() {
			$(this).addClass("hover")
		},
		function() {
			$(this).removeClass("hover")
		}
	);


    if (firstTime) {
        if (ie6) {
            $("#optionDis").attr("selected", "selected");
        }
        else { localize('#local-text h2', "locationtext"); }
    }

    else {
        $("#local-text h2").html($('#country-selector option:selected').text());
    }

    //*****************************************************************//
    //************HERO UPDATES FROM COUNTRY XML*******************************//

    var gfxCode = $xml.find("heroheadline").text();
    var imgWidth = $xml.find("heroheadlinewidth").text();
    var imgHeight = $xml.find("heroheadlineheight").text();

    var gfxEl = $("#banner span#gfx").html(gfxCode);
    gfxEl.css("height", imgHeight);
    gfxEl.css("width", imgWidth);

	// Fix transparency issues in IE6
	if (ie6) {
		$("#banner span#gfx img").addClass('unitPng');
		setTimeout(pngfix,1000);
	}

	if ($xml.find("headlinetext").text().length > 1) {
		var altText = $xml.find("headlinetext").text();
		$("#bannertxt").text(altText);
		$("#banner span#gfx img").attr("alt", altText);
	}

	// Update the hero CTA

    // this harmless snippet will add a top margin to the top-most sub-nav popup menu
    $('.section:first > .contents').addClass('contents-first');
}

function adjustRtlCss() {
    $('.gaat40-search').css('left', '400px')
    $('.mod-search-searchbox-container').css('right', '200px');
    $('.mod-search-searchbox-test-wrapper .mod-search-searchbox-menu-container').css('right', '110px');
    $('.mod-search-searchbox-container .mod-search-searchbox-input-type-submit').css('right', 'auto');
    $('.mod-search-searchbox-test-wrapper .mod-search-searchbox-menu-container').css('right', '112px');
    $('.mod-search-searchbox-test-wrapper .mod-search-searchbox-flyout-container').css('right', '-39px');
}

function trackPage(initialTracking, country) {
    omniture_page_name = country.language.countryval.replace(/_/g, ":").toLowerCase();
    waTrackAsLink("global gateway selection: " + country.name, 'o', 'wa_prop14=cim:' + omniture_page_name);
}

function loadHeader(country) {
    var headerJs = "/sites/sitewide/HAT/40recode/" + country.language.culture + "/json/gh_gateway.js";
    var languageClasses = "HAT-globalgateway HAT-wide " + country.language.fonttype + (country.language.textdirection === "rtl" ? " HAT-rtl" : "");
    var header = '/sites/sitewide/HAT/40recode/' + country.language.culture + '/' + country.language.textdirection + '_Standards_W1024_HTTP_UTF8/gh_gateway.inc';

    $("#gaat40-header, #ggw").attr('class', languageClasses);

    var data = '';

    /*
    The following section must be loaded synchronously to follow an execution order.
    */
    getSynchronousHtml(header, function (data) {
        /*
        US header is loaded by default from the page markup.
        For non-US locales, we need to manually load the header here.
        */
        $('.gaat40-overview').removeClass('header-show').addClass('header-hide');

        $('#gaat40-header').html(data);

        if (country.language.textdirection === 'rtl')
            adjustRtlCss();
    });
}

function loadFooter(country) {
    var footer = "/sites/sitewide/HAT/40recode/" + country.language.culture + "/" + country.language.textdirection + "_Standards_W1024_HTTP_UTF8/gf_default.inc";
    $("#footerdiv").load(footer, function () {
        $('#footerdiv').removeClass('header-hide').addClass('header-show');
    });
}

function instantiateLangages() {
    if (GAAT40.languages)
        return;
    GAAT40.languages = { countries: [{ name: 'United Kingdom - English', localizedCountry: 'United Kingdom (English)' }, { name: 'Saudi Arabia - English', localizedCountry: 'Saudi Arabia (English)' }, { name: 'South Africa - English', localizedCountry: 'South Africa (English)' }, { name: 'France - French', localizedCountry: 'France (Français)' }, { name: 'Spain - Spanish', localizedCountry: 'Spain (Español)' }, { name: 'Germany - German', localizedCountry: 'Germany (Deutsch)' }, { name: 'Hungary - Hungarian', localizedCountry: 'Hungary (Magyar)' }, { name: 'Italy - Italian', localizedCountry: 'Italy (Italiano)' }, { name: 'Poland - Polish', localizedCountry: 'Poland (Polski)' }, { name: 'Sweden - English', localizedCountry: 'Sweden (Svenska)' }, { name: 'Turkey - Turkish', localizedCountry: 'Turkey (Değiştir)' }, { name: 'Russia - Russian', localizedCountry: 'Russia (Русский)' }, { name: 'UAE - Arabic', localizedCountry: 'United Arab Emirates (العربية)' }, { name: 'Saudi Arabia - Arabic', localizedCountry: 'Saudi Arabia (اللغةالعربية)' }, { name: 'Egypt - Arabic', localizedCountry: 'Egypt (العربية)' }, { name: 'Czech Republic - Czech', localizedCountry: 'Czech Republic (Změna)' }, { name: 'Israel - Hebrew', localizedCountry: 'Israel (עברית)' }, { name: 'Netherlands - Dutch', localizedCountry: 'Netherlands (Nederlands)' }, { name: 'Romania - English', localizedCountry: 'Romania (Româneşte)' }, { name: 'Sweden - Swedish', localizedCountry: 'Sweden (Svenska)' }, { name: 'Ukraine - Ukrainian', localizedCountry: 'Ukraine (українська)' }, { name: 'Indonesia - Bahasa', localizedCountry: 'Indonesia (Bahasa)' }, { name: 'Thailand - Thai', localizedCountry: 'Thailand (ไทย)' }, { name: 'Vietnam - Vietnamese', localizedCountry: 'Vietnam (Thay đổi)' }, { name: 'Korea - Korean', localizedCountry: 'Korea (변경)' }, { name: 'Singapore - English', localizedCountry: 'Asia Pacific (English)' }, { name: 'Asia Pacific - English', localizedCountry: 'Asia Pacific (English)' }, { name: 'China - Simplified Chinese', localizedCountry: 'China (简体中文)' }, { name: 'Taiwan - Traditional Chinese', localizedCountry: 'Taiwan (變更)' }, { name: 'India - English', localizedCountry: 'India (English)' }, { name: 'Australia - English', localizedCountry: 'Australia (English)' }, { name: 'Japan - Japanese', localizedCountry: 'Japan (日本語)' }, { name: 'Mexico - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Latin America - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Brazil - Portuguese', localizedCountry: 'Brazil (Português)' }, { name: 'United States - English', localizedCountry: 'United States (English)' }, { name: 'Argentina - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Austria - German', localizedCountry: 'Austria (Deutsch)' }, { name: 'Belgium – French', localizedCountry: 'Belgium (Français)' }, { name: 'Belgium – Dutch', localizedCountry: 'Belgium (Nederlands)' }, { name: 'Belgium â€“French', localizedCountry: 'Belgium (Français)' }, { name: 'Belgium â€“Netherlands', localizedCountry: 'Belgium (Nederlands)' }, { name: 'Bolivia - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Canada - English', localizedCountry: 'Canada (English)' }, { name: 'Canada - French', localizedCountry: 'Canada (Français)' }, { name: 'Chile - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Colombia - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Costa Rica - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Czech Republic - English', localizedCountry: 'Czech Republic (English)' }, { name: 'Egypt - English', localizedCountry: 'Egypt (English)' }, { name: 'Hong Kong - English', localizedCountry: 'Hong Kong (English)' }, { name: 'Hungary - English', localizedCountry: 'Hungary (English)' }, { name: 'Ireland - English', localizedCountry: 'Ireland (English)' }, { name: 'Malaysia - English', localizedCountry: 'Malaysia (English)' }, { name: 'Middle East - English', localizedCountry: 'Middle East (English)' }, { name: 'Middle East - Arabic', localizedCountry: 'Arabic (تغيير)' }, { name: 'New Zealand - English', localizedCountry: 'New Zealand (English)' }, { name: 'Pakistan - English', localizedCountry: 'Pakistan (English)' }, { name: 'Peru - Spanish', localizedCountry: 'Latin America (Español)' }, { name: 'Philippines - English', localizedCountry: 'Asia Pacific (English)' }, { name: 'Switzerland - German', localizedCountry: 'Switzerland (Deutsch)' }, { name: 'United Arab Emirates - English', localizedCountry: 'United Arab Emirates (English)' }, { name: 'United Arab Emirates - Arabic', localizedCountry: 'United Arab Emirates (العربية)' }, { name: 'Uruguay - Spanish', localizedCountry: 'Uruguay (Spanish)' }, { name: 'Venezuela - Spanish', localizedCountry: 'Latin America (Español)'}] }; GAAT40.SubheadingLUT = { sub: [{ id: 'gaat40-sbhdr_stories', path: [{ value: '/consumer/media/' }, { value: '/consumer/inside/' }, { value: '/consumer/index' }, { value: '/consumer/stories'}] }, { id: 'gaat40-sbhdr_ptr', path: [{ value: 'business/partnerprograms'}] }, { id: 'gaat40-sbhdr_prod', path: [{ value: 'business/products' }, { value: 'consumer/products' }, { value: '/products/services/' }, { value: '/software/products/' }, { value: '/design/embedded/' }, { value: '/intel/technology-leadership/' }, { value: '/products/' }, { value: '/test/'}] }, { id: 'gaat40-sbhdr_itc', path: [{ value: '/itcenter/'}] }, { id: 'gaat40-sbhdr_dev-ctr', path: [{ value: '/business/design'}] }, { id: 'gaat40-sbhdr_learn', path: [{ value: '/consumer/learn/' }, { value: '/consumer/learn' }, { value: '/learn' }, { value: '/learn/practical-advice/' }, { value: '/learn/buying-guides/' }, { value: '/learn/glossary/'}] }, { id: 'gaat40-sbhdr_tech', path: [{ value: '/corporate/techtrends/' }, { value: '/technology/' }, { value: '/idf/' }, { value: 'intel/enhancinglives/' }, { value: '/corporate/europe/' }, { value: '/corporate/education/' }, { value: '/intel/citizenship/' }, { value: '/standards/' }, { value: '/corpresponsibility/' }, { value: '/intel/finance/' }, { value: '/business/technology'}] }, { id: 'gaat40-sbhdr_shop', path: [{ value: '/consumer/shop/' }, { value: '/shop' }, { value: '/consumer/shop'}] }, { id: 'gaat40-sbhdr_cr', path: [{ value: '/corporateresponsibility' }, { value: '/education' }, { value: '/environment' }, { value: '/environment/'}] }, { id: 'gaat40-sbhdr_info', path: [{ value: '/companyinfo'}] }, { id: 'gaat40-sbhdr_com', path: [{ value: '/communities/' }, { value: '/companyinfo/' }, { value: '/intel/diversity/' }, { value: '/intel/company/' }, { value: '/capital/' }, { value: '/museum/' }, { value: '/jobs/' }, { value: '/jobs' }, { value: '/pressroom/' }, { value: '/communities/index'}] }, { id: 'gaat40-sbhdr_game', path: [{ value: '/consumer/game/' }, { value: '/consumer/game'}] }, { id: 'gaat40-sbhdr_dlds', path: [] }, { id: 'gaat40-sh-reseller', path: [{ value: '/channel/reseller/' }, { value: '/channel/distributor/' }, { value: '/software/partner/'}] }, { id: 'gaat40-sh-chome', path: [{ value: '/consumer/index'}]}] }; GAAT40.ShareBlacklist = { path: [{ value: '/intel/legal/counsel'}] };
}

function getLocalizedCountry(countryName) {
    instantiateLangages();
    for (var index = 0; index < GAAT40.languages.countries.length; index++) {
        if (GAAT40.languages.countries[index].name == countryName) {
            return GAAT40.languages.countries[index].localizedCountry;
        }
    }
    return null;
}

function translateChangeCountryLink() {
    var localziedCountry = getLocalizedCountry(country.name);
    if (!localziedCountry) return;
    $('#gaat40-locale a').text(localziedCountry);
}

// can be used for cookies or URL search strings
function parseParams(str, delimiter) {
    var x = {};
    $.each(str.split(delimiter), function (i, n) {
        var keyVal = n.split(/=/);
        if (keyVal[0] && keyVal[1]) { x[keyVal[0]] = keyVal[1]; }
    });
    return x;
}

function parseDataByObjectName(data, objectName, terminator) {
    var startIndex = data.indexOf(objectName);
    var endIndex = data.indexOf(terminator, startIndex);
    var gaatString = data.substring(startIndex, endIndex + terminator.length);
    return gaatString;
}

function cookie(key) {
    //return parseParams(document.cookie, /; ?/)[key];
    //IE6 Cookie Fix 2/1/2009
    return decodeURIComponent(parseParams(document.cookie, /; ?/)[key]);
}

function param(key) {
    var params = parseParams(location.search.substr(1), "&");
    return params[key] ? unescape(params[key]) : null;
}

function setCookieWithCountryValue(country) {
    var nextyear = new Date();
    nextyear.setFullYear(nextyear.getFullYear() + 1);
    var cookie_value = "countrylang=" + encodeURIComponent(country.name) + "; domain=.intel.com; path=/; expires=" + nextyear.toUTCString();
    document.cookie = cookie_value;
}

function getLocale() {
    var search = location.search;
    var keyValues = search.split("&");
    if (keyValues.length > 0) {
        var value = keyValues[0].replace("?", "").replace("/", "");
        if (value === 'r=f')
            return null;
        return value;
    }
    return null;
}

// utility function to generate the 'no script' list of country links
function createNoscriptList() {
    var $div = $(".no-script").empty().show();
    var $list = $("<ul>").appendTo($div);
    $.each(HAT.Countries, function (i, n) {
        var value = n.link;
        if (n.cont) {
            $.ajax({ async: false, url: n.cont,
                success: function (countryXML) { value = $(countryXML).find("worklink").text(); }
            });
        }
        $list.append("<li><a href='" + value + "'>" + (n.localizedName || n.name) + "<\/a><\/li>");
        if ((i + 1) % 16 === 0) {
            if (i + 1 === HAT.Countries.length) {
                $list.css("text-align", "right");
                $div.append("<div class='clear'>");
            } else {
                $list = $("<ul>").appendTo($div);
            }
        }
    });
}

var isRedirecting = false;
function doRedirect(url) {
    if ( ! isRedirecting) {
        location = url;
        isRedirecting = true;
    }
}

function onGeoCheck(deeplink) {
    switch (deeplink) {
        case 'en_US_01':
            doRedirect('http://www.intel.com/content/www/us/en/homepage.html');
            break;
        case 'de_DE_03':
            doRedirect('http://www.intel.de/content/www/de/de/homepage.html');
            break;
        case 'pt_BR_01':
            doRedirect('http://www.intel.com.br/content/www/br/pt/homepage.html');
            break;
		case 'en_AU_01':
            doRedirect('http://www.intel.com/content/www/au/en/homepage.html');
            break;
		case 'en_AP_03':
            doRedirect('http://www.intel.my/content/www/my/en/homepage.html');
            break;
		case 'en_AP_06':
            doRedirect('http://www.intel.ph/content/www/ph/en/homepage.html');
            break;
		case 'en_IN_01':
            doRedirect('http://www.intel.in/content/www/in/en/homepage.html');
            break;
		case 'en_AP_07':
            doRedirect('http://www.intel.sg/content/www/xa/en/homepage.html');
            break;
		case 'en_AP_01':
            doRedirect('http://www.intel.hk/content/www/hk/en/homepage.html');
            break;
		case 'en_AP_04':
            doRedirect('http://www.intel.com/content/www/nz/en/homepage.html');
            break;
		case 'en_AP_05':
            doRedirect('http://www.intel.pk/content/www/pk/en/homepage.html');
            break;
		case 'en_UK_15':
            doRedirect('http://www.intel.co.uk/content/www/uk/en/homepage.html');
            break;
		case 'ko_KR_01':
            doRedirect('http://www.intel.com/content/www/kr/ko/homepage.html');
            break;
		case 'th_TH_01':
            doRedirect('http://www.intel.com/content/www/th/th/homepage.html');
            break;
		case 'vi_VN_01':
            doRedirect('http://www.intel.com/content/www/vn/vi/homepage.html');
            break;
		case 'id_ID_01':
            doRedirect('http://www.intel.com/content/www/id/id/homepage.html');
            break;	
		case 'zh_TW_01':
			doRedirect('http://www.intel.com/content/www/tw/zh/homepage.html');
    }
}

/*END Utility Functions */
//checking for best browser out there:

//just in case you are using the best browser-now we KNOW!!!
if ($.browser.msie && $.browser.version.substring(0, 1) === '6') {
    ie6 = true;
}

if ($.browser.msie && $.browser.version.substring(0, 1) === '7') {
    ie7 = true;
}

// left side navigation
$(".section-container").mouseenter(function () {
    if ($(this).parent().attr("class").indexOf("work") > -1) {
		$(this).parent().addClass("navhover-top");
	} else if ($(this).parent().attr("class").indexOf("about") > -1) {
		$(this).parent().addClass("navhover-bot");
	} else {
		$(this).parent().addClass("navhover");
	}
    $(this).find('.contents').show();
	$(this).addClass("navhover-container");
}).mouseleave(function () {
    $(this).parent().removeClass("navhover");
    $(this).parent().removeClass("navhover-top");
    $(this).parent().removeClass("navhover-bot");
    $(this).find('.contents').hide();
	$(this).removeClass("navhover-container");
});

/*
If there is a country code in the Query String parameter, skip this block
and load
*/
var deeplink = getLocale();
if (deeplink === null || deeplink === undefined || deeplink === '') {

    var ctry = null;
    var cVal = param("country");
    var ckVal = cookie("countrylang");

    // if there is a passed-in param use that
    if (cVal !== null && cVal !== undefined) {
        default_country_name = cVal;
    }
    // Otherwise if there is a cookie set clear it
    else if (ckVal !== null && ckVal !== undefined) {
        setCookieWithCountryValue('');
    };

    // If no cookie, then determine geo by browser language (geocheck.js)
    if ((default_country_name === null || default_country_name === undefined) && (geocheck !== undefined)) {
        ctry = HAT.Countries.getByDeeplink(checkGeo());
    }
    else {
        ctry = HAT.Countries.getByName(default_country_name);
    }

    if (ctry !== null && ctry !== undefined) {
        redirectUrl = "?" + ctry.deeplink;
        onGeoCheck(ctry.deeplink);
    } else {
        redirectUrl = '?' + DefaultLocale;
        onGeoCheck(DefaultLocale);
    }

    if (hasMobileParam(location.search)) {
        redirectUrl = addMobileParam(redirectUrl);
    }
    doRedirect(redirectUrl);
}
else {
    onGeoCheck(deeplink);
}

/*
Code below will execute if there is a country code found (either via the Query String,
browser language, or cookie.)
*/

var redirect = ((param("country") === null || param("country") === undefined) &&
            (deeplink === null || deeplink === undefined)); // don't (initially) redirect if a country has been passed in
var initialTracking = false;

$.each(HAT.Countries, function (i, country) {
    // for convenience, set up a direct link the the appropriate item in HAT.Languages.lang
    $.each(HAT.Languages.lang, function (i, language) {
        if ($.inArray(country.name, language.countrylang) >= 0) {
            country.language = language;
            return false;
        }
    });

    // set up the default country value and an analytics tracking name
    if (deeplink === country.deeplink || default_country_name === country.name) {
        default_country = country;
        // set omniture page name, but NOT for the default (index 0, en_US) selection
        if (i && country.language) {
            omniture_page_name = country.language.countryval.replace(/_/g, ":");
        }
    }
});

/* BEGIN Main Page Element Loader */
locale = getLocale();
//check the param first
country = HAT.Countries.getByDeeplink(locale);
if (country !== null) {
    setCookieWithCountryValue(country);
}

$(document).ready(function () {
    // parse the country list into a select box when loaded
    $.each(HAT.Countries, function (i, n) {
        $("<option value='" + n.name + "'>")
		.html(n.localizedName || n.name)
		.attr("selected", (n === default_country ? "selected" : ""))
		.appendTo("#country-selector");
    });

    //if no value is found, check the cookie
    if (country === null || country === undefined) {
        country = HAT.Countries.getByName(cookie("countrylang"));

        //if no value is found, check browser language
        if (country === null || country === undefined) {
            country = HAT.Countries.getByDeeplink(checkGeo());
        }

        //if no value is found still, set the default language
        if (country === null || country === undefined) {
            country = HAT.Countries.getByDeeplink(DefaultLocale);
        }

        redirectUrl = "?" + country.deeplink;

        if (hasMobileParam(location.search)) {
            redirectUrl = addMobileParam(redirectUrl);
        }
        doRedirect(redirectUrl);
    }
    else {
        setCookieWithCountryValue(country);
    }

    /*
    The searchbox markup contains the following hidden input to determine the localization settings
    <input type="hidden" id="input-market" name="c" value="de_DE" />
    We need to set it BEFORE we call
    */
    $('#input-market').val(country.language.culture);

	// to fix a positioning bug in IE if switching to a RTL language
    if (country.language && country.language.textdirection === "rtl") {
        curTextDir = country.language.textdirection;
    }
});

// show the country selector, and add a change handler
$("#country-selector").show().change(function (e) {
    firstTime = false;
    var selIndex = this.selectedIndex - 1;
    if (selIndex === -1) selIndex = 0;
    var selectedCountry = HAT.Countries[selIndex];
    redirectUrl = "?" + selectedCountry.deeplink;

    if (hasMobileParam(location.search)) {
        redirectUrl = addMobileParam(redirectUrl);
    }

    doRedirect(redirectUrl);
});

// If a country has a redirect set up, load that page url.
if (country && country.link) {
    doRedirect(country.link);
}
// Otherwise, set up the current page with country appropriate values
else if (country && country.cont && country.language) {

    $("html").attr("dir", country.language.textdirection);

    loadHeader(country);
    if (country.deeplink !== 'en_US_01') {
        loadFooter(country);
    }
    else {
        $(document).ready(function () {
            $('#footerdiv').removeClass('header-hide').addClass('header-show');
        });
    }

    // track change after the language updates for better user experience
    // but only after the initial page load
    if (initialTracking) {
        trackPage(country);
    }

    //default value for select country dropdown div
    // fix a bug in IE6 where the country selector loses track of which item is selected when changing between LTR and RTL
    $("#country-selector").find("option").filter(function () {
        if ($(this).val() === country.name) {
            $(this).attr("selected", "selected");
        }
    });

    $.get(country.cont, parseCountryXML, "xml");
}

// show the country selector, and add a change handler
// load the selected language if it is not the first (0th)
// this assumes that the default language is already set up
if ($("#country-selector").get(0).selectedIndex) {
    //$("#country-selector").trigger('change');

} else {
    //country = HAT.Countries[0];
	//alert("second: " + country.cont);
    //$.get(country.cont, parseCountryXML, "xml");
    //$("#main-c").addClass("postload");

    firstTime = true;
}

/* END Main Page Element Loader */
