// AddThis global config
var xMousePos;
var yMousePos;
var sharePopPosition;

var socialToolsId = "";
var socialToolsData = {};
var socialToolsTimeout = null;
var shareIpad = navigator && navigator.platform && navigator.platform.match(/^(iPad|iPod|iPhone)$/);

var addthis_config_ie = {
	ui_offset_top: 0,
	ui_offset_left: 0,
	username: 'infinitidotcom',
	ui_cobrand: 'INFINITI',
	ui_header_color: '#ffffff',
	ui_header_background: '#000000',
	ui_language: 'en',
	services_compact: !shareIpad ? 'email,facebook,twitter,delicious,live,yahoobkm,google' : 'email,facebook,twitter',
	ui_use_embeddable_services_beta: true,
	ui_click: false,
	data_link_trackback: true
}

var addthis_config = {
	username: 'infinitidotcom',
	ui_cobrand: 'INFINITI',
	ui_header_color: '#ffffff',
	ui_header_background: '#000000',
	ui_language: 'en',
	services_compact: !shareIpad ? 'email,facebook,twitter,delicious,live,yahoobkm,google' : 'email,facebook,twitter',
	ui_offset_top: 10,
	ui_offset_left: 0,
	ui_use_embeddable_services_beta: true,
	ui_click: false,
	data_link_trackback: true
}

// AddThis share data
var addthis_share = {
	url: 'http://www.infiniti.com',
	title: $('meta[name=title]').attr('content'),//'Test Title',
	description: $('meta[name=description]').attr('content'), //'Test Description'
	templates: {
    	twitter: '{{title}} {{url}}'
	}
}

var jsapiDebug = '';
var checkTimer = null;
var checkCount = 0;

function jsAPI() {
	this.cookiesEnabled = true;
	this.cookieDefaults =  {
		'region' : 'world|en'
	};
	
	this.sharingMeta = null;
	this.addThisWidth = 230;
	this.addThisHeight = 133;
	
	// cookie handling functions ////////////////////////////////////////////
	// pass expiryDays=0 for immediate expiry on browser close, otherwise defaults to 365 days
	this.setCookie = function(name, value, expiryDays) {
		if(this.cookiesEnabled) {
			var cookieStr = name + "=" + escape(value);
			if(typeof expiryDays == "undefined") expiryDays = 365;
			if(expiryDays != 0 ) {
				var date = new Date();
				date.setDate(date.getDate() + expiryDays);
				cookieStr += '; expires=' + date.toGMTString();
			}
			document.cookie = cookieStr + '; path=/';
		} else {
			this.cookieDefaults[name] = value;
		}
	}
	
	// returns NULL if not found
	this.getCookie = function(name) {
		var results = null;
		if(this.cookiesEnabled) {
			results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
			return results ? unescape(results[2]) : null;
		} else {
			results = this.cookieDefaults[name];
			return results ? results : null;
		}
		
	}

	// set cookie with negative expiry
	this.deleteCookie = function(name) {
		this.setCookie(name, '', -1);
	}

    // get the user's preferred language
    this.getPreferredUserLanguage = function() {
        // If the user has manually chosen a language on the Genkan page, the 'userSetLanguage' cookie will not be null
        var userSetLanguage = this.getCookie('userSetLanguage');

        if (userSetLanguage !== null) {
            return userSetLanguage;
        }

        // If not, we use the locale settings of the browser to determine the language
        var localeString;
        if (navigator.appName.indexOf('Explorer') != -1) {
            localeString = navigator.userLanguage || navigator.browserLanguage;
        }
        else {
            localeString = navigator.language;
        }

        // We only need the first two characters
        return localeString.slice(0,2);

    }
	
	// genkan     //////////////////////////////////////////////////////////////
	this.setGenkanCookie = function(name, value, expiryDays) {
		this.setCookie(name, value, expiryDays);

        this.setCookie('userSetLanguage',value.split('|')[1],expiryDays);
		
		if(regionTitles[value])
			document.title = regionTitles[value];
	}
	
	// wallpaper //////////////////////////////////////////////////////////////
	this.wallpaperPopup = function( modelName, width, height ){
		var url = appBase + 'global/'+language+'/models/' + modelName + '/wallpaper/' + width + 'x' + height;
		width = Math.min( screen.availWidth, width + 30 );
		height = Math.min( screen.availHeight, height + 95 );
		var options = 'scrollbars=yes,width=' + width + ',height=' + height;
		window.open( url, 'wallpaper', options );
	}
	
	// news popup //////////////////////////////////////////////////////////////
	this.newsPopup = function(story) {
		var url = appBase + 'global/'+language+'/infiniti-world/news-events/' + story + '/print';
		width = 670;
		height = 735;
		var options = 'scrollbars=yes,width=' + width + ',height=' + height;
		window.open( url, 'news', options );
	}
	
	// adeyaka popup //////////////////////////////////////////////////////////////
	this.adeyakaPopup = function(story) {
		var url = appBase + 'global/'+language+'/adeyaka-magazine/' + story + '/print';
		width = 670;
		height = 735;
		var options = 'scrollbars=yes,width=' + width + ',height=' + height;
		window.open( url, 'adeyaka', options );
	}
	
	// inspirations popup //////////////////////////////////////////////////////////////
	this.inspirationsCirqueFeaturedPopup = function(story) {
		var url = appBase + 'global/'+language+'/inspirations/cirque-du-soleil/featured/' + story + '/print';
		width = 670;
		height = 735;
		var options = 'scrollbars=yes,width=' + width + ',height=' + height;
		window.open( url, 'inspirations', options );
	}
	
	// mailTo popup //////////////////////////////////////////////////////////////
	this.mailToPopup = function(subject, messageBody, mailToLink) {
		var mailTo = 'mailto:?Subject='+encodeURIComponent(subject)+'&Body='+messageBody;
		var tempMailToLink = mailToLink;
		
		if(tempMailToLink) {
			//eg. http://infiniti.com/global/en/home#/infiniti-world/news-events
			tempMailToLink = document.location.protocol + '//' + document.location.hostname + '/global/' + language + mailToLink.split('#')[1];
		} else tempMailToLink = '';
		
		mailTo = mailTo+'%0D%0A'+tempMailToLink;
		
		var win = window.open(mailTo,'emailWindow');
		
		if (win && win.open &&!win.closed)
			win.close();
	}
	
	// omniture tracking functions //////////////////////////////////////////
	
	// should accept both absolute and relative URLs
	this.trackPage = function(url, siteVersion, type) {
		var i; // temp var for indexes
		var flashVer = swfobject.getFlashPlayerVersion();
		
		// strip jsessionid from end
		if((i = url.indexOf(';jsessionid=')) != -1)
			url = url.substring( 0, i );
			
		// strip # from end
		if((i = url.indexOf('#')) != -1)
			url = url.substring( 0, i );
			
		// strip trailing slash
		if(url.charAt(url.length-1 ) == '/')
			url = url.substring(0, url.length - 1);

		// strip host from start
		if(url.indexOf(host) == 0)
			url = url.substring(host.length);
			
		// strip appBase from start
		if(url.indexOf(appBase) == 0)
			url = url.substring(appBase.length);
		
		//url eg. inspirations/inspired-performance/introduction 
		var segments = url.split("/");
		
		s.server = 'server1';
		s.events = 'event20'; // Page View
		s.pageName = url;
		
		s.prop21 = language;
		s.prop27 = flashVer.major + '.' + flashVer.minor + '.' + flashVer.release;
		s.prop30 = 'Infiniti Global';
		s.prop31 = s.prop30 + '>' + s.pageName;
		s.prop34 = this.getCookie('region').split('|')[0]; //Current regional site
		
		if(siteVersion != null && siteVersion.toLowerCase() == 'flash'){
			siteVersion = 'Flash';
		}
		
		s.prop41 = (siteVersion == undefined) ? 'Flash' : siteVersion;
		
		s.hier1 = s.pageName;
		
		s.eVar28 = s.pageName;
		s.eVar33 = s.prop34;
		s.eVar34 = s.prop21;
		s.eVar39 = s.prop30;
				
		if(segments.length == 1) {
			if(segments[0] == 'home') {
				s.channel = 'home';
			} else if(segments[0] == 'index') {
				s.channel = 'Genkan';
				if(document.location.pathname.match(/^\/world/))
					s.prop36 = 'no';
				else
					s.prop36 = 'yes';
				
				s.eVar36 = s.prop36;
			} else if(segments[0] == 'sitemap') {
				s.channel = 'Footer';
			} else if(segments[0] == 'sitemap') {
				s.channel = 'Footer';
			} else if(segments[0] == 'country-selector') {
				s.channel = 'Footer';
			}
		} else if(segments.length >= 2) {
			if(segments[0] == 'adeyaka-magazine') {
				s.channel = 'adeyaka';
			};
			if(segments[0] == 'home'){
				s.channel = 'home';
			}
			if(segments[0] == 'inspirations') {
				s.channel = 'Inspirations';
				
				if(segments[1] == 'inspired-performance') {
					
				} else if(segments[1] == 'living-luxury') {
					
				} else if(segments[1] == 'expressive-design') {
					
				} else if(segments[1] == 'transforming-motion') {
					
				}
			} else if(segments[0] == 'models') {
				s.channel = 'Models';
				s.events = s.events + ', event22';
				if(segments[1].indexOf('?') != -1){
					s.prop20 = segments[1].split('?')[0]
				} else {
					s.prop20 = segments[1];
				}
				s.eVar29 = s.prop20;
			} else if(segments[0] == 'infiniti-world') {
				s.channel = 'Infiniti World';
				
				if(segments[1] == 'news-events') {
					if(segments[2].match(/^[\d][\d][\d][\d]-[\d][\d]-[\d][\d]-/)) {
						//&& segments[3] == 'features' && segments[4] == 'article'
						s.prop33 = segments[2];
						s.eVar31 = s.prop33;
					}
				} else if(segments[1] == 'infiniti-tv') {
					
				}
			} else if(segments[0] == 'about') {
				s.channel = 'Footer';
			}
		}
				
		//Since channel is now determined, set the Section Name 
		s.eVar32 = s.channel;
		//elementool request 2689 - coryj on 2/24/2010 - start
		s.eVar45=s.prop41;
		//elementool request 2689 - coryj on 2/24/2010 - end
		
		if(typeof type != 'undefined'){
			if(type == 'media-start'){
				s.events += ', event33';
			} else if(type == 'media-stop') {
				s.events += ', event34';
			}
		}
		
		
		//there is a handler on the html site so we don't need to execute this here for that section
		if(section != 'html') {
			var s_code=s.t();
			if(s_code) document.write(s_code);
		}
		// Clearing variables in the s object for Flash support
		//Remember to add to this if there are new props/eVars
		if(s.prop41.toLowerCase() == 'flash') {
			s.prop20 = '';
			s.prop33 = '';
			s.prop36 = '';
			s.eVar29 = '';
			s.eVar31 = '';
			s.eVar32 = '';
		}
		
		if(this.checkMeta) this.checkMeta();
	};
	
	/*
	  * @param type: one of 'click', 'exit', 'country-select', 'region-default-prompt', or 'download'
	  * @param name: the name of the link
	  * @param url: the URL of the link.  Only required for exit and download links
	  * 
	  * eg. document.jsAPI.trackLink('click', 'press-release', '/something/fun')
	  */
	this.trackLink = function(type, name, url){	
		// window.open("http://www.google.com");		
		var linkObj = true;
		var backname = null;
		var linkType = 'o';
		
		//var pageChanging = false;
		s.prop32 = name;
		s.eVar27 = s.prop32;
		s.events = 'event21';
		s.linkTrackVars = 'prop32,eVar27';
		s.linkTrackEvents = '';
		
		switch(type){
			case 'click':
				s.linkTrackVars = s.linkTrackVars + ',events';
				break;
			case 'body-click':
				s.events = 'event31'; //body path click
				s.linkTrackVars = s.linkTrackVars + ',events';
				break;
			case 'nav-path':
				s.events += ',event32'; //body path click
				s.linkTrackVars = s.linkTrackVars + ',events';
				break;
			case 'exit':
				s.events = s.events + ',event23,event28';
				s.prop39 = 'Non-Infiniti Site';
				
				s.prop40 = name;
				linkObj = $('<a href="'+url+'"></a>')[0];
				linkType = 'e';
			
				internalFilters = s.linkInternalFilters.split(',');
			
				for(i = 0; i < internalFilters.length; i++) {
					if(url.indexOf(internalFilters[i]) > -1) {
						s.prop39 = 'Infiniti Region Site';
						linkType = 'o';
					
						s.prop43 = this.getCookie('region');
						s.eVar44 = s.prop43;
						s.linkTrackVars = s.linkTrackVars + ',prop43,eVar44';
					}
				}
				if(name.indexOf('infiniti-worldwide-link') != -1){
					s.prop39 = 'Infiniti Region Site';
				}
			
				// TODO, account for non-region (i.e. microsites), prop39 should be 'Infiniti Other Site'
			
				s.eVar42 = s.prop39;
				s.eVar43 = s.prop40;
				s.linkTrackVars = s.linkTrackVars + ',prop39,prop40,eVar42,eVar43,events';
			
				//pageChanging = true;
				break;
			case 'pop-up-window': // same as exit, but opens a pop-up browser window
				s.events = s.events + ',event23,event28';
				s.prop39 = 'Non-Infiniti Site';
				s.prop40 = name;
				linkObj = $('<a href="'+url+'"></a>')[0];
				linkType = 'e';
				
				internalFilters = s.linkInternalFilters.split(',');
				
				for(i = 0; i < internalFilters.length; i++) {
					if(url.indexOf(internalFilters[i]) > -1) {
						s.prop39 = 'Infiniti Region Site';
						linkType = 'o';
						
						s.prop43 = this.getCookie('region');
						s.eVar44 = s.prop43;
						s.linkTrackVars = s.linkTrackVars + ',prop43,eVar44';
					}
				}
				
				// TODO, account for non-region (i.e. microsites), prop39 should be 'Infiniti Other Site'
				
				s.eVar42 = s.prop39;
				s.eVar43 = s.prop40;
				s.linkTrackVars = s.linkTrackVars + ',prop39,prop40,eVar42,eVar43,events';
				
				//pageChanging = true;

				window.open(url);		

				break;
			case 'download':
				s.events = s.events + ',event26';
				s.prop29 = name;
				s.eVar38 = s.prop29;
				s.linkTrackVars = s.linkTrackVars + ',prop29,eVar38,events';
				
				linkType = 'd';
				break;
			case 'country-select':
				s.events = s.events + ',event24';
				s.linkTrackVars = s.linkTrackVars + ',events';
				break;
			case 'region-default-prompt':
				s.prop35 = (name == 'Genkan region default clicked yes') ? 'yes' : 'no'; //Regional Default
				s.eVar35 = s.prop35;
				s.linkTrackVars = s.linkTrackVars + ',prop35,eVar35,events';
				linkObj = this;
				
				break;
			case 'region-change':
				s.prop34 = name.split('|')[0];
				s.eVar33 = s.prop34;
				s.linkTrackVars = s.linkTrackVars + ',prop34,eVar33,events';
				
				break;
			case 'region-default-prompt-view':
				s.linkTrackVars = s.linkTrackVars + ',events';
				s.events = s.events + ',event25';
				
				break;
			case 'brand-experience-exit':
				s.prop43 = this.getCookie('region');
				s.eVar44 = s.prop43;
				s.linkTrackVars = s.linkTrackVars + ',prop43,eVar44,events';
				
				//pageChanging = true;
				
				break;
			case 'flash-upgrade':
				s.linkTrackVars = s.linkTrackVars + ',events';
				s.events = s.events + ',event27';
				
				break;
			case 'logo-home':
				s.linkTrackVars = s.linkTrackVars + ',prop31,eVar28,eVar32,events';
				break;
				
			case 'regional-site-button':
				s.eVar42 = 'Infiniti Region Site Button';
				s.prop39 = 'Infiniti Region Site Button';
				s.eVar43 = s.eVar27;
				s.prop40 = s.prop32;		
				s.linkTrackVars = s.linkTrackVars + ',prop39,eVar28,eVar42,eVar43,prop40,events';
				break;				
		}
		
		s.linkTrackEvents = s.events;
		
		s.tl(linkObj, linkType, name);
		
		//Clear all variables so next page track does not retain data
		//Remember to add to this if there are new props/eVars
		if(s.prop41.toLowerCase() == 'flash') {
			s.prop29 = '';
			s.prop32 = '';
			s.prop34 = '';
			s.prop35 = '';
			s.prop39 = '';
			s.prop40 = '';
			s.prop43 = '';
			s.eVar27 = '';
			s.eVar33 = '';
			s.eVar35 = '';
			s.eVar38 = '';
			s.eVar42 = '';
			s.eVar43 = '';
			s.eVar44 = '';
		}
		
		//Change location if identified as Flash
		if (type.toLowerCase() == 'exit' || type.toLowerCase() == 'brand-experience-exit'){
			if(s.prop41.toLowerCase() == 'flash' && name.indexOf('infiniti-worldwide-link') == -1 && name.indexOf('contact-us-link') == -1) {
				var redirect = function() {
					if($.browser.msie){
						//Use alternate redirection method for ie because of a bug where tje referer is not passed when using document.location
						var referLink = document.createElement('a');
						referLink.href = url;
						document.body.appendChild(referLink);
						referLink.click();
					}
					else{
						//For all other browsers this works
						document.location = url;
					}
				}
				self.setTimeout(redirect,500); // wait 500 ms max to allow time for Omniture response
			}
		}
		
	
	if(this.checkMeta) this.checkMeta();
	}
	
	/* Media Tracking */
	this.trackMedia = function(mediaName, status, currentTime, totalTime) {
		    switch(status) {
		        case 'start':
		        s.Media.open(mediaName, totalTime, 'Flash Media Player');
		        break;
		        case 'play':
		        s.Media.play(mediaName, 0);
		        break;
		        case 'finish':
		        s.Media.stop(mediaName, currentTime);
		        s.Media.close(mediaName);
		        break;
		        case 'stop':
		        s.Media.stop(mediaName, currentTime);
		        break;
		    }
		}
	
	this.trackExpressInstall = function(prop) {
		var flashVer = swfobject.getFlashPlayerVersion();
		
		s.prop37 = prop;
		s.prop38 = (prop == 'Flash Upgrade Dialog Viewed') ? flashVer.major + '.' + flashVer.minor + '.' + flashVer.release : null;
		s.eVar40 = s.prop37;
		s.eVar41 = s.prop38;
		s.events = 'event21,event27';
        s.linkTrackVars =  (s.prop38 == null) ? 'events,prop37,eVar40' : 'events,prop37,prop38,eVar40,eVar41';
        s.linkTrackEvents = s.events;
		s.tl(false,'o', 'Flash Express Install');
	};
	
	this.addThis = function(strX, strY, popColour, popBGColour){
		
		var d = new Date();
		// check validity of data, otherwise fill with default info
		this.checkMetaValidity(strX, strY, popColour, popBGColour);
	};
	
	this.openSurvey = function(){
        omniture('/survey');
		url = "/static/media/sgframe.html";
		width = 725;
		height = 580;
		winl = (screen.width-width)/2;
		wint = (screen.height-height)/2;
		var options = 'left='+winl+',top='+wint+',screenX='+winl+',screenY='+wint+',resizable=0,toolbar=0,status=0,location=0,scrollbars=yes,width=' + width + ',height=' + height;
		window.open( url, 'survey', options );
	}
	
	
	this.checkMetaValidity = function(strX, strY, popColour, popBGColour){
		var deeplinkID = window.location.hash.substring(1);
		s.pageName = SWFAddress.getValue() + '/social_share_button';
		document.jsAPI.sharePopup(strX, strY, popColour, popBGColour);
	}
	
	this.sharePopup = function(strX, strY, popColour, popBGColour){
		// debug
		var d = new Date();
		jsapiDebug = jsapiDebug + 'this.sharePopup executed @'+ d + '\r\n';
		
		// get the dimensions of the addthis popup
		if(this.addThisWidth == null) this.addThisWidth = $('#at15s').width();
		if(this.addThisHeight == null) this.addThisHeight = $('#at15s').height();
		
		// desired position for popup
		var x = parseInt(strX);
		var y = parseInt(strY);
		
		// window dimensions
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		
		// figure out the correct orientation and position of popup y axis first and then x axis
		if((y + this.addThisHeight) >= windowHeight){
			// direction up
			addthis_config.ui_offset_top = y + 25;
			addthis_config.ui_hover_direction = 1;
			
			if((x + this.addThisWidth) <= windowWidth){
				// direction right
				addthis_config.ui_offset_left = x - 5;
				sharePopPosition = 2;
			}else{
				// direction left
				addthis_config.ui_offset_left = x - 195;
				sharePopPosition = 4;
			}
		}else{
			// direction down
			addthis_config.ui_offset_top = y - 25;
			addthis_config.ui_hover_direction = -1;
			
			if((x + this.addThisWidth) <= windowWidth){
				// direction right
				addthis_config.ui_offset_left = x - 5;
				sharePopPosition = 1;
			}else{
				// direction left
				addthis_config.ui_offset_left = x - 195;
				sharePopPosition = 3;
			}
		}
		
		// get meta data for sharing
		getSharingMeta();
		
		// replace the hidden addthis link and setup addthis again
		$('#addthis').remove();
		$('body').prepend('<a href="#" id="addthis"></a>');
		addthis.button('#addthis', addthis_config, addthis_share);
		
		// trigger the addthis popup a different event is used if the device supports touch like ipad/iphone
		if('ontouchstart' in window) $('#addthis').trigger('click');
		else $('#addthis').trigger('mouseover');
	}
	
	//Test cookie support
	this.setCookie('testCookies', 'value');
	this.cookiesEnabled = (this.getCookie('testCookies') != null) ? true : false;

	//Check to see if user moused off the Share link - wait a second
	this.shareButtonMouseOut = function(){
		$('#at15s').mouseout(function(){
			addthis_close();
		});
	}
	
	/* new addthis functions 
	 * @type = details or footer
	 * @strX = x
	 * @strY = y
	 * */
	this.showSocialTools = function (type, strX,strY){
		type = !type ? 'footer' : type;
		socialToolsId = '#social-media-'+type;
		socialToolsData = {	'top': strY+'px', 'left': strX+'px'};
		if(type == 'footer'){
			if(socialToolsTimeout != null){
				socialToolsTimeout = null;
			}
			socialToolsTimeout = setTimeout("timedSocialTools()", 50)
		} else {
			timedSocialTools();
		}
	}
	
	this.hideSocialTools  = function(type){
		$('#social-media-'+type).css('left', '-3000px');
	}
	
	this.sendToFacebook = function(){
		var href_fbook = 'http://api.addthis.com/oexchange/0.8/forward/facebook/offer?url=' + escape(addthis_share.url);
		href_fbook += '&title=' + addthis_share.title;
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'facebook');
		window.open(href_fbook);
	}
	this.sendToTwitter = function(){
		addthis_sendto('twitter', addthis_config, addthis_share);
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'twitter');
	}
	this.sendToPrint = function(){
		printArticle(htmlSafe+'/print');
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'print');
	}
	this.sendToEmail = function(){
		socialHash = SWFAddress.getValue() + '/social_external_button_';
		omniture('/social_external', 'pageTracking', true, socialHash + 'email');
		addthis_sendto('email');
	}
	
	this.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;	
	}
	
	this.setGalleryImage = function(i){
		galleryImage = i; 
	}
	
};
	
document.jsAPI = new jsAPI();

timedSocialTools = function(){
	$(socialToolsId).css(socialToolsData).show();
}
