// ### DEBUGGING ###############################################################
if (!document.head) {
	document.head = document.getElementsByTagName("head")[0];
}

var cmsContext = document.location.href.indexOf("/author/") != -1 ? "/author" : "";

// ### URI ENFORCER ############################################################
var currentURI = window.location.href;
var isInfinitiSite = (	location.hostname.indexOf('www.infiniti.com') > -1 ||
						location.hostname.indexOf('secure.infiniti.com') > -1  ||
						location.hostname.indexOf('stage.infiniti.com') > -1 ) ? true : false;
var isStageEnv = (currentURI.search('www.stage') > -1) ? true : false;

//  set paths for...                 Live site                       Staging environment
var securePath =    (!isStageEnv) ?	"https://secure.infiniti.com" : "https://www.stage.infiniti.com";
var nonSecurePath =	(!isStageEnv) ?	"http://www.infiniti.com"     : "http://www.stage.infiniti.com";

//  non-secure URI         -->         -->         -->          secure URI
var secureURIs = [

	// Ownership / My Infiniti
	["http://www.infiniti.com/iapps/ownership",					"https://secure.infiniti.com/iapps/ownership"],
	["https://www.infiniti.com/iapps/ownership",				"https://secure.infiniti.com/iapps/ownership"],
	["http://secure.infiniti.com/iapps/ownership",				"https://secure.infiniti.com/iapps/ownership"],
	["http://www.stage.infiniti.com/iapps/ownership",			"https://www.stage.infiniti.com/iapps/ownership"],
	
	// PreApproval
	["http://www.infiniti.com/iapps/preapprovedinput",			"https://secure.infiniti.com/iapps/preapprovedinput"],
	["https://www.infiniti.com/iapps/preapprovedinput",			"https://secure.infiniti.com/iapps/preapprovedinput"],
	["http://secure.infiniti.com/iapps/preapprovedinput",		"https://secure.infiniti.com/iapps/preapprovedinput"],
	["http://www.stage.infiniti.com/iapps/preapprovedinput",	"https://www.stage.infiniti.com/iapps/preapprovedinput"]
];

var secureURIfound = false;
//    push user to secure URI
if (isInfinitiSite && 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-svr
else if (isInfinitiSite && 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));
	}
}
// #############################################################################

/* 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 the implementation of SimpleSwap
// by Jehiah Czebotar
// Version 1.1 - June 10, 2005
// Distributed under Creative Commons
//
// Include this script on your page
// then make image rollovers simple like:
// <img src="/images/ss_img.gif" oversrc="/images/ss_img_over.gif">
//
// http://jehiah.com/archive/simple-swap
// 
function SimpleSwap(el,which) {
	el.src=el.getAttribute(which || "origsrc");
}
//// For IMG tags
function SimpleSwapSetup() {
	var x = document.getElementsByTagName("img");
	for (var i=0;i<x.length;i++) {
		var oversrc = x[i].getAttribute("oversrc");
		if (!oversrc) continue;     
		// preload image
		// comment the next two lines to disable image pre-loading
		x[i].oversrc_img = new Image();
		x[i].oversrc_img.src=oversrc;
		// set event handlers
		x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
		x[i].onmouseout = new Function("SimpleSwap(this);");
		// save original src
		x[i].setAttribute("origsrc",x[i].src);
	}
}
//// FOR INPUT-IMAGE tags
function SimpleSwapSetupFormImages() {
	var x = document.getElementsByTagName("input");
	for (var i=0;i<x.length;i++) {
		if (x[i].type == "image") {
			var oversrc = x[i].getAttribute("oversrc");
			if (!oversrc) continue;     
			// preload image
			// comment the next two lines to disable image pre-loading
			x[i].oversrc_img = new Image();
			x[i].oversrc_img.src=oversrc;
			// set event handlers
			x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
			x[i].onmouseout = new Function("SimpleSwap(this);");
			// save original src
			x[i].setAttribute("origsrc",x[i].src);
		}
	}
}

addLoadEvent(SimpleSwapSetup);
addLoadEvent(SimpleSwapSetupFormImages);
// End SimpleSwap

// Dynamic implementation of oversrc attribute for SimpleSwap
function setOverSrc(imgObj) {
	var _imgSrcPrefix = imgObj.src.substring( 0,imgObj.src.lastIndexOf('.') );
	var _imgSrcSuffix = imgObj.src.substring( imgObj.src.lastIndexOf('.') );
	imgObj.setAttribute("oversrc",_imgSrcPrefix + '_on' + _imgSrcSuffix);
}
// End Dynamic implementation of oversrc attribute

/*
/////////////// Topnav Code //////////////////
*/
var menuTimer;
var menuTimeout;
var submenuTimeout;
var currentMenu;
var currentsubMenu;

function menuOn(menuName) {
	var theMenu;

	if (menuTimeout){ clearTimeout(menuTimeout); }	// clear the timeout

	if (currentMenu){			// hide the current menu
		theMenu = $(currentMenu);
		theMenu.style.visibility = "hidden";
	}
	currentMenu = menuName;
	theMenu = $(currentMenu);
	theMenu.style.visibility = "visible";				// display menuName
}

function submenuOn(submenuName) {
	var thesubMenu;

	if (submenuTimeout){ clearTimeout(submenuTimeout); } // clear the timeout

	if (currentsubMenu){			// hide the current menu
		thesubMenu = $(currentsubMenu);
		thesubMenu.style.visibility = "hidden";
	}
	currentsubMenu = submenuName;
	thesubMenu = $(currentsubMenu);
	theMenu = $(currentMenu);
	thesubMenu.style.visibility = "visible";
	theMenu.style.visibility = "visible";				// display menuName
}

// Hides the dropdown menus
// inputs: menuName - name of the menu DIV layer without the Div.  ie. vehicles
// outputs: none
function menuOff(menuName) {
	if (menuTimeout){ clearTimeout(menuTimeout); }	// clear the current timeout
	menuTimeout = setTimeout('$("' + menuName + '").style.visibility = "hidden"', 500);		// set the new timeout
}

function submenuOff(submenuName) {
	if (submenuTimeout){ clearTimeout(submenuTimeout); }	// clear the current timeout
	submenuTimeout = setTimeout('$("' + submenuName + '").style.visibility = "hidden"', 330);		// set the new timeout
}
// End Topnav code


// ## 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.html", url, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4)
				if (xmlhttp.status==200)	location.href = url+queryString;
				else						location.href = rootUrl;
		};
		xmlhttp.send(null);
	}
};
// Pair english, spanish urls - ONLY IF THEY DO NOT FOLLOW THE STANDARD NAMING PATTERN
//		Standard naming pattern:
//			http://www.domain.com/some/folder/a_filename.html
//			http://www.domain.com/espanol/some/folder/a_filename.html
//		Do not use the pairing function when the URLS are identical and the only difference is the the "/espanol" folder prefix.
//
//		Pairing function example:
//langMgr.pairURLs( '/some/folder/a_file.html', '/espanol/some/other/folder/another_file.html' );

// ## END Language Manager Object code


// getModelName(): gets model name from url by comparing against pre-defined list of models
function getModelName(){
	var arrModelNames = ['g_coupe','g_sedan','m','q','fx','qx'];
	var urlStr = location.href;
	
	for(i=0;i<arrModelNames.length;i++) {
		if(urlStr.indexOf('/'+arrModelNames[i]+'/')!=-1)
			return arrModelNames[i];
	}
}

function getModelNavStr() {
	var urlStr = location.href;
	var modelNavArr = [
		{submenuNum:1,featureNum:1,featureName:'performance'},
		{submenuNum:1,featureNum:2,featureName:'interior'},
		{submenuNum:1,featureNum:3,featureName:'technology'},
		{submenuNum:1,featureNum:4,featureName:'safety'},
		{submenuNum:2,featureNum:1,featureName:'exterior_photos'},
		{submenuNum:2,featureNum:2,featureName:'interior_photos'},
		{submenuNum:2,featureNum:3,featureName:'colors'},
		{submenuNum:3,featureNum:1,featureName:'packages'},
		{submenuNum:3,featureNum:2,featureName:'individual_options'},
		{submenuNum:3,featureNum:3,featureName:'dealer_accessories'},
		{submenuNum:4,featureNum:1,featureName:'standard_features'},
		{submenuNum:4,featureNum:2,featureName:'specifications'},
		{submenuNum:5,featureNum:1,featureName:'review'}
	];
	var modelNavArr_q = [
		{submenuNum:1,featureNum:1,featureName:'performance'},
		{submenuNum:1,featureNum:2,featureName:'interior'},
		{submenuNum:1,featureNum:3,featureName:'technology'},
		{submenuNum:1,featureNum:4,featureName:'safety'},
		{submenuNum:2,featureNum:1,featureName:'exterior_photos'},
		{submenuNum:2,featureNum:2,featureName:'interior_photos'},
		{submenuNum:2,featureNum:3,featureName:'colors'},
		{submenuNum:3,featureNum:1,featureName:'individual_options'},
		{submenuNum:3,featureNum:2,featureName:'dealer_accessories'},
		{submenuNum:4,featureNum:1,featureName:'standard_features'},
		{submenuNum:4,featureNum:2,featureName:'specifications'},
		{submenuNum:5,featureNum:1,featureName:'review'}
	];
	if(getModelName()=='q')
		var mArr = modelNavArr_q;
	else
		var mArr = modelNavArr;
		
	for(i=0;i<mArr.length;i++) {
		if(urlStr.indexOf(mArr[i].featureName)!=-1)
			return 'submenu='+mArr[i].submenuNum+'&feature='+mArr[i].featureNum;
	}
	
	return 'submenu=0&feature=0';
}

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);

		//TAR1035: Force key to Sentence case if referral key
		//if (strName.toLowerCase() == strReferralSite.toLowerCase() ||
		//	strName.toLowerCase() == strReferralArea.toLowerCase() ||
		//	strName.toLowerCase() == strReferralCreative.toLowerCase()) {
		//	strName = strName.substring(0,1).toUpperCase() + strName.substring(1).toLowerCase();
		//	}			
			
        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['fx'] =      'MSRP excludes $650 destination charge ($750 for QX56), tax, title, license, and options. Retailer sets actual price. Price shown is for FX35 RWD.';
	pricingdetailsArr['g_coupe'] = 'MSRP excludes $650 destination charge ($750 for QX56), tax, title, license, and options. Retailer sets actual price. Price shown is for G35 Coupe with automatic transmission.';
	pricingdetailsArr['g_sedan'] = 'MSRP excludes $650 destination charge ($750 for QX56), tax, title, license, and options. Retailer sets actual price. Price shown is for G35 Sedan 6MT.';
	pricingdetailsArr['m'] =       '* MSRP for 2007 M excludes $650 destination charge, tax, title, license, and options. Retailer sets actual price. Price shown is for M35.';
	pricingdetailsArr['q'] =       'MSRP excludes $650 destination charge ($750 for QX56), tax, title, license, and options. Retailer sets actual price. Price shown is for Q45 Sport.';
	pricingdetailsArr['qx'] =      'MSRP excludes $650 destination charge ($750 for QX56), tax, title, license, and options. Retailer sets actual price. Price shown is for QX56 2WD.';
	
	var pricingdetailsModelSelectorArr = new Array();
	pricingdetailsModelSelectorArr['g_coupe'] = "All prices are Manufacturer's Suggested Retail Price (MSRP). MSRP excludes $650 ($750 for QX56) destination and handling charges, tax, title, license, and options. Retailer sets actual price. Prices shown are for G35 Coupe and G35 Coupe 6MT.";
	pricingdetailsModelSelectorArr['g_sedan'] = "All prices are Manufacturer's Suggested Retail Price (MSRP). MSRP excludes $650 ($750 for QX56) destination and handling charges, tax, title, license, and options. Retailer sets actual price. Prices shown are for G35, G35x AWD, and G35 6MT.";
	pricingdetailsModelSelectorArr['m'] =       "All prices are Manufacturer's Suggested Retail Price (MSRP). MSRP for 2007 M excludes $650 ($750 for QX56) destination and handling charges, tax, title, license, and options. Retailer sets actual price. Prices shown are for M35, M35x AWD, M35 Sport, M45, and M45 Sport.";
	pricingdetailsModelSelectorArr['fx'] =      "All prices are Manufacturer's Suggested Retail Price (MSRP). MSRP excludes $650 ($750 for QX56) destination and handling charges, tax, title, license, and options. Retailer sets actual price. Prices shown are for FX35, FX35 AWD, and FX45 AWD.";
	pricingdetailsModelSelectorArr['qx'] =      "All prices are Manufacturer's Suggested Retail Price (MSRP). MSRP excludes $650 ($750 for QX56) destination and handling charges, tax, title, license, and options. Retailer sets actual price. Prices shown are for QX56 2WD and QX56 4WD.";	
	pricingdetailsModelSelectorArr['q'] =       "";
	
	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];
	}
}

// Flash parameter detection and passing for MICROSITES
function checkSrcParam() {
		var src, html, qPos;
		
		src = getQueryParam('src');
		if(src=='') return;
		
		html = getHtml('ufoMicroMovie');
		if(html) {
			qPos = html.indexOf('?');
			if(qPos > -1) //existing querystring?
				html += '&';
			else
				html += '?';
		
			html = html + 'src=' + src;		
			setHtml('ufoMicroMovie', html);
		}
}

// 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 _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));
}

// Determines the page name for use in the promo xml file
function getThisPage () {
	var pageName;
	var urlStr = location.pathname;
	var fileNameStartIndex = urlStr.lastIndexOf('index.html')+1;
	var fileNameExtIndex = urlStr.lastIndexOf('.');
	
	if (fileNameExtIndex > -1) { // URL contains a proper file name
		pageName = urlStr.substring(fileNameStartIndex,fileNameExtIndex);
		if (pageName == 'index' && urlStr.indexOf('colors/index.html') > -1) //if the filename is index, figure out if its vlp or colors index
			pageName = 'colors';
	} else { // no file name in URL, we are loading the default page (index.html)
		if (urlStr.indexOf('colors/index.html') > -1) //figure out if its vlp or colors index
			pageName = 'colors';
		else
			pageName = 'index';
	}
	
	return pageName;
}

// Launches microsite window, or points browser to launch page if blocked
function launchMicrosite (url, launchUrl, winName, winParams) {
	try {
		var winObj = window.open(url, winName, winParams);
		winObj.focus();
	} catch (err) {
		location.href=launchUrl;
	}
}
