if(location.host != "dodge.co.uk" ) {
                document.domain = "dodge.co.uk";
}


var cdj;
var JsonP;
var request;

window.addEvent('domready', function() {

	cdj.loadConfig("dodge");
	cdj.init();

});

cdj = {
	modelID: null,
	modelDirectory: null,
	pageName: null,
	offersCount: 0
};

cdj.config = {

	disclaimerEntity: "&dagger;",
	debug: true
};

cdj.config.chrysler = {
        homepageModelID: 21,
        manufacturerID: 2,
        servicesDomain: (location.host == "test.chrysler.co.uk" || location.host == "chrysler08.cdj.sdev.net") ? "http://chrysler.services.cdj.sdev.net" : "http://services.chrysler.co.uk"
};

cdj.config.dodge = {
        homepageModelID: 30,
        manufacturerID: 4,
        servicesDomain: (location.host == "test.dodge.co.uk" || location.host == "dodge08.cdj.sdev.net") ? "http://dodge.services.cdj.sdev.net" : "http://services.dodge.co.uk"
};




cdj.loadConfig = function(manufacturer) {
	if (cdj.config[manufacturer]) {
		$extend(cdj.config, cdj.config[manufacturer]);
	}
};

cdj.URIs = {

    eBrochurePopup: function() { return cdj.config.servicesDomain + "/providers/eBrochurePopup.ashx"; },
    modelPrice: function() { return cdj.config.servicesDomain + "/providers/startingPrice.ashx"; },
    modelOffers: function() { return cdj.config.servicesDomain + "/providers/offers.ashx"; }
};

cdj.log = function(message) {
	if (console && console.log && cdj.config.debug) {
		console.log(message);
	}
};

/*
var original_onload_register = onload_register;

onload_register = function(arg) {
    
    if(arg.indexOf('/crawls.swf') != -1) {
            
        // intercept crawls SWF - injecting prices into the page first
        window.addEvent('domready', function() {

            cdj.data.getModelPrices(function(result) { cdj.callback.loadCrawlInfo(result); eval(arg); });
        });
    }
    else
    {
        original_onload_register(arg);
    }
}
*/

cdj.init = function() {

    cdj.getModel();
	cdj.getPageName();

    cdj.injectPrices();
    cdj.injectOffers();
    
    cdj.eBrochure.init();
};

cdj.carouselInit = function() {

    if($('innerScroller') && $('outerScroller')) {

	    var p = $$('.fadein');
	    
	    p.each(function(el) {
	        el.effect('opacity',{ duration:2500, wait:true, transition:Fx.Transitions.Expo.easeOut }).start(0,1);
	    });
  
        avScroll = new avScroll({container:'innerScroller', imgWidth:255, scrollRange:0, leftHandle:'leftClicker',rightHandle:'rightScroller', rw:'leftFF', ff:'rightFF', speed:700});
    }
};

cdj.getPageName = function() {

    var path = window.location.pathname.toLowerCase();
    var page = path.substring(path.lastIndexOf('/') + 1);
    cdj.pageName = page;
};

cdj.getModel = function() {

	var url = window.location.pathname.toLowerCase();
	
	if(url.indexOf('avenger') != -1) {
		cdj.modelID = 38;
		cdj.modelDirectory = 'avenger';
	}
	else if(url.indexOf('caliber') != -1) {
		cdj.modelID = 28;
		cdj.modelDirectory = 'caliber';
	}
	else if(url.indexOf('journey') != -1) {
		cdj.modelID = 43;
		cdj.modelDirectory = 'journey';
	}
	else if(url.indexOf('nitro') != -1) {
		cdj.modelID = 36;
		cdj.modelDirectory = 'nitro';
	}
};

cdj.injectPrices = function() {
    
    if(cdj.pageName == "lineup.html") { 
        // lineup.html is special model lineup page displaying all product prices
        
        if($('vehicle_lineup')) {    
            cdj.data.getModelPrices(cdj.callback.loadLineUpPrices);
		}      
    }
    else if(cdj.modelID !== null) {
        
        // if we have a match then the user is on model homepage
        // so we need to pull model price 
        if($('modelStartingPrice')) {
            cdj.data.getModelPrices(cdj.callback.loadModelPrice);
		}
	}

	// if we have flyout divs in DOM
	// we're on the homepage so make call for
	// flyout price population
	if($ES('div.flyout') !== 0) {
		cdj.data.getModelPrices(cdj.callback.loadFlyoutPrices);
	}
};

cdj.injectOffers = function() {
    
    if(cdj.modelID == null) {
		
		// homepage uses JS scroller
		if($('scroller') && $('innerScroller')) {
    
			// if we have a model ID then use this
			// otherwise use the homepage model ID
			cdj.data.getModelOffers(cdj.callback.loadModelOffers);
		}	
	}
	else {
		
		// model pages use simple offer panel
		if($('offerPanel')) {
			// if we have a model ID then use this
			// otherwise use the homepage model ID
			cdj.data.getModelOffers(cdj.callback.loadModelOffers);
		}
	}
};


// redirect to dealer search
// using postcode specified 
cdj.searchDealers = function(postcode) { 
		
	var dealerSearchURL = 'http://' + location.host + '/dealer/index.html';

	if(postcode) {
		dealerSearchURL += '?postcode=' + postcode;
    }

	window.location = dealerSearchURL;
};



// Contains data request methods, 
// JsonP request objects,
// and response data
cdj.data = {

    // variables store result of JsonP requests
    modelPrices: null,
	modelOffers: null,
	
	// request objects
    modelPricesRequest: null,
    modelOffersRequest: null,
	
	getModelPrices: function(callback) {
    
        if(cdj.data.modelPrices === null) {
     
            if(cdj.data.modelPricesRequest === null) {
            
                cdj.data.modelPricesRequest = new JsonP(cdj.URIs.modelPrice(), {
		            queryString: 'man=' + cdj.config.manufacturerID,
		            onComplete: function(data) { cdj.data.modelPrices = data; }
                }).request();
            }
            
            cdj.data.modelPricesRequest.addEvent('onComplete', callback);

        } else {
            callback(cdj.data.modelPrices);
        }
    },
    getModelOffers: function(callback) {

        if(cdj.data.modelOffers === null) {
        
            if(cdj.data.modelOffersRequest === null) {
                
                cdj.data.modelOffersRequest = new JsonP(cdj.URIs.modelOffers(), {
		            queryString: (cdj.modelID !== null) ? 'mid=' + cdj.modelID : 'mid=' + cdj.config.homepageModelID,
		            onComplete: function(data) { cdj.data.modelOffers = data; }
                }).request();
            }
            
            cdj.data.modelOffersRequest.addEvent('onComplete', callback);

        } else {
            callback(cdj.data.modelOffers);
        }
    }
};

cdj.callback = {

	loadModelOffers: function(result) {
		
		offerHTML = "";

		if(result.offers) {

			result.offers.each(function(offer) {
			
				if(offer.url && offer.id)
				{
					// target new window if the link is to an external site
					if( offer.url.indexOf('.pdf') != -1 || ((offer.url.indexOf('http://') != -1 || offer.url.indexOf('https://') != -1) && offer.url.indexOf('chrysler.co.uk') == -1 && offer.url.indexOf('dodge.co.uk') == -1 && offer.url.indexOf('jeep.co.uk') == -1))		
					{
						target = "_blank";
					}
					else
					{
						target = "_self";
					}
					
					offerHTML += "<a href=\"" + offer.url + "\" target=\"" + target + "\"><img src=\"" + cdj.config.servicesDomain + "/offers/images/" + offer.id + ".gif\"></a>";			

					cdj.offersCount++;
				}
			});

			// show offer panel if we have any offers 
			if(cdj.offersCount != 0) {

				if(cdj.modelID == null) {
					// homepage uses JS scroll
					$('innerScroller').innerHTML = offerHTML;

					cdj.carouselInit();
					$('scroller').style.display = '';
				}
				else {	
					$('offerPanel').innerHTML = offerHTML;
					$('offerPanel').style.display = '';	
				}		
			}

		}
	},
	
	loadFlyoutPrices: function(result) {
    
		if(result.models) {

			result.models.each(function(model) {

				priceHTML = "";

				if(model.modelId && model.offerPrice && model.startingPrice) {

					// if offer price is less than starting price
					// then display offer price along with disclaimer HTML entity
					if(model.offerPrice < model.startingPrice) {
						priceHTML = model.offerPrice + cdj.config.disclaimerEntity;
					}
					else {
						priceHTML = model.startingPrice;
					}

					modelTag = model.modelName.toLowerCase().replace(' ','_');
					priceElement = 'li#' + modelTag + ' p';

					if($E(priceElement)) {

						// populate price and show element
						$E(priceElement).innerHTML = "Starting From: " + priceHTML + " OTR";
						$E(priceElement).style.display = '';	

					}	
				}

			});
		}
	},
	
	loadLineUpPrices: function(result) {

		if(result.models) {

			result.models.each(function(model) {

				priceHTML = "";

				if(model.modelId && model.offerPrice && model.startingPrice) {

					// if offer price is less than starting price
					// then display offer price along with disclaimer HTML entity
					if(model.offerPrice < model.startingPrice) {
						priceHTML = model.offerPrice + cdj.config.disclaimerEntity;
					}
					else {
						priceHTML = model.startingPrice;
					}

					modelTag = model.modelName.toLowerCase().replace(' ','_');
					priceElement = 'span.lineup-' + modelTag;

					if($E(priceElement)) {

						// populate price and show element
						$E(priceElement).innerHTML = "Starting From: " + priceHTML + " OTR";
						$E(priceElement).style.display = '';	
					}	
				}
			});
		}
	},
	
	loadModelPrice: function(result) {
    
        if(result.models) { 
        
            result.models.each(function(model) {

				    if(model.modelId == cdj.modelID && model.offerPrice && model.startingPrice) {
				    
		                // if offer price is less than starting price
		                // then display offer price along with disclaimer HTML entity
		                if(model.offerPrice < model.startingPrice) {
    		                priceHTML = model.offerPrice + cdj.config.disclaimerEntity;
		                }
		                else {
    		                priceHTML = model.startingPrice;
		                }

                        if($('modelStartingPrice')) { 
		                    // populate price
		                    $('modelStartingPrice').innerHTML += priceHTML;

		                    // finally show price element
	                        $('modelStartingPrice').style.display = '';		
	                    }
				    }
		    });
		}
	}
	
	/*
	loadCrawlInfo: function(result) {
     
        if(result["models"]) { 
        
            $$('div.crawl_info').each(function(element) { 
            
                modelName = element.id.toLowerCase().replace(' ','_');
                
                result["models"].each(function(model) {

				    if(model["modelName"].toLowerCase().replace(' ','_') == modelName && model["offerPrice"] && model["startingPrice"]) {
				    
		                // if offer price is less than starting price
		                // then display offer price along with disclaimer HTML entity
		                if(model["offerPrice"] < model["startingPrice"]) {
    		                priceHTML = model["offerPrice"] + cdj.config.disclaimerEntity;
		                }
		                else {
    		                priceHTML = model["startingPrice"];
		                }
		                
		                $E('span.vehicle_name', element).innerHTML = "A car!";

                        // populate price
                        if($E('p.starting_at_p', element)) { 
		                    $E('p.starting_at_p', element).innerHTML = "Starting at: " + priceHTML;
	                    }
				    } 
		        });
		        
            });  
        }
  	}
  	*/
};

// handles eBrochure popup functionality
cdj.eBrochure = {

	cookied: false,
	postcode: null,
	isActive: false,

	init: function() {
	
	    var keyCode;
	    
		// proceed to load and setup eBrochure popup
		// only if we are on a model-specific page
		// and the ebrochure link exists on the page
		if(cdj.modelID !== null && $('ebrochures')) {
			cdj.eBrochure.requestPopupHTML(cdj.modelID);	
	    }
			
		document.addEvent('keypress', function(e) {
			
			if ( window.event ) {
				keyCode = window.event.keyCode;
			} else {
				keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
			}
			
			// Hide DropBox on Escape key
			if( keyCode == 27 && cdj.eBrochure.isActive) { 
			    cdj.eBrochure.closePopup();
			}
		}.bind(this));	
	},
	
	// pulls in eBrochure Popup HTML
	requestPopupHTML: function(modelID) {

		var request = new JsonP(cdj.URIs.eBrochurePopup(), {
        		queryString: 'mid=' + modelID,
			onComplete: function(data) { cdj.eBrochure.requestCallback(data); }
		}).request();

	},

	validateForm: function() {

		var bError = false;
        	var sMessage = "Please complete the following fields:\r\n";

        	if($('firstname').value === "") {
        		bError = true;
        		sMessage += "First name\r\n";
        	}

	        if($('surname').value === "") {
        		bError = true;
		        sMessage += "Surname\r\n";
        	}

	        if($('email').value === "") {
		        bError = true;
		        sMessage += "Email address\r\n";
        	}

	        if($('postcode').value === "") {
		        bError = true;
		        sMessage += "Postcode\r\n";
        	}

	        if(bError) {
	        	alert(sMessage);
			return false;
		}
        	else {
			cdj.eBrochure.formSubmitted();
          		return true;
        	}
	},

	formSubmitted: function() {

		cdj.eBrochure.cookied = true;
		cdj.eBrochure.postcode = $('postcode').value;
		cdj.eBrochure.showThanks();
	},

	// handles callback for requestPopupHTML method
	requestCallback: function(HTML) {
            		
		// create new popup element to hold popup HTML	
		var popupElement = new Element('div', {   'id': 'ebrochure_popover',
                				'styles': {
                            				'position': 'absolute',
                            				'top': '100px',
                            				'left': '518px',
                            				'z-index': 9999
                            			}
            	});

            	popupElement.setOpacity(0);
            	popupElement.style.display = 'none';
            
            	popupElement.innerHTML = HTML;
            	$('wrapper').adopt(popupElement);

		
		// add click handler for close button

		$('ebrochure_closepopup').addEvent('click', function() {
			cdj.eBrochure.closePopup();
		});


		// add change handlers for product radio buttons

		$$("input[name=product]").addEvent('change', function() {

			// if postcode is set then the user
			// has already completed the form
			if(cdj.eBrochure.cookied) {
				cdj.eBrochure.showDownloadAnother();
		    }
		});	


		// finally add click handler on ebrochure link

		$('ebrochures').addEvent('click', function() {
			cdj.eBrochure.showHidePopup();
		});
	},

	// toggles popup box
	showHidePopup: function() {

		var fXPopover = new Fx.Styles($('ebrochure_popover'), {duration:500, wait:false});

		if(!cdj.eBrochure.isActive) {

			$('ebrochures').addClass('features_menu_on');

			fXPopover.element.setOpacity(0);
			fXPopover.element.style.display = '';

    			fXPopover.start({'opacity': [0, 1]}).chain(function() {
				cdj.eBrochure.isActive = true;
			});
		}
		else {
			cdj.eBrochure.closePopup();
		}
	},

	// replaces form div with thanks div
	showThanks: function() {

		var fxForm = new Fx.Styles($('diveBrochureForm'), {duration:500, wait:false});
		var fxThanks = new Fx.Styles($('diveBrochureThanks'), {duration:500, wait:false});

    		fxForm.start({'opacity': [1, 0]}).chain(function() {

			fxForm.element.style.display = 'none';

			fxThanks.element.setOpacity(0);
			fxThanks.element.style.display = '';

			fxThanks.start({'opacity': [0, 1]});
		});
	},

	// fades out popup box
	closePopup: function() {

		var fxPopover = new Fx.Styles($('ebrochure_popover'), {duration:500, wait:false});

		$('ebrochures').removeClass('features_menu_on');

		if(cdj.eBrochure.isActive) {

			fxPopover.start({'opacity': [1, 0]}).chain(function() {
		
				fxPopover.element.style.display = 'none';
				cdj.eBrochure.isActive = false;
			});
		}
	},

	// replaces form and thanks page
	// 'download another' div
	showDownloadAnother: function() {
		
		cdj.eBrochure.cookied = true;

		$('diveBrochureForm').style.display = 'none';
		$('diveBrochureThanks').style.display = 'none';
		$('divDownloadAnother').style.display = '';

		$('ebrochure_derivative').innerHTML = cdj.eBrochure.getLabelForSelectedProduct();

		$('ebrochure_downloadlink').href = cdj.eBrochure.buildBrochureLink();

	},

	getSelectedProductID: function() {

		var ID = 0;

		$$("input[name=product]").each(function(item) {
			
			if(item.checked) {
				ID = item.value;
		    }
		});	

		return ID;
	},

	// returns the label for the selected product
	getLabelForSelectedProduct: function() {
		
		return $$("label[for=prod" + cdj.eBrochure.getSelectedProductID() + "]")[0].innerHTML;
	},

	buildBrochureLink: function() {
	
		var link;

		if($('ebrochure_downloadlink').href.indexOf("?") == -1) {
			link = $('ebrochure_downloadlink').href += "?productId=" + cdj.eBrochure.getSelectedProductID() + "&pc=" + cdj.eBrochure.postcode;		
		}
		else {
			var qsPos = $('ebrochure_downloadlink').href.indexOf("?");
			
			link = $('ebrochure_downloadlink').href.substring(0,qsPos) + "?productId=" + cdj.eBrochure.getSelectedProductID() + "&pc=" + cdj.eBrochure.postcode;

		}

		return link;
	}
};


cdj.pageLoad = {

	// method populates iframe named by iframeName variable
	// with the URL specified in the iframeSrc variable.

	// querystring variables specifed in the qsTransfer array
	// will be pulled from the page and added to iframeSrc
	loadIframe: function(iframeName, iframeSrc, qsTransfer) {
		
		if( $(iframeName) && iframeSrc) {

			var iframeQS = '';

			// loop through qsTransfer array to build querystring
			for(var i = 0; i < qsTransfer.length; i++) {
				
				if(qsTransfer[i]) {
					var sourceKey = qsTransfer[i].sourceKey;
					var qsValue = request.decode(request.queryString(sourceKey));
					var targetKey = qsTransfer[i].targetKey;

					if(qsValue)
					{
						if(iframeQS !== '') {
							iframeQS += "&";
					    }	

						iframeQS += targetKey + "=" + qsValue;
					}
				}
			}

			if(iframeQS !== '') {

				$(iframeName).src = iframeSrc + "?" + iframeQS;
			}
			else {

				$(iframeName).src = iframeSrc;
			}
			
			// finally show the iframe
			$(iframeName).style.display = '';

			return true;		
		}	
		
		return false;
	}
};

request = {
	
	queryString: function(key) {
		var qs = location.search;
		
		if(qs.charAt(0) == '?') {
			qs = qs.substring(1,qs.length);
	    }
		
		var vars = qs.split(/[&;]/);
		var rs = {};

		if (vars.length) {
		    vars.each(function(val) {
			    var keys = val.split('=');
			    if (keys.length && keys.length == 2) { 
			        rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]);
			    }
		    });
		}
		
		return request.decode(rs[key]);
	},

	decode: function(encoded) {
		if(encoded == null) return null;
		return unescape(encoded.replace(/\+/g,  " "));
	}
};


/* iFrame resizing methods */

function setIframeHeight(iframeName) {

	try {	
		var iframeWin = window.frames[iframeName];
		var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
		if ( iframeEl && iframeWin ) {
			iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
			var docHt = getDocHeight(iframeWin.document);
			// need to add to height to be sure it will all show
			if (docHt) iframeEl.style.height = docHt + "px";
		}
	}
	catch(err) {}
}

function getDocHeight(doc) {
	
	var docHt = 0, sh, oh;
	if (doc.height) docHt = doc.height;
	else if (doc.body) {
		if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
		if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
		if (sh && oh) docHt = Math.max(sh, oh);
	}
	return docHt;

}

JsonP = new Class({
	options: {
		onComplete: Class.empty,
		callBackKey: "callback",
		queryString: "",
		data: {},
		timeout: 5000,
		retries: 0
	},
	initialize: function(url, options){
		this.setOptions(options);
		this.url = this.makeUrl(url).url;
		this.fired = false;
		this.scripts = [];
		this.requests = 0;
		this.triesRemaining = [];
	},
/*	Property: request
		Executes the Json request.
	*/
	request: function(url, requestIndex){
		var u = this.makeUrl(url);
		if(!$chk(requestIndex)) {
			requestIndex = this.requests;
			this.requests++;
		}
		if(!$chk(this.triesRemaining[requestIndex])) { 
		    this.triesRemaining[requestIndex] = this.options.retries;
		}
		
		var remaining = this.triesRemaining[requestIndex]; //saving bytes

		var dl = (window.ie)?50:0; //for some reason, IE needs a moment here...
		(function(){
			var script = new Asset.javascript(u.url, {id: 'jsonp_'+u.index+'_'+requestIndex});
			this.fired = true;
			this.addEvent('onComplete', function(){
//				try {script.remove();}catch(e){}
			}.bind(this));

			if(remaining) {
				(function(){
					this.triesRemaining[requestIndex] = remaining - 1;
					if(script.getParent() && remaining) {
						script.remove();
						this.request(url, requestIndex);
					}
				}).delay(this.options.timeout, this);
			}
		}.bind(this)).delay(dl);
		return this;
	},
	makeUrl: function(url){
	    var jurl;
		var index = (JsonP.requestors.contains(this))?
								JsonP.requestors.indexOf(this):
								JsonP.requestors.push(this) - 1;
		if(url) {
			var separator = (url.test('\\?'))?'&':'?';
			jurl = url + separator + this.options.callBackKey + "=JsonP.requestors[" +
				index+"].handleResults";
			if(this.options.queryString) { jurl += "&"+this.options.queryString; }
			jurl += "&"+Object.toQueryString(this.options.data);
		} else { 
		    jurl = this.url;
		}
		return {url: jurl, index: index};
	},
	handleResults: function(data) {
		this.fireEvent('onComplete', [data, this]);
	}
});

JsonP.requestors = [];
JsonP.implement(new Options());
JsonP.implement(new Events());


String.prototype.reverse = function()  {
	if (!this) { 
	    return '';
	}
	revstr='';

	for (i = this.length-1; i>=0; i--) {
		revstr+=this.charAt(i)
	}
	
	return revstr;
};

Element.extend({
	getAncestor: function(selector){
		var es = $$(selector);
		var ancestor = this.getParent();
		while(!es.contains(ancestor)) {
			ancestor = ancestor.getParent();
		}
		return ancestor;
	}
});

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}





// colorator
/*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:");
            }       
        }
    }else{
        if(location.protocol == "https:") {
              window.location = location.href.split("https:").join("http:");
        }  
    }
}

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;
}

/* onload handler setter */
var cur_section;
var populate_zip;
var audio_on_text;
var audio_off_text;
var es_confirm_apps;


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++) {
		//alert(window_onload);
		eval(window_onload[i]);
	}
	//window_onload[i] = "";
};

function onload_register(func) {
	window_onload.push(func);
	/*
	var notIn = false;
	//alert("onload_register: "+ func);
	alert(window_onload);
	for (var i = 0; i < window_onload.length; i++) {
        if (window_onload[i] == func) {
            notIn = true;
			i = window_onload.length + 2; // GET OUT
        }
    }
	if (!notIn){
		//alert("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 = 0; //additional padding to add to the menu width
		fmc.getFirst().getChildren().each(function(lc){
			if(lc.hasClass('link_container') || lc.hasClass('feature_nav_divider')){
				menuWidth = menuWidth + parseInt($(lc).getSize().scrollSize.x);
			}
		});
		fmc.setStyle("width", menuWidth + "px");
		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");

		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" && $(m).id != "build_menu") {
				if (this.timer) { clearTimeout(this.timer); }
				this.menuBuffer = setTimeout("checkMenus('"+this.id+"_container')", 200);
			}

		}

		$(m).onmouseout = function(){
			if (!isFormOpen) {
				if ($(m).id != "dealer_finder" && $(m).id != "build_menu") {
					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.removeClass('brand_menu_link');
		menu_link.addClass('brand_menu_link_on');
	}

	//set before calculation to calcuate with borders
	menu.setStyle('border-style', 'solid');
	
	var menuHeight = menu.getSize().scrollSize.y;
	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');
	

	//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).removeClass('sub_menu_wrapper_at');
			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');
			menu_link.addClass('brand_menu_link');
		}

		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');
		menu_link.addClass('brand_menu_link');
	}
	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');
	
	//make sure we turn our border off!!
	menu.setStyle('border-style','none');
}

/* 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);

			$(cur_sub_menu).removeClass('sub_menu_wrapper_at');

			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_parent = menu.getParent();
		link_parent.addClass('sub_menu_wrapper_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_parent = menu.getParent();
		link_parent.removeClass('sub_menu_wrapper_at');

	}
}

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').setStyles({'background-image':'url(/shared/images/arrow_down_blk.jpg)'});
				$('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').setStyles({'background-image':'url(/shared/images/arrow_right.jpg)'});
		$('detail').removeClass("detail_highlight");
		return false;
	}
}

function fade_down_model_info(){

            if($('vehicle_shown_info_container')){$('vehicle_shown_info_container').setStyle("visibility", "hidden");}

            if($('vehicle_pricing_background')){$('vehicle_pricing_background').setStyle("visibility", "hidden");}

            if($('vehicle_pricing')){$('vehicle_pricing').setStyle("visibility", "hidden");}

            if($$('#vehicle_pricing p')){$$('#vehicle_pricing p').setStyle("visibility", "hidden");}

            if ($('miles_per_gallon')){$('miles_per_gallon').setStyle("visibility", "hidden");}

}



function fade_up_model_info(){

            if($('vehicle_shown_info_container')){$('vehicle_shown_info_container').setStyle("visibility", "visible");}

            if($('vehicle_pricing_background')){$('vehicle_pricing_background').setStyle("visibility", "visible");}

            if($('vehicle_pricing')){$('vehicle_pricing').setStyle("visibility", "visible");}

            if($$('#vehicle_pricing p')){$$('#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;
		}else if(as_p.getLast().innerHTML == "NA"){
		  as_p.setHTML("");
    }
	});
	/*$$('.starting_at_p').each(function(start_p){
		var start_p = $(start_p);
		var start_val = start_p.getLast().innerHTML;
		if(start_val == "X" || start_val == "$X"  || start_val == " $X"){
			start_p.setHTML(glossary_label_pricing_avail_soon)
		}else{
			$(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;
}

// ==========================================================
// update_pricing_mpg() 
// ==========================================================
function update_pricing_mpg(startingAt, asShown, cityMpg, hwyMpg) {
	
	//if(startingAt) {
		//$('starting_at_price').setText(startingAt);
	//}
	if(hwyMpg && $('hwy_value')) {
		$('hwy_value').setText(hwyMpg);
	}
	
}

/* 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)) {
		//console.log("flash is in the house");

		// if we have main content lets temporarily clone it for the print stylesheet
		if(argElement == "main_content") {
			if ($(argElement).getFirst() && $('promo_background')){
				if ($(argElement).getFirst().getTag() == 'map') {
					var clone = $(argElement).getElement('img').clone().injectAfter('promo_background');
				}
				else {
					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 ) {
		//CHECK WITH JASON LAW FOR WHAT NEEDS TO GO HERE
		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" && 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) {
			
			// check if we need to pass the entire combined user data object
			
			if(argFlashVars.indexOf("passUserData=true") != -1) {
				flash_vars += "&cookieUserData=" + getCombinedUserData();
			}
			
			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();
			}
		}
	}
}



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');
				
}


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;

		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 (es_confirm_apps){
		if(confirm(glossary_def_dg_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 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;
 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_dg_application_confirm_statement)){
		window.open(aU,wN,wO);
	}
 aC ? window.close():"";
}

function englishRedirect(argUrl,whichWindow,justalert) {
	if(confirm( glossary_def_dg_application_confirm_statement)){
    if(justalert == 'yes'){
		} else {
	    if(whichWindow == ''){window.location = argUrl;}
	    else{window.open(argUrl);}
		}
	}
}

function demoAlert(){ 
	if(confirm(glossary_def_dg_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");
    }else if(cur_section !== null && cur_section != "features"){
if($(cur_section)) {
    $(cur_section).addClass("vehicle_nav_link_at");
}
    }
}

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 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);
		link.title = 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 = {};
	activated_disclaimers = {};//HERE
	var next_disclaimer = 1;

	//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;//HERE
			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) {//HERE
				footer_disclaimer.innerHTML = embedded_disclaimers[disclaimer_id]
				footer_disclaimer.removeClass("hide");
				$(footer_disclaimer.nextSibling).removeClass("hide");
				activated_disclaimers[disclaimer_id]	= true //HERE
			}
		});
	});

	//Find ownership disclaimers that need to be shown
	$$('sup.embedded_disclaimer_hidden').each(function(embedded_disclaimer){ //HERE
		disclaimer_id = embedded_disclaimer.innerHTML;//HERE
	    activated_disclaimers[disclaimer_id]	= false;//HERE
	});//HERE
	
	$$('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) {//HERE
				footer_disclaimer.innerHTML = "&nbsp;"
				footer_disclaimer.removeClass("hide");
				$(footer_disclaimer.nextSibling).removeClass("hide");
				activated_disclaimers[disclaimer_id]	= true //HERE
			}
		});
	});


}

/*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 setDisclaimerLinkTitle(){
    if($('disclaimer_link')){
        //$('disclaimer_link').getFirst().setAttribute('title',glossary_label_legal_information);
    }
}

onload_register('highlightVehicleNav();');
onload_register('handleSSIEmbeddedDisclaimers();');
onload_register('check_pricing();');
onload_register('setDisclaimerLinkTitle();');
if (window.ie6){onload_register('iePngFix();');}

function flashFeatureSectionTextLink(flash_url,flash_lid,flash_lpos){
	document.location = flash_url;
	linkTrack(flash_lpos, flash_lid);
}

function getCurVehicleValue(){
	return cur_vehicle;
}
function rollMe(element) {
}
function vehicleMenu_rollOver(element) {
}
function vehicleMenu_rollOut(element) {
}





function setButtonType(buttonTypeValue,txtVal){
	userData.buttonType = buttonTypeValue;
	Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
	bottonTypeList = buttonTypeValue.toLowerCase().split(" ");
	buttonTypeJoined = bottonTypeList.join("");
	//alert(cur_vehicle+"test_"+buttonTypeJoined+"button");
	linkTrack("test", cur_vehicle+"test_"+buttonTypeJoined+"button");
	if(txtVal){
		//linkTrack("test", buttonTypeValue);
		//appendToMLC(txtVal);
	}
	//linkTrack('content_button_test', bottonTypeList.toLowerCase().join(""));
}

function getButtonType(){
	cookieUserData = Cookie.get("userdata");
	return cookieUserData;
}

function appendToMLC(txtVal){
	hbx.mlc+=txtVal;
	resetMLC(hbx.mlc);
	//alert("ran new mlc");
	//alert(hbx.mlc);
}
function resetMLC(newMLC){
	_hbSet('vcon', newMLC);
	_hbSend();
}
function getCurVehicleValue(){
	return cur_vehicle;
}
function scheduleTestDriveVideoLink(){
	document.location = "/bridge/index.html?app=testdrive&family="+cur_vehicle;
}
function findDealerVideoLink(){
	document.location = "/bridge/dealerloc.html";
}

function brandPopup(target,vehicle,year){
	flexWin("/bridge/index.html?app="+target+"&family="+vehicle+"&year="+year,'yes','770','600',target,'all');
}

// Identical to getParameter() except sniffs the contents of the URL's # anchor instead of the ? query parameters
function getHashParameter(aP){var qS = new String(location.hash.substring(1,location.hash.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;}}

// Converts an integer like so: 10000 -> 10,000
function insertCommas(num) {
	num = num.toString();
	return (num.length > 3) ? insertCommas(num.substr(0, num.length - 3)) + ',' + num.substr(num.length - 3) : num ;
}

// ==========================================================
// getCombinedUserData() -- combines session and persistent
// ==========================================================
function getCombinedUserData() {
	var sessionUserData = Cookie.get("usersessiondata"); 
	// if we have a cookie return
	if(sessionUserData && cookieUserData) {
		return escape(sessionUserData.slice(0, -1) + ", " + cookieUserData.slice(1));
	} else {
		return escape(cookieUserData);
	}
}


//colorator end


// Carousel JS

var avScroll = new Class({
    isMoving: false,	
    options: {
		imgWidth: 0,
		scrollRange: 0,
		leftHandle: null,
		rightHandle: null,
		container: null,
		position: 0,
		speed: 3000
	},

	initialize: function(options){
	this.setOptions(options)
	
		this.imgWidth = options['imgWidth'];
		this.scrollRange = options['scrollRange'];
		this.leftHandle = options['leftHandle'];
		this.rightHandle = options['rightHandle'];	
		this.container = $(options['container']);
		this.totalClicks = cdj.offersCount;
		this.displayCount = 3;
			
		this.position = 0;
		this.speed = options['speed'];		
		$(this.leftHandle).addEvent('click',this.leftClick.bindWithEvent(this));
		$(this.rightHandle).addEvent('click',this.rightClick.bindWithEvent(this));
	},
	leftClick: function(){
		
				if(this.position > 0 && avScroll.isMoving == false){
					var start= this.position * this.imgWidth;
					var end = ( this.position - 1 ) * this.imgWidth;

					avScroll.isMoving = true;

					$(this.container).effect('right',{ duration: this.speed,wait:true, 
					transition:Fx.Transitions.Expo.easeOut}).start(start,end).chain(function(){avScroll.isMoving = false;});

					this.position--;
				}

				else if(this.position == 0 && avScroll.isMoving == false){ 
					var start = 0;
					var end = ((cdj.offersCount - this.displayCount) * this.imgWidth);

					avScroll.isMoving = true;

					$(this.container).effect('right',{ duration: this.speed, wait:true,
					transition:Fx.Transitions.Expo.easeOut }).start(start,end).chain(function(){avScroll.isMoving = false;});

					this.position = cdj.offersCount - this.displayCount;
				}
				
				
	},
		
	rightClick: function(){
				
				if(this.position == (cdj.offersCount - this.displayCount) && avScroll.isMoving == false) {
					var start= this.position * this.imgWidth;
   					var end = 0;

					avScroll.isMoving = true;

   					$(this.container).effect('right',{ duration: this.speed, wait:true,
   					transition:Fx.Transitions.Expo.easeOut }).start(start,end).chain(function(){avScroll.isMoving = false;});

   					this.position = 0;
				}
				

				else if(this.position < cdj.offersCount && avScroll.isMoving == false) { 		 
					var start= this.position * this.imgWidth;
					var end = ((this.position + 1) * this.imgWidth); 

					avScroll.isMoving = true;

					$(this.container).effect('right',{ duration: this.speed, 
					transition:Fx.Transitions.Expo.easeOut}).start(start,end).chain(function(){avScroll.isMoving = false;});

					this.position++;	
				}


	}
				
});
avScroll.implement(new Options, new Events);

// End carousel JS

function imgbrowser(element) { 
	// Get the variables of the small (clicked) and large imgs
	var imgbrowsersmall = $(element).getProperty('name');
	var imgbrowsermain = $('imgbrowser-big').getElements('img');
	
	// Do the swap
	imgbrowsermain.setProperty('src', imgbrowsersmall);
	
	// Tell me it worked properly
	return;
}



/*
 * Smoothbox v20070814 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.1x
 * 
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// on page load call TB_init
window.addEvent('domready', TB_init);

// prevent javascript error before the content has loaded
TB_WIDTH = 0;
TB_HEIGHT = 0;
var TB_doneOnce = 0 ;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init(){
	$$("a.smoothbox").each(function(el){el.onclick=TB_bind});

	// links in shopping tools
	$("shoppingtools-brochure").addEvent('click', TB_bind);
	$("shoppingtools-testdrive").addEvent('click', TB_bind);
}

function TB_bind(event) {
	var event = new Event(event);
	// stop default behaviour
	event.preventDefault();
	// remove click border
	this.blur();
	// get caption: either title or name attribute
	var caption = this.title || this.name || "";
	// get rel attribute for image groups
	var group = this.rel || false;
	// display the box for the elements href
	TB_show(caption, this.href, group);
	this.onclick=TB_bind;
	return false;
}


// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel) {

	// create iframe, overlay and box if non-existent
	if ( !$("TB_overlay") )
	{
		new Element('iframe').setProperty('id', 'TB_HideSelect').injectInside(document.body);
		$('TB_HideSelect').setOpacity(0);
		new Element('div').setProperty('id', 'TB_overlay').injectInside(document.body);
		$('TB_overlay').setOpacity(0);
		TB_overlaySize();

		// add loading class
		$("TB_overlay").addClass('loaderBg');

		new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut}).start(0,0.8);
	}
	
	
	if ( !$("TB_window") )
	{
		new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
		$('TB_window').setOpacity(0);
	}
	
	$("TB_overlay").onclick=TB_remove;
	window.onscroll=TB_positionEffect;

	// check if a query string is involved
	var baseURL = url.match(/(.+)?/)[1] || url;

	// regex to check if a href refers to an image
	var imageURL = /\.(jpe?g|png|gif|bmp)/gi;

	// check for images
	if ( baseURL.match(imageURL) ) {
		var dummy = { caption: "", url: "", html: "" };
		
		var prev = dummy,
			next = dummy,
			imageCount = "";
			
		// if an image group is given
		if ( rel ) {
			function getInfo(image, id, label) {
				return {
					caption: image.title,
					url: image.href,
					html: "<span id='TB_" + id + "'>&nbsp;&nbsp;<a href='#'>" + label + "</a></span>"
				}
			}
		
			// find the anchors that point to the group
			var imageGroup = [] ;
			$$("a.smoothbox").each(function(el){
				if (el.rel==rel) {imageGroup[imageGroup.length] = el ;}
			})

			var foundSelf = false;
			
			// loop through the anchors, looking for ourself, saving information about previous and next image
			for (var i = 0; i < imageGroup.length; i++) {
				var image = imageGroup[i];
				var urlTypeTemp = image.href.match(imageURL);
				
				// look for ourself
				if ( image.href == url ) {
					foundSelf = true;
					imageCount = "Image " + (i + 1) + " of "+ (imageGroup.length);
				} else {
					// when we found ourself, the current is the next image
					if ( foundSelf ) {
						next = getInfo(image, "next", "Next &gt;");
						// stop searching
						break;
					} else {
						// didn't find ourself yet, so this may be the one before ourself
						prev = getInfo(image, "prev", "&lt; Prev");
					}
				}
			}
		}
		
		imgPreloader = new Image();
		imgPreloader.onload = function() {
			imgPreloader.onload = null;

			// Resizing large images
			var x = window.getWidth() - 150;
			var y = window.getHeight() - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			// TODO don't use globals
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			
			// TODO empty window content instead
			$("TB_window").innerHTML += "<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + imageCount + prev.html + next.html + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div>";
			
			$("TB_closeWindowButton").onclick = TB_remove;
			
			function buildClickHandler(image) {
				return function() {
					$("TB_window").remove();
					new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
					
					TB_show(image.caption, image.url, rel);
					return false;
				};
			}
			var goPrev = buildClickHandler(prev);
			var goNext = buildClickHandler(next);
			if ( $('TB_prev') ) {
				$("TB_prev").onclick = goPrev;
			}
			
			if ( $('TB_next') ) {		
				$("TB_next").onclick = goNext;
			}
			
			document.onkeydown = function(event) {
				var event = new Event(event);
				switch(event.code) {
				case 27:
					TB_remove();
					break;
				case 190:
					if( $('TB_next') ) {
						document.onkeydown = null;
						goNext();
					}
					break;
				case 188:
					if( $('TB_prev') ) {
						document.onkeydown = null;
						goPrev();
					}
					break;
				}
			}
			
			// TODO don't remove loader etc., just hide and show later
			$("TB_ImageOff").onclick = TB_remove;
			TB_position();
			TB_showWindow();
		}
		imgPreloader.src = url;
		
	} else { //code to show html pages
		
		var queryString = url.match(/\?(.+)/)[1];
		var params = TB_parseQuery( queryString );
		
		TB_WIDTH = (params['width']*1) + 30;
		TB_HEIGHT = (params['height']*1) + 40;

		var ajaxContentW = TB_WIDTH - 30,
		ajaxContentH = TB_HEIGHT - 45;

		if(url.indexOf('TB_iframe') != -1){				
			urlNoQuery = url.split('TB_');		
			$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 30)+"px;height:"+(ajaxContentH + 15)+"px;' scrolling='no' onload='TB_showWindow()'> </iframe>";
		} else {
			$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>";
		}
	
		$("TB_closeWindowButton").onclick = TB_remove;
		
			if(url.indexOf('TB_inline') != -1){	
				$("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
				TB_position();
				TB_showWindow();
			}else if(url.indexOf('TB_iframe') != -1){
				TB_position();
				if(frames['TB_iframeContent'] == undefined){//be nice to safari
					$(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });
					TB_showWindow();
				}
			}else{
				var handlerFunc = function(){
					TB_position();
					TB_showWindow();
				};
				var myRequest = new Ajax(url, {method: 'get',update: $("TB_ajaxContent"),onComplete: handlerFunc}).request();
			}
	}

	window.onresize=function(){ TB_position(); TB_overlaySize();}  
	
	document.onkeyup = function(event){ 	
		var event = new Event(event);
		if(event.code == 27){ // close
			TB_remove();
		}	
	}
		
}

//helper functions below

function TB_showWindow(){

	setTimeout(function() {

	// remove loading class
	$("TB_overlay").removeClass('loaderBg');

	if (TB_doneOnce==0) {
		TB_doneOnce = 1;
		var myFX = new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){if ($('TB_load')) { $('TB_load').remove();}} }).start(0,1);
		
	} else {
		$('TB_window').setStyle('opacity',1);
		if ($('TB_load')) { $('TB_load').remove();}
	}
	
	}, 1000);
}

function TB_remove() {
 	$("TB_overlay").onclick=null;
	document.onkeyup=null;
	document.onkeydown=null;
	
	if ($('TB_imageOff')) $("TB_imageOff").onclick=null;
	if ($('TB_closeWindowButton')) $("TB_closeWindowButton").onclick=null;
	if ( $('TB_prev') ) { $("TB_prev").onclick = null; }
	if ( $('TB_next') ) { $("TB_next").onclick = null; }

	new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_window').remove();} }).start(1,0);
	new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_overlay').remove();} }).start(0.6,0);

	window.onscroll=null;
	window.onresize=null;	
	
	$('TB_HideSelect').remove();
	TB_init();
	TB_doneOnce = 0;
	return false;
}

function TB_position() {

	var top = (window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2);
	top = top - 50;
	if(top < 0)
		top = 0;

	$("TB_window").setStyles({width: TB_WIDTH+'px', 
				 left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
				 top: top +'px'});
}


function TB_positionEffect() {
	new Fx.Styles('TB_window', {duration: 75, transition: Fx.Transitions.sineInOut}).start({
		'left':(window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
		'top':(window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_overlaySize(){
	// we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
	$("TB_overlay").setStyles({"height": '0px', "width": '0px'});
	$("TB_HideSelect").setStyles({"height": '0px', "width": '0px'});
	$("TB_overlay").setStyles({"height": window.getScrollHeight()+'px', "width": window.getScrollWidth()+'px'});
	$("TB_HideSelect").setStyles({"height": window.getScrollHeight()+'px',"width": window.getScrollWidth()+'px'});
}

function TB_load_position() {
	if ($("TB_load")) { $("TB_load").setStyles({left: (window.getScrollLeft() + (window.getWidth() - 56)/2)+'px', top: (window.getScrollTop() + ((window.getHeight()-20)/2))+'px',display:"block"}); }
}

function TB_parseQuery ( query ) {
	// return empty object
	if( !query )
		return {};
	var params = {};
	
	// parse query
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}

/* End Smoothbox */