// redirect to regional site if region-default cookie is true and we can find a URL for the region in our regions object
if(document.jsAPI.getCookie('region-default') != null && document.jsAPI.getCookie('region-default') == 'true') {
	var region = document.jsAPI.getCookie('region');
	if(region && regions[region]){
		if(debugMode) alert('region redirect');
		window.location = regions[region];
	}
}

//Redirect if cookied region is set to something other than what was geo'd
if(document.jsAPI.getCookie('region')) {
	var cookiedRegionCombo = document.jsAPI.getCookie('region');
	var currentRegionCombo = countryCode + '|' + language;
	
	if(cookiedRegionCombo != currentRegionCombo) {
		rRegion = cookiedRegionCombo.split('|')[0];
		rLanguage = cookiedRegionCombo.split('|')[1];
		window.location = appBase + rRegion + '/' + rLanguage + '/index' + getQueryString();
	}
}

// browser detection
var isIpad = navigator.platform.indexOf("iPhone") != -1 || navigator.platform.indexOf("iPod") != -1 || navigator.platform.indexOf("iPad") != -1;

// detect browser language
var browserLang = null;
if(window.navigator.language) { // Firefox and Opera
	browserLang = window.navigator.language;
} else if(navigator.browserLanguage) { // Internet Explorer
	browserLang = navigator.browserLanguage;
}

// ensure 2 char length
if(browserLang != null && browserLang.length >= 2) {
	browserLang = browserLang.substring(0, 2).toLowerCase();
	// redirect if different from current and we find a match in the regions object
	if(browserLang != language && regions[countryCode + '|' + browserLang] && document.jsAPI.getCookie('region') == null) {
		if(debugMode) alert('language redirect');
		window.location = appBase + countryCode + "/" + browserLang + "/index" + getQueryString();
	}
}

if(document.jsAPI.getCookie('region') == null)
	document.jsAPI.setCookie('region', countryCode+'|'+language);

function genkanFlashEmbedCallback(e) {
	if(e.success) {
		//Genkan no longers has flash, so this is not needed.
		//swffit.fit("flashcontent", 960, 600);    
	} else {
		var bodyEl = $('body');

		bodyEl.removeClass('flashenabled');
		bodyEl.addClass('noflash');
		
		document.jsAPI.trackPage('index', 'HTML'); //if/when deeplink support required, window.location.hash.substring(1)
		document.jsAPI.setCookie('declinedExpressInstall', 'true', 0); //Flash ExpressInstall declined or failed
		
		setGenkanClicks();
	}
}

$(document).ready(function() {
	if (!swfobject.hasFlashPlayerVersion('<xsl:value-of select="$minFlashVersion"/>')) {
		setGenkanClicks();
	}
});

detectVideoSupport = function(){
	var detect = document.createElement('video') || false;
	this.html5 = detect && typeof detect.canPlayType !== "undefined";
	this.mp4 = this.html5 && (detect.canPlayType("video/mp4") === "maybe" || detect.canPlayType("video/mp4") === "probably");
	this.ogg = this.html5 && (detect.canPlayType("video/ogg") === "maybe" || detect.canPlayType("video/ogg") === "probably");
	return this;	
}
videoSupport = detectVideoSupport();

var embedPlayer = function(id, vidFile, vidImg){
	if($('#'+id).length == 0){
		return false;
	}
	if(videoSupport.mp4 || flash){   // MP4 support only.
		jwplayer(id).setup({
			flashplayer: "/static/global/jwplayer/player.swf",
			file: vidFile, 
			image: vidImg,
			width: '100%',
			height: '100%',
			controlbar: 'over',
			mute: true,
			stretching: 'fill',
			skin: "/static/global/jwplayer/glow/glow_genkan.xml",
			modes: [
				{type: 'html5'}
			]
		}).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,
			width: '100%',
			height: '100%',
			controlbar: 'over',
			mute: true,
			stretching: 'fill',
			skin: "/static/global/jwplayer/glow/glow_genkan.xml"
		}).play();
	}
}

function setGenkanClicks() {
	$('#flash-install-link a').click(function(e) {
		document.jsAPI.trackLink('exit', 'Adobe Flash install', this.href);
	});
	
	$('#region-overlay #cta_yes').click(function(e) {
		document.jsAPI.setCookie('region', $('#cta_regional').attr('rel'));
		document.jsAPI.setCookie('region-default', 'true');
		document.jsAPI.trackLink('region-default-prompt', 'Genkan region default clicked yes');
		
		var targetUrl = $('#cta_regional').attr('href');
		document.jsAPI.trackLink('exit', targetUrl, targetUrl);
		var redirect = function(){
			document.location = targetUrl;
		}
		self.setTimeout(redirect,500); // wait 500 ms to allow time for Omniture request

		e.preventDefault();
	});
	
	$('#region-overlay #cta_no').click(function(e) {
		document.jsAPI.trackLink('region-default-prompt', 'Genkan region default clicked no');
		
		var targetUrl = $('#cta_regional').attr('href');
		document.jsAPI.trackLink('exit', targetUrl, targetUrl);
		var redirect = function(){
			document.location = targetUrl;
		}
		self.setTimeout(redirect,500); // wait 500 ms to allow time for Omniture request

		e.preventDefault();
	});
	
	$('#region-selector table td a').click(function(e) {
		var link = this;
		$.getJSON('/scripts/region-localization.js?linkCountry='+$(link).attr('rel')+'&linkLanguage='+$(link).attr('lang'), function(data) {
			if($(link).attr('lang') == 'he' || $(link).attr('lang') == 'ar') {
				$('#region-overlay-content').addClass('rtl');
			} else {
				$('#region-overlay-content').removeClass('rtl');
			}
			
			$('#region-default-message').html(data.prompt.replace(/<[^>]*>/g, ""));
			$('#region-default-yes').html(data.yesLabel.replace(/<[^>]*>/g, ""));
			$('#region-default-no').html(data.noLabel.replace(/<[^>]*>/g, ""));
			$('#region-default-warning').html(data.defaultWarning.replace(/<[^>]*>/g, ""));
			
			$('#region-selector').attr('currentURL', link.href);
			$('#region-selector').attr('region', $(link).attr('rel')+'|'+$(link).attr('lang'));
			
			$('#region-overlay').css('display', 'block');
			
			document.jsAPI.trackLink('region-default-prompt-view', 'Genkan region default message displayed');
		});
		
		e.preventDefault();
	});
	
	$('#region-overlay #close-button').click(function(e) {
		$('#region-overlay').css('display', 'none');
		document.jsAPI.trackLink('region-default-prompt', 'Genkan region default clicked close');
		e.preventDefault();
	});

	$('#flash-install-link').click(function() {
		//TODO Omniture
	});
	
	
	//new ones.
	$('#flash-install-link').click(function(e) {
		document.jsAPI.trackLink('exit', 'Adobe Flash install', this.href);
	});
	$('#cta_regional').click(function(e) {
		if($(this).attr('lang') == 'world'){
			document.jsAPI.trackLink('show-genkan-country-overlay-not-geolocated', 'Show Genkan Country Overlay Not Geolocated');
			show_overlay.apply($('#overlay_change_country').get(0));
		}
	});
	$('#overlay_change_country').hover(function(e) {
		document.jsAPI.trackLink('show-genkan-country-overlay-geolocated', 'Show Genkan Country Overlay');
	});
	$('#cta_international').click(function(e) {
		document.jsAPI.trackLink('enter-global-entryway', 'Entering Global Entryway');
	});	

	$('#main_nav_logo').click(function(){
		window.location = "/global/en/home#/home";
	});
	
	$('#home_slides .copy h2, #home_slides .copy .info').hover(
		function(){ 
			$(this).parents('.copy').find('.cta').addClass('hover'); 
		}, function(){ 
			$(this).parents('.copy').find('.cta').removeClass('hover'); 
		}).click(function(){ 
			window.location = $(this).parents('.copy').find('.info').attr('href'); 
		})
		
	$('.copy .cta').click(function(){
		$this = $(this);
		$curSlide = $this.closest('.slide');
		var idx = $('#home_slides > div').index($curSlide) + 1;
		var title = $curSlide.find('h2').html().replace(/[ ]/g, '-');
		var name = 'Index-Tray'+idx+'-'+title;
		document.jsAPI.trackLink('body-click', name);
	});
}


var HOME_CONST = {
	imageTimeout: 5000,
	videoInterval: 1000,
	imageElapsed: 0,
	factor: 100,
	paused: false,
	videoState: null
};
if($.browser.msie && $.browser.version == '6.0'){
	//HOME_CONST.factor = 20;
	//No need for crappier animations now that the below hack is present.
}
if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
	//This is a godgiven solution to the IE6 background image caching bug
	// By default IE6 keeps hitting the server for the same bg image if its used by multiple elements
	// Do keep in mind this setting is persistent.
  try {
    document.execCommand("BackgroundImageCache", false, true);
  } catch(err) {}
}

var timeoutObj = null;

$(function(){
	document.jsAPI.trackPage('/index', 'HTML'); 
	
	//UAT fix for area between p and a when user hovers over color of CTA doesnt flicker.
	/*
	$('.info').hover(function(){
		$('.info a').css({'color':'#CF55FE','text-shadow':'0 0 5px #CF55FE'});
		$('#home_slides .slide .copy div.info a .arrow').css('background-position','-5px -7px');
	},function(){
		$('.info a').css({'color':'#FFFFFF','text-shadow':'none'});
		$('#home_slides .slide .copy div.info a .arrow').css('background-position','-8px 0');
	});
	*/
	
	initialize_menu();
	
	// models overlay
	$('#car_sel li').hover(function(){
		var curSlideId = '#spot_'+$(this).attr('id');
		$('#car_spotlight div').hide().filter(curSlideId).show();
		$('#car_sel li div').removeClass('default').removeClass('hover');
		$('div', this).addClass('hover');
	}).click(function(){
		$this = $(this);
		var row = $('#car_sel li').index(this) + 1;
		var car_name = $this.attr('id');
		var name = "index-models-"+row+"-"+car_name;
		document.jsAPI.trackLink('nav-path', name);
	});
	
	$('#car_spotlight div').click(function(){
		var tarId = '#car_sel #' + $(this).attr('id').replace('spot_', '');
		window.location = $('a', tarId).attr('href');
	});
	
	// whats inside overlay
	$('.thumbs li :not(h4)').click(function(){ 
		$parent = $(this).closest('li');
		var idx = $('.thumbs li').index($parent) + 1;
		var row = idx > 4 ? 2 : 1;
		var column = row == 1 ? idx : idx - 4;
		var title = $parent.find('h5').html().replace(/[ ]/g, '-').toLowerCase();
		
		var name = 'index-whatsinside-'+row+'|'+column+'-'+title;
		document.jsAPI.trackLink('nav-path', name);
		var dest = $(this).closest('li').find('a').attr('href');
		if(flash){
			dest = dest.split('#');
			dest[0] = '/global/en/home';
			dest = dest.join('#');
		}
		
		// delay before changing pages to make sure tracking is completed
		setTimeout(function(){
			window.location = dest; 
		}, 800);
	});
	
	// hover is not added to whats inside items on ipad
	if(!isIpad){
		$('.thumbs li :not(h4)').hover(function(){ 
			$(this).closest('li').addClass('hover'); 
		}, function(){ 
			$(this).closest('li').removeClass('hover'); 
		})
	}
	
	initialize_slides();
	clearTimeout(timeoutObj);
	HOME_CONST.imageElapsed = 0;
	
	$('#social-media-footer .facebook').live('click', function(){
		socialHash = 'genkan/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'facebook');
		return true;
	});

	$('#social-media-footer .twitter').live('click', function(){
		socialHash = 'genkan/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'twitter');
	});
		
	$('#social-media-footer .flickr').live('click', function(){
		socialHash = 'genkan/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'flickr');
	});
	
	$('#social-media-footer .youtube').live('click', function(){
		socialHash = 'genkan/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'youtube');
	});		
	$('.social-media-details, #social-media-footer').css('cursor', 'pointer');
	
});

$(window).resize(function(){
	resize_slides();
}).load(function(){
	$('.initial').fadeIn();
	$.preLoadImages('/static/media/images/genkan/whats_inside.jpg','/static/media/images/genkan/model_thumbs.jpg', '/static/media/images/genkan/spot_sprites.jpg');
	
	if($('#slide1').attr('data-type') != 'video'){
		timeoutObj = setTimeout(updateImageSlideProgress, HOME_CONST.imageInterval);
	} else {
		$('#pager a').eq(0).addClass('video')
	}
	
	resize_slides();
	$('body').attr('style', '');
});

var getTotalDimensions = function(){
	var $overlay = $('.overlay:visible');
	var $dim = {width: '100%', height: '100%'};
	if($overlay.length > 0 && $overlay.outerHeight() + $('#wrapper').outerHeight() > $(window).height()){
		$dim.height = $overlay.outerHeight() + 20;
	}else if($(window).height() - $('#wrapper').outerHeight() < 400){
		$dim.height = 400;
	}else {
		$dim.height = $(window).height() - $('#wrapper').outerHeight();
	}
	if($(window).width() < 950){
		$dim.width = 950;
	}
	return $dim;
}

var resize_slides = function(){
	 $('#home_slides').css(getTotalDimensions());
};

var initialize_menu = function(){
	var $nav = $('#main_nav');
	
	$('#home_slides, #main_nav, .big').hoverIntent(function(){ hide_overlay(); }, function(){});
	$('#overlay_change_country, #overlay_whats_inside, #overlay_models').hoverIntent(show_overlay, function(){});
	
	$('#main_nav li:not(#main_nav_logo)').hover(function(e){
		$(this).addClass('hover');
	}, function(e){
		$(this).removeClass('hover');
	});
};

var hide_overlay = function(){
	if($('.overlay:visible').length > 0){
		$('.overlay, #region-overlay').hide(); 
		resize_slides(); 
		$('#main_nav').find('.sel').removeClass('sel');
		$('.bottom_arrow').hide();
		// image
		if(!HOME_CONST.paused && timeoutObj == null && HOME_CONST.slideType == 'image'){
			timeoutObj = setTimeout(updateImageSlideProgress, HOME_CONST.imageInterval);
		}
		// ipad video
		else if(!HOME_CONST.paused && timeoutObj == null && HOME_CONST.slideType == 'video' && isIpad){
			timeoutObj = setTimeout(updateImageSlideProgress, HOME_CONST.imageInterval);
		}
		// video
		else if(HOME_CONST.slideType == 'video' && !HOME_CONST.paused) {
			jwplayer('bg_video').play(true);
		}
	}
}

var show_overlay = function(){
	
	$this = $(this);
	myId = $this.attr('id');
	$parent = $this.parents('li');
	$main_menu = $parent.parents('ul');
	$dialog = $('div[rel='+ myId +']');
	$dialog.css({top: $main_menu.outerHeight(), 'margin-left': -($dialog.outerWidth() / 2)})
	
	if($dialog.css('display') == 'block'){
		return false;
	}
	
	$('.asiaPacific a[rel*=au]').addClass('nolinks');
	
	$('.bottom_arrow').hide();
	$('.overlay, #region-overlay').hide();
	$main_menu.find('.sel').removeClass('sel');
		
	//clearing out models
	$('#car_spotlight div').hide().filter('.default').show()
	$('#car_sel li div').removeClass('hover');
	var tarId = '#car_sel #' + $('#car_spotlight div.default').attr('id').replace('spot_', '') + " div";
	$(tarId).addClass('default');
	
				
	$dialog.slideDown(250, function(){
		$parent.add($this).addClass('sel');
		resize_slides();
		clearTimeout(timeoutObj);
		timeoutObj = null;
		
		var videoPlayer = jwplayer('bg_video');
		if(videoPlayer){	
			HOME_CONST.paused = 'overlay';
			videoPlayer.pause(true);
		}
		
		var c_left = $parent.offset().left + Math.round($parent.outerWidth() / 2) - Math.round($('.bottom_arrow').width() / 2);
		var c_top = $parent.outerHeight();
		$('.bottom_arrow').css({top: c_top, left: c_left}).show();
	});
}

var initialize_slides = function(){
	HOME_CONST.imageInterval = HOME_CONST.imageTimeout / HOME_CONST.factor;
	
	$('#home_slides > div').each(function(index){
		var $this = $(this);
		
		// when video not supported use image instead
		//Reverted fix
		if($.browser.msie || (!flash && !(videoSupport.mp4 || videoSupport.ogg) && $this.attr('data-type') == 'video')){
			$this.attr('data-type', 'image');
		}
		
		// when image type append the background image element
		if($this.attr('data-type') == 'image' && typeof $this.attr('data-bg') != 'undefined'){
			$this.append('<img src="'+ $this.attr('data-bg') + '" class="bg" galleryimg="no" />');
		}
		
		css_config = {};
	});
	
	$('#home_slides').cycle({
		fx: 'fade',
		//easeIn: 'easeInOutExpo',
		//easeOut: 'easeInOutExpo',
		speed: 600,
		animIn: {"padding-left": "0"},
		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(prevSlide, curSlide){
			$curSlide = $(curSlide);
			//Clear progress bars
			if($curSlide.attr('data-type') == 'video' && !isIpad){
				$('#pager .activeSlide .loader div').attr('class', ''); 
				$('#pager .activeSlide').css({'background': 'none', 'text-indent': 0});
			}
		}, 
		before: function(curSlide, nextSlide, options, forwardFlag){
			//Slide logic goes here:
			$nextSlide = $(nextSlide);
			HOME_CONST.slideType = $nextSlide.attr('data-type');
							
			//Clear preexisting image/video timers
			if(timeoutObj != null){
				clearTimeout(timeoutObj);
				timeoutObj = null;
				HOME_CONST.imageElapsed = 0;
			}
			
			// Remove previous slide's video instance
			if(isIpad){
				// ipad
				if($('#bg_video_ipad').length > 0){
					$('#bg_video_pad').remove();
				}
			}else{
				// normal
				if($('#bg_video').length > 0){
					jwplayer('bg_video').remove();
					$('#bg_video').remove();
				}
			}
			
			//Clear pager
			$('#pager .activeSlide .loader div').attr('class', '');
			$('#pager .activeSlide .buffer div').attr('class', 'buffer-100');
			
			//If next slide type is image or ipad video
			
			if($nextSlide.attr('data-type') == 'image' || ($nextSlide.attr('data-type') == 'video' && isIpad)){
				//Set update timeout for progress animation
				timeoutObj = setTimeout(updateImageSlideProgress, HOME_CONST.imageInterval);
			}
			
			//If next slide type is video
			if($nextSlide.attr('data-type') == 'video'){
				var path = $nextSlide.attr('data-path');
				var bg = $nextSlide.attr('data-bg');
				
				clearTimeout(timeoutObj);
			
				// ipad video
				if(isIpad){
					$nextSlide.append('<div id="bg_video_ipad"><img src="' + bg + '" class="bg" galleryimg="no" /><a href="' + path + '" class="play" target="_blank"></a></div>');
				}
				// normal video
				else{
					$nextSlide.append('<div id="bg_video"></div>');
					$('#pager a').removeClass('paused');
					
					//Embed video
					//embedPlayer('bg_video', path, path.replace('mp4', 'jpg'))
					embedPlayer('bg_video', path);
	
					//Buffer listener
					jwplayer('bg_video').onBufferChange(function(evt){
						var progress = evt.bufferPercent;
						$('#pager .activeSlide .buffer div').attr('class', 'buffer-'+progress)
					}).onTime(function(evt){
						var progress = 'loader-' + Math.round((evt.position/evt.duration)*100);
						var $indicator = $('#pager .activeSlide .loader div');
						
						if(!$indicator.hasClass(progress)){
							$indicator.attr('class', progress);
						}
						
					}).onComplete(function(){
						$curSlide = $('#home_slides > div:visible');
						if($curSlide.data('logged-video-stop') != true){
							var idx = $('#home_slides > div').index($curSlide) + 1;
							var title = cleanTagTitle($curSlide.find('h2').html());
							var name = 'index/Tray'+idx+'/'+title+'/video';
							document.jsAPI.trackPage(name, 'HTML', 'media-stop');
							$nextSlide.data('logged-video-stop', true);
						}
						jwplayer('bg_video').remove();
						$('#bg_video').remove();
						$('#home_slides').cycle('next');
					}).onPause(function(){
						if(HOME_CONST.paused == 'overlay'){
							HOME_CONST.paused = false;
						} else {
							HOME_CONST.paused = true;
						}
					}).onPlay(function(){
						HOME_CONST.paused = false;
						
						$curSlide = $('#home_slides > div:visible');
						
						if($curSlide.data('logged-video-play') != true){
							var idx = $('#home_slides > div').index($curSlide) + 1;
							var title = cleanTagTitle($curSlide.find('h2').html());
							var name = 'index/Tray'+idx+'/'+title+'/video';
												
							document.jsAPI.trackPage(name, 'HTML', 'media-start');
							$nextSlide.data('logged-video-play', true);
						}
					}).onBuffer(function(){
						HOME_CONST.paused = false;
					});
				}
			}
			
			if($nextSlide.data('logged') != true){
				var idx = $('#home_slides > div').index($nextSlide) + 1;
				var title = cleanTagTitle($nextSlide.find('h2').html());
				var name = 'index/Tray'+idx+'/'+title;
				document.jsAPI.trackPage(name, 'HTML');
				$nextSlide.data('logged', true);
			}
			
		}
	});
	
	/*$('#pager #cta_auto').click(function(){
		$this = $(this);
		if($this.hasClass('paused')){
			$this.removeClass('paused');
			$('#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);
		} else {
			$this.addClass('paused');
			clearTimeout(timeoutObj);
			timeoutObj = null;
		}
	});*/
	$('#pager a').click(function(){
		var $this = $(this);
		var curType = $('#home_slides .slide').eq($('#pager a').index(this)).attr('data-type');

		HOME_CONST.imageElapsed = 0;
		
		// image and ipad video
		if(curType == 'image' || (curType == 'video' && isIpad)){
			if($this.hasClass('paused')){
				HOME_CONST.paused = false;
				$this.removeClass('paused');
				timeoutObj = setTimeout(updateImageSlideProgress, HOME_CONST.imageInterval);	
			} else {
				HOME_CONST.paused = true;
				$('#pager a').removeClass('paused');
				$this.addClass('paused');
				clearTimeout(timeoutObj);
				timeoutObj = null;
			}
		}
		
		var $curSlide = $('.slide:visible');
		var idx = $('#home_slides > div').index($curSlide) + 1;
		var title = cleanTagTitle($curSlide.find('h2').html());
		var name = 'index/Tray'+idx+'/'+title;
		s.pageName = name;
		document.jsAPI.trackLink('body-click', 'Genkan Tray Carousel Controls Clicked');
	});
};

var cleanTagTitle = function(val){
	//If Google Translate is active
	//Grab the first line of the source text. 
	var googleTranslateSrc = $(val).find('.google-src-text');
	if(googleTranslateSrc.length > 0){
		val = googleTranslateSrc.eq(0).html();
	}
	
	var clean = val.split('\n');
	if(clean.length > 0){
		clean = clean[0];
	}
	clean = clean.replace(/\.|<[^>]+>/gi, '').replace(/[ ]/gi, '-');
	return clean;
}
			
var updateImageSlideProgress = function(){
	with(HOME_CONST){
		imageElapsed += imageInterval;
						
		var progress = Math.floor(100 / (imageTimeout / imageElapsed));
		
		$('#pager .activeSlide .loader div').attr('class', 'loader-' + progress);
		
		if(imageElapsed <= imageTimeout){
			timeoutObj = setTimeout(updateImageSlideProgress, imageInterval);
		} else {
			imageElapsed = 0;
			$('#home_slides').cycle('next');
		}
	}
}
