/**
 * Auto A2Z Search handler
 * 
 * Provides a search interface for the AutoA2Z application
 * 
 * @author Ollie Maitland
 * @copyright Byng Systems LLP
 */

var AUTO_PARAM_MODELS = 'model';
var AUTO_PARAM_MAKES  = 'make';
var AUTO_POSTCODE_EMPTY = ' - Enter postcode -';

var AutoSearch = new Class(
{
	Implements: Options,
    options: {
        makeId  : [],
        modelId : [],
        price: {
            min: 0,
            max: 10000
        }
    },
    
    /**
     * Holds the request stub
     * 
     * @param ByngRequest
     */
    gateway : new ByngRequest('default','search','site','ajax'),
	
	/**
	 * Initialise the search 
	 * 
	 * @param Element container
	 * @param Object options
	 */
	initialize : function (container, options)
	{
		this.setOptions(options);
		this.setContainer(container);
	},
	
	/**
	 * Set the container and attach behaviour
	 * 
	 * @param Element container
	 */
	setContainer : function (container)
	{
		// attach behaviour
		if (container.getElement('select.make').value == 'null') {
			container.getElement('select.model').setProperty('disabled','disabled');
		}
		
		container.getElement('input.postcode').addEvent('focus', function(event){
			if (event.target.hasClass('empty')) {
				event.target.set('value','');
			}
		});
		
		container.getElement('input.postcode').addEvent('blur', function(event){
			if (event.target.hasClass('empty') && event.target.get('value') == '') {
				event.target.set('value',AUTO_POSTCODE_EMPTY);
			}
		});
			
		container.getElement('select.make').addEvent('change', this.setMake.bind(this));
		container.getElements('button.submit_search').addEvent('click', this.fireSearch.bind(this));
		container.getElement('.advancedexpand').addEvent('click', this.toggleAdvancedOptions.bind(this));
		container.getElement('.basicexpand').addEvent('click', this.toggleBasicOptions.bind(this));
		
		// set the class reference
		this.container = container;
	},
	
	/**
	 * Get the container
	 * 
	 * @return Element
	 */
	getContainer : function()
	{
		return this.container;
	},
	
	/**
	 * Get selector by class (locally)
	 * 
	 * @param String className
	 * @return Element
	 */
	getSelectorByClass : function ( className )
	{
		return this.getContainer().getElement('select.'+className);
	},
	
	/**
	 * Set the make in the search options
	 * 
	 * @param Event event
	 */
	setMake : function (event)
	{
		this.gateway.setAction('retrieve_properties');
		Byng.transit.post(	{	'request'   : this.gateway,
								'onComplete': this.populateModels.bind(this)},
							{	'parentId'  : event.target.value,
							 	'type' 		: AUTO_PARAM_MODELS});
	},
	
	/**
	 * Populate the models
	 * 
	 * @param DomElement xml
	 */
	populateModels : function (xml)
	{
		var resp = new ByngXml ( xml );
		try {
			var makeId = resp.getParam('parentId');
			var models = resp.getParam('properties');
		} catch (e) {}
		
		// truncate the models
		var selector = this.getSelectorByClass( AUTO_PARAM_MODELS );		
			selector.options.length = 0;
			selector.options[0] = new Option ('- Any Model -','');
		
		// condition: makeId not set
		if (makeId == false) {
			selector.setProperty('disabled');
			return;	
		}
		
		var i = 1;
		// hydrate the options from the data	
		$each(models,function(modelId, title) {
			this.options[i] = new Option(modelId, title);
			i++;
		}.bind(selector));
		selector.value = '';
		selector.removeProperty('disabled');
	},
	
	/**
	 * Fire the search request
	 * 
	 * @param Event event
	 */
	fireSearch : function (event)
	{
		var errors = [];
		
		event.stop();
		
		// validation here
		var form = event.target.getParent('form');
		var postcode = form.getElement('input.postcode');
		var postcodeRequired = !(form.hasClass('price_calculator'));
		if ( postcodeRequired ) {
			if (postcode.get('value') == '' || postcode.get('value') == AUTO_POSTCODE_EMPTY) {
			
				$$('.az-popup_error').setStyle('display', 'block');		
			
				var requestPostcode = function(e){
					e.stop();
					var newPostcode = $('add_postcode').get('value');
					postcode.value = newPostcode;
					$$('.az-popup_error').setStyle('display', 'none');				
				}
				
				$('submit_postcode').addEvent('click', requestPostcode);
				$('postcode_get').addEvent('submit', requestPostcode);
				

				return;
				
				//errors.push('Please enter your postcode');

			}
		} else {
			postcode.set('value','');
		}
		
		if (errors.length == 0) {
			form.submit();
		} else {
			alert (errors.join('\n'));
		}
},
	
	/**
	 * Toggle the advanced search
	 * 
	 * @param Event event
	 */
	toggleAdvancedOptions : function (event)
	{
		event.stop();
		Byng.ui.toggle($('advancepane'));	
		$('basicpane').addClass('hide');
		$$('.az-search').addClass('az-blank_bg');
	},

	toggleBasicOptions : function (event)
	{
		event.stop();
		Byng.ui.toggle($('advancepane'));	
		$('basicpane').removeClass('hide');
		$$('.az-search').removeClass('az-blank_bg');
	}
	
	
	
});