/* onload handler */
var window_onload = new Array;
var onloadRef = window.onload;
var cur_section;
var populate_zip;
var audio_on_text = "Audio On";
var audio_off_text = "Audio Off";
var es_confirm_apps;


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);
}

var userData = new Object;

function getUserData(skipPrefSets){
	
	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: "/"});

}

function linkTrack(){
	//placeholder
}

function pageTrack(){
	//placeholder
}



/* end onload handler */
// 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,overrideFlashVersion){
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)


	 var site_config = {
    	'host':location.host,
        'src':location.href,
        'title':document.title,
    	'isSafari':isSafari,
    	'isLTOpera92':isLTOpera92,
    	'asset_path':'en',
    	'EOF':'EOF'
    };

    
    if( (typeof(cur_year) !="undefined" && cur_year != '') && (typeof(cur_vehicle) !="undefined" && cur_vehicle != '') ) {
    	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 = 11;
	}else if (overrideFlashVersion != null){
		flash_version = overrideFlashVersion;
	}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';
	}
}

// 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: "/"});
}

/*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 options = "";
  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 (argApp == "ext_url") {
		sizedWin = true;
		launchUrl = "http://" + argMisc;
		options = "scrollbars=yes,toolbar=yes,resizable=yes,status=yes,location=yes,menubar=yes,";			
	}
	
	if (argApp == "ext_sni") {
		sizedWin = true;
		launchUrl = "http://" + argMisc + "/new-inventory/index.htm?reset=InventoryListing";
		options = "scrollbars=yes,toolbar=yes,resizable=yes,status=yes,location=yes,menubar=yes,";			
	}
  
	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;
}




function nocacheRandom(){var axel = Math.random() + "";var ord = axel * 1000000000000000000;return ord;}


function muteAudio(val) {
	userData.muteAudio = val;

	//Bake the userData cookie
	Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
}














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.*/






	
// ###############################################################################################
// #################  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;
}
var dateAtPageStart = getCurrentTime();
function getCurrentTime(){
	_currentTime = new Date();
	return Number(_currentTime);
}
function getStartTime(){
	return dateAtPageStart;
}

function _getDiv(id){
  var listOfDivs = document.getElementsByTagName('div');
  for(var i=0;i<listOfDivs.length;i++)
				{
					if(listOfDivs[i].id == id)
					{
						//alert('listOfDivs[i] = '+listOfDivs[i].id);
						return listOfDivs[i];
						  
					}
				}
}

function changeElementStyle(_id, _style, _value){
  //$(_id).setStyle(_style, _value);
  //document.getElementById(_id).style[_style] = _value;
  _getDiv(_id).style[_style] = _value;
 // alert('changeElementStyle - value = '+ _value);
}



// ###############################################################################################

function resetMLC(newMLC){
	hbx.mlc = newMLC;
	_hbSet('vcon', newMLC);
	_hbSend();
}