
//Remember last opened drawer
var pageLoadTabSelect = false;;
var lastOpenDrawer = null;
var isSafari = (navigator.userAgent.indexOf("Safari") != -1)?true:false;

function getItem(id) {
	return document.getElementById(id);
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function getPos(element, which) {
/*
	@which --> "Left" or "Top"
*/
	pos = 0
	while (element != null) {
	pos += element["offset" + which]
	element = element.offsetParent;
	}
	return pos;
}

function getLang()
{
	// Default to en-us
	var qs = new String(),		 
		loc = new Array(),
		lang = new String();
		defaultLang = "en-us";
	
	qs = document.location.search;
	loc = qs.match(/loc=(.{5})/g);
	lang = (loc != null) ? RegExp.$1 : defaultLang;
	if (!RegExp(".{2}-.{2}").test(lang)) lang = defaultLang;
	
	return lang;
}


//This method removes all other prototyped methods 
//from the Array. Good to use with (i in array). *** Not working!
Array.prototype.clean = function() {
	for (var i in this)
		if (typeof this[i]=="function")
			delete this[i];
	return this;
}

//Array.addItems("Item1","Item2","ItemX..");
//Return the array with new items added to end.
Array.prototype.addItems = function() {
	for (var i=0; i<arguments.length; i++)
		this[++this.length-1] = arguments[i];
	return this;
}

//new Boolean(Array.contains(itemToLookFor));
//Return true if an array contains an item.
Array.prototype.contains = function(item) {
	for (var i=0; i<this.length; i++)
		if (this[i]==item) return true;
	return false;
}

//var UniqueArray = Array.getUnique();
//Removes duplicate items from an array.
Array.prototype.getUnique = function() {
	var temp = new Array();
	for (var i=0; i<this.length; i++)
		if (!temp.contains(this[i])) 
			temp[++temp.length-1] = this[i];
	return temp;
}

//Prototype function to return an objects position in an array
Array.prototype.indexOf = function (item) {
	for (var i=0; i<this.length; i++) {
		if (this[i] == item) {
		 return i;
		}
	}
	return -1;
}

// Function was not working using IE7
//
//Prototype function to remove an item from an array
//Array.prototype.remove = function (item) {
//	try{
//	
//		if (item != null) {
//			itemPos = this.indexOf(item);
//			if (itemPos != -1) {
//				first = this.slice(0, itemPos);
//				second = this.slice(itemPos+1);
//				return first.concat(second);
//			} else {
//				return this;
//			}
//		} else {
//			return null;
//		}
//	} catch (e){
//	}
//}

//Remove items from an Array
//itemsToRemove: single item or array
Array.prototype.removeItems = function(itemsToRemove) {

    if (!/Array/.test(itemsToRemove.constructor)) {
        itemsToRemove = [ itemsToRemove ];
    }

    var j;
    for (var i = 0; i < itemsToRemove.length; i++) {
        j = 0;
        while (j < this.length) {
            if (this[j] == itemsToRemove[i]) {
                this.splice(j, 1);
            } else {
                j++;
            }
        }
    }
}


/*******************************************************************************
* Detects if required version of Flash Player is installed                     *
* int reqVersion	- Required version number                                    *
* Returns a true if required version or greater is installed, otherwise false. *
*******************************************************************************/
function flashDetect(reqVersion){
	if ((new String(document.location)).indexOf("?flash=false") != -1) {
		return false;
	}

	var actualVersion = 0;
	var gotIt = got6 = got7 = got8 = got9 = got10 = false;
	if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.toLowerCase().indexOf("win") != -1)) {
		vbCode = '<scr'+'ipt language="VBScript"\> \n';
		vbCode += 'on error resume next \n';
		for(x=6; x<=10; x++){
			vbCode += 'got'+x+' = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.'+x+'"))) \n';
		}
		vbCode += '</scr'+'ipt\> \n';
		document.write(vbCode);
		for (var i = 6; i <= 10; i++) {
			if (eval("got" + i) == true) actualVersion = i;
		}
	} else {
		var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
		if (plugin) {
			actualVersion = parseInt(plugin.description.substring(plugin.description.indexOf(".")-1));
		}
	}
	if(actualVersion >= reqVersion) gotIt = true;
	return gotIt;
}

/**********************************************************************************
* Function to preload rollover images                                             *
* Pass in an unlimited number of comma delimited strings for fully pathed images. *
**********************************************************************************/
function preloadImages() {
	var doc = document;
	if (doc.images){
		if (!doc.preLoaders) doc.preLoaders=new Array();
		var i, j = doc.preLoaders.length, a=preloadImages.arguments;
		for (i = 0; i < a.length; i++) {
			doc.preLoaders[j] = new Image;
			doc.preLoaders[j++].src = a[i];
		}
	}
}

/*****************************************
* Function to find an object in the DOM  *
* string name - id of the object to find *
* object doc  - optional document object *
*****************************************/
/*
function findObj(name, doc) {
	var par,i,x;
	if(!doc) doc = document;
	if( (par = name.indexOf("?")) > 0 && parent.frames.length) {
		doc = parent.frames[name.substring(par+1)].document;
		name = name.substring(0,par);
	}
	if( !(x = doc[name]) && doc.all) x = doc.all[name];
	for ( i = 0; !x && i < doc.forms.length; i++) x = doc.forms[i][name];
	for ( i = 0; !x && doc.layers && i < doc.layers.length; i++) x = findObj(name,doc.layers[i].document);
	if ( !x && doc.getElementById) x = doc.getElementById(name);
	return x;
}
*/
/****************************************************************************************
* Function to do rollovers                                                              *
* Pass in an unlimited number of comma delimited strings for rollover pairs.            *
* Pairs should consist of a comma delimited set of strings: name and fully pathed image *
****************************************************************************************/
function swapImage() {
	var i,x,args = swapImage.arguments;
	for( i = 0; i < (args.length-1); i += 2) {
		if ( (x = findObj(args[i])) !=null) {
			x.src = args[i+1];}
	}
}

/*****************************************************************************
* Open/Close Drawer behavior                                                 *
* object parentDiv - reference to the outer most drawer container            *
* boolen closeLast - do you wish to close the last opened drawer             *
* string openHdrClassName - name of class to apply to header div on open		 *
* string closeHdrClassName - name of class to apply to header div	on close	 *
*****************************************************************************/
function openClose(parentDiv, closeLast, openHdrClassName, closeHdrClassName) {
	var contentArea = null;
	var leftContent = null;
	if (closeLast && lastOpenDrawer != null) {
		openClose(lastOpenDrawer, 0, closeHdrClassName, "");
	}
	
	if (navigator.appName.search("Microsoft") != -1) {
		drawerHeader = parentDiv.childNodes[0];
		scrollPather = parentDiv.childNodes[1];
		dataContainer = parentDiv.childNodes[2];
	} else {
		//Mozilla 5.0 reads tabs as a text object.
		drawerHeader = scrollPather = dataContainer = null;
		for (i = 0; i < parentDiv.childNodes.length; i++) {
			if ( parentDiv.childNodes[i].nodeName == "DIV" ) {
				if (drawerHeader == null) {
					drawerHeader = parentDiv.childNodes[i];
				} else if (scrollPather == null){
					scrollPather = parentDiv.childNodes[i];
				} else if (dataContainer == null) {
					dataContainer = parentDiv.childNodes[i];
				}
			}
		}
	}

	heightValue = drawerHeader.offsetHeight + scrollPather.offsetHeight + "px";
	if (parentDiv.style.height != heightValue) {
		//Open drawer
		if (openHdrClassName != "") {
			drawerHeader.className = openHdrClassName;
		}
		parentDiv.style.height = heightValue;
		parentDiv.style.borderBottom = "1px solid #666666";
		scrollPather.style.visibility = "visible";
		dataContainer.style.visibility = "visible";
		if (navigator.appName.search("Microsoft") != -1) {
			scroller = scrollPather.childNodes[0];
			dataEntry = dataContainer.childNodes[0];
		} else {
			scroller = scrollPather.childNodes[1];
			dataEntry = dataContainer.childNodes[1];
		}

		lastOpenDrawer = parentDiv;
		//Initialize scrollbar
		initScrollbar(dataEntry.id, dataContainer.id, scrollPather.id, scroller.id);
	} else {
		//Close Drawer
		if (openHdrClassName != "") {
			drawerHeader.className = openHdrClassName;
		}
		parentDiv.style.height = drawerHeader.offsetHeight + "px";
		scrollPather.style.visibility = "hidden";
		dataContainer.style.visibility = "hidden";
	}

}

/* Drag code for scrollbars */
var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

function showProps(elem) {
for(prop in elem) {
document.write("<b>" + prop +  ":</b> " + elem[prop] + "<br>");
}
}

/**********************************************************************
* Initialize scrollbars                                               *
* string contentId   - Id of the div containing the scrolling content *
* string containerId - Id of the div containing the content div       *
* string pathId      - Id of the div containing the scroller          *
* string scrollerId  - Id of the div being used as the scroller       *
**********************************************************************/
function initScrollbar(contentId, containerId, pathId, scrollerId) {
	var scrollContent = document.getElementById(contentId);
	var scrollContainer = document.getElementById(containerId);
	var scrollPath = document.getElementById(pathId);
	var scrollBar = document.getElementById(scrollerId);

	   //collect the variable
    var docH = scrollContent.offsetHeight;
    var contH = scrollContainer.offsetHeight;
    var scrollAreaH = scrollPath.offsetHeight;
    /*
	var docH = $(scrollContent).innerHeight();
	var contH = $(scrollContainer).innerHeight();
	var scrollAreaH = $(scrollPath).innerHeight();
	*/
    //calculate height of scroller and resize the scroller div
    //(however, we make sure that it isn't to small for long pages)
    var scrollH = (contH * scrollAreaH) / docH;
    //if(scroller.scrollH < 15) scroller.scrollH = 15;

	//Hide scrollbar if scrolling isn't necessary
	if ((scrollH >= scrollAreaH) || (docH == 0)) {
		scrollBar.style.height = "0px";
		scrollPath.style.visibility = "hidden";
		scrollContainer.style.width = (scrollContainer.parentNode.offsetWidth - (scrollContainer.offsetLeft * 2)) + "px";
	} else {
		scrollBar.style.height = Math.round(scrollH) + "px";
		scrollPath.style.visibility = "visible";
		scrollContainer.style.width = (scrollContainer.parentNode.offsetWidth - (scrollContainer.offsetLeft * 3) - scrollPath.offsetWidth) + "px";

	 	//what is the effective scroll distance once the scoller's height has been taken into account
		var scrollDist = Math.round(scrollAreaH-scrollH);

		//make the scroller div draggable
		 Drag.init(scrollBar,null,0,0,0,scrollDist);
			var scrollY = parseInt(scrollBar.style.top);
			var docY = 0 - (scrollY * (docH - contH) / scrollDist);
			scrollContent.style.top = docY -2 + "px";
		//add ondrag function
		scrollBar.onDrag = function (x,y) {
			var scrollY = parseInt(scrollBar.style.top);
			var docY = 0 - (scrollY * (docH - contH) / scrollDist);

			scrollContent.style.top = docY -2 + "px";
		}
	}
}

//Remove items from an Array
//itemsToRemove: single item or array

//Create layer dynamically
function makeLayer (parentLayer, layerName, className) {
	if(!document.getElementById(layerName)){
		newLayer = document.createElement('DIV');
		newLayer.id = layerName;
		if (className != null) {
			newLayer.className = className;
		}
		try {
			document.getElementById(parentLayer).appendChild(newLayer); // string
		} catch(e) {
			try {
				parentLayer.appendChild(newLayer); // by object ref
			} catch (e) {
			}
		}
	}
}

//Remove layer
function killLayer(parentLayer, layerName){
	try {
		var theLayer = document.getElementById(layerName);
		document.getElementById(parentLayer).removeChild(theLayer);
	} catch(e) {
			try {
				theLayer.parentNode.removeChild(theLayer); //by object ref
			} catch (e) {

			}
	}
}

//Get element positions
function getposOffset(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		//alert(parentEl.id);
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

//Slide behaviors
var slideAgain = new Array();

function slideUp(layerName, parentName, stepValue, maxHeight, optionalFunction){
	clearTimeout(slideAgain[layerName]);
	var theLayer = document.getElementById(layerName);
	var parentLayer = document.getElementById(parentName);
	theLayer.style.visibility = "visible";
	var parentLayer = document.getElementById(parentName);
	if (theLayer.offsetHeight < maxHeight){
		if (maxHeight - theLayer.offsetHeight < stepValue) {
			stepValue = maxHeight - theLayer.offsetHeight;
		}
		yClip = theLayer.offsetHeight + stepValue;
		theLayer.style.top = ((parentLayer.offsetTop + parentLayer.offsetHeight) - theLayer.offsetHeight - stepValue) + "px";
		//theLayer.style.height = yClip;
		$('#' + layerName).css('height', yClip);
		//$('#' + layerName).css('top', ((parentLayer.offsetTop + parentLayer.offsetHeight) - theLayer.offsetHeight - stepValue) + "px");
		
		if (yClip > 0 && optionalFunction != "") {
			//Evaluate optional function call after first sizing - Some functions like initScrollbar fail if the layer has 0 height
			eval(optionalFunction);
			optionalFunction = ""; //Clear function
		}
		if (yClip != maxHeight) {  //Call again if we haven't reached max height
			slideAgain[layerName] = setTimeout("slideUp('"+layerName+"','"+parentName+"', "+stepValue+", "+maxHeight+", '"+optionalFunction+"');", 20);
		}
		else {
			/* omniture */
			if(layerName == "specialOffers") {
				//Omniture now captured in fireOmnitureSpecialOffersSelect function in bp.js
				//bubbleSequentialEvent(" var variables = [ {name: 'events', value: 'event3'} ]");
			}
			else if(layerName == "financeCalc") {
				//Omniture now captured in fireOmnitureCalculatorSelect function in bp.js.
				//bubbleSequentialEvent(" var variables = [ {name: 'events', value: 'event2'} ]");
			}
		}

	}


}

function slideDown(layerName, parentName, stepValue, maxHeight){
	clearTimeout(slideAgain[layerName]);
	var theLayer = document.getElementById(layerName);
	var parentLayer = document.getElementById(parentName);
	if (theLayer.offsetHeight > 0) {
		yClip = theLayer.offsetHeight - stepValue;
		if (yClip < 0) {
			yClip = 1; //IE can't handle 0 height
			theLayer.style.visibility = "hidden";
			return;
		}
		theLayer.style.top = parseInt(theLayer.style.top) + stepValue + "px";
		//theLayer.style.height = yClip;
		$('#' + layerName).css('height', yClip);
		//$('#' + layerName).css('top', parseInt(theLayer.style.top) + stepValue + "px");

		slideAgain[layerName] = setTimeout("slideDown('"+layerName+"','"+parentName+"', "+stepValue+", "+maxHeight+");", 20);
	}
}

var slideDownDelay = new Array();
function delaySlideDown(layerName, parentName, stepValue, maxHeight, delayTime) {
	if (typeof(delayTime) == "undefined") { delayTime = 20; }
	slideDownDelay[layerName] = setTimeout("slideDown('"+layerName+"','"+parentName+"', "+stepValue+", "+maxHeight+");", delayTime);
}

//Format money
function moneyFormat(value) {
	//FIXME - Get repository items for money
	value = value.toString();

	//Check for dropped 0 in cents
	if (value.indexOf(".") > value.length - 3) {
		value += "0";
	}

	if (value.length > 3) {
		startPos = value.length % 3;
		formatedValue = value.substr(0,startPos);
		for ( var i = startPos ; i< value.length; i += 3) {
			if (formatedValue == "") {
				formatedValue = value.substr(i, 3);
			} else {
				formatedValue += "," + value.substr(i, 3);
			}
		}
		formatedValue = formatedValue.replace(/,\./i, ".");
		return formatedValue;
	} else {
		return value;
	}
}

var lastTop = "";
//Swap Z index of content and nav divs
function swapZ(dTop, dBottom) {
	if (document.getElementById(dTop) && document.getElementById(dBottom)) {
			document.getElementById(dTop).style.zIndex = 1000;
			document.getElementById(dBottom).style.zIndex = 1;
	}

	if (dTop != lastTop) {
		try {
			//showHideFields();
		} catch (e) {}
	}

	lastTop = dTop;
}

// used in common offers
// definitely need to redo this
function getModelInformation (model_num) {
	var offerCarImg = 'Lancer';
	var modelName = 'Lancer';
	
	switch(model_num) {
	case "100022":case "100014":case "100031":case "100040":case "100050":
			offerCarImg = 'Lancer';
			modelName = 'Lancer';
			break;
		case "100028":case "100038":
			offerCarImg = 'Endeavor';
			modelName = 'Endeavor';
			break;
		case "100020":case "100018":case "100034":case "100039":case "100049":
			offerCarImg = 'Galant';
			modelName = 'Galant';
			break;
		case "100025":case "100015":case "100029":case "100036":case "100046":
			offerCarImg = 'Eclipse';
			modelName = 'Eclipse';
			break;
		case "100024":case "100016":case "100030":case "100037":case "100047":
			offerCarImg = 'EclipseSpyder';
			modelName = 'Eclipse Spyder';
			break;
		case "100033":case "100041":case "100051":
			offerCarImg = 'LancerSportback';
			modelName = 'Lancer Sportback';
			break;
		case "100026":case "100019":case "100035":case "100042": case "100048":
			offerCarImg = 'Outlander';
			modelName = 'Outlander';
			break;
		case "100044":case "100053":
			offerCarImg = 'OutlanderSport';
			modelName = 'Outlander Sport';
			break;
		case "100027":case "100023":
			offerCarImg = 'Raider';
			modelName = 'Raider';
			break;
		case "100021":case "100032":case "100043":case "100052":
			offerCarImg = 'LancerEVO';
			modelName = 'Lancer Evolution';
			break;
		case "100017":
			offerCarImg = 'Endeavor';
			modelName = 'Endeavor';
			break;
		default:
	}
	
	return "offerCarImg='" + offerCarImg + "';modelName='" + modelName +"'";
}


/* prepend CDN host depending on deployment */
function getCdnPath(path) {
	switch(useCachefly) {
	case "stage":
		return "http://mmnastage.cachefly.net" + path;
		break;
	case "production":
		return "http://mmna.cachefly.net" + path;
		break;
	case "none":
		return domainPath + path;
		break;
	default:
		return path;
		break;
	}
}
/* draw the flash navigation object */ 
function drawFlash(divId, objectId, width, height, swfPath, xmlPath, isHome) {
	//alert("drawing flash:  debug "+divId);
	var swfUrl = getCdnPath(swfPath);
	var flashvars = {};
			//flashvars.xmlpath = getCdnPath(xmlPath + "."+langCode+".xml");
			flashvars.xmlPath = getCdnPath(xmlPath + ".xml");
			flashvars.domainPath = domainPath;
			flashvars.cacheflyPath = getCdnPath("");
			flashvars.zpCode = sessionZipCode;
	if (isHome){
		flashvars.isHome = "true";
	}			
			var params = {};
			//params.play = "true";
			//params.loop = "false";
			params.menu = "false";
			//params.quality = "best";
			params.scale = "noscale";
			//params.salign = "tl";
			params.wmode = "transparent";
			params.bgcolor = "#FFFFFF";
			//params.devicefont = "true";
			//params.seamlesstabbing = "true";
			//params.swliveconnect = "true";
			//params.allowfullscreen = "false";
			params.allowscriptaccess = "always";
			params.allownetworking = "all";
			//params.base = "/MMNA";
			var attributes = {};
			attributes.id = objectId;
			//attributes.align = "top";
			swfobject.embedSWF(swfUrl, divId, width, height, "9.0.0", "/MMNA/swf/expressInstall.swf", flashvars, params, attributes, flashCallback);

}

function flashCallback (e) {
	// displays the flash error message when player fails to load
	if (e.success == false) {
		$('#' + e.id).show();
	}
}
function drawNavFlash(isHome) {
	//drawFlash("flashnav", "globalNav", "1000", "500", "/MMNA/swf/mitsubishi_mainnav.swf", "/MMNA/xml/mainnav", isHome);
}
function drawHomeFlash() {
	// doesn't need currentPage, cachflypath, version 6 OK? 495
	drawFlash("home_content", "homeFlash", "1000", "500", "/MMNA/swf/mitsubishi_home.swf", "/MMNA/home/xml/mitsubishi_home", false);
	$("homeFlash").css("z-index", "-1");
}
/* bridge for refactored code */
function drawNav(isHome) {
	drawNavFlash(isHome);
}


//Recenter the page on window resize
function reCenter() {
	page = document.getElementById("pageContent");

	leftVal = (document.body.clientWidth - parseInt(page.style.width)) / 2;
	leftVal < 0?leftVal="0px":leftVal+="px";
	page.style.left =  leftVal;
	page.style.visibility = "visible";

	if(navigator.userAgent.indexOf("MSIE") != -1) {
		getItem("nav").style.left = "0px";
		getItem("bodyDiv").style.left = "0px";
	}
}

//Format a date to MM/DD/YY
function formatDate (dateObject) {
	var dateString = (dateObject.getMonth()+1) + "/" + dateObject.getDate() + "/" + dateObject.getFullYear().toString().substr(2,2);
	return dateString;
}

//Definition of a Dealer object
function dealerItem ( dealerId, dealerName, dealerAddress, dealerCity, dealerState, dealerZip, dealerPhone, dealerUrl, dealerMiles, dealerEcommerce, dealerDiamond, iDealer, latitude, longitude  ) {
	this.id = dealerId;
	this.name = dealerName;
	this.address = dealerAddress;
	this.city = dealerCity;
	this.state = dealerState;
	this.zip = dealerZip;
	this.phone = dealerPhone;
	this.url = dealerUrl;
	this.miles = dealerMiles;
	this.ecommerce = dealerEcommerce;
	this.diamond = dealerDiamond;
	this.iDealer = iDealer;
	this.latitude = latitude;
	this.longitude = longitude;
}


//Function for switching tabs in tabbed page interface
//function may be overloaded to provide a reference
//to the container to resize
var lastTabX = new Array();

function selectTab (tabId, currentTabId) {
	//alert("here");
	try {
		getItem(tabId).style.left = lastTabX[tabId];
	} catch (e) {}

	getItem(tabId).style.visibility = "visible";
	try {
		getItem(currentTabId).style.visibility = "hidden";
		lastTabX[currentTabId] = getItem(currentTabId).style.left;
		getItem(currentTabId).style.left = -2000;
	} catch (e) {}
	//alert(getItem(tabId).offsetHeight);
	if(!isSafari) {
		curUrl = document.location.toString();
		curUrl = curUrl.substr(0, curUrl.indexOf('#')) + "#" + tabId + "Tab";

		document.location = curUrl;
	}
		parentDiv = getItem(tabId).parentNode;
		if( parentDiv.id != "vehContentRight" && navigator.userAgent.indexOf("Safari") == -1) {
			parentDiv.style.height = getItem(tabId).offsetHeight + "px";
		}
		//Reset bg size to fix FF bug
			getItem('individual_vehicle_content').style.height = ((getItem(tabId).offsetHeight + 30) > 490)?(getItem(tabId).offsetHeight + 30)+"px":490+ "px";

		if(navigator.userAgent.indexOf("MSIE 7") != -1) {
			try {
				getItem("vehContentRight").style.marginLeft = "240px";
			} catch(e) {}
		}


	if(pageLoadTabSelect) {
		//don't want to fire the omniture event the first time in/through:
		pageLoadTabSelect = false;
	}
	else {
		if(arguments.length != 3) {
			//fire off omniture event:
			if(pcode) {
				//have to clear s.pageName temporarily; will be reset
				s.pageName = '';
				bubbleSequentialEvent(" var variables = [ {name: 'pageName', value: '" + (pcode + " - " + tabId + "Tab") + "'} ]");
			}
		}
	}

}

function resizeAncestor(sizeBenchmark, ancestorsBack) {
	/*
		@sizeBenchmark --> the id of the element which the ancestor should be the same size as
		@ancestorsBack -- > the integer representing the number of "generations" to move outwards;
			for example: 1 = parent, 2 = grand-parent, 3 = great-grand-parent
	*/

	//get a reference to the starting point:
		var ancestorRef = getItem(sizeBenchmark);

		//define extra padding - in pixels - to throw on the bottom of the ancestor:
		var xPadding = (arguments.length == 3) ? arguments[2] : 130;

		for(var i = 0; i < ancestorsBack; i++) {
			ancestorRef = ancestorRef.parentNode;
		}

		//alert("Resizing " + ancestorRef.id);
		ancestorRef.style.height = getItem(sizeBenchmark).offsetHeight + xPadding + "px";
}

//Function for setting tab on entery from bookmark
function checkTabUrl(defaultTab) {
	pageLoadTabSelect = true;
	curUrl = document.location.toString();
	if (curUrl.indexOf('#') != -1) {
		tabUrl = curUrl.substr(curUrl.indexOf('#') + 1, (curUrl.length - curUrl.indexOf('#') - 4));
		selectTab(tabUrl);
	} else {
		if (defaultTab != null) {
			setTimeout('selectTab("'+defaultTab+'");', 100);
		}
	}

}

//function which adds to the queue of functions to execute upon window.onload
function addToOnload(newFunc) {
	var currentOnload = window.onload;
	window.onload = function() {
		if(currentOnload != null && typeof currentOnload == "function") {
			currentOnload();
		}
		newFunc();
	};
}


function fancyPop(strURL, width, height)
{
    launchCenter(strURL, '_blank', width, height, 'scrollbars=no,toolbar=no,location=no,menubar=no,resizable=no')
}

function launchCenter(url, name, width, height, winstyle)
{
    var str = "height=" + height + ",innerHeight=" + height;
    str += ",width=" + width + ",innerWidth=" + width;  if (window.screen) {
    var ah = screen.availHeight - 30;    var aw = screen.availWidth - 10;
    var xc = (aw - width) / 2;    var yc = (ah - height) / 2;
    str += ",left=" + xc + ",screenX=" + xc;
    str += ",top=" + yc + ",screenY=" + yc;  }
    return window.open(url, name, str + "," + winstyle);
}




//function jims pop up for "bluetooth" / "hands-free" mini frame set
function WinPop(file,name,w,h,m,s,t,r,l){
/*
		LPos = (screen.width) ? (screen.width-w)/2 : 0;
		TPos = (screen.height) ? (screen.height-h)/2 : 0;
		options = "width=" + w + ",height=" + h + ",top=" +TPos + " ,left=" + LPos + ",menubar=" + m + ",scrollbars=" + s + ",toolbar=" + t + ",resizable=" + r + ",location=" + l;
		PopWallpaper = window.open(file,name,options);
		PopWallpaper.focus();
*/
	var allcookies = document.cookie; // gets cookie string
	var pos = allcookies.indexOf("kiosk="); //finds location of cookie
	var sCookieStart  = pos + 6;
	var sCookieEnd = allcookies.indexOf(";", sCookieStart);
		if (sCookieEnd == -1){
			sCookieEnd = allcookies.length;
		}
	var value = allcookies.substring(sCookieStart,sCookieEnd);
	var bValue = unescape(value);
	var bCookievalue = (bValue == "true")? true:false;

	// for CIC launch dialog windows instead of popups
	if (bCookievalue){
		//var  sHeight = h + 50;
		var sModalWindow;
		var sHeight = h + 15;
		sModalWindow = window.showModalDialog(file,self, 'dialogHeight:' + sHeight + 'px; dialogWidth:' + w + 'px; center:yes; edge:sunken; help:no; resizable:' + r +'; scroll:' + s +'; status:no; unadorned:no');
		//location.href = sModalWindow;
	} else {
		LPos = (screen.width) ? (screen.width-w)/2 : 0;
		TPos = (screen.height) ? (screen.height-h)/2 : 0;
		options = "width=" + w + ",height=" + h + ",top=" +TPos + " ,left=" + LPos + ",menubar=" + m + ",scrollbars=" + s + ",toolbar=" + t + ",resizable=" + r + ",location=" + l;

		PopWallpaper = window.open(file,name,options);
		if(PopWallpaper)
		{
		    PopWallpaper.focus();
		}
	}
}

function switchLang(lang) {
	if (lang == null || lang == "") {
		lang ="en";
	}

	var curURL = document.location;
	var curHash = curURL.hash;
	var curSearch = curURL.search;
	var curPath = curURL.pathname;
	var curHost = curURL.host;

	if (curSearch == "" || curSearch == null) {
		curSearch = "?loc=" + lang + "-us";
	} else {
		if (curSearch.indexOf("loc=") != -1) {
			curSearch = curSearch.replace(/loc=en-us/i,"loc=" + lang + "-us");
			curSearch = curSearch.replace(/loc=es-us/i,"loc=" + lang + "-us");
		} else {
			curSearch += "&loc=" + lang + "-us";
		}
	}

	document.location = "http://" + curHost + curPath + curSearch  + curHash;
}

// added Jan 10, 2007
function popupWindow (_url,_w,_h) {    TPos = (screen.height) ? (screen.height-_h)/2 : 0;    LPos = (screen.width) ? (screen.width-_w)/2 : 0;    popup = window.open ("","popupMitsu","width=" + _w + ",height=" + _h + ",top=" + TPos + ",left=" + LPos + ",resize=no,scrollbars=no");    popup.location.href = _url;    return;popupWindow }

/*
	new addition for <landingButton> button
	for evo btn
*/
function updateLocation(str)
{
	window.location = str;
}

// Homepage tile tweak for staying within site & capturing site metrics in XML
function goToURL(url, targ){

	targ = typeof(targ) != 'undefined' ? targ : "_self";

	window.open (url,targ);

	//window.location = url;
}

function setTileProp(url)
{
	s.prop10 = url;
	//alert(url);
}

function NewWindow(mypage,myname,w,h,scroll,pos){
	// DO NOT REMOVE
	var win=null;
	if(pos=="random"){
		LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
	}
	if(pos=="center"){
		LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;
	} else if((pos!="center" && pos!="random") || pos==null){
		LeftPosition=0;TopPosition=20
	}
	settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
	win=window.open(mypage,myname,settings);
}

function getArgs() {

	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split("&");

	for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}

	return args;

}

function getURLParam(strParamName, upperCaseOverride){
	  var upperCaseOverride = (upperCaseOverride) ? true : false;
	  var strReturn = "";
	  var strHref = window.location.href;
	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = (upperCaseOverride) ? strHref.substr(strHref.indexOf("?")) : strHref.substr(strHref.indexOf("?")).toLowerCase();
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      var compareTo = (upperCaseOverride) ? strParamName : strParamName.toLowerCase();
	      if (aQueryString[iParam].indexOf(compareTo + "=") > -1 ){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        break;
	      }
	    }
	  }
	  return unescape(strReturn);
	} 

function insertSwfHeader(title) {	
	
	// check to see if page uses the main body div 'full' or 'left' and 'right'
	// ALL pages SHOULD have either 'full' or 'left' div tags see UI documentation
	// /Volumes/TRAFFIC/MITSUBISHI_Interactive/Website/Documentation/UIstructure03.html
	if (document.getElementById('full')!=null) {
		mainDiv = document.getElementById('full');
		width   = "740";
	} else if (document.getElementById('left')!=null){
		mainDiv = document.getElementById('left');
		width   = "540";
	} else if (document.getElementById('vehicle_main_content')!=null){
		mainDiv = document.getElementById('vehicle_main_content');
		width   = "540";
	} else if (document.getElementById('body').childNodes[0]!=null){
		// default to first child node of body which we know is present in all content pages
		mainDiv = document.getElementById('bodyDiv').childNodes[0];
		width   = "540";
	}else{
		alert ('exception');
		width ="540";
	}

	
	// create the h1 tag and swf object for the h1 title
	var markup = "";
	markup += 	'<object type="application/x-shockwave-flash" data="/MMNA/swf/new_header.swf" width='+width+' height="40">';
	markup +=		'<param name="allowScriptAccess" value="sameDomain" />';
	markup +=		'<param name="allowFullScreen" value="false" />';
	markup +=		'<param name="movie" value="/MMNA/swf/new_header.swf" />';
	markup +=		'<param name="quality" value="high" />';
	markup +=		'<param name="wmode" value="transparent" />';
	markup +=		'<param name="scale" value="noscale" />';
	markup +=		'<param name="salign" value="tl" />';
	markup +=		'<param name="flashvars" value="headline='+String(title).replace(/&/, "\%26").replace(/\%\s{1}/,"\%25 ")+'" />';
	markup +=		title;
	markup +=	'</object>';
    
	if (arguments.length == 2){
		// new style
		// replace existing default h1 tag with the swf object
		var H1NodeList = $('#' + arguments[1] + ' h1').eq(0);
	    if (H1NodeList.length) {	    	
		    $(H1NodeList).html(markup);
	    }
	    
	} else {
		// fall back to old architecture
		// replace existing default h1 tag with the swf object
		H1NodeList =  document.getElementsByTagName('h1');
		if (H1NodeList[0]) {
			H1NodeList[0].innerHTML = markup;
		} else if (mainDiv!=null) {
			var newH1   = document.createElement("h1");	
			mainDiv.parentNode.insertBefore(newH1,mainDiv);
			newH1.innerHTML = markup;	
		} else {
			alert("ERROR: This page does not follow the MMNA UI architecture and insertSwfHeader() can not be used.")
		}
	}
}

if (document.getElementsByClassName == undefined) {
	document.getElementsByClassName = function(className)
	{
		var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
		var allElements = document.getElementsByTagName("*");
		var results = [];
	
		var element;
		for (var i = 0; (element = allElements[i]) != null; i++) {
			var elementClass = element.className;
			if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
				results.push(element);
		}
	
		return results;
	}
}

/* omniture environmental variables */
var omnitureVehicleSuite = 'mitsubishicars-vehiclesdev';
var omnitureCompanySuite = 'mitsubishicar-companydev';
var omnitureMediaSuite = 'mitsubishicar-mediadev';
var omnitureFinanceSuite = 'mitsubishicar-financedev';
var omnitureOwnersSuite = 'mitsubishicars-ownersdev';
var omnitureOtherSuite = 'mitsubishicar-vipdev';

if (location.host == 'www.mitsubishicars.com') {
	omnitureVehicleSuite = 'mitsubishicars-vehicles,mitsubishimmna-all';
	omnitureCompanySuite = 'mitsubishicar-company,mitsubishimmna-all';
	omnitureMediaSuite = 'mitsubishicar-media,mitsubishimmna-all';
	omnitureFinanceSuite = 'mitsubishicar-finance,mitsubishimmna-all';
	omnitureOwnersSuite = 'mitsubishicars-owners,mitsubishimmna-all';
	omnitureOtherSuite = 'mitsubishicar-vip,mitsubishimmna-all';
}
