//-- // ### URI ENFORCER ############################################################
var currentURI = window.location.href;

//alert(currentURI);

var isNissanSite = (	location.hostname.indexOf('www.nissanusa.com') > -1 ||
						location.hostname.indexOf('secure.nissanusa.com') > -1 ||
						location.hostname.indexOf('stage.nissanusa.com') > -1 ) ? true : false;
var isStageEnv = (currentURI.search('stage.') > -1) ? true : false;

//  set paths for...                 Live site                       Staging environment ) ?	"https://secure.nissanusa.com" : "https://www.stage.nissanusa.com";
var securePath =    (!isStageEnv) ?	"https://secure.nissanusa.com" : "https://secure.stage.nissanusa.com";

var nonSecurePath = (currentURI.search('collage.') > -1) ? "http://collage.designory.com:92" : ((currentURI.search('www.integ') > -1) ? "http://www.integ.nissanusa.nna" : ((currentURI.search('www.qa') > -1) ? "http://www.qa.nissanusa.nna" : ((!isStageEnv) ? "http://www.nissanusa.com" : "http://www.stage.nissanusa.com")));

var nonSecurePath = (currentURI.search('collage.') > -1) ? "http://collage.designory.com:92" : ((currentURI.search('www.integ') > -1) ? "http://www.integ.nissanusa.nna" : ((currentURI.search('www.qa1') > -1) ? "http://www.qa1.nissanusa.com" : ((currentURI.search('www.qa2') > -1) ? "http://www.qa2.nissanusa.com" : ((currentURI.search('www.newdev') > -1) ? "http://www.newdev.nissanusa.com" : ((!isStageEnv) ? "http://www.nissanusa.com" : "http://www.stage.nissanusa.com")))));

//  non-secure URI         -->         -->         -->          secure URI
var secureURIs = [

	// My Nissan
	["http://www.nissanusa.com/apps/mynissan",					"https://secure.nissanusa.com/apps/mynissan"],
	["https://www.nissanusa.com/apps/mynissan",					"https://secure.nissanusa.com/apps/mynissan"],
	["http://secure.nissanusa.com/apps/mynissan",				"https://secure.nissanusa.com/apps/mynissan"],
	["http://www.stage.nissanusa.com/apps/mynissan",			"https://secure.stage.nissanusa.com/apps/mynissan"],

	// PreApproval
	["http://www.nissanusa.com/apps/preapprovedinput",			"https://secure.nissanusa.com/apps/preapprovedinput"],
	["https://www.nissanusa.com/apps/preapprovedinput",			"https://secure.nissanusa.com/apps/preapprovedinput"],
	["http://secure.nissanusa.com/apps/preapprovedinput",		"https://secure.nissanusa.com/apps/preapprovedinput"],
	["http://www.stage.nissanusa.com/apps/preapprovedinput",	"https://secure.stage.nissanusa.com/apps/preapprovedinput"],
	
	["http://www.nissanusa.com/apps/espanol/preapprovedinput",			"https://secure.nissanusa.com/apps/espanol/preapprovedinput"],
	["https://www.nissanusa.com/apps/espanol/preapprovedinput",			"https://secure.nissanusa.com/apps/espanol/preapprovedinput"],
	["http://secure.nissanusa.com/apps/espanol/preapprovedinput",		"https://secure.nissanusa.com/apps/preapprovedinput"],
	["http://www.stage.nissanusa.com/apps/espanol/preapprovedinput",	"https://secure.stage.nissanusa.com/apps/espanol/preapprovedinput"],

	// PreApproval - LDS
	["http://www.nissanusa.com/apps/preapprovedconfirm",	"https://secure.nissanusa.com/apps/preapprovedconfirm"],
	["https://www.nissanusa.com/apps/preapprovedconfirm",	"https://secure.nissanusa.com/apps/preapprovedconfirm"],
	["http://secure.nissanusa.com/apps/preapprovedconfirm", "https://secure.nissanusa.com/apps/preapprovedconfirm"],
	["http://www.stage.nissanusa.com/apps/preapprovedconfirm", "https://secure.stage.nissanusa.com/apps/preapprovedconfirm"],
	
	["http://www.nissanusa.com/apps/espanol/preapprovedconfirm",	"https://secure.nissanusa.com/apps/espanol/preapprovedconfirm"],
	["https://www.nissanusa.com/apps/espanol/preapprovedconfirm",	"https://secure.nissanusa.com/apps/espanol/preapprovedconfirm"],
	["http://secure.nissanusa.com/apps/espanol/preapprovedconfirm", "https://secure.nissanusa.com/apps/espanol/preapprovedconfirm"],
	["http://www.stage.nissanusa.com/apps/espanol/preapprovedconfirm", "https://secure.stage.nissanusa.com/apps/espanol/preapprovedconfirm"],

	// RDR - Owners
	["http://www.nissanusa.com/apps/RdrOwners",					"https://secure.nissanusa.com/apps/RdrOwners"],
	["https://www.nissanusa.com/apps/RdrOwners",				"https://secure.nissanusa.com/apps/RdrOwners"],
	["http://secure.nissanusa.com/apps/RdrOwners",				"https://secure.nissanusa.com/apps/RdrOwners"],
	["http://www.stage.nissanusa.com/apps/RdrOwners",			"https://secure.stage.nissanusa.com/apps/RdrOwners"],

	// Service records
	["http://www.nissanusa.com/apps/servicerecords",		"https://secure.nissanusa.com/apps/servicerecords"],
	["https://www.nissanusa.com/apps/servicerecords",		"https://secure.nissanusa.com/apps/servicerecords"],
	["http://secure.nissanusa.com/apps/servicerecords",		"https://secure.nissanusa.com/apps/servicerecords"],
	["http://www.stage.nissanusa.com/apps/servicerecords",	"https://secure.stage.nissanusa.com/apps/servicerecords"]

];
var isSpanishPage=(/\bes(panol)?\b/.test(location.pathname) || /\blanguage=es\b/.test(location.search) ); // latter half for search

var secureURIfound = false;
//    push user to secure URL
if (isNissanSite && currentURI.search('http://') > -1) {
	for (var i in secureURIs) {
		if (currentURI.search(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.search('http://secure.') > -1) {
		location.replace(currentURI.replace("http://secure.","http://www."));
	}
}
//    pull user from secure URI
else if (isNissanSite && currentURI.search('https://') > -1) {
	for (var i in secureURIs) {
		if (currentURI.search(secureURIs[i][1]) > -1) {
			secureURIfound = true;
		}
	}
	// no secure URI found, check & pull user from bad https://www URI
	if (!secureURIfound && currentURI.search('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('.nissanusadealers.com') > -1 &&
    currentURI.indexOf('/apps/dealerlocator') == -1 &&
		!/zipCode=/.test(currentURI) &&
		!/city=(.*)&state=(.*)/.test(currentURI)) {
	location.replace(currentURI.replace(".nissanusadealers.com",".nissanusa.com"));
}

var allVehicles=['altima','armada','frontier','maxima','murano','pathfinder','quest','sentra','ser','titan','versa','xterra','z'];
var allVehiclesPattern=new RegExp("\\b("+allVehicles.join("|")+")\\b","i");
var isVehiclePage=allVehiclesPattern.test(location.pathname);
var thisVehicle=RegExp.$1;// because of the line above, this is populated with '' or with the model name

if(typeof globalNavFv=='undefined') var globalNavFv={};
if(typeof footerNavFv=='undefined') var footerNavFv={};
if(typeof regionalNavFv=='undefined') var regionalNavFv={};

// #############################################################################

/* GLOBAL SCRIPTS */

// XML HTTP Request general use object
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {
	try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp=false; }
}
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
	try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp=false; }
if (!xmlhttp && window.createRequest)
	try { xmlhttp = window.createRequest(); } catch (e) { xmlhttp=false; }


// 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);
}

// Shortuct to innerHTML
function getHtml(elmId) {
	return $( elmId ).innerHTML;
}

// Modifier for innerHTML
function setHtml(elmId, strContent) {
	$( elmId ).innerHTML = strContent;
}

// This is Sean Schricker's implementation of SimplERSwap
function setOverSrc(elem){
	elem.overStatePreload=new Image();
	elem.overStatePreload.src=elem.src.replace(/(_on)*(\.\w+)$/,'_on$2');
	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='';
}

function setOverSrc_ro(elem){
	elem.overStatePreload=new Image();
	elem.overStatePreload.src=elem.src.replace(/(_ro)*(\.\w+)$/,'_ro$2');
	elem.onmouseover=function(){this.src=this.src.replace(/(_ro)*(\.\w+)$/,'_ro$2')}
	elem.onmouseout=function(){this.src=this.src.replace(/(_ro)+(\.\w+)$/,'$2')}
	elem.onload='';
}


// Open External links in new window
// Argument href is required, all others optional
// Usage: <a href="http://www.foo.bar" onclick="return popExt(this.href, 600, 400, 'myWin', 'resizeable=no,location=no')">
function popExt(href, width, height, name, params){
  var features = "";
  if (width) features += "width="+width+",left="+Math.floor( (screen.width - width) / 2);
  if (height) features += ",height="+height+",top="+Math.floor( (screen.height - height) / 2);
  if (params) features += ","+params;
  var winname = name ? name : "nissanusa_ext";
  window.open(href, winname, features);
  return false;
}
// using above for flash returns false for the page.
function popExtFL(href, width, height, name, params){
  var features = "";
  if (width) features += "width="+width+",left="+Math.floor( (screen.width - width) / 2);
  if (height) features += ",height="+height+",top="+Math.floor( (screen.height - height) / 2);
  if (params) features += ","+params;
  var winname = name ? name : "nissanusa_ext";
  window.open(href, winname, features);
}

//added popExtSwf() function as per SR 17191
// 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')">
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 : "nissanusa_ext";
  window.open(myurl, winname, features);
}


// widePage repositions bottom frame on apps
// called on page load
// should be called after rendering dynamic content
function widePage(){
  if (document.getElementById("frameContent")){
    var h = document.getElementById("frameContent").clientHeight;
    var frameH = (h+20);
    if (document.getElementById("frameBgTop")) {
	    if (frameH > 539) { document.getElementById("frameBgBottom").style.height=(frameH-539)+"px"; } else { document.getElementById("frameBgBottom").style.display = "none"; }
	    document.getElementById("frameBgTop").style.height= frameH + "px";
    } else {
	    	if(document.getElementById("frameBg"))
		    document.getElementById("frameBg").style.height= frameH + "px";
    }
  }
}
addLoadEvent(widePage);

// ## Language Manager Object code
var langMgr = {
	enToEs: [], esToEn: [], rootEn: '/', rootEs: '/espanol/', doingReq: false,
	pairURLs: function (enURL, esURL) {
		langMgr.enToEs[enURL] = esURL;
		langMgr.esToEn[esURL] = enURL;
	},
	jumpToLanguage: function (lang) {
		if (langMgr.doingReq) return;
		langMgr.doingReq = true;
		var pathName = location.pathname;
		var hostName = location.href.substring( 0,location.href.indexOf(pathName) );
		var queryString = (location.search.length > 0) ? location.href.substring( location.href.indexOf(location.search) ) : '';
		if (lang == 'es') {
			var destURL = langMgr.enToEs[pathName];
			if (destURL) location.href = hostName+destURL+queryString;
			else
				if (xmlhttp) langMgr.requestPage( hostName+'/espanol'+pathName, hostName+langMgr.rootEs, queryString );
				else location.href = hostName+langMgr.rootEs;
		}
		else if (lang == 'en') {
			var destURL = langMgr.esToEn[pathName];
			if (destURL) location.href = hostName+destURL+queryString;
			else
				if (xmlhttp) {
					var esString = '/espanol';
					var destUrlPrefix = pathName.substring( 0, pathName.indexOf(esString) );
					var destUrlSuffix = pathName.substring( pathName.indexOf(esString)+esString.length, pathName.length );
					langMgr.requestPage( hostName+destUrlPrefix+destUrlSuffix, hostName+langMgr.rootEn, queryString );
				}
				else location.href = hostName+langMgr.rootEs;
		}
	},
	requestPage: function (url,rootUrl,queryString) {
		xmlhttp.open("HEAD", url, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4)
				if (xmlhttp.status==200)	location.href = url+queryString;
				else						location.href = rootUrl;
		}
		xmlhttp.send(null);
	}
}


function trim(str){
	//return str.replace(' ','').replace(/(\s)/g,''); << WTF is this nonsense??
	return str.replace(/^\s+|\s+$/g,'');
}

// Return a value from the query string
function getQueryParam(paramName) {
	var qString = location.search.substring(1);
    if (qString.indexOf(paramName) == -1) return '';
    var pValueStart = qString.indexOf(paramName) + paramName.length + 1;
    var pValueEnd = qString.indexOf('&', pValueStart);
    if ( pValueEnd==-1 ) pValueEnd = qString.length;
    return unescape( qString.substring( pValueStart,pValueEnd ) );
}
// Return a querystring-formatted value from a string

function getStringParam(searchString, paramName) {

    if (searchString.indexOf(paramName) == -1) return '';

    var pValueStart = searchString.indexOf(paramName) + paramName.length + 1;

    var pValueEnd = searchString.indexOf('&', pValueStart);

    if ( pValueEnd==-1 ) pValueEnd = searchString.length;

    return unescape( searchString.substring( pValueStart,pValueEnd ) );

}


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';
}

// Flash parameter detection and passing for MICROSITES
function checkSrcParam() {
		var src, html, qPos;

		src = getQueryParam('src');
		if(src=='') return;

		html = getHtml('ufoPFAMovie');
		if(html) {
			qPos = html.indexOf('?');
			if(qPos > -1) //existing querystring?
				html += '&';
			else
				html += '?';

			html = html + 'src=' + src;
			setHtml('ufoPFAMovie', html);
		}
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// Returns the current environment and returns a string. Values: prod, stage, qa & dev
function getCurrentEnv() {
	var envHostName = location.hostname;
	var envPort = location.port;
	if (envPort == 9080 || envPort == 8080)		return 'dev';
	if (envHostName.indexOf("www.qa") > -1)		return 'qa';
	if (envHostName.indexOf("stage1.") > -1)		return 'stage';
	if (envHostName.indexOf(".nissanusa.com") > -1)	return 'prod';
	return 'prod';
}

// Returns the current locale for the page as a string. Values: en, es & null
function getCurrentLocale() {
	try {
		return $('metaLocale').content;
	} catch(e) { return null; }
}

// Allows proper functionality of the Flash global nav
function swapIndexIn() {
	document.getElementById("dataFlashGlobalNav").style.height = "550px";
}

function swapIndexOut() {
	document.getElementById("dataFlashGlobalNav").style.height = "75px";
}

// If a VLP, allow Flash div layer to vary in height
function snapFlash(size) {
	if ((!document.getElementById("movFlashGlobalNav")) && (document.getElementById("movFlashCore"))) {
		document.getElementById("movFlashCore").style.height=size+"px";
		document.getElementById("movFlashCore_swf").style.height=size+"px";
		//document.getElementById("gFlashCore").style.height=size+"px";
		//document.getElementsByTagName('embed')[0].setAttribute('height',size);
	}
}

// ###	Create wallpaper popup window
function popWallpaper(veh,index,size,isMicroSite) {
  if (isMicroSite == "yes") {
  	galleryWinObj = window.open('/wallpapers.html?vehicle=' + veh + '&index=' + index + '&size=1280' + '&ismicrosite=1','wallpaper','height=720,width=800');
  } else {
  	galleryWinObj = window.open('/wallpapers.html?vehicle=' + veh + '&index=' + index + '&size=1280','wallpaper','height=720,width=800');
  }
	galleryWinObj.focus();
}

// ###	Send email from Flash
function sendEmail(sentSubject, sentBody) {
    var s = sentSubject;
    var b = sentBody;
    var urlstring = "mailto:?subject="+s+"&body="+b;
    var newwin = window.open(urlstring);
}
function searchSite(myQuery){
	if(myQuery=='null'){
		myQuery='nissan';
	}
	var languageCode=(isSpanishPage)?'es':'en';
	var searchPageUrlTemplate="http://search.nissanusa.com/search?q={0}&ie=UTF-8&language={1}&site=NissanUSA_{2}&output=xml_no_dtd&client=default_frontend_prod&proxystylesheet=default_frontend_prod&oe=UTF-8";
	location.href=searchPageUrlTemplate.format( escape(myQuery), languageCode, languageCode.toUpperCase() );
}

//we only need this once, so it's going outside.
var swfoBaseURL = window.location.hostname;

var swfoBsplit = swfoBaseURL.split(".");

if(location.protocol=='https:'){
	//if secure, then it'll only be one of these 2
	swfoBaseURL=(/stage/.test(location.host))?"secure.stage.nissanusa.com":"secure.nissanusa.com";
}else if (swfoBsplit.length > 4 || swfoBsplit[0].toLowerCase() != "www") {
	var swfoNewbsplit = new Array();
	for (var bs = 0; bs < swfoBsplit.length; bs++) {
		if ((/(ww[w123]|dev|escher|qa|secure|stage|collage|nissanusa|prod|designory|com|nna|129|33|85|201|85|214)/i).test(swfoBsplit[bs])) {
			swfoNewbsplit.push(swfoBsplit[bs]);
		}
	}
	swfoBaseURL = swfoNewbsplit.join(".");
	if (swfoBaseURL.length == 0) {
		swfoBaseURL = "www.nissanusa.com";
	}
	if(!(/ww[w123]|collage|escher|prod|129/i).test(swfoBaseURL)){
			swfoBaseURL = "www." + swfoBaseURL;
		//swfoBaseURL = window.location.protocol+"//"+swfoBaseURL;
	}
} else {
	swfoBaseURL="";
}

//var swfoCoreURL = (swfoBaseURL : "") + "/flash/core.swf";
if(swfoBaseURL.length > 0){
	swfoBaseURL=window.location.protocol+"//"+swfoBaseURL+  ((location.port) ? (location.port == "8080" ? "" : ":"+location.port) : "") ;
}

// moved to addHistory.js
//function updateHash(histId)

// #############################################################################
// 						content from dhtml_pop.js
// #############################################################################

var _currentDhtmlPop
var minX=0, maxX=0
var minY=0, maxY=0

function _snapWithinBounds(min,val1, val2, max){
	if(isNaN(parseFloat(val2))){val2=val1}
	//val2 gives a second possible placement.
	if( ((val1>=max) & (val2<val1)) || ((val1<=min) & (val1<val2)) ){
		return Math.max( min, Math.min(val2,max) )
	}else{
		return Math.max( min, Math.min(val1,max) )
	}
}
function _snapX(val1,val2){
	return _snapWithinBounds(minX,val1,val2,maxX)
}
function _snapY(val1,val2){
	//if(_currentDhtmlPop.clientHeight > (maxY-minY)){
	//	//buggy, but may be worked with in the future to keep it onscreen.
	//	return _snapWithinBounds(minY,val1,null,minY)
	//}
	return _snapWithinBounds(minY,val1,val2,maxY)
}
function showDhtmlPop( obj, e, anchor, preferredPlacement, onopen, cleanupPop){
	/// sample usage: showDhtmlPop('dhtmlPopID',event,this,3)
	/// second and third args MUST be event and this when called from an anchor
	/// There are 2 new extra args. References to functions to call on opening and after closing.
	// see the switch() below for the preferredPlacement options.
	if(typeof onopen == 'function'){onopen(anchor,obj)}

	hideDhtmlPop()

	obj=document.getElementById(obj)
	if (obj==null) return;
	obj.style.visibility='hidden'
	obj.style.display='inline'

	_currentDhtmlPop=obj

	var tempX = 0, originalX = 0;
	var tempY = 0, originalY = 0;
	var offset=10;

	minX=(document.body.clientWidth-964)/2 //For centered-content div pages.
	maxX= minX+964-obj.clientWidth

  //alert('document.body.clientWidth = ' + document.body.clientWidth)

	minY=document.body.scrollTop
	maxY=document.body.clientHeight+document.body.scrollTop-(obj.clientHeight);

	tempX = originalX = (document.all) ? (event.clientX + document.body.scrollLeft - minX) : (e.pageX - minX);
	tempY = originalY = (document.all) ? (event.clientY + document.body.scrollTop) : (e.pageY);

/*
  if(document.all) {
    alert('event.clientX = ' + event.clientX)
    alert('document.body.scrollLeft = ' + document.body.scrollLeft)
    alert('minX = ' + minX)
  } else {
    alert('minX = ' + minX)
    alert('e.pageX = ' + e.pageX)
  }
*/

  //height hack for IE7
  version=0
  if (navigator.appVersion.indexOf("MSIE")!=-1) {
    temp=navigator.appVersion.split("MSIE")
    version=parseFloat(temp[1])
  }
  if (version>=7) //NON IE browser will return 0
    tempY += document.documentElement.scrollTop;

	switch(preferredPlacement.toLowerCase()){
		case 'side': /// right/left, mainly right, centered vertically.
			tempX=_snapX(tempX + offset, tempX-obj.clientWidth - offset)
			tempY=_snapY(tempY-(obj.clientHeight/2))
			break;

		case 'above': /// above.
			tempX=_snapX(tempX-(obj.clientWidth/2)-offset)
			tempY=_snapY(tempY-(obj.clientHeight)-offset, tempY+offset)
			break;

		case 'below': /// below.
			tempX=_snapX(tempX-(obj.clientWidth/2)+offset)
			tempY=_snapY(tempY+offset, tempY-(obj.clientHeight)-offset)
			break;

		case 'belowtallpage': /// belowTallPage.
			tempX=_snapX(tempX-(obj.clientWidth/2)+offset)
			tempY=tempY+offset //_snapY(tempY+offset, tempY-(obj.clientHeight)-offset) //
			break;

		case 'anchorcenter': /// anchorCenter.
//      alert('before: tempX = ' + tempX);
//      alert('obj.clientWidth = ' + obj.clientWidth);
//      alert('offset = ' + offset);

      tempX=_snapX(tempX-(obj.clientWidth/2)+offset)
			tempY=tempY-(obj.clientHeight/2)+offset

//      alert('after: tempX = ' + tempX);

      // make sure the right of the popup is not off the main page
      if((tempX + obj.clientWidth) > 964) { tempX = 964 - obj.clientWidth - 80; }

      // make sure the left of the popup positive
      if(tempX < 30) { tempX = 30; }

			break;

		case 'top': /// top.
			tempX=_snapX(tempX-(obj.clientWidth/2)+offset) - 200
			tempY= 0

      //Detect IE
      version=0
      if (navigator.appVersion.indexOf("MSIE")!=-1) {
        temp=navigator.appVersion.split("MSIE")
        version=parseFloat(temp[1])
      }

      // IE
      if (version > 0) {
        // make sure popup is below the start of the visible client area
        if(tempY < document.body.scrollTop) {
          tempY = document.body.scrollTop + 30
        }

        // make sure the bottom of the popup is above the bottom of the visible client area
/*
        if((tempY + obj.clientHeight) > document.body.scrollHeight) {
          tempY = document.body.scrollHeight - obj.clientHeight - 150
        }
*/
        if((tempY + obj.clientHeight) > (document.body.scrollHeight - 200)) {
          tempY = document.body.scrollHeight - obj.clientHeight - 350
        }

      // Non-IE
      } else {
        // make sure popup is below the start of the visible client area
        if(tempY < window.scrollY) {
          tempY = window.scrollY + 30
        }

        // make sure the bottom of the popup is above the bottom of the visible client area
/*
        if((tempY + obj.clientHeight) > (window.scrollY + document.body.scrollHeight)) {
          tempY = window.scrollY + document.body.scrollHeight - obj.clientHeight - 150
        }
*/
        if((tempY + obj.clientHeight) > (window.scrollY + document.body.scrollHeight - 200)) {
          tempY = window.scrollY + document.body.scrollHeight - obj.clientHeight - 350
        }
      }

/*
      //Detect IE5.5+
      version=0
      if (navigator.appVersion.indexOf("MSIE")!=-1) {
        temp=navigator.appVersion.split("MSIE")
        version=parseFloat(temp[1])
      }
      //NON IE browser will return 0
      if (version>=5.5)
        tempX -= 300
*/

      // make sure the left of the popup positive
      if(tempX < 30) { tempX = 30; }

      // make sure the top of the popup is below the global header
      if(tempY < 50) { tempY = 50; }

			break;

		case 'anchorabove': /// anchorAbove.
			tempX=_snapX(tempX-(obj.clientWidth/2)+offset)
			/*added if condition to fix SR 16560*/
		if (tempY < 730)
		{
			tempY=tempY - obj.clientHeight - offset - 200
		}

		else{	
			tempY=tempY - obj.clientHeight - offset - 400
		}
				
			break;

		case 'salesevent':
      tempX=_snapX(tempX-(obj.clientWidth/2)+offset)
			tempY=tempY-(obj.clientHeight/2)+offset

      // make sure the right of the popup is not off the main page
      if((tempX + obj.clientWidth) > 964) { tempX = 964 - obj.clientWidth - 80; }

      // make sure the left of the popup positive
      if(tempX < 30) { tempX = 30; }

      //Detect IE
      version=0
      if (navigator.appVersion.indexOf("MSIE")!=-1) {
        temp=navigator.appVersion.split("MSIE")
        version=parseFloat(temp[1])
      }

      // IE
      if (version > 0) {
        // make sure popup is below the start of the visible client area
        if(tempY < document.body.scrollTop) {
          tempY = document.body.scrollTop + 30
        }

        if (document.getElementById("tabSoaPageBgResize")) {
          // make sure the bottom of the popup is above the bottom of the visible client area
          if((tempY + obj.clientHeight) > (document.getElementById("tabSoaPageBgResize").clientHeight)) {
//            tempY = document.body.scrollHeight - obj.clientHeight - 240
            tempY -= obj.clientHeight
          }
        } else {
          // make sure the bottom of the popup is above the bottom of the visible client area
          if((tempY + obj.clientHeight) > (document.body.scrollHeight  - 340)) {
            tempY = document.body.scrollHeight - obj.clientHeight - 380
          }
        }

      // Non-IE
      } else {
        // make sure popup is below the start of the visible client area
        if(tempY < window.scrollY) {
          tempY = window.scrollY + 30
        }

        // make sure the bottom of the popup is above the bottom of the visible client are
        if (document.getElementById("tabSoaPageBgResize")) {
          if((tempY + obj.clientHeight) > (document.getElementById("tabSoaPageBgResize").clientHeight)) {
            tempY -= obj.clientHeight
          } else if((tempY + obj.clientHeight) > (window.scrollY + document.body.scrollHeight - 340)) {
            tempY = window.scrollY + document.body.scrollHeight - obj.clientHeight - 240
          }
        }
      }

      // make sure the top of the popup is below the global header
      if(tempY < 50)
        tempY = 50;

			break;

		default:
	}

	obj.style.top  = (tempY) + 'px';
	obj.style.left = (tempX) + 'px';
	obj.style.visibility='visible'

	/*with($('mPopShadow').style){
		width=obj.clientWidth+ 'px';
		height=obj.clientHeight+ 'px';
		top=(tempY+8) + 'px';
		left=(tempX+8) + 'px';
		display='block'
	}*/
	if(typeof cleanupPop == 'function'){cleanupPop()}
}
function _getElementNodes(popID){
	var nodes=[]
	var cn=$(popID).childNodes
	for(var i=0;i<cn.length;i++){
		if(cn[i].nodeType==1){ nodes.push(cn[i]) }
	}
	return nodes
}
function setDhtmlContentsTEMPLATE(popID){
	///begin prelim
	var nodes=_getElementNodes(popID)
	var header=nodes[1]
	var panel1=nodes[2]
	var panel2=nodes[3]
	///end prelim
	///begin your code ##########
	header.innerHTML=counterTest++

	return (popID)
}
function hideDhtmlPop(ref){
	if(_currentDhtmlPop){_currentDhtmlPop.style.display='none'}

	//if(ref){ref.style.display='none'}
	//$('mPopShadow').style.display='none'
}

// #############################################################################
// 						content from popup360.js
// #############################################################################

function popup360(name,code,year,lang,type) {
	winObj = window.open('/popup360.html?' + 'name='+name+'&code='+code+'&year='+year+'&lang='+lang+'&type='+type,"videoWindow","width=640,height=500,resizable,top=30,left=30");
	winObj.focus();
}

// #############################################################################
// 						content from load_background.js
// #############################################################################

var xmlhttp;
var ImageToLoad = '';

function loadBgImage(url)
{
  xmlhttp=null;
  ImageToLoad = url;
  // code for Mozilla, etc.
  if (window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest()
  }

  // code for IE
  else if (window.ActiveXObject)
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
  if (xmlhttp!=null)
  {
    xmlhttp.onreadystatechange=loadBgStateChange
    xmlhttp.open("GET",url,true)
    xmlhttp.send(null)
  }
  else
  {
    //alert("Your browser does not support XMLHTTP.")
    if (document.getElementById("tabSoaPageBg")) {
      document.getElementById("tabSoaPageBg").style.backgroundImage = "url('/img/bg/bg_gradient.jpg')";
    }
  }
}

function loadBgStateChange()
{
  var newUrl = '';

  // if xmlhttp shows "loaded"
  if (xmlhttp.readyState==4) {
    // if "OK"
    if (xmlhttp.status==200) {
      if (document.getElementById("tabSoaPageBg")) {
        newUrl = "url('" + ImageToLoad + "')";
        document.getElementById("tabSoaPageBg").style.backgroundImage = newUrl;
      }
    } else {
      if (document.getElementById("tabSoaPageBg")) {
        document.getElementById("tabSoaPageBg").style.backgroundImage = "url('/img/bg/bg_gradient.jpg')";
      }
    }
  }
}

function convertToASCII(str){
	return str.replace(/(&#\d+;)/g,function(w){return String.fromCharCode(+w.replace(/\D/g,''))});
}
function testEnglishSpanishURL(str) {
  if(str.indexOf('/espanol/') > -1) {
    var myregexp = new RegExp("espanol/");
    str = str.replace(myregexp, '')
	
	
  } else if(str.indexOf('/configurator/es') > -1) {
    var myregexp = new RegExp("/configurator/es");
    str = str.replace(myregexp, '/configurator/en')
  } else if(str.indexOf('/configurator/en') > -1) {
    var myregexp = new RegExp("/configurator/en");
    str = str.replace(myregexp, '/configurator/es')
  } else {
    // find the position of the '/' that is AFTER '//'
    var startPos = str.indexOf('//') + 2;
    if (startPos < 0) startPos = 0;
    var insertPos = str.indexOf('/', startPos)
    // insert 'espanol' at that position
    var strBefore = str.substr(0, str.indexOf('/', insertPos) + 1);
    var strAfter = str.substr(insertPos);
    var str = strBefore + 'espanol' + strAfter;
  }
  return str;
  
}

 var str = location.href;
  if(str.indexOf('?dhash=') > -1) {
    var myregexp = new RegExp("\\?dhash=");
    str = str.replace(myregexp, '#')
    location.href = str;
}





function toggleEnglishSpanishURL() {
	
   var myPageId=+$('crmEngine').getAttribute('pageid');	
	
  // Test For Edmunds
  var externalSite = location.host;

  //var str = currentURI
  var str = location.href;
 

  
  if(str.indexOf('/espanol/') > -1) {
    var myregexp = new RegExp("espanol/");
	

    str = str.replace(myregexp, '')

   // Configurator App

  } else if(str.indexOf('/configurator/app') > -1) {
    var myregexp = new RegExp("/configurator/app");
    str = str.replace(myregexp, '/configurator/es')
  } else if(str.indexOf('/configurator/es') > -1) {
    var myregexp = new RegExp("/configurator/es");
    str = str.replace(myregexp, '/configurator/en')
  } else if(str.indexOf('/configurator/en') > -1) {
    var myregexp = new RegExp("/configurator/en");
    str = str.replace(myregexp, '/configurator/es')

  // REQUEST A QUOTE App

  } else if(str.indexOf('/requestquote/en') > -1) {
    var myregexp = new RegExp("/requestquote/en");
    str = str.replace(myregexp, '/requestquote/es')
  } else if(str.indexOf('/requestquote/es') > -1) {
    var myregexp = new RegExp("/requestquote/es");
    str = str.replace(myregexp, '/requestquote/en')

  } else if(str.indexOf('/apps/techpubs') > -1) {
    var myregexp = new RegExp("/apps/techpubs");
    str = str.replace(myregexp, '/apps/techpubs')

  } else if(str.indexOf('/apps/cpo') > -1) {
    var myregexp = new RegExp("/apps/cpo");
    str = str.replace(myregexp, '/apps/espanol/cpo')

  } else if(str.indexOf('/apps/paymentestimator') > -1) {
    var myregexp = new RegExp("/apps/paymentestimator");
    str = str.replace(myregexp, '/apps/espanol/paymentestimator')

  // Apps
  } else if(str.indexOf('/apps/espanol') > -1) {
    var myregexp = new RegExp("/apps/espanol");
    str = str.replace(myregexp, '/apps')
  } else if(str.indexOf('/apps') > -1) {
    var myregexp = new RegExp("/apps");

    if((!(externalSite.indexOf('nissanusa.com') > -1))||(!(externalSite.indexOf('nissanusa.nna') > -1))){
		 /*added  'if' condition to fix SR 18457*/ 
		 if(str.indexOf('/apps/brochure') > -1){	
			str = str.replace(myregexp, '/apps/espanol')
			//location.href = str;
		}else{
		 str = 'http://www.nissanusa.com/espanol';
		}
		/*end of 'if' condition*/
    }else{
       str = str.replace(myregexp, '/apps/espanol')
    }
	
  // Compare
  } else if(str.indexOf('/compare/en') > -1) {
    var myregexp = new RegExp("/compare/en");
    str = str.replace(myregexp, '/compare/es')
  } else if(str.indexOf('/compare/es') > -1) {
    var myregexp = new RegExp("/compare/es");
    str = str.replace(myregexp, '/compare/en')


  } else {
    // find the position of the '/' that is AFTER '//'
    var startPos = str.indexOf('//') + 2;
    if (startPos < 0) startPos = 0;
    var insertPos = str.indexOf('/', startPos)

    // insert 'espanol' at that position
    var strBefore = str.substr(0, str.indexOf('/', insertPos) + 1);
    var strAfter = str.substr(insertPos);
    var str = strBefore + 'espanol' + strAfter;
  }
  //alert('old URL = ' + currentURI + '\nnew URL = ' + str);
  
  if(myPageId=="5966"){		
		location.href = "/global/error/404_es.html";
  }else if(myPageId == "23447"){
	  	location.href = "/global/error/404.html";	  
  }else{
  		location.href = str;
	}
}