$(document).ready(function() {


	// Display search form (is set to display:none to prevent fouc)
    $('#tabVehicleSearch').css('display', 'block');

	// Create tabs and start them working
    
    $("#tabVehicleSearch").tabs();
	$("#tabVehicleSearch").tabs('select', 0);

	//$("#tabOffersList").tabs();
    //$('#offersList').tabs();

	$("#tabUsedVehicleInfo").tabs();
    $('#usedVehicleInfo').tabs();

	$("#tabFinanceCalculator").tabs();
    $('#financeCalculator').tabs();

	$("#tabUsedVehicleSecondaryInfo").tabs();
    $("#usedVehicleSecondaryInfo").tabs();

    //We moved body style to the standard search.
    collectAdvancedSearchLists();
    
    showMyFavourites();

	$('.navNewCars li').mouseover(function() {
		$('.navNewCars a').addClass('active');
	});
	$('.navNewCars li').mouseout(function() {
		$('.navNewCars a').removeClass('active');
	});

	// Show the contact details dropdown on hover, hide on click elsewhere
	$('#contactDetailsDropdown').mouseover(function() {
		$('.dropdownContainer').show();
	})
	$(document).click(function() {
		$('.dropdownContainer').hide();
	});


	// Datepicker anywhere!
	var dateOptions = {
		dateFormat: 'dd/mm/yy',
		changeYear: true,
		changeMonth: true,
		showOn: "both",
		buttonImage: netdirector.baseUrl +"/local/images/iconCalendar.gif",
		buttonImageOnly: true
	};
	$('input.datepicker').datepicker(dateOptions);

	var dateOptionsFuture = {
		minDate: +1,
		dateFormat: 'dd/mm/yy',
		showOn: "both",
		buttonImage: netdirector.baseUrl +"/local/images/iconCalendar.gif",
		buttonImageOnly: true
	};
	$('input.datepickerFuture').datepicker(dateOptionsFuture);

	var dateOptionsPast = {
		maxDate: -1,
		changeMonth: true,
		changeYear: true,
		yearRange: "-90:-18",
		dateFormat: 'dd/mm/yy',
		showOn: "both",
		buttonImage: netdirector.baseUrl +"/local/images/iconCalendar.gif",
		buttonImageOnly: true
	};
	$('input.datepickerPast').datepicker(dateOptionsPast);

	// For unique styling of dialog buttons
	$('.ui-dialog-buttonpane button').each( function () {

		var html = $(this).html();
		$(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'); 
	
	/**
	* Looks for any form title fields and populates the title select box
	*/
	$('.prePopulateTitleList').each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select Title -');

		// Add Options
		$.each(selectTitleList, function(i,item){
			$( thisSelection ).addOption(item.title, item.title);
		});
		$( thisSelection ).attr( "selectedIndex", 0);
	});


	/**
	* Looks for any form country fields and populates the country select box
	*/
	$('.prePopulateCountryList').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').each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select County -');

		var currentCountry = '';
		var text = '';

		// 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').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 + ' .countyInputField').hide();

		}else{

			$( thisFormId + ' .countySelectboxField').hide();
			$( thisFormId + ' .countyInputField').show();
		}
	});

	$(".init-validator").validate();	
	
});

var newVehicleSearchLoaded = false;
var advancedSearchLoaded   = false;
var advancedSearchCarCount = 0;
var advancedSearchVanCount = 0;

var resultDisplayKeyboardHighlight = 0;
var currentISearch = '';
var totalResults   = 0;
var quickSearchResults = new Array();
var favouritesLimit  = 3;

 // Remembers the value for when moving away from the quick search and coming back
var rememberQuickVehicleSearchValue = '';

// Remembers results from quick search to show them again without ajax call
var rememberedDisplayText = '';

document.onkeydown = detectkeyPress;

$(document).ready(function() {

	// Create tabs and start them working
    $("#tabVehicleSearch").tabs();
	$("#tabNewVehicleSpec").tabs();
	$("#tabUsedVehicleInfo").tabs();


	// Generate Price
	priceListing();

	$('#layout_stockUpdates_email').click(
		function(event) {
			if ($('#layout_stockUpdates_email').val() == '- Enter Email Here -') {
				$('#layout_stockUpdates_email').val('');
			}
		}
	);
});


/**
* @ desc This will attempt to reset any options selected in the search
*/
function rememberSearchSettings(){

	// Remember Search Params
	if( parseInt( searchParams.makeId ) > 0 ){

		$("#auto_marque_detail_id").selectOptions( searchParams.makeId );
		collectAvailableModels( searchParams.modelId, 0);
	}

	if( parseInt( searchParams.vanMakeId ) > 0 ){
		$("#van_auto_marque_detail_id").selectOptions( searchParams.makeId );
		collectAvailableModels( searchParams.vanModelId, 1);
	}
}


/**
* @ desc This will show/hide advanced search options
*/
function toggleAdvancedSearch( el ){

	$( el ).animate({opacity: 'toggle', height: 'toggle'}, 300);
}


/**
* @ 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><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin: 0px 5px;\"></span>"+txt+"</p>";
			alertBox.addClass('ui-state-error').html(msg);
		break;

		case 'highlight':
			msg = "<p><span class=\"ui-icon ui-icon-info\" style=\"float: left; margin: 0px 5px;\"></span>"+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');
	}
}


/**
* @ desc This Resets the dialog alert box
*/
function resetTips(alertBoxId){

	alertBox = ( alertBoxId != null && alertBoxId != '' ) ? $('#'+alertBoxId) : $('#dialogAlertBox');
	alertBox.removeClass('ui-state-error ui-state-highlight').html('');
}


/**
* @ 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':
				this.checked = false;
				break;
			case 'radio':
				// Clearing all radio buttons is supremely stupid - virtually all radio button sets WANT a default set - that's why they're radio buttons!
				break;
		}
		$(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 Available Models
*/
function collectAvailableModels(selectedId, isVan){

	if( isVan == 1 ){
		var marqueId = $("#van_auto_marque_detail_id");
		var modelId = $("#van_auto_model_detail_id");
	}else{
		var marqueId = $("#auto_marque_detail_id");
		var modelId = $("#auto_model_detail_id");
	}

	modelId.attr('disabled', true);

	ndCollector(
		'/frontend-operations/available-model-list/',
		'marque_id=' + marqueId.val() + '&is_van=' + isVan,
		function(data){

			// Remove all options
			modelId.removeOption(/./);

			// Add Options
			$.each(data, function(i,item){
				modelId.addOption(item.id, item.modelName);
			});

			// If previously selected..
			if( 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');

            // calculate vehicle count
            

			collectAdvancedSearchCount();
		},
		function(objRequest){

			modelId.removeAttr('disabled');
		}
	);
}

/**
* @ desc This will collect New Vehicle Marque Lists
*/
function collectNewVehicleMarqueLists(){

	// Only load lists once
	if( newVehicleSearchLoaded != true ){

		// Remove all options and disable
		$('#new_car_franchise_detail_id').attr('disabled', 'disabled');
		$('#new_van_franchise_detail_id').attr('disabled', 'disabled');

		$.ajax({
			url: '/frontend-operations/new-vehicle-marque-list/',
			dataType: 'json',
			data: '',
			success: function(data){
				newVehicleSearchLoaded = true;

				// Remove loading and show default select option
				$('#new_car_franchise_detail_id').removeOption(/./).addOption('', '-  Select Make  -');
				$('#new_van_franchise_detail_id').removeOption(/./).addOption('', '-  Select Make  -');

				// Add Options
				if( data.newMarque != null ){
					$.each(data.newMarque, function(i,item){
						$("#new_car_franchise_detail_id").addOption(item.id, item.marqueName);
						$( '#new_car_franchise_detail_id option:last' ).data('url',item.franchiseUrl);
					});
				}

				if( data.newVanMarque != null ){
					$.each(data.newVanMarque, function(i,item){
						$("#new_van_franchise_detail_id").addOption(item.id, item.marqueName);
						$( '#new_van_franchise_detail_id option:last' ).data('url',item.franchiseUrl);
					});
				}

				$('#new_car_franchise_detail_id').removeAttr('disabled').attr( "selectedIndex", 0);
				$('#new_van_franchise_detail_id').removeAttr('disabled').attr( "selectedIndex", 0);
			},
			error: function(objRequest){
				$('#new_car_franchise_detail_id').removeAttr('disabled').removeOption(/./).addOption('', '-  Select Make  -');
				$('#new_van_franchise_detail_id').removeAttr('disabled').removeOption(/./).addOption('', '-  Select Make  -');
			}
		});
	}
}


/**
* @ desc This will collect Available Models
*/
function collectNewModels(){

	var selectedId = 0;

	// Select which Marque Selector to choose dependant on car/van
	if( $('#new_car_is_van').val() == 1 ){

		var marqueId = $("#new_van_franchise_detail_id");
		var modelId   = $("#new_van_model_name");
		var variantId = $("#new_van_variant");
	}else{

		var marqueId = $("#new_car_franchise_detail_id");
		var modelId   = $("#new_car_model_name");
		var variantId = $("#new_car_variant");
	}

	modelId.attr('disabled', 'disabled');


	$.ajax({
		url: '/frontend-operations/new-model-list/',
		dataType: 'json',
		data: 'franchise_detail_id=' + marqueId.val() + '&is_van=' + $('#new_car_is_van').val(),
		success: function(data){
				// Remove all options
				modelId.removeOption(/./);
				variantId.removeOption(/./);

				// Add Options
				$.each(data, function(i,item){

					var option = modelId.addOption(item.id, item.references.heading);

					$( 'option:last', modelId ).data('url',item.url);
					$( 'option:last', modelId ).data('content_url', item.references.content_url);
				});

				// If previously selected..
				if( 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');
				if( modelId.attr( "selectedIndex") > 0 ){
					collectNewVariants();
				}
			},
		error: function(objRequest){

			modelId.removeAttr('disabled');
		}
	});
}


/**
* @ desc This will collect Available Variants
*/
function collectNewVariants(){

	var selectedId = 0;

	// Select which Marque Selector to choose dependant on car/van
	if( $('#new_car_is_van').val() == 1 ){

		var marqueId = $("#new_van_franchise_detail_id");
		var modelId   = $("#new_van_model_name");
		var variantId = $("#new_van_variant");
	}else{

		var marqueId = $("#new_car_franchise_detail_id");
		var modelId   = $("#new_car_model_name");
		var variantId = $("#new_car_variant");
	}

	variantId.attr('disabled', 'disabled');

	$.ajax({
		url: '/frontend-operations/new-variant-list/',
		dataType: 'json',
		data: 'franchise_detail_id=' + marqueId.val() + '&cms_page_area_link_id=' + modelId.val(),
		success: function(data){

				// Remove all options
				variantId.removeOption(/./);

				// Add Options
				$.each(data, function(i,item){

					variantId.addOption(item.id, item.variant);
				});

				// If previously selected..
				if( selectedId > 0){
					variantId.selectOptions(selectedId);
				}else{
					// select 1st one if only one available
					var preSelect = ( data.length == 1 ) ? 1: 0;
					variantId.attr( "selectedIndex", preSelect);
				}
				variantId.removeAttr('disabled');
			},
		error: function(objRequest){

			variantId.removeAttr('disabled');
		}
	});
}

function priceListing(){

	// Create list of price values for search box
	var i = 500;
	while ( i < 30001 ) {
	
		$("#lower_price").addOption(i, String.fromCharCode(163) + addCommas(i));
		$("#price").addOption(i, String.fromCharCode(163) + addCommas(i));

		if ( i < 10000 ) {
			i += 500;
		} else {
			i += 1000;
		}
	}
	$("#lower_price").addOption('999999', String.fromCharCode(163) + '30,000+').attr( "selectedIndex", 0);
	$("#price").addOption('999998', String.fromCharCode(163) + '30,000+').attr( "selectedIndex", 0);
}



/**
* @ desc This will collect Available Bodystyles, transmissions and fuel types
*/
function collectAdvancedSearchLists(){

	// Only load lists once
	if( advancedSearchLoaded != true ){

		// Remove all options and disable
		$('#advancedSearchLocation').attr('disabled', 'disabled');
		$('#auto_body_style_detail_id').attr('disabled', 'disabled');
		$('#auto_transmission_detail_id').attr('disabled', 'disabled');
		$('#auto_fuel_type_detail_id').attr('disabled', 'disabled');

		ndCollector(
			'/frontend-operations/advanced-search-list/',
			'',
			function(data){

				advancedSearchLoaded = true;

				// Remove loading and show default select option
				$('#advancedSearchLocation').removeOption(/./).addOption('', '- Select Location -');
				$('#auto_body_style_detail_id').removeOption(/./).addOption('', '- Select Bodystyle -');
				$('#auto_transmission_detail_id').removeOption(/./).addOption('', '- Select Transmission -');
				$('#auto_fuel_type_detail_id').removeOption(/./).addOption('', '- Select Fuel Type -');

				// Add Options
				if( data.location != null ){
					$.each(data.location, function(i,item){
						if (item.name.indexOf('-aftersales') < 0) {
							var checkDuplicates = item.name.split(' ');
							var itemName = arrayUnique(checkDuplicates).toString().replace(',', ' ');
														
							$("#advancedSearchLocation").addOption(item.id, itemName);
						}
					});
				}

				if( data.bodyStyle != null ){
					$.each(data.bodyStyle, function(i,item){
						$("#auto_body_style_detail_id").addOption(item.id, item.bodyStyleName);
					});
				}

				if( data.transmission != null ){
					$.each(data.transmission, function(i,item){
						$("#auto_transmission_detail_id").addOption(item.id, item.transmissionTypeName);
					});
				}

				if( data.fuel != null ){
					$.each(data.fuel, function(i,item){
						$("#auto_fuel_type_detail_id").addOption(item.id, item.fuelTypeName);
					});
				}

				$('#advancedSearchLocation').removeAttr('disabled').attr( "selectedIndex", 0);
				$('#auto_body_style_detail_id').removeAttr('disabled').attr( "selectedIndex", 0);
				$('#auto_transmission_detail_id').removeAttr('disabled').attr( "selectedIndex", 0);
				$('#auto_fuel_type_detail_id').removeAttr('disabled').attr( "selectedIndex", 0);
			},
			function(objRequest){

				$('#advancedSearchLocation').removeAttr('disabled').removeOption(/./).addOption('', '- Select Location -');
				$('#auto_body_style_detail_id').removeAttr('disabled').removeOption(/./).addOption('', '- Select Bodystyle -');
				$('#auto_transmission_detail_id').removeAttr('disabled').removeOption(/./).addOption('', '- Select Transmission -');
				$('#auto_fuel_type_detail_id').removeAttr('disabled').removeOption(/./).addOption('', '- Select Fuel Type -');
			}
		);
	}
}


/**
* @ desc This will collect Count of stock available
*/
function collectAdvancedSearchCount(){

	if( $('#tabVansSearch').hasClass('active') == true ){

		var extraParams = '&auto_marque_detail_id=' + $('#van_auto_marque_detail_id').val() + '&auto_model_detail_id=' + $('#van_auto_model_detail_id').val();
	}else{
		var extraParams = '&auto_marque_detail_id=' + $('#auto_marque_detail_id').val() + '&auto_model_detail_id=' + $('#auto_model_detail_id').val();
	}

	ndCollector(
		'/frontend-operations/advanced-search-count/',
		$('#frmSearchUsedCars').serialize() + extraParams,
		function(data){

			if( $('#tabVansSearch').hasClass('active') == true ){

				advancedSearchVanCount = data;
				$('#vehicleCountDisplay').html(data + ' Van(s) Available');
			}else{
				advancedSearchCarCount = data;
				$('#vehicleCountDisplay').html(data + ' Car(s) Available');
			}
		},
		function(objRequest){

		}
	);
}

/*
function showCarSearch ( showCars ){

	if( showCars == true ){
		// Show car tab
		$('#vehicleType').show();
		$('#tabContentVanSearch').hide();
		$('#tabVansSearch').removeClass('active');
		$('#tabContentCarSearch').show();
		$('#tabCarsSearch').addClass('active');
		$('#advancedSearchDoors').show();
		$('#advancedSearchTaxBand').show();
		$('#search_url').val('used-cars');
		$('#is_van').val(0);
		$('#vehicleCountDisplay').html(advancedSearchCarCount + ' Car(s) Available');

	}else{
		// Show van tab
		$('#vehicleType').hide();
		$('#tabContentCarSearch').hide();
		$('#tabCarsSearch').removeClass('active');
		$('#tabContentVanSearch').show();
		$('#tabVansSearch').addClass('active');
		$('#advancedSearchDoors').hide();
		$('#advancedSearchTaxBand').hide();
		$('#search_url').val('vans');
		$('#is_van').val(1);
		$('#vehicleCountDisplay').html(advancedSearchVanCount + ' Van(s) Available');
	}
}
*/

/**
* @ desc sets and submits New Vehicles Search form
*/
function intelliQuickSearch(){

	if( currentISearch != $('#quick_search_value').val() ){

		rememberQuickVehicleSearchValue = $('#quick_search_value').val();

		if ( $('#quick_search_value').val() != '' && $('#quick_search_value').val() != 'Quick Vehicle Search' && $('#quick_search_value').val().length > 1 ) {

			var searchArray = $('#quick_search_value').val().toLowerCase().split(' ');

			ndCollector(
				'/frontend-operations/intelli-quick-search/',
				'quick_search_value=' + $('#quick_search_value').val(),
				function(data){

					var text = ''; // per row
					var displayText = ''; // whole html for search results

					var names = ''; // per row collect
					var textNames = ''; // to stop similar results showing twice

					var searchItemArray = new Array();

					if (data != null) {

						displayText = '<table border="0" style="width: 100%;" cellpadding="0" cellspacing="0"><tr><th style="width: 100%; text-transform:uppercase;" colspan="2">Used Stock Search</th></tr>';

						$.each(data, function(i,item){

							text  = '';
							names = '';
							text += '<tr id="result_row_' + ++i + '" onmouseover="this.className = \'trOver\';" onmouseout="this.className=\'\';"><td style="width:60px;">';
							text += '<img src="' + netdirector.baseUrl + (( item.image_src != null && item.image_src != '' ) ? '/upload/images/stock/small/' + item.image_src : '/local/images/noImage72x54.gif' ) + '" alt="" class="float_left" style="width:60px;" /></td><td>';
							text += '<a href="javascript: submitQuickSearch(' + item.id + ');" title="' + item.marque_name + '" style="text-decoration:none; color:#666;" id="result_row_link_' + i + '">';

							searchItemArray[item.id] = item;

							//if( wordExists(searchArray,item.marque_name.toLowerCase()) == true  ){

								text += ' '  + item.marque_name;
								names += ' '  + item.marque_name;
							//}

							//if( wordExists(searchArray,item.model_name.toLowerCase()) == true  ){

								text += ' '  + item.model_name;
								names += ' '  + item.model_name;
							//}

							if( wordExists(searchArray,item.variant.toLowerCase()) == true  ){

								text += ' '  + item.variant;
								names += ' '  + item.variant;
							}

							//if( wordExists(searchArray,item.body_style_name.toLowerCase()) == true  ){

								text += ' '  + item.body_style_name;
								names += ' '  + item.body_style_name;
							//}

							if( wordExists(searchArray,item.fuel_type_name.toLowerCase()) == true  ){

								text += ' '  + item.fuel_type_name;
								names += ' '  + item.fuel_type_name;
							}

							if( wordExists(searchArray,item.transmission_type_name.toLowerCase()) == true  ){

								text += ' '  + item.transmission_type_name;
								names += ' '  + item.transmission_type_name;
							}

							if( wordExists(searchArray,item.registration_year.toLowerCase()) == true  ){

								text += ' '  + item.registration_year;
								names += ' '  + item.registration_year;
							}

							if( wordExists(searchArray,item.engine_size.toLowerCase()) == true  ){

								text += ' '  + item.engine_size + 'cc';
								names += ' '  + item.engine_size + 'cc';
							}

							if( wordExists(searchArray,item.full_registration.toLowerCase()) == true  ){

								text += ' '  + item.full_registration;
								names += ' '  + item.full_registration;
							}
							text += '</a></td>';

							//alert( displayTextNames.search(text) );
							if( textNames.search(names) < 0 ){
								textNames += names;
								displayText += text;
							}
						});
						displayText += '</table>';
						quickSearchResults = searchItemArray;
						totalResults = data.length;
						resultDisplayKeyboardHighlight = 0;
					}
					$('#searchResults').html(displayText);
					$('#searchResults').addClass('results');

					currentISearch = $('#quick_search_value').val(); // set the current value for remembrance
				},
				function(objRequest){

				}
			);
		} else {

			$('#searchResults').html('');
			$('#searchResults').removeClass('results');
			$('#searchResults').addClass('noResults');
		}
	}
}


/**
* @ desc sets and submits New Vehicles Search form
*/
function submitNewVehicleSearch(){

	var modelContentUrl = null;
	if( $('#new_car_is_van').val() == 1 ){

		var franchiseUrl  = $( '#new_van_franchise_detail_id option:selected').data('url');
		var modelUrl   = $( '#new_van_model_name option:selected').data('url');
		modelContentUrl = $( '#new_van_model_name option:selected').data('content_url');
		var variantId = $("#new_van_variant").val();
		var areaUrl = 'new-vans';
	}else{

		var franchiseUrl  = $( '#new_car_franchise_detail_id option:selected').data('url');
		var modelUrl   = $( '#new_car_model_name option:selected').data('url');
		modelContentUrl = $( '#new_car_model_name option:selected').data('content_url');
		var variantId = $("#new_car_variant").val();
		var areaUrl = 'new-cars';
	}
	
	if ((modelContentUrl !== null) && (modelContentUrl != '')) {
		window.open (modelContentUrl);
		return;
	}

	if (netdirector.isGroup != 1) {
		franchiseUrl = netdirector.franchiseUrl;
	}

	if ((modelUrl === undefined) || (modelUrl == null) || (modelUrl == '')) {
		alert('You must select a make and model to search for');
		return;
	}

	var url = netdirector.baseUrl + '/' + ( ( franchiseUrl != '' && franchiseUrl != 'group' ) ? franchiseUrl + '/' : '' ) + areaUrl + '/' + modelUrl;
	if (variantId != undefined) {
		if (variantId.length > 0) {
			url +=  '/' + variantId;
		}
	}

	window.location = url;
}


/**
* @ desc sets category and submits form
*/
function submitCategorySearch( category ){

	$('#category_search').val( category );
	$('#frmSearchUsedCars').submit();
}


/**
* @ desc submits quick search form
*/
function submitQuickSearch(id){


	var searchArray = $('#quick_search_value').val().toLowerCase().split(' ');
	var item = quickSearchResults[id];

	//if( wordExists(searchArray,item.marque_name.toLowerCase()) == true  ){

		$('#quick_search_marque_id').val( item.auto_marque_detail_id );
	//}

	//if( wordExists(searchArray,item.model_name.toLowerCase()) == true  ){

		$('#quick_search_model_id').val( item.auto_model_detail_id );
	//}

	if( wordExists(searchArray,item.variant.toLowerCase()) == true  ){

		$('#quick_variant').val( item.variant );
	}

	//if( wordExists(searchArray,item.body_style_name.toLowerCase()) == true  ){

		$('#quick_auto_body_style_detail_id').val( item.auto_body_style_detail_id );
	//}

	if( wordExists(searchArray,item.fuel_type_name.toLowerCase()) == true  ){

		$('#quick_auto_fuel_type_detail_id').val( item.auto_fuel_type_detail_id );
	}

	if( wordExists(searchArray,item.transmission_type_name.toLowerCase()) == true  ){

		$('#quick_auto_transmission_detail_id').val( item.auto_transmission_detail_id );
	}

	if( wordExists(searchArray,item.registration_year.toLowerCase()) == true  ){

		$('#quick_registration_year').val( item.registration_year );
	}

	if( wordExists(searchArray,item.engine_size.toLowerCase()) == true  ){

		$('#quick_engine_size').val( item.engine_size );
	}

	if( wordExists(searchArray,item.full_registration.toLowerCase()) == true  ){

		$('#quick_full_registration').val( item.full_registration );
	}
	$('#frmQuickSearchUsedCars').submit();
}


function quickSearchFocus(){

	if( $('#quick_search_value').val() == 'Quick Vehicle Search' ){

		if( rememberQuickVehicleSearchValue != '' ){
			$('#quick_search_value').val(rememberQuickVehicleSearchValue)
			$('#searchResults').html(rememberedDisplayText);
			$('#searchResults').addClass('results');
		}else{
			$('#quick_search_value').val('')
		}
	}
}


function quickSearchBlur(){

	$('#quick_search_value').val('Quick Vehicle Search');
	rememberedDisplayText = $('#searchResults').html();
	setTimeout( "hideQuickSearchResults()",300);
}


function hideQuickSearchResults(){

	if( rememberedDisplayText != '' ){
		$('#searchResults').animate({height: "toggle"}, 200, function(){

			$('#searchResults').html('');
			$('#searchResults').removeClass('results');
			$('#searchResults').addClass('noResults');
		});
	}
}


/**
* @ desc sets category and submits form
*/
function submitAdvancedSearch(){

	if( $('#tabVansSearch').hasClass('active') == true ){

		$('#search_marque_id').val( $('#van_auto_marque_detail_id').val() );
		$('#search_model_id').val( $('#van_auto_model_detail_id').val() );
	}else{

		$('#search_marque_id').val( $('#auto_marque_detail_id').val() );
		$('#search_model_id').val( $('#auto_model_detail_id').val() );
	}
	$('#frmSearchUsedCars').submit();
}


/**
* @ 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;
}


function wordExists(arr, obj) {
	for(var i=0; i<arr.length; i++) {
		if( arr[i] != '' ){
			if (obj.search(arr[i]) >= 0) return true;
		}
	}
}


function detectkeyPress(e){

	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;

	if( keycode == 40 ){
		keyboardDown();
	}else if( keycode == 38 ){
		keyboardUp();
	}else if( keycode == 13 ){
		keyboardReturn();
	}
}


function keyboardDown(){

	if( resultDisplayKeyboardHighlight < totalResults ){
		if( resultDisplayKeyboardHighlight > 0 ){
			$( '#result_row_' + resultDisplayKeyboardHighlight ).removeClass('trOver');
		}
		resultDisplayKeyboardHighlight += 1;
		$( '#result_row_' + resultDisplayKeyboardHighlight ).addClass('trOver');
	}
}


function keyboardUp(){

	if( resultDisplayKeyboardHighlight > 1 ){
		$( '#result_row_' + resultDisplayKeyboardHighlight ).removeClass('trOver');
		resultDisplayKeyboardHighlight -= 1;
		$( '#result_row_' + resultDisplayKeyboardHighlight ).addClass('trOver');
	}
}


function keyboardReturn(){

	if( resultDisplayKeyboardHighlight > 0 ){
		$( '#result_row_link_' + resultDisplayKeyboardHighlight ).focus();
		window.location = $( '#result_row_link_' + resultDisplayKeyboardHighlight ).attr( 'href' );
		return false;
	}
}

/**
* @ desc This will post the (custom cms) form via Ajax
*/
function submitCustomForm( formType, callback ){

	if( formType == '' ){
		return;
	}

	// Check if form is valid before proceeding
	if( $( "#form" + formType ).valid() ){

		$('body').css('cursor', 'progress');

		$.ajax({
		  url: '/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 ( callback ) { callback(); }

					if ( typeof itForm == 'function' ) {
						itForm(data.intellitracker);
					}
				}else{

					// Show generic message
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
				}
			},
		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
	//$('#form' + formType + ' :input:text:first').focus();
}



function addToMyFavourites( vehicleId ){

	$('body').css('cursor', 'progress');

	$.ajax({
	  url: '/frontend-operations/save-vehicle-to-favourites/',
	  dataType: 'json',
	  data: 'auto_car_detail_id=' + vehicleId +'&max='+ favouritesLimit,
	  success: function(data){

			if( data == true ){
	
				// Favourite has been added successfully
				alert( 'Vehicle has been saved' );
				showMyFavourites();
			}else{

				// Favourite failed to save
				alert("Failed to save vehicle:\nEither it's already in your list or your list is full.");
			}
			$('body').css('cursor', 'default');
		},
	error: function( objRequest ){
			// Could not save favourite
			$('body').css('cursor', 'default');
		}
	});
}


/**
* @ desc remove this vehicle to favourites via Ajax
*/
function removeFavourite( vehicleId ){

	$('body').css('cursor', 'progress');

	$.ajax({
	  url: '/frontend-operations/remove-vehicle-from-favourites/',
	  dataType: 'json',
	  data: 'auto_car_detail_id=' + vehicleId,
	  success: function(data){

			if( data == true ){
	
				// Favourite has been removed successfully
				window.location.reload(true);
			}else{

				// Favourite failed to remove
			}
			$('body').css('cursor', 'default');
		},
	error: function( objRequest ){
			// Could not save favourite
			$('body').css('cursor', 'default');
		}
	});
}



function showMyFavourites(){

	$('body').css('cursor', 'progress');

	$.ajax({
	  url: '/frontend-operations/view-my-favourites/',
	  dataType: 'json',
	  data: 'limit=' + favouritesLimit,
	  success: function(data){

			if( data != 0 ){
			
				var vehicleTitle, text;
	
				// Add Options
				$.each(data, function(i,item){
					
					vehicleTitle = item.references.marque_name + ' ' + item.references.model_name + ' ' + item.variant;
					text = '<a href="' + netdirector.baseUrl + netdirector.areaUrl  + item.id + '/' + vehicleTitle.toLowerCase().replace( ' ', '-' ) + '" title="' + vehicleTitle + '"><img src="' + netdirector.baseUrl + '/upload/images/stock/small/' + item.imageSrc + '" alt="' + vehicleTitle + '" style="width:80px; height:60px;" /></a>';
					
					$('#thumb_' + ( i + 1 ) ).html( text );
				});

				//$('#favouritesSave').show();
				//$('#favouritesCompare').show();
				//$('#favouritesRetrieve').hide();
			}else{

				// Could not retrieve favourites
				//$('#favouritesSave').hide();
				//$('#favouritesCompare').hide();
				//$('#favouritesRetrieve').show();
			}
			$('body').css('cursor', 'default');
		},
	error: function( objRequest ){
			// Could not retrieve favourites
			//$('#favouritesSave').hide();
			//$('#favouritesCompare').hide();
			//$('#favouritesRetrieve').show();
			$('body').css('cursor', 'default');
		}
	});
}



/**
* @ desc This will save the temporary stored favourites to the database
*/
function saveFavourites(){

	// Check if form is valid before proceeding
	if( $( "#formSaveFavourites" ).valid() ){

		$('body').css('cursor', 'progress'); 

		$.ajax({
		  url: '/frontend-operations/save-favourites/',
		  dataType: 'json',
		  data: $( '#formSaveFavourites' ).serialize(),
		  success: function(data){
		  
				if( data != 0 ){
					
					// Submitted ok.

					updateTips('Saved','You can now come back and view your saved vehicles anytime.','highlight','','alertBoxSaveFavourites');

					clearFormElements("#formSaveFavourites"); 
					setTimeout( "autoCloseDialog('dialogSaveFavourites');",4000);
					
				}else{

					// Show generic message
					updateTips('Request Failed','The form submit request failed, please try again.','error','','alertBoxSaveFavourites');
				}
				$('body').css('cursor', 'default'); 
			},
		error: function( objRequest ){
				updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBoxSaveFavourites');
				$('body').css('cursor', 'default'); 
			}
		});
	}
}



/**
* @ desc This will retrieve previously stored favourites
*/
function retrieveFavourites(){

	// Check if form is valid before proceeding
	if( $( "#formRetrieveFavourites" ).valid() ){

		$('body').css('cursor', 'progress'); 

		$.ajax({
		  url: '/frontend-operations/retrieve-favourites/',
		  dataType: 'json',
		  data: $( '#formRetrieveFavourites' ).serialize(),
		  success: function(data){
		  
				if( data == true ){
					
					// Submitted ok.
					updateTips('Retrieved','Redirecting..','highlight','','alertBoxRetrieveFavourites' );

					setTimeout( "window.location = netdirector.baseUrl + '/' + netdirector.franchiseUrl + 'used-cars/favourites';", 500);
					
				}else{

					// Show generic message
					updateTips('Request Failed','The email you have provided was not found in our system','error','','alertBoxRetrieveFavourites' );
				}
				$('body').css('cursor', 'default'); 
			},
		error: function( objRequest ){
				updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBoxRetrieveFavourites' );
				$('body').css('cursor', 'default'); 
			}
		});
	}
}

/**
 * Setup the "Request A Service" CMS form
 *
 * Populates the vehicle make / fuel type / transmission type fields and sets up the datepicker and model field population
 */
function setupRequestAServiceForm()
{
	var formId = '#formCustomRequestAService';

	var dateOptions = {
		minDate: +1,
		dateFormat: 'dd/mm/yy',
		showOn: "both",
		buttonImage: netdirector.baseUrl +"/local/images/iconCalendar.gif",
		buttonImageOnly: true
	};
	$(formId +' .datepicker').datepicker(dateOptions);

	$(formId +' select[name=auto_marque_detail_id]').change(function() {
		$(formId +' select[name=auto_model_detail_id]')
			.attr('disabled', 'disabled')
			.empty()
			.append('<option value="">- Select Model -</option>');

		$.ajax({
			url: '/frontend-operations/fetch-models-for-marque/',
			dataType: 'json',
			data: $(formId).serialize(),
			success: function(data){
				if ((data.status != 'ok') || (data.list.length < 1)) {
					return;
				}

				$(formId +' select[name=auto_model_detail_id]')
					.attr('disabled', '');
				for (i = 0; i < data.list.length; i++) {
					var entry = data.list[i];
					$(formId +' select[name=auto_model_detail_id]')
						.append('<option value="'+ entry.id +'">'+ entry.modelName +'</option>');
				}
			},
			error: function(objRequest) {
//				console.log(objRequest);
			}
		});
	});

	$.ajax({
		url: '/frontend-operations/fetch-request-a-service-lists/',
		dataType: 'json',
		data: '',
		success: function(data){
			if (data.status != 'ok') {
				return;
			}
			var i = 0;
			var entry = null;

			$(formId +' select[name=auto_marque_detail_id]')
				.attr('disabled', '')
				.empty()
				.append('<option value="">- Select Make -</option>');
			for (i = 0; i < data.marqueList.length; i++) {
				entry = data.marqueList[i];
				$(formId +' select[name=auto_marque_detail_id]')
					.append('<option value="'+ entry.id +'">'+ entry.marqueName +'</option>');
			}

			$(formId +' select[name=auto_fuel_type_detail_id]')
				.attr('disabled', '')
				.empty()
				.append('<option value="">- Select Fuel Type -</option>');
			for (i = 0; i < data.fuelTypeList.length; i++) {
				entry = data.fuelTypeList[i];
				$(formId +' select[name=auto_fuel_type_detail_id]')
					.append('<option value="'+ entry.id +'">'+ entry.fuelTypeName +'</option>');
			}

			$(formId +' select[name=auto_transmission_type_detail_id]')
				.attr('disabled', '')
				.empty()
				.append('<option value="">- Select Transmission Type -</option>');
			for (i = 0; i < data.transmissionList.length; i++) {
				entry = data.transmissionList[i];
				$(formId +' select[name=auto_transmission_type_detail_id]')
					.append('<option value="'+ entry.id +'">'+ entry.transmissionTypeName +'</option>');
			}

		},
		error: function(objRequest) {
//			console.log(objRequest);
		}
	});

}

function collectAllModels(elementId, marqueId, isVan, selectedId){ 
 	var modelId = $( elementId ); 
	modelId.attr('disabled', 'disabled'); 
 
	$.ajax({ 
		url: '/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 -'); 
		} 
	}); 
}

/**
 * If the text value matches the placeholder value, clear it.
 */
function clearPlaceholder(selector)
{
	if ($(selector).attr('placeholder') == $(selector).val()) {
		$(selector).val('');
	}
}

function getGoogleConversionCode() {
	// loads in the google conversion code via ajax
	$('#googleConversionCode').remove();
	$('body').append('<div id="googleConversionCode"  style="display:none;"></div>');
	$('#googleConversionCode').load('/frontend-operations/fetch-adwords-conversion-code');
}


function arrayUnique(arrayName)
{
	var newArray = new Array();
	
	label:for(var i=0; i<arrayName.length;i++ )
	{  
		for(var j=0; j<newArray.length;j++ )
		{
			if(newArray[j]==arrayName[i]) 
				continue label;
		}
		newArray[newArray.length] = arrayName[i];
	}
	return newArray;
}


/**
 * Displays an opening hours popup
 */
function displayEPrice(vehicleId, franchiseDetailId) {

	// The callback function needs to set up the form
	callBack = function() {
		$('#frmEprice').submit(function(ev) {
			ev.preventDefault();

			// Check if form is valid before proceeding
			if( $( "#frmEprice" ).valid() ){

				$('body').css('cursor', 'progress');

				$( '.replaceSenderEmail' ).html( $('#eprice_enquiry_email').val() );

				$.ajax({
				  url: '/frontend-operations/submit-form/',
				  dataType: 'json',
				  data: $( '#frmEprice' ).serialize(),
				  success: function(data){
					  if( data != 0 ){
						  updateTips('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','','alertBoxEPrice');
						  $('#ePriceDetail').slideUp(function() {
							  $('#ePriceSuccess').slideDown();
						  });

							itForm(data.intellitracker);

							if ((franchiseDetailId > 0) && (franchiseDetailId != 2)) {
								var crtR = Math.floor(Math.random()*99999999999);
								var criteoImage = '<img src="https://sslwidget.criteo.com/'+ criteo.PoolId +'/display.js?p1='
									+ encodeURIComponent("v=2&wi="+ criteo.SalesCampaignId +"&t="+ crtR +"&s=1&i1="+ fullReg +"&p1=1&q1=1")
									+'&t1=transaction&resptype=gif" width="1" height="1" />';
								$("body").append(criteoImage);
							}

							// insert the google conversion code into the page
							getGoogleConversionCode();

					  } else {
						  updateTips('Request Failed','The form submit request failed, please try again.','error','','alertBoxEPrice');
					  }
				  },
				error: function( objRequest ){
						updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBoxEPrice');
					}
				});
				$('body').css('cursor', 'default');

			}
		});
	}

	displayCustomPopup('e-price/?vehicleId='+vehicleId +'&franchise_detail_id='+ franchiseDetailId, callBack);
}

/**
 * Display a custom popup on the page
 * This supports a callback function that is run once the form is displayed
 */
function displayCustomPopup(popupName, callBack) {
	$('#ePriceWrapper').load( '/popup/'+popupName, function() {
		scroll(0,0);
		$('#ePriceWrapper').fadeIn('slow', callBack);
	});
}


