var selectTitleList = [
	{title: "Mr",	male: true},
	{title: "Mrs",	female: true},
	{title: "Ms",	female: true},
	{title: "Miss",	female: true}
];

/**
 * User car search class.
 *
 * @author Ewen Elder <ewen.elder@gforces.co.uk>
 */
var usedCarSearch = {
	form : '#usedVehicleSearch',

	/**
	 * Initiate the used car search class.
	 */
	init : function ()
	{
		$(this.form).slideDown();

		if (netdirector.isGroup && $('form#primaryJumps').length)
		{
			this.groupHomepage.init();
		}

		else
		{
			this.setSearchParams()
				.getSearchLists()
				.setupFields()
				.listeners()
				.setActives();

			this.slider.init();
			this.status.init();

			this.presentation();
		}


		$('#advancedSearchPostcode').defaultInputValues();
	},


	setSearchParams : function ()
	{
		var param,
			value,
			element;


		if (typeof searchParams === 'undefined')
		{
			return this;
		}


		for (param in searchParams)
		{
			element = $('[name=used-car-search[' + param + ']], [name=used-car-search[' + param + '][]]');

			if (!element.length)
			{
				continue;
			}


			if (element.attr('multiple') && element.attr('name').indexOf('[]') > -1 && searchParams[param].indexOf(',') > -1)
			{
				values = searchParams[param].split(',');

				for (value in values)
				{
					$('option[value=' + values[value] + ']').attr('selected', true);
				}
			}

			else
			{
				element.val(searchParams[param]);
			}
		}


		return this;
	},


	/**
	 * Setup the search fields.
	 */
	setupFields : function ()
	{
		var i,
			type,
			types = [],
			label,
			colour,
			element,
			elements,
			newElement,
			labelText,
			noSelection,
			inputAttributes,
			labelAttributes;


		// Remove label for attr.
		$('fieldset > dl > dt label:not([for=advancedSearchIsFranchiseApproved])', this.form).removeAttr('for');


		// Add classNames to each dd element and add a clear div for CSS.
		$('dd:not(.advanced), .advanced dd', this.form).each(function ()
		{
			elements = $('input, select', this);

			var className;

			if ( $(this).find('> dl:first-child').hasClass('advanced') )
			{
				className = 'additionalAdvancedSearchOptions';
			}

			else if( elements.length )
			{
				className = elements.attr('id').indexOf('advancedSearchStandardEquipment') > -1 ? 'advancedSearchStandardEquipmentContainer' : elements.attr('id') + 'Container';
			}


			$(this).addClass(className);

			if (!$(this).parent().hasClass('advanced'))
			{
				$(document.createElement('div'))
					.addClass('clear')
					.appendTo($(this));
			}
		});


		// Add IDs to each dt element for CSS.
		$('fieldset > dl > dt', this.form).each(function ()
		{
			$(this).attr('id', 'left-tab-' + $('> label', this).text().replace(/ /g, '-').toLowerCase());
		});


		// Postcode and distance.
		$('#advancedSearchPostcode')
			.parent()
			.prev()
			.remove();

		$('#advancedSearchPostcode')
			.parent()
			.remove()
			.end()
			.insertBefore('#advancedSearchDistance');


		// Don't want the Select Any option for body styles.
		//$('#advancedSearchBodystyle option:first-child').remove();


		// id : input type.
		elements = {
			'advancedSearchFuel' : 'radio',
			'advancedSearchModel' : 'checkbox',
			'advancedSearchColour' : 'checkbox',
			'advancedSearchTransmission' : 'radio',
			'advancedSearchLocation' : 'checkbox',
			'advancedSearchBodystyle' : 'checkbox'
		};


		// Rules: if an option element has a classname then it belongs to a group (like transmission -> manual).
		for (element in elements)
		{
			types = [];

			$('#' + element).hide();


			noSelection = (!$('option:selected', '#' + element).length);

			$('#' + element + ' option').each(function (i)
			{
				if (!i && $(this).next('option[class]').length)
				{
					$(this).addClass('ANY');
				}


				// If a grouped option and already has an input created then append the value to the existing element instead of creating a new one.
				if ($(this).attr('className').length && $('input.' + $(this).attr('className')).length && $(this).attr('className') !== 'ANY')
				{
					$('input.' + $(this).attr('className')).attr('value', $('input.' + $(this).attr('className')).attr('value') + ',' + $(this).val());
				}

				// Otherwise just create a new input element.
				else
				{
					labelText = $(this).attr('className').length ? $(this).attr('className') : $(this).html();


					inputAttributes = {
						type : elements[element],
						id : element + '_' + $(this).text().replace(/ /, '_'),
						className : element + ($(this).attr('className').length ? ' ' + $(this).attr('className') : ''),
						disabled : $(this).attr('disabled')
						//checked : !!($(this).attr('selected') || (!i && noSelection)) // Can't do this here because of IE 6/7... typical :|
					};




					inputAttributes.id = element + ($(this).text() === 'Any' || $(this).text().indexOf('Any ') > -1 ? '_Any' : $(this).text().replace(/ /g, '_'));


					if ($(this).val().length)
					{
						inputAttributes.value = $(this).val();
					}

					if (elements[element] === 'radio')
					{
						inputAttributes.name = element + '_radio';
					}


					labelAttributes = {
						'for' : inputAttributes.id
						//title : labelText
					};

					if (element === 'advancedSearchModel')
					{
						labelAttributes.id = labelText.replace(/ /g, '');
					}


					label = $(document.createElement('label'))
						.addClass(labelAttributes['for'])
						.attr(labelAttributes)
						.html(labelText);

					if (!i && $(this).next('option[class]').length)
					{
						label.insertAfter('#' + element);
					}

					else
					{
						label.insertBefore('#' + element);
					}


					newElement = $(document.createElement('input'))
						.attr(inputAttributes)
						.insertBefore('#' + element);

					// Gotta set the checked attribute AFTER the element has been inserted into the DOM because IE6/7 won't allow you to set it beforehand.
					newElement
						.attr('checked', ($(this).attr('selected') || (!i && noSelection)))
						.button();
				}
			});
		}


		// Additional model stuff - add extra clear div for CSS.
		$(document.createElement('div'))
			.addClass('clear')
			.insertBefore('#advancedSearchModel');


		// Additional colour stuff.
		$('.advancedSearchColourContainer label').each(function ()
		{
			labelText = $('span', $(this));

			labelText.html('<span class="frame" onmouseover="$(this).next().show()" onmouseout="$(this).next().hide()"><img src="/local/images/frameColour.png" /></span><span class="tooltip">' + labelText.text() + '</span>');

			if (labelText.text().toLowerCase() === 'any')
			{
				return;
			}


			colour = labelText.text().toLowerCase();

			if( colour == "grey" ){
				colour = "gray";
			}

			$(this).css('background', colour);



			if ($(this).attr('for') === 'advancedSearchColour_Any')
			{
				$(this).addClass('advancedSearchColour_Any');
			}
		});


		// Postcode/distance.
		$(document.createElement('div'))
			.addClass('clear')
			.insertAfter('#advancedSearchDistance');


		// Franchise approved.
		$('label[for=advancedSearchIsFranchiseApproved]')
			.attr('id', 'isFranchiseApproved')
			.parent()
			.remove()
			.end()
			.insertAfter($('#advancedSearchModel'));

		$('#advancedSearchIsFranchiseApproved')
			.parent()
			.remove()
			.end()
			.insertAfter($('label[for=advancedSearchIsFranchiseApproved]'));


		$('#advancedSearchIsFranchiseApproved').button();


		// Advanced search standard equipment.
		$('.advanced > .advancedSearchStandardEquipmentContainer')
			.prev()
			.find('label')
			.removeAttr('for')
			.text('Specification');

		$('.advanced dd input:checkbox').button();


		// jQuery UI Buttons doesn't work properly on checkboxes in IE7/8.
		// Important!! Don't apply this fix to IE6 as IE6 works fine without it, and will break if it is applied.
		/* Actually this issue doesn't seem to be an issue any more... dunno :/
		if (window.ActiveXObject && window.XMLHttpRequest && (!document.documentMode || document.documentMode < 9))
		{
			$('.advanced dd label').click(function ()
			{
				$('#' + $(this).attr('for'))
					.attr('checked', !($('#' + $(this).attr('for')).attr('checked')))
					.change();
			});
		}*/


		// Advanced search.
		$('#left-tab-advanced-search').next().find('> dl > dd').each(function ()
		{
			$(document.createElement('dd'))
				.addClass('break')
				.insertAfter($(this));
		});

		$('#left-tab-advanced-search + dd dd.break:last-child').remove();


		return this;
	},


	/**
	 * Get the advanced search lists.
	 */
	getSearchLists : function ()
	{
		var i;

		setupBodystyleData('advancedSearchBodystyle');

		$('#advancedSearchBodystyle option:selected').attr('selected', false);

		return this;

		$.get('/frontend-operations/component-advanced-search-list?bodyStyle=1', function (response)
		{
			if (response.bodyStyle !== null)
			{
				for (i in response.bodyStyle)
				{
					$(document.createElement('option'))
						.attr('value', response.bodyStyle[i].id)
						.html(response.bodyStyle[i].bodyStyleName)
						.appendTo('#advancedSearchBodystyle');
				}
			}
		});


		return this;
	},

	/**
	 * Opens and highlights any search menus that are not set to their default state.
	 */
	setActives : function ()
	{



		return this;
	},


	/**
	 * Initial presentation of the search column, set selected, default open options etc.
	 */
	presentation : function ()
	{
		var selected,
			openByDefault = [
				'#left-tab-distance',
				'#left-tab-model-select',
				'#left-tab-used-car-search'
			];


		$('#usedVehicleSearch fieldset > dl > dd').hide();


		$('fieldset > dl > dd > input, fieldset > dl > dd > select', this.form).each(function ()
		{
			selected = false;
			element = '';


			if ($(this).val() && $(this).val().length)
			{
				if ($(this).attr('id').indexOf('_Any') === -1)
				{
					if ($(this).attr('type') === 'text' || $(this)[0].tagName.toLowerCase() === 'select' || (($(this).attr('type') === 'checkbox' || $(this).attr('type') === 'radio') && $(this).is(':checked')))
					{
						selected = true;
					}
				}


				if (selected)
				{
					$(this)
						.closest('fieldset > dl > dd')
						.prev()
						.addClass('selected');
				}
			}
		});


		// If this is a payment search then only open the payment search box.
		if (window.location.pathname.indexOf('/payment-search') > -1)
		{
			openByDefault = ['#left-tab-payment-search'];
		}


		$(openByDefault.toString()).click();


		return this;
	},


	/**
	 * Attach listeners.
	 */
	listeners : function ()
	{
		// Prevent jumping about in IE6/7.
		if (window.ActiveXObject && (!document.documentMode || document.documentMode < 8))
		{
			$('label.ui-button').click(function ()
			{
				var element = $('#' + $(this).attr('for'));

				element
					.attr('checked', (!element.attr('checked')))
					.change();

				return false;
			});
		}


		/**
		 * Handle the model options.
		 */
		$('input.advancedSearchModel, input.advancedSearchLocation, input.advancedSearchColour, input.advancedSearchBodystyle').click(function () {


			var element;

			if (!$(this).attr('className').length) {
				return;
			}

			element = '#' + $(this).attr('className').split(' ')[0];


			if ( $(this).attr('id').indexOf('_Any') > -1 ) {
				$('option', element).val("");

				$(this)
					.siblings("input")
						.attr("checked", false)
						.button("refresh");

			} else {

				$('option[value=' + $(this).val() + ']', element)
					.attr('selected', $(this).is(':checked'))
					.find(':first-child')
					.attr('selected', false);

				$('[id*=_Any]', $(this).parent())
					.attr('checked', false)
					.button('refresh');
			}


			if (!$('input:checked', $(this).parent()).length)
			{
				$('[id*=_Any]', $(this).parent())
					.attr('checked', true)
					.button('refresh');
			}




			if ($('option:selected', element).length || (element === '#advancedSearchModel' && $('#advancedSearchIsFranchiseApproved:checked').length))
			{
				$(element)
					.closest('dd')
					.prev()
					.addClass('selectedActive');
			}

			else
			{
				$(element)
					.closest('dd')
					.prev()
					.removeClass('selected, selectedActive');
			}
		});


		/**
		 * The franchiseApproved checkbox.
		 */
		$('#advancedSearchIsFranchiseApproved').change(function ()
		{
			var element = $('#advancedSearchModel')
				.closest('dd')
				.prev();


			if ($('#advancedSearchModel option:selected').length || $('#advancedSearchIsFranchiseApproved:checked').length)
			{
				element.addClass('selectedActive');
			}

			else
			{
				element.removeClass('selected, selectedActive');
			}
		});


		/**
		 * Deal with fuel and transmission.
		 */
		$('input.advancedSearchTransmission, input.advancedSearchFuel').change(function ()
		{
			var i,
				values = $(this).val().split(','),
				element = $(this).parent().find('select');

			$('option', element).attr('selected', false);

			for (i in values)
			{
				$('option[value=' + values[i] + ']', element).attr('selected', true);
			}

			element = $(this)
				.closest('dd')
				.prev();


			if ($(this).closest('dd').find('input:checked:not(.ANY)').length)
			{
				element.addClass('selectedActive');
			}

			else
			{
				element.removeClass('selected, selectedActive');
			}
		});


		/**
		 * Postcode.
		 * @todo Placeholder plugin
		 */
		$('#advancedSearchPostcode').change(function ()
		{
			element = $(this)
				.closest('dd')
				.prev();


			if ($(this).val().length && $(this).val() !== $(this).data('defaultInputValues'))
			{
				element.addClass('selectedActive');

				$(document.createElement('input'))
					.attr({
						name : 'used-car-sort-order',
						type : 'hidden',
						value : 'distance_asc'
					}).appendTo('.advancedSearchDistanceContainer');
			}

			else
			{
				element.removeClass('selected, selectedActive');
				$('.advancedSearchDistanceContainer input[name=used-car-sort-order]').remove();
			}
		});


		/**
		 * Advanced options altered indicator.
		 */
		$('select, input', 'dl.advanced').change(function ()
		{
			var element = $(this)
				.parent()
				.closest('dd.additionalAdvancedSearchOptions')
				.prev();


			if ($('option:selected:not([value=""])', 'dl.advanced').length || $('input:checked:not([id*=_Any])', 'dl.advanced').length)
			{
				element.addClass('selectedActive');
			}

			else
			{
				element.removeClass('selected, selectedActive');
			}
		});


		/**
		 * Changes status of the DT (whether open, has options selected or open and has options selected).
		 */
		$('#usedVehicleSearch fieldset > dl > dt').click(function ()
		{
			var element = $(this).next();


			if ($(this).attr('id') === 'left-tab-payment-search')
			{
				$(this).siblings('dt.active').click();
			}

			else
			{
				$('#left-tab-payment-search.active').click();
			}


			if (element.is(':visible'))
			{
				if ($(this).hasClass('selectedActive'))
				{
					$(this)
						.addClass('selected')
						.removeClass('selectedActive');
				}


				$(this).removeClass('active');

				element.slideUp(400);
			}

			else
			{
				if ($(this).hasClass('selected'))
				{
					$(this)
						.removeClass('selected')
						.addClass('selectedActive');
				}


				$(this).addClass('active');

				element.slideDown(400);
			}
		});


		return this;
	}
};





/*****************************
 * Payment Search
 *////////////////////////////
$(function(){
	var lowSelect  = $( "#budget-minimumPayment", usedCarSearch.form ).hide();
	var highSelect = $( "#budget-maximumPayment", usedCarSearch.form ).hide();

	var paymentSearchSlider = $( ".paymentSearch .paymentRange", usedCarSearch.form );
	paymentSearchSlider
		.append(
			$("<div class='sliderContainer' />")

				//Labels
				.append(
					$("<span class='sliderTextLeft' />")
				)
				.append(
					$("<span class='sliderTextRight' />")
				)

				//Slider
				.append(
					$("<div />").slider({
						min: 50,
						max: 600,
						range: true,
						step: 25,
						values: [ lowSelect.val(), highSelect.val() ]
					})
					.bind("slide", function(event, ui){

						if(ui){

							if (ui.values[0] === ui.values[1])
							{
								return false;
							}

							lowSelect.val( ui.values[0] );
							highSelect.val( ui.values[1] );
						}

						paymentSearchSlider
							.find(".sliderTextLeft")
								.html( lowSelect.find("option[selected]").html() )
							.end()
							.find(".sliderTextRight")
								.html( highSelect.find("option[selected]").html() )
							.end();
					})
				)
				.find(".ui-slider-handle")
					.eq(0)
						.addClass('leftSlider')
					.end()
					.eq(1)
						.addClass('rightSlider')
					.end()
				.end()
		);

		paymentSearchSlider.find(".ui-slider").trigger("slide");

		setTimeout(function(){

			var paymentSearch = $("#usedVehicleSearch dd#paymentSearchContainer");
			var restOfForm = paymentSearch.siblings();


			lbStart(restOfForm, ':input, .ui-slider, label', ['1', '1']);//leadbeast stock start
			lbStart(paymentSearch, ':input, .ui-slider, label', ['57', '1']);//leadbeast stock start

			$('#usedVehicleSearch').submit(function(){
				if( $("#paymentSearchContainer").is(":visible") ){
					lbSubmit(['57', '2']);//leadbeast used payment search submit
				}else{
					lbSubmit(['1', '2']);//leadbeast used car search submit
				}

			});

		},1)



});

/**
 * jQuery Slider options and settings.
 */
usedCarSearch.slider = {
	/**
	 * The slider configurations.
	 */
	configuration : {
		advancedSearchMileage : {
			sliderText : {
				pre : 'up to ',
				post : ' miles'
			},
			min : 10000,
			max : 100000,
			step : 10000,
			value : +($('#advancedSearchMileage').val() || 1000000),
			slide : function (event, ui)
			{
				usedCarSearch.slider.mileage(event, ui);
			},
			create : function (event, ui)
			{
				setTimeout(function ()
				{
					usedCarSearch.slider.mileage(event, ui);
				}, 1);
			}
		},
		advancedSearchPrice : {
			sliderText : {
				pre : '&pound;'
			},
			min : 1000,
			max : 50000,
			step : 1000,
			range : true,
			values : [+($('#advancedSearchPriceLower').val() || 0), (+$('#advancedSearchPrice').val() || 100000)],
			slide : function (event, ui)
			{
				return usedCarSearch.slider.price(event, ui);
			},
			create : function (event, ui)
			{
				setTimeout(function ()
				{
					return usedCarSearch.slider.price(event, ui);
				}, 1);
			}
		},
		advancedSearchAge : {
			sliderText : {
				pre : 'up to ',
				post : ' months'
			},
			min : 6,
			max : 60,
			step : 6,
			value : 60,
			slide : function (event, ui)
			{
				usedCarSearch.slider.age(event, ui);
			},
			create : function (event, ui)
			{
				var age = usedCarSearch.slider.configuration.advancedSearchAge.value,
					date = new Date();


				date.setTime(date.getTime() - (age * 2628000000));
				var value = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();

				$('#advancedSearchAge option:first-child')
					.attr('value', value)
					.parent()
					.val(value);


				setTimeout(function ()
				{
					if ($(event.target).slider('option', 'value') === 60)
					{
						usedCarSearch.slider.age(event, ui);
					}
				}, 1);
			}
		},
		advancedSearchEngineSize : {
			sliderText : {
				post : 'l'
			},
			min : 0.6,
			max : 3,
			step : 0.2,
			range : true,
			values : [0.6, 3],
			slide : function (event, ui)
			{
				return usedCarSearch.slider.engineSize(event, ui);
			},
			create : function (event, ui)
			{
				setTimeout(function ()
				{
					usedCarSearch.slider.engineSize(event, ui);
				}, 1);
			}
		}
	},


	/**
	 * Initiate the used car search slider class.
	 */
	init : function ()
	{
		this
			.setup()
			.listeners();
	},


	/**
	 * Setup the sliders.
	 */
	setup : function ()
	{
		var configuration,
			age,
			date,
			value;

		if (typeof searchParams.engineSize !== 'undefined')
		{
			this.configuration.advancedSearchEngineSize.values = [((searchParams.engineSize.split('-')[0] / 1000) || 0.6), ((searchParams.engineSize.split('-')[1] / 1000) || 3)];
		}


		if (typeof searchParams.registrationDate !== 'undefined')
		{
			if (searchParams.registrationDate.length)
			{
				age = searchParams.registrationDate.split('-');
				date = new Date();

				date.setFullYear(age[0]);
				date.setMonth(age[1]);
				date.setDate(age[2]);

				value = Math.round((Date.parse(new Date()) - Date.parse(date)) / 2628000000);
			}

			else
			{
				value = this.configuration.advancedSearchAge.max;
			}


			this.configuration.advancedSearchAge.value = value;
		}


		for (configuration in this.configuration)
		{
			$(document.createElement('div'))
				.addClass('sliderContainer')
				.insertAfter('#' + configuration);

			$(document.createElement('div'))
				.attr('id', configuration + 'Slider')
				.appendTo('#' + configuration + ' + .sliderContainer');

			$('#' + configuration + 'Slider').slider(this.configuration[configuration]);
			$('#' + configuration).closest('dd').find('input, select, textarea').hide();


			if (typeof this.configuration[configuration].values === 'object')
			{
				$(document.createElement('span'))
					.addClass('sliderTextLeft')
					.html(this.getSliderText(configuration, this.configuration[configuration].values[0]))
					.insertBefore('#' + configuration + 'Slider');

				$(document.createElement('span'))
					.addClass('sliderTextRight')
					.html(this.getSliderText(configuration, this.configuration[configuration].values[1]))
					.insertBefore('#' + configuration + 'Slider');


				$('#' + configuration + 'Slider')
					.find('a:nth-child(2)')
					.addClass('leftSlider')
					.end()
					.find('a:nth-child(3)')
					.addClass('rightSlider');
			}

			else
			{
				$(document.createElement('span'))
					.addClass('sliderText')
					.html(this.getSliderText(configuration, this.configuration[configuration].value))
					.insertBefore('#' + configuration + 'Slider');
			}
		}


		return this;
	},


	/**
	 * Deals with the mileage slider slide event.
	 */
	mileage : function (event, ui)
	{
		var element,
			text = 'Any',
			value = '';


		if (event.type === 'slidecreate')
		{
			ui.value = $('#advancedSearchMileage').val();
		}


		if (ui.value > 0 && ui.value < $(event.target).slider('option', 'max'))
		{
			text = addCommas(this.getSliderText('advancedSearchMileage', ui.value));
			value = ui.value;
		}


		$('#advancedSearchMileage')
			.val(value)
			.change();


		$('#advancedSearchMileageSlider')
			.closest('.sliderContainer')
			.find('.sliderText')
			.html(text);


		element = $(event.target)
			.closest('dd')
			.prev();


		if (this.isAltered('advancedSearchMileage', ui.value))
		{
			element.addClass('selectedActive');
		}

		else
		{
			element.removeClass('selected selectedActive');
		}
	},


	/**
	 * Deals with the price slider slide event.
	 */
	price : function (event, ui)
	{
		var value = {
				min : 0,
				max : 10000000
			},
			text = {
				min : 'Any',
				max : 'Any'
			};


		if (event.type === 'slidecreate')
		{
			ui.values = [$('#advancedSearchPriceLower').val(), $('#advancedSearchPrice').val()];
		}


		if (ui.values[0] > $(event.target).slider('option', 'min'))
		{
			text.min = this.getSliderText('advancedSearchPrice', ui.values[0]);
			value.min = ui.values[0];
		}


		if (ui.values[1] > 0 && ui.values[1] < $(event.target).slider('option', 'max'))
		{
			text.max = this.getSliderText('advancedSearchPrice', ui.values[1]);
			value.max = ui.values[1];
		}


		if (value.min === value.max)
		{
			return false;
		}


		$('#advancedSearchPriceSlider')
			.closest('.sliderContainer')
			.find('.sliderTextLeft')
			.html(text.min)
			.end()
			.closest('.sliderContainer')
			.find('.sliderTextRight')
			.html(text.max);


		$('#advancedSearchPriceLower option:first-child')
			.attr('value', value.min)
			.parent()
			.val(value.min);

		$('#advancedSearchPrice option:first-child')
			.attr('value', value.max)
			.parent()
			.val(value.max)
			.change();


		var element = $(event.target)
			.closest('dd')
			.prev();


		if (this.isAltered('advancedSearchPrice', ui.values))
		{
			element.addClass('selectedActive');
		}

		else
		{
			element.removeClass('selected selectedActive');
		}


		return true;
	},


	/**
	 * Deals with the age slider slide event.
	 */
	age : function (event, ui)
	{
		var date,
			text,
			value;

		if (typeof ui.value === 'undefined' || ui.value === $(event.target).slider('option', 'max'))
		{
			text = 'Any';
			value = '';
		}

		else
		{
			date = new Date();
			date.setTime(date.getTime() - (ui.value * 2628000000));

			text = this.getSliderText('advancedSearchAge', ui.value);
			value = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
		}


		$('#advancedSearchAge option:first-child')
			.attr('value', value)
			.parent()
			.val(value)
			.change();

		$('#advancedSearchAgeSlider')
			.closest('.sliderContainer')
			.find('.sliderText')
			.html(text);


		var element = $(event.target)
			.closest('dd')
			.prev();


		if (this.isAltered('advancedSearchAge', ui.value))
		{
			element.addClass('selectedActive');
		}

		else
		{
			element.removeClass('selected selectedActive');
		}
	},


	/**
	 * Deals with the engine size slider slide event.
	 */
	engineSize : function (event, ui)
	{
		var values;

		var value = {
				min : null,
				max : null
			};

		var text = {
				min : 'Any',
				max : 'Any'
			};


		if( ui.values ){
			values = ui.values;
		}else{
			values = $("#advancedSearchEngineSizeSlider").slider("option","values");
		}

		if (values) {

			if ( values[0] !== $(event.target).slider('option', 'min') && values[0] !== value.min )
			{
				text.min = this.getSliderText('advancedSearchEngineSize', values[0].toFixed(1));
				value.min = values[0];
			}


			if (values[1] !== $(event.target).slider('option', 'max') && values[1] !== value.max)
			{
				text.max = this.getSliderText('advancedSearchEngineSize', values[1].toFixed(1));
				value.max = values[1];
			}

		}

		if( !value.min && !value.max ){
			value = "";
		}else if (value.min === value.max) {
			return false;
		}else{
			value = (value.min > 0 ? value.min * 1000 : '') + '-' + (value.max > 0 ? value.max * 1000 : '');
		}


		$('#advancedSearchEngineSize option:first-child')
			.attr('value', value)
			.parent()
			.val(value)
			.change();


		$('#advancedSearchEngineSizeSlider')
			.closest('.sliderContainer')
			.find('.sliderTextLeft')
			.html(text.min)
			.end()
			.closest('.sliderContainer')
			.find('.sliderTextRight')
			.html(text.max);

		/* This is dealt with in the listener for advanced.
		display = this.isAltered('advancedSearchEngineSize', ui.values) || $('select', 'dl.advanced').val().length || $('input:checked', 'dl.advanced').length ? 'block' : 'none';

		$(event.target)
			.closest('dl')
			.parent()
			.prev()
			.find('label em')
			.css('display',  display);
		*/


		return true;
	},


	/**
	 * Get the extra slider label text from slider configurations.
	 */
	getSliderText : function (configuration, text)
	{
		if (typeof this.configuration[configuration].sliderText === 'object')
		{
			text = (typeof this.configuration[configuration].sliderText.pre !== 'undefined' ? this.configuration[configuration].sliderText.pre : '') + text;
			text += typeof this.configuration[configuration].sliderText.post !== 'undefined' ? this.configuration[configuration].sliderText.post : '';
		}


		return text;
	},


	/**
	 * Checks if the slider's current value(s) is the same as the default settings or not.
	 */
	isAltered : function (configuration, value)
	{
		configuration = this.configuration[configuration];


		if (typeof value === 'undefined')
		{
			return false;
		}


		if (typeof value === 'object' && value.length === 2 && typeof configuration.values !== 'undefined')
		{
			if (value[0] > configuration.values[0] || (value[1] > 0 && value[1] < configuration.values[1]))
			{
				return true;
			}
		}

		//else if (value !== configuration.value && typeof configuration.value !== 'undefined')
		else if (value > 0 && value < configuration.max)
		{
			return true;
		}


		return false;
	},


	listeners : function ()
	{
		/*$('#advancedSearchEngineSizeSlider .leftSlider').mousedown(function ()
		{
			var values = $('#advancedSearchEngineSizeSlider').slider('option', 'values');

			if (values[0] === usedCarSearch.slider.configuration.advancedSearchEngineSize.min && values[1] === usedCarSearch.slider.configuration.advancedSearchEngineSize.max)
			{
				$('#advancedSearchEngineSizeSlider').slider('option', 'values', [values[0], (values[1] - usedCarSearch.slider.configuration.advancedSearchEngineSize.step)]);
			}
		})*/;
	}
};


/**
 * This class checks the status of the search, basically it's the vehicle count.
 */
usedCarSearch.status = {
	statusHtml : '%n Vehicle%s Found',
	createButtons : true,


	/**
	 * Initiate the status class.
	 */
	init : function ()
	{
		this.createStatusReportFields();

		if (this.createButtons)
		{
			this.createUpdateButtons();
		}

		this.listeners();
	},


	/**
	 * Create the status report fields.
	 */
	createStatusReportFields : function ()
	{
		var count = $(document.createElement('em'));

		// Group homepage.
		if ($('#primaryJumps').length)
		{
			count.appendTo('dt.count', usedCarSearch.form);
		}

		else
		{
			count.insertBefore('fieldset > dl > dd > .clear:last-child', usedCarSearch.form);
		}


		return this;
	},


	/**
	 * Create and add the status update buttons.
	 */
	createUpdateButtons : function ()
	{
		// Remove the submit button.
		$('ul', usedCarSearch.form).remove();


		$("<a href='#' class='btnUpdate'>Search</a>")
			.insertBefore('fieldset > dl > dd > .clear:last-child', usedCarSearch.form);

		$("<a href='#' class='btnUpdate'>Search</a>")
			.css( "marginTop", "1em" )
			.prependTo("fieldset > dl > dd.additionalAdvancedSearchOptions");

		return this;
	},


	/**
	 * The event listeners.
	 */
	listeners : function ()
	{
		var count,
			number,
			element,
			timeout,
			model,
			html;


		$('fieldset > dl > dd > a.btnUpdate', usedCarSearch.form).click(function ()
		{
			var button = $(this);

			var form = button.closest('form');

			if( button.is("#paymentSearchContainer a.btnUpdate") ){
				form.attr( "action", form.attr("data-payment-search-target") );
				//Disable all inputs that are not budget inputs here.
			}

			form.submit();
			return false;
		});


		$('select, input', usedCarSearch.form).change(function ()
		{
			clearTimeout(timeout);


			// Advanced search section.
			if ($(this).closest('.advanced').length)
			{
				element = $(this)
					.closest('.advanced')
					.closest('dd')
					.find('> a.btnUpdate')
					.prev();
			}

			// Outside the advanced search.
			else
			{
				element = $(this)
					.closest('dd')
					.find('> a.btnUpdate')
					.prev();
			}


			// If element is empty, then assume there is no submit button within the current dd container, check to see if there is a status element instead.
			if (!element.length)
			{
				element = $(this)
					.closest('dd')
					.find('> .clear')
					.prev('em');
			}


			if (!element.length)
			{
				element = $('.count', usedCarSearch.form);
			}


			// If no status element, don't bother doing the request.
			if (!element.length)
			{
				return;
			}


			timeout = setTimeout(function ()
			{
				$('#usedVehicleSearch dd > em').hide();


				if (usedCarSearch.form !== '#primaryJumps')
				{
					element.html('');

					$(document.createElement('img'))
						.attr({
							src : '/local/images/loading.gif',
							alt : 'Loading...'
						}).appendTo(element);

					element.fadeIn(100);
				}


				// Need to check engine size HERE and not during the slide event (or on slide stop).
				if ($('#advancedSearchEngineSize').length)
				{
					var engineSize = $('#advancedSearchEngineSize').val().split('-');

					if (engineSize[0] === engineSize[1])
					{
						$('#advancedSearchEngineSize option:selected').attr('value', (+engineSize[0] - 50) + '-' + engineSize[1]);
					}
				}


				$.get('/frontend-operations/advanced-search-count?' + $(usedCarSearch.form).serialize(), function (response)
				{
					for (model in response.availableModels)
					{
						$('.advancedSearchModelContainer input[value=' + model + ']').attr('disabled', (!parseInt(response.availableModels[model])));
					}

					$('.advancedSearchModelContainer input').button('refresh');


					if (usedCarSearch.form === '#primaryJumps')
					{
						element.html('');

						if (typeof response.count === 'undefined')
						{
							return;
						}

						count = response.count;


						while (count.length < 4)
						{
							count = 0 + count;
						}


						while (count.length)
						{
							number = count.substr(0, 1);

							count = count.substr(1);

							$(document.createElement('span'))
								.addClass('counter count' + number)
								.text(number)
								.appendTo(element);
						}

						$(document.createElement('span'))
							.addClass('title')
							.prependTo(element);
					}

					else
					{
						html = usedCarSearch.status.statusHtml.replace('%n', response.count).replace('%s', (response.count !== '1' ? 's' : ''));

						element.fadeOut(100, function ()
						{
							element
								.html(html)
								.fadeIn(100);
						});
					}
				});
			}, 1000);
		});

		return this;
	}
};


/**
 * Group homepage search.
 */
usedCarSearch.groupHomepage = {
	init : function ()
	{
		usedCarSearch.form = '#primaryJumps';


		// Ensure no options are already selected.
		$('option:selected', '#advancedSearchModel').attr('selected', false);


		this.setupFields()
			.listeners();

		usedCarSearch.status.statusHtml = '%n Matching Car%s';
		usedCarSearch.status.createButtons = false;
		usedCarSearch.status.init();
	},


	setupFields : function ()
	{
		var inputAttributes,
			element = $('#advancedSearchModel'),
			isAnyOption;

		// Setup models.
		$(element)
			.hide()
			.parent()
			.addClass('models');

		$('label[for=advancedSearchModel]')
			.parent()
			.hide();


		$('option:not(.otherModels)', element).each(function (i)
		{
			isAnyOption = ($(this).text().indexOf('Other ') > -1);

			inputAttributes = {
				type : 'checkbox',
				className : element.attr('id'),
				disabled : $(this).attr('disabled')
			};

			inputAttributes.id = element.attr('id') + (isAnyOption ? '_Any' : $(this).text().replace(/ /g, '_'));

			if ($(this).val().length)
			{
				inputAttributes.value = $(this).val();
			}


			$(document.createElement('label'))
				.attr({
					'for' : inputAttributes.id,
					id : 'modelsJump' + i
				})
				.addClass(!isAnyOption ? 'jump' + i : '')
				.html(!isAnyOption ? '<span>' + $(this).attr('className') + ' in stock</span>' : '')
				.insertBefore(element);

			$(document.createElement('input'))
				.attr(inputAttributes)
				.insertBefore(element)
				.button();
		});


		// Franchise approved and other models.
		$('label[for=advancedSearchModel_Any], #advancedSearchModel_Any, label[for=advancedSearchIsFranchiseApproved]').insertAfter('#advancedSearchIsFranchiseApproved');
		$('#modelsJump0').attr('id', 'otherModels');

		$('label[for=advancedSearchIsFranchiseApproved]').attr('id', 'isFranchiseApproved');
		$('#advancedSearchIsFranchiseApproved')
			.button()
			.parent()
			.addClass('checkboxOptions');


		// Postcode.
		$('label[for=advancedSearchPostcode]')
			.parent()
			.addClass('count')
			.end()
			.insertBefore('#advancedSearchPostcode');

		$('#advancedSearchPostcode')
			.parent()
			.addClass('postcodeSearch');

		$(document.createElement('a'))
			.attr('href', '#')
			.html('Search')
			.addClass('btnUpdate')
			.insertAfter('#advancedSearchPostcode');


		$('#primaryJumps ul').remove();

		return this;
	},


	listeners : function ()
	{
		$('input.advancedSearchModel').change(function ()
		{
			var display,
				element = '#advancedSearchModel';


			$('option[value=' + $(this).val() + ']', element)
				.attr('selected', $(this).is(':checked'))
				.find(':first-child')
				.attr('selected', false);


			$('option.otherModels', element).attr('selected', ($('#advancedSearchModel_Any').is(':checked')));

			$(element)
				.closest('dd')
				.prev()
				.find('label em')
				.css('display', display);
		});

		lbStart(usedCarSearch.form, '[name]', ['1', '1']);//leadbeast used car search start

		$(usedCarSearch.form).submit(function ()
		{
			if($('#advancedSearchPostcode').valid())
				lbSubmit(['1', '2']);//leadbeast used car search submit
			//Payment Search.

			return !!$('#advancedSearchPostcode').valid();
		});
	}
};



























$(document).ready(function() {

	//Title attributes on elements that don't semantically need them
	$("a:not([title]):not(:has(*))").each( function(){
		$(this).attr("title", $.trim( $(this).text() ) )
	});

	$('#homeNews > div:nth-child(4)').cycle({
		speed : 2000,
		timeout : 5000,
		pauseOnPagerHover : true
	});


	// Link manager.
	var linkManagerItems = [
		'#nav',
		'#homeNews',
		'div.box.partsJump'
	];

	$(linkManagerItems.toString()).linkManager();

	$('#nav [href=#]').click(function ()
	{
		return false;
	});


    // Fixes Chrome issues with date validator validator method
    jQuery.extend(jQuery.validator.methods, {
        date: function(value, element) {
            //return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
            var d = new Date();
            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        }
    });

    // Add a postcode validator method
    jQuery.validator.addMethod("postcode", function(value, element) {
            return this.optional(element) || /^(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|(SW|W)([2-9]|[1-9][0-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2})$/.test(value);
        }, "Enter a valid UK postcode with a space."
    );

	$("input.postcode[type=text]").live("keyup", function(){
		$(this).val( this.value.toUpperCase());
	});

	$("input.postcode[type=text]").live("blur", function(){
		var value = $(this).val();

		if( value.length >= 5 && value.indexOf(" ") === -1 ){
			$(this).val(value.substr(0, (value.length - 3)) + " " + value.substr(value.length - 3));
		}
	});

	// Create tabs and start them working
    $("#tabVehicleSearch").tabs();
	$("#tabNewVehicleSpec").tabs();
	$("#tabUsedVehicleDetails").tabs();

	// Generate GUID for intellitracker.
	if( typeof itGuid === 'undefined' ){
		itGenerateGuid();
	}

	$('#layout_stockUpdates_email').click(
		function(event) {
			if ($('#layout_stockUpdates_email').val() == '- Enter Email Here -') {
				$('#layout_stockUpdates_email').val('');
			}
		}
	);

	$("body").prepopulateLists();

	$(".init-validator").validate();

	// Work around for webkit scrollbar problem when using jquery ui dialog :|
	if ($.browser.webkit) {
		$('div[id*=dialog]').bind('dialogopen', function(){
			setTimeout(function(){
				$(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay');
			}, 1);
		});
	}

	/**
	 * Files added in the CMS should open in a new window
	 */
	$( "a.new-window,.cmsDownloads a, .mce-container-file a" ).click( function(){
		window.open( this.href );
		return false;
	});

	$('.ui-dialog-buttonpane button').each( function () {
		var html = $(this).text();
		$(this).addClass('btn' + html);
		$(this).html('<span class="ui-button-text">' + html + '</span');
	});

	var buttons = $('.ui-dialog-buttonpane').children('button');
	buttons.removeClass('ui-button-text-only').addClass('ui-button-text-icon').addClass('ui-button');

	$("input.postcode[type=text]").live("paste change keyup", function(){
		this.value = this.value.toUpperCase();
	});

	$("tr.trOut").live("mouseover", function(){
		$(this).addClass("trOver").removeClass("trOut");
	});

	$("tr.trOver").live("mouseout", function(){
		$(this).removeClass("trOver").addClass("trOut");
	});


	// Make sure all location select elements in contact forms have a default non value option and that it is selected.
	$('select[name=location_detail_id]').each(function ()
	{
		$(document.createElement('option'))
			.attr('value', '')
			.text('- Select a Location -')
			.prependTo($(this));


		$(this).attr('selectedIndex', 0);
	});
});


$.fn.prepopulateLists = function(){

	/**
	 * Looks for any form title fields and populates the title select box
	 */
	$( 'select.prePopulateTitleList', this ).each(function(){

		var $this = $(this);

		var defaultVal = $this.val();

		// Remove all options
		$("option", $this).remove();

		$this.append( $("<option value=''>- Select Title -</option>") );

		// Add Options
		$.each(selectTitleList, function(i,item){

			var option = $("<option>").text(item.title);

			if( item.title == defaultVal ){
				option.attr("selected", true);
			}

			$this.append( option );
		});

		if( !defaultVal ){
			$this.attr( "selectedIndex", 0);
		}

	});


	/**
	* Looks for any form country fields and populates the country select box
	*/
	$( '.prePopulateCountryList', this ).each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select Country -').addOption('United Kingdom', 'United Kingdom');

		// Add Options
		$.each(selectCountryList, function(i,item){
			$( thisSelection ).addOption(item.country, item.country);
		});
		$( thisSelection ).attr( "selectedIndex", 0);
	});


	/**
	* Looks for any form county fields and populates the county select box
	*/
	$( '.prePopulateCountyList', this ).each(function(){
		var thisSelection = '#' + this.id;
		// Remove all options
		$('option', thisSelection).remove();


		var currentCountry = '';
		var text = '<option value="">- Select County -</option>';

		// Add Options
		$.each(selectCountyList, function(i,item){

			if( currentCountry != item.country ){
				if( i > 0 ){
					text += '</optgroup>';
				}
				text += '<optgroup label="' + item.country + '">';
				currentCountry = item.country;
			}
			text += '<option value="' + item.county + '">' + item.county + '</option>';
		});
		text += '</optgroup>';
		$( thisSelection ).html(text);
		$( thisSelection ).attr( "selectedIndex", 0);
	});


	/**
	* Looks for any form country field and adjusts the county fields accordingly
	*/
	$( '.prePopulateCountryList', this ).change(function(){

		// Find the formId of the form this element sits in
		var thisFormId = '#' + $( this ).get( 0 ).form.id;

		// Then adjust the county field where necessary
		if( this.options[ this.selectedIndex].value == 'United Kingdom' ){
			$( thisFormId + ' .countySelectboxField').show();
            $( thisFormId + ' .countySelectboxField select').attr('name', 'county');
            $( thisFormId + ' .countyInputField input').addClass('required');
			$( thisFormId + ' .countyInputField').hide();
            $( thisFormId + ' .countyInputField input').attr('name', '');
            $( thisFormId + ' .countyInputField input').removeClass('required');

		}else{

			$( thisFormId + ' .countySelectboxField').hide();
            $( thisFormId + ' .countySelectboxField select').attr('name', '');
            $( thisFormId + ' .countyInputField input').removeClass('required');
			$( thisFormId + ' .countyInputField').show();
            $( thisFormId + ' .countyInputField input').attr('name', 'county');
            $( thisFormId + ' .countyInputField input').addClass('required');
		}
	});

	return this;
};


/**
 * @todo: modify most of the code below into a more jquery-esque way of thinking.
 */

/**
* @ desc This will attempt to open a dialog form via passed in ids
*/
function openDialogForm( dialogName, formName, alertBoxName ){

	if( dialogName != '' && formName != '' ){

		// Clear the form values
		clearFormElements('#' + formName);

		// Removes validation messages
		var validator = $('#' + formName).validate();
		if(validator){
			validator.resetForm();
		}

		if( alertBoxName != '' ){

			// Clear Alert Box Text
			resetTips( alertBoxName, true );
		}

		// Open the dialog box
		$('#' + dialogName ).dialog('open');

		// highlight first input
		$('#' + dialogName + ' :input:text:first').focus();
	}
}


function displayFormCaptchaImage( formElementId ){

	var form = $(formElementId);

	if( form.length && $('div.captcha', form).length ){

		var target = '/' + netdirector.franchiseUrl + 'frontend-operations/get-form-captcha-image/';

		$.getJSON(target,
		function(data){
			//If data is null, then captcha is turned off.
			if(data){
				if( data.id && $( 'input[name=sc[id]]', form ).length  ){

					$('input[name=sc[id]]', form ).val( data.id );

				}

				if( data.image && $('div.captcha div.captchaImage', form).length ){

					$('div.captcha div.captchaImage', form).html( data.image );

					if( $('div.captcha:hidden', form).length ){

						$('div.captcha', form).animate({
							opacity: 'toggle',
							height: 'toggle'
						},500);
					}
				}
			}

		});

	}
}


/**
* @ desc This updates the dialog alert box, passes in a header, text, type of msg, and optional input to highlight
*/
function updateTips(header,text,msgType,highlightInput,alertBoxId) {

	// Clear Alert Box Text
	resetTips(alertBoxId);

	var alertBox = ( alertBoxId != null && alertBoxId != '' ) ? $('#'+alertBoxId) : $('#dialogAlertBox');

	txt = '<strong>'+header+':</strong> '+ text;
	switch( msgType ){
		case 'error':
			msg = "<p>" + txt + "</p>";
			alertBox.addClass('ui-state-error').html(msg);
		break;

		case 'highlight':
			msg = "<p>" + txt + "</p>";
			alertBox.addClass('ui-state-highlight').html(msg);
		break;

		default:
			console.log('Error: No valid message type set');
		break;
	}

	if( highlightInput != '' ){
		$('#' + highlightInput).addClass('ui-state-error');
	}

	alertBox.slideDown(200);
}


/**
* @ desc This Resets the dialog alert box
*/
function resetTips(alertBoxId, close) {

	alertBox = ( alertBoxId != null && alertBoxId != '' ) ? $('#'+alertBoxId) : $('#dialogAlertBox');
	alertBox.removeClass('ui-state-error ui-state-highlight').html('');

	if (typeof close !== 'undefined' && !close) {
		alertBox.css('display', 'none');
	}
}


/**
* @ desc This will close the dialog box
*/
function autoCloseDialog(dialogFormType){

	$( "#" + dialogFormType ).dialog('close');
}


/**
* @ desc This will empty all form elements
*/
function clearFormElements(el) {

	$(el).find(':input').each(function() {
		switch(this.type) {
			case 'password':
			case 'select-multiple':
			case 'select-one':
			case 'text':
			case 'textarea':
				$(this).val('');
				break;
			case 'checkbox':
			case 'radio':
                if($(this).attr("name") != 'brochure_format'){
                    this.checked = false;
                }
		}
		$(this).removeClass('ui-state-error');
	});
}


/**
* @ desc This is a generic ajax request function
*/
function ndCollector( target, params, successFunction, errorFunction ){

	$.ajax({
		url: target,
		dataType: 'json',
		data: params,
		success: successFunction,
		error: errorFunction
	});
}




/**
* @ desc This will collect All Models under a particular Make
*/
function collectAllModels(elementId, marqueId, isVan, selectedId){

	var modelId = $( elementId );
	modelId.attr('disabled', 'disabled');

	$.ajax({
		url: '/' + netdirector.franchiseUrl + 'frontend-operations/all-model-list/',
		dataType: 'json',
		data: 'marque_id=' + marqueId + '&is_van=' + isVan,
		success: function(data){

				// Remove all options
				modelId.removeOption(/./).addOption('', '- Select Model -');

				// Add Options
				$.each(data, function(i,item){

					modelId.addOption(item.id, item.modelName);
				});

				// If previously selected..
				if( selectedId != null && selectedId > 0){
					modelId.selectOptions(selectedId);
				}else{
					// select 1st one if only one available
					var preSelect = ( data.length == 1 ) ? 1: 0;
					modelId.attr( "selectedIndex", preSelect);
				}
				modelId.removeAttr('disabled');
			},
		error: function(objRequest){

			modelId.removeAttr('disabled').removeOption(/./).addOption('', '- Select Model -');
		}
	});
}


/**
* @ desc This will collect All Makes under a particular Vehicle Type
*/
function collectAllMakes(elementId, isVan, selectedId){

	var marqueId = $( elementId );
	marqueId.attr('disabled', 'disabled');

	$.ajax({
		url: '/' + netdirector.franchiseUrl + 'frontend-operations/all-marque-list/',
		dataType: 'json',
		data: 'is_van=' + isVan,
		success: function(data){

				// Remove all options
				marqueId.removeOption(/./).addOption('', '- Select Marque -');

				// Add Options
				$.each(data, function(i,item){

					marqueId.addOption(item.id, item.marqueName);
				});

				// If previously selected..
				if( selectedId != null && selectedId > 0){
					marqueId.selectOptions(selectedId);
				}else{
					// select 1st one if only one available
					var preSelect = ( data.length == 1 ) ? 1: 0;
					marqueId.attr( "selectedIndex", preSelect);
				}
				marqueId.removeAttr('disabled');
			},
		error: function(objRequest){

			marqueId.removeAttr('disabled').removeOption(/./).addOption('', '- Select Marque -');
		}
	});
}

/**
* @ desc Adds commas in the right places to make long prices presentable
*/
function addCommas(nStr){

	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = ( x.length > 1 ) ? '.' + ( ( x[1].length == 1 )? x[1] + '0' : x[1] ) : '';
	var rgx = /(\d+)(\d{3})/;

	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/**
* @ desc Searches for passed in "word" within passed in "array" (used for intellisearch)
*/
function wordExists(arr, obj) {
	for(var i=0; i<arr.length; i++) {
		if( arr[i] != '' ){
			if (obj.search(arr[i]) >= 0) return true;
		}
	}
	return false;
}


/**
* @ desc This will post the (custom cms) form via Ajax
*/
function submitCustomForm( formType ){

	if( formType == '' ){
		return;
	}

	// Check if form is valid before proceeding
	if( $( "#form" + formType ).valid() ){

		$('body').css('cursor', 'progress');

		$.ajax({
		  url: '/' + netdirector.franchiseUrl + 'frontend-operations/submit-form/',
		  dataType: 'json',
		  data: $( '#form' + formType ).serialize(),
		  success: function(data){

				if( data != 0 ){

					// Submitted ok.
					setupCustomForm( formType );
					updateTips('Thank You','Your details have been submitted successfully','highlight','','alertBox' + formType);

					if ( typeof itForm == 'function' ) {
						itForm(data.intellitracker);
					}

					//Google analytics tracking
					window._gaq = window._gaq || [];
					window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);
				}else{

					// Show generic message
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
				}
				$('body').css('cursor', 'default');
			},
		error: function( objRequest ){
				updateTips('Request Failed','The request failed to submit, please try again.','error','','alertBox' + formType);
				$('body').css('cursor', 'default');
			}
		});
	}
}

/**
* @ desc This will setup form
*/
function setupCustomForm(formType){

	// Clear the form values
	clearFormElements('#form' + formType);

	// Removes validation messages
	var validator = $('#form' + formType).validate();
	validator.resetForm();

	// Clear Alert Box Text
	$('#alertBox' + formType).html('');

	// highlight first input
    //removed as causing page to jump down
	//$('#form' + formType + ' :input:text:first').focus();
}


/**
* @ desc This should start to be used for all form submits
*/
function globalSubmitForm( formType, successMsg ){

	if( !formType || !$( "#form" + formType ).length ){
		throw new Error("Invalid form(#form" + formType + "), cant submit data");
	}

	// Check if form is valid before proceeding
	if( $( "#form" + formType ).valid() && !$( "#form" + formType ).data('disable') ){

		var params = $( '#form' + formType ).serialize();

		globalFormStatus(formType, true);
		updateTips('<img src="/local/images/loading.gif" width="15" style="position:relative; display:inline; top:4px; margin:0 5px" />Submiting Form', '', 'highlight', '', 'alertBox' + formType);

		var formData = '';

		if( formType == 'ValueMyVehicle' ){

			formData = 'my_make=' + $('#valuemyvehicle_my_make_id > option:selected').text() + '&my_model=' + $('#valuemyvehicle_my_model_id > option:selected').text() + '&';
		}

		$.ajax({
			url: '/' + netdirector.franchiseUrl + 'frontend-operations/submit-form/?ajax_submit=true',
			dataType: 'json',
			data: formData + params,
			type: "post",
			success: function(data){

				if( data.status == true ){

					if ( typeof itForm == 'function' ) {
						itForm(data.intellitracker);
					}
					// Submitted ok.
					successMsg = ( successMsg != null && successMsg != '' ) ? successMsg : 'Thank you for your enquiry. We will respond as soon as possible';
					updateTips('Successful', successMsg,'highlight','','alertBox' + formType);

					clearFormElements("#form" + formType);

					//Google analytics tracking
					window._gaq = window._gaq || [];
					window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);

					setTimeout(function () {
						globalFormStatus(formType, false);
						autoCloseDialog('dialog' + formType);
					}, 4000);

				}else{

					displayFormCaptchaImage( '#form' + formType );

					if( data.error != null ){
						updateTips('Request Failed',data.error,'error','','alertBox' + formType);
					}else{
						updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
					}
					globalFormStatus(formType, false);
				}
			},
			error: function( objRequest ){
				updateTips('Request Failed','The submission request failed, please try again.','error','','alertBox' + formType);
				globalFormStatus(formType, false);
			}
		});
	}

}


/**
* @ desc Controls disabling of forms during submission process
*/
function globalFormStatus(formType, disable) {

	var id = '#form' + formType;

	if (typeof formType === 'undefined') {
		return;
	}
	var form = $(id);

	$(":input", form).attr("disabled", disable );

	if( disable ){
		form.add( form.closest(".ui-dialog").find(".ui-dialog-buttonpane") ).slideUp();
	}else{
		form.add( form.closest(".ui-dialog").find(".ui-dialog-buttonpane") ).show();
	}
}


/**
 *
 * Monthly repayment calculator, everything else int
 *
 * loanAmmount - the total ammount to be financed
 *
 * apr - the APR rate ( As a decimal e.g. 0.1 == 10% )
 *
 * term - number of months that the loan will last.
 */
function monthlyRepayments( principle, apr, term ){

	//No principle will throw an error
	if( !( principle > 0 ) ){
		throw new Error("You must provide a principle greater than 0");
	}

	//No term means that there is no monthly repayment to make
	if( !term ){
		return 0;
	}

	//No APR means that you pay only the principle back each month.
	if( !( apr > 0 ) ){
		return principle / term;
	}

	var monthlyRate = apr/12;

	return Math.floor( ( principle * monthlyRate ) / ( 1 - Math.pow( ( 1 + monthlyRate ),( -1 * term ) ) ) * 100 ) / 100;
}


//@hack Fix for not being able to scroll when a dialog is open in Chrome.
(function(){
	if( $.browser.webkit ){
		var oldCreate = $.ui.dialog.overlay.create;
		$.ui.dialog.overlay.create = function(){
			var r = oldCreate.apply(this, arguments);

			//Needs to happen after the bit below, which also runs a setTimeout
			setTimeout(function(){
				$([document, window]).unbind('.dialog-overlay');
			}, 1);

			return r;
		};
	}
})();


function setupBodystyleData(elementId)
{
	var thisSelection = '#' + elementId,
		bodyStyleName;

	$(thisSelection).attr('disabled', 'disabled').removeOption(/./).addOption('', 'Any Bodystyle');

	$.each(selectBodystyleList['car'], function (i, item)
	{
		if (typeof item.count !== "undefined" && item.count > 0 && (netdirector.isGroup || $.inArray(netdirector.franchiseDetailId.toString(), item.franchise_detail_id) > -1))
		{
			$(thisSelection).addOption(item.id, item.bodyStyleName);
		}
	});

	$( thisSelection ).removeAttr('disabled').attr( "selectedIndex", 0);
}



$(function ()
{
	usedCarSearch.init();

	$('#leftCol .ourLocations a').click(function (event)
	{
		if (event.clientX < 45)
		{
			$(this)
				.toggleClass('open')
				.nextAll('.address')
				.toggle();

			return false;
		}
	});

});


function shareOnFacebook()
{
	window.open("http://www.facebook.com/sharer.php?u=" + encodeURIComponent(document.location),'sharer','toolbar=0,status=0,width=626,height=436');
}
