//-- // ### URI ENFORCER ############################################################
var currentURI = window.location.href;
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
var securePath =    (!isStageEnv) ?	"https://secure.nissanusa.com" : "https://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.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.qa.') > -1) ? "http://www.qa.nissanusa.nna" : ((currentURI.search('www.qa1.') > -1) ? "http://www.qa1.nissanusa.com" : ((currentURI.search('www.qa2.') > -1) ? "http://www.qa2.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://www.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://www.stage.nissanusa.com/apps/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://www.stage.nissanusa.com/apps/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://www.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://www.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));
	}
}
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;
}

// 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 {
	    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 ) );
}

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 = "450px";
}

function swapIndexOut() {
	document.getElementById("dataFlashGlobalNav").style.height = "85px";
}

// 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=' + size + '&ismicrosite=1','wallpaper','height=720,width=800');
  } else {
	galleryWinObj = window.open('/wallpapers.html?vehicle=' + veh + '&index=' + index + '&size=' + size,'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))?"www.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)
