/**
 * Albertsons Common Functions
 * Version 1.0.0 - 11/23/2008
 * @author Benjamin Truyman
 **/

var ABS = ABS || {};

// Albertsons Common
ABS.Common = {
	initialize: function () {
		if ($('#global-search').get(0)) { ABS.Common.GlobalSearch.initialize(); }
	}
};

// Global Search
ABS.Common.GlobalSearch = {
	buttons: {},
	containers: {},
	inputs: {},
	validator: null,
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#global-search').get(0);
		this.containers.form = $('#global-search-form').get(0);
		
		// Define buttons
		this.buttons.submit = $('#global-search-submit');
		
		// Define inputs
		this.inputs.query = $('#global-search-input').get(0);
		this.inputs.context = $('#global-search-context').get(0);
		
		// Create shortcut to validator
		this.validator = ABS.Helpers.FormValidator;
		
		// Build error popup
		this.buildError();
		
		// Build search form
		this.buildForm();
		
		// Build form validator
		this.buildValidator();
	},
	
	buildError: function () {
		var html = '<div id="global-search-error" class="callout-small">' +
			'	<div class="l"></div>' +
			'	<div class="c" >' +
			'	<div id="global-search-error-text">' +
			'		<p >Please enter the word or phrase you would like to search for.</p>' +
			'	</div>' + 
			'	</div>' +
			'	<div class="r"></div>' +
			'</div>';
		this.containers.error = ABS.Managers.Popup.add($(html));
		$(this.containers.error).css({
			position: 'absolute',
			top: $(this.containers.form).offset().top - $('#container').offset().top + 22,
			left: $(this.containers.form).offset().left - $('#container').offset().left
		});
	},
	
	buildForm: function () {
		$(this.buttons.submit).click(ABS.Utils.Delegate.create(this, this.handleSubmit));
		$(this.inputs.query).keydown(ABS.Utils.Delegate.create(this, this.handleInput));
	},
	
	buildValidator: function () {
		this.validator = ABS.Helpers.FormValidator({
			form: this.containers.form,
			elements: [
				{
					name: 'searchTerm',
					options: {
						required: true
					}
				}
			]
		});
	},
	
	handleInput: function (e) {
		if (e.keyCode === 13) {
			$(this.buttons.submit).trigger('click');
		}else{
			$(this.containers.error).fadeOut(200);
		}
	},
	
	handleSubmit: function (e) {
		var results = this.validator.run();
		if (results.areValid) {
			$(this.containers.form).wrapInner('<form action="' + $(this.buttons.submit).attr('href') + '" method="GET"></form>');
			$('form', this.containers.form).submit();
			e.preventDefault();
		} else {
			e.preventDefault();
			$(this.containers.error).fadeIn(200);
		}
		
	}
};

$(document).ready(function () {
	ABS.Common.initialize();
});
