// Arrow Nav sequence of pages.
var fluxRegion;
var navPageLinksList = [
	'/global/en/home#/home',
	'/global/en/adeyaka-magazine/lobby/#/adeyaka-magazine/lobby/2011-09-13-generating-emotional-values',
	'/global/en/inspirations/redbull/introduction#/inspirations/redbull/introduction',
	'/global/en/inspirations/cirque-du-soleil/introduction#/inspirations/cirque-du-soleil/introduction',
	'/global/en/models/g-convertible#/models/g-convertible',
	'/global/en/models/g-coupe#/models/g-coupe',
	'/global/en/models/g-sedan#/models/g-sedan',
	'/global/en/models/m#/models/m',
	'/global/en/models/ex#/models/ex',
	'/global/en/models/fx#/models/fx',
	'/global/en/models/qx#/models/qx',
	'/global/en/models/future-vehicles/jx#/models/future-vehicles/jx',
	'/global/en/infiniti-world/news-events/#/infiniti-world/news-events/2011-12-20-rbr-season-review',
	'/global/en/infiniti-world/infiniti-tv/featured#/infiniti-world/infiniti-tv/featured/2012-01-23-fastest-accelerating-hybrid'
];

// Arrow Nav sequence of pages.
var navPageList = [
	'/global/en/home',
	'/global/en/adeyaka-magazine',
	'/global/en/inspirations/redbull',
	'/global/en/inspirations/cirque-du-soleil',
	'/global/en/models/g-convertible',
	'/global/en/models/g-coupe',
	'/global/en/models/g-sedan',
	'/global/en/models/m',
	'/global/en/models/ex',
	'/global/en/models/fx',
	'/global/en/models/qx',
	'/global/en/models/future-vehicles',
	'/global/en/infiniti-world/news-events',
	'/global/en/infiniti-world/infiniti-tv'
];

//getting the server date.
var serverDate = '';
$.get('/currentDate', function(thisData) {
	serverDate = thisData;
});

//putting server date into function for flash to use.
var getServerDate = function(){
	return serverDate;
}



var htmlPagePathSelected;

var activeSection;
var activeSubSection;

var countryList = [];
var countryLinks = [];

var currentSection = '';

	/* North America */
	countryList['ca|en'] = 'Canada';
	countryLinks['ca|en'] = 'http://www.infiniti.ca/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['pa|en'] = 'Panama';
	countryLinks['pa|en'] = 'http://www.infiniti.com.pa/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['mx|en'] = 'Mexico';
	countryLinks['mx|en'] = 'http://www.infiniti.mx/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['id|en'] = 'Indonesia';
	countryLinks['id|en'] = 'http://www.infiniti-indonesia.co.id/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['gu|en'] = 'Guam';
	countryLinks['gu|en'] = 'http://www.infinitiguam.com/index.htm?r=CA&ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['pr|pr'] = 'Puerto Rico';
	countryLinks['pr|pr'] = 'http://www.infinitipr.com/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['us|en'] = 'USA';
	countryLinks['us|en'] = 'http://www.infinitiusa.com/?dcp=nml.mtl.HMP.infiniticom_brandexperience&ig-track=Infiniti.com-InfinitiBrand';
	
	/* Europe */
	countryList['at|de'] = 'Austria';
	countryLinks['at|de'] = 'http://www.infiniti.at/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['be|en'] = 'Belgium';
	countryLinks['be|en'] = 'http://www.infiniti.be/?ig-track=Infiniti.com-InfinitiBrand';	
	
	countryList['be|fr'] = 'Belgium';
	countryLinks['be|fr'] = 'http://www.infiniti.be/fra/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['bg|bg'] = 'Bulgaria';
	countryLinks['bg|bg'] = 'http://www.infinitibg.bg/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['cz|cs'] = 'Czech Republic';
	countryLinks['cz|cs'] = 'http://www.infiniticars.cz/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['fr|fr'] = 'France';
	countryLinks['fr|fr'] = 'http://www.infiniti.fr/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['de|de'] = 'Germany';
	countryLinks['de|de'] = 'http://www.infiniti.de/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['gr|el'] = 'Greece';
	countryLinks['gr|el'] = 'http://www.infiniti.gr/';
	
	countryList['hu|hu'] = 'Hungary';
	countryLinks['hu|hu'] = 'http://www.infiniti.hu/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['it|it'] = 'Italy';
	countryLinks['it|it'] = 'http://www.infiniti.it/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['lu|en'] = 'Luxembourg';
	countryLinks['lu|en'] = 'http://www.infiniti.lu/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['nl|nl'] = 'Netherlands';
	countryLinks['nl|nl'] = 'http://www.infiniti-cars.nl/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['pl|pl'] = 'Poland';
	countryLinks['pl|pl'] = 'http://www.infiniticars.pl/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['ro|ro'] = 'Romania';
	countryLinks['ro|ro'] = 'http://www.infiniti.ro/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['ru|ru'] = 'Russia';
	countryLinks['ru|ru'] = 'http://www.infiniti.ru/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['es|es'] = 'Spain';
	countryLinks['es|es'] = 'http://www.infiniti.com.es/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['ch|en'] = 'Switzerland';
	countryLinks['ch|en'] = 'http://www.infiniti.ch/enu/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['tr|tr'] = 'Turkey';
	countryLinks['tr|tr'] = 'http://www.infiniti.com.tr/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['ua|uk'] = 'Ukraine';
	countryLinks['ua|uk'] = 'http://www.infiniti.ua/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['uk|en'] = 'United Kingdom';
	countryLinks['uk|en'] = 'http://www.infiniti.co.uk/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['eu|en'] = 'Infiniti Europe';
	countryLinks['eu|en'] = 'http://www.infinitieurope.com/?ig-track=Infiniti.com-InfinitiBrand';
	
	/* Middle East */
	countryList['ad|en'] = 'Abu Dhabi';
	countryLinks['ad|en'] = 'http://www.infiniti-abudhabi.com/en/?ig-track=Infiniti.com-InfinitiBrand';
        
    countryList['az|en'] = 'Azerbaijan';
    countryLinks['az|en'] = 'http://www.infiniti-azerbaijan.com/en/?ig-track=Infiniti.com-InfinitiBrand';		
    
    countryList['bh|en'] = 'Bahrain';
    countryLinks['bh|en'] = 'http://www.infiniti-bahrain.com/en/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['db|en'] = 'Dubai';
	countryLinks['db|en'] = 'http://www.infiniti-dubai.com/en/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['il|he'] = 'Israel';
	countryLinks['il|he'] = 'http://www.infiniti.co.il/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['kw|en'] = 'Kuwait';
	countryLinks['kw|en'] = 'http://www.infiniti-kuwait.com/en/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['lb|en'] = 'Lebanon';
	countryLinks['lb|en'] = 'http://www.infiniti-lebanon.com/en/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['om|en'] = 'Oman';
	countryLinks['om|en'] = 'http://www.infiniti-oman.com/en/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['qa|en'] = 'Qatar';
	countryLinks['qa|en'] = 'http://www.infiniti-qatar.com/en/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['sa|en'] = 'Saudi Arabia';
	countryLinks['sa|en'] = 'http://www.infiniti-ksa.com/en/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['me|en'] = 'Middle East';
	countryLinks['me|en'] = 'http://www.infiniti-me.com/en/locator.html?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['jo|en'] = 'Jordan';
	countryLinks['jo|en'] = 'http://www.infiniti-jordan.com/?ig-track=Infiniti.com-InfinitiBrand';
	
	
	/* Asia Pacific */
	countryList['cn|zh'] = 'China';
	countryLinks['cn|zh'] = 'http://www.infiniti.com.cn/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['tw|zh'] = 'Taiwan';
	countryLinks['tw|zh'] = 'http://www.infiniti.com.tw/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['kr|ko'] = 'Korea';
	countryLinks['kr|ko'] = 'http://www.infiniti.co.kr/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['id|en'] = 'Indonesia';
	countryLinks['id|en'] = 'http://www.infiniti-indonesia.co.id/?ig-track=Infiniti.com-InfinitiBrand';
	
	countryList['sg|en'] = 'Singapore';
	countryLinks['sg|en'] = 'http://www.infiniti-singapore.com/?ig-track=Infiniti.com-InfinitiBrand';
	

var currentNewsArticleId = 1;

function updateImageBorders(id) {
	for(i=1;i<=5;i++) {
		var img = 'carouselImage'+i;
		var oImg = document.getElementById(img)
		oImg.style.border = '1px solid #000';
	}
	var oActiveImg = document.getElementById(id)
	oActiveImg.style.border = '1px solid #797979';
}

function launchArticle(uri, style) {
	alert('http://' + window.location.hostname + '/html/en' + uri + '?display='+style);	
}

function launchGallery(uri, style) {
	alert('http://' + window.location.hostname + '/html/en' + uri + '?display='+style);
}

function showArticleArchive(){
    document.title = 'News and Events Archive - Infiniti Global Official Site'; 
    window.currentSection = 'archive';
	currentSection = 'articles';
	//hide featured
	$('#articleArchiveLink').addClass('selected-subnav');
	$('#featuredArticlesLink').removeClass('selected-subnav');
	
	if(($.browser.msie) && ($.browser.version == '6.0')){
		$('#articleArchiveLink').unbind('mouseover');
		$('#featuredArticlesLink').mouseover(function(){
				$(this).css('color', '#ffffff');
			}
		);
		$('#featuredArticlesLink').mouseout(function(){
				$(this).css('color', '#aaaaaa');
			}
		);
	}

	var odiv1 = document.getElementById('featuredArticles');
	odiv1.style.display = 'none';
	odiv1.style.visibility = 'hidden';
	var odiv2 = document.getElementById('archiveArticles');
	odiv2.style.display = 'block';
	odiv2.style.visibility = 'visible';
	var odiv3 = document.getElementById('infiniti-carousel-text');
	odiv3.style.visibility = 'hidden';
	var odiv4 = document.getElementById('infiniti-carousel-container');
	odiv4.style.visibility = 'hidden';
	$('#page-selector-previous').attr('style', 'visibility:visible;');
	$('#page-selector-next').attr('style', 'visibility:visible;');
	document.jsAPI.trackPage(window.location.hash.substring(1),'HTML');
}
function showAdeyakaArticleArchive(){
    document.title = 'Adeyaka Magazine Archive - Infiniti Global Official Site'; 
    window.currentSection = 'archive';
	//hide featured
	$('#articleArchiveLink').addClass('selected-subnav');
	$('#iPadLink, #lobbyLink, #loungeLink, #galleryLink').removeClass('selected-subnav').click(function(){
		$(this).addClass('selected-subnav');
		$('#articleArchiveLink').removeClass('selected-subnav');
	});
	
	if(($.browser.msie) && ($.browser.version == '6.0')){
		$('#articleArchiveLink').unbind('mouseover');
		$('#ipadLink, #lobbyLink, #loungeLink, #galleryLink').mouseover(function(){
				$(this).css('color', '#ffffff');
			}
		);
		$('#ipadLink, #lobbyLink, #loungeLink, #galleryLink').mouseout(function(){
				$(this).css('color', '#aaaaaa');
			}
		);
	}

	$('#lobby, #lounge, #gallery, #ipad').css('visibility', 'hidden');
	$('#archiveArticles').show().css('visibility', 'visible');
	$('#infiniti-carousel-text, .adeyaka-carousel-container').attr('style', 'visibility: hidden');
	$('#page-selector-previous, #page-selector-next, .adeyakacontent').css('visibility', 'visible');
	document.jsAPI.trackPage(window.location.hash.substring(1),'HTML');
}
function hideAdeyakaArticleArchive(){
	//hide features
	$('#lobby, #lounge, #gallery, #ipad').css('visibility', 'visible');
	$('#archiveArticles').hide();
	$('#infiniti-carousel-text, .adeyaka-carousel-container').css('visibility', 'visible');
	$('#page-selector-previous, #page-selector-next, .adeyakacontent').css('visibility', 'visible');
}

function showFeaturedArticles(){
    $.fancybox.close();

    window.currentSection = 'featured';
	currentSection = 'featured';
	$('#featuredArticlesLink').addClass('selected-subnav');
	$('#articleArchiveLink').removeClass('selected-subnav');
	
	if(($.browser.msie) && ($.browser.version == '6.0')){
		$('#featuredArticlesLink').unbind('mouseover');
		$('#articleArchiveLink').mouseover(function(){
				$(this).css('color', '#ffffff');
			}
		);
		$('#articleArchiveLink').mouseout(function(){
				$(this).css('color', '#aaaaaa');
			}
		);
	}
	
	var odiv = document.getElementById('featuredArticles');
	odiv.style.display = 'block';
	odiv.style.visibility = 'visible';
	var odiv2 = document.getElementById('archiveArticles');
	odiv2.style.display = 'none';
	odiv2.style.visibility = 'hidden';
	var odiv3 = document.getElementById('infiniti-carousel-text');
	odiv3.style.visibility = 'visible';
	var odiv4 = document.getElementById('infiniti-carousel-container');
	odiv4.style.visibility = 'visible';
	$('#page-selector-previous').attr('style', 'visibility:visible;');
	$('#page-selector-next').attr('style', 'visibility:visible;');
}

function changeNewsArticle(id, deeplink, text)
{
	//hide the current article
	var oDivName = 'infinitiworldContentPane'+currentNewsArticleId;
	var oDiv = document.getElementById(oDivName);
	oDiv.className = 'infinitiworldContentPaneHidden';
	var oDivName = 'infinitiworldImagePane'+currentNewsArticleId;
	var oDiv = document.getElementById(oDivName);
	oDiv.className = 'infinitiworldImagePaneHidden';
	
	//show the selected article
	var oDivName = 'infinitiworldContentPane'+id;
	var oDiv = document.getElementById(oDivName);
	oDiv.className = 'infinitiworldContentPane';
	var oDivName = 'infinitiworldImagePane'+id;
	var oDiv = document.getElementById(oDivName);
	oDiv.className = 'infinitiworldImagePane';
	currentNewsArticleId = id;
	
	oArticle = document.getElementById('currentArticle');
	oArticle.value = deeplink;
	
	oArticleIndex = document.getElementById('currentArticleIndex');
	oArticleIndex.value = id;
}


function changeRegion(region){
	
	$("#footer-selector").removeClass('set-item');
	$('.adeyakacontent').css('visibility','visible');
	$('.infinitiworldcontent').css('visibility', 'visible');
	$('.infinitiworldarchiveArticlescontent').css('visibility', 'visible');
	
	if(currentSection=='featured'){
		$('.infiniti-carousel-container').css('visibility', 'visible');
		$('.infiniti-carousel-text').css('visibility', 'visible');
	}
	
	document.jsAPI.setCookie('region', region);
	
    if (countryList[region].toLowerCase()=='infiniti europe') {
        jQuery("#footer-link").html('<li class="footer-region"><a href="' + countryLinks[region] + '">VISIT &nbsp; ' + countryList[region] + '</a></li>');
        jQuery(".region-link").html('<a id="regionalLink" href="' + countryLinks[region] + '"><span class="button"><p>VIEW DETAILS AND SPECS</p></span></a>');
        jQuery("#adeyakavisit").html('<a class="adeyakacomvisitlink" href="http://www.adeyaka.com/" target="_blank">Visit Adeyaka.com</a><a class="adeyakavisitlink" href="' + countryLinks[region] + '">Visit &nbsp; ' + countryList[region].toUpperCase() + '</a>');
    }
    else {
        jQuery("#footer-link").html('<li class="footer-region"><a href="' + countryLinks[region] + '">VISIT &nbsp; INFINITI &nbsp;' + countryList[region] + '</a></li>');
        jQuery(".region-link").html('<a id="regionalLink" href="' + countryLinks[region] + '"><span class="button"><p>VIEW DETAILS AND SPECS</p></span></a>');
        jQuery("#adeyakavisit").html('<a class="adeyakacomvisitlink" href="http://www.adeyaka.com/" target="_blank">Visit Adeyaka.com</a><a class="adeyakavisitlink" href="' + countryLinks[region] + '">Visit &nbsp; INFINITI &nbsp;' + countryList[region].toUpperCase() + '</a>');
    }
	
	
	tmp = region.split("|");
	try{
		getButtonXML(tmp[0]);
	} catch(e){
		//todo: get rid of this.	
	}
	resetHash();
	jQuery.fancybox.close();
}

//default sizes of window
var MINWIDTH = 720;
var MAXWIDTH = 1995;
var MINHEIGHT = 0;
var MAXHEIGHT = 904;
var MARGINTOPOFFSET = 0;
var MARGINLEFTOFFSET = 0;
var marginTop = 0;
var marginLeft = 0;
var topAlign = 0;
var leftAlign = 0;
var FOOTERHEIGHT = 49;
//might need to change this
var TOPPADDING = 0;
var LEFTPADDING = 0;
var flashLeft = 0;
var flashTop = 0;
var flash = false;
var width, height;
var maxWidthLeftOffset = 1200; // the difference between the real width and the MAXWIDTH
var windowHeight = 0; // the full height of the browser window
var windowWidth = 0; // the full width of the browser window

var url = window.location.href;
baseTemp = url.split('/');
base="";
for(var i=0;i<3;i++){
    base+=baseTemp[i]+"/";
}
fla = url.substring(url.lastIndexOf('?')+1,url.lastIndexOf('?')+9);
lang = baseTemp[3];

var onloadHandlers = [];
var onresizeHandlers = [];	

/*
if(($.browser.msie) && (window.location.toString().indexOf('lightbox') < 0) && (($.browser.version == '7.0') || ($.browser.version == '6.0'))){
	onloadHandlers[onloadHandlers.length] = 'showScreenSize()';
	onresizeHandlers[onresizeHandlers.length] = 'showScreenSize()';
	window.onload = function(){
		for(var i=0;i<onloadHandlers.length;i++){
				eval(onloadHandlers[i]);
		}
	
	}
	window.onresize = function(){
			for(var i=0;i<onresizeHandlers.length;i++){
			eval(onresizeHandlers[i]);
		}
	}
}
*/

function getScreenSize(){
 if (self.innerHeight) {    // all except Explorer
        width = self.innerWidth;
        height = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }
    windowHeight = height;
    windowWidth = width;
    
    if (width <= MINWIDTH){
        marginLeft = LEFTPADDING + MARGINLEFTOFFSET;
        leftAlign = width/2;
        width = MINWIDTH;
    }else{
        if (width >= MAXWIDTH){
            maxWidthLeftOffset = (width-MAXWIDTH)/2;
            width = MAXWIDTH;
        }
        marginLeft = ((width-MINWIDTH)/2)+LEFTPADDING + MARGINLEFTOFFSET;
        leftAlign = width/2;
    }
    if (height <= MINHEIGHT ){
        marginTop = TOPPADDING + MARGINTOPOFFSET;
        topAlign = height/2;
        height = MINHEIGHT;
        footerTop = height-topAlign;
        breadcrumbTop = 0;
    }else{
        if (height >= MAXHEIGHT){
            height = MAXHEIGHT;
            breadcrumbTop = 0;
        }
        marginTop = ((height-MINHEIGHT)/2)+TOPPADDING + MARGINTOPOFFSET;
        topAlign = height/2;
        footerTop = height-topAlign-FOOTERHEIGHT;
    }     
    
}
function showScreenSize(){
	return null;
}


var qs = window.location.href;
fla = qs.substring(qs.lastIndexOf('?')+1,qs.lastIndexOf('?')+9);


/* DOM */
// Safari DOM workaround by Johnnie Blevins
// http://www.blevins.cx/javascripting/DOMParsing.html
if (!String.prototype.toDocumentFragment) {
    String.prototype.toDocumentFragment = function toDocumentFragment(context) {
        var aRange=document.createRange();
        context= context || document.getElementsByTagName("body")[0];
        aRange.selectNodeContents(context);
        return aRange.createContextualFragment(this);
    }
}

onloadHandlers[onloadHandlers.length] = 'killFlickerOnResize()';
function killFlickerOnResize(){
    var bodyArray = document.getElementsByTagName('body');
    bodyArray[0].style.visibility='visible';
}

try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}


/*cookie redirects*/

var expireOffset = new Date(new Date().getTime()+(180*24*60*60*1000)).toGMTString();

function goLocation(lang) {
    if(lang)
        document.location.href= '/'+lang+'/';
}
function goLangDeeplink(redirURL){
    document.location.href=redirURL;
}
function goDeeplink(redirURL) {
    document.location.href=redirURL;
}
function setCookie(me){
    document.cookie = "lang2="+me+"; expires="+expireOffset+"; path=/;";
}
function setCookieHome(me){
    document.cookie = "lang2="+me+"; expires="+expireOffset+"; path=/;";
    goLocation(me);
}
function openRegionWindow(url){
	window.open(url, '_blank');
	SWFAddress.setValue('/home');
}

function alignElementsGlobal(){
    var BOTTOM_NAV_HEIGHT = 0;
    var WIDTH_OFFSET = 0;
    var leftPosition = 0;
    var topPosition = 0; 
    var newOffsetMaxMid = 1;
        
        if (height >= MAXHEIGHT){
            topPosition = MAXHEIGHT - BOTTOM_NAV_HEIGHT - TOPPADDING - marginTop + newOffsetMaxMid;
        }
        else if (height <= MINHEIGHT){
            topPosition = MINHEIGHT - BOTTOM_NAV_HEIGHT - TOPPADDING - marginTop + FOOTERHEIGHT;
        }
        else{
            topPosition = height - BOTTOM_NAV_HEIGHT - TOPPADDING - marginTop + newOffsetMaxMid;
        }
        leftPosition = LEFTPADDING - marginLeft - WIDTH_OFFSET;
}
onresizeHandlers[onresizeHandlers.length] = 'alignElementsGlobal()';
onloadHandlers[onloadHandlers.length] = 'alignElementsGlobal()';

	
	
function initMicrositeDrawer(all_microsites,model) {
	var appendText = '<ul style="display:none">';
	appendText+= '<li id="preferred-language-copy">Please select your preferred language:</li>';
	$.each(all_microsites, function(key, m) {
	    appendText += '<li>';
	    appendText +='<a href="'+m.url+'">'+m.language+'</a>';
	    appendText +='</li>';
	});
	appendText +='</ul>';
	
	$('.region-link').append(appendText);
	
	$('.region-link li:last').css({'border':'none'});
	
	if (model.toLowerCase()=='m') {
	    $('.region-link li,.region-link li a').css({'color':'#333'});
	}

	$('#micrositeBtn,.region-link ul').unbind('mouseover,mouseleave');
		
	$('#micrositeBtn,.region-link ul').mouseover( 
	    function(e) {
		if ($('.region-link ul').css('display')=='none') {
		    $('.region-link ul').fadeIn('slow');
		}
		if (typeof $('#micrositeBtn').data('mouseleave_bound')==='undefined') {
		    $('#micrositeBtn').data('mouseleave_bound',true);
		    $('.region-link ul,#micrositeBtn').mouseleave( function(event) {
			var btn_offset = $('#micrositeBtn').offset();
			if (event.currentTarget.tagName=="A") {
			    if (event.clientX <= btn_offset.left || event.clientX >= btn_offset.left+200 || event.clientY <= btn_offset.top) {
				$('.region-link ul').fadeOut('fast');
			    }
        }
        else {
			    var list_offset = $('.region-link ul').offset();
			    if (event.clientY <= list_offset.top) {
				return;
			    }
			    else {
				$('.region-link ul').fadeOut('fast');
			    }
			}
		    });
		}
	    }
	);
}
// Choses to display the button and changes the url according to the region and returned url
function getButtonXML(region, model){
	$.ajax({
	    type: "GET",
	    url: 'http://' + window.location.hostname + '/static/global/xml/models/infiniti_ge_region_models.xml',
	    dataType: "xml",
	    success: function (xml){
	
	       
		var reLink = $(xml).find('region[id='+region+']').find('model[name='+model+']').attr("url") || '';
		var microsites = $(xml).find('region[id='+region+']').find('model[name='+model+']').find("microsite");
		var reMicrositeLink = '';
		var micrositeText = '';
	
		if (microsites.length == 1) {
		    reMicrositeLink = microsites[0].attributes.getNamedItem('url').value;
		    micrositeText = microsites[0].attributes.getNamedItem('text').value;
        }
		else if (microsites.length > 1) {
		
		    var all_microsites = Array();
	
		    window.preferredLangFound = false;
		    var preferredLang = document.jsAPI.getPreferredUserLanguage();
	
		    microsites.each( function() {
	
			if (preferredLang == $(this).attr('language')) {
			    reMicrositeLink = $(this).attr('url');
			    micrositeText = $(this).attr('text');
			    window.preferredLangFound = true;
		}	
	
			all_microsites.push({'url':$(this).attr('url'),'text':$(this).attr('text'),'language':$(this).attr('language_display')});
		    });
	
		    if (!window.preferredLangFound) {
			reMicrositeLink = microsites[0].attributes.getNamedItem('url').value;
			micrositeText = microsites[0].attributes.getNamedItem('text').value;
		    }
	
		}
		
		/* not sure why this was overriding the links in infiniti_ge_region_models.xml but taking it out for ig-823		    
		if (region == 'us') {
		    flash = false;
		    for (i=0; i < navigator.plugins.length; i++) {
			plugin = navigator.plugins[i].name;
			if(plugin.indexOf('Flash')==-1){
			    if(!flash){
				flash = false;
			    }
			    } 
			    else {
			    flash = true;
			}
		    };
	
		    if(!flash){
			reLink = "http://www.infinitiusa.com/?dcp=nml.mtl.HMP.infiniticom_brandexperience";
		    }
		}*/
	    
		if (reLink == '' && reMicrositeLink == '') {
		$('#model-detail-box').hide();
			
		} else {
			$('#model-detail-box').show();
			oLink = $('#regionalLink');
	
		    // If the regional link for this model exists, set the href of the first link to the reLink value
		    if (reLink!='') {
			oLink.attr('href',reLink);
		    }
		    if (reLink!='' && reMicrositeLink !='') { // Both regional link and microsite link are present, copy the link and set the href to the reMicrositeLink value
			oLink.after(oLink.clone().attr('href',reMicrositeLink).attr('id','micrositeBtn').css('margin-top','7px').addClass('dark'));
			oLink.next().find('span p').text(micrositeText);
	
			if (typeof all_microsites !='undefined') {
			    initMicrositeDrawer(all_microsites,model);
			}
	
		    }
		    else if (reLink=='' && reMicrositeLink !=''){ // If the regional link doesn't exist, then there is only a microsite link
			oLink.find('span p').text(micrositeText);
			oLink.attr('href',reMicrositeLink).addClass('dark');
	
			if (typeof all_microsites !='undefined') {
			    initMicrositeDrawer(all_microsites,model);
			}
	
		    }

				    
				    //  Not required at this time.
				    //  Omniture: This is to add tracking to the button in models
				    //$('#regionalLink').bind('click', function() {
				    //	omniture('<xsl:value-of select="$pagePath"/>/button','linkTracking');
				    //});	
			    }
		    }
	    });
    }



/* For by Fancybox to create lightbox overlays, and now, so much more. */
jQuery(document).ready(function() {
	
	// This sets the initial 'Visit Infiniti [Region]' link to the correct country information.
	if (!(document.jsAPI.getCookie('region') == null) && !(countryList[document.jsAPI.getCookie('region')] == null)) {
		fluxRegion = document.jsAPI.getCookie('region');
	}
	
	if(fluxRegion){
		
		if (countryList[fluxRegion].toLowerCase()=='infiniti europe') {
		    jQuery("#footer-link").html('<li class="footer-region"><a href="' + countryLinks[fluxRegion] + '">VISIT &nbsp; ' + countryList[fluxRegion] + '</a></li>');
		    jQuery(".region-link").html('<a id="regionalLink" href="' + countryLinks[fluxRegion] + '"><span class="button"><p>VIEW DETAILS AND SPECS</p></span></a>');
		}
		else {
		    jQuery("#footer-link").html('<li class="footer-region"><a href="' + countryLinks[fluxRegion] + '">VISIT &nbsp; INFINITI &nbsp;' + countryList[fluxRegion] + '</a></li>');
		    jQuery(".region-link").html('<a id="regionalLink" href="' + countryLinks[fluxRegion] + '"><span class="button"><p>VIEW DETAILS AND SPECS</p></span></a>');
		}
	}

	// Sets the global navigation to the correct section and sub-section.
	if(activeSection != ''){
		jQuery('#page-section').attr('class', activeSection);
	}

	if(activeSubSection != ''){
		jQuery('#sub-models li').removeClass('nav-selected');
		jQuery('#'+activeSubSection).addClass('nav-selected');
	}

	// This gives the arrow nav the page it is on.
	jQuery("#page-selector-previous a").attr("href", arraySelector(navPageLinksList, navPageList, htmlPagePathSelected, -1));
	jQuery("#page-selector-previous a").mousedown(function(){omniture('/arrow-previous', 'linkTracking');});
	jQuery("#page-selector-next a").attr("href", arraySelector(navPageLinksList, navPageList, htmlPagePathSelected, 1));
	jQuery("#page-selector-next a").mousedown(function(){omniture('/arrow-next', 'linkTracking');});
	
	// swipe gestures to twitter arrow clicks
	if(isIpad){
		jQuery('.wrapper').eq(0).swipe({
			threshold: 100,
			swipeLeft: function(e){
				e.stopPropagation();
				// grab arrow
				var nextArrow = jQuery('#page-selector-next a').eq(0);
				// trigger any tracking on the arrow
				nextArrow.trigger('mousedown');
				// follow link
				window.location.href = nextArrow.attr('href');
			},
			swipeRight: function(e){
				e.stopPropagation();
				// grab arrow
				var previousArrow = jQuery('#page-selector-previous a').eq(0);
				// trigger any tracking on the arrow
				previousArrow.trigger('mousedown');
				// follow link
				window.location.href = previousArrow.attr('href');
			}
		});
	}
	
	// This sets the Fancybox overlay functionality for the 'overlay' class.
	jQuery("a.overlay").fancybox({
		'hideOnOverlayClick': false,
		'scrolling'			:	'auto',
		'autoDimensions'	:	false,
		'autoScale'			:	false,
		'enableEscapeButton':	false,
		'width'				:	984,
		'height'			:	600,
		'speedIn'			:	600, 
		'speedOut'			:	200, 
		'overlayShow'		:	true,
		'overlayOpacity'	:	1,
		'overlayColor'		:	'#000',
		'padding'			:	0,
		'margin'			:	0,
		onClosed: function(){
			resetHash();
			showAdditionalElements();
			$('embed').show();	
		}
	});
	
	jQuery('#footer-about, #footer-sitemap, #footer-privacy, #footer-selector, #footer-contact').bind('click', function() {
		hideAdditionalElements();
		$('embed').hide();
	});
	
	function hideAdditionalElements(){
		$('#fancybox-overlay').css('visibility', 'visible');	
		$('.adeyakacontent').css('visibility','hidden');		
		$('.infinitiworldcontent').css('visibility', 'hidden');	
		$('#fancybox-wrap').css('visibility', 'hidden');			
		setTimeout("$('#fancybox-wrap').css('margin', '0 0 0 0');",500);
		setTimeout("$('#fancybox-wrap').css('visibility', 'visible');",1000);			
					
	}		
	function showAdditionalElements(){
		$('.adeyakacontent').css('visibility','visible');
		$('.infinitiworldcontent').css('visibility', 'visible');
		$('.infinitiworldarchiveArticlescontent').css('visibility', 'visible');
		
		if(currentSection=='featured'){
			$('.infiniti-carousel-container').css('visibility', 'visible');
			$('.infiniti-carousel-text').css('visibility', 'visible');
		}
	}
	
	if(!flash){
		$(".hideFromFlashWrapper").show();	
	}
	
});


function displayToggle(element, displayState){
	
	var oppositeState = (displayState == 'on') ? 'off' : 'on';
	
	jQuery("#" + element + "-" +displayState).show();
	jQuery("#" + element + "-" +oppositeState).hide();
	
	return false;
}

function arraySelector(linksList, list, presentItem, direction) {
	
	var thisPosition = jQuery.inArray(presentItem, list);
	var totalCount = list.length;
	var desiredPosition = thisPosition + direction;
	
	if (desiredPosition < 0) {
		desiredPosition = (totalCount - 1);
		
	} else if (desiredPosition >= totalCount) {
		desiredPosition = 0;
	}
	
	return linksList[desiredPosition];
}


var footerIteration = 0;


function footerAction (location) {
	
	footerStyleHashAction(location);
	
	// Stores the page title of the last non overlay page
	if (footerIteration == 0) {
		previousPageTitle = parent.document.title;
	}
	footerIteration++;

	// Sets title to the correct title of the chosen footer section
	$.ajax({
		type: "GET",
		url: 'http://' + window.location.hostname + '/assembly.xml',
		dataType: "xml",
		success: function (xml){
			var pageTitle = $(xml).find('page[id='+location+']').attr("pageTitle");
			parent.document.title = pageTitle;
		}
	});
	
	// Sets the page title to the last non overlay page back on overlay close
	jQuery('#fancybox-close').bind('click', function() {
		parent.document.title = previousPageTitle;
		footerIteration = 0;
	});	
}

// Footer elements, sets the url # to the specified location and sets the active element style.
function footerStyleHashAction(location, pageTitle){
	
	// Sets the active class around the selected footer element
	var footerSections = {
		'/about/introduction' : 'footer-about',
		'/sitemap' : 'footer-sitemap',
		'/legal' : 'footer-privacy',
		'/country-selector' : 'footer-selector'
	}
	$('#who_we_are').cycle('destroy');
	$('#who_we_are_wrapper').hide();
	$('.wwa_bg').remove();
	
	jQuery.each(footerSections, function(key, value) {
		if (key != location) {
			jQuery("#" + value).removeClass('set-item');
			
		} else {
			jQuery("#" + value).addClass('set-item');
		}
	});
	
	
	// Removes the styling for the selected footer element on close
	jQuery('#fancybox-close').bind('click', function() {
		jQuery("#" + footerSections[location]).removeClass('set-item');
		loadInfinitiTVDefault();
	});	
	
	if (pageTitle !== undefined) {
		parent.document.title = pageTitle + ' - Infiniti Global Official Site'; 
	}
}
/*
function createImages(numImages,typeImages,imgDir){
	if(typeImages==="#model360-int"){
		var type = 'interior';
	}else{
		var type = 'exterior';
	}
	var modelHash = SWFAddress.getValue() + '/360s_'+type+'_Load_Start';
	omniture('/models_360', 'pageTracking', true, modelHash);	
	var startTime = (new Date()).getTime();
	for(jd=1; jd<=numImages; jd++){
		if(jd==numImages){
			$(typeImages).append("<img class='lastImg' src='"+imgDir+jd +".jpg' />");
		}else{
			$(typeImages).append("<img src='"+imgDir+jd +".jpg' />");
		}
	}
	$('.lastImg').load(function(){
		var endTime = (new Date()).getTime();
	    var millisecondsLoading = (endTime - startTime)/1000;
		modelHash = SWFAddress.getValue() + '/360s_'+type+'_Load_End';
		omniture('/models_360', 'pageTracking', true, modelHash, millisecondsLoading);	    
	});

	$('.make360').make360();
	
    
}
*/

videoSupport = document.jsAPI.detectVideoSupport();

$(function(){
	
	//about -> technology overlay -> fixing video links so they appear in html and flash.
	$('#about .popupSubtitle a').each(function(){
	    var temphash = $(this).attr('href').replace('event:','/');
	    var temparray = temphash.split('/');
	    temparray.pop();
	    tempurl = temparray.join('/');
	    tempurl = '/global/en' + tempurl + '#' + temphash;
	    $(this).attr('href',tempurl).attr('style','color:#fff; text-decoration:underline;');
	});
	
	$('.overlay').click(function(){
    	if(videoSupport.html5){
    		if($('#jwcontainer').length != 0){
    			jwplayer("jwcontainer").stop();
    			$('#jwcontainer').hide();
    		}
    		if($('#jwsingle').length != 0){
    			jwplayer("jwcontainersingle").stop();
    			$('#jwsingle').hide();
    		}	
    	}else{
    		$('.htmlplayer-video embed').remove();
    		$('#jwcontainersingle embed').remove();	
    		$('#jwsingle').hide();
    	}
	});
	
	$('.adeyakaNavLink').click(function(){
		if(videoSupport.html5){
			jwplayer("jwcontainersingle").stop();	
		}
		$('#jwsingle').hide();
		$('#jwcontainersingle embed').remove();
	});
	$('.adeyakaNavLinkEnd').click(function(){
		if(videoSupport.html5){
			jwplayer("jwcontainersingle").stop();	
		}
		$('#jwsingle').hide();
		$('#jwcontainersingle embed').remove();
		showNav();
	});
	
	
	$('#jwcontainer_jwplayer_display_icon').live('click',function(){
		omniture('/infiniti-world/infiniti-tv', 'pageTracking', true, SWFAddress.getValue());
	});
	
	$('.eachvid, #jwcontainer').click(function(e){
		
		$('.eachvid').removeClass('current_Video');
		$(this).addClass('current_Video');
		
		getSharingMeta(SWFAddress.getValue());		
		
		e.preventDefault();
		var vidFile = $(this).attr('id');
		var vidHash = $(this).attr('href');
		SWFAddress.setValue(vidHash.replace('#',''));
		omniture('/infiniti-world/infiniti-tv', 'pageTracking', true, SWFAddress.getValue());
		
		if(videoSupport.mp4){
			
			// MP4 support only.
			jwplayer("jwcontainer").remove();
			vidImage = vidFile.replace('mp4','jpg');
			jwplayer("jwcontainer").setup({
				file: vidFile,
				//image: vidImage,
				height: 350, 
				width: 620, 
				skin: "/static/global/jwplayer/glow/glow.xml",				
				events: {
		            onComplete: function(event) {
						$('#jwcontainer_jwplayer_display_icon').css({'background-image':'url(/static/global/jwplayer/glow/display/replayIcon.png)','display':'block'});
		            }
		        }
			});
			jwplayer("jwcontainer").play();
		
		}else if(videoSupport.ogg){
			
			// OGG support only
			jwplayer("jwcontainer").remove();
			vidImage = vidFile.replace('mp4','jpg');
			vidFile = vidFile.replace('mp4','ogv');
			jwplayer("jwcontainer").setup({
				file: vidFile,
				//image: vidImage,
				height: 350, 
				width: 620, 
				skin: "/static/global/jwplayer/glow/glow.xml",				
				events: {
		            onComplete: function(event) {
		                $('#jwcontainer_jwplayer_display_icon').css({'background-image':'url(/static/global/jwplayer/glow/display/replayIcon.png)','display':'block'});
		            }
		        }
			});
			jwplayer("jwcontainer").play();
			
		}else{
	
			$('#jwcontainer').hide();
			$('.htmlplayer-video').html('');
			$('<embed src="' + vidFile + '" width="' + $('.htmlplayer-video').width() + '" height="' + $('.htmlplayer-video').height() + '" autoplay="true" scale="tofit" />').appendTo('.htmlplayer-video');
			$('#atic_email').live('click',function(e){
				$('#at16p, #atie6ifh, #atie6cmifh').css('margin-left','170px');
			});	
			$('#social-email').click(function(){
				setTimeout("$('#at16p, #atie6ifh, #atie6cmifh').css('margin-left','170px');",2000);					
			});
		}
		
	});
		
});

function loadInfinitiTVDefault(){
	
	if(videoSupport.html5){
		$('.htmlplayer-video').css('background-image','url(/static/global/jwplayer/glow/display/playerImage.jpg)');
	}
	
	if(typeof videoList == 'undefined'){
		return false;
	}
	//check for a hash first.
	if(SWFAddress.getValue().replace('/infiniti-world/infiniti-tv/featured','').replace('/infiniti-world/infiniti-tv/models','').replace('/infiniti-world/infiniti-tv/technology','').replace('/infiniti-world/infiniti-tv/tv-spots','').replace('/infiniti-world/infiniti-tv/brand','').replace('/','').length == 0){
		//use the first one in the list.
		
		vidFile = '/static/global/media/swf/' + videoList[0].file;
		vidHash = videoList[0].deeplinkID;
		//need to set this timeout for chrome/safari
		if(videoSupport.html5){
			setTimeout("SWFAddress.setValue(vidHash.replace('#',''));",1000);	
		}else{
			SWFAddress.setValue(vidHash.replace('#',''));
		}

	}else{
		
		var ctr = 0;
		while(videoList.length > ctr){
			if(videoList[ctr].deeplinkID === SWFAddress.getValue()){
				vidFile = '/static/global/media/swf/' + videoList[ctr].file;
			}
			ctr++; 
		}
	
	}
	
	// handle error cases where a video file is not found
	if(typeof vidFile === 'undefined'){
		// first video is used
		vidFile = '/static/global/media/swf/' + videoList[0].file;
		vidHash = videoList[0].deeplinkID;
		
		// set the hash
		if(videoSupport.html5){
			setTimeout("SWFAddress.setValue(vidHash.replace('#',''));",1000);	
		}else{
			SWFAddress.setValue(vidHash.replace('#',''));
		}
	}
	
	getSharingMeta(SWFAddress.getValue());
	omniture('/infiniti-world/infiniti-tv', 'pageTracking', true, SWFAddress.getValue());	    
	
	//set currently playing video to active.
	$('.controls a').each(function(index) {
		if($(this).attr('href') === '#' + SWFAddress.getValue()){
			$(this).addClass('current_Video');
		}else{
			$(this).removeClass('current_Video');
		}
	});
	
	if(videoSupport.mp4){   // MP4 support only.
	
		jwplayer("jwcontainer").setup({
			flashplayer: "/static/global/jwplayer/player.swf",
			file: vidFile, 
			image: vidFile.replace('mp4','jpg'),
			height: 350, 
			width: 620, 
			skin: "/static/global/jwplayer/glow/glow.xml",
			events: {
	            onComplete: function(event) {
	                $('#jwcontainer_jwplayer_display_icon').css({'background-image':'url(/static/global/jwplayer/glow/display/replayIcon.png)','display':'block'});
	            }
	        }

		});
	
	}else if(videoSupport.ogg){   // OGG support only
	
		vidFile = vidFile.replace('mp4','ogv');
		jwplayer("jwcontainer").setup({
			flashplayer: "/static/global/jwplayer/player.swf",
			file: vidFile, 
			image: vidFile.replace('ogv','jpg'),
			height: 350, 
			width: 620, 
			skin: "/static/global/jwplayer/glow/glow.xml",
			events: {
	            onComplete: function(event) {
					$('#jwcontainer_jwplayer_display_icon').css({'background-image':'url(/static/global/jwplayer/glow/display/replayIcon.png)','display':'block'});
	            }
	        }
		});	

	}else{   // NO HTML5 support
			
		$('#jwcontainer').hide();
		$('.htmlplayer-video').html('');
		$('<embed src="' + vidFile + '" width="' + $('.htmlplayer-video').width() + '" height="' + $('.htmlplayer-video').height() + '" autoplay="true" scale="tofit" />').appendTo('.htmlplayer-video');
		$('#atic_email').live('click',function(e){
			$('#at16p, #atie6ifh, #atie6cmifh').css('margin-left','170px');
		});
		$('#social-email').click(function(){
			setTimeout("$('#at16p, #atie6ifh, #atie6cmifh').css('margin-left','170px');",2000);			
		});
	} 
	
	
}


function playSingleVideo(vidFile,vidImage, noRedirect){
	if(typeof originalMetaUrlOverride != 'undefined' && originalMetaUrlOverride){
		$('#jwsingle').attr('rel', originalMetaUrlOverride);
	} else {
		$('#jwsingle').attr('rel', originalMetaUrl);
	}
	hideNav();
	$('.adeyakaarchiveArticlescontent').css('visibility','hidden');
	getSharingMeta(SWFAddress.getValue());
	//omniture('/infiniti-world/infiniti-tv', 'pageTracking', true, SWFAddress.getValue() + '/video');
	document.jsAPI.trackPage(SWFAddress.getValue() + '/video', 'Html', 'media-start');
	
	vidFile = '/static/global/media/swf/' + vidFile;
		
	if(videoSupport.mp4){   // MP4 support only.
		
		jwplayer("jwcontainersingle").setup({
			flashplayer: "/static/global/jwplayer/player.swf",
			file: vidFile, 
			height: 350, 
			width: 620, 
			skin: "/static/global/jwplayer/glow/glow.xml",
			events: {
	            onComplete: function(event) {
					$('#jwcontainer_jwplayer_display_icon').css({'background-image':'url(/static/global/jwplayer/glow/display/replayIcon.png)','display':'block'});
					document.jsAPI.trackPage(SWFAddress.getValue() + '/video', 'Html', 'media-stop');
	            }
	        }
		});
		$('#jwsingle').css({'display':'block','position':'absolute','top':'73px','z-index':'500'});
		$('#bottomGradient, #topGradient').css('z-index','200');
		jwplayer("jwcontainersingle").play();
	
	}else if(videoSupport.ogg){   // OGG support only
		
		vidFile = vidFile.replace('mp4','ogv');
		jwplayer("jwcontainersingle").setup({
			flashplayer: "/static/global/jwplayer/player.swf",
			file: vidFile, 
			height: 350, 
			width: 620, 
			skin: "/static/global/jwplayer/glow/glow.xml",
			events: {
	            onComplete: function(event) {
					$('#jwcontainer_jwplayer_display_icon').css({'background-image':'url(/static/global/jwplayer/glow/display/replayIcon.png)','display':'block'});
					document.jsAPI.trackPage(SWFAddress.getValue() + '/video', 'Html', 'media-stop');
	            }
	        }
		});	
		$('#jwsingle').css({'display':'block','position':'absolute','top':'73px','z-index':'500'});
		$('#bottomGradient, #topGradient').css('z-index','200');
		jwplayer("jwcontainersingle").play();
		
	}else{   // NO HTML5 support
		
		$('#jwsingle').css({'display':'block','position':'absolute','top':'73px','z-index':'500'});
		$('#jwcontainer').hide();
		$('#jwcontainersingle').html('');
		$('<embed src="' + vidFile + '" width="' + $('#jwcontainersingle').width() + '" height="' + $('#jwcontainersingle').height() + '" wmode="opaque" autoplay="true" scale="tofit" />').appendTo('#jwcontainersingle');
		$('.jwsingle_border .closeButton').css({'top':'0','right':'0'});  //ugly hack for ie.
	}
	

	$('#jwsingle .closeButton').click(function(e){
		document.jsAPI.trackLink('click', '/infiniti-world/infiniti-tv', SWFAddress.getValue() + '/video/close_button');
		if(videoSupport.html5){
			jwplayer("jwcontainersingle").stop();	
		}
		$('#jwsingle').hide();
		$('#jwcontainersingle embed').remove();
		$('#copy-container,#page-selector-previous,#page-selector-next').css('visibility','visible');
		
		if(typeof noRedirect == 'undefined'){
			if(SWFAddress.getValue() == $('#jwsingle').attr('rel')){
				SWFAddress.setValue( SWFAddress.getValue().replace('/features/video', '/features/article') );
			} else {
				SWFAddress.setValue( $('#jwsingle').attr('rel') );
			}
		}
		
		e.preventDefault();
	});
	
}

var embedIframePlayer = function(id, vidFile, vidImg){
	if($('#'+id).length == 0){
		return false;
	}
	if(videoSupport.mp4){   // MP4 support only.
		jwplayer(id).setup({
			flashplayer: "/static/global/jwplayer/player.swf",
			file: vidFile, 
			image: vidImg,
			height: 300, 
			width: 620, 
			skin: "/static/global/jwplayer/glow/glow.xml",
			events: {
				onFullscreen: setIframeVideoFullScreen
			}
		}).play();
	}else if(videoSupport.ogg){   // OGG support only
		vidFile = vidFile.replace('mp4','ogv');
		jwplayer(id).setup({
			flashplayer: "/static/global/jwplayer/player.swf",
			file: vidFile, 
			image: vidImg,
			height: 300, 
			width: 620, 
			skin: "/static/global/jwplayer/glow/glow.xml",
			events: {
				onFullscreen: setIframeVideoFullScreen
			}
		}).play();
	}else{   // NO HTML5 support
		var elm = $('#'+id);
		elm.html('');
		$('#videowrapper .video').css({'width':'510px','padding-left':'60px'});
		$('<embed src="' + vidFile + '" width="510" height="' + elm.height() + '" autoplay="true" scale="tofit" />').appendTo('#'+id);
	}
}

var setIframeVideoFullScreen = function(event){
	window.parent.viewIframeVideoFullscreen(this.config.file, this.getState(), this.getPosition());
	this.pause(true);
	return false;
}
var viewIframeVideoFullscreen = function(filepath, state, position){
	$('body').append('<div id="tempVideoContainer"></div>');
	state = state == 'PLAYING' ? true : false;
	
	var playa = jwplayer('tempVideoContainer').setup({
		flashplayer: "/static/global/jwplayer/player.swf",
		file: filepath, 
		height: 300, 
		width: 620, 
		skin: "/static/global/jwplayer/glow/glow.xml",
		events: {
			onFullscreen: function(val){
				if(val.fullscreen === false){
					var pos = this.getPosition();
					var state = this.getState();
					jwplayer('tempVideoContainer').stop();
					$('#tempVideoContainer').remove();
					document.getElementById('fancybox-frame').contentWindow.videoReturnToNormal(pos, state);
				}
			}
		}
	}).setFullscreen(true).seek(position).play(true);
}


/* NEW ENHANCED 360 FOR MODELS PAGES.
 *********************************************/
var spriteVars = {
	'batch_counter': 0,
	'internal_counter':0,
	'total_counter':0,
	'width': 640,
	'height': 360,
	'cssTop':0,
	'visible_img':null,
	'hasLoadedExt':false,
	'hasLoadedInt':false
}
var sprites = new Array();
var modelhash = '';
var startTime = '';

function spriteEnhancedLoad(typeImages){
	type = typeImages === "#model360-int" ? 'interior' : 'exterior';
	var localBatchCounter;
	//create divs first
	if(spriteVars.batch_counter == 0){
		for(var a=0; a < sprites[spriteVars.batch_counter].numImages; a++){
			spriteVars.cssTop = ((spriteVars.height * (a + 1)) - spriteVars.height) -  (((spriteVars.height * (a + 1)) - spriteVars.height) * 2);
			if(a == (sprites[spriteVars.batch_counter].numImages) -1){
				$(typeImages).append('<div id="'+ type+spriteVars.total_counter+'" class="sprite'+' lastImg" style="display:none; background:url('+sprites[spriteVars.batch_counter].img+') no-repeat scroll 0 '+spriteVars.cssTop+'px;"></div>');
				$(typeImages + ' .loading').remove();
				$(typeImages).makeEnhanced360(spriteVars);
			}else{
				$(typeImages).append('<div id="'+type+spriteVars.total_counter+'" class="sprite'+'" style="display:none; background:url('+sprites[spriteVars.batch_counter].img+') no-repeat scroll 0 '+spriteVars.cssTop+'px;"></div>');
			}	
			spriteVars.total_counter++;
		}
	}else if(spriteVars.batch_counter == 2){
		var localBatchCounter = 1;
		var internal_counter = 0;
	
		$('div', typeImages).each(function(i, elm){
				
			spriteVars.cssTop = ((spriteVars.height * (internal_counter + 1)) - spriteVars.height) -  (((spriteVars.height * (internal_counter + 1)) - spriteVars.height) * 2);
			$(this).after('<div id="'+type+spriteVars.total_counter+'" class="sprite'+'" style="display:none; background:url('+sprites[localBatchCounter].img+') no-repeat scroll 0 '+spriteVars.cssTop+'px;"></div>');
			internal_counter++;
			spriteVars.total_counter++;
			
			spriteVars.cssTop = ((spriteVars.height * (internal_counter + 1)) - spriteVars.height) -  (((spriteVars.height * (internal_counter + 1)) - spriteVars.height) * 2);
			$('#'+type+(spriteVars.total_counter - 1)).after('<div id="'+type+spriteVars.total_counter+'" class="sprite'+'" style="display:none; background:url('+sprites[localBatchCounter].img+') no-repeat scroll 0 '+spriteVars.cssTop+'px;"></div>');
			internal_counter++;
			spriteVars.total_counter++;
			
			if(internal_counter == sprites[localBatchCounter].numImages && localBatchCounter != 2){
				localBatchCounter++;
				internal_counter = 0;
			} else if(internal_counter == sprites[localBatchCounter].numImages){
				//lets find out what image we are currently on and recreate the 360 with that image focused on.
				spriteVars.visible_img = $('.make360 div').filter(":visible").attr('id');
				$(typeImages).makeEnhanced360(spriteVars);
			}
		
		});
	}else if(spriteVars.batch_counter == sprites.length - 1){
		var localBatchCounter = 3;
		var internal_counter = 0;
		
		$('div', typeImages).each(function(i, elm){
			spriteVars.cssTop = ((spriteVars.height * (internal_counter + 1)) - spriteVars.height) -  (((spriteVars.height * (internal_counter + 1)) - spriteVars.height) * 2);
			$(this).after('<div id="'+type+spriteVars.total_counter+'" class="sprite'+'" style="display:none; background:url('+sprites[localBatchCounter].img+') no-repeat scroll 0 '+spriteVars.cssTop+'px;"></div>');
			internal_counter++;
			spriteVars.total_counter++;
			
			spriteVars.cssTop = ((spriteVars.height * (internal_counter + 1)) - spriteVars.height) -  (((spriteVars.height * (internal_counter + 1)) - spriteVars.height) * 2);
			$('#'+type+(spriteVars.total_counter - 1)).after('<div id="'+type+spriteVars.total_counter+'" class="sprite'+'" style="display:none; background:url('+sprites[localBatchCounter].img+') no-repeat scroll 0 '+spriteVars.cssTop+'px;"></div>');
			internal_counter++;
			spriteVars.total_counter++;
			
			if(internal_counter == sprites[localBatchCounter].numImages && localBatchCounter != sprites.length - 1){
				localBatchCounter++;
				internal_counter = 0;
			} else if(internal_counter == sprites[localBatchCounter].numImages) {
				spriteVars.visible_img = $('.make360 div').filter(":visible").attr('id');
				$(typeImages).makeEnhanced360(spriteVars);
				var endTime = (new Date()).getTime();
				var millisecondsLoading = (endTime - startTime)/1000;
				modelHash = SWFAddress.getValue() + '/360s_'+type+'_Load_End';
				omniture('/models_360', 'pageTracking', true, modelHash, millisecondsLoading);
				if(type == 'interior'){
					spriteVars.hasLoadedInt = true;
				}else{
					spriteVars.hasLoadedExt = true;
				}
			}
		});
	}
}

var spriteRef = [];
function preloadEnhanced360Images(typeImages,path){
	spriteRef = [];  
	if(path){
		type = typeImages === "#model360-int" ? 'interior' : 'exterior';
		modelHash = SWFAddress.getValue() + '/360s_'+type+'_Load_Start';
		omniture('/models_360', 'pageTracking', true, modelHash);	
		startTime = (new Date()).getTime();
		spriteVars.batch_counter = 0;
		spriteVars.internal_counter = 0;
		spriteVars.total_counter = 0;
		spriteVars.cssTop = 0;
		for(var i=0; i < 9; i++){
			sprites[i] = { numImages:'8', img:path+ i +'.jpg'};
		}
	}
	//now start loading image.
	var sprite = new Image();
	$(sprite).load(function () {
		spriteEnhancedLoad(typeImages);
		if(spriteVars.batch_counter != sprites.length - 1){
			spriteVars.batch_counter++;
			preloadEnhanced360Images(typeImages);
		}else{
			$(typeImages).addClass('loaded');
		}
	}).attr('src', sprites[spriteVars.batch_counter].img);
	spriteRef.push($(sprite));
}


/* OLD REGULAR 360 FOR MODELS PAGES.
 *********************************************/
function createImages(numImages,typeImages,imgDir){
	if(typeImages==="#model360-int"){
		var type = 'interior';
	}else{
		var type = 'exterior';
	}
	var modelHash = SWFAddress.getValue() + '/360s_'+type+'_Load_Start';
	omniture('/models_360', 'pageTracking', true, modelHash);	
	var startTime = (new Date()).getTime();
	for(jd=1; jd<=numImages; jd++){
		if(jd==numImages){
			$(typeImages).append("<img class='lastImg' src='"+imgDir+jd +".jpg' />");
			$('.lastImg').load(function(){
				var endTime = (new Date()).getTime();
			    var millisecondsLoading = (endTime - startTime)/1000;
				modelHash = SWFAddress.getValue() + '/360s_'+type+'_Load_End';
				omniture('/models_360', 'pageTracking', true, modelHash, millisecondsLoading);	  
				$(typeImages + ' .loading').remove();
				$(typeImages).addClass('loaded');
				$(typeImages).make360();				
			});			
		}else{
			$(typeImages).append("<img src='"+imgDir+jd +".jpg' />");
		}
	}	
    
}




/* REDBULL JS
 ******************************************/

var animateCall = "";
$(window).load(function(){

	

	
	//drivers main page animation
	/*driverInfo = function(){	
		$('.redbull-drivers .info-vettel').animate({
			height:'92px'
		},1000, function() {
			$('.info-vettel h2, .info-vettel p').animate({
				right:'0'
			},1500);
			$('.redbull-drivers .info-webber').animate({
				height:'92px'
			},1000,function(){
				$('.info-webber h2, .info-webber p').animate({
					left:'0'
				},1000)
			})
		})
	}*/
	driverInfo = function(){	
		$('.redbull-drivers .info-vettel').animate({
			height:'92px'
		},1000);
		$('.info-vettel h2, .info-vettel p').animate({
				right:'0'
			},1000, function() {	
			$('.redbull-drivers .info-webber').animate({
				height:'92px'
			},1000)
			$('.info-webber h2, .info-webber p').animate({
				left:'0'
			},1000)
		})
	}	
	setTimeout("driverInfo()",500);
	
});

function showFacebookOverlay()
{
	//redbull intro facebook notice animation
	if (SWFAddress.getValue().indexOf('/inspirations/redbull/introduction/features/video') != 0 && !flash){
		$('.introredbull-facebook').animate({height:'110px'}, 2000);
	}else{
		$('.introredbull-facebook').css('height','110px').hide();
	}
}

$(document).ready(function(){
	
	$('#redbull-orbs').cycle({
		fx:'fade',
		timeout:5000
	});
	
	$('#redbull-orbs a').hover(function(){
		$('#redbull-orbs').cycle('pause');
	},function(){
		$('#redbull-orbs').cycle('resume');
	});
	
	$('.both-vettel-link, .both-webber-link, .both-vettel-img, .both-webber-img, .single-webber-link, .single-vettel-link').click(function(e){
		e.preventDefault;
		SWFAddress.setValue($(this).attr('href').replace('#',''));
	});
	
	
	//add the facebook like box on the footer of the page.
	if($('.redbull-introduction').length === 1){
		$('<div class="introredbull-facebook"></div>').prependTo('#social-media-footer');
		
		if(document.jsAPI.getCookie('region') === 'world|en'){
			$('.introredbull-facebook').css({'right':'-107px','background':'url(/static/global/media/images/content/inspirations/redbull/facebooklike2.png)'});
		}
		
		//hack to help with news and events story being pulled for redbull racing homepage.
		var tempVar = $('.news-link .newsEventsTitle').html().replace('<p class="newsEventsTitle>','').replace('</p>','');
		$('.news-link').html('<div class="smlarrow"></div>' + tempVar);
	}
	
	$('.redbull-introduction-overlay a#continue').click(function(){
			$('.redbull-introduction-overlay').hide();
			$('.redbull-introduction').fadeIn();
			showFacebookOverlay();
			document.jsAPI.setCookie('redbull_visited', 'true');
	});
	
	
	//add the correct class to the grid depending on the date.
	setGridStatus(); 
    	
	//2011-season grid tooltip
    $('#redbullgrid .boxbox a').click(function(e){
    	
    	e.preventDefault();
    	//first hide all (incase the mouseout function doesn't get fired)
    	$('.tooltip').hide();
	
	//ie7/ie6 fix for zindex stuff.(otherwise tooltip will be under main nav)
	$('.redbull-bg .content').css('z-index','1000');
    	
    	var tooltipElm = $(this).parent().siblings('.tooltip');
    	var tooltipTop = '-' + ($('.tooltip').outerHeight() - 12 ) + 'px';
        var tooltipLeft = '-' + (($('.tooltip').outerWidth() / 2) - ($(this).outerWidth() / 2)) + 'px';
        
        $(tooltipElm).css({'top' : tooltipTop ,'left' : tooltipLeft });
        $.browser.msie ? $(tooltipElm).show() : $(tooltipElm).fadeIn();
         
        $(this).mouseout(function(){
        	 $(tooltipElm).hide();
		 $('.redbull-bg .content').css('z-index','1');
        });
         
    });  
    
});

function createRaceGrid(){
	
	//grid box animation
	var boxes = $('.boxbox').get();
	var maxLength = boxes.length;
			
	animateCall = function(first){
		if(first)boxes.splice(0, 1);
		var nextID = Math.floor(Math.random() * boxes.length);
		var nextElm = $('#' + $(boxes[nextID]).attr('id'));
		if(boxes.length > 0){
			boxes.splice(nextID, 1);
			nextElm.animate({
				opacity: 'toggle'
			}, 500, null);
			setTimeout("$('#box1').fadeIn(500, animateCall())",50);
		}
	}
	setTimeout("$('#box1').fadeIn(500, animateCall(1))",500);
	
}

function setGridStatus(newServerDate){

	$.get('/currentDate', function(thisData) {
		serverDate = thisData;
		
		if(newServerDate){
			serverDate = newServerDate;
		}	
		//add the correct class to the grid depending on the time.
		var nextRaceSet = false;
		$('#redbullgrid .box').each(function(){
			$(this).find('a').removeClass();  //remove any class first (mostly for QA when resetting the date)
		    var thisCountry = $(this).attr('id');
		    var hasDatePast = datePast(serverDate,redbullRaceStart[thisCountry]);
		    if(thisCountry == 'bahrain'){
		    	$(this).find('a').addClass('cancelled-race');
		    }else if(hasDatePast == 1){
		    	$(this).find('a').addClass('past-race');
		    }
		    if(hasDatePast == 0){
		    	if(!nextRaceSet){
		    		nextRaceSet = true;
		    		$(this).find('a').addClass('next-race');
		    	}
		    }
		});
		
		createRaceGrid();		
		
	});	

}

function datePast(curDate,otherDate){	

	var curDateArr = curDate.split('-');
	var otherDateArr = otherDate.split('-');
	var curDateVar = new Date(curDateArr[0], curDateArr[1], curDateArr[2]);
	var otherDateVar = new Date(otherDateArr[0], otherDateArr[1], otherDateArr[2])
	
	if(otherDateVar <= curDateVar){
		return 1;
	} else if(otherDateVar > curDateVar){
		return 0;
	}

}


var redbullRaceStart = { 
	'bahrain'   : '2011-03-12',
	'australia' : '2011-03-28',
	'malaysia'  : '2011-04-11',
	'china'     : '2011-04-18',
	'turkey'    : '2011-05-09',
	'spain'     : '2011-05-23',
	'monaco'    : '2011-05-30',
	'canada'    : '2011-06-13',
	'europe'    : '2011-06-27',
	'britain'   : '2011-07-11',
	'germany'   : '2011-07-25',
    'hungary'   : '2011-08-01', 
    'belgium'   : '2011-08-29', 
    'italy'     : '2011-09-12',
    'singapore' : '2011-09-26',
    'japan'     : '2011-10-10',
    'korea'     : '2011-10-17',
    'india'     : '2011-10-31',
    'abudhabi'  : '2011-11-14',
    'brazil'    : '2011-11-28'    
}

/* Tracking
 ********************************************/
$(document).ready(function(){
	//INTRODUCTION
	$('#redbull-orbs a').live('click',function(e){		
		var link = $(this).attr('href');
		var rel = $(this).attr('rel');
		var name='Facebok | Pit Crew Challenge | '+rel;
		document.jsAPI.trackLink('exit',name,link);
		window.open(link);
		e.preventDefault();
	});
	$('.redbull-bg .intro-vettel-webber').click(function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/introduction/driverimage';
		document.jsAPI.trackLink('click',name,link);
	});
	$('.redbull-bg .twtr-timestamp').live('click',function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/introduction_social_external_twitter_timestamp';
		document.jsAPI.trackLink('exit',name,link);
	});
	$('.redbull-bg .twtr-reply').live('click',function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/introduction_social_external_twitter_reply';
		document.jsAPI.trackLink('exit',name,link);
	});
	$('.redbull-bg .twtr-rt').live('click',function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/introduction_social_external_twitter_retweet';
		document.jsAPI.trackLink('exit',name,link);
	});
	$('.redbull-bg .twtr-fav').live('click',function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/introduction_social_external_twitter_favorite';
		document.jsAPI.trackLink('exit',name,link);
	});
	$('.redbull-bg .button_facebook_like').live('click',function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/introduction/Facebook_Like';
		document.jsAPI.trackLink('exit',name,link);
	});
	
	
	// PARTNERSHIP
	$('.redbull-bg .rbr-cta').click(function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/cta/redbullracing.com';
		document.jsAPI.trackLink('exit',name,link);
	});
	$('.redbull-bg .rbr-link').click(function(){
		var link = $(this).attr('href');
		var name = 'red_bull_racing/logo/redbullracing.com';
		document.jsAPI.trackLink('exit',name,link);
	});
	$('.redbull-bg .rbr-link-car').click(function(){
		var link = $(this).attr('href');
		var name = 'red_bull_racing/image/redbullracing.com';
		document.jsAPI.trackLink('exit',name,link);
	});
	
	// DRIVERS
	$('.redbull-bg .both-vettel-img').click(function(){
		var link = $(this).attr('href');
		var name='image-red_bull_racing/drivers/sebastian_vettel';
		document.jsAPI.trackLink('click',name,link);
	});
	$('.redbull-bg .both-vettel-link').click(function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/drivers/sebastian_vettel';
		document.jsAPI.trackLink('click',name,link);
	});
	$('.redbull-bg .both-webber-img').click(function(){
		var link = $(this).attr('href');
		var name='image-red_bull_racing/drivers/mark_webber';
		document.jsAPI.trackLink('click',name,link);
	});
	$('.redbull-bg .both-webber-link').click(function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/drivers/mark_webber';
		document.jsAPI.trackLink('click',name,link);
	});
	$('.redbull-bg .single-vettel-link').click(function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/drivers/sebastian_vettel/mark_webber';
		document.jsAPI.trackLink('click',name,link);
	});
	$('.redbull-bg .single-webber-link').click(function(){
		var link = $(this).attr('href');
		var name='red_bull_racing/drivers/mark_webber/sebastian_vettel';
		document.jsAPI.trackLink('click',name,link);
	});	
	

	// 2011SEASON
	$('.boxbox a').click(function(){
		var name = '2011_season-'+$(this).closest('.box').attr('id');
		var link = $(this).attr('href');
		document.jsAPI.trackLink('click',name,link);
	});
	$('.redbull-bg .rbr-link-grid').click(function(){
		var link = $(this).attr('href');
		var name = 'red_bull_racing/grid/redbullracing.com';
		document.jsAPI.trackLink('exit',name,link);
	});
	
	//tracking model page exit links
	$('#model-detail-box #regionalLink').live('click',function(){
		var link = $(this).attr('href');
		document.jsAPI.trackLink('exit',link,link);
	});
	
	
});


