var _zip			= 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;}}

//
//	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.gotoZip();
}

//
//	displayHandler controls the state of the visual content of the site.  Slides between panels, renders new content.
//
var displayHandler = {
	
	// 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;
			}
		}
		
		this.updateHeaderDetails();
	},
	
	/***************************************************************************************
	 *	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;
		}
		
		// 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
	
		}
	},
	// 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 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'));
		}
	}
}

//
//	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.toString();
			
			userData.zipcode = zipValue.toString();
			Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
			Cookie.set("zipcode",zipValue.toString())
			__f = "?zip="+_zip;
			populate_dealerInfo();
			$('dealer_finder').setStyle('display','none');
			
			// 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.toString();

				// Set cookie for futurereference
				userData.zipcode = input.toString();
				Cookie.set('userdata', Json.toString(userData), {duration: 365, path: "/"});
				Cookie.set("zipcode",input.toString())
				__f = "?zip="+_zip;
				$('dealer_finder').setStyle('display','none');
				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');
			}
		}
		setupIncentivesNavAccordion(cur_page);
	},

	// 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('incentivesLoader();');
