/**
 * lh.js
 * @author Lewis Howles (lh)
 *
 * Default niceties and other Voodoo.
 */

var lh = {
	init : function() {
		(searchQuery.config.form.length || searchQuery.config.resultsFrame.length) && searchQuery.init();
		lh.externalLinks();
		lh.highlighter();
		lh.styleSwitcher();
		
		/* Allinta CMS can't do this. */
		mainNav = $('#main-nav');
		mainNav.detach(); /* Remove from DOM while manipulating */
		mainNav
			.find('.Home')
			.append(' <em>View Residential</em>');
		mainNav
			.find('.Landlords')
			.append(' <em>Landlord information</em>');
		mainNav
			.find('.Tenants')
			.append(' <em>Information for tenants</em>');
		mainNav
			.find('.Properties')
			.append(' <em>View all our properties</em>');
		mainNav
			.find('.Contact')
			.append(' <em>Our contact details</em>');
		mainNav
			.appendTo('#global-header'); /* Attach it back to the DOM */
		
		/* Banner rotation */
		if (!$.browser.msie || !$.browser.version == 7) {
			$('#slider').nivoSlider({
				effect:'fade',
				animSpeed:500, //Slide transition speed
				pauseTime:5000,
				slices:1,
				directionNav:false, //Next & Prev
				controlNav:true, //1,2,3...
				keyboardNav:true, //Use left & right arrows
				pauseOnHover:true //Stop animation while hovering
			});
		}
		
		/* Slide in and out the Property Search */
		var propertySearch = $('#property-search').data('open', false),
			propertySearchToggle = $('#property-search-toggle').find('span');
		
		$('#banner')
			.delegate('#property-search-toggle', 'click', function() {
				if (propertySearch.data('open')) {
					propertySearch.hide('drop', {'direction' : 'up'}, 500).data('open', false);
					propertySearchToggle.removeClass('hide').text('Show');
				}
				else {
					propertySearch.show('drop', {'direction' : 'up'}, 500).data('open', true);
					propertySearchToggle.addClass('hide').text('Hide');
				}
			});
		
		/* Slide in and out the Featured Properties */
		var featuredFrame = $('#featured-frame').data('open', true),
			featuredFrameToggle = $('#featured-frame-toggle').find('span');
		
		$('#featured')
			.delegate('#featured-frame-toggle', 'click', function() {
				if (featuredFrame.data('open')) {
					log('its open');
					featuredFrame.hide('drop', {'direction' : 'up'}, 500).data('open', false);
					featuredFrameToggle.removeClass('hide').text('Show');
				}
				else {
					log('its closed');
					featuredFrame.show('drop', {'direction' : 'up'}, 500).data('open', true);
					featuredFrameToggle.addClass('hide').text('Hide');
				}
			});
		
		/* Placeholder text */
		if (!Modernizr.input.placeholder) {
			$("input[type=text], textarea")
				.each(function(){
					var $this = $(this);
					
					if($this.val() === "")
						$this.val($this.attr('title'));
				});
			
			$("input.text, textarea")
				.focus(function(event){
					var $this = $(this);
					
					if($this.val() === $this.attr('title')) {
						$this.val("");
					}
				})
				.blur(function(event){
					var $this = $(this);
					
					if($this.val() === "") {
						$this.val($this.attr('title'));
					}
				});
		}
	},
	
	/*
	 * Set target blank on external links
	 */
	externalLinks : function() {
		$('a[rel~="external"]')
			.attr('target', '_blank')
	},
	
	highlighter : function() {
		$('form.fancy')
			.delegate('input, select, textarea', 'mouseover focusin mouseout focusout', function(e) {
				var isIn = (e.type === 'mouseover' || e.type === 'focusin');
				
				lh.toggleFocus($(this), isIn);
			});
	},
	
	toggleFocus : function(hovered, modifier) {
		hovered.parent('li').not('.li-submit').toggleClass('focus', modifier);
	},
	
	styleSwitcher : function() {
		styleSwitcher = $('#style-switcher').find('a');
		
		styleSwitcher
			.data('sheet','global')
			.bind('click', function(){
				var params = (styleSwitcher.data('sheet') == 'global') ? ['reader','Visual Mode'] : ['global','Reader Mode'];
				$('link[rel=stylesheet]')
					.eq(1) // 0-indexed position of stylesheet. Change this is you had to move global.
					.attr('href', 'css/'+params[0]+'.css');
				styleSwitcher.data('sheet',params[0]);
				styleSwitcher.text(params[1]);
			});
	}
}

var searchQuery = {
	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;1000",
			"1250" : "&pound;1250",
			"1500" : "&pound;1500",
			"2000" : "&pound;2000"
		},
		
		form : $('#property-search'),
		
		contactTypeSelect : $('#contract'),
		
		contractTypeRadio : $('input[name=contract]'),
		
		minimumPrice : $('#ddlPayMin'),
		
		maximumPrice : $('#ddlPayMax'),
		
		resultsFrame : $('#results-frame')
	},
	
	init : function(config) {
		(config && typeof(config) == 'object') && $.extend(lh.config, config);
		
		var form = searchQuery.config.form,
			minimumPrice = searchQuery.config.minimumPrice,
			maximumPrice = searchQuery.config.maximumPrice,
			contractTypeSelect = searchQuery.config.contactTypeSelect,
			contractTypeRadio = searchQuery.config.contractTypeRadio;
		
		if (form.length) {
			var contracts = [contractTypeSelect, contractTypeRadio];
			$.each(contracts, function(k,v) {
				if (v.length) {
					var type = (k == 0) ? 'select' : 'radios';
					
					searchQuery.updateCombo(v, type);
					
					v.change(function() {
						searchQuery.updateCombo(v, type)
					});
				}
			});
		}
		
		searchQuery.config.resultsFrame.length && searchQuery.getValues();
	},
	
	updateCombo : function(contract, type) {
		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(val, text) {
			options += '<option value="'+val+'">'+text+'</option>';
		});
		
		var prices = [minimumPrice, maximumPrice];
		$.each(prices, function(k,v){
			v.empty().detach();
			
			(k == 0) ? v.append('<option value="0">Min Price</option>') : v.append('<option value="0">Max Price</option>');
			
			v.append(options).val('0');
		});
		
		minParent.append(minimumPrice);
		maxParent.append(maximumPrice);
	},
	
	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"],
			resultsFrame = searchQuery.config.resultsFrame;
		
		resultsFrame.attr('src', function(i, a) {
			if (a == '')
				return 'http://search.view-residential.co.uk/resultslite.aspx?chainID='+chainID+'&Contract='+contract+'&ddlBedrooms='+ddlBedrooms+'&ddlPayMin='+ddlPayMin+'&ddlPayMax='+ddlPayMax+'&txtQuicksearch='+txtQuickSearch+'&ddlResultsOrder='+ddlResultsOrder+'&countries='+countries
			else
				return a;
		});
	}
}

// Get URL Parameters
$.extend({
  getUrlVars: function(){
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
	  hash = hashes[i].split('=');
	  vars.push(hash[0]);
	  vars[hash[0]] = hash[1];
	}
	return vars;
  },
  getUrlVar: function(name){
	return $.getUrlVars()[name];
  }
});

$(lh.init());
