/// Genkan does not use URL hash
var BASE_PATH = '/global/'+ (language == null ? 'en' : language);
var CHINA_HOSTNAME = "global-cn.infiniti.com";
var globalDebug = '';
var hash = window.location.hash.substring(1); // eg "/main/landing"
var path = window.location.pathname.substring(BASE_PATH.length); 
var currentMetaUrl;
var hashCheck;
var isIpad = navigator && navigator.platform && navigator.platform.match(/^(iPad|iPod|iPhone)$/);
var originalMetaUrlOverride = null;
var overlayInfo ={
	'/about/introduction': { id: 'footer-about', title: 'About Infiniti'},
	'/about/safety':{ id: 'footer-about', title: 'Safety'},
	'/about/environment':{ id: 'footer-about', title: 'Environment, Hybrids, Diesel, Electric'},
	'/about/technology':{ id: 'footer-about', title: 'Technology'},
	'/about/brand-history':{ id: 'footer-about',title: 'Brand History'},
	'/sitemap':{ id: 'footer-sitemap', title: 'Site Map'},
	'/legal': { id: 'footer-privacy', title: 'Privacy Policy'},
	'/country-selector':{ id: 'footer-selector', title: 'Country Selector'},
	'/contact':{ id: 'footer-contact', title: 'Contact Us'}
};
var sharingMetaAjax = null, prevSharing, htmlSafe = "", uhtmlSafe = "";
var galleryImage = null;
var HOME_CONST = {
	imageTimeout: 6000,
	videoInterval: 1000,
	imageElapsed: 0
};
var timeoutObj = null;



/////START URL REDIRECTS
//IF WE ARE IN FLASH, LETS MAKE SURE WE CHANGE THE URL TO '/global/en/home' THEN APPEND THE HASH AND REDIRECT. 

var currentQueryString = window.location.href.match(/.+\?([^#]+).+?/);
currentQueryString = currentQueryString ? '?' + currentQueryString[1] : '';

if(flash){
	var flashBasePath = BASE_PATH + '/home'+ currentQueryString;
	if(path != '/home'){		
		window.location = flashBasePath +'#' + hash;
	}else{
		if(hash == '/features/archives'){   //exception for news and events archive, different in html and flash :S
			window.location = flashBasePath +'#/infiniti-world/news-events/archive';		
		}else if(hash == '/contact'){
			window.location = flashBasePath +'#/contact-us';
		}	
	}
}

//IF WE ARE IN HTML, AND HASH IS NOT HOME, CHANGE URL BASED ON HASH.
if(!flash && path === '/home' && hash != '/home'){
	for(var i=0; i < navPageList.length; i++){
		//strip global/en
		var needle = '/' + navPageList[i].split('/').slice(3).join('/');
		if(hash.indexOf(needle) != -1){
			htmlRedirect(needle);	
		}
	}
	if(hash === '/contact-us'){
		window.location = BASE_PATH + '/home'+ currentQueryString +'#/contact';
	}
}else if(!flash && hash.indexOf('/archive/') >= 0){ //special redirect for archives in adeyaka mag.
	window.location = BASE_PATH + '/adeyaka-magazine/lobby/#' + hash;
}

function htmlRedirect(section){
	if(hash == '/infiniti-world/news-events/archive'){  //need to add this since archives are different in flash and html
		window.location = BASE_PATH + section + currentQueryString + '#/features/archives';
	}else if(section.indexOf('/inspirations/cirque-du-soleil') != -1 || 
			 section.indexOf('/inspirations/redbull') != -1 || 
			 section.indexOf('/models/future-vehicles') != -1 || 
			 section.indexOf('/infiniti-world') != -1 || 
			 section.indexOf('/adeyaka-magazine') != -1 ){
		
		if(hash != '/inspirations/redbull/introduction/features/video'){
			var splitHash = hash.replace(/\/[\w-]+\/features\/(article|gallery|video)/,'').split('/');
			var elmInArray = splitHash.length;
			if(elmInArray > 4){
				splitHash.pop();
			}
			var newURL = splitHash.join('/');
		}else{
			var newURL = hash.replace(/\/features\/(article|gallery|video)/,'');
			alert(newURL);
		}		
		if(hash.indexOf('/adeyaka-magazine/archive') != -1){     //for adeyaka archives, there is no page, only an overlay
			newURL = '/adeyaka-magazine/lobby';
		}
		if(hash.indexOf('/adeyaka-magazine/archive/20') != -1 || 
		   hash.indexOf('/inspirations/cirque-du-soleil/introduction/20') != -1 ){  //for adeyaka archived stories, we need to add /featured/article ... in flash it does not have this in the hash.
				hash = hash + '/features/article';
		}
		window.location = BASE_PATH + newURL + currentQueryString + '#' + hash;
	}else if(section.indexOf('/models') != -1){
		var newURL = section;
		window.location = BASE_PATH + newURL + currentQueryString + '#' + hash;
	}	
}
/////END URL REDIRECTS

// set the region cookie if it's empty
if((document.jsAPI.getCookie('region') == 'world|en' && !document.jsAPI.cookiesEnabled) ||
   (document.jsAPI.getCookie('region') == null && document.jsAPI.cookiesEnabled)) {
    checkGeoRegion();
}
$(window).resize(function(){
	if(flash && ($(window).width() > 960 || $(window).height() > 680)){
		$('#social-media-footer').hide();
	}
	$('.wwa_bg').css({height: $('.wrapper').height(), width: $('.wrapper').width()});
});
$(document).resize(function(){
	$('.wwa_bg').css({height: $('.wrapper').height(), width: $('.wrapper').width()});
});
$(window).load(function(){
	$('.wwa_bg').css({height: $('.wrapper').height(), width: $('.wrapper').width()});
})

function checkGeoRegion() {
	var newRegion = getQueryParam("r").toLowerCase();
	newRegion = (newRegion == 'gb') ? 'uk': newRegion; //If user is geolocated to 'gb', point region to 'uk'
    var defaultLang = regionLangDefault[newRegion];

    if (newRegion != "" && defaultLang != null) {
        document.jsAPI.setCookie('region', newRegion + '|' + defaultLang);
    } else if (document.location.hostname == CHINA_HOSTNAME) {
        document.jsAPI.setCookie('region', 'cn|zh');
    } else {
        document.jsAPI.setCookie('region', 'world|en');
    }
}

function globalFlashEmbedCallback(e) {
	if(e.success) {
		swffit.fit("flashcontent", 960, 680);
	} else {
		document.jsAPI.trackPage(path, 'HTML');
		document.jsAPI.setCookie('declinedExpressInstall', 'true', 0); //Flash ExpressInstall declined or failed
		injectFlashUpgradeNotice();
	}
}



function getSharingMeta(hsh){
	var pathKey = "";
	var oldHtmlSafe = uhtmlSafe;
	if(hsh == '' || !hsh){
		htmlSafe = window.top.SWFAddress.getValue();
	} else {
		htmlSafe = hsh;
	}
	uhtmlSafe = htmlSafe.replace("/global/en", "");
	if(htmlSafe.indexOf('/inspirations/redbull/introduction/features/video') == -1){
		htmlSafe = htmlSafe.replace("/global/en", "").replace("/features/article", "").replace("/features/gallery", "").replace("/features/video", "");
	}else{
		htmlSafe = htmlSafe.replace("/features/video", "/video");
	}	
				
	if(oldHtmlSafe == htmlSafe){
		return true;
	}
	
	if(sharingMetaAjax != null){
		sharingMetaAjax.abort();
		sharingMetaAjax = null;
	}
	
	if(oldHtmlSafe.match('/features') == null && SWFAddress.getValue().match('/features') == null){
		$('.social-media-details').hide();
	} else if(hash.match(/\/features\/(article|gallery|video|archives|archive)/) != null) {
		$('#fancybox-frame').contents().find('.social-media-details').hide();
	}
	
	if(hash.indexOf('infiniti-tv')>0){ // video
		pathKey = "deeplink";
	}else if(hash.indexOf('living-luxury/introduction')>0 || hash.indexOf('inspired-performance/introduction')>0){ // intropage
		pathKey = "intropage";
	}else{ // page
		pathKey = "link";
	}
	
	sharingMetaAjax = $.ajax({
		type: "GET",
		url: 'http://' + window.location.hostname + '/sharing-meta.xml?'+ pathKey +'=' + htmlSafe,
		dataType: "xml",
		success: function(xml){
			if(hash.match(/\/features\/(article|gallery|video|archives|archive)/) == null){
				$('.social-media-details').show();
			} else {
				$('#fancybox-frame').contents().find('.social-media-details').show().addClass('ie7-visible');
			}
			fillSharingMeta(xml);
			sharingMetaAjax = null;
		}
	});
}

function fillSharingMeta(xml){
	var hashVal = SWFAddress.getValue();
	var cacheBuster = '?cid=share&v='+Math.floor(Math.random()*1000000);
	if(hashVal in overlayInfo){
		addthis_share.url = 'http://' + window.location.host + window.location.pathname + cacheBuster + '#' + hashVal;
	}else if(hashVal == '/inspirations/redbull/introduction/features/video'){
		var htmlFriendly = hashVal.replace('/features/video', '/video');
		addthis_share.url = 'http://' + window.location.host + '/global/en' + htmlFriendly + cacheBuster + '#' + hashVal;
	}else if(hashVal.indexOf('future-vehicles') != -1 || hashVal.indexOf('cirque-du-soleil') != -1 || hashVal.indexOf('who-we-are') != -1 || hashVal.indexOf('redbull') != -1){
		var htmlFriendly = hashVal.replace('/features/article', '').replace('/features/gallery', '').replace('/features/video', '');
		addthis_share.url = 'http://' + window.location.host + '/global/en' + htmlFriendly + cacheBuster + '#' + hashVal;	
	} else {
		hashVal = SWFAddress.getValue().replace('/features/article', "").replace('/features/gallery', "").replace('/features/video', '');
		addthis_share.url = 'http://' + window.location.host + '/global/en' + hashVal + cacheBuster + '#' + hashVal;	
	}

	addthis_share.title = $(xml).find("meta").find("title").text();
	addthis_share.description = $(xml).find("meta").find("description").text();
	addthis_share.screenshot = $(xml).find("meta").find("img_src").text();
	
/*
	// Hack for Red Bull partnership page... whatever
	if (hashVal.indexOf('redbull/partnership') != -1) {
		document.title = addthis_share.title;
	}
*/
	
	config = addthis_config;
	configname = 'addthis_config';
	if($.browser.msie){
		 config = addthis_config_ie;
		 configname = 'addthis_config_ie';
	};
	loc = window.location.href;
	if(loc.indexOf("lightbox")>0){
		addthis_config_ie.ui_hover_direction = 0;
	}
	
	var href_fbook = 'http://api.addthis.com/oexchange/0.8/forward/facebook/offer?url=' + escape(addthis_share.url);
	href_fbook += '&title=' + addthis_share.title;
	
	$('.social-media-details .social-icon.facebook').attr('href', href_fbook).unbind('click').bind('click', function(){
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'facebook');
	});	
}

function rewriteUrl(useSWFAddress){	
	hash = window.location.hash.substring(1); // eg "/main/landing"
	path = window.location.pathname.substring(BASE_PATH.length); 
	
	if(hash != '' && hash.match(/^\//) == null) {
		hash = '/' + hash;
		//window.location = '#' + hash;
		return '#' + hash;
	}
	
	if(path.charAt(path.length-1) == '/') // strip trailing slash
		path = path.substring(0, path.length-1);
	
	if(hash != '' && hash != path) {
		var newURL = BASE_PATH + hash;
	
		if(debugMode)alert('hash: '+hash+', path: '+path+', redirecting to: '+newURL);
		//window.location = newURL;
		return BASE_PATH + hash;
	} else if(hash == '' && window.location.pathname.match(BASE_PATH)) {
		if((document.jsAPI.getCookie('region') == 'world|en' && !document.jsAPI.cookiesEnabled) ||
				(document.jsAPI.getCookie('region') == null && document.jsAPI.cookiesEnabled)) {
			checkGeoRegion();
				}
	
				//window.location = '#'+path;
				if(useSWFAddress)
					SWFAddress.setValue(path);
				return '#'+path;
	}else{
		return window.location.pathname;
	}
}

if(flash){
	rewriteUrl(true);
}

function showNav() {
	if(SWFAddress.getValue().indexOf('adeyaka')!=-1 && SWFAddress.getValue().indexOf('archive')!=-1){
		$('.adeyakaarchiveArticlescontent').css('visibility','visible');
		return false;
	}
	if(SWFAddress.getValue().indexOf('adeyaka')!=-1 && SWFAddress.getValue().indexOf('archive')==-1){
		$('#page-selector-previous, #page-selector-next, #adeyaka_lobby_carousel, #adeyaka_lounge_carousel, #adeyaka_gallery_carousel, .adeyakacontent, #fancybox-wrap, #content, .infinitiworldarchiveArticlescontent, .infiniti-carousel-container, .infiniti-carousel-text, .infiniti-carousel-text-adeyaka, .infinitiworldcontent, #copy-container, .adeyakaarchiveArticlescontent, .flux').css('visibility','visible');
	}
    if (SWFAddress.getValue().indexOf('archive')==-1) {
        $('#page-selector-previous, #page-selector-next, #adeyaka_lobby_carousel, #adeyaka_lounge_carousel, #adeyaka_gallery_carousel, .adeyakacontent, #fancybox-wrap, #content, .infinitiworldarchiveArticlescontent, .infiniti-carousel-container, #lobby, #ipad, #gallery, #lounge, .infiniti-carousel-text, .infinitiworldcontent, #copy-container, .adeyakaarchiveArticlescontent, #infiniti-carousel-text, .flux').css('visibility','visible');
    }
    else {
        $('#page-selector-previous, #page-selector-next, #fancybox-wrap, #content, .infinitiworldarchiveArticlescontent, .infinitiworldcontent, #copy-container, #infiniti-carousel-text, .flux').css('visibility','visible');
    }
};

function hideNav() {
	if($('#jwsingle').length > 0){
		jwplayer("jwcontainersingle").stop();
	}	
	if(!videoSupport.html5){
		$('#jwcontainersingle').html('');
	}
	$('#jwsingle').hide();
	var minScreenHeight = 798;
	var screenHeight = $(window).height();
	var offset = (screenHeight >= minScreenHeight) ? 13 : 13;
	
	$('#fancybox-wrap').css('margin', offset+'px 0 0 0');
	$('#page-selector-previous, #page-selector-next, #adeyaka-carousel-container, #adeyaka_lobby_carousel, #infiniti-carousel-text, #adeyaka_lounge_carousel, #adeyaka_gallery_carousel, .adeyakacontent, #fancybox-overlay, .infinitiworldarchiveArticlescontent, .infiniti-carousel-container, #lobby, #ipad, #gallery, #lounge, .infiniti-carousel-text, .infiniti-carousel-text-adeyaka, .infinitiworldcontent, #copy-container, .adeyakaarchiveArticlescontent, .flux').css('visibility', 'hidden');	 	
	if($.browser.msie && $.browser.version == '6.0'){
		$('#fancybox-wrap').css('margin', '22px 0 0 0');
	}
	setTimeout("$('#fancybox-wrap').css('visibility', 'visible');",1000);							
};

//window.location = rewriteUrl(true);

//Carousel stuff	
	function swap(id1, id2, parent1, parent2, hashlocation){
		$(('#'+parent1+' div:not(.articleOptions), #'+parent2+' div:not(.articleOptions)').replace(/\//gi, '\\/')).hide();
		$(('#'+id1+', #'+id2).replace(/\//gi, '\\/')).fadeIn();
	}
	
	function mycarousel_getItemHTML(item)
	{
        if (typeof(item)!== 'undefined') {
            return '<img onMouseOver="'+item.onMouseOver+'" onClick="'+item.onClick+'" id="carouselImage'+item.id+'" src="' + item.url + '" class="'+item.class_name+'" width="131" height="64" />';
        }
        else {
            return false;
        }
	};
	
	function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt)
	{
	    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[carousel.index(i, mycarousel_itemList.length) - 1]));
		$('[jcarouselindex='+(carousel.first+1)+']').find('img').css('border', '1px solid #fff').end().siblings().find('img').css('border', '1px solid #555')
	};

	function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt){  carousel.remove(i); };
	
	function mycarousel_initCallback(carousel) {
		offset = carouselimages[SWFAddress.getPath()];
		items = mycarousel_itemList.length;
		
		// swipe gestures for ipad
		if(isIpad){
			jQuery('.jcarousel-clip').eq(0).swipe({
				threshold: 100,
				swipeLeft: function(e){
					e.stopPropagation();
					jQuery('.jcarousel-next').eq(0).trigger('click');
				},
				swipeRight: function(e){
					e.stopPropagation();
					jQuery('.jcarousel-prev').eq(0).trigger('click');
				}
			});
		}
		
		// previous and next arrows
		jQuery('.jcarousel-prev').bind('click', function() {
			if(!$('#mycarousel').data('jcarousel').animating){
				offset = offset != 1 ? offset - 1 : items;
				SWFAddress.setValue(swap_hl[offset]);
			}
		});
		jQuery('.jcarousel-next').bind('click', function() {
			if(!$('#mycarousel').data('jcarousel').animating){
				offset = offset != items ? offset + 1 : 1;
				SWFAddress.setValue(swap_hl[offset]);
			}
		});
		
		oldHash = window.location.hash.substring(1);
		SWFAddress.setValue(swap_hl[offset]);
	};	
	
	function scrollTo(i, noScroll){
		var car = $('#mycarousel').data('jcarousel');
		if(!car){ return false; }
				
		var correctVal = $('#carouselImage'+i+', #carouselImageneCarousel'+i).parents('li').attr('jcarouselindex') || i;
		if(!noScroll){	car.scroll(correctVal-1);	}

		if(typeof swap_arg == 'undefined'){
			swap(swap_alt1[i], swap_alt2[i], swap_parent1[i], swap_parent2[i], swap_hl[i]);
		} else {
			changeNewsArticle(i, swap_arg[i], null);
			swap_hl = swap_arg;
		}
		$('#infiniti-carousel-text').text(articleTitles[swap_hl[i]]);
		window.document.title = pageTitles[i];
			
		getSharingMeta(swap_hl[i]);
		originalMetaUrl = swap_hl[i];
		
		//IG-925 fix
		//if(swap_hl[i] != oldHash){
			omniture(swap_hl[i]);
		//}
		
		offset = i;
		
		showNav();	

	}
	function manageCarousel(elementID, updateHash){
		var car = $('#mycarousel').data('jcarousel');
		selected = $('#'+elementID).parent().attr('jcarouselindex');
		
		if(car.first == selected){ jQuery('.jcarousel-prev').trigger("click"); }
		if(car.last == selected){ jQuery('.jcarousel-next').trigger("click"); }
	}
	
	
function footerBackButtonIntegration(){
	var pathNames = SWFAddress.getPathNames();
	var coreSection = ((pathNames[0] == "home" || pathNames[0] == "adeyaka-magazine" || pathNames[0] == "infiniti-world") &&(SWFAddress.getValue().match(/\/features\/(article|gallery)/)==null) && pathNames[1] != 'who-we-are');
	var isArchive = (pathNames[0]=='features' && pathNames[1]=='archives');
	var isModels = pathNames[0] == "models" && SWFAddress.getValue().match(/\/features\/(article|gallery|video)/)==null;
	var isInspirations = pathNames[0] == "inspirations" && SWFAddress.getValue().match(/\/features\/(article|gallery|video)/)==null;
    if(coreSection || isArchive || isModels || isInspirations)
    {	
		if(jQuery.fancybox){
			jQuery.fancybox.close();
			$('.wwa_bg').remove();
		}
        if (SWFAddress.getValue().indexOf('archive')==-1) {
            showNav();
        }
    }
    
}

/* Using SWFAddress for Social Sharing */
SWFAddress.onChange = function(e){
	var isInIFrame = (window.location != window.parent.location) ? true : false;
	hash = SWFAddress.getValue(); 
	path = SWFAddress.getBaseURL().split(BASE_PATH)[1];
    var pathNames = SWFAddress.getPathNames();
    if (pathNames.length > 0) {
        var overValue = pathNames[0].toLowerCase();
    }
    


	getSharingMeta();
		
	htmlSafe = "" + SWFAddress.getValue() + "";
	if(htmlSafe.indexOf('/global/en')==0){
		htmlSafe = htmlSafe.replace("/global/en", "");
	};
	
	//cursor handling for fancybox
	startCursor = function(){ $('body').css('cursor', 'wait'); }
	endCursor = function(){ $('body').css('cursor', 'auto'); }
	//end cursor handling


	//adding rbr link to news and events section based on hash
	if(hash.indexOf('racing') != -1 || hash.indexOf('vettel') != -1 || hash.indexOf('rbr') != -1 || hash.indexOf('-gp') != -1){
		$('.newsTopLinks #redbullLink').show();
	}else{
		$('.newsTopLinks #redbullLink').hide();
	}
	
	//adding new temporary JX links to microsite for specific regions only.
	/*
		if(this is a jx story in the carousel && this users region has a jx microsite in it IE: USA)
			$('.newsTopLinks #newJXLink').show();
		}else{
			$('.newsTopLinks #newJXLink').hide();
		}
	*/

	if(SWFAddress.getValue().indexOf('/features/threesixty/exterior') != -1 || SWFAddress.getValue().indexOf('/features/threesixty/interior') != -1){
		hideNav();
	} 

	
	//adding conditions for redbull racing drivers panels.
	if(SWFAddress.getValue() == '/inspirations/redbull/drivers/webber' && !flash){
		$('.redbull-drivers-vettel, .redbull-drivers').hide();
		$('.redbull-drivers-webber').fadeIn();
		$('.redbull-driver-webber-content .scrollbar-drivers').tinyscrollbar({ sizethumb:32 });
		socialHash = SWFAddress.getValue() + '/social_share_button';
		omniture(hash);
	}else if (SWFAddress.getValue() == '/inspirations/redbull/drivers/vettel' && !flash){
		$('.redbull-drivers-webber, .redbull-drivers').hide();
		$('.redbull-drivers-vettel').fadeIn();
		$('.redbull-driver-vettel-content .scrollbar-drivers').tinyscrollbar({ sizethumb:32 });
		socialHash = SWFAddress.getValue() + '/social_share_button';
		omniture(hash);
	}else if (SWFAddress.getValue() == '/inspirations/redbull/drivers' && !flash){
		$('.redbull-drivers-webber, .redbull-drivers-vettel').hide();
		$('.redbull-drivers').fadeIn();
		socialHash = SWFAddress.getValue() + '/social_share_button';
		omniture(hash);
	}else if (SWFAddress.getValue().indexOf('/inspirations/redbull/introduction/features/video')==0 && !flash){
		$('.redbull-introduction, .introredbull-facebook').hide();
		playSingleVideo($('#jwsingle').attr('video'), '', true);
		$('#jwsingle').show();
		$('.closeButton').bind('click',function(){
			SWFAddress.setValue('/inspirations/redbull/introduction');
		});
		socialHash = SWFAddress.getValue() + '/social_share_button';
		document.jsAPI.trackPage(hash,'Html');
	}else if (SWFAddress.getValue().indexOf('/inspirations/redbull/introduction')==0 && !flash){
//		if(document.jsAPI.getCookie('redbull_visited') == 'true'){
			$('.redbull-introduction').fadeIn();
			showFacebookOverlay();
/*		} else {
			$('.redbull-introduction-overlay').fadeIn();
		}*/
		$('#jwsingle').hide();
		socialHash = SWFAddress.getValue() + '/social_share_button';
	}
	
	//hide the facebook like box on redbull pages when overlays are opened.
	if (SWFAddress.getValue().indexOf('/inspirations/redbull/introduction')!=0){
		$('.introredbull-facebook').hide();
	}
	
//adding condition for new /inspirations/cirque-du-soleil/introduction
	if(SWFAddress.getValue().indexOf('inspirations/cirque-du-soleil/introduction')==1 && !flash){
		if(SWFAddress.getValue().indexOf('features')!=-1 && !flash){
			
			var url = '/global/en'+hash.replace(/\/features\/(article|gallery)/,'')+'?r=CA&display=lightbox';
			url += hash.indexOf('/features/gallery') != -1 ? '&gallery=true' : '';
			var fake_fancybox = $('<a href="'+url+'" style="display:none">test</a>').fancybox({
				'hideOnOverlayClick': false, type: 'iframe', 'autoDimensions' : false, 'autoScale' : false, 'enableEscapeButton': false, width: 890, height: 375, padding: 0, overlayOpacity: 0, showCloseButton: false,	
				onClosed: function(){
					SWFAddress.setValue('/inspirations/cirque-du-soleil/introduction');
				}
			});
			
			if ($('#fancybox-frame').length) {
                omniture(hash);
                if (hash.indexOf('/features/article')!=-1) {
                    $('#fancybox-frame')[0].contentWindow.showArticle();
                }
                else if (hash.indexOf('/features/gallery')!=-1) {
                    $('#fancybox-frame')[0].contentWindow.showGallery();
                }
                hideNav();
            }
            else {
                fake_fancybox.click();
            }
			
		}
	}else if($('.cirquepanelcontentheader').length > 0 && !isInIFrame){     //adding condition for new /inspirations/cirque-du-soleil/featured
			if(typeof carouselimages != 'undefined'){
				pos = carouselimages[hash == '/' ? path : hash];
			}
		if(hash.match(/\/features\/(article|gallery|video)/) !== null){
				 
			originalMetaUrlOverride = hash;
			var url = '/global/en'+hash.replace(/\/features\/(article|gallery|video)/,'')+'?r=CA&display=lightbox';
			
			url += hash.indexOf('/features/gallery') != -1 ? '&gallery=true' : '';
			url += hash.indexOf('/features/video') != -1 ? '&video=true' : '';
			
			var fake_fancybox = $('<a href="'+url+'" style="display:none">test</a>').fancybox({
				'hideOnOverlayClick': false, 
				type: 'iframe', 
				'autoDimensions' : false, 
				'autoScale' : false, 
				'enableEscapeButton': false, 
				width: 890, 
				height: 375, 
				padding: 0, 
				overlayOpacity: 0, 
				showCloseButton: false,	
				onStart: startCursor,
				onCancel: endCursor,
				onClosed: function(){
					 SWFAddress.setValue(SWFAddress.getValue().replace('/features/article', '').replace('/features/gallery', '').replace('/features/video', ''));
					 originalMetaUrlOverride = null;
				}
			});
			if ($('#fancybox-frame').length > 0) {
				omniture(hash);
				if (hash.indexOf('/features/article')!=-1) {
					$('#fancybox-frame')[0].contentWindow.showArticle();
				}
				else if (hash.indexOf('/features/gallery')!=-1) {
					$('#fancybox-frame')[0].contentWindow.showGallery();
				}
				else if (hash.indexOf('/features/video')!=-1) {
					$('#fancybox-frame')[0].contentWindow.showVideo();
				}
			}
			else {
				$('body').css('cursor', 'wait');
				fake_fancybox.click();
			}
		} else if(typeof pos != 'undefined'){ 
			//remove TRUE when we have more items in Carousel
			//scrollTo(pos,true);
			scrollTo(pos);
			 
		} else {
			originalMetaUrlOverride = null;
		}
	}else if(hash.indexOf('/inspirations/redbull/drivers') == 0 && !isInIFrame && !flash){     //adding condition for new /inspirations/redbull/drivers overlay
				
		if(typeof carouselimages != 'undefined'){
			pos = carouselimages[hash == '/' ? path : hash];
		}
		
		if(hash.match(/\/features\/(article|gallery|video)/) !== null){
			
			//hide content
			$('.flux').hide();
			
			originalMetaUrlOverride = hash;
			var url = '/global/en'+hash.replace(/\/features\/(article|gallery|video([0-9]?))/,'')+'?r=CA&display=lightbox';
			
			url += hash.indexOf('/features/gallery') != -1 ? '&gallery=true' : '';
			url += hash.indexOf('/features/video') != -1 ? '&video=true' : '';
			
			var fake_fancybox = $('<a href="'+url+'" style="display:none">test</a>').fancybox({
				'hideOnOverlayClick': false, 
				type: 'iframe', 
				'autoDimensions' : false, 
				'autoScale' : false, 
				'enableEscapeButton': false, 
				width: 890, 
				height: 375, 
				padding: 0, 
				overlayOpacity: 0, 
				showCloseButton: false,	
				onStart: startCursor,
				onCancel: endCursor,
				onClosed: function(){
					 SWFAddress.setValue(SWFAddress.getValue().replace(/\/features\/(article|gallery|video([0-9]?))/,''));
					 originalMetaUrlOverride = null;
				}
			});
			if ($('#fancybox-frame').length > 0) {
				omniture(hash);
				if (hash.indexOf('/features/article')!=-1) {
					$('#fancybox-frame')[0].contentWindow.showArticle();
				}
				else if (hash.indexOf('/features/gallery')!=-1) {
					$('#fancybox-frame')[0].contentWindow.showGallery();
				}
				else if (hash.indexOf('/features/video')!=-1) {
					$('#fancybox-frame')[0].contentWindow.showVideo();
				}
			}
			else {
				$('body').css('cursor', 'wait');
				fake_fancybox.click();
			}
		} else if(typeof pos != 'undefined'){ 
			//remove TRUE when we have more items in Carousel
			//scrollTo(pos,true);
			scrollTo(pos);
			 
		} else {
			originalMetaUrlOverride = null;
		}
	}else if($('.futurevehiclescontentheader').length > 0 && !isInIFrame){         //future vehicles overlay
			if(hash.match(/\/features\/(article|gallery|video)/) !== null){
				originalMetaUrlOverride = hash;
				var url = '/global/en'+hash.replace(/\/features\/(article|gallery|video)/,'')+'?r=CA&display=lightbox';
				url += hash.indexOf('/features/gallery') != -1 ? '&gallery=true' : '';
				url += hash.indexOf('/features/video') != -1 ? '&video=true' : '';
				var fake_fancybox = $('<a href="'+url+'" style="display:none"></a>').fancybox({
					'hideOnOverlayClick': false, 
					type: 'iframe', 
					'autoDimensions' : false, 
					'autoScale' : false, 
					'enableEscapeButton': false, 
					width: 890, 
					height: 375, 
					padding: 0, 
					overlayOpacity: 0, 
					showCloseButton: false, 
					onStart: startCursor,
					onCancel: endCursor,
					onClosed: function(){
						SWFAddress.setValue(SWFAddress.getValue().replace(/\/[^\/]+\/features\/article/, '').replace(/\/[^\/]+\/features\/gallery/, '').replace(/\/[^\/]+\/features\/video/, ''));
						originalMetaUrlOverride = null;
					}
				});
				
				
				if ($('#fancybox-frame').length > 0) {
					omniture(hash);
					if (hash.indexOf('/features/article')!=-1) {
						$('#fancybox-frame')[0].contentWindow.showArticle();
					}
					else if (hash.indexOf('/features/gallery')!=-1) {
						$('#fancybox-frame')[0].contentWindow.showGallery();
					}
					else if (hash.indexOf('/features/video')!=-1) {
						$('#fancybox-frame')[0].contentWindow.showVideo();
					}
				}
				else {
					fake_fancybox.click();
				}
			}
		}
		//inspirations/redbull/partnership
		else if(hash.indexOf('/inspirations/redbull/partnership') == 0 && !isInIFrame && !flash){
			if(hash.match(/\/features\/(article|gallery|video)/) !== null){
				originalMetaUrlOverride = hash;
				var url = '/global/en'+hash.replace(/\/features\/(article|gallery|video)/,'')+'?r=CA&display=lightbox';
				url += hash.indexOf('/features/gallery') != -1 ? '&gallery=true' : '';
				url += hash.indexOf('/features/video') != -1 ? '&video=true' : '';
				var fake_fancybox = $('<a href="'+url+'" style="display:none"></a>').fancybox({
					'hideOnOverlayClick': false, 
					type: 'iframe', 
					'autoDimensions' : false, 
					'autoScale' : false, 
					'enableEscapeButton': false, 
					width: 890, 
					height: 375, 
					padding: 0, 
					overlayOpacity: 0, 
					showCloseButton: false, 
					onStart: startCursor,
					onCancel: endCursor,
					onClosed: function(){
						SWFAddress.setValue(SWFAddress.getValue().replace(/\/[^\/]+\/features\/article/, '').replace(/\/[^\/]+\/features\/gallery/, '').replace(/\/[^\/]+\/features\/video/, ''));
						originalMetaUrlOverride = null;
					}
				});
				
				
				if ($('#fancybox-frame').length > 0) {
					omniture(hash);
					if (hash.indexOf('/features/article')!=-1) {
						$('#fancybox-frame')[0].contentWindow.showArticle();
					}
					else if (hash.indexOf('/features/gallery')!=-1) {
						$('#fancybox-frame')[0].contentWindow.showGallery();
					}
					else if (hash.indexOf('/features/video')!=-1) {
						$('#fancybox-frame')[0].contentWindow.showVideo();
					}
				}
				else {
					fake_fancybox.click();
				}
			}
		}
	else if(!$('#mycarousel').length && !flash && !isInIFrame){
		if(hash.match(/\/features\/(article|gallery|archives)/) !== null){
			originalMetaUrlOverride = hash;
			var url = '/global/en'+hash.replace(/\/features\/(article|gallery)/,'')+'?r=CA&display=lightbox';
			url += hash.indexOf('/features/gallery') != -1 ? '&gallery=true' : '';
			var fake_fancybox = $('<a href="'+url+'" style="display:none">test</a>').fancybox({
				'hideOnOverlayClick': false, 
				type: 'iframe', 
				'autoDimensions' : false, 
				'autoScale' : false, 
				'enableEscapeButton': false, 
				width: 890, 
				height: 375, 
				padding: 0, 
				overlayOpacity: 0, 
				showCloseButton: false,
				onStart: startCursor,
				onCancel: endCursor,
				onClosed: function(){
					originalMetaUrlOverride = null;
                    if ( SWFAddress.getValue().indexOf('archive')==-1) {
                        SWFAddress.setValue(SWFAddress.getValue().replace('/features/article', '').replace('/features/gallery', '').replace('/features/video', ''));
                    }
                    else {
						if(hash.indexOf('adeyaka') == -1){
							SWFAddress.setValue('/features/archives');
						} else {
							SWFAddress.setValue('/adeyaka-magazine/archive');
						}
                    }
				}
			});

            if (hash.indexOf('/features/archives')==-1) {

                if ($('#fancybox-frame').length) {
                    omniture(hash);
                    if (hash.indexOf('/features/article')!=-1) {
                        $('#fancybox-frame')[0].contentWindow.showArticle();
                    }
                    else if (hash.indexOf('/features/gallery')!=-1) {
                        $('#fancybox-frame')[0].contentWindow.showGallery();
                    }
                }
                else {
                    fake_fancybox.click();
                }
            }
		}

	}
	
	else if($('#mycarousel').length && !isInIFrame){
		if(typeof carouselimages != 'undefined'){
		pos = carouselimages[hash == '/' ? path : hash];
		}
		if(typeof pos != 'undefined'){ 
			scrollTo(pos);
		} else if(hash.match(/\/features\/(article|gallery|archives)/) !== null){
			originalMetaUrlOverride = hash;
			
			if($('#jwsingle:visible').length > 0 && videoSupport.html5){
				jwplayer("jwcontainersingle").stop();	
			}
			
			var url = '/global/en'+hash.replace(/\/features\/(article|gallery)/,'')+'?r=CA&display=lightbox';
			
            
			url += hash.indexOf('/features/gallery') != -1 ? '&gallery=true' : '';
			
			var fake_fancybox = $('<a href="'+url+'" style="display:none">test</a>').fancybox({
				'hideOnOverlayClick': false, 
				type: 'iframe', 
				'autoDimensions' : false, 
				'autoScale' : false, 
				'enableEscapeButton': false, 
				width: 890, 
				height: 375, 
				padding: 0, 
				overlayOpacity: 0, 
				showCloseButton: false,
				onStart: startCursor,
				onCancel: endCursor,
				onClosed: function(){
					originalMetaUrlOverride = null;
                    if ( SWFAddress.getValue().indexOf('archive')==-1) {
                        SWFAddress.setValue(SWFAddress.getValue().replace('/features/article', '').replace('/features/gallery', ''));
                    }
                    else {
                       if(hash.indexOf('adeyaka') == -1){
							SWFAddress.setValue('/features/archives');
						} else if(hash.indexOf('video') == -1) {
							SWFAddress.setValue('/adeyaka-magazine/archive');
						}
                    }
				}
			});

            if (hash.indexOf('/features/archives')==-1) {

                if ($('#fancybox-frame').length) {
                    omniture(hash);
                    if (hash.indexOf('/features/article')!=-1) {
                        $('#fancybox-frame')[0].contentWindow.showArticle();
                    }
                    else if (hash.indexOf('/features/gallery')!=-1) {
                        $('#fancybox-frame')[0].contentWindow.showGallery();
                    }
                }
                else {
                    fake_fancybox.click();
                }
            }
		}
	}

	
	if((hash != null)&&(hash != '/')){
		footerBackButtonIntegration();

        if ( (hash=='/features/featured-articles'||hash.indexOf('archive')==-1) && ((SWFAddress.getValue().match(/\/features\/(article|gallery)/)==null && document.getElementById('featuredArticles') !== null))) {
            if (jQuery.inArray(overValue,['about','sitemap','legal','country-selector','contact']) == -1) {
                showFeaturedArticles();
            }
            // If the current news article id is 1 (for example, on initial page load), activate the first news article.
            // This fixes the issue of loading #/features/featured-articles with no news story being selected.

            if (currentNewsArticleId == 1) {
                scrollTo(1);
            }
        	//this sets the featured article link in the subnav for infiniti-world to current default story
            if(hash.indexOf('/features/featured-articles') == 0){
            	var tempFeature = $('#sub-world #world-news').attr('href').replace('/global/en/infiniti-world/news-events/#/infiniti-world/news-events/','');
            	SWFAddress.setValue('/infiniti-world/news-events/'+tempFeature);
        	}
        }
        if ( (hash.indexOf('archive')==-1) && ((SWFAddress.getValue().match(/\/features\/(article|gallery)/)==null && $('#lobby, #ipad, #gallery, #lounge').length>0))) {
            if (jQuery.inArray(overValue,['about','sitemap','legal','country-selector','contact']) == -1) {
                hideAdeyakaArticleArchive();
            }
        }
		if (hash.indexOf('/adeyaka-magazine') != -1) {
				//set proper top nav
				if(hash.indexOf('archive') == -1){
					$('#articleArchiveLink').removeClass('selected-subnav');
					if(hash.indexOf('/adeyaka-magazine/lobby') != -1){
						$('#lobbyLink').addClass('selected-subnav');
					}
					if(hash.indexOf('/adeyaka-magazine/lounge') != -1){
						$('#loungeLink').addClass('selected-subnav');
					}
					if(hash.indexOf('/adeyaka-magazine/gallery') != -1){
						$('#galleryLink').addClass('selected-subnav');
					}
					if(hash.indexOf('/adeyaka-magazine/ipad') != -1){
						$('#iPadLink').addClass('selected-subnav');
					}
				}
			}
		
		if(hash.indexOf('infiniti-tv') != -1){
			loadInfinitiTVDefault()
		}

		if(hash != path){
			if(pathNames.length > 0){

                if (hash=='/features/archives') {
                    $('.infiniti-carousel-container').css('visibility', 'hidden');
                    $('.infiniti-carousel-text').css('visibility', 'hidden');
                    showArticleArchive();
                }
				if (hash.indexOf('/adeyaka-magazine') != -1) {
					if(hash.indexOf('/archive') != -1 && (hash.indexOf('/features') == -1) && $('#jwsingle:visible').length != 0){
						showAdeyakaArticleArchive();
						$('.adeyakaarchiveArticlescontent').css('visibility','hidden');
						return true;
					} else if(hash.indexOf('/archive') != -1 && (hash.indexOf('/features/video') != -1) ){
						var id = SWFAddress.getPathNames().slice(0, 3).join('/');
						$.ajax({
								url: '/static/global/xml/' + SWFAddress.getPathNames().slice(0, 3).join('/') + '.xml', 
								success: function(data){
									var path = $('page[id="/'+ id + '/video"] videobox', data).attr('filepath');
									if(path != ''){
										playSingleVideo(path);
									} else {
										//If video not found go to article view
										SWFAddress.setValue('/'+ id +'/features/article');
									}
								},
								error: function(){
									//If video not found go to article view
									SWFAddress.setValue('/'+ id +'/features/article');
								}
							}
						);
					} else if(hash.indexOf('/archive') != -1 && (hash.indexOf('/features') == -1)){
						showAdeyakaArticleArchive();
						return true;
					} else if(hash.indexOf('/features') == -1) {
						hideAdeyakaArticleArchive();
						return true;
					}
					return true;
                }

                //handle the overlays section;
                if (jQuery.inArray(overValue,['about','sitemap','legal','country-selector', 'contact']) != -1) {
					$('.wwa_bg').remove();
					
                    jQuery.each(overlayInfo,function(key,value){
                        if (hash==key) {
                            activeOverlay = value;
                        }
                    });

                    omniture(hash);
					getSharingMeta();
                    footerStyleHashAction(hash,activeOverlay.title); 
                    //if ($('#flashcontent').length === 0 && !flash) {
                    if(!flash){
                    	hideNav();
                        $('#fancybox-overlay').css({'visibility':'visible','display':'block'});
                    }    
                    //}
                    $('a#'+activeOverlay.id).siblings().removeClass('set-item');
                    $('a#'+activeOverlay.id).addClass('set-item');

                    if (overValue == 'about') {
                        if ( $('#fancybox-wrap').css('display')=='none' || !$('div#about').is(':visible')) {
                            $('#aboutDeepLink').trigger('click');
                        }
                        overlaySelector(hash);
                    }
                    else {
                        $('a#'+activeOverlay.id).click();
                    }
					
                }
				
				if(pathNames[0] == 'home' && pathNames[1] == 'who-we-are' && !flash){
					hideNav();
								
					var fake_fancybox = $('<a href="#who_we_are_wrapper"></a>').fancybox({
						'hideOnOverlayClick': false, 
						'autoDimensions' : false, 
						'enableEscapeButton': false, 
						'autoScale': false,
						'showCloseButton': false,
						'scrolling': 'no',
						'overlayShow'		:	true,
						'overlayOpacity'	:	1,
						'overlayColor'		:	'#000',
						width: 940, 
						height: 570, 
						padding: 0,
						onClosed: function(){
							SWFAddress.setValue("/home");
							originalMetaUrlOverride = null;
							$('#who_we_are').cycle('destroy');
							$('#who_we_are_wrapper').hide();
							$('.wwa_bg').remove();
							$('#fancybox-overlay').css('visiblity', 'hidden');
							document.title = previousPageTitle;
							showNav();
						}
						
					});
														
					if($('#fancybox-inner #who_we_are').length > 0){
						var idx = $('#fancybox-wrap #who_we_are > div').index($('#fancybox-wrap #who_we_are > div#'+pathNames[2]));
						$('#pager a').eq(idx).click();
						$('#fancybox-overlay').css({'visibility':'visible','display':'block'});
					} else {
						HOME_CONST.imageInterval = HOME_CONST.imageTimeout / 100;
						$('body').append('<div class="wwa_bg"></div>');
						$('.wwa_bg').show().css({height: $('.wrapper').height(), width: $('.wrapper').width()});
						$('#fancybox-overlay').css({'visibility':'visible','display':'block'});
						
						var idx = $('#who_we_are > div').index($('#who_we_are > div#'+pathNames[2]));
						
						fake_fancybox.click();
						$('#who_we_are_wrapper').show();
						
						$('#fancybox-wrap #who_we_are').cycle({
							fx: 'fade',
							startingSlide: idx,
							speed: 570,
							timeout: 0,
							pager: '#pager',
							pagerAnchorBuilder: function(idx, slide){
								return "<a href='javascript: void(0);'>"+ (idx + 1) +"<div class='loader'><div></div></div><div class='buffer'><div class='buffer-100'></div></div></a>";
							},
							after: function(curSlide, prevSlide, options, forwardFlag){
								$('#pager a .loader div').attr('class', '');
								$('#pager .activeSlide .loader div').addClass('loader-100');
							},
							before: function(curSlide, nextSlide, options, forwardFlag){
								//Slide logic goes here:
								$nextSlide = $(nextSlide);
								$('.wwa_bg').attr('id', 'wwa-'+$nextSlide.attr('id'));
																			
								//Clear preexisting image/video timers
								if(timeoutObj != null){
									clearTimeout(timeoutObj);
									timeoutObj = null;
									HOME_CONST.imageElapsed = 0;
								}
								
								//Clear pager
								$('#pager .activeSlide .loader div').attr('class', '');
								$('#pager .activeSlide .buffer div').attr('class', 'buffer-100');
								//Set update timeout for progress animation
								//timeoutObj = setTimeout(updateImageSlideProgress, HOME_CONST.imageInterval);
							}
						});
						$('#pager .activeSlide .loader div').addClass('loader-100');
						
						$('#who_we_are_wrapper #pager a').unbind('click').click(function(){
							var idx = $('#pager a').index($(this));
							SWFAddress.setValue('/home/who-we-are/' + $('#fancybox-wrap #who_we_are > div').eq(idx).attr('id'));
						});
						
						// attach swipe event handler for ios devices
						if(isIpad){
							jQuery('#who_we_are_wrapper').swipe({
								threshold: 100,
								swipeLeft: function(e){
									e.stopPropagation();
									jQuery('#wwa_right_arrow').trigger('click');
									jQuery('#at15s').trigger('mouseout');
								},
								swipeRight: function(e){
									e.stopPropagation();
									jQuery('#wwa_left_arrow').trigger('click');
									jQuery('#at15s').trigger('mouseout');
								},
								click: function(e, target){
									// only trigger mouseout if not clicking on share button will prevent a quick open and close scenario
									if(!jQuery(target).hasClass('share_button')){
										jQuery('#at15s').trigger('mouseout');
									}
								}
							});
						}
						
						$('#who_we_are_wrapper #wwa_left_arrow').unbind('click').click(function(){
							var $nextSlideA = $('#pager a.activeSlide').prev();
							if($nextSlideA.length == 0){
								$('#pager a:last').click();
							} else {
								$nextSlideA.click();
							}
						});
						
						$('#who_we_are_wrapper #wwa_right_arrow').unbind('click').click(function(){
							var $nextSlideA = $('#pager a.activeSlide').next();
							if($nextSlideA.length == 0){
								$('#pager a:first').click();
							} else {
								$nextSlideA.click();
							}
						});
						
						$('#who_we_are_wrapper #fancybox-close').unbind('click').click(function(){
							$.fancybox.close();
						});
						
						// timeout used for ipad fix below
						var captionTimeout;
						
						$('#pager a').hover(function(){
							// usefull elements
							$this = $(this);
							$caption = $('#slide_caption');
							$pager = $('#pager');
							
							// calculate positiong for caption
							var slideOffset = $pager.find('a').index($this) * $this.outerWidth(true) + ($this.width() / 2);
							var pos = {left: Math.round($pager.position().left - ($pager.width() / 2) + slideOffset) - ($caption.width() / 2)};
							
							// show caption
							$caption.html($('#cta_who_we_are li').eq($('#pager a').index($(this))).find('p').html());
							$caption.css(pos);
							$('.loader div', this).attr('class', 'loader-100');
							
							// fix for ipad trigger the mouseleave after a little while
							if(isIpad){
								captionTimeout = setTimeout(function(){
									$this.trigger('mouseleave');
								}, 2500);
							}
						}, function(){
							// clear ipad fix timeout
							if(isIpad) clearTimeout(captionTimeout);
							
							// hide captions
							$('#slide_caption').html('');
							$('.loader div', $(this).filter(':not(.activeSlide)')).attr('class', '');
						});
						
						previousPageTitle = document.title;
					}
					
					document.title = $('#who_we_are div:visible h1').html().split('<')[0] + " - Infiniti Global Official Site";
					//CUSTOM ONLOAD EVENT, NON-STANDARD
					var ctaPosition = $('#cta_who_we_are a').index($('#cta_who_we_are a[href=#'+ SWFAddress.getValue() +']')) + 1;
					document.jsAPI.trackPage('home/proofpoint'+ ctaPosition +'/'+pathNames.pop(), 'Html');
				}
				
                    
			}
		}else{

            if (typeof previousPageTitle != 'undefined') {
                document.title = previousPageTitle;
            }
            
            // Store the page title only for non-overlays 
            // (overlays set the title on their own)
            //alert('storing '+document.title);
            window.previousPageTitle = document.title;

            // Ensure that no footer links are highlighted
            $('#footer a').removeClass('set-item');
			addthis_share.url = 'http://' + window.location.hostname + BASE_PATH + window.location.hash.substring(1) + "?cid=share";
			addthis_share.title = $('meta[name=title]').attr('content');
			addthis_share.description = $('meta[name=description]').attr('content');
		}
	}else{ // null hash case
        // Ensure that no footer links are highlighted
        $('#footer a').removeClass('set-item');
        
		addthis_share.url = 'http://' + window.location.hostname + BASE_PATH + window.location.hash.substring(1) + "?cid=share";
		addthis_share.title = $('meta[name=title]').attr('content');
		addthis_share.description = $('meta[name=description]').attr('content');

        // If there is any overlay, close it.
        $.fancybox.close();
	}
} 

function resetHash(){
    if (typeof(previousPageTitle) != 'undefined') {
        parent.document.title = previousPageTitle;
    }
	
	$('.internal-link-group a').removeClass('set-item')
	$('#page-selector-previous, #page-selector-next, #adeyaka_lobby_carousel, #adeyaka_lounge_carousel, ').attr('style', 'visibility: visible;');
	$('#adeyaka_gallery_carousel').attr('style', 'visibility: visible;');
	
	if(originalMetaUrlOverride != null){
		window.location.hash = '#' + originalMetaUrlOverride;	
		return true;
	}
	if(SWFAddress.getValue().indexOf('infiniti-tv') == -1){
		SWFAddress.setValue(originalMetaUrl);	
	}
	if(window.uri.indexOf('infiniti-tv') != -1){
		window.location = window.location;
	}	
}
function overlaySelector(overlayToShow){

	var aboutNavItems = [
	    "about-introduction",
		"about-safety",
		"about-environment",
		"about-technology",
		"about-brand-history"
	]

    overlayToShow = overlayToShow.substring(1).replace(/\//g,'-'); 

	$.each(aboutNavItems, function() {
		if (this != overlayToShow) {
			$("#overlay-" + this).hide();
			$("#link-" + this).removeClass('set-item');
		}
	});

	$("#overlay-" + overlayToShow).show();
	$("#link-" + overlayToShow).addClass('set-item');
	
	return false;
}

function printArticle(id){
	if(id.indexOf('news-events') != -1){
		id = id.replace('/archive', '');
	}
	id = id.replace(/\/features\/(article|video|gallery)/gi, '');
	var hostname = host + '/global/en' + id;
	
	if(galleryImage != null){
		hostname += '/' + galleryImage;
	}
	window.open(hostname, '_blank', 'height=725,width=680,status=0,titlebar=0,toolbar=0,location=0,scrollbars=1', '');
}

$(function(){
	if(SWFAddress.getValue() == '/'){
		SWFAddress.setValue(window.location.pathname.replace('/global/en', ''));
	}
	
	//temp fix for genkan/infiniti-worldwide countries with no links.....also check genkanscripts.js where this is called twice.
	$('.asiaPacific a[rel*=au]').addClass('nolinks');
	
	//fix for adeyaka archives.
	if (hash.indexOf('/adeyaka-magazine/archive')!=-1) {
		$('.adeyakaarchiveArticlescontent').css('visibility','visible');
	}
	
	// download wallpaper button with fix for ipad/iphone/ipod
	if(isIpad){
		$('.wallpaper-toggle').live('click', function(e){
			displayToggle('wallpaper', 'on');
		});
	}else{
		$('.wallpaper-toggle').live('mouseover', function(e){
			displayToggle('wallpaper', 'on');
		}).live('mouseout', function(e){
			displayToggle('wallpaper', 'off');
		});
	}
		
	getSharingMeta();

	$('.adeyaka #archiveArticles a').live('mouseover', function(){ $(this).addClass('hover'); }).live('mouseout', function(){ $(this).removeClass('hover'); })
	$('.share_button').live('click', function(e){
		e.preventDefault();
		socialHash = SWFAddress.getValue() + '/social_share_button';
		omniture('/social_external', 'pageTracking', true, socialHash);		
		var curPos = $(this).offset();
		document.jsAPI.sharePopup(curPos.left, curPos.top);
	});
	
	//href_fbook = 'http://api.addthis.com/oexchange/0.8/forward/facebook/offer?url=' + addthis_share.url;
	//href_fbook += '&title=' + addthis_share.title;
	$('#social-media-footer .facebook').live('click', function(){
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'facebook');
		return true;
	});

	//href_twitter = 'http://api.addthis.com/oexchange/0.8/forward/twitter/offer?url=' + addthis_share.url;
	//href_twitter += '&title=' + addthis_share.title;
	$('#social-media-footer .twitter').live('click', function(){
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'twitter');
		//return false;
	});
	
	$('.social-media-details .email, #social-media-footer .email').live('click', function(){
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'email');
		addthis_sendto('email');
		return false;
	});	
	
	$('.social-media-details .print, #social-media-footer .print').live('click', function(){
		printArticle(htmlSafe+'/print');
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'print');
		return false;
	});
	
	$('#social-media-footer .flickr').live('click', function(){
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'flickr');
	});
	
	$('#social-media-footer .youtube').live('click', function(){
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'youtube');
	});		
	$('.social-media-details, #social-media-footer').css('cursor', 'pointer');
		
	//cirque tracking
	$('.cirquepanel-introduction .featuredStory_img a, .cirquepanel-introduction .featuredStory_info a').live('click', function(){
		var linkId = 'nav-image-' + $(this).attr('href').split('/').pop();
		document.jsAPI.trackLink('click',linkId);
	});
	//added more cirque tracking
	$('.cirquepanel-introduction a.newsCta, .cirquepanel-introduction .cirquepanel-intro-copy2 a').live('click', function(){
		var linkId = $(this).attr('href').split('#').pop();
		document.jsAPI.trackLink('click',linkId);
	});
	
	
	
	/*$('.cirquepanel-introduction .featuredStory_info').live('click', function(){
		var linkId = 'nav-image-' + $(this).children('a').attr('href').split('/').pop();
		document.jsAPI.trackLink('click',linkId);
	});*/	
	
	if(!flash){
		$('.flash_on').remove();
	}
	
	$('.social-media-details .twitter').bind('click', function(){
		addthis_sendto('twitter', addthis_config, addthis_share);
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'twitter');
		return false;
	});
	

	if(isIpad){
		$('.nav li.top-a').click(function(e){
			if($(this).children('div').length > 0){
				e.preventDefault();
			}
			});
		$('.nav li.top-a div a').click(function(e){
			e.stopPropagation();
		})
		}		
	$('ul.nav a').click(function(){
		if($(this).attr('href') != '#'){
			var curPath = $(this).attr('href').split('#')[1];
			if(curPath.indexOf('adeyaka') != -1 || curPath.indexOf('infiniti-world') != -1){
				curPath = curPath.split('/');
				curPath.pop();
				curPath = curPath.join('/');
			}
			curPath = curPath.replace(/\//gi, '-');
			var curUrl = window.location.hash.substring(1);
			curPath = 'top-nav-button' + curPath + '-HTML';
			document.jsAPI.trackLink('click', curPath, curUrl);
		}
	})
	
	$('#contact a, #country-selector-content a').live('click', function(){
		var curUrl = window.location.hash.substring(1);
		var curPath = $(this).attr('id');
		document.jsAPI.trackLink('exit', curPath, curUrl);
		openRegionWindow($(this).attr('href'));
		return false;
	});
	
	$('dt span.country-name').hover(function(){
		var href = $(' a', $(this).parent().next()).attr('href');
		if(href != null && href.length > 0){
			$(this).addClass('sel');
		}
	}, function(){
		$(this).removeClass('sel');
	}).click(function(){
		$(' a', $(this).parent().next()).click();
	});
	
	$('.footer-region a').click(function(){
		var destUrl = $(this).attr('href');
		document.jsAPI.trackLink('exit', destUrl, destUrl);
	});
	
	$('#who_we_are .media').click(function(e){
		playSingleVideo($(this).attr('href'), '', true);
		var name = "wwa-video-clicked";
		document.jsAPI.trackLink('body-click', name);
		e.preventDefault();
	});
	
	$('#cta_who_we_are li').hover(function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); });
	
	$('#cta_who_we_are a').click(function(){
		var name = "home-proofpoints-" + ($('#cta_who_we_are a').index(this)+1) + '-' + $(this).attr('href').split('/').pop();
		document.jsAPI.trackLink('body-click', name, $(this).attr('href').substring(1));
	});
	
	$('#news_wrapper a').click(function(){
		var name = "home-features-" + ($('#news_wrapper a').index(this)+1) + '-' + $(this).attr('href').split('/').pop();
		document.jsAPI.trackLink('body-click', name, $(this).attr('href').substring(1));
	});
	
	$('.available a').live('click', function(){
		var ctaPosition = $('#cta_who_we_are a').index($('#cta_who_we_are a[href=#'+ SWFAddress.getValue() +']')) + 1;
		var pathNames = SWFAddress.getPathNames();
		var name = 'home-proofpoint'+ctaPosition+'-'+pathNames.pop()+'-'+$(this).html().replace(/[ ]/g, '-').toLowerCase();
		document.jsAPI.trackLink('body-click', name);
	});
});

var updateImageSlideProgress = function(){
	HOME_CONST.imageElapsed += HOME_CONST.imageInterval;
					
					
	var progress = Math.floor(100 / (HOME_CONST.imageTimeout / HOME_CONST.imageElapsed));
	
	$('#pager .activeSlide .loader div').attr('class', 'loader-' + progress);
	
	if(HOME_CONST.imageElapsed <= HOME_CONST.imageTimeout){
		timeoutObj = setTimeout(updateImageSlideProgress, HOME_CONST.imageInterval);
	} else {
		HOME_CONST.imageElapsed = 0;
		var $nextSlideA = $('#pager a.activeSlide + a');
		if($nextSlideA.length == 0){
			$('#pager a:first').click();
		} else {
			$nextSlideA.click();
		}
	}
}
