var suppressPushDeeplink = false;

function pushDeeplink (id) {
	if(suppressPushDeeplink)
	{
		/*
		try{
			getSWF("loader").updateDeeplink(id);
		}catch(e){
		  ;  
		}
		*/
	}
	else
	{
		try{
			getSWF("loader").pushDeeplink(id);
		}catch(e){
		  ;  
		}
	}
}

function jsAPI () {
	
	this.numWatchInteractions = (getCookie("numWatchInteractions") != "" ? getCookie("numWatchInteractions") : 0);
	
	/* HISTORY HANDLER */
    this.onHistoryChangeHandler = function(data){
    	//alert("onHistoryChangeHandler data: " + data + ", suppressPushDeeplink: " + suppressPushDeeplink);
    	
    	pushDeeplink(data);
    };
    
    unFocus.History.Keeper.addEventListener('historyChange', this.onHistoryChangeHandler);

    this.addHistory = function(data) {
        suppressPushDeeplink = true;
        unFocus.History.Keeper.addHistory(data);
        suppressPushDeeplink = false;
    };
    
    this.writeTitle = function(title) {
		//check for flash's duplicate title bug
		var parts = title.split(">");		
		if (parts.length > 1){
			if (parts[0].replace(/^\s+|\s+$/g,"").toLowerCase() != parts[1].replace(/^\s+|\s+$/g,"").toLowerCase()){
				 document.title = unescape(title);
			}
		}
       
    }
	this.isReady = function() {
		return true;
	}

    this.getCurrentState = function() {
    };
    
    this.setCookie = function(deeplink, lang){
        document.cookie = "lang2="+lang+"; expires="+expireOffset+"; path=/;";
		goLangDeeplink(deeplink);
    }   

	/* TRACKING */

    this.trackPage = function(channel, section, watchId) {

		var watchIdParts = watchId.split(':homepage');
		s.pageName = (watchIdParts[0] + ":" + section).toLowerCase();
		s.channel = channel;
		s.server = "server1";
		s.prop15 = lang;
		s.prop19 = (flashEmbedded ? "flash" : "html");
		s.prop21 = "";
		s.prop26 = ""; //reset
		//traffic
		s.prop3 = watchIdParts[0];
		//conversion
		s.eVar17 = watchIdParts[0];
		s.eVar24 = ""; //reset
		s.eVar25 = ""; //reset

		if (section=="catalogue"){
			if(watchIdParts.length > 1) { //Requires extra variables set if :homepage is part of the page name for the gallery
				s.pageName = (watchIdParts[0]+':'+section).toLowerCase();
				s.prop26 = watchIdParts[0].toLowerCase();
			}
			s.events = "event1,event21";
		} else {
			s.events = "event1,event22";
			this.numWatchInteractions++;
			if (this.numWatchInteractions == 1){
				s.events += ",event27";
			} else if (this.numWatchInteractions == 3){
				s.events += ",event28";
			} else if (this.numWatchInteractions == 5){
				s.events += ",event29";
			}
		}
		createCookie("numWatchInteractions", this.numWatchInteractions);
		var s_code=s.t();
		if(s_code)document.write(s_code);
	};
	
	this.trackarch2Page = function(channel, pageName){
		s.pageName = pageName;
		s.channel = channel;
		s.server = "server1";
		s.prop1 = channel;
		s.prop15 = lang;
		s.prop19 = (flashEmbedded ? "flash" : "html");
		s.prop21 = "";
		s.eVar12 = pageName;
		s.eVar24 = ""; //reset
		s.eVar25 = ""; //reset
		s.events="event1";
		var s_code=s.t();
		if(s_code)document.write(s_code);
	}
	
	this.trackOfficialDealers = function(channel, pageName){
		s.pageName = pageName;
		s.channel = channel;
		s.server = "server1";
		s.prop1 = channel;
		s.prop15 = lang;
		s.prop19 = (flashEmbedded ? "flash" : "html");
		s.prop21 = "";
		s.eVar12 = pageName;
		s.eVar24 = ""; //reset
		s.eVar25 = ""; //reset
		s.events="event1";
		var s_code=s.t();
		if(s_code)document.write(s_code);
	};
	
	this.trackOfficialDealersClick = function(pageName, linkId){
		s.pageName = pageName;
		switch(linkId){
			case 'faq-menu-buying':
				this.trackLink(pageName, linkId, 'faq:buying_rolex_watch');
			break;
			case 'faq-menu-maintaining':
				this.trackLink(pageName, linkId, 'faq:maintaining_rolex_watch');
			break;
			case 'faq-menu-authenticity':
				this.trackLink(pageName, linkId, 'faq:authenticity');
			break;
			case 'bottom-link-dealers':
				this.trackLink(pageName, linkId, 'store-locator:dealers');
			break;
			case 'bottom-link-affiliates':
				this.trackLink(pageName, linkId, 'store-locator:affiliates');
			break;
			case 'bottom-link-faq':
				this.trackLink(pageName, linkId, 'faq:buying_rolex_watch');
			break;
			case 'bottom-link-expertise':
				this.trackLink(pageName, linkId, 'faq:expertise_rolex_dealers');
			break;
			default:this.trackLink(pageName, linkId, '');
		}
		
	};
	
	this.trackOfficialDealersEvent = function(eventId, eventValue, url){
		//set pagename to country
		pageNameParts = s.pageName.split(":");
		s.pageName = pageNameParts[0] + ":" + pageNameParts[1] + (pageNameParts.length > 2 ? ":" + (eventId=="affiliate-shown" ? eventValue : pageNameParts[2]) : "");
		switch(eventId){
			case 'city-changed':
				s.events = "event34";
				s.eVar27 = eventValue;
				s.linkTrackVars = "events,eVar27";
			break;
			case 'district-changed':
				s.events = "event35";
				s.eVar28 = eventValue;
				s.linkTrackVars = "events,eVar28";
			break;
			case 'dealer-shown':
				s.events = "event33";
				s.eVar29 = eventValue;
				s.linkTrackVars = "events,eVar29";
			break;
			case 'affiliate-shown':
				s.events = "event38";
				s.eVar30 = eventValue;
				s.linkTrackVars = "events,eVar30";
			break;
			case 'dealer-clickthrough':
				s.events = "event36";
				s.linkTrackVars = "events";
				if (url){
					newWindow = window.open(url);
					newWindow.focus();
				}
			break;
			case 'affiliate-clickthrough':
				s.events = "event37";
				s.linkTrackVars = "events";
				if (url){
					newWindow = window.open(url);
					newWindow.focus();
				}
			break;
		}
		s.linkTrackEvents = s.events;
		s.tl(this, 'o', s.pageName);
	};
	
	this.trackHomepage = function(channel, pageName) {
			s.pageName = pageName;
			s.channel = channel;
			s.server = "server1";
			s.prop1 = channel;
			s.prop15 = lang;
			s.prop19 = (flashEmbedded ? "flash" : "html");
			s.prop21 = "";
			s.eVar12 = pageName;
			s.eVar24 = ""; //reset
			s.eVar25 = ""; //reset
			s.events="event1";
			var s_code=s.t();
			if(s_code)document.write(s_code);
	};
	
	this.trackHomepageLink = function(linkId, popUp) {
		s.events = "";
		switch(linkId) {
			case 'context-link-1': //context link 1 
				try{this.trackLink('homepage', 'Datejust_36mm_Homepage_Link>Gallery_Datejust_36mm', 'datejust-36mm:catalogue')}catch(e){}
			break;
			case 'context-link-2': //context link 2 
				try{this.trackLink('homepage', 'Datejust_36mm_Homepage_Link>Oyster_Perpetual_Gallery', 'catalogue')}catch(e){}
				//goDeeplink('/'+lang+'/world-of-rolex/sports-culture/spotlight/roger-federer/index.jsp');
			break;
			case 'context-link-3': //context link 3
				try{this.trackLink('homepage', 'Datejust_36mm_Homepage_Link>Datejust_36mm_Downloads', 'homepage')}catch(e){}
			break;
			case 'watch-face-1': //watch face 1
				try{this.trackLink('homepage', 'Datejust_36mm_Homepage_Watch>Gallery_Datejust_36mm', 'datejust-36mm:catalogue')}catch(e){}
			break;
			case 'feature-1': //feature-1 from flyout
				try{this.trackLink('homepage', 'Homepage_Features_Bar>Obsession_with_Perfection', 'The_Rolex_Company:An_Obsession_With_Perfection')}catch(e){}
			break;
			case 'feature-2': //feature-2 from flyout
				try{this.trackLink('homepage', 'Homepage_Features_Bar>Rolex_Awards', 'http://rolexawards.com/en/index.jsp')}catch(e){}
				if (popUp) {
					newWindow = window.open("http://rolexawards.com/en/index.jsp");
					newWindow.focus();
				}
			break;
		}
	};
	this.trackFedererLink = function(linkId) {
		switch(linkId) {
		case 'federer-link-1':
		goDeeplink('/'+lang+'/world-of-rolex/sports-culture/spotlight/roger-federer/index.jsp');
		break;
		}
	};
		
	//Adding Tracking for Cobranding Links
	this.trackCobranding = function(currentPage, linkId, destinationPage, dealerId){
		currentPage = currentPage.toLowerCase();
		destinationPage = destinationPage.toLowerCase();
		s.pageName = currentPage;
		s.prop21 = currentPage + ":" +linkId + ":" + destinationPage;
		if(linkId.indexOf("nav-footer-cobranded") > -1){
		s.events = "event31";
		} else {
		s.events = "event30";	
		}
		s.eVar26 = dealerId;
		var s_code=s.t();
		if(s_code)document.write(s_code);
		
	};
	
	// track cobranding box on load
	this.trackCobranding = function(channel, pageName) {
		if (s.events.indexOf("event32") > -1){
			s.events+="";
		}
			s.events+=",event32";
			var s_code=s.t();
			if(s_code)document.write(s_code);
	};
	
	// track onload for Sprit of Achievement
	this.trackSpiritofAchievement = function(channel, pageName) {
		s.pageName = pageName;
		s.channel = channel;
		s.server = "server1";
		s.prop1 = channel;
		s.prop15 = lang;
		s.prop19 = (flashEmbedded ? "flash" : "html");
		s.prop21 = "";
		s.eVar12 = pageName;
		s.eVar24 = ""; //reset
		s.eVar25 = ""; //reset
		s.events="event1";
		var s_code=s.t();
		if(s_code)document.write(s_code);
	};
	
	// track onload for Defining Moments
	this.trackDefiningMoments = function(channel, pageName) {
		s.pageName = pageName;
		s.channel = channel;
		s.server = "server1";
		s.prop1 = channel;
		s.prop15 = lang;
		s.prop19 = (flashEmbedded ? "flash" : "html");
		s.prop21 = "";
		s.eVar12 = pageName;
		s.eVar24 = ""; //reset
		s.eVar25 = ""; //reset
		s.events="event1";
		var s_code=s.t();
		if(s_code)document.write(s_code);
	};
	
	this.trackLink = function(currentPage, linkId, destinationPage){
		s.events = "";
		if(linkId.indexOf("filter-list") > -1){
			var parts = linkId.split('>');
			if (parts.length == 3){
				s.eVar24 = parts[1];
				s.eVar25 = parts[1] + "_" + parts[2];
			}
			s.events = "event25";
		} else{
			s.eVar24 = "";
			s.eVar25 = "";
		}
		currentPage = currentPage.toLowerCase();
		destinationPage = destinationPage.toLowerCase();
		s.pageName = currentPage;
		s.eVar18 = currentPage;
		var p21 = currentPage.replace(/:/g,">") + ":" + linkId + ":" + destinationPage.replace(/:/g,">");
		s.prop21 = p21.toLowerCase();
		s.events += (s.events != '' ? "," : "") + "event20";
		s.linkTrackVars = "events,prop21" + (s.eVar24 != null && s.eVar25 != null ? ',eVar24,eVar25' : '');
		s.linkTrackEvents = s.events;
		s.prop15 = lang; //global var
		s.tl(this, 'o', currentPage);
	};

	
	this.trackCatalogueClick = function(href, navName, currentWatchId){
		s.events = "";
		model = href.match(/(M[0-9]+[a-z]*-?[0-9]*)/ig);
		if(model == null) {// for basel URLs
			if (flashEmbedded){
				model = href;
			} else{
				model = href.match(/2009-collection\/[a-z0-9-]*/ig)[0].replace('2009-collection/', 'basel09 ').replace('-', ' ');
			}
		}
		this.trackLink(currentWatchId+":catalogue", navName.replace(/:/g,">"), model+":catalogue");
	};
	
	this.trackBrochureClick = function(href, navName, flashDestination){
		s.events = "";
		target = "brochure";
		hrefParts = href.split('/');
		if (navName == "close"){
			target = "catalogue";
		} else if (navName == "brochure-nav"){
			target += ":" + hrefParts[hrefParts.length-3] + ":" + hrefParts[hrefParts.length-2];
		} else if (navName == "left-arrow" || navName == "right-arrow" || navName == "bottom-nav"){
			target += ":" + hrefParts[hrefParts.length-3] + ":" + hrefParts[hrefParts.length-2];
		}
		model = href.match(/(M[0-9]+[a-z]*-?[0-9]*)/ig);
		if (model == null){
			pageNameParts = s.pageName.split(':');
			model = pageNameParts[0];
		}
		target = target.replace("brochure:brochure:","brochure:");
		if (target.indexOf("servlet") > -1){
			target = "download-pdf";
		}
		this.trackLink(s.pageName, navName, model+":"+(flashDestination != null ? flashDestination : target));
	}

	
	this.trackVideo = function(channel, flashDestination, watchCode, mediaName, control, seconds, total){
		if (control == "play"){
			s.Media.open(mediaName, total, "Flash Media Player");
			s.Media.play(mediaName, 0);
		} else if (control == "forward"){
			s.Media.stop(mediaName, seconds);
		} else if (control == "finish"){
			s.Media.close(mediaName);
		}
		var s_code=s.t();
		if(s_code)document.write(s_code);
	};
	
	this.trackDownload = function(channel, section, url){
		//channel + section are for backward compatibility
		s.tl(this,'d', url);
		if(/.pdf/i.test(url) || /.wmv/i.test(url) || /.mov/i.test(url)) {
			newWindow = window.open(url,'newWindow','');
			newWindow.focus();
		} else {
			document.location = url;
		}
		return false;
	};
	
	this.trackExit = function(destination, popup) {
		s.prop20 = destination;
		s.events = "";
		s.linkTrackVars = "events,prop20";
		s.linkTrackEvents = s.events;
		s.tl(this, 'e', destination);
		if(popup)
			window.open(destination);
		else
			window.location(destination);
	};
	
		
	this.recordSlowConnectionMetrics = function(loadTime, seenSlowMessage){
        //send a xiti/omniture hit to record slow connection
        //xitiFlashSlowConnection(loadTime, seenSlowMessage);
    };
	
	/* SPEED */
	 this.disableFlash = function() {
        document.cookie = "disableFlash=true; path=/";
        document.location.href = document.location.href;
		this.trackLink("flash_disabled", "flash_disabled", destinationPage)
    };

	this.trackExpressInstall = function(eVar) {
		s.eVar21 = eVar;
		s.events = "event16";
        s.linkTrackVars = "events,eVar21";
        s.linkTrackEvents = s.events;
		s.tl(false,'o', 'Flash Express Install');
	};
	
	
	this.trackNavLink = function(linkName, currentPageName, nextPageName){
		this.trackLink(currentPageName, linkName, nextPageName);
	};
	
	this.trackFooterLink = function(linkName, currentPageName, nextPageName){
		this.trackLink(currentPageName, linkName, nextPageName);
	};
};
document.jsAPI = new jsAPI();

// Function to dynamically load Background CSS file for HTML if JS and no Flash is detected
function loadJSImages(filename){
	var fileref = document.createElement("link");
	fileref.setAttribute("rel", "stylesheet");
	fileref.setAttribute("type", "text/css");
	fileref.setAttribute("href", filename);
	if (typeof fileref!="undefined")
	document.getElementsByTagName("head")[0].appendChild(fileref);
}



function getSWF (movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }
    else {
        return document[movieName];
    }
}

function historyHandler () {    
    // this is the public method that will be called to add an entry
    
    // the method that will take updates from the History Keeper
    this.addHistory = function(data) {
        suppressPushDeeplink = true;
        unFocus.History.Keeper.addHistory(data);
        suppressPushDeeplink = false;
    };

    this.writeTitle = function(title) {
		//check for flash's duplicate title bug
		var parts = title.split(">");		
		if (parts.length > 1){
			if (parts[0].replace(/^\s+|\s+$/g,"").toLowerCase() != parts[1].replace(/^\s+|\s+$/g,"").toLowerCase()){
				 document.title = unescape(title);
			}
		}
    }
    this.isReady = function() {
		return true;
	}
	
    this.flashReady = function(){
         /* try{          
            getSWF("loader").SetVariable("htmlHeight", height);
            getSWF("loader").SetVariable("htmlWidth", width);
            flash = true;
        }catch(e){
            return false;
        } */
        return true;    
    };

    // add the event listener
    // A private method would not be properly scoped, and could not update state.
    this.getCurrentState = function() {
        //always was here alert(state);
    };

    //setCookie method for internal Flash pages
    /*
    this.setCookie = function(lang){
        document.cookie = "lang2="+lang+"; expires="+expireOffset+"; path=/;";
		goLocation(lang);
    }
    */

    this.setCookie = function(deeplink, lang){
        document.cookie = "lang2="+lang+"; expires="+expireOffset+"; path=/;";
		goLangDeeplink(deeplink);
    }

   	this.htmlSectionClick = function(redirURL) {
		goDeeplink(redirURL);
	};

    // These page tracking functions must live inside the HistoryHandler object
    // in order to prevent a Flash/JS display bug in IE6
    this.pageTrack = function(xiti_section, xiti_page, spotlight_section, spotlight_page) {
        pageTrack(xiti_section, xiti_page, spotlight_section, spotlight_page);
    };
    
    this.xitiDownloadClick = function(section, url, popup) {
	s.tl(this,'d', url);
	if(/.pdf/i.test(url) || /.wmv/i.test(url) || /.mov/i.test(url)) {
		newWindow = window.open(url,'newWindow','');
		newWindow.focus();
	} else {
		document.location = url;
	}
	return false;
    };
    
    this.xitiExitClick = function(section, url, popup, destination_type) {
		//xitiExitClick(section, url, popup, "2", destination_type);	
		s.prop20 = url;
		s.events = "";
		
		s.linkTrackVars = "events,prop20,";
		s.linkTrackEvents = "event12,event13";
		s.linkTrackEvents = s.events;
		if (url.indexOf('rolexdealers.com') > 0){
			s.linkTrackVars += "eVar18,";
			s.eVar18=url;
			if (destination_type == "AFF"){
				s.events="event12,"; //affiliate clickthrough
			} else{
				s.events="event13,"; //dealer clickthrough
			}
		}
		s.tl(this, 'e', url);
		if(popup)
			window.open(url);
		else
			window.location(url);
		return false;
    };
    
    this.xitiFlashEvent = function(section, name) {
        xitiFlashEvent(section, name);
    };
    
    this.xitiFlashMediaEvent = function(section, medianame, control, seconds, total) {
        xitiFlashMediaEvent(section, medianame, control, seconds, total);
    };

    this.xitiNavClick = function(section, trackString, targetUrl) {
        xitiNavClick(section, trackString, "2", null, targetUrl);
    };

    this.disableFlash = function() {
        document.cookie = "disableFlash=true; path=/";
        document.location.href = document.location.href;
        //send a xiti/omniture hit to record flash disabling 
        xitiNavClick("flash_disabled", "flash_disabled", "2", null, document.location.href);
    };
    this.recordSlowConnectionMetrics = function(loadTime, seenSlowMessage){
        //send a xiti/omniture hit to record slow connection
        xitiFlashSlowConnection(loadTime, seenSlowMessage);
    };
};
document.historyHandler = new historyHandler ();

//register
onloadHTMLHandlers[onloadHTMLHandlers.length] = 'loadJSImages("/css/html-background-images.css");';


