var _tab			= 'purchase';
var _daa_region		= '';
var _zip			= null;
var _family			= null;
var _modelYear		= 2008;
var _app			= null;
var _model			= null;
var _year			= 2008;
var _offers			= new Array();
var vehFuncs		= new Array();
var _selectedOffer	= null;
var cur_page = "incentives";
var _promoCode = "";

//
//	incentivesLoader() is called on page load and does any initial data handling and display configuration necessary.
//	Sniffs for a zip code and a vehicle and goes to the right section for the data available.
//
function incentivesLoader() {
	displayHandler.init();
	
	if (_family && (_zip || daaOffers)) {
		displayHandler.gotoVehicle(_family, _modelYear, _tab);
		linkTrack('vehicles', _family);	// Tracking
	}
	else if (daaOffers) {
		displayHandler.gotoZip();
	}
	else {
		displayHandler.gotoLanding();
	}
}

function getManual(){  

	for(i=0; i < _offers.length; i++){
		if(_offers[0] instanceof DAAOffer && _offers[1] instanceof CustomOffer){        
	      var manualOffer = 1;
	      return manualOffer;
	    } else {
		   var manualOffer = 0;
		   return manualOffer;
		}
	}

}



//
//	displayHandler controls the state of the visual content of the site.  Slides between panels, renders new content.
//
var displayHandler = {
	scroller		: false,
	vertScroller	: false,
	promoFader		: false,
	navSlider		: false,
	curPage			: false,
	navVisible		: false,
	offersHeight	: false,
	allowAutoScroll	: false,	
	daaEvent	    : false,
	
	// Switch to landing section (no zip, no vehicle), allows user to choose a zip
	gotoLanding : function() {
		this.hideNav();
		this.hidePromos();
		this.scrollTo('landingSection');
		$('landingSection').setStyle('width','938px');
		$('frame').setStyle('width','938px');
	},
	
	// Switch to zip section (yes zip, no vehicle), allows user to choose a vehicle
	// zipValue parameter is used for passing a zipcode global to be saved.
	gotoZip : function(zipValue) {
		if (zipValue) {
			zipHandler.save($(zipValue+'_input').getProperty('value'));
			
			// If a vehicle is known (e.g. via the URL) just hop right on over to that
			if (_family) {
				this.gotoVehicle(_family, _modelYear);
				return;
			}
		}
		$("zipSection").setStyle("visibility","visible");
		$('zipSection').setStyle('background-image','url("/dma/assets/backgrounds/zip_landing.jpg")');	
		this.updateHeaderDetails();
		this.scrollTo('zipSection');
		this.showNav();
		this.showPromos();
	},

	// Switch to a specific vehicle section (yes zip, yes vehicle)
	// vehicle, year parameters allow for vehicle and year globals to be saved.
	gotoVehicle : function(vehicle, year, tab) {
		if (vehicle) {
			_family = vehicle;
		}
		
		if (year) {
			_modelYear = year;
		}
		
		if (tab) {
			_tab = tab;
		}
		else if (vehicle_config && _family) {
			if (vehicle_config[_family]) {
				if (_family == vehicle_config[_family].family) {
					//_tab = vehicle_config[_family].offer_type;
					_tab = "purchase";
				}
			}
		}
		
		// If daaOffers isn't defined we're on /en/incentives and need to go to the proper DAA site
		if (!daaOffers) {
			gotoDAAPage();
		}
		else {
			// Update the URL to include the new vehicle and zip information
			this.updatePermalink();
		
			// Since we are first loading a vehicle, prevent scrolling on the next offer display (which is auto-fired by loadOffers())
			this.allowAutoScroll = false;
		
			// Update highlighted vehicle in nav
			/* OLD NAV
			$$('#vehicleMenu li.incentives_item a').removeClass('navselected');
			if ($(vehicle+'_veh')) {
				$(vehicle+'_veh').addClass('navselected');
			}
			*/
		
			var vehicleData = nameplateData.vehicles[vehicle];
		
			// Override campaign details for this vehicle
			if (vehicleData.campaignOverride) {
				($$('#vehicleSection .campaignPromo')[0]).setStyle('backgroundImage', 'url("' + vehicleData.campaignImage + '")');
				($$('#vehicleSection .campaignText')[0]).setText(vehicleData.campaignText);
			}
		
			// Load in dealer data and PSAM data
			dealerConnector.load();
		
			this.showNav();
			this.showPromos();
			this.updateHeaderDetails();
			this.scrollTo('vehicleSection');
			this.hideOfferDetails();
			this.switchTabs(_tab); // calls this.loadOffers()
			this.getCampaign();
			
			// Run a list of functions that are pushed into the daaFuncs Array after clicking on vehicle
			for(i=0; i < vehFuncs.length; i++){
				eval(vehFuncs[i]);
			}
			
			$('vehiclePromoHeader').setStyle('backgroundImage', "url('" + nameplateData['vehicles'][vehicle]['image'] + "')");
			
			
			
			
		}
	},
	
	getCampaign : function() {
		if (daaOffers.logo) {
			
				if ((_family == "ram_2500"
						|| _family == "ram_3500"
						|| _family == "chassis_cab_3500"
						|| _family == "chassis_cab_4500"
						|| _family == "chassis_cab_5500"
						
				))
				{
					($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
						'backgroundImage': "url('/dma/img/dodge_tm_2_10_logo.png')",
						'backgroundRepeat': "no-repeat",
						'backgroundPosition': "2% top"
					});
				}
				
				
				
				
				/*if (daaOffers.logo == "epp_01_09"
					&& (_family == "sprinter"
						|| _family == "patriot"
						|| _family == "compass"
						|| _family == "caliber"
						|| _family == "crossfire"
						|| _family == "pacifica"
						|| _family == "pt_convertible"))
				{
					($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
						'backgroundImage': "url('')",
						'backgroundRepeat': "no-repeat",
						'backgroundPosition': "2% 35%"
					})
					;
				}*/
				else {
					if (window.ie6){
						var ext = ".gif";
					}
					else {
						var ext = ".png";
					}
					if (window.ie6){
						var dir = "gif/";
					}
					else {
						var dir = "";
					}
					if (_family == 'ram_1500') {
						if (vehicle_config[_family] !== undefined) {
							if (vehicle_config[_family].campaign != "") {
								if (vehicle_config[_family].campaign == "dodge_tm_02_09.png") {
									var pos = "0";
								}
								else {
									var pos = "2";
								}
								
								if(brand == "chrysler"){
									
									($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
										'backgroundImage': "url('/dma/img/"+dir+""+vehicle_config[_family].campaign+"')",
										'backgroundRepeat': "no-repeat",
										'backgroundPosition': "2% top",
										'height' : "240px",
										'position': 'relative',
										'top': '18px'
									});
									
								} else {

								($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
									'backgroundImage': "url('/dma/img/"+dir+""+vehicle_config[_family].campaign+"')",
									'backgroundRepeat': "no-repeat",
									'backgroundPosition': ""+pos+"% top",
									'height' : "240px"
								});
								
								}
							}
							else {
								
								if(brand == "chrysler"){
									
									($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
										'backgroundImage': "url('/dma/img/"+dir+""+brand+"_"+daaOffers.logo+"_logo"+ext+"')",
										'backgroundRepeat': "no-repeat",
										'backgroundPosition': "2% top",
										'height' : "240px",
										'position': 'relative',
										'top': '18px'
									});
									
								} else {
								
								($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
									'backgroundImage': "url('/dma/img/"+dir+""+brand+"_"+daaOffers.logo+"_logo"+ext+"')",
									'backgroundRepeat': "no-repeat",
									'backgroundPosition': "2% top"
								});
								
								}
							}
						}
					}
					else {
						try {
							if (vehicle_config[_family].campaign != "" && vehicle_config[_family] != undefined) {
								
								if(brand == "chrysler"){
									
									($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
										'backgroundImage': "url('/dma/img/"+dir+""+vehicle_config[_family].campaign+"')",
										'backgroundRepeat': "no-repeat",
										'backgroundPosition': "2% top",
										'height' : "240px",
										'position': 'relative',
										'top': '18px'
									});
									
								} else {
								
								($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
									'backgroundImage': "url('/dma/img/"+dir+""+vehicle_config[_family].campaign+"')",
									'backgroundRepeat': "no-repeat",
									'backgroundPosition': "2% top",
									'height' : "240px"
								});
								
								}
							}
							else {
								
								if(brand == "chrysler"){
									
									($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
										'backgroundImage': "url('/dma/img/"+dir+""+brand+"_"+daaOffers.logo+"_logo"+ext+"')",
										'backgroundRepeat': "no-repeat",
										'backgroundPosition': "2% top",
										'height' : "240px",
										'position': 'relative',
										'top': '18px'
									});
									
								} else {
								
								($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
									'backgroundImage': "url('/dma/img/"+dir+""+brand+"_"+daaOffers.logo+"_logo"+ext+"')",
									'backgroundRepeat': "no-repeat",
									'backgroundPosition': "2% top"
								});
								
								}
							}
						}
						catch(err){
							
							if(brand == "chrysler"){
								
								($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
									'backgroundImage': "url('/dma/img/"+dir+""+brand+"_"+daaOffers.logo+"_logo"+ext+"')",
									'backgroundRepeat': "no-repeat",
									'backgroundPosition': "2% top",
									'height' : "240px",
									'position': 'relative',
									'top': '18px'
								});
								
							} else {
							
							($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
								'backgroundImage': "url('/dma/img/"+dir+""+brand+"_"+daaOffers.logo+"_logo"+ext+"')",
								'backgroundRepeat': "no-repeat",
								'backgroundPosition': "2% top"
							});
							
							}
						}
					}
				}
			
		}
		else {
			if (nameplateData.vehicles[_family].campaignImage != '') {
				if (dealerConnector.event == true) {
					($$('#vehiclePromoHeader .campaignPromo')[0]).setStyle('background-image', "");
				}
				else {
					
					if(brand == "chrysler"){
						
						($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
							'backgroundImage': "url('/dma/img/"+dir+""+vehicle_config[_family].campaign+"')",
							'backgroundRepeat': "no-repeat",
							'backgroundPosition': "2% top",
							'height' : "240px",
							'position': 'relative',
							'top': '18px'
						});
						
					} else {
					
					($$('#vehiclePromoHeader .campaignPromo')[0]).setStyle('background-image', "url('"+nameplateData.vehicles[_family].campaignImage+"')");
					
					}
				}
			}
			else if (_family && vehicle_config[_family]) {
				if (dealerConnector.event == true) {
					($$('#vehiclePromoHeader .campaignPromo')[0]).setStyle('background-image', "");
				}
				else {
					
					if(brand == "chrysler"){
						
						($$('#vehiclePromoHeader .campaignPromo')[0]).setStyles({
							'backgroundImage': "url('/dma/img/"+dir+""+vehicle_config[_family].campaign+"')",
							'backgroundRepeat': "no-repeat",
							'backgroundPosition': "2% top",
							'height' : "240px",
							'position': 'relative',
							'top': '18px'
						});
						
					} else {
					
					($$('#vehiclePromoHeader .campaignPromo')[0]).setStyle('background-image', "url('/dma/img/"+dir+""+vehicle_config[_family].campaign+"')");
					
					}
				}
			}
			else {
				($$('#vehiclePromoHeader .campaignPromo')[0]).setStyle('background-image', "");
			}
		}
	},
	
	switchTabs : function(newTab) {
		_tab = newTab;

		// Unhighlight old tab
		($$('#incentiveTabs a.current')[0]).removeClass('current');
		
		// Highlight new tab
		($$('#incentiveTabs a.'+newTab+'_tab')[0]).addClass('current');
		
		if (_tab == 'lease'){
			$$('.dealerBtns ul li')[0].setStyle('display','none');
		}
		else {
			$$('.dealerBtns ul li')[0].setStyle('display','block');
		}
		
		var vehicleData = nameplateData.vehicles[_family];
		
		// Hide offer details
		this.hideOfferDetails();
		
		// Reload data and display it
		this.loadOffers();
	},
	
	// Loads in offers from PSAM and custom offers
	loadOffers : function() {
		// Clear out the last array of offers
		_offers = new Array();
			
		var vehicleData = nameplateData.vehicles[_family];
		
		if (!vehicleData.disable) {
			var loader = new Ajax('/dma/loader/loader.xml', {	
				method : 'get',	 
				onComplete : function(text, xml) {
					var thisEvent = xml.getElementsByTagName("loader");
					var daaEvent = thisEvent[0].firstChild.nodeValue;

					if (daaEvent == 'true') {
				      	dealerConnector.event = true;
					
						displayHandler.loadCustomOffers(vehicleData[_tab+'Offers']);
						siloConnector.load();
						displayHandler.showIncentives(vehicleData.disable);
			 		}
					else if (daaOffers) {
						displayHandler.loadDAAOffers();
						
						displayHandler.loadCustomOffers(vehicleData[_tab+'Offers']);
						
						siloConnector.load();
						displayHandler.showIncentives(vehicleData.disable);
					}
				}
			}).request();
		}
	},
	
	
	
	/***************************************************************************************
	 *	PRIVATE FUNCTIONS FOLLOW
	 *	Don't call these unless you're calling them from within this object
	 ***************************************************************************************/
	
	// Initialize visual tools and handle creation of dynamic elements
	init : function() {
		// Ensure vehicle_config is at least defined (important for /en/incentives/ which doesn't normally have this)
		if (typeof(vehicle_config) == 'undefined' || vehicle_config == null) {
			vehicle_config = null;
		}
		
		// Handle ZIP code acquisition
		if (getParameter('zip') != 'null' && getParameter('zip') != '') {
			_zip = getParameter('zip');
		}
		else if (getHashParameter('zip')) {
			_zip = getHashParameter('zip');
		}
		else if (userData.zipcode) {
			_zip = userData.zipcode;
		}
		
		// Handle family acquisition
		if (getParameter('family') != 'null' && getParameter('family') != '') {
			_family = getParameter('family');
		}
		else if (getHashParameter('family')) {
			_family = getHashParameter('family');
		}
		
		// Handle tab acquisition
		if (getParameter('tab') != 'null' && getParameter('tab') != '') {
			_tab = getParameter('tab');
		}
		else if (getHashParameter('tab')) {
			_tab = getHashParameter('tab');
		}
		else if (vehicle_config && _family) {
			if (vehicle_config[_family]) {
				if (_family == vehicle_config[_family].family) {
					_tab = "purchase";
				}
			}
		}
		
		// Reformat vehicle IDs from brand sites to custom IDs needed by PSAM
		switch (_family) {
			case 'grandcherokee':
				_family = 'grand_cherokee';
			break;
			case 'grandcaravan':
				_family = 'grand_caravan';
			break;
			case 'wranglerunlimited':
				_family = 'wrangler_unlimited';
			break;
			case 'ram_chassis_cab':
				_family = 'chassis_cab_3500'
			break;
			case 'ram_heavy_duty':
				_family = 'ram_3500';
			break;
			case 'ram_2500_3500':
				_family = 'ram_2500';
			break;
			default:
			_family = cur_vehicle;
			break;
		}
		
		// Ensure daaOffers is at least defined
		if (typeof(daaOffers) == 'undefined' || daaOffers == null) {
			daaOffers = null;
			
			// If we're on /en/incentives/ and we know a zip, hop over to the right DAA page
			if (_zip && _zip != 'null') {
				gotoDAAPage(true);
			}
		}
		// Initialize some DAA-specific stuff
		else {
			// If we don't have a zip code, get one
			if (!_zip) {
				zipHandler.change();
				
				// Update the set button to say Enter in just this one case
				($$('#zipInput a.default')[0]).setText('Enter');
			}
		
			// Write the tagline out on the vehicle page
			($$('#vehiclePromoHeader h1')[0]).setHTML(daaOffers.tagline);
		}
		
		// Initialize page scroller
		if (!this.scroller) {
			this.scroller = new Fx.Scroll('frame', {
				wait: false,
				duration: 0, // Set to 0 for inclusion of flash landing
				offset: {'x': 0, 'y': 0},
				transition: Fx.Transitions.Quad.easeInOut
			});
		}

		// Initialize whole window vertical scroller
		if (!this.vertScroller) {
			this.vertScroller = new Fx.Scroll(window, {
				wait: false,
				duration: 500,
				offset: {'x': 0, 'y': 0},
				transition: Fx.Transitions.Quad.easeInOut
			});
		}

		// Initialize whole window vertical scroller
		if (!this.promoFader) {
			if ($('promos')) {
				this.promoFader = new Fx.Styles('promos', {
					wait: false,
					duration: 500,
					offset: {'x': 0, 'y': 0},
					transition: Fx.Transitions.Quad.easeInOut
				});
			}
		}
		
		// Initialize navigation slide effect
		if (!this.navSlider) {
			this.navSlider = new Fx.Styles('vehicleMenu', {
				wait: false,
				duration: 0, // Set to 0 for inclusion of flash landing
				transition: Fx.Transitions.Quad.easeInOut,
				onStart: function() {
					if (this.element.getStyle('width') == '0px') {
						this.element.setStyle('display', 'block');
						this.element.getNext().setStyles({'width':'762px', 'overflow':'hidden'});
					}
				},
				onComplete: function() {
					if (this.element.getStyle('width') == '0px') {
						this.element.setStyle('display', 'none');
						this.element.getNext().setStyle('width', 'auto');
					}
				}
			});
			
			// Build up the vehicle menu
			var vehicleItems = nameplateData.vehicles.length;
			var vehicleData = nameplateData.vehicles;
			/* OLD NAV
			// Create <UL>
			var list = new Element('ul', {
				'id': 'incentives_list'
			}).injectInside('vehicleMenu');

			// Create internal <UL> header
			var vehlist_header = new Element('li', {
				'id': 'veh_header'
			}).injectInside('incentives_list');
			$('veh_header').setHTML('<h2>Vehicles</h2>');

			// Create <LI>s of the vehicle list
			for (var curVehicle in vehicleData) {
				new Element('li', {
					'id': 'incentives_'+vehicleData[curVehicle].id,
					'class': 'incentives_item'
				}).injectAfter('veh_header');

				$('incentives_'+vehicleData[curVehicle].id).setHTML('<a href="javascript:displayHandler.gotoVehicle(\'' + vehicleData[curVehicle].id + '\', \'' + vehicleData[curVehicle].model_year + '\')" name="&lpos=vehicles&lid=' + vehicleData[curVehicle].id + '" id="' + vehicleData[curVehicle].id + '_veh">' + vehicleData[curVehicle].displayName + '</a>');
			}
			*/
		}
		
		// Set campaign text across all three sections
		$$('p.campaignText').each(function(elt) {
			elt.setHTML(campaign.text);
		});
		
		// Wire up landing page zip input form
		$('landing_zip').addEvent('submit', function(e) {
			var input = $('landing_zip_input');
			
			if (parseInt(input.value, 10) && input.value.length == 5) {
				displayHandler.gotoZip('landing_zip');
			}
			else {
				// Error happened, explain to the user
				$('landing_zip_label').setHTML('<span class="error">Invalid ZIP code</span> &ndash; Enter your ZIP code to view current incentives for your area.');
			}
			
			// Cancel form submission and the resultant page reload
			new Event(e).stop();
		});
		
		// Wire up the landing page zip input form submitter button (which is itself an <a> and needs special handling)
		$('landing_zip_submit').addEvent('click', function(e) {
			$('landing_zip').fireEvent('submit', new Event(e));
		});
		
		// Set the appropriate background image
		if (_mlc != "/en/incentives;/"+brand+"/en/incentives") {
			if (daaOffers.logo) {
				if (userData.bandwidth == "high" || !userData.bandwidth) {
					$('zipSection').setProperty('style','background-image', 'url("")');
				}
				else {
					if (daaOffers.background) {
						$('zipSection').setStyle('background-image', 'url("/dma/assets/backgrounds/'+daaOffers.background+'.png")');
					}
					else {
						$('zipSection').setStyle('background-image', 'url("/dma/assets/backgrounds/'+daaOffers.logo+'.png")');
					}

					if (brand == 'chrysler') {
						($$('#vehiclePromoHeader .campaignPromo')[0]).setProperty('style', "background: url('/dma/img/"+brand+"_"+daaOffers.logo+"_logo.png') no-repeat 2% top; position: relative; top: 18px;");
					}
					else {
						($$('#vehiclePromoHeader .campaignPromo')[0]).setProperty('style', "background: url('/dma/img/"+brand+"_"+daaOffers.logo+"_logo.png') no-repeat 2% 35%;");
					}

					$('zipSection').setStyle('height', daaOffers.logo_height);
				}
			}
			else {
				$('zipSection').setStyle('background-image','url("/dma/assets/backgrounds/zip_landing.jpg")');	
			}
		}
		else {
			$('zipSection').setStyle('background-image','url("/dma/assets/backgrounds/zip_landing.jpg")');	
		}
	},
	
	// Scroll the page to the right section

	scrollTo : function(elt) {
		this.scroller.toElement(elt);
		this.curPage = elt;
	},
	
	// Show the vehicles list
	showNav : function() {
		if (!this.navVisible) {
			// Margin is how much right margin will be set on the vehicle menu
			var margin = 3;
			
			// Safari needs a little bit of extra love
			if (window.webkit) {
				$('vehicleMenu').setStyle('display', 'block');
				margin += 10;
			}
			
			// Menu is hidden, make visible
			this.navSlider.start({
				'marginLeft': [0, 8],
				'marginRight': [0, margin],
				'width': [0, 161]
			});
			
			this.navVisible = true;
		}
	},

	// Hide the vehicles list
	hideNav : function() {
		if (this.navVisible) {
			// Menu is visible, make invisible
			this.navSlider.start({
				'marginLeft': [8, 0],
				'marginRight': [3, 0],
				'width': [161, 0]
			});
		
			this.navVisible = false;
		}
	},
	
	// Show the promos
	showPromos : function() {
		if (this.promoFader) {
			this.promoFader.start({'height': 135});
		}
	},

	// Hide the promos
	hidePromos : function() {
		if (this.promoFader) {
			this.promoFader.start({'height': 0});
		}
	},

	// Update the details in the site header
	updateHeaderDetails : function() {
		if (_zip) {
			var zip_header = $$('#incentivesHeader .page_title')[0];

			zip_header.empty();
			zip_header.setText('Current Incentives for ' + _daa_region + ' ZIP code ');
			zip_header.adopt(new Element('span', {'class': 'dynamicZipCode'}).setText(_zip));
			zip_header.adopt(new Element('a', {'id': 'change_zip', 'name': '&lid=change&lpos=content', 'href': 'javascript:zipHandler.change(\'zip_text\')'}).setText('change'));
		}
	},
	
	// Hide the offer details above the dealer list
	hideOfferDetails : function() {
		$('offerSpecifics').setStyle('display', 'none');
		$('offerInfo').setStyle('top', 0);
	},
	
	// Updates the permalink with the current vehicle and zip information
	updatePermalink : function() {
		//check for IE8
			function getInternetExplorerVersion() {
			var rv = -1; // Return value assumes failure.
				if (navigator.appName == 'Microsoft Internet Explorer') {
				var ua = navigator.userAgent;
        		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

       			 if (re.exec(ua) != null)
           			 rv = parseFloat(RegExp.$1);
						}
				 return rv;
		}

   		var ver = getInternetExplorerVersion();

		//if IE8 change URL to have ? instead of hash
    	if (ver >= 8.0){
             if (_family && _family != 'null' || _zip) {
			window.location.href = '?family=' + _family + '&zip=' + _zip + '#';
		}}
		
		else{
		if (_family && _family != 'null') {
			window.location.hash = 'family=' + _family;
		}
		else {
			window.location.hash = '';
		}
		
		if (_zip) {
			window.location.hash += '&zip=' + _zip;
		}}
	},
	
	
	/* Old code
	if (_family && _family != 'null') {
			window.location.hash = 'family=' + _family;
		}
		else {
			window.location.hash = '';
		}
		
		if (_zip) {
			window.location.hash += '&zip=' + _zip;
		}
	},
	*/
	// Loads in offers from DAA data
	loadDAAOffers : function() {
		for (var offer in daaOffers.offers) {
			var offerIter = daaOffers.offers[offer];
			
			if (typeof(offerIter) != 'function') {
				// Ensure this offer is for this vehicle and for the right tab
				if (offerIter.offer_type == _tab && offerIter.family == _family) {
					_offers.push(new DAAOffer(offerIter.offer_text,
											  offerIter.offer_details,
											  offerIter.disclaimers,
											  offerIter.model,
											  offerIter.veh_name,
											  offerIter.campaign,
											  offerIter.offer_type));
				}
			}
		}
	},
	
	// Loads in custom offers created in-house
	loadCustomOffers : function(offers) {
		for (var offer in offers) {
			_offers.push(new CustomOffer(offers[offer].text, offers[offer].details, offers[offer].disclaimer, _family));
		}
	},

	// Correctly sizes the offers div based on its content
	updatePageHeight : function() {
		var vertOffset = $('incentiveTabs').getPosition().y + $('incentiveTabs').getSize().size.y;
		
		// Get the two sizes so that we can compare and find the greatest of the two
		var listSize = -vertOffset + $('offersContainer').getPosition().y + $('offersContainer').getSize().size.y;
		var infoSize = -vertOffset + $('offerInfo').getPosition().y + $('offerInfo').getSize().size.y;
		
		var maxSize = (listSize > infoSize) ? listSize : infoSize;
		
		// Update the internal size var so that other resizing functions have the correct value
		this.offersHeight = maxSize;
		
		$('offers').setStyle('height', this.offersHeight + 'px');
	},
	
	// Print out the data from the parsed XML of offers
	showIncentives : function(killSwitch) {
		// Display data loading spinner graphic
		if ($$('#offersContainer img').length == 0) {
			$('offersContainer').setHTML("<img src='/shared/images/incentive/loader.gif' class='spinner' />");
		}
		
		// this.allowAutoScroll is disabled which means we need to enable it and then scroll up to the top of the just-loaded vehicle
		if (!this.allowAutoScroll) {
			this.vertScroller.toElement('wrapper');
		}
		
		// Ensure we have data ready to go before we go
		if (!siloConnector.dataReady && !siloConnector.siloDown) {
			setTimeout('displayHandler.showIncentives('+killSwitch+')', 1000);
			return;
		}		
		
		// katamari <http://en.wikipedia.org/wiki/Katamari> is a variable used to glom together a huge HTML string for eventual setHTML().
		var katamari = '<ul>';
		
		if (siloConnector.siloDown && _offers.length == 0 && _tab == 'lease') {
			$('offersContainer').setHTML("<span class='spinner'><li><h3>Please contact your dealer for all leasing options available to you</h3></li></span>");
			return;
		}
		else if (siloConnector.siloDown && _offers.length == 0 && _tab == 'purchase') {
			$('offersContainer').setHTML("<span class='spinner'><li><h3>Please contact your dealer for all purchase options available to you</h3></li></span>");
			return;
		}
		
		var vehicleData = nameplateData.vehicles[_family];
		

		
		// Make sure we have some offers before rolling on
		if (_offers.length && !killSwitch) {
			var prevOffer = null;
			var numOffers = _offers.length;
			
			// DAA offers
			for (var offerIndex = 0; offerIndex < numOffers; offerIndex++) {
				if (!(_offers[offerIndex] instanceof DAAOffer))
					break;
					
				katamari += '<li><h3>'+ _offers[offerIndex].vehName + ' Local Deal</h3></li>';
				katamari += '<li><a href=\'javascript:displayHandler.showOffer(' + offerIndex + ')\' id=\'purchaseOffer_'+offerIndex+'\'>' + _offers[offerIndex].getSentence() + '</a></li>';
				prevOffer = _offers[offerIndex];
			}
			
			if (prevOffer) {
				katamari += '</ul><br /><ul>';
				prevOffer = null;
			}

			// Custom offers
			for (var offerIndex = offerIndex; offerIndex < numOffers; offerIndex++) {
				if (!(_offers[offerIndex] instanceof CustomOffer))
					break;

				if (!prevOffer) {
					//katamari += '<li><h3>On eligible ' + nameplateData.vehicles[_family].displayName + ' models</h3></li>';
				}

				katamari += '<li><a href=\'javascript:displayHandler.showOffer(' + offerIndex + ')\' id=\'purchaseOffer_'+offerIndex+'\'>' + _offers[offerIndex].getSentence() + '</a></li>';

				prevOffer = _offers[offerIndex];
			}

			if (prevOffer) {
				prevOffer = null;
				katamari += '</ul><br /><ul>';
			}
			
			// Loop over all PSAM offers, aggregating details as we go
			for (var offerIndex = offerIndex; offerIndex < numOffers; offerIndex++) {
				// If we don't have a run of offers with identical trim levels and years (or we're the first run through i.e. prevOffer == null),
				// print out the title
				if (!prevOffer
					|| (prevOffer instanceof Offer
						&& (prevOffer.getYear() != _offers[offerIndex].getYear()
							|| prevOffer.getName() != _offers[offerIndex].getName())))
				{
					katamari += '<li><h3>' + _offers[offerIndex].getYear() + ' ' + _offers[offerIndex].getName() + '</h3></li>';
					var trimLevelIndex = 1;
				}

				katamari += '<li><a href=\'javascript:displayHandler.showOffer(' + offerIndex + ')\' id=\'purchaseOffer_'+offerIndex+'\'><span>Offer ' + trimLevelIndex + ':</span> ' + _offers[offerIndex].getSentence() + '</a></li>';

				trimLevelIndex++;
				prevOffer = _offers[offerIndex];
			}
		}
		else {
			//katamari += '<li><h3>' + vehicleData.model_year + ' ' + vehicleData.displayName + '</h3></li>';
			katamari += '<li class=\'nonOffer\'>Contact a dealer for your best offer.</li>';
		}
		
		katamari += '</ul>';
		
		$('offersContainer').setHTML(katamari);
		
		// Recalculate the height of the offers area to allow correct resizing of the page as the user moves between offers
		this.updatePageHeight();
		
		// And show the first offer by default
		var promoCode = getParameter("promoCode");
		if (!killSwitch) {
			if(promoCode != ""){
				displayHandler.showOffer(getManual())
			} else {
				this.showOffer(0);
			}
		}
		
		
		
		
		
		
	},
	
	// Show the selected offer's details above the dealer list
	showOffer : function(offerIndex) {
		// Update the selected offer global var, do this even if there are no offers such that _selectedOffer == null in that case
		_selectedOffer = _offers[offerIndex];
		
		// Do update-y things if there are offers to display and tidy up after
		if (_offers.length) {
			// update the disclaimers
			offerDisc();
			
			// Reveal offer details
			$('offerSpecifics').setStyle('display', 'block');
			
			// offerLine is the just-clicked on offer
			var offerLine = $('purchaseOffer_'+offerIndex);
		
			// offerLineOffset is the visual distance from the top of the offers container to the top of this offer
			var offerLineOffset = offerLine.getPosition().y - $('offersContainer').getPosition().y;
			
			// Display the new HTML describing the selected offer
			$('offerTableHolder').setHTML(_selectedOffer.getDetails());
			
			// offerSpecificsHeight is the height of div#offerSpecifics but calculated creatively to get around IE6's inadequacies
			var offerSpecificsHeight = $('dealerList').getPosition().y - $('offerInfo').getPosition().y;
			
			// And a little more IE6 love to make it tall enough to show the promo tiles
			if (window.ie6) {
				offerSpecificsHeight += 40;
			}
			
			// Update the height of the vehicle section as a whole to accomodate his offer
			$('offers').setStyle('height', (
				this.offersHeight
				+ offerLineOffset
				+ offerSpecificsHeight)+'px'
			);
			
			// Update the offer with the 'current' class
			$$('#offersContainer a.current').each(function(elt) {
				elt.removeClass('current');
			});
			offerLine.addClass('current');
		
			// Relocate the offer info & dealer list to line up with the selected offer
			$('offerInfo').setStyle('top', offerLineOffset + 'px');
			
			// Scroll to this offer if we haven't just loaded a vehicle
			if (displayHandler.allowAutoScroll) {
				// If the rightside offer information fits entirely within the window scroll to the bottom of it, otherwise
				// scroll to the top of it minus a small (40px) offset
				if ($('offerInfo').getSize().size.y <= window.getSize().size.y) {
					this.vertScroller.scrollTo(0, $('offerInfo').getPosition().y
					 							  - (window.getSize().size.y
					 							  - $('offerInfo').getSize().size.y));
				}
				else {
					this.vertScroller.scrollTo(0, offerLine.getPosition().y - 40);
				}
			}
			else {
				// Allow auto-scrolling for any further actions that result in a run through showOffer()
				this.allowAutoScroll = true;
			}
			
			// Tracking
			// if (_selectedOffer instanceof Offer) {
			// 	var trackingCode = nameCleaner(_family)+'/'+nameCleaner(_selectedOffer.getKind())+'/';
			// }
			// else if (_selectedOffer instanceof CustomOffer) {
			// 	var trackingCode = nameCleaner(_family)+'/'+nameCleaner(_selectedOffer.getSentence()).replace(',', '')+'/';
			// }
			// else if (_selectedOffer instanceof DAAOffer) {
			// 	var trackingCode = nameCleaner(_family)+'/'+nameCleaner(_selectedOffer.getKind())+'/';
			// }
			// pageTrack(trackingCode, trackingCode);
			
			printOffer();
			
			// IE needs a little help preventing window.location.hash's text from appearing in the window's title.  Nuke that.
			if (window.ie7) {
				if (document.title.indexOf('#') != -1) {
					document.title = document.title.slice(0, document.title.indexOf('#'));
				}
			}
		}
	}
}



//
//	zipHandler controls the popup zip changing panel and the saving and displaying of zipcodes around the page.
//
var zipHandler = {
	fader : null,

	// Bring up zip changing panel
	change : function(scrollHere) {
		scrollHere = scrollHere || false;
		
		if (!this.fader) { this.init(); }

		// Fade in panel
		this.fader.start(1);
		
		if (scrollHere == true) {
			displayHandler.vertScroller.toElement('zipInput');
		}
	},

	// Save zip code from panel
	// zipValue is a shortcut that allows you to tell this to simply write the passed in value straight to a
	// cookie without bothering with visual elements.
	save : function(zipValue) {
		if (zipValue) {
			_zip = zipValue;
			
			userData.zipcode = _zip;
			Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
			$('dealer_finder').setStyle('display','none');
			
			// If daaOffers isn't defined we're on /en/incentives/ and need to now go to the right DAA site
			if (!daaOffers) {
				gotoDAAPage(true);
			}
			else {
				populate_dealerInfo();
				displayHandler.updatePermalink();
				displayHandler.updateHeaderDetails();
			}

			// We've written data out and we have no need to continue dealing with visuals, exit out.
			return;
		}
		
		// zipValue wasn't passed in, so grab the value from the zip popup div, validate it and write it to internal storage
		else {
			if (!this.fader) { this.init(); }

			var input = $('zipInput_field').value;

			if (parseInt(input, 10) && input.length == 5) {
				input = parseInt(input, 10); // strip out any errant whitespace/text
				while (input.toString().length < 5) {
					input = '0' + input.toString();
				}
				_zip = input;

				// Set cookie for futurereference
				userData.zipcode = _zip;
				Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
				$('dealer_finder').setStyle('display','none');
				
				gotoDAAPage();
				
				populate_dealerInfo();
				displayHandler.updateHeaderDetails();

				// Hide panel, update zip code around page
				this.fader.set(0);
				$$('.dynamicZipCode').each(function(text) {
					text.setText(_zip);
				});
			
				// Also hide the possibly visible error text
				$('zipInput_label').setStyle('display', 'none');
				
				// Also change the possibly renamed Enter/Change button (button text may change if page is loaded with no known zip)
				if (($$('#zipInput a.default')[0]).getText() == 'Enter') {
					($$('#zipInput a.default')[0]).setText('Change');
				}
			
				// Reload vehicle content
				if (displayHandler.curPage == 'vehicleSection') {
					dealerConnector.load();
					displayHandler.updatePageHeight();
				
					if (_family) {
						displayHandler.loadOffers();
					}
				}
			}
			
			// Entered zip code is invalid
			else {
				$('zipInput_label').setStyle('display', 'block');
			}
		}
	},

	// Cancel panel action
	cancel : function() {
		if (!this.fader) { this.init(); }

		// Hide panel, reset field
		this.fader.set(0);
		$('zipInput_field').value = _zip;
	},



	/***************************************************************************************
	 *	PRIVATE FUNCTIONS FOLLOW
	 *	Don't call these unless you're calling them from within this object
	 ***************************************************************************************/

	// Setup zip changing panel
	init : function() {
		if (!this.fader) {
			this.fader = new Fx.Style('zipInput', 'opacity', {
				wait: false,
				duration: 250,
				transition: Fx.Transitions.Quad.easeInOut,
				onStart: function() {
					// Clear the previous zip code
					$('zipInput_field').setProperty('value', '');
				},
				onComplete: function() {
					if (this.element.getStyle('opacity') == 1) {
						// Focus on the input
						$('zipInput_field').focus();
					}
				}
			});

			// Set initial zip code so it has the value from the user's cookie
			$('zipInput_field').setProperty('value', _zip);
			
			// Recreate normal form return-key-press behavior
			$('zipInput_field').addEvent('keypress', function(e) {
				if (e.keyCode == 13) {
					linkTrack('zip_changer', 'save_button');
					zipHandler.save();
				}
				else if (e.keyCode == 27) {
					linkTrack('zip_changer', 'cancel_button');
					zipHandler.cancel();
				}
			});
		}
	}
}


//
//	siloConnector handles dynamic loading and parsing of PSAM data for relevant vehicles
//
var siloConnector = {
	dataReady	: false,
	siloDown	: false,
	
	// Load in PSAM data for this vehicle, highlight relevant menu and setup parser to handle data return
	load : function(selected, id) {
		this.dataReady = false;
		this.siloDown = false;
		
		// PSAM URL
		//var url = '/incentives/IncentivesXMLController.do?brand=' + brand + '&zip=' + _zip + '&family=' + _family;
		
		// Autodata URL		
		var url = '/hostd/getincentivedetails.xml?languageCode=&brand='+ brand.capitalize() +'&year=&zip='+ _zip +'&bodymodel=&family='+_family;
				
				
		var xmlDoc = new Ajax(url, {
			method: 'get',
			onComplete: function(text, xml) {
				this.parse(text, xml);
			}.bind(this),
			onFailure: function(requester) {
				this.siloDown = true;
			}.bind(this)
		}).request();
	},
	
	// Here be dragons
	parse : function(text, xml) {
		// Loop over all model years
		var modelYearsXML = xml.getElementsByTagName('modelyear');
		var numYears = modelYearsXML.length;
		for (var yearElt = 0; yearElt < numYears; yearElt++) {
			// Get the model year
			var curYear = modelYearsXML[yearElt]['attributes'][0]['nodeValue'];
			
			// Loop over all vehicle trim levels
			var vehiclesXML = modelYearsXML[yearElt].getElementsByTagName(_tab+'Vehicle');
			var numVehicles = vehiclesXML.length;
			for (var vehicleElt = 0; vehicleElt < numVehicles; vehicleElt++) {
				// Get the vehicle trim level name
				var vehicleName = (vehiclesXML[vehicleElt].getElementsByTagName('description'))[0].firstChild.nodeValue;
				if (_tab == 'purchase')
					var vehiclePrice = stripNumber((vehiclesXML[vehicleElt].getElementsByTagName('base_price'))[0].firstChild.nodeValue);
				else
					var vehiclePrice = NaN;
				
				// Loop over all offers for this trim level
				var offersXML = vehiclesXML[vehicleElt].getElementsByTagName(_tab+'Offer');
				var numOffers = offersXML.length;
				for (var offerElt = 0; offerElt < numOffers; offerElt++) {
					// Get the offer for this vehicle
					var offerJSON = Json.evaluate(xml2json(offersXML[offerElt], " "));
					_offers.push(new Offer(vehicleName, curYear, vehiclePrice, offerJSON, _family));
				}
			}
		}

		this.dataReady = true;
	}
}

// Pulls out an integer from a string (clears whitespaces, etc)
function stripNumber(str) { return parseInt(str.replace(/\D/g, '')); }

// Identical to getParameter() except sniffs the contents of the URLs # anchors instead of the standard ? 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;}}

//function estimatePayments() { flexWin("http://www.chryslerfinancial.com/payments/index.jsp?brand="+brand,"yes","715","600","dealer_website","all"); }
function estimatePayments() { wrap ('cf_pmt_est', 'zipcode='+_zip+'', _family, ''); }

// 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 ;
}

// Jumps to the DAA page for the current zipcode (in the _zip var)
function gotoDAAPage(force) {
	force = force || false;
	
	if (parseInt(_zip, 10)) {
		input = parseInt(_zip, 10); // strip out any errant whitespace/text
		while (input.toString().length < 5) {
			input = '0' + input.toString();
		}
	}

	var dealerRequest = new Ajax("/hostd/getlocatedealersbasic.xml?zip="+_zip+"&is"+brand.capitalize()+"=Y", {
		method: 'get',
		onComplete: function(text, xml) {
			dma = daaLookup(xml);
			
			if (force || (daaOffers && dma != daaOffers.dma && dma != undefined)) {
				if (dma == undefined) {
					window.location.replace("/dma/index.html?zip="+_zip+"&family="+_family);
				}
				else {
					window.location.replace("/dma/"+dma+"/index.html?zip="+_zip+"&family="+_family);
				}
			}
		}
	}).request();
}




function DAAOffer(inSentence, inDetails, inDisclaimers, inModel, inVehName, inCampaign, inKind, inPrice) {
	this.sentence = inSentence;
	this.details = '<div id=\'textDetails\'>'+inDetails+'</div>';
	this.disclaimers = inDisclaimers;
	this.model = inModel;
	this.vehName = inVehName;
	this.campaign = inCampaign;
	this.kind = inKind;
	this.price = 0;
	
	// Set the member function references in the class prototype
	if (typeof(_daaoffer_prototype_called) == 'undefined') {
		_daaoffer_prototype_called = true;
		DAAOffer.prototype.getKind = getKind;
		DAAOffer.prototype.getPrice = getPrice;
		DAAOffer.prototype.getModel = getModel;
		DAAOffer.prototype.getDetails = getDetails;
		DAAOffer.prototype.getVehName = getVehName;
		DAAOffer.prototype.getCampaign = getCampaign;
		DAAOffer.prototype.getSentence = getSentence;
		DAAOffer.prototype.getDisclaimer = getDisclaimer;
		DAAOffer.prototype.getDisclaimers = getDisclaimers;
		DAAOffer.prototype.getDisclaimerCount = getDisclaimerCount;
	}

	// Getters!
	function getKind() { return this.kind; }
	function getPrice() { return this.price; }
	function getModel() { return this.model; }
	function getDetails() { return this.details; }
	function getVehName() { return this.vehName; }
	function getCampaign() { return this.campaign; }
	function getSentence() { return this.sentence; }
	function getDisclaimer(which) { return this.disclaimers[which]; }
	function getDisclaimers() { return this.disclaimers; }
	function getDisclaimerCount() { return this.disclaimers.length; }
}




function CustomOffer(inSentence, inDetails, inDisclaimer, inModel) {
	this.sentence = inSentence;
	this.details = '<div id=\'textDetails\'>'+decodeURI(inDetails)+'</div>';
	this.model = inModel;
	this.disclaimer = inDisclaimer;
	this.price = 0;
	
	// Set the member function references in the class prototype
	if (typeof(_customoffer_prototype_called) == 'undefined') {
		_customoffer_prototype_called = true;
		CustomOffer.prototype.getDetails = getDetails;
		CustomOffer.prototype.getSentence = getSentence;
		CustomOffer.prototype.getDisclaimer = getDisclaimer;
		CustomOffer.prototype.getPrice = getPrice;
	}

	// Getters!
	function getDetails() { return this.details; }
	function getSentence() { return this.sentence; }
	function getDisclaimer() { return this.disclaimer; }
	function getPrice() { return this.price; }
}




// Define Offer class
// An Offer holds all of its raw incentives JSON raw from the PSAM feed along with cherry-picked data
// values pertinent to the offer as a whole. Additionally, the Offer controls how it displays itself.
function Offer(inName, inYear, inPrice, inIncentives, inModel) {
	// initialize the member variables for this instance
	this.name = inName;
	this.year = inYear;
	this.price = inPrice;
	this.model = inModel;
	
	if (_tab == 'purchase')
		this.incentives = inIncentives.purchaseOffer;
	else if (_tab == 'lease')
		this.incentives = inIncentives.leaseOffer;

	this.kind = null;
	this.sentence = "Get ";
	this.details = '';
	this.savingsTotal = 0;
	this.savings = new Array();
	this.APR = new Object();
	
	// Create the temporary array of data pilfered from the passed-in JSON array
	var incentivesFound = new Array();
	
	// contains() is a function available in incentivesFound that returns the location of the passed-in string if it is the name attribute
	// of some object in incentivesFound. 0 otherwise.
	incentivesFound.contains = function(input) {
		for (var i in this)
			if (typeof(this[i]) != 'function')
				if (this[i].name == input)
					return i + 1;
		return 0;
	}

	// getByName() is a function available in incentivesFound that returns the object in incentivesFound with the passed-in
	// name. Object assumed to exist.
	incentivesFound.getByName = function(input) {
		for (var i in this)
			if (typeof(this[i]) != 'function')
				if (this[i].name == input)
					return this[i];
		return false;
	}

	// Build up the list of kinds of incentives found for parsing later...
	// The index property is the index number of the <incentive> within its parent <purchase/leaseOffer>. If it is the only
	// <incentive> (and thus not part of an array) use the index value -1.
	if (this.incentives.incentive.length) {
		for (var index in this.incentives.incentive) {
			if (typeof(this.incentives.incentive[index]) != 'function') {
				incentivesFound.push({
					'name' : this.incentives.incentive[index].$name,
					'value': this.incentives.incentive[index].$value,
					'index': index
				});
			}
		}
	}
	else {
		incentivesFound.push({
			'name' : this.incentives.incentive.$name,
			'value': this.incentives.incentive.$value,
			'index': -1
		});
	}


	
	// Switch on the name of the <purchase/leaseOffer> contained by this Offer.  Case by case handling is provided by each
	// specific case herein.
	switch(this.incentives.$name) {
		case 'Cash_Allowance':
			this.kind = 'Cash_Allowance';

			// Check to see if this type of incentive was found in the initial pass through of the data for this offer.
			if (incentivesFound.contains('customer_cash')) {
				// incentive is the temporary variable used to store the name/value of this specific incentive
				var incentive = incentivesFound.getByName('customer_cash');

				// savings is the temporary variable used to store the numeric value of the specific cash savings provided
				// by this incentive
				var savings = stripNumber(incentive.value);

				// Add this data to the offer-describing sentence
				this.sentence += "$" + insertCommas(savings);
				this.sentence += " Customer Cash Allowance";

				// Add this savings data to the running total of savings and to the array describing each individual portion
				// of the total savings
				this.savingsTotal += savings;
				this.savings.push({
					'Customer Cash Allowance': savings
				});
			}

			if (incentivesFound.contains('gmac_bonus_cash')) {
				var incentive = incentivesFound.getByName('gmac_bonus_cash');
				var savings = stripNumber(incentive.value);

				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " GMAC Bonus Cash<sup>[6]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'GMAC Bonus Cash<sup>[6]</sup>': savings
				});
			}
			
			if (incentivesFound.contains('owner_loyalty_cash')){
				var incentive = incentivesFound.getByName('owner_loyalty_cash');
				var savings = stripNumber(incentive.value);
				
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				
				this.sentence += insertCommas(savings);
				this.sentence += " Owner Loyalty Cash<sup>[4]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'Owner Loyalty Cash<sup>[4]</sup>': savings
				});
			}
			
			var bonusSavings = 0;
			if (incentivesFound.contains('bonus_cash')) {
				var incentive = incentivesFound.getByName('bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash2')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash2');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('bonus_consumer_cash')) {
				var incentive = incentivesFound.getByName('bonus_consumer_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('retail_purchase_bonus_cash')) {
				var incentive = incentivesFound.getByName('retail_purchase_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			
			if (bonusSavings > 0) {
				
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				
				
				this.sentence += insertCommas(bonusSavings);
				this.sentence += " Bonus Cash Allowance";

				this.savingsTotal += bonusSavings;
				this.savings.push({
					'Bonus Cash': bonusSavings
				});
			}
			

			if (incentivesFound.contains('national_bonus_cash') && incentivesFound.contains('regional_bonus_cash')) {
				var incentive = incentivesFound.getByName('national_bonus_cash');
				var savings = stripNumber(incentive.value);
				var incentive2 = incentivesFound.getByName('regional_bonus_cash');
				var savings2 = stripNumber(incentive2.value);

				this.sentence += ", $";
				this.sentence += insertCommas(savings);
				this.sentence += " National Bonus Cash Allowance and $";
				this.sentence += insertCommas(savings2);
				this.sentence += " Regional Bonus Cash Allowance";

				this.savingsTotal += savings;
				this.savingsTotal += savings2;
				this.savings.push({
					'National Bonus Cash': savings
				});
				this.savings.push({
					'Regional Bonus Cash': savings2
				});
			}


			// Build up details text blob for this offer
			if (daaOffers.logo == "epp_01_09" || daaOffers.logo == "custom_epp_01_09") {
				// Build up details text blob for this offer
				this.details += '<table><tr>';
			}
			else {
				// Build up details text blob for this offer
				this.details += '<table><tr>';
				this.details += '<td class="label">Base MSRP*</td>';
				this.details += '<td class="value">';
				if (!isNaN(this.price)) {
					this.details += '$' + insertCommas(this.price);
				}
				else {
					this.details += 'N/A';
				}
			
			}
			this.details += '</td></tr>';

			// Add in a row per kind of cash savings
			for (var savings in this.savings) {
				if (typeof(this.savings[savings]) != 'function') {
					for (var obj in this.savings[savings]) {
						this.details += '<tr><td class="label">' + obj + '</td>';
						this.details += '<td class="value">$' + insertCommas(this.savings[savings][obj]) + '</td></tr>';
					}
				}
			}

			// If we have an MSRP, show the net savings
			
			if (daaOffers.logo == "epp_01_09" || daaOffers.logo == "custom_epp_01_09") {
				this.details += '<tr><td class="label"></td>';
				this.details += '<td class="value"></td></tr>';
			}
			else if (!isNaN(this.price)) {
				this.details += '<tr><td class="label">Net Price</td>';
				this.details += '<td class="value">$' + insertCommas(this.price - this.savingsTotal) + '</td></tr>';
			}
			this.details += '</table>';
		break;



		case 'Standard_APR':
			this.kind = 'Standard_APR';

			if (incentivesFound.contains('standard_apr')) {
				this.sentence += "low APR financing";

				// Get the index of this <incentive> within its parent <purchase/leaseOffer> so as to see whether it was
				// part of an array of <incentive>s or not.
				// If it wasn't, it's index number will be -1.
				var incentiveIndex = (incentivesFound.getByName('standard_apr')).index;
				if (incentiveIndex != -1) {
					var months = (this.incentives.incentive[incentiveIndex].incentiveTerm.$name).split('/');
					var rates = (this.incentives.incentive[incentiveIndex].incentiveTerm.$value).split('/');
				}
				else {
					var months = (this.incentives.incentive.incentiveTerm.$name).split('/');
					var rates = (this.incentives.incentive.incentiveTerm.$value).split('/');
				}

				//Pass over the rates and trip out whitespace
				for (var rate in rates) {
					if (typeof(rates[rate]) != 'function') {
						rates[rate] = (rates[rate]).replace(/\s/g, '');
					}
				}

				// Assign the found months and rates data to object members for later retrieval
				this.APR.months = months;
				this.APR.rates = rates;
			}
			
			if (incentivesFound.contains('combo_apr')) {
				this.sentence += "low APR financing";

				// Get the index of this <incentive> within its parent <purchase/leaseOffer> so as to see whether it was
				// part of an array of <incentive>s or not.
				// If it wasn't, it's index number will be -1.
				var incentiveIndex = (incentivesFound.getByName('combo_apr')).index;
				if (incentiveIndex != -1) {
					var months = (this.incentives.incentive[incentiveIndex].incentiveTerm.$name).split('/');
					var rates = (this.incentives.incentive[incentiveIndex].incentiveTerm.$value).split('/');
				}
				else {
					var months = (this.incentives.incentive.incentiveTerm.$name).split('/');
					var rates = (this.incentives.incentive.incentiveTerm.$value).split('/');
				}

				//Pass over the rates and trip out whitespace
				for (var rate in rates) {
					if (typeof(rates[rate]) != 'function') {
						rates[rate] = (rates[rate]).replace(/\s/g, '');
					}
				}

				// Assign the found months and rates data to object members for later retrieval
				this.APR.months = months;
				this.APR.rates = rates;
			}
			
			if (incentivesFound.contains('combo_cash')) {
				var incentive = incentivesFound.getByName('combo_cash');
				var savings = stripNumber(incentive.value);

				this.sentence += " with $";
				this.sentence += insertCommas(savings);
				this.sentence += " Combo Cash Allowance";

				this.savingsTotal += savings;
				this.savings.push({
					'Combo Cash': savings
				});
			}
			
			if (incentivesFound.contains('owner_loyalty_cash')) {
				var incentive = incentivesFound.getByName('owner_loyalty_cash');
				var savings = stripNumber(incentive.value);
				
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " Owner Loyalty Cash<sup>[4]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'Owner Loyalty Cash<sup>[4]</sup>': savings
				});
			}
			
			if (incentivesFound.contains('customer_cash')) {
				var incentive = incentivesFound.getByName('customer_cash');
				var savings = stripNumber(incentive.value);
				
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " Customer Cash";

				this.savingsTotal += savings;
				this.savings.push({
					'Customer Cash': savings
				});
			}

			var bonusSavings = 0;
			if (incentivesFound.contains('bonus_cash')) {
				var incentive = incentivesFound.getByName('bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash2')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash2');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('bonus_consumer_cash')) {
				var incentive = incentivesFound.getByName('bonus_consumer_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('retail_purchase_bonus_cash')) {
				var incentive = incentivesFound.getByName('retail_purchase_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}

			if (bonusSavings > 0) {
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(bonusSavings);
				this.sentence += " Bonus Cash Allowance";

				this.savingsTotal += bonusSavings
				this.savings.push({
					'Bonus Cash': bonusSavings
				});
			}
			
			

			if (incentivesFound.contains('national_bonus_cash') && incentivesFound.contains('regional_bonus_cash')) {
				var incentive = incentivesFound.getByName('national_bonus_cash');
				var savings = stripNumber(incentive.value);
				var incentive2 = incentivesFound.getByName('regional_bonus_cash');
				var savings2 = stripNumber(incentive2.value);

				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " National Bonus Cash Allowance and $";
				this.sentence += insertCommas(savings2);
				this.sentence += " Regional Bonus Cash Allowance";

				this.savingsTotal += savings;
				this.savingsTotal += savings2;
				this.savings.push({
					'National Bonus Cash': insertCommas(savings)
				});
				this.savings.push({
					'Regional Bonus Cash': insertCommas(savings2)
				});
			}

			if (incentivesFound.contains('gmac_bonus_cash')) {
				var incentive = incentivesFound.getByName('gmac_bonus_cash');
				var savings = stripNumber(incentive.value);

				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " GMAC Bonus Cash<sup>[6]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'GMAC Bonus Cash<sup>[6]</sup>': savings
				});
			}


			// Build up details text blob for this offer
			this.details += '<table cellspacing="0" id="APR"><tr>';
			for (var month in this.APR.months) {
				if (typeof(this.APR.months[month]) != 'function') {
					var className = 'month';
					if (month == 0)
						className += ' first';

					this.details += '<td class="' + className + '">' + this.APR.months[month] + '</td>';
				}
			}
			this.details += '<td class="month first">months</td>';
			this.details += '</tr>';

			this.details += '<tr>';
			for (var rate in this.APR.rates) {
				if (typeof(this.APR.rates[rate]) != 'function') {
					var className = 'rate';
					if (rate == 0)
						className += ' first';

					this.details += '<td class="' + className + '">' + this.APR.rates[rate] + '</td>';
				}
			}
			this.details += '<td class="rate first">APR<sup>[5]</sup></td>';
			this.details += '</tr>';
			this.details += '</table>';
			
			//this.details += '<div id="bonusDetails">Financing Through <a href="javascript:estimatePayments()">Chrysler Financial</a></div>';

			if (this.savingsTotal) {
				this.details += '<table id="APRSavingsTable">';
				for (var savings in this.savings) {
					if (typeof(this.savings[savings]) != 'function') {
						for (var obj in this.savings[savings]) {
							this.details += '<tr><td class="label">' + obj + '</td>';
							this.details += '<td class="value">$' + insertCommas(this.savings[savings][obj]) + '</td></tr>';
						}
					}
				}
				this.details += '</table>';
			}
		break;

		case 'Combo':
		case 'Combo_APR':
			this.kind = 'Combo_APR';

			if (incentivesFound.contains('combo_apr')) {
				this.sentence += " an APR Combo";

				var incentiveIndex = (incentivesFound.getByName('combo_apr')).index;
				if (incentiveIndex != -1) {
					var months = (this.incentives.incentive[incentiveIndex].incentiveTerm.$name).split('/');
					var rates = (this.incentives.incentive[incentiveIndex].incentiveTerm.$value).split('/');
				}
				else {
					var months = (this.incentives.incentive.incentiveTerm.$name).split('/');
					var rates = (this.incentives.incentive.incentiveTerm.$value).split('/');
				}

				for (var rate in rates) {
					if (typeof(rates[rate]) != 'function') {
						rates[rate] = (rates[rate]).replace(/\s/g, '');
					}
				}

				this.APR.months = months;
				this.APR.rates = rates;
			}

			if (incentivesFound.contains('combo_cash')) {
				var incentive = incentivesFound.getByName('combo_cash');
				var savings = stripNumber(incentive.value);

				this.sentence += " with $";
				this.sentence += insertCommas(savings);
				this.sentence += " Combo Cash Allowance";

				this.savingsTotal += savings;
				this.savings.push({
					'Combo Cash': savings
				});
			}

			var bonusSavings = 0;
			if (incentivesFound.contains('bonus_cash')) {
				var incentive = incentivesFound.getByName('bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash2')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash2');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('bonus_consumer_cash')) {
				var incentive = incentivesFound.getByName('bonus_consumer_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('retail_purchase_bonus_cash')) {
				var incentive = incentivesFound.getByName('retail_purchase_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}

			if (bonusSavings > 0) {
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(bonusSavings);
				this.sentence += " Bonus Cash Allowance";

				this.savingsTotal += bonusSavings;
				this.savings.push({
					'Bonus Cash': bonusSavings
				});
			}

			if (incentivesFound.contains('gmac_bonus_cash')) {
				var incentive = incentivesFound.getByName('gmac_bonus_cash');
				var savings = stripNumber(incentive.value);

				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " GMAC Bonus Cash<sup>[6]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'GMAC Bonus Cash<sup>[6]</sup>': savings
				});
			}


			// Build up details text blob for this offer
			this.details += '<table cellspacing="0" id="APR"><tr>';
			for (var month in this.APR.months) {
				if (typeof(this.APR.months[month]) != 'function') {
					var className = 'month';
					if (month == 0)
						className += ' first';

					this.details += '<td class="' + className + '">' + this.APR.months[month] + '</td>';
				}
			}
			this.details += '<td class="month first">months</td>';
			this.details += '</tr>';

			this.details += '<tr>';
			for (var rate in this.APR.rates) {
				if (typeof(this.APR.rates[rate]) != 'function') {
					var className = 'rate';
					if (rate == 0)
						className += ' first';

					this.details += '<td class="' + className + '">' + this.APR.rates[rate] + '</td>';
				}
			}
			this.details += '<td class="rate first">APR<sup>[5]</sup></td>';
			this.details += '</tr>';
			this.details += '</table>';

			if (this.savingsTotal) {
				this.details += '<div id="bonusDetails">';
				this.details += '<span>+ $' + insertCommas(this.savingsTotal) + '</span>';

				for (var saving in this.savings) {
					if (typeof(this.savings[saving]) != 'function') {
						for (var object in this.savings[saving]) {
							this.details += object + ', ';
						}
					}
				}
				this.details = this.details.substr(0, this.details.length - 2);

				this.details += '</div>';
			}

				// edit for jeep and dodge
				if (brand == "jeep" || brand == "dodge"){
				this.details += '<div id="financial">Financing Through <a href="http://www.chryslerfinancial.com/">Chrysler Financial</a></div>';
				}
		break;



		case 'leaseOffer':
			this.kind = 'leaseOffer';

			// Check to see if this type of incentive was found in the initial pass through of the data for this offer.
			if (incentivesFound.contains('customer_cash')) {
				// incentive is the temporary variable used to store the name/value of this specific incentive
				var incentive = incentivesFound.getByName('customer_cash');

				// savings is the temporary variable used to store the numeric value of the specific cash savings provided
				// by this incentive
				var savings = stripNumber(incentive.value);

				// Add this data to the offer-describing sentence
				this.sentence += "$" + insertCommas(savings);
				this.sentence += " Customer Cash Allowance";

				// Add this savings data to the running total of savings and to the array describing each individual portion
				// of the total savings
				this.savingsTotal += savings;
				this.savings.push({
					'Customer Cash Allowance': savings
				});
			}
			
			if (incentivesFound.contains('gmac_bonus_cash')) {
				var incentive = incentivesFound.getByName('gmac_bonus_cash');
				var savings = stripNumber(incentive.value);

				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " GMAC Bonus Cash<sup>[6]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'GMAC Bonus Cash<sup>[6]</sup>': savings
				});
			}

			var bonusSavings = 0;
			if (incentivesFound.contains('bonus_cash')) {
				var incentive = incentivesFound.getByName('bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash2')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash2');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}

			if (bonusSavings > 0) {
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(bonusSavings);
				this.sentence += " Bonus Cash Allowance";

				this.savingsTotal += bonusSavings;
				this.savings.push({
					'Bonus Cash': bonusSavings
				});
			}

			if (incentivesFound.contains('bonus_lease_loyalty')) {
				var incentive = incentivesFound.getByName('bonus_lease_loyalty');
				var savings = stripNumber(incentive.value);
				
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				
				this.sentence += insertCommas(savings);
				this.sentence += " Lease Loyalty<sup>[4]</sup> Cash Allowance";
				

				this.savingsTotal += savings;
				this.savings.push({
					'Lease Loyalty<sup>[4]</sup> Cash': savings
				});
				}
			
			if (incentivesFound.contains('bonus_lease_cash')) {
				var incentive = incentivesFound.getByName('bonus_lease_cash');
				var savings = stripNumber(incentive.value);
				
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				
				this.sentence += insertCommas(savings);
				this.sentence += " Bonus Lease Cash Allowance";
				

				this.savingsTotal += savings;
				this.savings.push({
					'Bonus Lease Cash': savings
				});
				}



			if (incentivesFound.contains('national_bonus_cash') && incentivesFound.contains('regional_bonus_cash')) {
				var incentive = incentivesFound.getByName('national_bonus_cash');
				var savings = stripNumber(incentive.value);
				var incentive2 = incentivesFound.getByName('regional_bonus_cash');
				var savings2 = stripNumber(incentive2.value);

				this.sentence += ", $";
				this.sentence += insertCommas(savings);
				this.sentence += " National Bonus Cash Allowance and $";
				this.sentence += insertCommas(savings2);
				this.sentence += " Regional Bonus Cash Allowance";

				this.savingsTotal += savings;
				this.savingsTotal += savings2;
				this.savings.push({
					'National Bonus Cash': savings
				});
				this.savings.push({
					'Regional Bonus Cash': savings2
				});
			}

			if (incentivesFound.contains('lease_loyalty')) {
				var incentive = incentivesFound.getByName('lease_loyalty');
				var savings = stripNumber(incentive.value);

				this.sentence += ", and $";
				this.sentence += insertCommas(savings);
				this.sentence += " Lease Loyalty<sup>[4]</sup> Cash Allowance";

				this.savingsTotal += savings;
				this.savings.push({
					'Lease Loyalty<sup>[4]</sup> Cash': savings
				});
			}
			
			if (incentivesFound.contains('owner_loyalty_cash')){
				var incentive = incentivesFound.getByName('owner_loyalty_cash');
				var savings = stripNumber(incentive.value);
				
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				
				this.sentence += insertCommas(savings);
				this.sentence += " Owner Loyalty Cash<sup>[4]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'Owner Loyalty Cash<sup>[4]</sup>': savings
				});
			}


			// Build up details text blob for this offer
			this.details += '<table>';
			for (var savings in this.savings) {
				if (typeof(this.savings[savings]) != 'function') {
					for (var obj in this.savings[savings]) {
						this.details += '<tr><td class="label">' + obj + '</td>';
						this.details += '<td class="value">$' + insertCommas(this.savings[savings][obj]) + '</td></tr>';
					}
				}
			}
			this.details += '</table>';
		break;



		case 'Gas':
			this.kind = 'Gas';

			if (incentivesFound.contains('gas_card')) {
				var incentive = incentivesFound.getByName('gas_card');

				this.sentence += incentive.value;
				this.sentence += " Gas Guarantee [1]";
			}

			if (incentivesFound.contains('gas_cash')) {
				var incentive = incentivesFound.getByName('gas_cash');
				var savings = stripNumber(incentive.value);

				this.sentence += " plus $";
				this.sentence += insertCommas(savings);
				this.sentence += " Gas Card bonus cash";

				this.savingsTotal += savings;
				this.savings.push({
					'Gas Card Bonus Cash': savings
				});
			}

			if (incentivesFound.contains('lease_loyalty')) {
				var incentive = incentivesFound.getByName('lease_loyalty');
				var savings = stripNumber(incentive.value);

				this.sentence += ", and $";
				this.sentence += insertCommas(savings);
				this.sentence += " Lease Loyalty<sup>[4]</sup> Cash Allowance too!";

				this.savingsTotal += savings;
				this.savings.push({
					'Lease Loyalty<sup>[4]</sup> Cash': savings
				});
			}

			var bonusSavings = 0;
			if (incentivesFound.contains('bonus_cash')) {
				var incentive = incentivesFound.getByName('bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('misc_bonus_cash2')) {
				var incentive = incentivesFound.getByName('misc_bonus_cash2');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('bonus_consumer_cash')) {
				var incentive = incentivesFound.getByName('bonus_consumer_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}
			if (incentivesFound.contains('retail_purchase_bonus_cash')) {
				var incentive = incentivesFound.getByName('retail_purchase_bonus_cash');
				var savings = stripNumber(incentive.value);
				
				bonusSavings += savings;
			}

			if (bonusSavings > 0) {
				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(bonusSavings);
				this.sentence += " Bonus Cash Allowance";

				this.savingsTotal += bonusSavings;
				this.savings.push({
					'Bonus Cash': bonusSavings
				});
			}

			if (incentivesFound.contains('gmac_bonus_cash')) {
				var incentive = incentivesFound.getByName('gmac_bonus_cash');
				var savings = stripNumber(incentive.value);

				if(this.incentives.incentive.length > 0){
					this.sentence += " plus $";
				} else {
					this.sentence += " $";
				}
				this.sentence += insertCommas(savings);
				this.sentence += " GMAC Bonus Cash<sup>[6]</sup>";

				this.savingsTotal += savings;
				this.savings.push({
					'GMAC Bonus Cash<sup>[6]</sup>': savings
				});
			}

			// Build up details text blob for this offer
			this.details += '<div id="textDetails">';
			this.details += '<strong>Let\'s Refuel America. <a target="_blank" href="/en/refuel/">Learn More</a></strong>';
			if (incentivesFound.contains('gas_cash')) {
				this.details += '<br/>' + this.sentence;
			}
			this.details += '</div>';
		break;


		default:
			this.kind = 'Unknown';
			this.sentence = "Contact a dealer for your best offer.";
		break;
	}

	// Set the member function references in the class prototype
	if (typeof(_offer_prototype_called) == 'undefined') {
		_offer_prototype_called = true;
		Offer.prototype.getName = getName;
		Offer.prototype.getYear = getYear;
		Offer.prototype.getKind = getKind;
		Offer.prototype.getPrice = getPrice;
		Offer.prototype.getDetails = getDetails;
		Offer.prototype.getSentence = getSentence;
	}

	// Getters!
	function getName() { return this.name; }
	function getYear() { return this.year; }
	function getKind() { return this.kind; }
	function getPrice() { return this.price; }
	function getDetails() { return this.details; }
	function getSentence() { return this.sentence; }
}

onload_register('incentivesLoader();');
onload_register('setup_menus()');