/**
 * lh.js
 * @author Lewis Howles (Boilerplate)
 *
 * 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();
		lh.highlighter();
		$('#map-canvas').length && lh.maps();

		//Orbit plugin content scroller
		if ($('#scroll').length) {
			$("#scroll").orbit({
				animation: 'fade',			// fade, horizontal-slide, vertical-slide, horizontal-push
				animationSpeed: 800,		// how fast animtions are
				timer: true,						// true or false to have the timer
				advanceSpeed: 4000,			// if timer is enabled, time between transition
				pauseOnHover: false,		// if you hover pauses the slider
				directionalNav: false,	// manual advancing directional navs
				captions: false,				// do you want captions?
				bullets: true						// true or false to activate the bullet navigation
	   });
			$('#xmas-opening').colorbox({inline:true, open:true, href:"#xmas-opening"});
		}

		// Form Validation
		$('#contact-form').length && lh.validate();
	
		// Placeholder
		$('#property-search').length && lh.placeholder();
	
		// Elastic text areas
		var textarea = $('.fancy').find('textarea');
			textarea.length && textarea.elastic();
		},
	
		// Set target blank on external links
		externalLinks : function() {
			$('a[rel~="external"]').attr('target', '_blank');
		},
	
		// Triggers toggleFocus when hovering styled form fields
		highlighter : function() {
			$('#contact-form').delegate('input, select, textarea', 'mouseover focusin mouseout focusout', function(e) {
				// Check whether the event is an 'inward' event
				var isIn = (e.type === 'mouseover' || e.type === 'focusin');
	
				lh.toggleFocus($(this), isIn);
		});
	},
	
	maps : function() {
			var offices = [
				['Bicknacre, East Hanningfield and Villages', 51.695227, 0.584874, 1, '14 Monks Mead<br />Bicknacre<br />Essex<br />CM3 4EU<br /><br />Tel: 01245 225777<br />Fax: 01245 224201<br /><a href="mailto:bicknacre@churchandhawes.com">bicknacre@churchandhawes.com</a><br /><br />Premier Homes: 01245 225002'],
				
				['Burnham, Dengie and Villages', 51.626881, 0.814806, 2, '156 Station Road,<br />Burnham on Crouch,<br />Essex,<br />CM0 8HJ<br /><br />Tel: 01621 782652<br />Fax: 01621 784944<br /><a href="mailto:burnham@churchandhawes.com">burnham@churchandhawes.com</a><br /><br />Premier Homes: 01621 786160'],
				
				['Danbury, Little Baddow and Villages', 51.717305, 0.574550, 3, '58 Main Road,<br />Danbury (Adj. to The Griffin P.H.),<br />Essex,<br />CM3 4NG<br /><br />Tel: 01245 225853<br />Fax: 01245 226230<br /><a href="mailto:danbury@churchandhawes.com">danbury@churchandhawes.com</a><br /><br />Premier Homes: 01245 227775'],
				
				['Maldon, Maylandsea and Villages', 51.731245, 0.675090, 6, '6 High Street,<br />Maldon,<br />Essex,<br />CM9 5PJ<br /><br />Tel: 01621 855195<br />Fax: 01621 857015<br /><a href="mailto:maldon@churchandhawes.com">maldon@churchandhawes.com</a><br /><br />Premier Homes: 01621 878414'],
				
				['South Woodham Ferrers and Villages', 51.644645, 0.618986, 4, '19 Reeves Way,<br />South Woodham Ferrers,<br />Essex,<br />CM3 5XF<br /><br />Tel: 01245 329429<br />Fax: 01245 323425<br /><a href="mailto:swf@churchandhawes.com">swf@churchandhawes.com</a><br /><br />Premier Homes: 01245 329479'],
				
				['Residential Lettings Department', 51.731263, 0.675181, 5, '4 High Street,<br />Maldon,<br />Essex,<br />CM9 5PJ<br /><br />Tel: 01621 878417<br />Fax: 01621 878419<br /><a href="mailto:lettings@churchandhawes.com">lettings@churchandhawes.com</a><br /><br />For enquires telephone your local branch direct.']
				],				
	
				myOptions = {
					zoom: 11,
					center: new google.maps.LatLng(51.68648, 0.68355), 					
					mapTypeId: google.maps.MapTypeId.ROADMAP
				},
	
				map = new google.maps.Map(document.getElementById("map-canvas"), myOptions),
				infowindow = null;
	
			infowindow = new google.maps.InfoWindow({
						content: "loading...",
						maxWidth: 300
			});
	
			for (var i = 0; i < offices.length; i++) {
				var office = offices[i],
					officeLatLng = new google.maps.LatLng(office[1], office[2]),
					marker = new google.maps.Marker({
								position: officeLatLng,
								map: map,
								title: office[0],
								zIndex: office[3],
								html: office[4]
				});
					
				google.maps.event.addListener(marker, "click", function () {
							infowindow.setContent(this.html);
							infowindow.open(map, this);
				});
			}
	},

	// Adds a 'focus' class to parent lis only if a field is hovered,
	// not the li itself.
	toggleFocus : function(hovered, modifier) {
		// Use the result of isIn above to modify toggleClass
		hovered.parent('li').not('.li-submit').toggleClass('focus', modifier);
	},

	// If the placeholder attribute is not supported by the user's
	// browser, implement a replacement using the value of the
	// original placeholder attribute, so no additional markup is
	// required.
	placeholder : function() {
		// Use Modernizr to check for support
		if (!Modernizr.input.placeholder) {
			// Set initial values to placeholder
			$("[placeholder]").each(function(){
				var input = $(this);
				
				// Check value is empty before overwriting
				(input.val() === '') && input.val(input.attr('placeholder'));
			});
			
			$("[placeholder]")
				.focus(function(){
					var input = $(this);
					
					// Clear the value only if it is identical to the
					// placeholder.
					(input.val() === input.attr('placeholder')) && input.val('');
				})
				.blur(function(){
					var input = $(this);
					
					// Return the value to placeholder only if the
					// current value is blank.
					(input.val() === '') && input.val(input.attr('placeholder'));
				})
				.parents('form').submit(function() {
					$(this).find('[placeholder]').each(function() {
						var input = $(this);
						
						if (input.val() === input.attr('placeholder')) {
							input.val('');
						}
					});
				});
		}
	},

	validate : function() {
		$('#contact-form').validate({
			rules: {
				//first_name : 'required',
				//To_Email : 'required',
				//status : 'required',
				full_name : "required",
				address : 'required',
				post_code : 'required',

				home_phone : {
					required : true,					
					phoneUK : true
				},
				
				mobile_phone : {
					required : true,					
					mobileUK : true
				},				

				/*
				property_type : 'required',
				property_style : 'required',
				heating : 'required',
				parking : 'required',
				bedrooms : 'required',
				
				flat_floor : {
					required : {
						depends : function () {
							return ($("#property_type").val() == 'Flat');
						}
					}
				},
				*/

				from_email : {
					required : true,
					email : true
				},

				confirm_from_email : {
					required : true,
					equalTo : '#from_email'
				},

				txtCaptcha : 'required'
			},

			messages: {
				full_name : 'Please provide at least your full name',
				address : 'Please specify your address',
				post_code : 'Please specify your postcode',				
				//property_type : 'Please select a property type',
				//flat_floor : 'Please confirm the floor that your flat is on',				
				//property_style : 'Please select a property style',
				//heating : 'Please select a type of heating',	
				//parking : 'Please select a type of parking',
				//bedrooms : 'Please select the number of bedrooms',
				//To_Email : 'Please specify which areas you are interested in',
				//status : 'Please specify your current situation',

				home_phone : {
					required : 'Please supply a valid UK landline phone number',
					phoneUK : 'This is number is not valid.'
				},
				
				mobile_phone : {
					required : 'Please supply a valid UK mobile phone number',
					mobileUK : 'This is number is not valid.'
				},

				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 : 'For security, 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(),
					globalError = $('#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);
					globalError.show();
				} else {
					globalError.hide();
				}
			}
		});
	}
}

var searchQuery = {
	// Configuration settings.
	// Update if the names of any elements have changed.
	// Alternatively, extend with $(lh.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",
			"5000000" : "&pound;5,000,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",
			"2500" : "&pound;2,500",
			"3000" : "&pound;3,000",
			"3500" : "&pound;3,500",
			"4000" : "&pound;4,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,
			contractTypeSelect = searchQuery.config.contactTypeSelect,
			contractTypeRadio = searchQuery.config.contractTypeRadio,
			contractTypeHidden = searchQuery.config.contractTypeHidden;

		if (form.length) {
			var contracts = [contractTypeSelect, 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">Min Price</option>') : value.append('<option value="0">Max 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(),
			chainID = allVars["chainID"],
			txtQuickSearch = allVars["txtQuickSearch"],
			contract = allVars["contract"],
			ddlBedrooms = allVars["ddlBedrooms"],
			ddlPayMin = allVars["ddlPayMin"],
			ddlPayMax = allVars["ddlPayMax"],
			ddlResultsOrder = allVars["ddlResultsOrder"],
			countries = allVars["countries"],
			newBuild = allVars["NewBuild"],
			offices = allVars["Offices"],
			propType = allVars["style1"],
			radius = allVars["ddlSearchArea"],
			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.churchandhawes.com/resultslite.aspx?chainID='+chainID+'&Contract='+contract+'&ddlBedrooms='+ddlBedrooms+'&ddlPayMin='+ddlPayMin+'&ddlPayMax='+ddlPayMax+'&txtQuicksearch='+txtQuickSearch+'&ddlResultsOrder='+ddlResultsOrder+'&countries='+countries+'&NewBuild='+newBuild+'&Offices='+offices+'&style1='+propType+'&ddlSearchArea='+radius
			});
		}
	}
}

// Initialise
$(lh.init());

