/**
 * lh.js
 * @author Lewis Howles (Boilerplate)
 *
 * One part default niceties, one part scripting goodness...
 */

var lh = {
	// Initialisation function.
	init : function() {
		(search_query.config.form.length || search_query.config.results_frame.length) && search_query.init();
		lh.external_links();

		// Form Validation
		$('#contact-form').length && lh.validate();

		// Elastic text areas
		var textarea = $('.fancy').find('textarea');
		textarea.length && textarea.elastic();
	},

	// Set target blank on external links
	external_links : function() {
		$('a[rel~="external"]').attr('target', '_blank');
	},

	validate : function() {
		$('#contact-form').validate({
			rules: {
				first_name : 'required',
				
				last_name : 'required',
				
				contact_address : 'required',

				telephone : {
					required : true,
					phoneUK : true
				},

				from_email : {
					required : true,
					email : true
				},

				confirm_from_email : {
					required : true,
					equalTo : '#from_email'
				},

				query : 'required',

				txtCaptcha : 'required'
			},

			messages: {
				first_name : 'Please provide at least your first name, so we know what to call you',

				from_email : {
					required : 'We need your email address to contact you',
					email : 'The email address you provided doesn&rsquo;t seem to be valid'
				},

				confirm_from_email : {
					required : 'Please confirm your email address, just in case',
					equalTo : 'The email addresses you&rsquo;ve provided don&rsquo;t match'
				},

				query : 'Don&rsquo;t forget to ask us a question, or leave us a comment',

				txtCaptcha : 'Please enter the numbers you see above'
			},

			errorPlacement: function(error, element) {
				var required = element.next('.required');

				if (required.length)
				  error.insertAfter(required);
				else
				  error.insertAfter(element);
			},

			invalidHandler: function(e, validator) {
				var errors = validator.numberOfInvalids(),
					global_error = $('#global-error');

				if (errors) {
					var message = errors == 1
						? 'You missed 1 field. It has been highlighted below.'
						: 'You missed ' + errors + ' fields.  They have been highlighted below.';
					$('#error-message').text(message);
					global_error.show();
				} else {
					global_error.hide();
				}
			}
		});
	}
}

var search_query = {
	// Configuration settings.
	// Update if the names of any elements have changed.
	// Alternatively, extend with $(search_query.init({form : $('#new-form-name')}));
	config : {
		sale : {
			"50000" : "&pound;50,000",
			"75000" : "&pound;75,000",
			"100000" : "&pound;100,000",
			"125000" : "&pound;125,000",
			"150000" : "&pound;150,000",
			"175000" : "&pound;175,000",
			"200000" : "&pound;200,000",
			"250000" : "&pound;250,000",
			"300000" : "&pound;300,000",
			"400000" : "&pound;400,000",
			"500000" : "&pound;500,000",
			"750000" : "&pound;750,000",
			"1000000" : "&pound;1,000,000",
			"1500000" : "&pound;1,500,000"
		},

		rent : {
			"250" : "&pound;250",
			"500" : "&pound;500",
			"750" : "&pound;750",
			"1000" : "&pound;1,000",
			"1250" : "&pound;1,250",
			"1500" : "&pound;1,500",
			"2000" : "&pound;2,000"
		},

		form : $('#property-search'),

		text : $('#txtQuickSearch'),

		contact_type_select : $('#contract').filter('select'),

		contract_type_radio : $('#contract-buy'),

		contract_type_hidden : $('#contract').filter($(':hidden')),

		quick_search : $('#txtQuickSearch'),

		minimum_price : $('#ddlPayMin'),

		maximum_price : $('#ddlPayMax'),

		results_frame : $('#results-frame')
	},

	// Initialisation function.
	init : function(config) {
		// Extend config with new values.
		(config && typeof(config) == 'object') && $.extend(lh.config, config);

		// Variable declarations from config.
		var form = search_query.config.form,
			text = search_query.config.text,
			minimum_price = search_query.config.minimum_price,
			maximum_price = search_query.config.maximum_price,
			contact_type_select = search_query.config.contact_type_select,
			contract_type_radio = search_query.config.contract_type_radio,
			contract_type_hidden = search_query.config.contract_type_hidden;

		if (form.length) {
			var contracts = [contact_type_select, contract_type_radio, contract_type_hidden];

			// Determine the type of 'contract' field used and react accordingly.
			$.each(contracts, function(index, field) {
				if (field.length) {
					var type = (index == 0) ? "select" : ((index == 1) ? "radios" : "hidden");

					if (type == "radios") {
						$('#contract-buy, #contract-rent').change(function() {
							search_query.update_combo($(this), type)
						});
					}
					else if (type == "select") {
						field.change(function() {
							search_query.update_combo(field, type)
						});
					}
				}
			});
		}

		// Update the URL of the search results frame using results
		// from search
		search_query.config.results_frame.length && search_query.get_values();
	},

	// Updates the values in minimum and maximum price select boxes
	// based on whether Buying or Renting is the contract of choice.
	update_combo : function(contract, type) {
		// Variable declarations from config.
		var	options = '',
			minimum_price = search_query.config.minimum_price,
			maximum_price = search_query.config.maximum_price,
			min_parent = search_query.config.minimum_price.parent(),
			max_parent = search_query.config.maximum_price.parent(),
			sale = search_query.config.sale,
			rent = search_query.config.rent,
			values = (type == 'select') ? (values = (contract.val() == 'buying') ? sale : rent) : (values = (contract.filter('input:checked').val() == 'buying') ? sale : rent);

		// To keep values neat & readable, create options here
		$.each(values, function(value, text) {
			options += '<option value="'+value+'">'+text+'</option>';
		});

		var prices = [minimum_price, maximum_price];
		$.each(prices, function(key,value){
			// Detach DOM node for faster manipulation.
			value.empty().detach();

			(key == 0) ? value.append('<option value="0">Minimum Price</option>') : value.append('<option value="0">Maximum Price</option>');

			value.append(options).val('0');
		});

		// Append back to the DOM
		min_parent.append(minimum_price);
		max_parent.append(maximum_price);
	},

	// Retrieve the values from the URL submitted by the search form
	// and submit them to the search system. Add any additionally
	// required fields to this list.
	get_values : function() {
		var allVars = $.getUrlVars(),
			chain_id = allVars["chainID"],
			txt_quick_search = allVars["txtQuickSearch"],
			contract = allVars["contract"],
			ddl_bedrooms = allVars["ddlBedrooms"],
			ddl_pay_min = allVars["ddlPayMin"],
			ddl_pay_max = allVars["ddlPayMax"],
			ddl_results_order = allVars["ddlResultsOrder"],
			countries = allVars["countries"],
			offices = allVars["Offices"],
			ddl_type = allVars["ddlType"],
			results_frame = search_query.config.results_frame;

		// Only update values if a search has been performed -
		// ignores pages with set results.
		if ($.type(chain_id) != "undefined") {
			results_frame.attr('src', function(index, value) {
				return 'http://search.issl.co.uk/resultslite.aspx?chainID='+chain_id
					   +'&Contract='+contract
					   +'&ddlBedrooms='+ddl_bedrooms
					   +'&ddlPayMin='+ddl_pay_min
					   +'&ddlPayMax='+ddl_pay_max
					   +'&txtQuicksearch='+txt_quick_search
					   +'&ddlResultsOrder='+ddl_results_order
					   +'&countries='+countries
					   +'&Offices='+offices
					   +'&style1='+ddl_type
			});
		}
	}
}

// Initialise
$(lh.init());

