var ie = (navigator.userAgent.indexOf('MSIE')>=0) ? true : false;
var ie6 = (navigator.userAgent.indexOf('MSIE 6')>=0) ? true : false;
var ninWii = (navigator.platform.indexOf('Nintendo Wii')>=0) ? true : false;
var ninDSi = (navigator.platform.indexOf('Nintendo DSi')>=0) ? true : false;
var threeDS = (navigator.platform.indexOf('Nintendo 3DS')>=0) ? true : false;
var POP = {};
/*** JavaScript Enabled ***/

var jsEnabled = function(){
	$('body').removeClass('no-js');
};

/*** Wii Fixes ***/

var wiiFixes = function(){
	if(ninWii){
		$('body').addClass('nin-wii');
		$('html').css({
			'height' : 'auto'
		});
	}
}

/*** DSi Fixes ***/

var dsiFixes = function(){
	if(ninDSi){		
		$('body').addClass('nin-dsi');
	}
}

var threeDSFixes = function() {
	if(threeDS){	
		var url = window.location.href;
		window.location = url + '/3ds/';
	}
}

/*** Modal Window ***/

POP.modalWindow = function(target, options){
	var base = this;

	base.options = {
		className: 'modal-window',
		exteriorFire: false,
		exteriorFireContent: '',
		placeExisting: false,
		placeExistingElement: $('my-element'),
		callback:function(){}, 
		callbackClose:function(){}
	}

	if(typeof options == 'object'){
		$.extend(base.options, options);
	}

	if(target){
		base.elClicked = target;
		base.targetLink = base.elClicked.attr('href');
	}

	if(base.options.exteriorFire){
		$(document).bind('modalOpen',function(e, target){
			base.__createModal();
		});

		$(document).trigger('modalOpen');
	}else{
		$(base.elClicked).click(function(e){
			e.preventDefault();
			base.__createModal(this);
		});
	}
};

POP.modalWindow.prototype = {
	modalEventHandlers:function(){
		var base = this;

		base.elOverlay.click(function(){
			base.__modalHide(400);
		});
		base.elBtnClose.click(function(){
			base.__modalHide(400);
		});
		$(window).bind('resize', function(){
			base.positionModal();
		});
		$(window).scroll(function(e){
			base.positionModal();
		});
		$(document).keydown(function(e){
			base.__handleEscape(e, base);
		});
	},
	modalElements:function(){
		var base = this;

		base.elOverlay = $('<div id="overlay" />').fadeTo(0, '0.90');
		base.elBtnClose = $('<a class="btn" id="btn-modal-close"><span class="offscreen">Close</span></a>');
		base.elModalWindow = $('<div id="modal-window" />').addClass(base.options.className);

		if(typeof document.body.style.maxHeight === 'undefined' || navigator.platform == "Nintendo Wii"){
			base.elOverlay.css({
				height: ($(document.viewport).height() > $(document.body).height() ? $(document.viewport).height() : $(document.body).height()) + 'px'
			});
		}
	},
	positionModal:function(){
		var scrollTop = $(window).scrollTop();
		var base = this,
			leftPosition = ($(document.body).width() - base.elModalWindow.width()) / 2 + 'px',
			topPosition = ($(window).height() - base.elModalWindow.height()) / 2 + scrollTop + 'px';

		if($(window).height() < base.elModalWindow.height() && base.options.exteriorFire){
			base.elModalWindow.css({
				'left' : leftPosition,
				'position' : 'absolute',
				'top' : '100px'
			});
		}else{
			base.elModalWindow.css({
				'left' : leftPosition,
				'top' : topPosition
			});
		}
	},
	__createModal:function(el, fadeTime){
		var base = this,
			modalWindowContent;

		base.elOrigin = el;
		base.modalElements();
		base.modalEventHandlers();

		if(base.options.placeExisting){
			modalWindowContent = base.elModalWindow.append($(base.options.placeExistingElement).children().clone(true));
		}else{
			modalWindowContent = base.elModalWindow.append($($('> a', el).attr('href')).children().clone(true));

		}

		base.elModalWindow.append(base.elBtnClose);
		$('body').append(base.elOverlay, base.elModalWindow);
		base.elOverlay.fadeIn(fadeTime);

		if(ie6){
			modalWindowContent.show();
		}else if(ie){
			modalWindowContent.show();
		}else{
			modalWindowContent.fadeIn(fadeTime);
		}

		base.positionModal();
		base.options.callback.call(base);
	},
	__modalHide:function(fadeTime){
		var base = this,
			remove = function(){
				$(this).remove();
			};

		base.elOverlay.fadeOut(fadeTime, remove);
		base.elModalWindow.fadeOut(fadeTime, remove).empty();

		if(typeof document.body.style.maxHeight === 'undefined'){
			$('body', 'html').css({
				'height' : 'auto',
				'overflow' : 'auto',
				'width' : 'auto'
			});
		}

		$(document).unbind('keydown', base.__handleEscape);

		if(base.options.exteriorFire){
			$(document).unbind('modalOpen');
		}

		base.options.callbackClose.call(base);
	},
	__handleEscape:function(e, base){
		var base = this;

		if(e.keyCode === 27){
			base.__modalHide(400);
		}
	}
};

/*** Embed Video Players ***/

var embedVideo = function(target, options){
	var base = this;

	base.options = {
		modalVideo: false,
		swfFile: 'my-player.swf',
		swfHeight: '100',
		swfWidth: '100',
		flashVersion: '9.0.0',
		flashExpressIntall: false,
		videoAutoPlay: true,
		externalVideo: false,
		mediaPath: '',
		callback: function() {}
	}

	if(typeof options == 'object'){
		$.extend(base.options, options);
	}

	base.elTarget = target;

	base.replaceElement(base.elTarget)
}

embedVideo.prototype = {
	replaceElement:function(el){
		var base = this,
			modalTarget = $('<div id="flash-target-video" />'),
			flashVideoId,
			flashVideo,
			flashVideoPoster,			
			flashVideoTitle;

		if(base.options.modalVideo){
			$('div#modal-window').append(modalTarget);
			
			flashVideo = $('a.trailer').attr('data-video');
			flashVideoId = $(modalTarget).attr('id');
			flashVideoPoster = $('a.trailer').attr('data-poster');
			flashVideoTitle = flashVideo.replace(/.*\/(.*)\.(flv|mp4)$/,"$1");

			base.embedSWF(flashVideoId, flashVideo, flashVideoPoster, flashVideoTitle);
		}else{
			for(var i=0; i<el.length; i++){
				flashVideo = $(el[i]).attr('data-video');
				flashVideoId = $(el[i]).attr('id');
				flashVideoPoster = $(el[i]).children('img').attr('src');
				flashVideoTitle = flashVideo.replace(/.*\/(.*)\.(flv|mp4)$/,"$1");

				base.embedSWF(flashVideoId, flashVideo, flashVideoPoster, flashVideoTitle);
			}
		}
	},
	embedSWF:function(flashVideoId, flashVideo, flashVideoPoster, flashVideoTitle){
		var base = this;
		
		if(!base.options.videoHeight) base.options.videoHeight = base.options.swfHeight;
		if(!base.options.videoWidth) base.options.videoWidth = base.options.swfWidth;

		base.videoAnalytics();

		var settings = {
			path: '' + base.options.swfFile,
			width: base.options.swfWidth,
			height: base.options.swfHeight,
			version: base.options.flashVersion,
			id: flashVideoId,
			expressInstall: base.options.flashExpressIntall
		};
		
		var flashVars = {
			videoPath: flashVideo,
			videoHeight: base.options.videoHeight,
			videoWidth: base.options.videoWidth,
			posterPath: flashVideoPoster,
			accountStr: base.accountStr,
			countryStr: base.countryStr,
			langStr: base.langStr,
			pageNameStr: base.locPageName,
			videoTitle: flashVideoTitle,
			pageURL: window.location,
			prop7: '',
			prop10: 'Starfox 64 3D',
			prop11: '“Action Space Shooter',
			gameNameStr: 'Starfox 64 3D',
			liveBool: base.omnitureLiveBool,
			autoPlay: base.options.videoAutoPlay
		};

		var params = {
			allowscriptaccess: 'always',
			salign: "tl",
			wmode: 'transparent'
		};

		var attributes = { };

		if(base.options.externalVideo){
			flashVars.videoID = flashVideo;
			Metrix.YouTube(flashVideo);
		}else{
			flashVars.flvPath = base.options.mediaPath;// + '../_ui/video/' + flashVideo;
		}

    	swfobject.embedSWF(settings.path, settings.id, settings.width, settings.height, settings.version, settings.expressInstall, flashVars, params, attributes);
		base.options.callback.call(); 
	},
	videoAnalytics:function(){
		var base = this;

		base.langStr;
		base.countryStr;
		base.accountStr;
		base.pageNameStr;
		base.omnitureLiveBool;
		base.locURI = window.location.pathname.toString();
		base.locPathName = base.locURI.replace(/^\/(es|fr)\//i, '/');

		if (base.locURI.match(/^\/es\//)) {
			base.langStr = 'es';
			base.countryStr = 'mx';
			base.accountStr = 'ncomglobal,ncommxstarfox64';
		} else if (base.locURI.match(/^\/fr\//)) {
			base.langStr = 'fr';
			base.countryStr = 'ca';
			base.accountStr = 'ncomglobal,ncomcastarfox64';
		} else {
			base.langStr = 'en';
			base.countryStr = 'us';
			base.accountStr = 'ncomglobal,ncomstarfox64';
		}
		
		if (base.locPathName.match(/^\/$/) ||  base.locPathName.match(/^\/(index|default)/)) {
			base.locPathName = 'home';
		} else {
			base.locPathName = base.locPathName.replace(/^\//, '').replace(/\/$/, '').replace(/\//i, ':').replace(/\-|_/, ' ');
		}

		base.locPageName = base.countryStr + ':microsite:starfox 64 3d:' + base.locPathName;

		if(window.location.host.toString().match(/(^|\.)(nintendo|starfox643d)\.com$/)){
			base.omnitureLiveBool = 'true';
		} else {
			base.omnitureLiveBool = 'false';
			base.accountStr = 'ncomdev';
		}
	}
}

/**
*	Dynamically resize (img) element
**/
POP.resizeBg = function(target, options) {
	var self = this;
	self.el = $(target);
	self.options = $.extend({
		
	}, options || {});
	self.__init();
}

POP.resizeBg.prototype = {
	__init: function() {
		var self = this;
		self.win = $(window);
		self.__addEventListeners();
		//force resize event function when image has fully loaded (has image info)
		self.el.load(function() {
			self.__onWindowResize();
		});
	},
	__addEventListeners: function() {
		var self = this;
		$(window).bind('resize', function(e) {
			self.__onWindowResize();
		});
	},
	__onWindowResize: function(e) {
		var self = this,
			h = self.win.height(),
			w = self.win.width(),
			elH = self.el.height(),
			elW = self.el.width(),
			hRatio = elH / h,
			wRatio = elW / w;
		
		if(hRatio < wRatio) {
			self.el.css({
				'height': '100%',
				'width': 'auto'
			});
		}else {
			self.el.css({
				'height': 'auto',
				'width': '100%'
			});
		}
	}
}

/**
*	Fade in different elements
**/
POP.showHTML = function(targets, options) {
	var self = this;
	self.els = targets;
	self.len = self.els.length;
	self.options = $.extend({
		delay: 600,
		fadeInTime: 1000
	}, options || {});
	self.animate = (jQuery.support.opacity) ? true : false;
	self.__init();
}

POP.showHTML.prototype = {
	__init: function() {
		var self = this;
		for(var i = 0; i < self.len; i++) {
			$(self.els[i]).hide();
		}
	},
	show: function() {
		var self = this, touts = [];
		//Show elements incremently
		for(var i = 0; i < self.len; i++) {
			(function(j) {
				touts[j] = setTimeout(function() {
					if(self.animate) {
						$(self.els[j]).fadeIn(self.options.fadeInTime);
					}else {
						//No Opacity Browsers 
						$(self.els[j]).show();
					}
				}, j * self.options.delay);
			}(i));
		}
	}
}

/***functions for the global header***/
function twitterActivate() {
	base.exitUrl("http://twitter.com/share?text=Star Fox 64 3D for Nintendo 3DS. Check out the official site: http://starfox643d.nintendo.com");
	Omniture.trackTwitter();
}

function facebookActivate() {
	u=location.href;
	base.exitUrl('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&'+(new Date).valueOf());
	Omniture.trackFacebook();
}



if(window.location.host.toString().match(/(^|\.)nintendo\.com$/)){
	var mediaPath = '';
}else{
	var mediaPath = '';
}
$(function(){
	var modalBuyBtn = new POP.modalWindow($('#nav-preorder'), {className: 'modal-buy-now'});
});

/*** Tab Switcher for Downlevel ***/
var tabSwitcher = function() {
	
	$(".tab-content").hide(); //Hide all content
	$("ul.subnav li:first").addClass("active").show(); //Activate first tab
	$(".tab-content:first").show(); //Show first tab content

	$("ul.subnav li").click(function() {
		$("ul.subnav li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab-content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn("fast"); //Fade in the active ID content
		return false;
	});
};			

		
			
/*** Load On DOM Ready ***/

$(function(){
	jsEnabled();
	wiiFixes();
	dsiFixes();
	threeDSFixes();
//	var resizeBg = new POP.resizeBg('#flash-target img');
	
	var showHtml = new POP.showHTML(['.bg1']);
	window.jsShow = function() {
		showHtml.show();
		$('body').addClass('no-flash');
	}
		
	tabSwitcher();
	//window.jsShow();
	
	// buy 3DS button in header
	//$('.nintendo3DS-buy').click(function(event){
	//	event.preventDefault();
	//	window.open('http://www.nintendo.com/3ds/buy','Buy_Now','height=692,width=796,status=0,toolbar=0, location=0, menubar=0, resizable=0, scrollbars=0, directories=0');
	//});
	
	
	window.initBuyNow3ds = function() {
		window.open("http://www.nintendo.com/3ds/buy");
	}
	window.initBuyNow3dsFR = function() {
		window.open("http://www.nintendo.com/3ds/fr/buy");
	}
});
