/**
 * Albertsons Zip Code Entry
 * Version 1.0.0 - 12/29/2008
 * @author Benjamin Truyman
 **/

var ABS = ABS || {};

// Albertsons Homepage
ABS.ZIP = {
	initialize: function () {
		if ($('#zip-entry').get(0)) { ABS.ZIP.ZipEntry.initialize(); }
		ABS.ZIP.Popup.initialize();
	}
};

// Find A Store form
ABS.ZIP.ZipEntry = {
	buttons: {},
	containers: {},
	inputs: {},
	validator: null,
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#zip-entry').get(0);
		this.containers.form = $('#zip-entry-form').get(0);
		
		// Define buttons
		this.buttons.submit = $('#zip-entry-submit').get(0);
		
		// Define inputs
		this.inputs.zip = $('#zip-entry-zip');
		
		// Create shortcut to validator
		this.validator = ABS.Helpers.FormValidator;
		
		// Build search form
		this.buildForm();
		
		// Build form validator
		this.buildValidator();
	},
	
	buildForm: function () {
		$(this.containers.form).submit(ABS.Utils.Delegate.create(this, this.handleSubmit));
		$(this.inputs.zip).keyup(ABS.Utils.Delegate.create(this, this.handleInput));
	},
	
	buildValidator: function () {
		this.validator = ABS.Helpers.FormValidator({
			form: this.containers.form,
			elements: [
				{
					name: 'zip',
					options: {
						required: true,
						zip: true
					}
				}
			]
		});
	},
	
	handleInput: function (e) {
		// Clear out any input that is not a number
		if ($(this.inputs.zip).val().match(/[^0-9]/) !== null) {
			$(this.inputs.zip).val($(this.inputs.zip).val().replace(/[^0-9]/g, ''));
		}
	},
	
	handleSubmit: function (e) {
		var results = this.validator.run();
		if (!results.areValid) {
			if ($(this.inputs.zip).val().length === 0) {
				alert('Please enter a valid Zip Code.');
			} else {
				alert('Your zip code must be five digits long. Please re-enter your zip code.');
			}
			e.preventDefault();
		}
	}
};

ABS.ZIP.Popup = {
	buttons: {},
	containers: {},
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#zip-popup');
		
		// Define buttons
		this.buttons.close = $('#zip-popup-close').get(0);
		
		// Build Navigation
		this.buildNavigation();
	},
	
	buildNavigation: function () {
		$(this.buttons.close).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
	},
	
	showPopup: function () {
		$(this.containers.main).fadeIn(250);
	},
	
	hidePopup: function () {
		$(this.containers.main).fadeOut(250);
	},
	
	handleNavigation: function (e) {
		if (e.currentTarget === this.buttons.close) {
			this.hidePopup();
		}
	}
};

$(document).ready(function () {
	ABS.ZIP.initialize();
});

function setZip(){
	var zipcode = document.getElementById('zip-entry-zip').value;
	document.getElementById('zipCodeLLC').value = zipcode;
}