// ### URI ENFORCER ############################################################
var globalJsIsIndeedLoaded=true;

if(typeof suppressInfinitiUSAPopup == "undefined") var suppressInfinitiUSAPopup = false;

var currentURI = window.location.href;
var isInfinitiSite = ( location.hostname.indexOf('www.infinitiusa.com') > -1 ||
						location.hostname.indexOf('secure.infinitiusa.com') > -1  ||
						location.hostname.indexOf('stage.infinitiusa.com') > -1 ) ? true : false;
//var isStageEnv = (currentURI.indexOf('.stage.') > -1) ? true : false;
//s SDSR
var isStageEnv=false;
var sStageEnvServer='';
var sStageEnvServerSuffix='';
if(currentURI.indexOf('.stage.') > -1)
{
	isStageEnv=true;
	sStageEnvServer='stage';
	sStageEnvServerSuffix='com';
}
else if(currentURI.indexOf('.dev.') > -1)
{
	isStageEnv=true;
	sStageEnvServer='dev';
	sStageEnvServerSuffix='designory.com';
}
else if(currentURI.indexOf('.qa1.') > -1)
{
	isstageEnv=true;
	sStageEnvServer='qa1';
	sStageEnvServerSuffix='com';
}
else if(currentURI.indexOf('.qa2.') > -1)
{
	isStageEnv=true;
	sStageEnvServer='qa2';
	sStageEnvServerSuffix='com';
}
else if(currentURI.indexOf('.qa.') > -1)
{
	isStageEnv=true;
	sStageEnvServer='qa';
	sStageEnvServerSuffix='nna';
}
//e SDSR

//  set paths for...                 Live site                       Staging environment
var securePath =    (!isStageEnv) ?	"https://secure.infinitiusa.com" : "https://www."+sStageEnvServer+".infinitiusa."+sStageEnvServerSuffix; //"https://www.stage.infinitiusa.com";
var nonSecurePath =	(!isStageEnv) ?	"http://www.infinitiusa.com"     : "http://www."+sStageEnvServer+".infinitiusa."+sStageEnvServerSuffix;  //"http://www.stage.infinitiusa.com";
if(currentURI.indexOf('129.33.85.202') > -1)
{
  securePath =    "https://129.33.85.202";
  nonSecurePath =	"http://129.33.85.202";
} else if(currentURI.indexOf('129.33.85.215') > -1)
{
  securePath =    "https://129.33.85.215";
  nonSecurePath =	"http://129.33.85.215";
}

var secureURIs = [

	// Ownership / My Infiniti
	["http://www.infinitiusa.com/iapps/ownership",		"https://secure.infinitiusa.com/iapps/ownership"],
	["https://www.infinitiusa.com/iapps/ownership",		"https://secure.infinitiusa.com/iapps/ownership"],
	["http://secure.infinitiusa.com/iapps/ownership",		"https://secure.infinitiusa.com/iapps/ownership"],
	["http://www.stage.infinitiusa.com/iapps/ownership",	"https://www.stage.infinitiusa.com/iapps/ownership"],
	["http://secure.stage.infinitiusa.com/iapps/ownership",		"https://secure.stage.infinitiusa.com/iapps/ownership"],

	// PreApproval
	["http://www.infinitiusa.com/iapps/preapprovedinput",	"https://secure.infinitiusa.com/iapps/preapprovedinput"],
	["https://www.infinitiusa.com/iapps/preapprovedinput",	"https://secure.infinitiusa.com/iapps/preapprovedinput"],
	["http://secure.infinitiusa.com/iapps/preapprovedinput",	"https://secure.infinitiusa.com/iapps/preapprovedinput"],
	["http://www.stage.infinitiusa.com/iapps/preapprovedinput","https://www.stage.infinitiusa.com/iapps/preapprovedinput"],
	["http://secure.stage.infinitiusa.com/iapps/preapprovedinput","https://secure.stage.infinitiusa.com/iapps/preapprovedinput"],

	// PreApproval - LDS
	["http://www.infinitiusa.com/iapps/preapprovedconfirm",	"https://secure.infinitiusa.com/iapps/preapprovedconfirm"],
	["https://www.infinitiusa.com/iapps/preapprovedconfirm",	"https://secure.infinitiusa.com/iapps/preapprovedconfirm"],
	["http://secure.infinitiusa.com/iapps/preapprovedconfirm",	"https://secure.infinitiusa.com/iapps/preapprovedconfirm"],
	["http://www.stage.infinitiusa.com/iapps/preapprovedconfirm","https://www.stage.infinitiusa.com/iapps/preapprovedconfirm"],
	["http://secure.stage.infinitiusa.com/iapps/preapprovedconfirm","https://secure.stage.infinitiusa.com/iapps/preapprovedconfirm"]

];

var secureURIfound = false;
//    push user to secure URI
if (isInfinitiSite && currentURI.indexOf('http://') > -1) {
	for (var i in secureURIs) {
		if (currentURI.indexOf(secureURIs[i][0]) > -1) {
			secureURIfound = true;
			location.replace(currentURI.replace(secureURIs[i][0],secureURIs[i][1]));
		}
	}
	// no secure URI found, check & pull user from bad http://secure URI
	if (!secureURIfound && currentURI.indexOf('http://secure.') > -1) {
		location.replace(currentURI.replace("http://secure.","http://www."));
	}
}
//    pull user from secure-svr
else if (isInfinitiSite && currentURI.indexOf('https://') > -1) {
	for (var i in secureURIs) {
		if (currentURI.indexOf(secureURIs[i][1]) > -1) {
			secureURIfound = true;
		}
	}
	// no secure URI found, check & pull user from bad https://www URI
	if (!secureURIfound && currentURI.indexOf('https://www.') > -1) {
		location.replace(currentURI.replace("https://www.","http://www."));
	}
	// else pull user from standard secure URI to non secure URI
	else if (!secureURIfound) {
		location.replace(currentURI.replace(securePath,nonSecurePath));
	}
}

if (currentURI.indexOf('.infinitiusaretailers.com') > -1 &&
    currentURI.indexOf('/iapps/retailerlocator') == -1 &&
		!/dealerzip=/.test(currentURI) &&
		!/city=(.*)&state=(.*)/.test(currentURI)) {
	location.replace(currentURI.replace(".infinitiusaretailers.com",".infinitiusa.com"));
}

var secureNonSecurePath = (secureURIfound) ? securePath : nonSecurePath;

// #############################################################################

/* GLOBAL SCRIPTS */

				// Function to safely register multiple functions with the onLoad browser event
				function addLoadEvent(func) {
					var oldonload = window.onload;
					if (typeof window.onload != 'function') window.onload = func;
					else {
						window.onload = function() {
							oldonload();
							func();
						}
					}
				}

				// Shortcut getID function
				function $(ee) {
					return document.getElementById(ee);
				}

// Schricker's format
String.prototype.format=function(){
	var ar=arguments;
	return this.replace(/\{\d+\}/g,function(w){return ar[+w.replace(/[}{]/g,'')]});
}

				// Shortuct to innerHTML
				// used on Payment Estimator - only?
				function getHtml(elmId) {
					return $( elmId ).innerHTML;
				}

				// Modifier for innerHTML
				// used on config colors/packages pages
				function setHtml(elmId, strContent) {
					$( elmId ).innerHTML = strContent;
				}

				// Sean Schricker's simplerSwap
				function setOverSrc(elem){
					elem.onmouseover=function(){this.src=this.src.replace(/(_on)*(\.\w+)$/,'_on$2')}
					elem.onmouseout=function(){this.src=this.src.replace(/(_on)+(\.\w+)$/,'$2')}
					elem.onload='';
				}

// alternative rollover function
function roll(img_name, img_src) {
  document[img_name].src = img_src;
}

				// getModelName(): gets model name from url by comparing against pre-defined list of models
				// WARNING: Some BS inline javascript in Schedule a Test Drive overrides this function, basically making this useless on a consistant basis
				function getModelName(){
					var arrModelNames = ['g_sedan','g_coupe','g_convertible','m','q','fx','qx','ex'];
					var urlStr = location.href;

					for(i=0;i<arrModelNames.length;i++) {
						if(urlStr.indexOf('/'+arrModelNames[i]+'/')!=-1)
							return arrModelNames[i];
					}
					return null;
				}

				function trim(str){
					return str.replace(' ','').replace(/(\s)/g,'');
				}

function getQueryString() {
    var objQSArgs=new Object();
    var strQuery=document.location.search.substring(1);
    var arrPairs=strQuery.split("&");

    for(var i=0;i<arrPairs.length;i++){
        var pos=arrPairs[i].indexOf('=');

        if(pos==-1){continue;}

        var strName=arrPairs[i].substring(0,pos);
        var strValue=arrPairs[i].substring(pos+1);

        objQSArgs[strName]=unescape(strValue);
    }
    return objQSArgs;
}

				function showPricingDetails() {
					var obj = $('pricingDetails');
					obj.style.visibility='hidden'
					obj.style.display='inline'
					_currentDhtmlPop=obj
					obj.style.top  = (document.body.clientHeight - obj.clientHeight)/2+ 'px';
					obj.style.left = (document.body.clientWidth - obj.clientWidth)/2+ 'px';
					obj.style.visibility='visible';
				}

				function setupPricingDetails() {
					var pricingdetailsArr = new Array();

					pricingdetailsArr['ex'] =      "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsArr['fx'] =      "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsArr['g_sedan'] = "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsArr['g_coupe'] = "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsArr['g_convertible'] = "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsArr['m'] =       "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsArr['qx'] =      "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";

					var pricingdetailsModelSelectorArr = new Array();
					//Changes made for May 2007 C&I Update
					pricingdetailsModelSelectorArr['g_sedan'] = "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsModelSelectorArr['g_coupe'] = "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsModelSelectorArr['g_convertible'] = "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsModelSelectorArr['m'] =       "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsModelSelectorArr['ex'] =      "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsModelSelectorArr['fx'] =      "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";
					pricingdetailsModelSelectorArr['qx'] =      "*All prices are Manufacturer?s Suggested Retail Price (MSRP). MSRP excludes destination and handling charges, tax, title, license, and options. Dealer sets actual price.";

					var sUrl = location.href;
					var sModel = getModelName();
					var ePricing = $('pricingDetailsCopy');

					if (sUrl.indexOf("models")!=-1) {
						if (sModel=="q")
							ePricing.innerHTML = pricingdetailsArr[sModel];
						else
							ePricing.innerHTML = pricingdetailsModelSelectorArr[sModel];
					 } else {
						ePricing.innerHTML = pricingdetailsArr[sModel];
					}
				}

				function getQueryParam(nombre){
					var _re = new RegExp("[&\?]"+String(nombre)+"=([^&]+)");
					return (_re.test(location.search))?RegExp.$1:'';
				}

				// Return a querystring-formatted value from a string
				function getStringParam(searchString, nombre) {
					var _re = new RegExp("[&\?]"+String(nombre)+"=([^&]+)");
					return (_re.test(searchString))?RegExp.$1:'';
				}

// SWFObject stuff below	=	=	=	=	=	=	=	=	=
//Object inheritance framework from
//http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html

Function.prototype.Inherits = function( parent )
	{
		this.prototype = new parent();
		this.prototype.constructor = this;
	}

  // **************************************************************************************************
  // ****      I.E. DOM IMPLEMENTATION ISSUE FIX                                                   ****
  // **************************************************************************************************

// Stub function
function createElementWithName(){
	}

// Anonymous function fills in stub automatically depending on browser implementation of name
// attribute.	IE requires a non-standard call to document.createElement in order to set the name
// attribute for elements, which is necessary for dynamically generated forms.
(function(){
	try {
		var el=document.createElement( '<div name="foo">' );
		if( 'DIV'!=el.tagName ||
				'foo'!=el.name ){
			throw 'create element error';
		}
		createElementWithName = function( tag, name ){
			return document.createElement( '<'+tag+' name="'+name+'"></'+tag+'>' );
		}
	}catch( e ){
		createElementWithName = function( tag, name ){
			var el = document.createElement( tag );
			// setAttribute might be better here ?
			el.name = name;
	el.setAttribute("name",name);
			return el;
		}
	}
})();

// Add createElementWithName to document object as createNamedElement
if (typeof(document.createNamedElement) == 'undefined') {
	document.createNamedElement = createElementWithName;
}

//=	=	=	=	=	=	=	=	=	=	=	=
/**
 * SWFObject v1.4.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, xiRedirectUrl, redirectUrl, detectKey){

	if (!$) { return; }
	this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
	this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
	this.params = new Object();
	this.variables = new Object();
	this.attributes = new Array();
	if(swf) { this.setAttribute('swf', swf); }
	if(id) { this.setAttribute('id', id); }
	if(w) { this.setAttribute('width', w); }
	if(h) { this.setAttribute('height', h); }
	if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
	this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
	if(c) { this.addParam('bgcolor', c); }
	var q = quality ? quality : 'high';
	this.addParam('quality', q);
	this.setAttribute('useExpressInstall', useExpressInstall);
	this.setAttribute('doExpressInstall', false);
	var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
	this.setAttribute('xiRedirectUrl', xir);
	this.setAttribute('redirectUrl', '');
	if(redirectUrl) {this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},
	getAttribute: function(name){
		return this.attributes[name];
	},
	addParam: function(name, value){
		this.params[name] = value;
	},
	getParams: function(){
		return this.params;
	},
	addVariable: function(name, value){
		this.variables[name] = value;
	},
	getVariable: function(name){
		return this.variables[name];
	},
	getVariables: function(){
		return this.variables;
	},
	getVariablePairs: function(){
		var variablePairs = new Array();
		var key;
		var variables = this.getVariables();
		for(key in variables){
			variablePairs.push(key +"="+ variables[key]);
		}
		return variablePairs;
	},
	getSWFHTML: function() {
		var swfNode = "";
		if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
			if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); }
			swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"';
			swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
			var params = this.getParams();
			 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
			var pairs = this.getVariablePairs().join("&");
			 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
			swfNode += '/>';
		} else { // PC IE
			if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); }
			swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
			swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
			var params = this.getParams();
			for(var key in params) {
			 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
			}
			var pairs = this.getVariablePairs().join("&");
			if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
			swfNode += "</object>";
		}
		return swfNode;
	},
	write: function(elementId){
		if(this.getAttribute('useExpressInstall')) {
			// check to see if we need to do an express install
			var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
			if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
				this.setAttribute('doExpressInstall', true);
				this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
				document.title = document.title.slice(0, 47) + " - Flash Player Installation";
				this.addVariable("MMdoctitle", document.title);
			}
		}
		if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
			var n = (typeof elementId == 'string') ? $(elementId) : elementId;
			n.innerHTML = this.getSWFHTML();
			return true;
		}else{
			if($('homepageFA') || $('VLP') || $('gMain') || $('gRegionalNav') || $('VLPinterior') || $('VLPcolor') || $('VLPexterior') || $('body_flash'))
			{
				if(this.getAttribute('redirectUrl') != "") {

					document.location.replace(this.getAttribute('redirectUrl'));
				}
			}
		}
		return false;
	}
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
	var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
	if(navigator.plugins && navigator.mimeTypes.length){
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description) {
			PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
		}
	}else{
		// do minor version lookup in IE, but avoid fp6 crashing issues
		// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
		try{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		}catch(e){
			try {
				var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
				PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
				axo.AllowScriptAccess = "always"; // throws if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
			} catch(e) {
				if (PlayerVersion.major == 6) {
					return PlayerVersion;
				}
			}
			try {
				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			} catch(e) {}
		}
		if (axo != null) {
			PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
		}
	}
	return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
	this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
	this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
	this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
	if(this.major < fv.major) return false;
	if(this.major > fv.major) return true;
	if(this.minor < fv.minor) return false;
	if(this.minor > fv.minor) return true;
	if(this.rev < fv.rev) return false;
	return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
	getRequestParameter: function(param) {
		var q = document.location.search || document.location.hash;
		if(q) {
			var pairs = q.substring(1).split("&");
			for (var i=0; i < pairs.length; i++) {
				if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
					return pairs[i].substring((pairs[i].indexOf("=")+1));
				}
			}
		}
		return "";
	}
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
	if (window.opera || !document.all) return;
	var objects = document.getElementsByTagName("OBJECT");
	for (var i=0; i < objects.length; i++) {
		objects[i].style.display = 'none';
		for (var x in objects[i]) {
			if (typeof objects[i][x] == 'function') {
				objects[i][x] = function(){};
			}
		}
	}
}
// prevents prepUnload from being mapped recursively
if (typeof prepUnloadMapped != 'number') {
  var prepUnloadMapped = 0;
}

// fixes bug in fp9 see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
deconcept.SWFObjectUtil.prepUnload = function() {
      __flash_unloadHandler = function(){};
      __flash_savedUnloadHandler = function(){};
      if (typeof window.onunload == 'function') {
            var oldUnload = window.onunload;
            window.onunload = function() {
                  deconcept.SWFObjectUtil.cleanupSWFs();
                  oldUnload();
            }
      } else {
            window.onunload = deconcept.SWFObjectUtil.cleanupSWFs;
      }
  prepUnloadMapped = 0;
}

if (prepUnloadMapped == 0) {
  prepUnloadMapped = 1;
  if (typeof window.onbeforeunload == 'function') {
      var oldBeforeUnload = window.onbeforeunload;
      window.onbeforeunload = function() {
            deconcept.SWFObjectUtil.prepUnload();
            oldBeforeUnload();
      }
  } else {
      window.onbeforeunload = deconcept.SWFObjectUtil.prepUnload;
  }
}

/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;








//=	=	=	=	=	=	==	=	=	=	=
/*

Some of this code is part of the Flash / JavaScript Integration Kit:
http://www.macromedia.com/go/flashjavascript/

Created by:

Christian Cantrell
http://weblogs.macromedia.com/cantrell/
mailto:cantrell@macromedia.com

Mike Chambers
http://weblogs.macromedia.com/mesh/
mailto:mesh@macromedia.com

Macromedia

***** Added 1/17/06 by Geoff Stearns (geoff@deconcept.com):

This version of the JS Integration kit requires swfobject 1.4.4 or later
Download SWFObject at http://blog.deconcept.com/swfobject/
http://blog.deconcept.com/code/intkit/

the swfobject.js file must be linked before this file is linked.

SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php

*/

/**
 * The FlashSerializer serializes JavaScript variables of types object, array, string,
 * number, date, boolean, null or undefined into XML.
 */

/**
 * Create a new instance of the FlashSerializer.
 * useCdata: Whether strings should be treated as character data. If false, strings are simply XML encoded.
 */
function FlashSerializer(useCdata){
	this.useCdata = useCdata;
}

/**
 * use encodeURIComponent() if the browser supports it, otherwise use escape()
 */
FlashSerializer.prototype.encodeVal = function(val){
	if(document.encodeURIComponent) {
		return encodeURIComponent(val);
	}
	return escape(val);
}

/**
 * Serialize an array into a format that can be deserialized in Flash. Supported data types are object,
 * array, string, number, date, boolean, null, and undefined. Returns a string of serialized data.
 */
FlashSerializer.prototype.serialize = function(val){
	var result = new Array();
	switch(typeof val){
		case 'undefined':
			result[0] = 'undef';
			break;
		case 'string':
			result[0] = 'str';
			result[1] = this.encodeVal(val);
			break;
		case 'number':
			result[0] = 'num';
			result[1] = val.toString();
			break;
		case 'boolean':
			result[0] = 'bool';
			result[1] = val.toString();
			break;
		case 'object':
			if (val == null) {
				result[0] = 'null';
			} else if (val.getTime) {
				result[0] = 'date';
				result[1] = this.encodeVal(val.getTime());
			} else { // array or object
				try {
					result[0] = 'xser';
					result[1] = this.encodeVal(this._serializeXML(val));
				}catch (e){}
			}
			break;
		default:
			// do nothing
	}
	return result;
}

/**
 * Private
 */
FlashSerializer.prototype._serializeXML = function(obj)
{
		var doc = new Object();
		doc.xml = '<fp>';
		this._serializeNode(obj, doc, null);
		doc.xml += '</fp>';
		return doc.xml;
}

/**
 * Private
 */
FlashSerializer.prototype._serializeNode = function(obj, doc, name){
	switch(typeof obj) {
		case 'undefined':
			doc.xml += '<undf'+this._addName(name)+'/>';
			break;
		case 'string':
			doc.xml += '<str'+this._addName(name)+'>'+this._escapeXml(obj)+'</str>';
			break;
		case 'number':
			doc.xml += '<num'+this._addName(name)+'>'+obj+'</num>';
			break;
		case 'boolean':
			doc.xml += '<bool'+this._addName(name)+' val="'+obj+'"/>';
			break;
		case 'object':
			if (obj == null) {
				doc.xml += '<null'+this._addName(name)+'/>';
			} else if (obj.getTime) {
				doc.xml += '<date'+this._addName(name)+'>'+obj.getTime()+'</date>';
			} else if (obj.length != undefined) {
				doc.xml += '<array'+this._addName(name)+'>';
				for (var i = 0; i < obj.length; ++i) {
					this._serializeNode(obj[i], doc, null);
				}
				doc.xml += '</array>';
			} else {
				doc.xml += '<obj'+this._addName(name)+'>';
				for (var n in obj) {
					if (typeof(obj[n]) == 'function') {
						continue;
					}
				this._serializeNode(obj[n], doc, n);
				}
				doc.xml += '</obj>';
			}
			break;
		default:
			// do nothing
	}
}

/**
 * Private
 */
FlashSerializer.prototype._addName= function(name){
	if (name != null) {
		return ' name="'+name+'"';
	}
	return '';
}

/**
 * Private
 */
FlashSerializer.prototype._escapeXml = function(str){
	if (this.useCdata) {
		return '<![CDATA['+str+']]>';
	} else {
		return str.replace(/&/g,'&amp;').replace(/</g,'&lt;');
	}
}

/**
 * setProxy creates the unique uid the flash movie will need to get calls from javascript
 *
 */
deconcept.SWFObject.prototype.setProxy = function(callbackScope, swfUrl){
	this.uid = new Date().getTime() + (Math.round(Math.random()*100000));
	deconcept.SWFObject.fpmap[this.uid] = this;
	this.q = new Array();
	this.callbackScope = callbackScope;
	this.proxySwfName = swfUrl ? swfUrl : "swfobject_js_gateway.swf";
	this.flashSerializer = new FlashSerializer(false);
	this.addVariable('lcId', this.uid);
	var isIE = (document.all && !window.opera) ? true : false;
	this.addVariable('jsintkit_isIE', isIE);

	nnaFlashSWFObjectList[this.uid] = this;

	if (isIE) {
		// add fscommand catcher
		var scriptNode = document.createElement("script");
		scriptNode.setAttribute("type", "text/vbscript");
		// can't use appendChild on script nodes, so using .text instead
		scriptNode.text = 'Sub '+ this.getAttribute('id') +'_FSCommand(ByVal command, ByVal args) call deconcept.SWFObject.callJS(command, args) End Sub';
		document.getElementsByTagName('head')[0].appendChild(scriptNode);
	}
}

/**
 * Call a function in your Flash content.	Arguments should be:
 * 1. ActionScript function name to call,
 * 2. any number of additional arguments of type object,
 *		array, string, number, boolean, date, null, or undefined.
 */
deconcept.SWFObject.prototype.call = function() {
	if (!this.uid || arguments.length == 0) {
		return;
	}

	this.q.push(arguments);
	if (this.q.length == 1){
		this._execute(arguments);
	}
}

/**
 * "Private" function.	Don't call.
 */
deconcept.SWFObject.prototype._execute = function(args){
	var fo = new SWFObject(this.proxySwfName, "flashproxy", 1, 1, 6);
	fo.addVariable('lcId', this.uid);
	fo.addVariable('functionName', args[0]);

	if (args.length > 1) {
		for (var i=1; i<args.length; ++i) {
			var serialized = this.flashSerializer.serialize(args[i]);
			fo.addVariable('t'+(i-1), serialized[0]);
			if (serialized.length > 1) {
				fo.addVariable('d'+(i-1), serialized[1]);
			}
		}
	}

	var divName = '_flash_proxy_' + this.uid;
	if(!$(divName)) {
		var newTarget = document.createElement("div");
		newTarget.id = divName;
		document.body.appendChild(newTarget);
	}
	fo.write(divName);
}

/**
 * This is the function that proxies function calls from Flash to JavaScript.
 * It is called implicitly.
 */
deconcept.SWFObject.callJS = function(command, args){
	var argsArray = eval(args);
	var scope = deconcept.SWFObject.fpmap[argsArray.shift()].callbackScope;
	if(scope && (command.indexOf('.') < 0)){
		var functionToCall = scope[command];
		functionToCall.apply(scope, argsArray);
	}else{
		var functionToCall = eval(command);
		functionToCall.apply(functionToCall, argsArray);
	}
}

 /**
	* This function gets called when a Flash function call is complete. It checks the
	* queue and figures out whether there is another call to make.
	*/
deconcept.SWFObject.callComplete = function(uid){
	var fp = deconcept.SWFObject.fpmap[uid];
	if (fp != null) {
		fp.q.shift();
		if (fp.q.length > 0) {
			fp._execute(fp.q[0]);
		}
	}
}

nnaFlashSWFObjectList = new Array();
deconcept.SWFObject.fpmap = new Object();

//=	=	=	=	=	=	=	=	=	=	=
/*
Example usage:
	// Declare variables object
	var flashvars = {
		handle:'handletest'
		,flashVarText:'testing'
		,anothervar:'testing'
	};
	// Embed Flash object in page
	var so = new swfoWrapper('so_tester.swf','flashcontent',flashvars,300,300);
*/
swfoWrapper.Inherits(SWFObject);

function swfoWrapper (swf, container, vartable, width, height, requiredversion)
{
	// this = new SWFObject();
/*	if(deconcept.SWFObjectUtil.getPlayerVersion ().major<=8)
	{	// default required flash version, background color
		this.setAttribute('redirectUrl', 'non-flash/index.html');
		this.write(this.container);
		return;
	}*/

    var bOnProd = (location.href.indexOf('http://build.infinitiusa.com')==0);
		this.requiredversion = typeof requiredversion == 'number' ? requiredversion : 8;
		this.backcolor = '#000000';
		// if width and height specified then set, otherwise default
		this.height = typeof(width) == 'number' ? width : 964;
		this.width = typeof(height) == 'number' ? height : 600;
		// parameters provided by default constructor
    if(bOnProd && swf.indexOf('http')==-1) {
  		swf = 'http://www.infinitiusa.com' + swf;
    }
    this.swf = swf;

		this.container = container;
		// call the SWFObject constructor
		this.Inherits(SWFObject, swf, container + '_swf', this.height, this.width, this.requiredversion, this.backcolor);
		// add all variables

		// Changas  MADEE BY CTS
		//this.setAttribute('redirectUrl', 'http://www.infiniti.com/global/error/getflash.html');
		//this.redirectUrl="http://www.integ.infiniti.nna/non-flash/index.html";

		this.setAttribute('redirectUrl', '/non-flash/index.html');

		// Changas  MADE BY CTS - ENDS HERE

		//var isInAuthor=(location.href.indexOf("/author/")>1)
		if((typeof showEdits != 'undefined') && showEdits){
			this.addVariable("author",1);
		}

		//Add some variables and params for Refresh2
		var handleHopeful=location.pathname.replace(/\.(x|ht)ml$/,''); // lop off the extension
		
		//cpo apps
		if((handleHopeful.indexOf("/iapps/cpo/search") != -1) || (handleHopeful.indexOf("/iapps/cpo/vehicleDetails") != -1) ){	
			handleHopeful = "/iapps/cpo/searchResults";
		} else {
			if(handleHopeful.indexOf("/iapps/cpo") != -1){	
				handleHopeful = "/iapps/cpo";
			}
		}

		handleHopeful=handleHopeful.replace(/\/$/,'/index'); // add index if it ends in a slash
		handleHopeful=handleHopeful.replace(/ownership\/warranty\-\w+/,'ownership/warranty'); // add index if it ends in a slash
		handleHopeful=handleHopeful.replace(/(lease\-faq|purchase\-faq)/,'purchase-vs-lease'); // add index if it ends in a slash

		// Fix promo mapping for vehicle pages
		if (/\/ex\/|\/fx\/|\/g_coupe\/|\/g_sedan\/|\/g_convertible\/|\/m\/|\/qx\//.test(window.location.pathname)){
			if (/models\-pricing/.test(handleHopeful))
				this.addVariable('promo',getModelName()+',models');
			else if (/packages\-options/.test(handleHopeful))
				this.addVariable('promo',getModelName()+',packages');
			else if (/specs\-options\/accessories/.test(handleHopeful))
				this.addVariable('promo',getModelName()+',dealer_accessories');
			else if (/specs\-options/.test(handleHopeful))
				this.addVariable('promo',getModelName()+',specifications');
			else if (/awards\-reviews/.test(handleHopeful))
				this.addVariable('promo',getModelName()+',review');
			else if (/colors/.test(handleHopeful))
				this.addVariable('promo',getModelName()+',colors');
		}

		this.addVariable( "handle", handleHopeful   );
		this.addVariable( "htmlSwfId",  container + '_swf' );

		if ((typeof myVar != 'undefined')||(typeof(zipcode_2) != "undefined"))
		{
			this.addVariable( "cpozip", zipcode_2);
		}

    if(bOnProd) {
  		var basePrefix='http://www.infinitiusa.com';
  		this.addVariable("isExternal", 'true');
    } else {
  		//var basePrefix=(location.href.indexOf("/author/")>1)?'/author':'';
  		var basePrefix=(location.href.replace(/https?:\/\/[^\/]+(\/(author|publish))?.*/,'$1'));
    }


		this.addParam('base',basePrefix+'/flash');
		this.addParam('scale','noscale');
		this.addParam('wmode','transparent');
		this.addParam('allowScriptAccess','always');
		this.addVariable('src', getQueryParam('src'));

		for (var varitem in vartable) {
			if (typeof(vartable[varitem]) != 'function'){
				if(/^atr_/.test(varitem)){
					this.setAttribute(varitem.replace(/^atr_/,''),vartable[varitem]);
				}else if(/^param_/.test(varitem)){
					this.addParam(varitem.replace(/^param_/,''),vartable[varitem]);
				}else{
					this.addVariable(varitem,String(vartable[varitem]).replace(/&amp;/g,'%26').replace(/\+/g,'%2B'));
				}
			}
		}



	this.postform = function (action,query) {
		var fe = document.createElement("form");
		fe.id = "flashsearchform";
		fe.action = action;
		fe.enctype = "multipart/form-data";
		fe.encoding = "multipart/form-data";
		fe.method = "post";
		fe.style.display = "none";
		var qv = "";
		var qa = query.split(",");
		for (var i = 0; i < qa.length; i++) {
			qv += String.fromCharCode(qa[i])
		}

		var qps = qv.split("&");
		for (var i = 0; i < qps.length; i++) {
			var qp = qps[i].split("=");
			var qpe = document.createNamedElement("input",qp[0]);
			qpe.type = "hidden";
			var qpev = qp[1];
			qpe.value = qpev;
			fe.appendChild(qpe);
		}

		var qpcs = document.createNamedElement("input","_charset_");
		qpcs.type = "hidden";
		qpcs.value = "utf-8";
		fe.appendChild(qpcs);
		document.body.appendChild(fe);
		fe.submit();
	}

	this.write(this.container);
	return;
}

swfoWrapper.prototype.Inherits = function( parent )
	{
		if( arguments.length > 1 )
		{
			parent.apply( this, Array.prototype.slice.call( arguments, 1 ) );
		}
		else
		{
			parent.call( this );
		}
}

				var topNavFv={}
				var regionalNavFv={}
        var addedNavs = 0;
				function addNavsToNonRefresh(){
					if(/iapps\/ownership/.test(location.pathname) && !/(login|forgotPassword|signUpNow)$/.test(location.pathname))
						regionalNavFv.loggedIn='true';
					if(deconcept.SWFObjectUtil.getPlayerVersion().major >= 8) {
						if($('gRegionalNav')){
							new swfoWrapper("/flash/model_nav.swf", 'gRegionalNav', regionalNavFv, 176, 550);
						}
						if ($('gTopNav')){
							new swfoWrapper("/flash/global_nav.swf", 'gTopNav', topNavFv, 964, 64); // only if gtopnav and flash!!!!
						}
						if ( $('gTopNavExternal') && 
								 !/compare./.test(location.hostname) &&
								 !/billmatrix./.test(location.hostname) &&
								 !/chrome./.test(location.hostname) &&
								 !/search./.test(location.hostname) ) {

              if(typeof(infinitiRootSrc)=='string' && infinitiRootSrc.indexOf('https')==0) { 
								if(typeof topNavFv == 'undefined'){topNavFv={};}
								topNavFv.isExternal=true; // actually isRemote.
								topNavFv.param_base=infinitiRootSrc+"/flash";
								new swfoWrapper(infinitiRootSrc+"/flash/global_nav.swf", 'gTopNavExternal', topNavFv, 964, 64);
              } else {
								new swfoWrapper(nonSecurePath + "/flash/global_nav.swf", 'gTopNavExternal', topNavFv, 964, 64); // only if gtopnav and flash!!!!
							}
						}
						if($('gPromoBar')){
							new swfoWrapper("/flash/promo.swf", 'gPromoBar', {}, 767, 88);
						}
				  } else {
							importXML();
					}
          addedNavs = 1;
				}

				addLoadEvent(addNavsToNonRefresh);

// do this check if we're not on the non-flash homepage AND we're not on the global bridge page
if ( (currentURI.indexOf('/non-flash/') == -1) && (currentURI.indexOf('/global/index.html') == -1) )
  addLoadEvent(fncFixGlobalFooter);


//-	BEGIN SSE PROMO	=	When done, delete to the end of this section.
//-	BEGIN SSE PROMO	=	=	=	=	=	=	=	=	=	=	=
//-	BEGIN SSE PROMO	=	=	=	=	=	=	=	=	=	=	=

var pcA=[];
pcA['generic']=['generic','index',''];
pcA['g']=['gs','g_sedan','g_sedan'];
pcA['gs']=['gs','g_sedan','g_sedan'];
pcA['g35']=['gs','g_sedan','g_sedan'];
pcA['g_sedan']=['gs','g_sedan','g_sedan'];
pcA['gcp']=['gc','g_coupe','g_coupe'];
pcA['g_coupe']=['gc','g_coupe','g_coupe'];
pcA['gcv']=['generic','g_convertible','g_convertible'];
pcA['gconv']=['generic','g_convertible','g_convertible'];
pcA['g_convertible']=['generic','g_convertible','g_convertible'];
pcA['m']=['m','m','m_sedan'];
pcA['m_sedan']=['m','m','m_sedan'];
pcA['m45']=['m','m','m_sedan'];
pcA['ex']=['ex','ex','ex'];
pcA['ex35']=['ex','ex','ex'];
pcA['fx']=['fx','fx','fx'];           // since there are no FX offers, this goes to the generic offers page
pcA['fx45']=['fx','fx','fx'];         // since there are no FX offers, this goes to the generic offers page
pcA['fx50']=['fx','fx','fx'];         // since there are no FX offers, this goes to the generic offers page
pcA['qx']=['qx','qx','qx'];
pcA['qx56']=['qx','qx','qx'];

function drawPromoSide(myVehicle, myCode){
	var pA=document.createElement('a');
	pA.id='promoSide';
	pA.style.marginLeft='25px';
	pA.style.marginTop='25px';
	pA.style.display='block';
	var iii=document.createElement('img');
	iii.style.display='inline';
	iii.src=getCurrentSiteForPromos()+'/img/promos/'+pcA[myVehicle][0]+'_promo_config_summary.jpg';
	pA.appendChild(iii);

	//pA.innerHTML=myVehicle;
	if(pcA[myVehicle][2]=='')
		pA.href=getCurrentSiteForPromos() + '/current-offers/index.html?' + myCode;
	else
		pA.href=getCurrentSiteForPromos() + '/current-offers/index.html?vehicle=' + pcA[myVehicle][2] + '&' + myCode;
		
	if($('summaryContainer')){
		$('summaryContainer').appendChild(pA);
	}else{
		var _divs=document.getElementsByTagName('div');
		for(var i=0;i<_divs.length;i++){
			if(/tColumnL/.test(_divs[i].className)){
				_divs[i].id='tColumnL';
				break;
			}
		}
		if($('tColumnL'))$('tColumnL').appendChild(pA);
	}
	return pA
}

function getCurrentSiteForPromos(){

	var pp='';
	var www='www';
	if(location.hostname.indexOf('stage.')>=0){
		pp= 'www.stage.infinitiusa.com';
	}else if(location.hostname.indexOf('qa1.')>=0){
		pp= 'www.qa1.infinitiusa.com';
	}else if(location.hostname.indexOf('qa2.')>=0){
		pp= 'www.qa2.infinitiusa.com';
	}else if(location.hostname.indexOf('qa.')>=0){
		pp= 'www.qa.infiniti.nna';
	}else if(location.hostname.indexOf('integ.')>=0){
		pp= 'www.integ.infiniti.nna';
	}else if(location.hostname.indexOf('collage.')>=0){
		pp= 'collage.designory.com:1160';
	}else if(location.hostname.indexOf('newdev.')>=0){
		pp= 'www.newdev.infinitiusa.com';
	}else if(location.hostname.indexOf('dev.')>=0){
		pp= 'www.dev.infiniti.designory.com';
	}else if(location.hostname.indexOf('prod.')>=0){
		pp= 'prod.infinitiusa.com';
	}
	else{
		if (location.hostname.indexOf('ww1')>=0) {
			www = 'ww1';
		}else if(location.hostname.indexOf('ww2')>=0){
			www = 'ww2';
		}else if(location.hostname.indexOf('ww3')>=0){
			www = 'ww3';
		}else{
			www = 'www';
		}
		pp= www+'.infinitiusa.com';
	}
	return location.protocol+"//"+pp;
}

function drawPromoBottom(myVehicle, myCode, myArea){// pass in myElement in case it doesn't have a className.
	myVehicle=String(myVehicle).replace(/\d+/,'')||'generic';
	myArea=myArea||'RAQ';

	var pA=document.createElement('a');
	pA.id='promoBottom';
	var iii=document.createElement('img');
	iii.style.display='inline';
	iii.src=getCurrentSiteForPromos()+'/img/promos/'+pcA[myVehicle][0]+'_long_promo_'+myArea+'.jpg';
	pA.appendChild(iii);
	
	if(pcA[myVehicle][2]=='')
		pA.href=getCurrentSiteForPromos() + '/current-offers/index.html?' + myCode;
	else
		pA.href=getCurrentSiteForPromos() + '/current-offers/index.html?vehicle=' + pcA[myVehicle][2] + '&' + myCode;
		
	pA.style.display='block'
	pA.style.marginBottom='1em'
	return pA;
}

var locatePromoTries = 0
function insertLocateRetailerPromo()
{
  // don't try this more than 10,000 times--that's 10,000 milliseconds or 10 seconds (plus processing time)
  if (locatePromoTries < 10000) {
    if($('main_div')==null || document.getElementsByName('moreDealers') == null) {
      setTimeout('insertLocateRetailerPromo()',1);
    } else {
      $('main_div').innerHTML = '<div style="padding-top: 95px; padding-left: 7px;" id="bck_div"><a href="/current-offers/?intcmp=Current_Offers.Banner.Locate."><img width="246" height="158" style="border: 0px none;" src="/img/promos/show_more_retailers.jpg"/></a></div>';

      // center SHOW MORE RETAILERS button above SSE button link
      var moreDealers = document.getElementsByName('moreDealers')[0];
      moreDealers.style.left = '67px';
      moreDealers.style.top = '177px';
    }
  }
  locatePromoTries++;
}

function getTrackingModelCode(modelID) {
  var modelCode = '';
  if(modelID=='gcp') { modelCode = 'G_Coupe'; }
  else if(modelID=='g') { modelCode = 'G_Sedan'; }
  else if(modelID=='gcv') { modelCode = 'G_Convertible'; }
  else if(modelID=='gconv') { modelCode = 'G_Convertible'; }
  else if(modelID=='m') { modelCode = 'M_Sedan'; }
  else if(modelID=='ex') { modelCode = 'EX'; }
  else if(modelID=='ex35') { modelCode = 'EX'; }
  else if(modelID=='fx') { modelCode = ''; }          // no offers for FX so we won't include FX in the tracking code
  else if(modelID=='fx50') { modelCode = 'FX'; }
  else if(modelID=='qx') { modelCode = 'QX'; }
  return modelCode;
}

function addPromosToTools(myVehicle){
	myVehicle=myVehicle||'qx';
	if(typeof hasLoadedOptionalPromos == 'undefined'){
		hasLoadedOptionalPromos=true; // because global.js is sometimes added 2 times.
	}else{
		return
	}
	var thisVehicle=null;
	var thisCode='';
	var thisArea='';
  var trackingModelCode = '';
	if(! ($('crmEngine') && $('crmEngine').getAttribute('pageid'))){
		return; //keying off the pageid, so if there is none, get out.
	}

	// See which page it is.
	var myPageId=+$('crmEngine').getAttribute('pageid');
	switch(myPageId){

		// Side, car specific
		case 8348:	//Configurator summary
			thisVehicle=location.search.replace(/^.+mo=\d+:([a-z]+).+$/i,'$1');
      trackingModelCode = getTrackingModelCode(thisVehicle);
      if(trackingModelCode=='')
        thisCode="intcmp=Current_Offers.Banner.Build.";
      else
        thisCode="intcmp=Current_Offers." + trackingModelCode + ".Banner.Build.";

			if(/^(gcv|gcp|g|gs|fx|m|qx|ex)$/.test(thisVehicle)){
				drawPromoSide(RegExp.$1, thisCode);
			}
			break;

		//case 8349:	//Configurator Request a Quote
			//if(myPageId==8349)	thisCode="intcmp=SummerSalesEvent.Banner.Build.Summary.";


    // Bottom, car specific or not.
    case 13976:  //  Schedule a Test Drive - Thank You
			thisVehicle=$('modelCode').value.toLowerCase();
      trackingModelCode = getTrackingModelCode(thisVehicle);
      if(trackingModelCode=='')
        thisCode="intcmp=Current_Offers.Banner.Test_Drive.";
      else
        thisCode="intcmp=Current_Offers." + trackingModelCode + ".Banner.Test_Drive.";

			if(/^(gconv|gcv|gcp|g35|gs|fx45|m45|qx56|ex35)$/.test(thisVehicle)){
				drawPromoSide(RegExp.$1, thisCode);
			}
			break;

    //case 13055:	// brochure both

		//commented for WSE

		/*case 13059:	// brochure mail
		case 13058:	// brochure ebrochure
			// will have fallen through by now if brochure. do not break!
			thisVehicle=location.pathname.replace(/^.+\b(g_coupe|g_sedan|g_convertible|m|fx|qx)\b.*$/,'$1');
			thisCode="intcmp=SummerSalesEvent.Banner.Brochure.Brochure_Req_Confirm.";
			thisArea='brochure';*/

		//END comment for WSE

		case 354:	// Locate a retailer Results
      insertLocateRetailerPromo();
			break;

/*
		case 354:	// Locate a retailer Results
			if(myPageId==354){
				thisVehicle='generic';
				thisCode="intcmp=WinterSalesEvent.Locate_Retailer:Current_Offers.Banner.";
				thisArea='brochure';
			}

		case 501:	//RAQ thank you / Send to Retailer
			if(myPageId==501){
				thisVehicle=page.model.toLowerCase()
				thisCode="intcmp=WinterSalesEvent.Config_Step6:Vehicle_Offer_1.Promo.";
			}
*/
		case 8350:	// Configurator Thank You page
      thisArea='config';
      thisVehicle=page.toLowerCase()
      trackingModelCode = getTrackingModelCode(thisVehicle);
      if(trackingModelCode=='')
        thisCode="intcmp=Current_Offers.Banner.Build.";
      else
        thisCode="intcmp=Current_Offers." + trackingModelCode + ".Banner.Build.";

			if(!$('tBottomEdge')){// then assign the right one its id.
				var imgs=document.getElementsByTagName('img');
				// try to find it by className
				for(var i=0;i<imgs.length;i++){
					if(imgs[i].className=='tBottomEdge'){
						imgs[i].id='tBottomEdge';
						break;
					}
				}
			}
			if(!$('tBottomEdge')){// Still not found?
				// try by filename. This is for locate, really.
				for(var i=0;i<imgs.length;i++){
					if(imgs[i].src.indexOf('rounded_corners_bot.gif')>=0){
						imgs[i].id='tBottomEdge';
						break;
					}
				}
			}
			//see, we had to id it so we'd know what to replace.
			if($('tBottomEdge')){
				$('tBottomEdge').parentNode.replaceChild(drawPromoBottom(thisVehicle,thisCode,thisArea),$('tBottomEdge'))
			}
			break;
	}
}



// comment to remove the promos - remove comment to add the promos back
/*
if(typeof hasAddedPromosToTools == 'undefined'){
	addLoadEvent(addPromosToTools)
	hasAddedPromosToTools=true;
}
*/

//-	END SSE PROMO	=	=	=	=	=	=	=	=	=	=	=
//-	END SSE PROMO	=	=	=	=	=	=	=	=	=	=	=
//-	END SSE PROMO	=	=	=	=	=	=	=	=	=	=	=


var detectFlash = deconcept.SWFObjectUtil.getPlayerVersion().major >= 8;

///////////////////////////////////   CTS   //////////////////////////////////////////

			/**  ** ** Loading topnav from XML starts here ** **  **/
			/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

			var xmlDoc;
			var hostname=window.location.hostname;

			// get a reference to the hostname unsullied by https or "build"
			var nonSecNonToolsPath = (!secureURIfound) ? getCurrentSiteForPromos() : nonSecurePath;

/**  Opening XML document  */
// This function imports XML using xmlPath and creates an XML Object for
// implementing DOM and extracting the data from XML.
function importXMLRaw(){

	if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.onload = createTopNav;
	}
	else if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4)
				createTopNav();
		};
 	}
	else
	{
		return;
	}

	// xmlPath holds the path of the xml file.
	var xmlPath = nonSecNonToolsPath+"/xml/non-flash/nonFlash.xml";
	xmlDoc.load(xmlPath);
}

				// Implements XML load using jQuery
				function importXML() {
					if (currentURI.indexOf('http://stage.build.infiniti.com') > -1){
						var xmlPath = "http://stage.build.infiniti.com/ngstcms_infiniti/js/non-flash/nonFlash.xml";
					}else if (currentURI.indexOf('http://build.infinitiusa.com') > -1){
						var xmlPath = "http://build.infinitiusa.com/ngstcms_infiniti/js/non-flash/nonFlash.xml";
					}else if (currentURI.indexOf('secure.infinitiusa.com') > -1){
						var xmlPath = "https://secure.infinitiusa.com/xml/non-flash/nonFlash.xml";
					}else{
						var xmlPath = nonSecNonToolsPath+"/xml/non-flash/nonFlash.xml";
					}

					if (typeof jQuery != 'undefined') {
						jQuery.ajax({url: xmlPath, async: false, dataType: "xml",
							error: function (o, status, error) {if (typeof(console) != 'undefined') console.log("o: " + o + "\nstatus: " + status + "\nerror: " + error);},
							success: function (data, status) {xmlDoc = data; createTopNav(); }
						});
					} else {
						importXMLRaw();
					}
				}

				/** Topnav is a constructor to hold attributes of each menu item*/
				function topnavitem(name,source,href,border,bordercolor){
					this.name = name;
					this.source = source;
					this.href = href;
					this.border = border;
					this.bordercolor = bordercolor;
				}

				// set to resolve Safari bug
				varMenuComplete = false;

				/** Creates top navigator using data from XML sheet */
				function createTopNav(){
					if (varMenuComplete==true){
						return;
					}
					var menus = xmlDoc.getElementsByTagName("menu");
					var no_of_menus = menus.length;
					jQuery("#gTopNav").html("");
					jQuery("#gTopNavExternal").html("");
					jQuery("#ufoGlobalNav").html("");/*added to fix SR 17503*/

					for(var i=0; i<menus.length; i++)
					{
						var iframeWidth=0;
						var iframeHeight=0;
						var menuitems = menus[i].childNodes;
						var no_of_items = menus[i].childNodes.length;
						var topnavarray = new Array(no_of_items);
						var j=0;
						if (menus[i].childNodes[j].nodeType != 1)
							j++;
						if(menus[i].childNodes[j].firstChild.nodeValue=="iframe"){
							iframeWidth = menus[i].childNodes[j].getAttribute("width");
							iframeHeight=  menus[i].childNodes[j].getAttribute("height");
							j++;
							if (menus[i].childNodes[j].nodeType != 1)
								j++;
						}
						topnavarray[0] = new topnavitem(menus[i].childNodes[j].firstChild.nodeValue,menus[i].childNodes[j].getAttribute("src"),menus[i].childNodes[j].getAttribute("href"));
						j++;
						for( ; j<no_of_items; j++)
						{
							if (menus[i].childNodes[j].nodeType != 1)
								continue;
							topnavarray[menus[i].childNodes[j].getAttribute("order")] = new topnavitem(menus[i].childNodes[j].firstChild.nodeValue,menus[i].childNodes[j].getAttribute("src"),menus[i].childNodes[j].getAttribute("href"),menus[i].childNodes[j].getAttribute("border"),menus[i].childNodes[j].getAttribute("border-color"));
						}
						createmenu(topnavarray,iframeWidth,iframeHeight);
					}
					
					/*modifications to fix SR 17503: start here*/
					jQuery("#gTopNav > div,#gTopNavExternal > div,#ufoGlobalNav > div").css("float", "left");
					jQuery("#gTopNav *,#gTopNavExternal *,#ufoGlobalNav *").css("z-index", "300");
					jQuery("#gTopNav > div > div,#gTopNavExternal > div > div,#ufoGlobalNav > div > div").css("position","absolute");
					jQuery("#gTopNav > div > div,#gTopNavExternal > div > div,#ufoGlobalNav > div > div").hide();
					jQuery("#gTopNav > div > iframe,#gTopNavExternal > div > iframe,#ufoGlobalNav > div > iframe").hide();
					jQuery("#gTopNav > div,#gTopNavExternal > div,#ufoGlobalNav > div").hover(function(){showMenu(jQuery(this).attr("ID"),jQuery("#"+jQuery(this).attr("ID") +">"+" div").attr("ID"));},function(){hideMenu(jQuery(this).attr("ID"),jQuery("#"+jQuery(this).attr("ID") +">"+" div").attr("ID"));});
					jQuery("#gTopNav > div > div > div > a > img,#gTopNavExternal > div > div > div > a > img,#ufoGlobalNav > div > div > div > a > img").css("cursor","pointer");
					jQuery("#gTopNav > div > div > div > a >img,#gTopNavExternal > div > div > div > a >img,#ufoGlobalNav > div > div > div > a > img").each(function() { setOverSrc(this)});
					/*modifications to fix SR 17503: end here*/
					createFooter();
					varMenuComplete = true;
				}

				// This function creates menu for each item in the topNav depending on no. of menuitems
				// provided in the nonFlash.xml.
				function createmenu(menuarray,iframeWidth,iframeHeight)
				{
					var menuheaderdiv = imageanchordiv(menuarray[0].name,menuarray[0].source,menuarray[0].href);
					var itemdiv = document.createElement("div");
					itemdiv.id = menuarray[0].name+"items";
					var fixdiv = document.createElement("div");
					fixdiv.id = menuarray[0].name+"items1";
					var itemiframe = document.createElement("iframe");
					itemiframe.id = menuarray[0].name+"itemsiframe";
					jQuery(itemiframe).css({width:iframeWidth, height:iframeHeight});

					for(var k=1; k<menuarray.length && menuarray[k]!=null; k++){
						var menuImageDiv = imageanchordiv(menuarray[k].name,menuarray[k].source,menuarray[k].href);

						if(menuarray[k].border!=null ){
							jQuery(menuImageDiv).css({borderBottomWidth:menuarray[k].border, borderColor:menuarray[k].bordercolor, borderBottomStyle:"solid"});
						}

						itemdiv.appendChild(menuImageDiv);
					}

					fixdiv.innerHTML=itemdiv.innerHTML;
					menuheaderdiv.appendChild(itemdiv);
					menuheaderdiv.appendChild(fixdiv);
					menuheaderdiv.appendChild(itemiframe);

					// If gTopNav exists then menu is appended to gTopNav, else it's appended to gTopNavExternal.
					if($("gTopNav")){
						$("gTopNav").appendChild(menuheaderdiv);
					}else if($("gTopNavExternal")){
						$("gTopNavExternal").appendChild(menuheaderdiv);
					}/*added to fix SR 17503*/else if($("ufoGlobalNav")){
						$("ufoGlobalNav").appendChild(menuheaderdiv);
					}
				}

				// This function creates an anchor tag for every menuItem in the menu.
				// It takes three parameters: 1) the name of the div for each menuItem,
				// 2) source which is the path of the image and
				// 3) href which is the set as link for anchor tag.
				function imageanchordiv(divname,source,href){
					var img = document.createElement("img");
					img.id="img"+divname;
					img.src = "http://"+hostname+"/"+source;
					var a = document.createElement("a");
					if(href=="null"){
						jQuery(a).removeAttr("href");
					}else{
						a.setAttribute("href",nonSecNonToolsPath+"/"+href);
					}
					var div = document.createElement("div");
					div.id = divname;
					a.appendChild(img);
					div.appendChild(a);
					return div;
				}


/** This method Retains the menu even after moving on to menu list from menu header*/
function retainMenu(buttonID,menuID){
	jQuery("#"+menuID).show();
	jQuery("#"+buttonID+"itemsiframe").show();
}

				var menuShouldShow = new Array();
				var menuHiding = new Array();
				var menuShowing = new Array();

				/** To show menu list when mouse moves on to menu header */
				function showMenu(buttonID, menuID,alignment){
					if (typeof menuShouldShow[buttonID]=='undefined') {
						menuShouldShow[buttonID] = true;
					}
					menuShouldShow[buttonID] = true;
					if (typeof menuShowing[buttonID]=='undefined') {
						menuShowing[buttonID] = false;
					}
					if (typeof menuHiding[buttonID]=='undefined') {
						menuHiding[buttonID] = false;
					}
					if (!menuShowing[buttonID] && !menuHiding[buttonID]) {
						//jQuery("#"+menuID+"1").css({zIndex: "101"});
						var temp=jQuery("#"+buttonID).offset().left + ((alignment!="horizontal")?20:($(buttonID).offsetWidth-1));
						jQuery("#"+menuID ).css({left: temp+"px", top: jQuery("#"+buttonID).offset().top+((alignment!="horizontal")?($(buttonID).offsetHeight)+"px":0+"px") });
						jQuery("#"+menuID+"1").css({left: temp+"px", top: jQuery("#"+buttonID).offset().top+((alignment!="horizontal")?($(buttonID).offsetHeight)+"px":0+"px") });
						jQuery("#"+menuID).slideDown("fast", function() { menuShowing[buttonID] = false; if(!menuShouldShow[buttonID] && !menuHiding[buttonID]) { hideMenu(buttonID, menuID) }; } );
						jQuery("#"+menuID+"1").slideDown("fast");
						jQuery("#"+buttonID+"itemsiframe").css({position:"absolute",left: temp+"px", top: jQuery("#"+buttonID).offset().top+((alignment!="horizontal")?($(buttonID).offsetHeight)+"px":0+"px"), border:"none", zIndex:"99" });
						jQuery("#"+buttonID+"itemsiframe").slideDown("fast");
					}
				}

				/** To hide menu list when mouse moves out of menu header or menu list */
				function hideMenu(buttonID,menuID) {
					menuShouldShow[buttonID] = false;
					if(menuShowing[buttonID] == false) {
						menuHiding[buttonID] = true;
						jQuery("#"+menuID+"1").slideUp("fast");
						jQuery("#"+menuID).slideUp("fast", function() { menuHiding[buttonID] = false; if(menuShouldShow[buttonID] && !menuShowing[buttonID]) { showMenu(buttonID, menuID) }; } );
						jQuery("#"+buttonID+"itemsiframe").slideUp("fast");
					}
				}

				/** ** **  Loading topnav from XML ends here ** **  */

				/** Creates the Footer nav */
				// This function creates footernav only when footer is not created through globalNav.js
				function createFooter(){
					var baseURL = '';
					if ( /build./.test(location.hostname) ||
							 /compare./.test(location.hostname) ||
							 /chrome./.test(location.hostname) ||
							 /search./.test(location.hostname) )
						baseURL = 'http://www.infinitiusa.com';

				  // It's checked if globalNav.js file is included or not
					if(jQuery('script[src$=globalNav.js]').length==0) {
						$('gFooter').innerHTML="";
						var footer = "";
						footer += '<a href="' + baseURL + '/global/index.html" target="wGlobal" id="gFooterAboutLink" style="text-decoration: none">Infiniti Worldwide</a> ';

						if (detectFlash && currentURI.indexOf('/non-flash/') == -1) {
							footer += '<a href="' + baseURL + '/iapps/handraiser/siteWideOptin?tool=footer.sitewide_optin" style="text-decoration: none">Join Mailing List</a> ';
						}

						footer += '<a href="' + baseURL + '/iapps/contactus" style="text-decoration: none">Contact Us</a> ';
						footer += '<a id="siteFeedbackLink" onclick="showbox()" href="#" style="text-decoration: none">Site Comments</a> ';

						if (detectFlash && currentURI.indexOf('/non-flash/') == -1) {
							footer += '<a href="' + baseURL + '/global/sitemap.html" style="text-decoration: none">Site Map</a> ';
						}

						footer += '<a href="' + baseURL + '/global/privacy.html" style="text-decoration: none">Privacy & Legal</a> ';
						
						if (currentURI.indexOf('/non-flash/') > -1)
							footer += '<a href="http://www.adobe.com/products/flashplayer/" style="text-decoration: none">Get Flash</a>';
						
						$('gFooter').innerHTML = footer;
						$('gFooter').style.visibility = 'visible';
					}
					removeLinks();
				}

				function removeLinks(){
					if($('bottomLeftLink'))
					{
						$('bottomLeftLink').innerHTML="";
						$('bottomLeftLink').className="";
					}
					if($('mailBrochureHome'))
					{
						$('mailBrochureHome').innerHTML="";
						$('mailBrochureHome').className="";
					}
					if($('eBrochureHome'))
					{
						$('eBrochureHome').innerHTML="";
						$('eBrochureHome').className="";
					}
					if($('bothBrochureHome'))
					{
						$('bothBrochureHome').innerHTML="";
						$('bothBrochureHome').className="";
					}
				}

				// Open External swf in new window
				// Argument swfName, querystr, width and height are required, the others optional
				// Usage: <a href="#" onclick="return popExtSwf('mySwf.swf', 'a=b', 600, 400, 'myWin', 'resizeable=no,location=no')">
				// used by G Coupe NavTeq Traffic Key Feature
				function popExtSwf(swfName, querystr, width, height, title, params){
				  var features = "";
				  var myurl = '/popSwf.html?swfname=' + swfName;
				  var isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != -1);

				  if (width) {
					var winWidth = width;
					if(isSafari) winWidth += 20;    // hack to enlarge window for Safari
					features += "width=" + winWidth + ",left=" + Math.floor( (screen.width - width) / 2);
					myurl += '&width=' + width;
				  }

				  if (height) {
					var winHeight = height;
					if(isSafari) winHeight += 20;   // hack to enlarge window for Safari
					features += ",height=" + winHeight + ",top="+Math.floor( (screen.height - height) / 2);
					myurl += '&height=' + height;
				  }

				  if (querystr) {
					myurl += '&' + querystr;

					var qsSrc = getStringParam(querystr, 'src');
					if (qsSrc != '')
					  myurl += '&Model=' + qsSrc;
				  }

				  if (title) myurl += '&title=' + escape(title);
				  if (params) features += ","+params;
				  var winname = name ? name : "infiniti_ext";
				  window.open(myurl, winname, features);
				}

				function fncFixGlobalFooter(){
					var baseURL = '';
					if ( (typeof(isExternal)=='boolean' && isExternal==true && !/.qa/.test(location.hostname)) ||
							 /build./.test(location.hostname) ||
							 /compare./.test(location.hostname) ||
							 /chrome./.test(location.hostname) ||
							 /search./.test(location.hostname) ) {
						baseURL = 'http://www.infinitiusa.com';
					}

/*					
          if (/espanol/.test(currentURI)) {

						footerHTML = '<a href="/global/index.html" target="wGlobal" onMouseover="ddrivetip(\'En ingl&#233;s\')" onMouseout="hideddrivetip()" id="gFooterAboutLink">Infiniti Global</a>'
											 + '<a href="/iapps/handraiser/siteWideOptin?tool=footer.sitewide_optin" style="text-decoration: none" onMouseover="ddrivetip(\'En ingl&#233;s\')" onMouseout="hideddrivetip()">Inscr&#237;bete en la Lista de Correos</a>'
											 + '<a href="/ownership/accessories.html?tool=footer.accessories" style="text-decoration: none" onMouseover="ddrivetip(\'En ingl&#233;s\')" onMouseout="hideddrivetip()">Accesorios</a>'
											 + '<a href="/iapps/contactus" style="text-decoration: none" onMouseover="ddrivetip(\'En ingl&#233;s\')" onMouseout="hideddrivetip()">Cont&#225;ctanos</a>'
											 + '<a id="siteFeedbackLink" onclick="showbox()" href="#" style="text-decoration: none" onMouseover="ddrivetip(\'En ingl&#233;s\')" onMouseout="hideddrivetip()">Comentarios</a>'
											 + '<a href="/global/privacy.html" style="text-decoration: none" onMouseover="ddrivetip(\'En ingl&#233;s\')" onMouseout="hideddrivetip()">Privacidad y Legal</a>';
				  } else if (/chinese/.test(currentURI)) {

								footerHTML = '<a href="/global/index.html" target="wGlobal" onMouseover="ddrivetip(\'è‹±æ–‡\')" onMouseout="hideddrivetip()" id="gFooterAboutLink"><img src="/chinese/img/global/foot-inf-global.gif"  alt="" width="69" height="11" style="display:inline;"/></a>'
													 + '<a href="/iapps/handraiser/siteWideOptin?tool=footer.sitewide_optin" style="text-decoration: none" onMouseover="ddrivetip(\'è‹±æ–‡\')" onMouseout="hideddrivetip()"><img src="/chinese/img/global/foot-mail-list.gif"  alt="" width="68" height="11" style="display:inline;"/></a>'
													 + '<a href="/ownership/accessories.html?tool=footer.accessories" style="text-decoration: none" onMouseover="ddrivetip(\'è‹±æ–‡\')" onMouseout="hideddrivetip()"><img src="/chinese/img/global/foot-accessories.gif"  alt="" width="22" height="11" style="display:inline;"/></a>'
													 + '<a href="/iapps/contactus" style="text-decoration: none" onMouseover="ddrivetip(\'è‹±æ–‡\')" onMouseout="hideddrivetip()"><img src="/chinese/img/global/foot-contact.gif"  alt="" width="47" height="11" style="display:inline;"/></a>'
													 + '<a id="siteFeedbackLink" onclick="showbox()" href="#" style="text-decoration: none" onMouseover="ddrivetip(\'è‹±æ–‡\')" onMouseout="hideddrivetip()"><img src="/chinese/img/global/foot-comment.gif"  alt="" width="47" height="11" style="display:inline;"/></a>'
													 + '<a href="/global/privacy.html" style="text-decoration: none" onMouseover="ddrivetip(\'è‹±æ–‡\')" onMouseout="hideddrivetip()"><img src="/chinese/img/global/foot-priv-legal.gif"  alt="" width="91" height="11" style="display:inline;"/></a>';
						  } else {
								footerHTML = '<a href="' + baseURL + '/global/index.html" target="wGlobal" id="gFooterAboutLink" style="text-decoration: none;font-weight:bold;">Infiniti Worldwide</a>';

								if(detectFlash && currentURI.indexOf('/non-flash/') == -1) {
									footerHTML += '<a href="' + baseURL + '/iapps/handraiser/siteWideOptin?tool=footer.sitewide_optin" style="text-decoration: none">Join Mailing List</a>'
															+ '<a href="' + baseURL + '/ownership/accessories.html?tool=footer.accessories" style="text-decoration: none;">Accessories</a>';
								}

								footerHTML += '<a href="' + baseURL + '/iapps/contactus" style="text-decoration: none">Contact Us</a>'
													  + '<a id="siteFeedbackLink" onclick="showbox()" href="#" style="text-decoration: none">Site Comments</a>';

								if (detectFlash && currentURI.indexOf('/non-flash/') == -1)
									footerHTML += '<a href="' + baseURL + '/global/sitemap.html" style="text-decoration: none">Site Map</a>';

								footerHTML += '<a href="' + baseURL + '/global/privacy.html" style="text-decoration: none">Privacy & Legal</a>';

								if (currentURI.indexOf('/non-flash/') > -1)
									footerHTML += '<a href="http://www.adobe.com/products/flashplayer/" style="text-decoration: none">Get Flash</a>';
						  }

				
				
				
				
				

					if ($('gFooter')) {
						$('gFooter').innerHTML = footerHTML;
						if($('gFooter').style)
							$('gFooter').style.visibility = 'visible';
				  }
				}
				
				
				*/
				
				

				// only used on pre-sell page(s)?  uses initUFO
				function loadFlashNonFlashGlobalNav() {
				  if (hasReqestedFlashVersion) {
					// load flash global nav
					var sModel = getModelName();
					if (sModel)
						$('gTopNav').setAttribute("ufoflashvars","model="+sModel);
					var xmlPath = trim($('ufoGlobalNavMovie').innerHTML).replace(/::.*:/g,'');
					var basePath = xmlPath.substring(0,xmlPath.lastIndexOf("/flash"))+"/flash";
					$('gTopNav').setAttribute("ufobase", basePath);
					initUFO('gTopNav','ufoGlobalNavMovie');
				  } else {
					// load non-flash global nav
					addLoadEvent(alignElements);
					addLoadEvent(importXML);
				  }
				}

function IsNumeric(sText) {
  var ValidChars = "0123456789";
  var IsNumber = true;
  var Char;

  if(sText==null || sText.length==0) {
    return false;
  }

  for (i = 0; i < sText.length && IsNumber == true; i++) {
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) == -1) {
      IsNumber = false;
    }
  }
  return IsNumber;
}

		function swapHeaders(){
			for(var i=1;i<=2;i++){
				var _h=document.getElementsByTagName('h'+i);
				for(var j=0;j<_h.length;j++){
					if(/gSwap/.test(_h[j].className)){
						swapHeader(_h[j],"h{0}_{1}".format(i,j))
					}
				}
			}
		}
		addLoadEvent(swapHeaders);
		HnHeights=[22,16];

		function swapHeader(myHeader,swfID){
			if(myHeader && /h[12]/i.test(myHeader.tagName)){
				var headerN=+myHeader.tagName.replace(/h/i,'')
				var _id=swfID||'header'+(''+Math.random()).replace(".",'')
				var _ih=myHeader.innerHTML.replace(/^\s+|\s+$|[\r\n]/g,'');
				_ih=_ih.replace(/["' \t]/g,function(blah1){return escape(blah1)});
				var _d=document.createElement('div');
				myHeader.innerHTML="";
				_d.className="gNoPrint";
				_d.id=_id;
				myHeader.appendChild(_d);
				var _d=document.createElement('div');
				_d.className="gOnlyPrint";
				_d.innerHTML=unescape(_ih);
				_d.id=_id+"_text"
				myHeader.appendChild(_d);
				var _fv={}
				_fv["h{0}Text".format(headerN)]=_ih;
				_fv.param_quality="low";
				new swfoWrapper("/flash/global/h1.swf", _id, _fv, 720, HnHeights[headerN-1]);
				myHeader.style.visibility = 'visible';
			}
		}

function closeInfinitiUSAPopup(){
	jQuery("#iusapop").hide();
	jQuery(".iusaTransparentDiv").hide();
	jQuery(".iusaPopupBackground").hide();

  if($("suppressiusa")) {
    if($("suppressiusa").checked) {
      // write cookie so we don't show popup again for 365 days
      var expires = 365 * 1000 * 60 * 60 * 24;
      var today = new Date();
      today.setTime( today.getTime() );
      var expires_date = new Date( today.getTime() + (expires) );
      var cookieString = "suppressiusapopup=1;" + "path=/; expires=" + expires_date.toGMTString();
      document.cookie = cookieString;
    }
  }
}

function createInfinitiUSATransparentDiv()
{
	var transparentDiv = document.createElement("div");
	transparentDiv.id = "iusaTransparentDiv";
	transparentDiv.className = "iusaTransparentDiv";

//  var offsetObj = jQuery(".gBody").offset();
//  if(typeof(offsetObj)=="undefined")
//    offsetObj = jQuery(".gbody").offset();

//	jQuery(transparentDiv).css({left:(offsetObj.left+0)+"px"});

	document.body.appendChild(transparentDiv);
	jQuery("#iusaTransparentDiv").fadeTo("fast",0.4);
}

function getElementsByClassName(classname, node) {
  if(!node) node = document.getElementsByTagName("body")[0];
  var a = [];
  var re = new RegExp('\\b' + classname + '\\b');
  var els = node.getElementsByTagName("*");
  for(var i=0,j=els.length; i<j; i++)
    if(re.test(els[i].className))
      a.push(els[i]);
  return a;
}

function iusaPngPreloadFix()
{
	jQuery(".iusaPopupBackground > img").ifixpng();
}

function preLoadImages(source)
{
	if (!!document.images)
    {
      preload_image_object = new Image();
	  preload_image_object.src=source;
    }
}

function ShowInfinitiUSAPopup()
{
	// read rdx querystring param
	if(suppressInfinitiUSAPopup || getQueryParam('rdx')==undefined || getQueryParam('rdx').length==0)
		return;

  // read cookie to see if user suppressed InfinitiUSA popup
  var suppressedPopup = true;
  if (document.cookie.indexOf("suppressiusapopup=") == -1) {
    suppressedPopup = false;
  }

  if(suppressedPopup)
    return;
  
  // read cookie to see if user already saw InfinitiUSA popup for this session
  var showedPopup = true;
  if (document.cookie.indexOf("showediusapopup=") == -1) {
    showedPopup = false;
  }

  if(showedPopup)
    return;
  
  // create popup
	var iusaDiv = document.createElement("div");
	iusaDiv.id = "iusaPopupContainer";
	document.body.appendChild(iusaDiv);

  var iusaPopupBGPath = secureNonSecurePath + "/img/infiniti-usa/infinitiusapopup.png";
  var iusaPopupSuppressText = "Do Not Display This Message Again";
  var iusePopupClosePath = secureNonSecurePath + "/img/infiniti-usa/close.gif";
  
  if(currentURI.indexOf('/espanol/') >= 0) {
    iusaPopupBGPath = "/espanol/img/infiniti-usa/infinitiusapopup.png";  
    iusaPopupSuppressText = "No mostrar este mensaje nunca mÃ¡s.";
    iusePopupClosePath = "/espanol/img/infiniti-usa/close.gif";
  }
  
  $('iusaPopupContainer').innerHTML = '<div class="iusaPopupBackground" id="iusaPopupBackground">' +
    '    <img src="' + iusaPopupBGPath + '"/>' +
    '  </div>' +
    '  <div id="iusapop">' +
    '		  <div class="iusapopclosediv">' +
    '				<a href="#" onclick="javascript:closeInfinitiUSAPopup();"><img border="0" src="' + iusePopupClosePath + '" /></a>' +
    '		  </div>' +
    '		  <div class="iusaPopupText">' +
    '       <input type="checkbox" name="suppressiusa" id="suppressiusa" style="background:transparent;border:0">&nbsp;&nbsp;' + iusaPopupSuppressText + '<br />' +
    '       <br /><br />' +
    '    		<a href="#" onclick="javascript:closeInfinitiUSAPopup();"><img class="iusaButton" src="' + secureNonSecurePath + '/img/infiniti-usa/popup_ok.gif" onload="setOverSrc(this)" alt="OK" name="iusaOK" width="61" height="28" border="0" id="iusaOK" /></a>' +
    '		  </div>' +
    '	</div>';
  
  // write cookie so we don't show popup again for this session
  document.cookie = "showediusapopup=1;" + "path=/";
  
	createInfinitiUSATransparentDiv();
  var offsetLeft = 0;
  var offsetTop = 0;
  var offsetObj = jQuery(".gBody").offset();
  if(typeof(offsetObj)!="undefined") {
    offsetLeft = offsetObj.left;
    offsetTop = offsetObj.top;
  } else {
    offsetObj = jQuery(".gbody").offset();  
    if(typeof(offsetObj)!="undefined") {
      offsetLeft = offsetObj.left;
      offsetTop = offsetObj.top;
    } else {
      offsetLeft =  + (document.body.clientWidth/2) - 482;
      offsetTop = 0;
    }
  }
  
  jQuery("#iusapop,.iusaPopupBackground").css({left:(offsetLeft + 239)+"px",top:(offsetTop + 120)+"px",visibility:"visible"});
	iusaPngPreloadFix();
}

try {
	if (typeof(jQuery)=='undefined') {
		document.write('<scr'+'ipt src="' + secureNonSecurePath + '/js/jquery/jquery.js" language="JavaScript" type="text/javascript"></scr'+'ipt>\n');
	}
	//document.write('<scr'+'ipt src="' + secureNonSecurePath + '/js/jquery/jquery.ifixpng.js" language="JavaScript" type="text/javascript"></scr'+'ipt>\n');
} catch (e) {
	document.write('<scr'+'ipt src="' + secureNonSecurePath + '/js/jquery/jquery.js" language="JavaScript" type="text/javascript"></scr'+'ipt>\n');
	//document.write('<scr'+'ipt src="' + secureNonSecurePath + '/js/jquery/jquery.ifixpng.js" language="JavaScript" type="text/javascript"></scr'+'ipt>\n');
}

if(currentURI.indexOf('/search./') == -1) {
	jQuery('head').append('<link rel="stylesheet" type="text/css" href="' + secureNonSecurePath + '/css/g/iusa.css" />\n');
}

//if(currentURI.indexOf('/non-flash/') == -1 && currentURI.indexOf('/search./') == -1)
if(currentURI.indexOf('/non-flash/') == -1)
  addLoadEvent(ShowInfinitiUSAPopup);

// Fix IE 6 Not caching CSS background images (flickering css bg images on hover states)
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}
}
