/*
 * for users that don't have firefox/firebug, override console object
 */
try { console.log('init console... done'); } catch(e) { console = { log: function(text) {}, trace: function(text){} }; }


var DONWLOAD_URL = BASE_CONTEXT + "/pages/mds/util/downloadFile.do";
var i;

// begin common libraries

	// BrowserDetect
	// http://www.quirksmode.org/js/detect.html
	var BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"An unknown browser";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";this.OS=this.searchString(this.dataOS)||"an unknown OS";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1)
	return data[i].identity;}
	else if(dataProp)
	return data[i].identity;}},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};BrowserDetect.init();

// end common libraries

// begin global variables

	var global = new Object();
	global.siteSpeed = "high";

	/*********************Cookie**********************/
	var COOKIE_EXPIRES = 1;
	//var COOKIE_CUSTOMER_LOCATION = "cookie_customer_location";
	var COOKIE_CUSTOMER_LOCATION = "cookie_customer_location";
	/*************************************Coookies for Raqs***********************************/
	var COOKIE_RAQ_DATA = "cookie_raq_data";
	var COOKIE_RAQ_DEALERS_DATA = "cookie_raq_dealers_data";

// end global variables


/*
 * for users that don't have firefox/firebug, override console object
 */
if (console == undefined)
	var console = {
		log : function(text) {
		},
		trace : function(text) {
		}
	};

//http://www.biasecurities.com/blogs/jim/archive/2005/04/28/1794.aspx
function AttachEvent(elementObj, eventName, eventHandlerFunctionName) {
	if (elementObj.addEventListener) { // Non-IE browsers
		elementObj.addEventListener(eventName, eventHandlerFunctionName, false);
	} else if (elementObj.attachEvent) { // IE 6+
		elementObj.attachEvent('on' + eventName, eventHandlerFunctionName);
	} else { // Older browsers
		var currentEventHandler = elementObj['on' + eventName];
		if (currentEventHandler == null) {
			elementObj['on' + eventName] = eventHandlerFunctionName;
		} else {
			elementObj['on' + eventName] = function(e) {
				currentEventHandler(e);
				eventHandlerFunctionName(e);
			}
		}
	}
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/, "");
}

String.prototype.replaceAll = function(f,t){
	var s = this;
	while (s.indexOf(f) > -1) s = s.replace(f, t); 
	return s;
}

var css = function() {
	var private_var;
	function private_method() {
		// do stuff here
	}
	return {
		hasClassName : function(elem, className) {
			return (elem.className.indexOf(className) != -1);
		},
		addClassName : function(elem, className) {
			this.removeClassName(elem, className);
			elem.className = (elem.className + " " + className).trim();
		},
		removeClassName : function(elem, className) {
			elem.className = elem.className.replace(className, "").trim();
		}
	};
}();

var cookie = function() {
	var private_var;
	function private_method() {
		// do stuff here
	}
	return {
		create : function(name, value, days) {
			var obj = document.getElementById("mdsGfooterAboutWrapper");

			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				var expires = "; expires=" + date.toGMTString();
			} else {
				var expires = "";
			}
			document.cookie = name + "=" + value + expires + "; path=/";
		},
		read : function(name) {

			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for ( var i = 0; i < ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == ' ')
					c = c.substring(1, c.length);
				if (c.indexOf(nameEQ) == 0)
					return c.substring(nameEQ.length, c.length);
			}
			return null;
		},
		erase : function(name) {
			this.create(name, "", -1);
		}
	};
}();


// based on superPopup from classic sites
var popup = function() {

	var private_var;
	function private_method() {
		// do stuff here
	}

	return {
		pop : function(pOptions) {

			var url = null;
			var type = null;
			var directories = null;
			var location = null;
			var menubar = null;
			var resizable = null;
			var scrollbars = null;
			var status = null;
			var toolbar = null;
			var top = null;
			var left = null;
			var width = null;
			var height = null;
			var winName = null;
			var clickTrackValue = null;
			// URL is the only required field.
			if (pOptions.url != null) {	url = pOptions.url;};
			if (pOptions.type != null) { type = pOptions.type;};
			// type will set some basic options to make the function cleaner -- otherwise all values can be set
			if(type == "interstitial"){winName="interstitial";width="600";height="450";scrollbars="no";resizable="no";}
			if(type == "tradein"){winName="tradein";width="600";height="650";scrollbars="no";resizable="yes";}
			if(type == "onstar"){winName="popOnstar";width="675";height="461";scrollbars="no";resizable="no";}
			if(type == "100k"){winName="pop100k";width="740";height="850";scrollbars="no";resizable="no";scrollbars="yes";}

			// test to see if we have set a window option on the function or in a profile above, if not then set the value to be a default.
			if (pOptions.directories != null) { directories = pOptions.directories;} else if (directories == null) { directories = "no" ;}
			if (pOptions.location != null) { location = pOptions.location;} else if (location == null) { location = "no" ;}
			if (pOptions.menubar != null) { menubar = pOptions.menubar;} else if (menubar == null) { menubar = "no" ;}
			if (pOptions.resizable != null) { resizable = pOptions.resizable;} else if (resizable == null) { resizable = "no" ;}
			if (pOptions.scrollbars != null) { scrollbars = pOptions.scrollbars;} else if (scrollbars == null) { scrollbars = "yes" ;}
			if (pOptions.status != null) { status = pOptions.status; } else if (status == null) { status = "yes" ;}
			if (pOptions.toolbar != null) { toolbar = pOptions.toolbar; } else if (toolbar == null) { toolbar = "no" ;}
			if (pOptions.top != null) { top = pOptions.top} else if (top == null) { top = "50";}
			if (pOptions.left != null) { left = pOptions.left;} else if (left == null) { left = "50" ;}
			if (pOptions.width != null) { width = pOptions.width;} else if (width == null) { width = "250" ;}
			if (pOptions.height != null) { height = pOptions.height;} else if (height == null) { height = "250" ;}
			if (pOptions.winName != null) { winName = pOptions.winName;} else if (winName == null) { winName = "popUp" ;}
			if (pOptions.clickTrack != null) { clickTrackValue = pOptions.clickTrack;}
			windowOptions = "width=" + width + ", height=" + height + ", directories=" + directories + ", location=" + location + ", menubar=" + menubar + ", resizable=" + resizable + ", scrollbars=" + scrollbars + ", toolbar=" + toolbar + ", status=" + status + ", top=" + top + ", left=" + left;

			window.open(url,winName,windowOptions);
		}
	};
}();


var util = function() {
	var private_var;
	function private_method() {
		// do stuff here
	}
	return {
		getBrowserForCss : function() {
			var obj = document.getElementById("mdsGfooterAboutWrapper");

			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				var expires = "; expires=" + date.toGMTString();
			} else {
				var expires = "";
			}
			document.cookie = name + "=" + value + expires + "; path=/";
		},
		getElementsByClassName : function(classname, node) {
			if (!node)
				node = document.getElementsByTagName("body")[0];
			var a = [];
			var re = new RegExp('\\b' + classname + '\\b');
			var els = node.getElementsByTagName("*");

			for ( var i = 0, j = els.length; i < j; i++)
				if (re.test(els[i].className))
					a.push(els[i]);

			return a;
		}
	};
}();

var ui = function() {
	var private_var;
	function private_method() {
		// do stuff here
	}
	return {
		toggleAboutThisPage : function() {
			var obj = document.getElementById("mdsGfooterAboutWrapper");

			if (obj != null) {
				if (hasClassName(obj, "closed")) {
					css.removeClassName(obj, "closed");
				} else {
					css.addClassName(obj, "closed");
				}
			}
		},
		toggleSpeed : function() {

			if (global.siteSpeed == "high") {
				cookie.create("global.siteSpeed", "low", 14);
			} else {
				cookie.create("global.siteSpeed", "high", 14);
			}

			window.location.replace(unescape(window.location.pathname));

		},
		externalLink : function(anchor) {
			var interstitialUrl = BASE_CONTEXT + "/pages/misc/instersticial/popupToExteriorLink.do?newURL=" + escape(anchor.href);
			// call omniture tracking manually
			exitLink(anchor);
			popup.pop({url:interstitialUrl, type:'interstitial'});
			return false;
		},
		showWorldwideSites : function() {
			var d$ = mrm.$('#wsDialog');
			var g$ = mrm.$('#gMdsFooter');
			d$.addClass("active");
			d$.css('left', (DL_GetElementLeft(g$) + (g$.width() / 2) + 'px'));
			d$.css('top', (DL_GetElementTop(g$) - (d$.height() / 2) + 'px'));
		},
		hideWorldwideSites : function() {

		},
		hideWorldwideSiteDiv : function() {
			mrm.$('#wsDialog').removeClass('active');
			mrm.$('#wsDialog').removeClass('activeCountries');
			mrm.$('#continentList li ul').removeClass('wsEnableCountry').addClass('wsDisableCountry');
		},
		showCountries : function(continentId) {

			mrm.$('#continentList li ul').each(function(value){
				value.removeClass('wsEnableCountry');
				value.addClass('wsDisableCountry');
			});

			mrm.$('#' + continentId + ' ul').removeClass('wsDisableCountry');
			mrm.$('#' + continentId + ' ul').addClass('wsEnableCountry');
			
			var d$ = mrm.$('#wsDialog');
			var g$ = mrm.$('#gMdsFooter');
			d$.addClass('activeCountries');
			d$.css('left', (DL_GetElementLeft(g$) + (g$.width() / 2) + 'px'));
			d$.css('top', (DL_GetElementTop(g$) - (d$.height() / 2) + 'px'));
		},
		hideCountries :  function() {
			mrm.$('#wsDialog').removeClass('activeCountries');
			mrm.$('#continentList li ul').removeClass('wsEnableCountry').addClass('wsDisableCountry');
		}

	};
}();

function getRequest() {
	try {
		return (new ActiveXObject("Msxml2.XMLHTTP2"));
	} catch (e) {}
	try {
		return (new ActiveXObject("Microsoft.XMLHTTP"));
	} catch (e) {}
	try {
		return (new XMLHttpRequest());
	} catch (e) {}

	return (null);
}


function Global_Load_EventHandler() {

	var t$ = mrm.$('#gSpeedToggle');

	if (global.siteSpeed == "low") {
		mrm.$('body').addClass('lowspeed');
		if (t$.length >= 1) {
			t$.html("<a title='High Speed Version' href=\"javascript:chooseSpeed('Y')\" ><span class='clickable'>High Speed Version</span></a>");
		}
	}

	if (global.siteSpeed == "high") {
		mrm.$('body').addClass('highspeed');
		if (t$.length >= 1) {
			t$.html("<a  rel='nofollow' title='Low Speed Version' href=\"javascript:chooseSpeed('N')\" ><span class='clickable'>Low Speed Version</span></a>");
		}
	}

	if (BrowserDetect) {
		// Explorer6 FireFox2
		mrm.$('body').addClass(BrowserDetect.browser + "" + BrowserDetect.version);

		console.log("BrowserDetect.browser: " + BrowserDetect.browser);
		console.log("BrowserDetect.version: " + BrowserDetect.version);
		console.log("BrowserDetect.OS: " + BrowserDetect.OS);
	}

	console.log("global.siteSpeed: " + global.siteSpeed);

	// update footer link
	if (t$.length >= 1) {
		t$.click(function() {
			ui.toggleSpeed();
		});
	}

}

	// inline initialization -- can happen before any load events fire
	{
		var speed = cookie.read("global.siteSpeed");
		if (speed != null) {
			global.siteSpeed = speed;
		}
	}
	//

	// domready initialization
	mrm.$(function() {
		Global_Load_EventHandler();
	});
	//

function isDecimalNumberKey(evt) {
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		if (navigator.appName != 'Microsoft Internet Explorer') {
			if (charCode == 46 && evt.target.value.search(/\./) == -1) {
				return true;
			} else {
				return false;
			}
		} else if (charCode == 46 && evt.srcElement.value.search(/\./) == -1) {
			return true;
		} else {
			return false;
		}
	}
	return true;
}


/************************************GLOBAL SEARCH***************************************/
function showhideSearch(obj){
	var search = 'Search'
	if (obj.value == search) obj.value="";
	else{
		if (obj.value.trim() == "") obj.value=search;
	}
}
/************************************GLOBAL SEARCH END***************************************/

/************************************Utility Functions***************************************/

function isNoE(content)
{
	return (content==null || content=="");
}

/************************************Default Zipcode***************************************/

function Location(zipcode,region,county,isMultiCounty,isMultiRegion){
	this.zipcode = zipcode;
	this.region = region;
	this.county= county;
	this.isMultiCounty = isMultiCounty;
	this.isMultiRegion = isMultiRegion;
}

function Region(code,descr,dmas)
{
	this.code=code;
	this.descr=descr;
	this.dmas = dmas;
}

function County(code,descr)
{
	this.code=code;
	this.descr=descr;
}

function saveDefaultLocation(zipcode,region,county,isMultiCounty,isMultiRegion)
{
	var loc = new Location(zipcode,region,county,isMultiCounty,isMultiRegion);
	Cookie.write(COOKIE_CUSTOMER_LOCATION,JSON.encode(loc),{duration: COOKIE_EXPIRES, path:'/'});
}

function getDefaultLocation()
{
	var locstr = Cookie.read(COOKIE_CUSTOMER_LOCATION);
	var cookieDecoded;
	
	if(locstr!=null & locstr!=''){
		cookieDecoded = JSON.decode(locstr);
	}else{
		return null;
	}
	return cookieDecoded;
}

function getRelativePath(){
	var Str = document.location.href;
	var newStr = "";
	var index=0;
	for(i=0;i<Str.length;i++){
		if(!(Str.charAt(i)=="/" && i > 6)){
			newStr = newStr + Str.charAt(i);
		}else{
			i=Str.length;
		}
	}
	return newStr;
}

function linkTo(url){
	var newUrl = BASE_CONTEXT+url;
	window.location.href=newUrl;
}
function submitForm(id){
	var formObj = document.getElementById(id);
	formObj.submit();
}



/***************BEGIN::Position functions***********************/

/** Return the Left position of a given element.
 * @param eElement
 * @return
 */
function DL_GetElementLeft(eElement) {
	var nLeftPos = eElement.offsetLeft;
	var eParElement = eElement.offsetParent;
	while (eParElement != null) {
		nLeftPos += eParElement.offsetLeft;
		eParElement = eParElement.offsetParent;
	}
	return nLeftPos;
}

/** Return the Top position of a given element.
 * @param eElement
 * @return
 */
function DL_GetElementTop(eElement) {
	var nTopPos = eElement.offsetTop;
	var eParElement = eElement.offsetParent;
	while (eParElement != null) {
		nTopPos += eParElement.offsetTop;
		eParElement = eParElement.offsetParent;
	}
	return nTopPos;
}


/** Calculates the coordinates to center an element taking in
 *  consideration the size of the element itself, size of the
 *  window and the scroll of the page.
 *
 * @param elemID
 * @return  postion class object
 */
function getCenterPosition(elemID) {
	// Locate the element
	var e$ = mrm.$('#' + elemID);
	// Make sure that the element exists
	if (e$.length == 0)	return null;
	// Find its current height and width
	var w = e$.width();
	var h = e$.height();
	// Position the box, vertically, in the middle of the window
	var t = scrollY() + (windowHeight() / 2) - (h / 2);
	// But no higher than the top of the page
	if (t < 0) t = 0;
	// Position the box, horizontally, in the middle of the window
	var l = scrollX() + (windowWidth() / 2) - (w / 2);
	// But no less than the left of the page
	if (l < 0) l = 0;
	// Set the adjusted position of the element
	var pos = new Position(l, t);
	return pos;
};

/** A function for determining how far horizontally the browser is scrolled
 * @return
 */
function scrollX() {
	// A shortcut, in case we're using Internet Explorer 6 in Strict Mode
	var de = document.documentElement;
	// If the pageXOffset of the browser is available, use that
	return self.pageXOffset ||

	// Otherwise, try to get the scroll left off of the root node
			(de && de.scrollLeft) ||
			// Finally, try to get the scroll left off of the body element
			document.body.scrollLeft;
}

/** A function for determining how far vertically the browser is scrolled
 * @return
 */
function scrollY() {
	// A shortcut, in case we're using Internet Explorer 6 in Strict Mode
	var de = document.documentElement;
	// If the pageYOffset of the browser is available, use that
	return self.pageYOffset ||
	// Otherwise, try to get the scroll top off of the root node
			(de && de.scrollTop) ||
			// Finally, try to get the scroll top off of the body element
			document.body.scrollTop;
}

/** Get the actual height (using the computed CSS) of an element
 * @param elem
 * @return
 */
function getHeight(elem) {
	// jQuery-ize elem, which might be passed as either DOM element or mooTools object.
	var e$ = mrm.$('#' + elem.getAtribute('id'));
	return (e$.length > 0) ? e$.height() : 0;
}

/** Get the actual width (using the computed CSS) of an element
 * @param elem
 * @return
 */
function getWidth(elem) {
	// jQuery-ize elem, which might be passed as either DOM element or mooTools object.
	var e$ = mrm.$('#' + elem.getAtribute('id'));
	return (e$.length > 0) ? e$.width() : 0;
}

/** Find the height of the viewport
 * @return
 */
function windowHeight() {
	// A shortcut, in case we're using Internet Explorer 6 in Strict Mode
	var de = document.documentElement;
	// If the innerHeight of the browser is available, use that
	return self.innerHeight ||
	// Otherwise, try to get the height off of the root node
			(de && de.clientHeight) ||
			// Finally, try to get the height off of the body element
			document.body.clientHeight;
}

/** Find the width of the viewport
 * @return
 */
function windowWidth() {
	// A shortcut, in case we're using Internet Explorer 6 in Strict Mode
	var de = document.documentElement;
	// If the innerWidth of the browser is available, use that
	return self.innerWidth ||
	// Otherwise, try to get the width off of the root node
			(de && de.clientWidth) ||
			// Finally, try to get the width off of the body element
			document.body.clientWidth;
}

/** Find the horizontal position of the cursor
 * @param e
 * @return
 */
function getX(e) {
	// Normalize the event object
	e = e || window.event;
	// Check for the non-IE position, then the IE position
	return e.pageX || e.clientX + document.body.scrollLeft;
}

/** Find the vertical position of the cursor
 * @param e
 * @return
 */
function getY(e) {
	// Normalize the event object
	e = e || window.event;
	// Check for the non-IE position, then the IE position
	return e.pageY || e.clientY + document.body.scrollTop;
}

/** Find the mouse position.
 * @param e: Mouse Evennt
 * @return: Return the position x and y of the mouse.
 */
function getMousePosition(e) {
	var x = 0;
	var y = 0;
	var arrayMousePos = new Array();
	if (document.all) {
		x = e.clientX + document.body.scrollLeft;
		y = e.clientY + document.body.scrollTop;
	} else if (document.getElementById) {
		x = e.pageX;
		y = e.pageY;
	}
	arrayMousePos[0] = x
	arrayMousePos[1] = y;
	return arrayMousePos;
}
function getScreenCenter(){
	var left = windowWidth() / 2 + scrollX();
	var top = windowHeight() / 2 + scrollY();
	return new position(left, top);
}
/***************END::Position functions***********************/


function chooseSpeed(mode){
 	 if (mode=="N"){
              mode= "N&evar6=globalfoot_lowspeed";
        }
		var index = document.location.href.indexOf("?");
	var pathMode = ""
	if (index > -1){
		pathMode = document.location.href.replace("useFlash=N&evar6=globalfoot_lowspeed", "");
		pathMode = pathMode.replace("useFlash=N", "");
		pathMode = pathMode.replace("useFlash=Y", "");

		pathMode = pathMode + "&useFlash=" + mode;

		pathMode = pathMode.replace("?&", "?");

	}
	else

	pathMode = document.location.href + "?useFlash=" + mode;
	document.location.href = pathMode;
}

/** Returns the html to be used as a flashvar
 * @param id: String, Tag Id
 * @return: The result with escaped characters so it doesn't break the xhtml
 */
function getInnerHtml(id) {
		var result = mrm.$('#' + id).html();
	    result = result.split("\"").join(escape("\""));
	    result = result.split("&").join(escape("&"));
		return result;
}
/***************END::Position functions***********************/

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num);
}

/** Opens the interstitial popup and escapes the URL
 * @param url
 * @param name
 * @return
 */
function openInterstitial(url, name){
	url = url.split("\"").join(escape("\""));
	url = url.split("&").join(escape("&"));
	window.open(BASE_CONTEXT + '/pages/misc/instersticial/popupToExteriorLink.do?newURL=' + url,name,'width=529,height=234');
}
function openWin(url,winName,width,height){
		window.open(BASE_CONTEXT+url,winName,'width='+width+',height='+height+',left=300,top=200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');

}

function openWinParam(url,winName,param){
	if(url.indexOf("http://") != 0){
		window.open(BASE_CONTEXT+url,winName,param);
	}else{
		window.open(url,winName,param);
	}
}


function flashInnerHTML(node) {
    var nodeNamesWeConsider = "href|id|alt|title|hreflang|class|onclick|target|onblur|value|name|type|method|action|width|height|src|onmouseover|style|";
    // that string doesn't let us ignore "hreflang" (href) of "hideFocus" (id)
    var result = "";
	switch (node.nodeType) {
	// http://www.zvon.org/xxl/DOM2reference/DOM2/Output/data/_glossary.html#NodeTypes
		case 3: // text node
			var textValue = node.nodeValue;
			textValue = textValue.replaceAll(/\t/g, "");
			textValue = textValue.replaceAll(/\n/g, "");
			textValue = textValue.replaceAll(/\r/g, "");
			result += textValue;
		break;
		case 1:
			result += "<" + node.nodeName.toLowerCase();
			if (node.attributes != null) {
				if (node.attributes.length > 0) {
					for (var i = 0;  i < node.attributes.length; i++) {
						var nodeName = node.attributes.item(i).nodeName;
						//if ((node.attributes.item(i).value != "null") && (node.attributes.item(i).value != "") && (nodeNamesWeIgnore.indexOf(nodeName) == -1)) {
						if ((node.attributes.item(i).value != "null") && (nodeNamesWeConsider.indexOf(nodeName) != -1)) {
							result += " " + node.attributes.item(i).nodeName;
							result += "=\"";
							if(node.attributes.item(i).nodeName == "alt" || node.attributes.item(i).nodeName == "title"){
								node.attributes.item(i).value = node.attributes.item(i).value.replace("\"", "&#34;");
							}
							result += node.attributes.item(i).value +"\"";
						}
					}
				}
			}
			if (node.childNodes != null) {
				if (node.childNodes.length > 0) {
					result += ">";
					for (var j = 0;  j < node.childNodes.length; j++) {
						result += flashInnerHTML(node.childNodes[j]);
					}
					result += "</"+ node.nodeName.toLowerCase() +">";
				}
				else {
					result += "/>";
				}
			}
		break;
	}
	result = result.replaceAll("% ","%25 ");
	result = result.replaceAll("\"","%22");
	result = result.replaceAll("&amp;","%26");
	result = result.replaceAll("&","%26");
    return result;
}

function centeredWin(a_str_windowURL, a_str_windowName, a_int_windowWidth,
		a_int_windowHeight, a_bool_scrollbars, a_bool_resizable, a_bool_menubar,
		a_bool_toolbar, a_bool_addressbar, a_bool_statusbar, a_bool_fullscreen) {

  var int_windowLeft = (screen.width - a_int_windowWidth) / 2;
  var int_windowTop = (screen.height - a_int_windowHeight) / 2;
  var str_windowProperties = 'height=' + a_int_windowHeight + ',width=' + a_int_windowWidth + ',top=' + int_windowTop + ',left=' + int_windowLeft + ',scrollbars=' + a_bool_scrollbars + ',resizable=' + a_bool_resizable + ',menubar=' + a_bool_menubar + ',toolbar=' + a_bool_toolbar + ',location=' + a_bool_addressbar + ',statusbar=' + a_bool_statusbar + ',fullscreen=' + a_bool_fullscreen + '';
  var obj_window = window.open(a_str_windowURL, a_str_windowName, str_windowProperties)

	if (parseInt(navigator.appVersion) >= 4) {
      obj_window.window.focus();
    }
}

var xPosition,yPosition;

var position = new Class({

    initialize:function(x,y){

        this.x = x;

        this.y = y;

    }

});


function downloadFile(filePath){
	location.href = DONWLOAD_URL + "?filename=" + filePath;
}

function getUrlParams() {
	var qs = location.search;
	qs = qs.substring(1);
	// create an 'array' called newArray with the name value pairs from the querystring
	var qsArray = new Array;
	qsArray = qs.split('&'); //creating an array in which the values are separated by ampersands in the code//
	var keyValueArray = new Array; //this one loads the names and values into a hash (of sorts)//
	for(i=0; i<qsArray.length; i++) {
		var nameValue = qsArray[i].split('='); //splitting what we find between each ampersand into key value pairs //
		keyValueArray[nameValue[0]] = unescape(nameValue[1]); //we are then turning all the escaped characters back into the 'real thing' ie. %3F turns into a '?' //
	}
	return keyValueArray;
}

function openPrivacyStatement(a_str_windowURL) {
	var a_str_windowName = 'privacyStatement';
	var a_int_windowWidth = 567;
	var a_int_windowHeight = 600;
	var int_windowLeft = (screen.width - a_int_windowWidth) / 2;
	var int_windowTop = (screen.height - a_int_windowHeight) / 2;
	var str_windowProperties = 'height=' + a_int_windowHeight + ',width=' + a_int_windowWidth + ',top=' + int_windowTop + ',left=' + int_windowLeft;
	var obj_window = window.open(a_str_windowURL, a_str_windowName, str_windowProperties)
    if (parseInt(navigator.appVersion) >= 4) {
      obj_window.window.focus();
    }
}

// Functions for Zip Input validation.
function validateZip(s)
{
     var res = (reqField(s,"Zip Code") && testZip(s)) ;
     return res;
}

function testZip(s)
{
	 vZipInfo = null;
     reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
     //vZipInfo = new zipcodeUtil(s);
     if (!reZip.test(s)||(s=="00000")) {
          alert("Zip Code Is Not Valid");
          return false;
     }
	return true;
}

function reqField(s,fieldname)
{
     if(s=="")
     {
     	alert(fieldname+" Is Required");
         return false;
     }
     else{
	return true;
	}
}

function inputZip(src, evt){
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (   ((charCode >= 48 && charCode <= 57) && src.value.length<5) ||
	 (charCode<31) || (evt.keyCode=='37') || (evt.keyCode=='39') || (evt.keyCode=='46') )
	{
		return true;
	}
	else
	{
		return false;
	}
}



function fireInterstitial(url){
  var newURL="";
  var context = url.split("/")[1]; // search the context of the url
  var context2 = BASE_CONTEXT.split("/")[1]; // context of the brand site
  if(context!=context2){ // if both context are diferents, append the brand's context to the url
    newURL = BASE_CONTEXT+url;
  }else{
    newURL = url;
  }

  newURL=newURL.replace(/&/g,'%26');


  if(mrm.$.browser.msie){ // fix to IE
    centeredWin(newURL, "interstitialWin", "630", "323", true, false, false, false, false, false, false);//located in common.js
  }else{
    centeredWin(newURL, "interstitialWin", "620", "323", true, false, false, false, false, false, false);//located in common.js
  }
}

function currentOffer(year, brand, evar){
	var zipLoc = getDefaultLocation();
	var tempLink = "";
	
	try{
		if(year!=null&&year!="") tempLink += "&year="+year;
		if(brand!=null&&brand!="") tempLink += "&brand="+brand;
		if(evar!=null&&evar!="") tempLink += "&evar2="+evar;
		
		try{
			var dropdownIndex = document.getElementById('yearDropDown').selectedIndex;
			var dropdownValue = document.getElementById('yearDropDown')[dropdownIndex].value;


			if(null!=zipLoc){
				window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode="+zipLoc.zipcode+"&region="+zipLoc.region.code+"&county="+zipLoc.county.code+tempLink+"&brand="+vehicleArray[maxYear][i][0]+"&year="+dropdownValue;
			}else{
			if(tempLink!=""){
				window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?"+tempLink+"&zipCode=";
			}else{
				window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode=";
			}		
			}
		}catch(e){
			if(null!=zipLoc){		 
				window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode="+zipLoc.zipcode+"&region="+zipLoc.region.code+"&county="+zipLoc.county.code+tempLink;		 	
			}else{
			if(tempLink!=""){
				window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?"+tempLink+"&zipCode=";
			}else{
				window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode=";
			}
			}
		}		
		  
	
	}catch(e){
		if(tempLink!=""){
			window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?"+tempLink+"&zipCode=";
		}else{
			window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode=";
		}		
	}
	
}

function currentOfferHMC(year, brand){
	var zipLoc = getDefaultLocation();
	var tempLink = "";
	
		if(year!=null&&year!="") tempLink += "&year="+year;
		if(brand!=null&&brand!="") tempLink += "&brand="+brand;			
		  
	if(null!=zipLoc){		 
		window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode="+zipLoc.zipcode+"&region="+zipLoc.region.code+"&county="+zipLoc.county.code+tempLink+"&brand="+brand+"&year="+year;		 	
	}else{
		if(tempLink!=""){
			window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode="+tempLink;
		}else{
			window.location.href=BASE_CONTEXT+"/tools/currentoffers/results.do?zipCode=";
		}
	}
}

function clickTrack(obj) {
	now = new Date();
	// force all specified O_s properties to lower case
	var mapLowerCase = ['pageName','hier','prop','eVar','events','pe'];
	for ( var i in obj ) {
		for ( var j = 0; j < mapLowerCase.length; j++ ) {
			if ( i.indexOf(mapLowerCase[j]) >= 0 ) {
				if ( typeof obj[i] == 'string' ) {
					obj[i] = obj[i].toLowerCase();
					break;
				}
			}
		}
	}
	if(typeof Omniture_s != "undefined"){
		Omniture_s.t(obj);
	}
}

var omniUpdateInterval, omniUpdateProp, omniUpdateVal;
function updateOmnitureVal() {
	// Sets an Omniture tracking property myProp to myValue.
	if (typeof setOmnitureValue != 'undefined') {
		clearInterval(omniUpdateInterval);
		setOmnitureValue(omniUpdateProp, omniUpdateVal);
	}
}
function callOmnitureValUpdate(myProp, myVal) {
	// Calls the above function repeatedly until /mds/tiles/common/inc_tracking_omniture.jsp's js code is loaded.
	omniUpdateProp = myProp;
	omniUpdateVal = myVal;
	omniUpdateInterval = setInterval('updateOmnitureVal()', 10);
}
var omniUpdatesInterval, omniUpdatesArray;
function updateOmnitureVals() {
	if (typeof setOmnitureValues != 'undefined') {
		clearInterval(omniUpdatesInterval);
		setOmnitureValues(omniUpdatesArray);
	}
}
function callOmnitureValsUpdate(myArray) {
	// Calls the above function repeatedly until /mds/tiles/common/inc_tracking_omniture.jsp's js code is loaded.
	omniUpdatesArray = myArray;
	omniUpdatesInterval = setInterval('updateOmnitureVals()', 10);
}

function emptyObject(obj){
	for(var name in obj){
		return false;
	}
	return true;
}
function showWorldwideSitesDialog(src){
	var html = '';
	var url = BASE_CONTEXT+"/en/pages/global/nav/worldWideSites/pageData.xml";
	var xml;
	var data;
	var d$ = mrm.$('#wsDialog');
	if (d$.length > 0) {
		d$.remove();
	}
	var toolTipElm = document.createElement('div');
	toolTipElm.setAttribute('id', 'wsDialog');
	toolTipElm.innerHTML += "<div>"+DIVISION+" Worldwide</div>";
	toolTipElm.innerHTML += "<div><a href='#' onclick='closeWorldWideSitesDialog(this);'>Close</a></div>";
	toolTipElm.innerHTML += "<ul>";
	try{
	    xml = new JKL.ParseXML(url);
	    data = xml.parse();
	    for(var link in data.links.link){
	    	if(data.links.link.hasOwnProperty(link)){
	    		toolTipElm.innerHTML += "<li><a href='"+data.links.link[link].href+"' title='"+data.links.link[link].title+"' target='"+data.links.link[link].target+"' class='"+data.links.link[link].css+"' onclick='"+data.links.link[link].onclick+"'>"+data.links.link[link].text+"</a></li>";
	    	}
	    }
	}catch(err){}
	toolTipElm.innerHTML += "</ul>";
	document.body.appendChild(toolTipElm);
	d$ = mrm.$('#wsDialog');
	d$.css('left', (DL_GetElementLeft(src) + 'px'));
	d$.css('top', (DL_GetElementTop(src) + 'px'));
	return false;
}

function closeWorldWideSitesDialog() {
	mrm.$('#wsDialog').remove();
	return false;
}

function doVL(){
	validateCookie(this,'locateVehicleLanding()','vl',false);
	return false;
}

function doDL(){
	validateCookie(this,'locateDealer()','dl',false);
	return false;
}
function doBYO(){
	validateCookie(this,'byo()','byo',false);
	return false;
}

function doAffordability(){
	validateCookie(this,'byo()','byo',false);
	return false;
}

function pricingOffer(){
	var zipLoc = getDefaultLocation();
	if(null!=zipLoc){		
		window.location.href=BASE_CONTEXT+"/pages/mds/pricing/affordability.do?zipCode="+zipLoc.zipcode+"&regionCode="+zipLoc.region.code+"&countyCode="+zipLoc.county.code;	
	}else{		
		window.location.href=BASE_CONTEXT+"/pages/mds/pricing/affordability.do";
	}
}

function changeYear(year,url) {
	if ($type(window.changeYearOverride) == 'function') {
		// used if a page needs to change the normal behavior of the cahnge year function
		changeYearOverride(year);
	}else{
		window.location = url.split('?')[0];
	}
}

/* Set the user's zipcode to that of the 
   dealer inventory that was selected in LAD results
*/
function setLocationToDealer(zip) {
      var loc = getDefaultLocation();

      if(loc == null || loc.zipcode != zip) {
            
            /*var zipInfo = new zipcodeUtil(zip);
            var counties = zipInfo.getCounties();
            var regions = zipInfo.getRegions(counties[0].code);*/
                              
            saveDefaultLocation(zip, 
                                          null,
                                          null,
                                          false, 
                                          false);
      }
}


/* GMDS CADILLAC WRAPPED APPS SITE-WIDE JAVASCRIPT ===================================================
*	JavaScript and jQuery 1.4.4 functions for all Cadillac GMDS Wrapped Apps
=================================================================================================== */

/* INTERNET EXPLORER BOX-SHADOWS =====================================================================
*	For replacing .shadow1 and .shadow2 classes with IE-specific .shadow1_ie and .shadow2_ie, also
*	injecting an absolute-positioned div for the classes to style (Blur filter for shadow).
=================================================================================================== */

function applyShadowIe (divs$) {  // Applies IE box-shadow to divs.
	// Injects an absolute-positioned shadow div with styling from /en/css/_site.css, 
	// and positions it underneath each target div.
	if (mrm.$.browser.msie) {
		divs$.each(function(index, domEle) {
			var e$ = mrm.$(domEle);  // Target div to which shadow's applied.
			
			// Get target div info.
			var eId = e$.attr('id');
			var eOT = e$.offset().top;
			var eOL = e$.offset().left;
			var eOW = e$.outerWidth();
			var eOH = e$.outerHeight();
			
			// Add class to support div selection in subsequent functions.
			e$.addClass('shadow1target_ie');

			// Create shadow div.
			// Substitute correct IE-specific shadow class for target div's shadow class.
			var sCls = '';
			if (e$.hasClass('shadow1')) {
				sCls = 'shadow1_ie';
			} else if (e$.hasClass('shadow2')) {
				sCls = 'shadow2_ie';
			}
			var sId = eId + '_' + sCls;
			var s$ = mrm.$('<div>');
			s$.attr({
					'id': sId,
					'class': sCls
				})
				.css({
					'width': eOW + 'px',
					'height': eOH + 'px'
				});
				
			// Add shadow div as target's next sibling, remove target div's shadow class.  
			e$.after(s$);
			e$.removeClass('shadow1').removeClass('shadow2');
			
			// Position shadow div.
			var sPR = document.getElementById(s$.attr('id')).filters.item('DXImageTransform.Microsoft.Blur').pixelRadius;
			s$.offset({'top': eOT - sPR, 'left': eOL - sPR});
			
			// Add target div resize handler.  Subsequent dynamic content changes may change target div height.
			// Since shadow div is not a child of target div, it must be resized via jQuery to match.
			e$.resize(function() {
				resizeShadowIe(eId, sId, sPR);
			});
		});
	}
}

function resizeShadowIe (myTID, mySID, mySPR) {  // Resizes shadow div when target div is resized.
	var myE$ = mrm.$('#' + myTID);  // Target div.
	var myS$ = mrm.$('#' + mySID);  // Shadow div.
	// Adjust shadow div height to match new target div height.
	var myEOH = myE$.outerHeight();
	var mySH = myS$.outerHeight() - (2 * mySPR);
	var hDiff = myEOH - mySH;
	myS$.height(mySH + hDiff);
	// Check for and re-position any subsequent, sibling shadow divs below resized myS$.
	var moreDivs$ = mrm.$('#' + myTID + '~div.shadow1target_ie');
	if (moreDivs$.length > 0) {
		moreDivs$.each( function (index, domEle) {
			var d$ = mrm.$(domEle);
			var ds$ = d$.next('div.shadow1_ie');
			ds$.offset({'top': ds$.offset().top + hDiff, 'left': ds$.offset().left});
		});
	}
}

function getQsParams() {
	var qs = location.search,
		qsArray = [],
		keyValue = [],
		nameValue;
		
	qs = qs.substring(1);
	qsArray = qs.split('&');
	
	for (var i = 0, len = qsArray.length; len > i; i++) {
		nameValue = qsArray[i].split('=');
		keyValue[nameValue[0]] = unescape(nameValue[1]); 
	}
	
	return keyValue;
}

mrm.$(function() {
	if (mrm.$.browser.msie) {
		applyShadowIe(mrm.$('div[class*="shadow"]'));
	}
});

mrm.$(function() {
	mrm.$('#brandlogo').clone().insertBefore('#gMdsContent').css('display','none');
	mrm.$('<hr id="printLogoDiv"/>').css('display','none').insertBefore('#gMdsContent');
});
