/*Protocol Re-direct for SSL*/

function redirectPageBasedOnSSL() {
            //only swap protocols when on UAT and PROD. Avoid TEST
            if( location.href.indexOf( "://test" ) == -1) {
                if(typeof(remain_ssl) == "undefined") {
                    if(location.protocol == "https:") {
                        window.location = location.href.split("https:").join("http:");
                    }        
                } else {
                    if(location.protocol == "http:") {
                        window.location = location.href.split("http:").join("https:");
                    }
                }
            } 
}

if(!getParameter('disable_ssl_redirect')){
    redirectPageBasedOnSSL();
}
function setZip(zip){
	Cookie.set('zipcode',zip);
}

/*This method takes a string from dealer XML and 
returns the appropriate format based on string length.*/

function formatXMLValue(xmlData){
	var xmlDataLength = xmlData.length;
	
	//Phone
	if(xmlDataLength == 10){
	     var areaCode = xmlData.substring(0,3);
	     var phonePrefix = xmlData.substring(3,6);
	     var phoneLineNumber = xmlData.substring(6);
	     xmlData = "("+areaCode+") " + phonePrefix + "-" + phoneLineNumber;
	}
	
	//Long Zip
	if(xmlDataLength == 9){
	     var zip1 = xmlData.substring(0,5);
	     var zip2 = xmlData.substring(5);
	     xmlData = zip1 + "-" + zip2;
	}
	
	return xmlData;
}

//REMOVE AFTER ESPIFF CAMPAIGN
function buildESPIFF() {
	var message = "Are you sure you want to sign up for this extra $500 Cash allowance?";
	var content = $('main_content');
	var div = new Element('div', {'id': 'adjust_dealer','class': 'adjust_dealer'});
	var para = new Element('p');
	var span = new Element('span');
	var anch = new Element('a').setProperty('href', '#');
	para.setHTML(message).injectInside(div);
	anch.clone().addEvent('click', function() { eventESPIFF(true) }).setHTML(glossary_label_yes_please).injectInside(span);
	anch.clone().addEvent('click', function() { eventESPIFF(false) }).setHTML(glossary_label_no_thanks).injectInside(span);
	span.injectInside(div);
	div.injectInside(content);
}

function espiff(app, family) {
	family = family.substring(4);
	if(family == "commander" || family == "liberty"){
		var espiffUrl = "https://wsprod.bbdodetroit.com/launch/2008BrandeSpiff.jsp?pageid=" + app + "&vehid=" + family;
    //flexWin(espiffUrl,'yes','715','600','espiff','no');
	}
}

function eventESPIFF(go) {
	if (go) {flexWin('https://wsprod.bbdodetroit.com/launch/2008BrandeSpiff.jsp?pageid=promo&vehid='+cur_vehicle,'yes','715','600','espiff','no');}
	$('adjust_dealer').remove();
}
//REMOVE AFTER ESPIFF CAMPAIGN



/* onload handler */
var window_onload = new Array;
var onloadRef = window.onload;
var cur_section;
var populate_zip;
var audio_on_text;
var audio_off_text;
var es_confirm_apps;

/*
    window.ie - will be set to true if the current browser is internet explorer (any).
	window.ie6 - will be set to true if the current browser is internet explorer 6.
	window.ie7 - will be set to true if the current browser is internet explorer 7.
	window.khtml - will be set to true if the current browser is Safari/Konqueror.
	window.gecko - will be set to true if the current browser is Mozilla/Gecko.
*/

if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.khtml = true;
else if (document.getBoxObjectFor != null) window.gecko = true;

window.onload = function() {
  if(onloadRef != null) {
    onloadRef();
  }
	//for(var i =  window_onload.length; i >= 0; i--){ //Why is this running backwards?
	for(var i = 0; i < window_onload.length; i++){
    eval( window_onload[i]);
  }
};

function onload_register(func){
 window_onload.push(func);
}
/* end onload handler */

/* navigation menus */
var cur_menu;
var cur_sub_menu;
var isFormOpen;
var toggle, toggleOpen;
var curClassName = "";
var form_elements_to_turn_on = new Array();

/* Set up menu elements for mouse events */
function setup_menus(){

	var timer;
	$$('div.features_menu').each(function(f){
		f = $(f);
		var fmc = $(f.getLast());
		var menuWidth = 4;
		fmc.getFirst().getChildren().each(function(lc){
			if(lc.hasClass('link_container')){
				menuWidth = menuWidth + parseInt($(lc).getSize().scrollSize.x);
			}
		});
		/*fmc.setStyle("width", menuWidth + "px");*/ 
		fmc.setStyle("width", (menuWidth+1) + "px"); //need to expand nav width by 1 pixel to accomodate MY09 changes

		if ((f.getPosition().x - $('wrapper').getPosition().x) + f.getSize().scrollSize.x + (menuWidth / 2) > 960){
			var menuOffSet = -(f.getPosition().x - $('wrapper').getPosition().x) + 960 - menuWidth;
		}
		else{
			var menuOffSet = 0 - (menuWidth / 2) + (f.getSize().scrollSize.x / 2);
		}
		/*fmc.setStyle("left", (menuOffSet) + "px");*/
		fmc.setStyle("left", (menuOffSet-1) + "px"); //need to move left by 1 pixel to accomodate MY09 changes

		f.onmouseover = function(){
			if(this.timer){clearTimeout(this.timer);}
			this.menuBuffer = setTimeout("checkMenus('"+this.id+"_container')", 200);
		}

		f.onmouseout = function(){
			if(!isFormOpen){
				if(this.menuBuffer) { clearTimeout(this.menuBuffer); }
				this.timer = setTimeout("hide('"+this.id+"_container')", 200);
			}
		}
	});

	$('brand_menus').getChildren().each(function(m){
		$(m).onmouseover = function(){
			if($(m).id != "dealer_finder"){
				if(this.timer){clearTimeout(this.timer);}
				this.menuBuffer = setTimeout("checkMenus('"+this.id+"_container')", 200);
			}
		}

		$(m).onmouseout = function(){
			if(!isFormOpen){
				if($(m).id != "dealer_finder"){
					if(this.menuBuffer) { clearTimeout(this.menuBuffer); }
					this.timer = setTimeout("hide('"+this.id+"_container')", 1);
				}
			}
		}
	});

	$$('.menu_select_field').each(function(f){
		$(f).onfocus = function(){
			formMenuHolder(true);
		}
		/*$(f).onchange = function(){
			formMenuHolder(true);
		}*/
		$(f).onblur = function(){
			formMenuHolder(false);
		}
	});

	$$('.sub_menu_btn').each(function(s){
		$(s).onclick = function(){
			toggleSubMenu(this.getNext());
		}
	});
	$$('.button_list_menu_btn').each(function(s){
		$(s).onclick = function(){
			toggleSubMenu(this.getNext());
		}
	});
}

function formMenuHolder(argValue){
    isFormOpen = argValue;
}

/* Check to see what the current menu status is */
function checkMenus(whichMenu){
    /*if(cur_menu != whichMenu && self.cur_menu){
			hide(cur_menu);
    }*/
    if(cur_menu != whichMenu){
        show(whichMenu);
        cur_menu = whichMenu;
    }
}

function setFX(el, attrib, dur){
  return new Fx.Style(el, attrib, {duration: dur});
}

/* Turn on New Menu */
function show(whichMenu) {
	//blur all open select boxes and hide the open menu (but only if a form select is open)
	if(isFormOpen){
		$$('.menu_select_field').each(function(f) {
			f.blur();
		});
		if(cur_menu){
			hide(cur_menu);
		}
	}
	var menu = $(whichMenu);

	//Find nav link and add hover state
	if(menu.hasClass('features_menu_container')){
		var menu_children_arr = menu.getParent().getChildren();
		var menu_link = menu_children_arr[0];

		if (curClassName != "vehicle_feature_nav_link_on")
			curClassName = "vehicle_feature_nav_link";

		menu_link.removeClass('vehicle_feature_nav_link');
		menu_link.addClass('vehicle_feature_nav_link_on');
	}
	else {
		var menu_link = menu.getPrevious();
		menu_link.addClass('brand_menu_link_on');
	}

	var menuHeight = menu.getSize().scrollSize.y;
	//menu.setStyles({'overflow':'visible', 'height':menuHeight +'px'});
	var menuWidth = menu.getSize().scrollSize.x;

	/*toggleOpen = setFX(menu, 'height', 200).addEvent('onStart', function() {
		menu.setStyle('visibility', 'visible');
		menu.setStyle('border-style', 'solid');
	});*/

	var menuX = menu.getPosition().x;
	var menuY = menu.getPosition().y;

	if(window.ie6){
		$$('select').each(function(s) {
			if (s.className != "menu_select_field") {
				var elX = s.getPosition().x;
				var elY = s.getPosition().y;
				//if ((element begins between the left and right edge of the menu) OR (element starts to the left of the menu, but extends into the area))
				if ((elX  > menuX && elX  < (menuX + menuWidth)) || ( ((elX + s.getSize().scrollSize.x) > menuX ) && (elX < menuX))) {
					// if (element is contained within the vertical space occupied by the menu)
					if (elY > menuY && elY < (menuY + menuHeight)) {
						s.setStyle('visibility', 'hidden');
						form_elements_to_turn_on.push(s);
					}
				}
			}
		});
	}
	//toggleOpen.start(menuHeight);
	menu.setStyle('height', menuHeight+"px");
	menu.setStyle('visibility', 'visible');
	menu.setStyle('border-style', 'solid');

	//var toggle = new Fx.Style(menu, 'height',{duration: 200, onComplete:infoOpened});
	//toggleOpen.start(menuHeight);

	isFormOpen = false;
}

/* Turn off Current Menu */
function hide(whichMenu) {
	/* if a sub menu is open on my menu, close it.
	Reset cur_sub_menu so the other menu sub menus can open/close as needed */
	if ($(cur_sub_menu)) {
		if($(cur_sub_menu).getParent().id == whichMenu){

			$(cur_sub_menu).getLast().setStyle('height','0px');
		    $(cur_sub_menu).getLast().setStyle('display', 'none');

			var link = $(cur_sub_menu).getFirst();
			link.removeClass('sub_menu_btn_at');
			link.addClass('sub_menu_btn');
			cur_sub_menu = "";
		}
	}
	//toggleOpen.stop();
	cur_menu = null;
	var menu = $(whichMenu);

	//menu.setStyles({'overflow':'hidden', 'height':'0px'});
	if ($('flyouts')) { swapFlyout(''); }
	/*toggle = setFX(menu, 'height', 200).addEvent('onComplete', function(){
		if (menu.getStyle('height').toInt() == 0) {
			menu.setStyle('visibility', 'hidden');
		}

		//Find nav link and remove hover state
		if(menu.hasClass('features_menu_container')){
			var menu_children_arr = menu.getParent().getChildren();
			var menu_link = menu_children_arr[0];
			menu_link.removeClass('vehicle_feature_nav_link_on');
			menu_link.addClass(curClassName);
		}
		else {
			var menu_link = menu.getPrevious();
			menu_link.removeClass('brand_menu_link_on');
		}
		for (var t = 0; t < form_elements_to_turn_on.length; t++) {
			form_elements_to_turn_on[t].setStyle('visibility', 'visible');
		}
		form_elements_to_turn_on = [];
	});
	toggle.start(0);*/
	if(menu.hasClass('features_menu_container')){
		var menu_children_arr = $(menu.getParent()).getChildren();
		var menu_link = menu_children_arr[0];
		menu_link.removeClass('vehicle_feature_nav_link_on');
		menu_link.addClass(curClassName);
	}else{
		var menu_link = menu.getPrevious();
		menu_link.removeClass('brand_menu_link_on');
	}
	for(var t = 0; t < form_elements_to_turn_on.length; t++){
		form_elements_to_turn_on[t].setStyle('visibility', 'visible');
	}
	form_elements_to_turn_on = [];
	menu.setStyle('height','0px');
	menu.setStyle('visibility', 'hidden');
}

/* Toggle sub menu`s in the current main menu */
function toggleSubMenu(whichMenu){
  var menu = $(whichMenu);

  // This line allows Safari to pick up the actual height of the about-to-open menu div
  menu.setStyle('display', 'block');

  var menuHeight = menu.getSize().scrollSize.y;
  var parent = $(menu.getParent().getParent().id);
  var parent_button_id = menu.getParent().id;
  var parentHeight = parent.getSize().scrollSize.y;
  var closeHeight = 0;
  var toggleParent = new Fx.Style(parent, 'height',{duration: 300});

  //If there is a menu open already, close it
  if(parent_button_id != cur_sub_menu && self.cur_sub_menu){
    var menu_to_close = $(cur_sub_menu).getLast();
		if(menu_to_close.className != "button_list_wrapper_closed" && menu.className != "button_list_wrapper_closed"){
			closeHeight = $(menu_to_close).getStyle('height').toInt();
			var toggle_last = new Fx.Style(menu_to_close, 'height',{duration: 300}).addEvent('onComplete', function(){
				menu_to_close.setStyle('display', 'none');
			});
			toggle_last.start(0);

			var cur_link = $(cur_sub_menu).getFirst();
			cur_link.removeClass('sub_menu_btn_at');
			cur_link.addClass('sub_menu_btn');

			cur_sub_menu = "";
		}
	}

  //Open the menu that was clicked
  if(parent_button_id != cur_sub_menu && menu.getStyle('height') == "0px"){
		if(closeHeight > menuHeight){formMenuHolder(true);}
		var toggle = new Fx.Style(menu, 'height',{duration: 300}).addEvent('onComplete', function(){
			formMenuHolder(false);
		});

	menu.setStyle('display', 'block');
	toggleParent.start(parentHeight + menuHeight - closeHeight);
    toggle.start(menuHeight);
    cur_sub_menu = parent_button_id;

    var link = menu.getParent().getFirst();

    link.removeClass('sub_menu_btn');
    link.addClass('sub_menu_btn_at');

  }else{
    //this is the close click for the menu
	var toggle = new Fx.Style(menu, 'height',{duration: 300}).addEvent('onComplete', function(){
		menu.setStyle('display', 'none');
	});
    toggle.start(0);
    toggleParent.start(parentHeight - menuHeight);
    //if closing the only open menu, reset cur_sub_menu
    cur_sub_menu = "";

    var link = menu.getParent().getFirst();

    link.removeClass('sub_menu_btn_at');
    link.addClass('sub_menu_btn');
  }
}


function show_vehicle_menu(){
	show_menu = true;
	if(typeof AUTOMATICALLY_SHOW_VEHICLE_MENU != 'undefined') {
		show_menu = AUTOMATICALLY_SHOW_VEHICLE_MENU;
	}
	if(show_menu == true) {
		$('vehicle_menu').onmouseover();
		$('vehicle_menu').timer =  setTimeout("hide($('vehicle_menu_container'))", 5000);		
	}
}


function show_shopping_menu(){
	$('shop_menu').onmouseover();
	$('shop_menu').onmouseout = function(){};// override to do nothing
	//$('shop_menu').timer =  setTimeout("hide($('shop_menu_container'))", 5000);
}
/* end navigation menus */

/* vehicle as shown info */
var infoShown = false;
var inTransition = false;
var s;
var init_y_pos_info_container;
var content_div_offset;
var vehicle_pricing_block_height;

function vehicle_info_setup(){
	var vehicle_info = $('vehicle_shown_info');
	init_y_pos_info_container = $('vehleftarrow').getTop();
	content_div_offset = $('content').getTop();
	vehicle_pricing_block_height = $('vehicle_pricing_background').getSize().size.y;
	if(vehicle_info){
		var info_block_height = $('vehicle_shown_info_detail').getSize().scrollSize.y;
		vehicle_info.addEvent('mouseover', function(){
			clearTimeout(s);
			if(infoShown == false && inTransition == false) {
				inTransition = true;
				linkTrack("as_shown", "roll_over");
				new Fx.Style('vehicle_shown_info_detail','height',{duration:100, onComplete:infoOpened}).start(info_block_height);
				if (brand_id == "dodge"){
					new Fx.Style('vehicle_shown_info_container','top',{duration:100}).start(init_y_pos_info_container - info_block_height - content_div_offset);
					new Fx.Style('vehicle_pricing_background','top',{duration:100}).start(init_y_pos_info_container - info_block_height - content_div_offset - vehicle_pricing_block_height);
					new Fx.Style('vehicle_pricing','top',{duration:100}).start(init_y_pos_info_container - info_block_height - content_div_offset - vehicle_pricing_block_height);
				}
				//if ($('miles_per_gallon')){$('miles_per_gallon').setStyle("visibility", "hidden");}
				$('vehleftarrow').addClass("downarrow");
				$('detail').addClass("detail_highlight");
				return false;
			}
		});
		
		vehicle_info.addEvent('mouseout', function(){
			s = setTimeout(hideInfo, 50);
		});
	}
}

function hideInfo(){
  if(infoShown == true && inTransition == false) {
		inTransition = true;
		new Fx.Style('vehicle_shown_info_detail','height',{duration:200, onComplete:infoClosed}).start(0);
		if (brand_id == "dodge"){
			new Fx.Style('vehicle_shown_info_container','top',{duration:200}).start(init_y_pos_info_container - content_div_offset);
			new Fx.Style('vehicle_pricing_background','top',{duration:200}).start(init_y_pos_info_container - content_div_offset - vehicle_pricing_block_height);
			new Fx.Style('vehicle_pricing','top',{duration:200}).start(init_y_pos_info_container - content_div_offset - vehicle_pricing_block_height);
		}
		if ($('miles_per_gallon')){$('miles_per_gallon').setStyle("visibility", "visible");}
		$('vehleftarrow').removeClass("downarrow");
		$('detail').removeClass("detail_highlight");
		return false;
	}
}

function fade_down_model_info(){
	$('vehicle_shown_info_container').setStyle("visibility", "hidden");
	$('vehicle_pricing_background').setStyle("visibility", "hidden");
	$('vehicle_pricing').setStyle("visibility", "hidden");
	$$('#vehicle_pricing p').setStyle("visibility", "hidden");
	//if ($('miles_per_gallon')){$('miles_per_gallon').setStyle("visibility", "hidden");}
}

function fade_up_model_info(){
	$('vehicle_shown_info_container').setStyle("visibility", "visible");
	$('vehicle_pricing_background').setStyle("visibility", "visible");
	$('vehicle_pricing').setStyle("visibility", "visible");
	$$('#vehicle_pricing p').setStyle("visibility", "visible");
	if ($('miles_per_gallon')){$('miles_per_gallon').setStyle("visibility", "visible");}
}

function check_pricing(){
	$$('.as_shown_p').each(function(as_p){
		var as_p = $(as_p);
		if(as_p.getLast().innerHTML == "X"){
			as_p.setHTML(as_p.innerHTML.replace(/\s\$/g,' '));
			as_p.getLast().innerHTML = glossary_label_see_dealer;
		}
	});
	$$('.starting_at_p').each(function(start_p){
		var start_p = $(start_p);
		var start_val = start_p.getLast().innerHTML;
		(start_val == "X")?	start_p.setHTML(glossary_label_pricing_avail_soon) : $(start_p.getNext()).setStyle('visibility', 'visible');
		start_p.setStyle('visibility', 'visible');
	});
}

var as_shown_holder = 0;
function update_pricing(num){
	var asp = $('as_shown_price');
	if(asp){
		num = parseInt(num);
		if(as_shown_holder == 0)as_shown_holder = parseFloat((asp.innerHTML.split(',')).join(""));
		num += as_shown_holder;
		if(!isNaN(num))	asp.setHTML(comma_format(num));
	}
}
function comma_format(num){
	var n = new String(num);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	return a.join(",");
}

function infoOpened() {
	infoShown = true;
	inTransition = false;
}

function infoClosed() {
	infoShown = false;
	inTransition = false;
}
/* end vehicle as shown info */


// the variable to hold the flash name
var flashName;
var seedID = Math.floor(Math.random()*11111);
/*Turn on rendering div*/
function showFlash(argSwf,argElement,argFlashVars,overrideLowBand){
if($(argElement)) {
	// if we have main content lets temporarily clone it for the print stylesheet
	if(argElement == "main_content") {
		if ($(argElement).getFirst() && $('promo_background')){
			var clone = $(argElement).getFirst().clone().injectAfter('promo_background');
			clone.addClass('print');
			clone.setProperty('id', 'clone');
			var myArray = $$('#clone li');
			for(var i=0; i<myArray.length; i++) {
				myArray[i].setProperty('id', '');
			}
			myArray = $$('#clone a');
			for(var i=0; i<myArray.length; i++) {
				myArray[i].setProperty('id', '');
			}
			myArray = $$('#clone div');
			for(var i=0; i<myArray.length; i++) {
				myArray[i].setProperty('id', '');
			}
			myArray = $$('#clone ul');
			for(var i=0; i<myArray.length; i++) {
				myArray[i].setProperty('id', '');
			}
			myArray = $$('#clone p');
			for(var i=0; i<myArray.length; i++) {
				myArray[i].setProperty('id', '');
			}
			myArray = $$('#clone span');
			for(var i=0; i<myArray.length; i++) {
				myArray[i].setProperty('id', '');
			}
		}
	}

	if(argElement == "model_image") {
		var clone = $(argElement).getFirst().clone().injectAfter('colors');
		clone.addClass('print');
	}

	// cache buster for IE7 redraw issues
	if(argElement == "promos") {
		argSwf+= "?r=" + new Date().getTime();
	}

	var individualID = Math.floor(Math.random()*11111);
	/*
	    Prepare to load in the Flash rendering engine.
	    Uses Unobtrusive Flash Objects by Bobby van der Sluis
	    http://www.bobbyvandersluis.com/ufo/
	*/

	var isSafari = "";
 	navigator.userAgent.indexOf("Safari")>= 0 ? isSafari = true : isSafari = false;

	var isLTOpera92 = "";
 	navigator.userAgent.indexOf("Opera") >= 0 && parseFloat(navigator.appVersion) < 9.2 ? isLTOpera92 = true : isLTOpera92 = false;

	//Should Flash even be shown? (does user want it / can their browser support Flash 8 functionality)


	if ((userData.bandwidth != "low" && isLTOpera92 == false) || overrideLowBand ) {

    var site_config = {
    	'host':location.host,
        'src':location.href,
        'title':document.title,
    	'isSafari':isSafari,
    	'isLTOpera92':isLTOpera92,
    	'asset_path':'en',
    	'EOF':'EOF'
    };

    if(typeof(userData.zipcode) != "undefined") {
    	site_config['zip'] 			= userData.zipcode;
    }
    if( (typeof(cur_year) !="undefined" && cur_year != '') && typeof(cur_vehicle) !="undefined") {
    	site_config['cur_vehicle']	= vehicle_data[cur_year][cur_vehicle].apps.trilogy;
    }
    if(typeof(brand) != "undefined") {
    	site_config['brand'] 		= brand
    }
    if(typeof(embedded_disclaimers) != "undefined") {
    	site_config['embedded_disclaimers'] = Json.toString(embedded_disclaimers);
    }

	



	var flash_vars = '';
	for(k in site_config) {
		if (k != "toJSONString") {
    		flash_vars += "&" + k + "=" + encodeURIComponent(site_config[k]);
		}
	}

	// deep link & query strings
	if(location.href.indexOf("?") != -1) {
		// if we have a src in the query we need to strip it out to avoid overwrite
		if(location.href.indexOf("src=") != -1) {
			// split on the src
			var queryCleanedArray = location.href.split("src=");
			// if we have additional values past the src value
			if(queryCleanedArray[1].indexOf("&") != -1) {
				// remove the src altogether
				queryCleanedArray[1] = queryCleanedArray[1].substring(queryCleanedArray[1].indexOf("&")+1, queryCleanedArray[1].length);
			} else {
				// set the val to empty
				queryCleanedArray[1] = "";
			}
			// join on empty
			var cleanedVersion = queryCleanedArray.join("");
			flash_vars += "&" + cleanedVersion.substr(location.href.indexOf("?")+1);
		} else {
			flash_vars += "&" + location.href.substr(location.href.indexOf("?")+1);
		}
	}

	// add local connect sound vars
	flash_vars += "&localconnect_seed=" + seedID;
	flash_vars += "&localconnect_id=" + individualID;
	if(userData.audiopref == "on"){
		flash_vars += "&audio_pref=on";
	}else if(userData.audiopref == "off"){
		flash_vars += "&audio_pref=off";
	}else{
		flash_vars += "&audio_pref=off";
	}
	// add text size preference
	if(typeof(userData.featureTextSize) == "number"){
		flash_vars += "&text_size="+userData.featureTextSize;
	}

	//flash_vars += "&argMLC=" + hbx.mlc;
	if ( $(argElement) ) {
		var render_foo = document.getElementById(argElement);
		render_foo.style.display = 'block';
	}

	// set the name fo the flash based on the div
	flashName = argElement +  '_flash';
	
	// pass the containing div height and width
	flash_vars += "&stageWidth="+parseInt($(argElement).getStyle('width'))+"&stageHeight=" + parseInt($(argElement).getStyle('height')); 

	if(argFlashVars != null) {
		flash_vars += argFlashVars;
	}
	var debug_html = getParameter('flash');
	var flash_version;
	if(debug_html == "false" && debug_html !=  ""){
		flash_version = 10;
	}else{
		flash_version = 8;
	}
	var FO = {
	    movie:        argSwf,
	    width:        "100%",
	    height:       "100%",
	    name:	  	   flashName,
	    id:		  flashName,
	    allowscriptaccess:"always",
	    bgcolor:      "#FFFFFF",
	    scale:        "noscale",
	    wmode:        "transparent",
	    play:         "true",
	    quality:      "high",
	    menu:         "false",
	    majorversion: flash_version,
	    build:        "0",
	    xi:           "false",
	    flashvars:    flash_vars
	};
	UFO.create(FO, argElement);

	//these 2 lines are handled in the UFO.create function.
	//var renderElement = document.getElementById(argElement);
	//renderElement.style.visibility = 'visible';
	} else {
		$(argElement).style.visibility = 'visible';
		// the promo div had this class initially, but older browsers would improperly place the div when it conatined Flash.
		if ($('promos')){
			$('promos').style.overflow = 'auto';
			setlowbanddaalink();
			}
		}
	}
}

// External Interface hack for IE out of memory error
function nullFlashLoopFunction() { __flash_savedUnloadHandler = null; }
window.onbeforeunload = nullFlashLoopFunction;

function hasFlashMin(){
	var debug_html = getParameter('flash');
	var flash_version;
	if(debug_html == "false" && debug_html !=  ""){
		flash_version = 10;
	}else{
		flash_version = 8;
	}
	return(UFO.hasFlashVersion(flash_version,0));
}

function setAudio() {
	if ($('audio_text').innerHTML == audio_off_text){
		$('audio_text').setHTML(audio_on_text);
		window.document["audio_controller_flash"].SetVariable("audio_pref", "off");
		window.document["audio_controller_flash"].change(); // telling Flash to turn the sound off
		userData.audiopref = "off";
	}else{
		$('audio_text').setHTML(audio_off_text);
		window.document["audio_controller_flash"].SetVariable("audio_pref", "on");
		window.document["audio_controller_flash"].change();  // telling Flash to turn the sound on
		userData.audiopref = "on";
	}
	Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
}


var disclaimersShown = false;
var logosShown = true;
function showDisclaimers(){
	
	if(disclaimersShown){
		if ($('disclaimers')){
			$('disclaimers').setStyle('display', 'none');
		}
		disclaimersShown = false;
	}else{
		$('logo_links').setStyle('display','none');
		$('logo_link_topper').setStyle('display', 'none');
		$('brand_tab').removeClass('b_border');
		logosShown = false;
		if ($('disclaimers')){
			$('disclaimers').setStyle('display', 'block');
			disclaimersShown = true;
		}
	}
	$('legal_tab').toggleClass('b_border');
}
function showLogos(){
	
	if(logosShown){
		$('logo_links').setStyle('display', 'none');
		$('logo_link_topper').setStyle('display', 'none');
		logosShown = false;
	}else{
		if ($('disclaimers')){
			$('disclaimers').setStyle('display','none');
			$('legal_tab').removeClass('b_border');
			disclaimersShown = false;
		}
		$('logo_links').setStyle('display', 'block');
		$('logo_link_topper').setStyle('display', 'block');
		logosShown = true;
	}
	$('brand_tab').toggleClass('b_border');
				
}
/*Universal function to get parameter from url srting */
function getParameter(aP){var qS = new String(location.search.substring(1,location.search.length));var p = qS.split("&");var val = "";if(aP){for(i=0;i<p.length;i++){if(p[i].split( "=" )[0] == aP){val = p[i].split( "=" )[1];}}return val;}}
function wrap(argApp, argMisc, argFamily, argModel) {

  argApp = argApp.toLowerCase();
  var sizedWin = false;

  var model_year = argFamily.substr(0,4);
	if (isNaN(model_year)) {
		model_year = "";
	} else {
		//year must be prepended, so family var is what is left after the four digit year
		argFamily = argFamily.substr(4);
	}

	var launchUrl = getDomain() + "/bridge/index.html?";
  if( argMisc != '' ) launchUrl += argMisc + "&";

	if (argMisc.indexOf( "zipcode" ) == -1 && !isNaN(populate_zip)) {
		launchUrl += "zipcode=" + populate_zip + "&";
	}

  launchUrl += "app=" + argApp + "&family=" + argFamily + "&model=" + argModel + "&year=" + model_year;

  if( argApp == "chrome" || argApp == "edmunds" || argApp == "cf_pmt_est" || argApp == "cf_app_cred" ) {
    sizedWin = true;
	var app_width;
	var winHeight;
	var options = "";
	if (argApp == "chrome" || argApp == "edmunds") {
		app_width = 840;
		winHeight = ( window.screen.availHeight - 130 );		
		options = "resizable,scrollbars,toolbar,";
	} else if (argApp == "cf_app_cred") {
		app_width = 770;
		winHeight = ( window.screen.availHeight - 130 );		
		options = "scrollbars=yes,toolbar=yes,resizable=yes,status=yes,location=yes,menubar=yes,";	
	} else if (argApp == "cf_pmt_est") {
		app_width = 715;
		winHeight = 580;				
		options = "scrollbars=no,toolbar=no,resizable=yes,status=no,location=no,menubar=no,";
	}	
    var winWidth = app_width;
	options += "width=" + winWidth + ",height=" + winHeight;
    if( window.screen ) {
      var xPos = ( screen.availWidth - winWidth ) / 2;
      var yPos = ( ( screen.availHeight - winHeight ) / 2 ) - 40;
      options += ",left=" + xPos + ",screenX=" + xPos;
      options += ",top=" + yPos + ",screenY=" + yPos;
    }
  }

	if (es_confirm_apps){
		if(confirm(glossary_def_jp_application_confirm_statement)){
			if(sizedWin) {
			window.open( launchUrl, "Application", options );
			} else {
			window.location = launchUrl;
			}
		}
	} else {
		if(sizedWin) {
			window.open( launchUrl, "Application", options );
		} else {
			window.location = launchUrl;
		}
	
	}
}

// get proper domain for global navigation images and links
function getDomain( argLink ) {
    var curUrl = document.location.href;
    var newUrl = "";
    var thisDomain = "jeep.com";

    if( curUrl.indexOf( "iw-mount" ) >= 0  || curUrl.indexOf( "organic" ) >= 0 )  {
        // preserve virtualization
        newUrl = "";
    } else if( curUrl.indexOf( "://test" ) >= 0 ) {
        newUrl = "http://test";
    } else if( curUrl.indexOf( "://uat" ) >= 0 ) {
        newUrl = "http://uat";
    } else {
        newUrl = "http://www";
    }
    if (newUrl != ""){
     newUrl = newUrl + "." + thisDomain;
    }
    if( argLink ) {
        if( argLink.indexOf( "javascript:" ) >= 0 || argLink.indexOf( "/" ) != 0 ) {
            return argLink;
        } else {
            return newUrl + argLink;
        }
    } else {
        return newUrl;
    }
}

// get proper domain and http protocal for global navigation sourced images, styles, and target links
function getDomainImg( argLink ) {
    var curUrl = document.location.href;
    var newUrl = getDomain();
    var protocol = "";

    if(curUrl.indexOf("-5") >= 0){
     protocol = curUrl.indexOf("https:") >= 0 ? "https://":"http://";
     if(protocol == "https://"){
     var newUrlSplit = newUrl.split( "://" )[1];
     newUrlSplit = newUrlSplit.replace( /\./, "-5." );
     newUrl =  protocol + newUrlSplit;
     }
    }
  return newUrl;
}

// Please note these list of arguments (except the 'tabName') are for the signature of current function  wrap (so, if you modify the wrap function, please modify the signation of
// callVehicleCompare function) accordingly
function callVehicleCompare(tabName, argApp, argTracking, argFamily, argModel) {
     if((typeof(trilIsCompareSpec) == 'undefined') || (trilIsCompareSpec == null) || (typeof(changeTab) == 'undefined')) {
             wrap(argApp, argTracking, argFamily, argModel);
      } else {
              changeTab(tabName);
     }
}
function flexWin(aU,aS,aW,aH,aN,aO,aX,aY,aC){
 var wN = aN ? aN : "myWin" + nocacheRandom();
 var oV = aO == "all" ? 1 : 0;
 var oS = "history="+oV+",toolbar="+oV+",location="+oV+",directories="+oV+",status="+oV+",menubar="+oV+",resizable="+oV;
 var wO = aO != "all" ? aO : oS;
 var wW = aW ? aW : 800;wO += ",width=" + wW;
 var wH = aH ? aH : 600;wO += ",height=" + wH;
 var sB = ",scrollbars="+aS;wO+=sB;
 var wX = aX ? aX :(screen.availWidth-wW)/2;wO+=",left="+wX+",screenX="+wX;
 var wY = aY ? aY :((screen.availHeight-wH)/2)-40;wO+=",top="+wY+",screenY="+wY;
 //temporary code for 9/15 to handle CF integration from MoMS Pmt Est buttons
 //to be removed for M09 when those pages are generated.
 if (aU.indexOf("tname=cf_payment") > -1){
	wrap('cf_pmt_est','zipcode='+populate_zip,cur_year+cur_vehicle,'');
 } else {
	window.open(aU,wN,wO);
	aC ? window.close():"";
 }
}

function flexWinEnglish(aU,aS,aW,aH,aN,aO,aX,aY,aC){
 var wN = aN ? aN : "myWin" + nocacheRandom();
 var oV = aO == "all" ? 1 : 0;
 var oS = "history="+oV+",toolbar="+oV+",location="+oV+",directories="+oV+",status="+oV+",menubar="+oV+",resizable="+oV;
 var wO = aO != "all" ? aO : oS;
 var wW = aW ? aW : 800;wO += ",width=" + wW;
 var wH = aH ? aH : 600;wO += ",height=" + wH;
 var sB = ",scrollbars="+aS;wO+=sB;
 var wX = aX ? aX :(screen.availWidth-wW)/2;wO+=",left="+wX+",screenX="+wX;
 var wY = aY ? aY :((screen.availHeight-wH)/2)-40;wO+=",top="+wY+",screenY="+wY;
	if(confirm(glossary_def_jp_application_confirm_statement)){
		window.open(aU,wN,wO);
	}
 aC ? window.close():"";
}

function englishRedirect(argUrl,whichWindow,justalert) {
	if(confirm( glossary_def_jp_application_confirm_statement)){
    if(justalert == 'yes'){
		} else {
	    if(whichWindow == ''){window.location = argUrl;}
	    else{window.open(argUrl);}
		}
	}
}

function demoAlert(){ 
	if(confirm(glossary_def_jp_application_confirm_statement)){ 
	return true; 
		}else { 
	return false; }
}

function O_LC_ES(){
	if(demoAlert())O_LC();
}

function nocacheRandom(){var axel = Math.random() + "";var ord = axel * 1000000000000000000;return ord;}

function highlightVehicleNav(){

	  if(cur_section == "features"){
        
		$(cur_section).addClass("vehicle_feature_nav_link_at");
		$(cur_section).getParent().addClass("right_hover"); 
		$(cur_section).getParent().getParent().addClass("left_hover"); 
    
	}else if(cur_section != null && cur_section != "features" && $(cur_section)){
	    
		if($(cur_section)) {
			$(cur_section).addClass("vehicle_nav_link_at");
		}
		$(cur_section).getParent().addClass("right_hover"); 
		$(cur_section).getParent().getParent().addClass("left_hover"); 
		

	}
}

function setBandwidth(bandwidth) {
	userData.bandwidth = bandwidth;

	//Bake the userData cookie
	Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});

	//Refresh the page (requires JS 1.2)
	window.location.reload( false );
}

function muteAudio(val) {
	userData.muteAudio = val;

	//Bake the userData cookie
	Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
}


var userData = new Object;
function getUserData(){

	cookieUserData = Cookie.get('userdata');

	if(cookieUserData) {
		//Decompress JSON values of userData
		userData = eval('(' + cookieUserData + ')');
	}

	if(Cookie.get('zipcode')) {
		userData.zipcode = Cookie.get('zipcode');
	}

	//Bake the userData cookie
	Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
	setUserPreferences();
	setUserSegment();
	handleAkamaiLowBand();
}

function handleAkamaiLowBand() {
	//Bandwidth detection based on Akamai cookie
	ak_cookie = Cookie.get('CT_Akamai');
	if(ak_cookie && !userData.bandwidth) {
		ak_bandwidth = ak_cookie.split("throughput=");
		if(ak_bandwidth[1]) {
			if(ak_bandwidth[1].split(",")[0] == "low") {
				userData.bandwidth = "low";				

				var html_contents = "";
				html_contents += '<div id="akamai_lowband">';
				html_contents += '<img src="/en/images/ak_select_title.gif" class="ak_title" />';
				html_contents += "We've detected that you are using a slower connection to access the site.<br />To provide a great experience for all users we offer two versions of our site.<br />";
				html_contents += "<strong>The slower connection speed detected indicates that you may wish to select our low-bandwidth site.</strong>";
				html_contents += '<a href="javascript:setBandwidth(\'low\');"><img src="/en/images/ak_select_low.gif" /></a>';
				html_contents += "<span class='ak_link_desc'><strong>Recommended for users with dialup/modem or slower connections.</strong><br />Images optimized and videos removed to reduce download times.</span>";
				html_contents += '<a href="javascript:setBandwidth(\'high\');"><img src="/en/images/ak_select_high.gif" /></a>';
				html_contents += "<span class='ak_link_desc'><strong>Recommended for users with cable modem, DSL or other broadband connection speeds.</strong><br />Contains videos, animations and audio best experienced with a high-speed internet connection.</span>";
				html_contents += "<span class='ak_link_footer'>You can change your bandwidth setting at any time by selecting the <u>Low/High Bandwidth Version</u> setting in the page footer</span>";
				html_contents += '</div>';

				showHTML(html_contents);
			}
		}
	}
}

function setUserPreferences(){

	if (((location.toString()).indexOf("com/es/") != -1)||((location.toString()).indexOf("htdocs/es/") != -1)){
		audio_on_text = "Audio Activado";
		audio_off_text = "Audio Desactivado";
		es_confirm_apps = true;
	}else{
		audio_on_text = "Audio On";
		audio_off_text = "Audio Off";
		es_confirm_apps = false;
	}

	/*All Zip Code boxes*/
	populate_zip = Cookie.get('zipcode');
	if (!populate_zip){
		populate_zip = userData.zipcode;
	}
	$$('input').each(function(zip_input){
		if(zip_input.name == "zipcode"){
			if(populate_zip && populate_zip != "false" && populate_zip != "undefined"){
				zip_input.value = populate_zip;
				defaultZipCodeValue = populate_zip;
			}else{
				zip_input.value = glossary_label_zip;
				defaultZipCodeValue = glossary_label_zip;
			}
		}
	});


	if(userData.bandwidth == "low"){

		if ($('footer_links'))
		{
		var link = $('footer_links').getFirst().getNext();
		link.setHTML(glossary_label_high_band);
		/*/
		if (!(hasFlashMin())){
			$('get_flash_button').setHTML("<a href='http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW' title='Get Flash'><img src='/shared/images/get_flash.gif' /></a>");
		}
		//*/
		link.name="&lid=High Bandwidth Version&lpos=global_footer";
		link.href="javascript:setBandwidth('high');";
		}
	}
	if(userData.audiopref == "on"){
		$('audio_text').setHTML(audio_off_text);
	}else if(userData.audiopref == "off"){
		$('audio_text').setHTML(audio_on_text);
	}else{
		$('audio_text').setHTML(audio_off_text);
		// set the pref if the pref is undefined
		userData.audiopref = "on";
		Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
	}
	if (hasFlashMin() && userData.bandwidth != "low"){
		$('audio_button').setStyles({visibility: 'visible'});
	}
	if (!hasFlashMin()){
		// the promo div had this class initially, but older browsers would improperly place the div when it conatined Flash.
		if ($('promos')){
			$('promos').style.overflow = 'auto';
			setlowbanddaalink();
		}
	}
}

function setlowbanddaalink(){
            if($$('#promos ul')) {
                        var promo_set_uls = $$('#promos ul');
                        var first_ul = promo_set_uls[0];
                        var third_promo_li = first_ul.getChildren();
                        third_promo_li[2].setProperties({
                            id: 'third_promo_holder'
                        });

                        third_promo_link = $$('#third_promo_holder a');
                        third_promo_href = third_promo_link.getProperty('href').toString();

                        if (third_promo_href.substr(third_promo_href.length-1,third_promo_href.length) == "#"){
                                    third_promo_link.setProperty('href',"javascript:wrap('daa','','');");
                        }
            }
}


function setUserSegment(){
	if(dealerInfo.id != null){
		//setSeg("-12,-13,14");
		setSeg("14");
	}else if(userData.zipcode){
		//setSeg("-12,13");
		setSeg("13");
	}else{
		setSeg("12");
	}
}
function setSeg(argSeg){
 _hbSet('seg', argSeg);
 _hbSend();
}


function handleSSIEmbeddedDisclaimers() {
	embedded_disclaimers = {};
	var next_disclaimer = 1;
	//keeps track of what disclaimers have already been shown in case of repeat SSI file include leading to replication of disclaimers
	activated_disclaimers = {};

	//Count how many disclaimers are already numbered on the page
	$$('dt.disclaimer_text').each(function(existing_disclaimer){
		if(!isNaN(existing_disclaimer.innerHTML)) {
			next_disclaimer++
		}
	});


	//Find disclaimers that need to be renumbered
	$$('sup.embedded_disclaimer').each(function(embedded_disclaimer){
		disclaimer_id = embedded_disclaimer.innerHTML;
		disclaimer_id = disclaimer_id.substring(1,disclaimer_id.length - 1);
		if(typeof(embedded_disclaimers[disclaimer_id]) == "undefined") {
			embedded_disclaimers[disclaimer_id]	= next_disclaimer;
			activated_disclaimers[disclaimer_id]	= false;
			next_disclaimer++
		}

		embedded_disclaimer.innerHTML = "["+embedded_disclaimers[disclaimer_id]+"]";

		$$('dt.embedded_disclaimer_text').each(function(footer_disclaimer){
			if(footer_disclaimer.innerHTML == disclaimer_id && activated_disclaimers[disclaimer_id]	== false) {
				footer_disclaimer.innerHTML = embedded_disclaimers[disclaimer_id]
				footer_disclaimer.removeClass("hide");
				$(footer_disclaimer.nextSibling).removeClass("hide");
				activated_disclaimers[disclaimer_id]	= true
			}
		});
	});
	
	$$('sup.embedded_disclaimer_hidden').each(function(embedded_disclaimer){ //HERE
		disclaimer_id = embedded_disclaimer.innerHTML;//HERE
	    activated_disclaimers[disclaimer_id]	= false;//HERE
	});//HERE
	//Find ownership disclaimers that need to be shown
	$$('sup.embedded_disclaimer_hidden').each(function(embedded_disclaimer){
		disclaimer_id = embedded_disclaimer.innerHTML;

		$$('dt.embedded_disclaimer_text').each(function(footer_disclaimer){
			if(footer_disclaimer.innerHTML == disclaimer_id && activated_disclaimers[disclaimer_id]	== false) {
				footer_disclaimer.innerHTML = "&nbsp;"
				footer_disclaimer.removeClass("hide");
				$(footer_disclaimer.nextSibling).removeClass("hide");
				activated_disclaimers[disclaimer_id]	= true 
			}
		});
	});
//console.log(embedded_disclaimers);
}

//
//	iePngFix()
//	Allows transparent PNG images to be display correctly in IE 5.5 and 6
//  http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.
//  CSS backround PNGs not supported, use filter:progid:DXImageTransform.Microsoft.AlphaImageLoader in CSS for PNG backgrounds.
//

function iePngFix() {
	for(var i=0; i<document.images.length; i++) {
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='image');\"></span>"
			img.outerHTML = strNewHTML
			i = i-1
		}
	}
}

/*This was put in to set a title attribute on the disclaimer link with an
SSI glossary term. There is no clean way to do this in the XSL.*/

function setDisclaimerLinkTitle(){
    if($('disclaimer_link')){
        //$('disclaimer_link').getFirst().setAttribute('title',glossary_label_legal_information);
    }
}

function brandPopup(target,vehicle,year){
	flexWin("/bridge/index.html?app="+target+"&family="+vehicle+"&year="+year,'yes','770','600',target,'all');
}

onload_register('handleSSIEmbeddedDisclaimers();');
onload_register('highlightVehicleNav();');
onload_register('check_pricing();');
onload_register('setDisclaimerLinkTitle();');

/*This is for the vehicle navigation*/
function rollMe(element) {
}
function vehicleMenu_rollOver(element) {
	if(element.id != cur_section + '_left'){
		$(element.id).addClass('left_hover');
		$(element.id).getFirst().addClass('right_hover');
	}
	else {
		
	}
}
		
function vehicleMenu_rollOut(element) {
		if(element.id != cur_section + '_left'){
		$(element.id).removeClass('left_hover');
		$(element.id).getFirst().removeClass('right_hover');
		}
	else {
		
	}
		
	}
	
// ###############################################################################################
// #################  controlls the me / me too icons on the brand home page #####################
var featureMeTagCalloutVal = "";
function setFeatureCallout(_val) {
   featureMeTagCalloutVal = _val;
   thisMovie("main_content_flash").featureCallout();
}
function thisMovie(movieName) {
   if (navigator.appName.indexOf("Microsoft") != -1) {
       return window[movieName]
   }
   else {
       return document[movieName]
   }
}
function getFeatureCallout(){
	return featureMeTagCalloutVal;
}

// ###############################################################################################
