/**
 * lh.js
 * @author Lewis Howles @ Internet Solutions Services Limited (Of the default code in this file)
 *
 * One part default niceties, one part scripting goodness...
 */

var lh = {
	// Initialisation function.
	init : function() {
		(searchQuery.config.form.length || searchQuery.config.resultsFrame.length) && searchQuery.init();
		lh.externalLinks();

		// Form Functions
		$('form').length && lh.forms();
		
		var dresses = $('#image-slider');
					dresses.length && dresses.innerfade({
						speed: 1000,
						timeout: 6000,
						containerheight: '400px'
					});
	},

	// Set target blank on external links
	externalLinks : function() {
		$('a[rel~="external"]').attr('target', '_blank');
	},

	/**
	 * Form Tweaks
	 */
	forms : function() {
		var fancy = $('.fancy'),
			infield = $('.in-field');

		// In field labels
		infield.length && infield.find('label').inFieldLabels();

		if (fancy.length) {
			// To avoid 'required' HTML5 fields being invalid on page
			// load, add a blurred class to them which is used to style
			// invalid inputs
			fancy.find('input, textarea').blur(function(){
				$(this).addClass('blurred');
			});

			var textarea = fancy.find('textarea'),
				html = $('html');

			if (textarea.length && !(html.hasClass('ie8') || html.hasClass('ie7'))) {
				textarea.elastic();
			}
		}
	},

	validate : function() {
		$('#contact-form').validate({
			rules: {
				first_name : 'required',

				telephone : {
					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 searchQuery = {
	// Configuration settings.
	// Update if the names of any elements have changed.
	// Alternatively, extend with $(searchQuery.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'),

		contactTypeSelect : $('#contract').filter('select'),

		contractTypeRadio : $('#contract-buy'),

		contractTypeHidden : $('#contract').filter($(':hidden')),

		quickSearch : $('#txtQuickSearch'),

		minimumPrice : $('#ddlPayMin'),

		maximumPrice : $('#ddlPayMax'),

		resultsFrame : $('#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 = searchQuery.config.form,
			text = searchQuery.config.text,
			minimumPrice = searchQuery.config.minimumPrice,
			maximumPrice = searchQuery.config.maximumPrice,
			contactTypeSelect = searchQuery.config.contactTypeSelect,
			contractTypeRadio = searchQuery.config.contractTypeRadio,
			contractTypeHidden = searchQuery.config.contractTypeHidden;

		if (form.length) {
			var contracts = [contactTypeSelect, contractTypeRadio, contractTypeHidden];

			// 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") {
						searchQuery.updateCombo($(this), type);

						$('#contract-buy, #contract-rent').change(function() {
							searchQuery.updateCombo($(this), type);
						});
					}
					else if (type == "select") {
						searchQuery.updateCombo(field, type);

						field.change(function() {
							searchQuery.updateCombo(field, type);
						});
					}
				}
			});
		}

		// Update the URL of the search results frame using results
		// from search
		searchQuery.config.resultsFrame.length && searchQuery.getValues();
	},

	// Updates the values in minimum and maximum price select boxes
	// based on whether Buying or Renting is the contract of choice.
	updateCombo : function(contract, type) {
		// Variable declarations from config.
		var	options = '',
			minimumPrice = searchQuery.config.minimumPrice,
			maximumPrice = searchQuery.config.maximumPrice,
			minParent = searchQuery.config.minimumPrice.parent(),
			maxParent = searchQuery.config.maximumPrice.parent(),
			sale = searchQuery.config.sale,
			rent = searchQuery.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 = [minimumPrice, maximumPrice];
		$.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
		minParent.append(minimumPrice);
		maxParent.append(maximumPrice);
	},

	// 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.
	getValues : function() {
		var allVars 	 = $.getUrlVars(),
			id 			 = allVars["chainID"],
			text 		 = allVars["txtQuickSearch"],
			contract 	 = allVars["contract"],
			beds 		 = allVars["ddlBedrooms"],
			min 		 = allVars["ddlPayMin"],
			max 		 = allVars["ddlPayMax"],
			order		 = allVars["ddlResultsOrder"],
			countries	 = allVars["countries"],
			resultsFrame = searchQuery.config.resultsFrame;

		// Only update values if a search has been performed -
		// ignores pages with set results.
		if ($.type(chainID) != "undefined") {
			resultsFrame.attr('src', function(index, value) {
				return 'http://search.issl.co.uk/resultslite.aspx?chainID='+chainID
					   +'&Contract='+contract
					   +'&ddlBedrooms='+beds
					   +'&ddlPayMin='+min
					   +'&ddlPayMax='+max
					   +'&txtQuickSearch='+text
					   +'&ddlResultsOrder='+order
					   +'&countries='+countries
			});
		}
	}
}

// Initialise
$(lh.init());

