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 _selectedOffer	= null;


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 gotoDAAPage(force) {
	force = force || false;
	
	var cap = brand.capitalize();

	if (parseInt(_zip, 10)) {
		input = parseInt(_zip, 10); // strip out any errant whitespace/text
		while (input.toString().length < 5) {
			input = '0' + input.toString();
		}
	}
	

	var newurl = "/hostd/getlocatedealersbasic.xml?zip="+_zip+"&is"+cap+"=Y";
	var promo = getParameter("promoCode");
	var foo = new Ajax(newurl, {
		method: 'get',
		onComplete: function(text, xml) {
			dma = daaLookup(xml);
			if(parseInt(dma)){				
					var url = "/dma/"+dma+"/index.html?zip="+_zip+"&family="+_family;
					if(promo != ""){
						url += "&promoCode=true";
					}		
					window.location.replace(url);
			}
		}
	}).request();
}



function background(){
//window.addEvent('domready', function(){
		
		
	$('zipSection').setStyle('background-image','url("/dma/assets/backgrounds/zip_landing.jpg")');	

//});
}



//
//	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();
	displayHandler.gotoLanding();
}




//
//	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.scrollTo('landingSection');
		$('landingSection').setStyle('width','938px');
		$('frame').setStyle('width','938px');
	},
	
	
	
	/***************************************************************************************
	 *	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)
		
		
		// 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');
		} else {
			_family = "null";
		}
		
		// Handle tab acquisition
		if (getParameter('tab') != 'null' && getParameter('tab') != '') {
			_tab = getParameter('tab');
		}
		else if (getHashParameter('tab')) {
			_tab = getHashParameter('tab');
		}
		
		
		// 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 '2009avengersedan':
				_family = 'avenger';
			break;
			case '2009ptcruiser':
				_family = 'pt_cruiser';
			break;
			case '2009town_country':
				_family = 'town_country';
			break;
			case '2009sebringconvertible':
				_family = 'sebring_convertible';
			break;
			case 'null':
				_family = '';
			break;
			default:
				if(getParameter('family') != "null"){
					_family = _family.replace('2009','');				
				} else {
					_family = '';
				}
			break;
		}
		
		// Ensure daaOffers is at least defined
	
			// 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
	
		}
		// 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
			});
		}
		
		

		
		// 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) {
				zipHandler.save(input.value)
			} 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));
		});
	},
	
	// Scroll the page to the right section
	scrollTo : function(elt) {
		this.scroller.toElement(elt);
		this.curPage = elt;
		pageTrack(elt,elt);
	}
	
	
	
}





//
//	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
			
			gotoDAAPage(true);
			
			

			// 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');
				}
			
				
			}
			
			// 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
//

onload_register('background()');
onload_register('incentivesLoader();');
onload_register('setup_menus()');
