var advancedSearchLoaded   = false;
var newVehicleSearchLoaded = false;
var leasingVehicleSearchLoaded = false;
var advancedSearchCarCount = 0;
var advancedSearchVanCount = 0;
var possibleVehicleTypes   = ['car', 'van', 'bike'];

var resultDisplayKeyboardHighlight = 0;
var currentISearch = '';
var totalResults   = 0;
var favouritesLimit  = 6;
var quickSearchResults = new Array();

 // 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() {

    // fix for chrome and safari scrolling when in a form.
    if ( $.browser.webkit == true ) {
        $('div[id*=dialog]').bind('dialogopen', function ()
            {
                setTimeout(function ()
                {
                    $(document)
                        .unbind('mousedown.dialog-overlay')
                        .unbind('mouseup.dialog-overlay');
                }, 1);
            });
    }
    
	// Create tabs and start them working

    
	$("#tabNewVehicleSpec").tabs();
	$("#tabUsedVehicleInfo").tabs();
    // Display search form (is set to display:none to prevent fouc)
    $('#tabVehicleSearch').css('display', 'block');

	// Create tabs and start them working
    $("#tabVehicleSearch").tabs();

	// Display search form (is set to display:none to prevent fouc)
    $('#tabHomeVehicleType').css('display', 'block');

	// Create tabs and start them working
    $("#tabHomeVehicleType").tabs();

	// Display search form (is set to display:none to prevent fouc)
    $('#tabOfferSelection').css('display', 'block');

	// Create tabs and start them working
    $("#tabOfferSelection").tabs();

	// Display search form (is set to display:none to prevent fouc)
    $('#usedVehicleDetails').css('display', 'block');

	// Create tabs and start them working
    $("#usedVehicleDetails").tabs();

	// Display search form (is set to display:none to prevent fouc)
    $('#usedVehicleImageTabs').css('display', 'block');

	// Create tabs and start them working
    $("#usedVehicleImageTabs").tabs();
    

	$('input[name=addToCompare]').change( function( event ) {
		if ( event.target.checked ) {
			addToCompare( event.target.value );
		} else {
			removeFromCompare( event.target.value );
		}
	});

	// Generate Price
	priceListing();
	rememberSearchSettings();
	showMyFavourites();

	$('#layout_stockUpdates_email').click(
		function(event) {
			if ($('#layout_stockUpdates_email').val() == '- Enter Email Here -') {
				$('#layout_stockUpdates_email').val('');
			}
		}
	);

	setupCustomForm('OffersContactUs');

    /**
	* @ desc This is the pop up dialog box for Retrieving Favourites
	*/
	$("#dialogRetrieveFavourites").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		buttons: {
			'Submit': function() {
				retrieveFavourites();
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});


	/**
	* @ desc This is the pop up dialog box for Saving Favourites
	*/
	$("#dialogSaveFavourites").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		buttons: {
			'Submit': function() {
				saveFavourites();
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

    /**
	* @ desc This is the pop up dialog box for the rapid response form
	*/
	$("#dialogRapidResponse").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		buttons: {
			'Submit': function() {
				submitGlobalForm('RapidResponse');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

    /**
	* @ desc This is the pop up dialog box for the insurance overseas form
	*/
	$("#dialogInsuranceOverseas").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		buttons: {
			'Submit': function() {
				submitGlobalForm('InsuranceOverseas');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

    /**
	* @ desc This is the pop up dialog box for the insurance uk form
	*/
	$("#dialogInsuranceUk").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		buttons: {
			'Submit': function() {
				submitGlobalForm('InsuranceUk');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});
    
    /**
	* @ desc This is the pop up dialog box for the motorcycle enquiry form
	*/
	$("#dialogMotorcycleEnquiry").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		buttons: {
			'Submit': function() {
				submitGlobalForm('MotorcycleEnquiry');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

    /**
	* @ desc This is the pop up dialog box for the rapid response form
	*/
	$("#dialogOffersJump").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		buttons: {
			'Submit': function() {
				submitGlobalForm('OffersJump');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});


	/**
	* 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 Service Branch fields and populates the branches select box
	*/
	$('.prePopulateBranches').each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Please Select -');
        
        $.ajax({
            url: '/frontend-operations/get-service-branches/',
            dataType: 'json',
            
            success: function(data){
    
                // Add Options
                $.each(data, function(i,item){
                    $( thisSelection ).addOption(item.ID, item.Name);
                });
                
                $( thisSelection ).attr( "selectedIndex", 0);
                $( thisSelection ).removeAttr('disabled');
                
                },
            error: function(objRequest){
    
                modelId.removeAttr('disabled').removeOption(/./).addOption('', '- Please Select -');
            }
	    });
	});
    
    /**
	* Looks for any form bodystyle fields and populates the bodystyle select box
	*/
	$('.prePopulateBodyStyles').each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select BodyStyle -');
        
        $.ajax({
            url: '/frontend-operations/get-vehicle-body-styles/',
            dataType: 'json',
            
            success: function(data){
    
                // Add Options
                $.each(data, function(i,item){
                    $( thisSelection ).addOption(item.ID, item.Name);
                });
                
                $( thisSelection ).attr( "selectedIndex", 0);
                $( thisSelection ).removeAttr('disabled');
                
                },
            error: function(objRequest){
    
                modelId.removeAttr('disabled').removeOption(/./).addOption('', '- Select BodyStyle -');
            }
	    });
	});
    
    /**
	* Looks for any form sources fields and populates the sources select box
	*/
	$('.prePopulateInternetSecondarySources').each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Please Select -');
        
        $.ajax({
            url: '/frontend-operations/get-internet-secondary-sources/',
            dataType: 'json',
            
            success: function(data){
    
                // Add Options
                $.each(data, function(i,item){
                    $( thisSelection ).addOption(item.ID, item.Name);
                });
                
                $( thisSelection ).attr( "selectedIndex", 0);
                $( thisSelection ).removeAttr('disabled');
                
                },
            error: function(objRequest){
    
                modelId.removeAttr('disabled').removeOption(/./).addOption('', '- Please Select -');
            }
	    });
	});
    
    /**
	* Looks for any form marque fields and populates the marque select box
	*/
	$('.prePopulateVehicleMarques').each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select Marque -');
        
        
        $.ajax({
            url: '/frontend-operations/get-vehicle-makes/',
            dataType: 'json',
            
            success: function(data){
    
                // Add Options
                $.each(data, function(i,item){
                    $( thisSelection ).addOption(item.ID, item.Name);
                });
                
                $( thisSelection ).attr( "selectedIndex", 0);
                $( thisSelection ).removeAttr('disabled');
                
                },
            error: function(objRequest){
    
                modelId.removeAttr('disabled').removeOption(/./).addOption('', '- Select Marque -');
            }
	    });
	});
    
	/**
	* 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();

    $('.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');
});


/**
* @ desc This will collect All Models under a particular Make
*/
function collectServiceRanks(elementId, branchId){

	var rankId = $( elementId );
	rankId.attr('disabled', 'disabled');

	$.ajax({
		url: '/frontend-operations/get-service-branch-ranks/',
		dataType: 'json',
		data: 'branch_id=' + branchId ,
		success: function(data){
            
            // Remove all options
            rankId.removeOption(/./).addOption('', '- Select Rank -');
            
            // Add Options            
            if(data.length == undefined){
                rankId.addOption(data.ID, data.Name);
            }else{
				$.each(data, function(i,item){
					rankId.addOption(item.ID, item.Name);
				});
            }

            rankId.removeAttr('disabled');
            rankId.attr( "selectedIndex", 0);

			},
		error: function(objRequest){

			rankId.removeAttr('disabled').removeOption(/./).addOption('', '- Select Rank -');
		}
	});
}

/**
* @ desc This will collect All Service Branches
*/
function collectServiceBranches(elementId){

	var thisSelection = '#' + elementId;
    // Remove all options
    $( thisSelection ).removeOption(/./).addOption('', '- Please Select -');
    
    $.ajax({
        url: '/frontend-operations/get-service-branches/',
        dataType: 'json',
        
        success: function(data){

            // Add Options
            $.each(data, function(i,item){
                $( thisSelection ).addOption(item.ID, item.Name);
            });
            
            $( thisSelection ).attr( "selectedIndex", 0);
            $( thisSelection ).removeAttr('disabled');
            
            },
        error: function(objRequest){

            thisSelection.removeAttr('disabled').removeOption(/./).addOption('', '- Please Select -');
        }
    });
}

/**
* @ desc This will collect All Models under a particular Make
*/
function collectInternetSecondarySources(elementId){
    
    var thisSelection = '#' + elementId;
    // Remove all options
    $( thisSelection ).removeOption(/./).addOption('', '- Please Select -');
    
    $.ajax({
        url: '/frontend-operations/get-internet-secondary-sources/',
        dataType: 'json',
        
        success: function(data){

            // Add Options
            $.each(data, function(i,item){
                $( thisSelection ).addOption(item.ID, item.Name);
            });
            
            $( thisSelection ).attr( "selectedIndex", 0);
            $( thisSelection ).removeAttr('disabled');
            
            },
        error: function(objRequest){

            thisSelection.removeAttr('disabled').removeOption(/./).addOption('', '- Please Select -');
        }
    });
}

/**
* @ desc This will save the selected areas for this franchise via Ajax
*/
function submitGlobalForm( formType ){

	if( formType != '' ){

         var lowerFormType = formType.toLowerCase();

		// Check if form is valid before proceeding
		if( $( "#form" + formType ).valid() && !$( "#form" + formType ).data('disable') ){

            var formData = '';

            if($('#'+lowerFormType+'_title').length)
            {
                formData += 'title=' + $('#'+lowerFormType+'_title > option:selected').text();
            }
            if($('#'+lowerFormType+'_branch_of_service').length)
            {
                formData += '&branch_of_service=' + $('#'+lowerFormType+'_branch_of_service > option:selected').text();
            }
            if($('#'+lowerFormType+'_how_heard').length)
            {
                formData += '&how_did_you_hear_about_us=' + $('#'+lowerFormType+'_how_heard > option:selected').text();
            }
            if($('#'+lowerFormType+'_body_style').length)
            {
                formData += '&body_style=' + $('#'+lowerFormType+'_body_style > option:selected').text();
            }
            if($('#'+lowerFormType+'_vehicle_make').length)
            {
                formData += '&vehicle_make=' + $('#'+lowerFormType+'_vehicle_make > option:selected').text();
            }

            formData += '&';

			var params = $( '#form' + formType ).serialize();

			formStatusCustom(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);

            $.ajax({
				url: '/frontend-operations/submit-form/',
				dataType: 'json',
				data: formData + params,
				success: function(data){

					if( data.status == true ){
						itForm(data.intellitracker);
						// Submitted ok.
                        updateTips('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','','alertBox' + formType);

						clearFormElements("#form" + formType);

						//Google analytics tracking
						var _gaq = _gaq || [];
						_gaq.push(['_trackPageview', '/submit-form/' + encodeURIComponent( formType ) ]);

						setTimeout(function () {
							formStatusCustom(formType, false);
							autoCloseDialog('dialogOffers' + formType);
						}, 4000);

					}else{

						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);
						}

						formStatusCustom(formType, false);
					}
				},
				error: function( objRequest ){
                    updateTips('Request Failed','The submission request failed, please try again.','error','','alertBox' + formType);
					formStatusCustom(formType, false);
				}
			});
		}
	}
}

function formStatusCustom(formType, disable) {

	var id = '#form' + formType, height = 400;

	if (typeof formType === 'undefined') {
		return false;
	}

	if (disable) {
		// Store the form's original height.

		// Loading cursor and disabled submit button.
		$('body').css('cursor', 'progress');
		$(id + ' input, ' + id + ' textarea, ' + id + ' select').attr('disabled', true);

		$(id)
			.data('disable', true)
			.data('originalHeight', $(id).innerHeight())
			.animate({
				height : 0,
				opacity : 0
			}, 400, function () {
				$(this).css('display', 'none')
			})
			.parent()
			.next()
			.slideUp(300);

	} else {

		if (typeof $(id).data('originalHeight') !== 'undefined') {
			height = $(id).data('originalHeight');
		}

		$(id)

		// Enable submit button and default cursor.
		$(id + ' input, ' + id + ' textarea, ' + id + ' select').removeAttr('disabled');
		$('body').css('cursor', 'default');

		$(id)
			.css('display', 'block')
			.data('disable', false)
			.animate({
				height : height + 'px',
				opacity : 100
			}, 400)
			.parent()
			.next()
			.slideDown(300);
	}
}


/**
* @ 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();
        
        if( dialogName == 'dialogRapidResponse' ){
            collectServiceBranches( 'rapidresponse_branch_of_service' );
            collectInternetSecondarySources( 'rapidresponse_how_heard' );
        }
	}
}


function displayFormCaptchaImage( formElementId ){

	var form = $(formElementId)

	if( form.length && $('div.captcha', form).length ){

		var target = '/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 will attempt to reset any options selected in the search
*/
function rememberSearchSettings(){

	if( parseInt( searchParams.isBike ) == 1 ){

		showCarSearch('bike');

	}else if( parseInt( searchParams.isVan ) == 1 ){

		showCarSearch('van');

	}else{

		showCarSearch('car');
	}
}


/**
* @ 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>" + 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:not(:.noClear)').each(function() {

            switch(this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = true;
            }
		$(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, nonUser){

	nonUser    = ( nonUser != null && nonUser == true )? true : false;

	var isVan  = $('#is_van').val();
	var isBike = $('#is_bike').val();

	var marqueId = $("#auto_marque_detail_id").val();
	var modelId  = $("#auto_model_detail_id");

	modelId.attr('disabled', 'disabled');

	$.ajax({
		url: '/frontend-operations/available-model-list/',
		dataType: 'json',
		data: 'marque_id=' + marqueId + '&is_van=' + isVan + '&is_bike=' + isBike,
		success: 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 != 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');

				if( !nonUser ){

					// Calculate vehicle count only if user has changed selection
					collectAdvancedSearchCount();
				}
			},
		error: function(objRequest){

			modelId.removeAttr('disabled');
		}
	});
}

/**
* @ desc This will collect Available Models
*/
function collectAvailableLeasingModels(selectedId, nonUser){

	nonUser    = ( nonUser != null && nonUser == true )? true : false;

	var marqueId = $("#auto_leasing_marque_detail_id").val();
	var modelId  = $("#auto_leasing_model_detail_id");

	modelId.attr('disabled', 'disabled');

	$.ajax({
		url: '/frontend-operations/available-leasing-model-list/',
		dataType: 'json',
		data: 'marque_id=' + marqueId,
		success: function(data){

				// Remove all options
				modelId.removeOption(/./);

				// Add Options
				$.each(data, function(i,item){

					modelId.addOption(item.model_name, item.model_name);
				});

				// 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');

				if( !nonUser ){

					// Calculate vehicle count only if user has changed selection
					collectAdvancedSearchCount();
				}
			},
		error: function(objRequest){

			modelId.removeAttr('disabled');
		}
	});
}


/**
* @ 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: '/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: '/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 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 New Vehicle Marque Lists
*/
function collectLeasingVehicleMarqueLists(){

	// Only load lists once
	if( leasingVehicleSearchLoaded != true ){

		// Remove all options and disable
		$('#auto_leasing_marque_detail_id').attr('disabled', 'disabled');

		$.ajax({
			url: '/frontend-operations/leasing-vehicle-marque-list/',
			dataType: 'json',
			data: '',
			success: function(data){

					newVehicleSearchLoaded = true;

					// Remove loading and show default select option
					$('#auto_leasing_marque_detail_id').removeOption(/./).addOption('', 'Select Make');

					// Add Options
					if( data.leasingMarque != null ){
						$.each(data.leasingMarque, function(i,item){
							$("#auto_leasing_marque_detail_id").addOption(item.marque_name, item.marque_name);
							$( '#auto_leasing_marque_detail_id option:last' ).data('url',item.franchiseUrl);
						});
					}

					$('#auto_leasing_marque_detail_id').removeAttr('disabled').attr( "selectedIndex", 0);
				},
			error: function(objRequest){

				$('#auto_leasing_marque_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);
				});

				// 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');
		$('#auto_tax_band').attr('disabled', 'disabled');

		$.ajax({
			url: '/frontend-operations/advanced-search-list/',
			dataType: 'json',
			data: '',
			success: 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 -');
					$('#auto_tax_band').removeOption(/./).addOption('', '- Select Tax Band -');

					// Add Options
					if( data.location != null ){
						$.each(data.location, function(i,item){
							$("#advancedSearchLocation").addOption(item.id, item.name);
						});
					}
					/*
					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);
						});
					}
					*/
					if( data.taxBand != null ){
						$.each(data.taxBand, function(i,item){
							$("#auto_tax_band").addOption(item.band, 'Band ' + item.band + ' - ' + String.fromCharCode(163) + item.monthRate6 + '/' + String.fromCharCode(163) + item.monthRate12 + ' (6/12 months)' );
						});
					}

					$('#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);
					$('#auto_tax_band').removeAttr('disabled').attr( "selectedIndex", 0);
				},
			error: 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 -');
				$('#auto_tax_band').removeAttr('disabled').removeOption(/./).addOption('', '- Select Tax Band -');
			}
		});
	}
}


/**
* @ 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();
	}


	$.ajax({
		url: '/frontend-operations/advanced-search-count/',
		dataType: 'json',
		data: $('#frmSearchUsedCars').serialize() + extraParams,
		success: function(data){

				if( $('#selectCarsMotorbikes_1').attr('checked')){

					advancedSearchVanCount = data;
					$('#vehiclesFound').html(data + ' Bike(s) Found');
				}else{
					advancedSearchCarCount = data;
					$('#vehiclesFound').html(data + ' Car(s) Found');
				}
			},
		error: function(objRequest){

		}
	});
}


function showCarSearch ( vehicleType ){

	if( vehicleType == 'bike' ){
		// Show bike tab
		//$('#vehicleType').hide(); // category search

		//$('#tabCarsSearch').removeClass('active');
		//$('#tabVansSearch').removeClass('active');
		//$('#tabBikesSearch').addClass('active');

		$('#advancedSearchDoors').attr( "selectedIndex", 0).hide();
		$('#auto_tax_band').attr( "selectedIndex", 0).hide();
		$('#search_url').val('bikes');
		$('#is_van').val(0);
		$('#is_bike').val(1);

	}else if( vehicleType == 'van' ){
		// Show van tab
		$('#vehicleType').hide();// category search


		$('#tabCarsSearch').removeClass('active');
		$('#tabBikesSearch').removeClass('active');
		$('#tabVansSearch').addClass('active');

		$('#advancedSearchDoors').attr( "selectedIndex", 0).hide();
		$('#auto_tax_band').attr( "selectedIndex", 0).hide();
		$('#search_url').val('vans');
		$('#is_van').val(1);
		$('#is_bike').val(0);

	}else{
		// Show car tab
		$('#vehicleType').show(); // category search

		//$('#tabVansSearch').removeClass('active');
		//$('#tabBikesSearch').removeClass('active');
		//$('#tabCarsSearch').addClass('active');

		$('#advancedSearchDoors').show();
		$('#auto_tax_band').show();
		$('#search_url').val('used-cars');
		$('#is_van').val(0);
		$('#is_bike').val(0);
	}
	setupStockTypeData( vehicleType ); // collect lists for select boxes
	$('#vehicleCountDisplay').html(''); // hide counter because nothing is selected
	$('#auto_model_detail_id').attr( "selectedIndex", 0); // Reset Models list
}



/*
* @ desc New cars selector between cars and vans
*/
function showNewCarSearch ( showCars ){

	if( showCars == true ){
		// Show car tab
		$('#new_van_franchise_detail_id').hide(); //hide the select object
		$('#tabContentNewVanSearch').hide(); // hide the tab
		$('#tabNewVansSearch').removeClass('active'); // deactivate the tab

		$('#new_car_franchise_detail_id').show();
		$('#tabContentNewCarSearch').show();
		$('#tabNewCarsSearch').addClass('active');

		$('#new_car_search_url').val('new-cars');
		$('#new_car_is_van').val(0);

	}else{
		// Show van tab
		$('#new_car_franchise_detail_id').hide(); //hide the select object
		$('#tabContentNewCarSearch').hide();  // hide the tab
		$('#tabNewCarsSearch').removeClass('active'); // deactivate the tab

		$('#new_van_franchise_detail_id').show();
		$('#tabContentNewVanSearch').show();
		$('#tabNewVansSearch').addClass('active');

		$('#new_car_search_url').val('new-cars');
		$('#new_car_is_van').val(1);
	}
}


/**
* @ 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(' ');

			$.ajax({
				url: '/frontend-operations/intelli-quick-search/',
				dataType: 'json',
				data: 'quick_search_value=' + $('#quick_search_value').val(),
				success: 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
					},
				error: function(objRequest){

				}
			});
		} else {

			$('#searchResults').html('');
			$('#searchResults').removeClass('results');
			$('#searchResults').addClass('noResults');
		}
	}
}


/**
* @ desc sets and submits New Vehicles Search form
*/
function submitNewVehicleSearch(){

	var franchiseUrl, modelUrl, variantId, areaUrl

	if( $('#new_car_is_van').val() == 1 ){

		franchiseUrl  = $( '#new_van_franchise_detail_id option:selected').data('url');
		modelUrl   = $( '#new_van_model_name option:selected').data('url');
		variantId = $("#new_van_variant").val();
		areaUrl = 'new-vans';
	}else{

		franchiseUrl  = $( '#new_car_franchise_detail_id option:selected').data('url');
		modelUrl   = $( '#new_car_model_name option:selected').data('url');
		variantId = $("#new_car_variant").val();
		areaUrl = 'new-cars';
	}

	var url = netdirector.baseUrl + '/' + ( ( franchiseUrl != '' && franchiseUrl != 'group' ) ? franchiseUrl + '/' : '' )
			  + areaUrl + '/' + modelUrl;

	if(variantId) 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(){


	$('#search_marque_id').val( $('#auto_marque_detail_id').val() );
	$('#search_model_id').val( $('#auto_model_detail_id').val() );

	$('#frmSearchUsedCars').submit();
}

/**
* @ desc sets category and submits form
*/
function submitLeasingSearch(){


	$('#search_leasing_marque_id').val( $('#auto_leasing_marque_detail_id').val() );
	$('#search_leasing_model_id').val( $('#auto_leasing_model_detail_id').val() );

	$('#frmSearchLeasing').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 ){
    
var lowerFormType = formType.toLowerCase();
    //alert(lowerFormType);
	if( formType == '' ){
		return;
	}

	// Check if form is valid before proceeding
	if( $( "#form" + formType ).valid() ){

		$('body').css('cursor', 'progress');

        var formData = '';

        if($('#'+lowerFormType+'_title').length)
        {
            formData += 'title=' + $('#'+lowerFormType+'_title > option:selected').text();
        }
        if($('#'+lowerFormType+'_branch_of_service').length)
        {
            formData += '&branch_of_service=' + $('#'+lowerFormType+'_branch_of_service > option:selected').text();
        }
        if($('#'+lowerFormType+'_how_heard').length)
        {
            formData += '&how_did_you_hear_about_us=' + $('#'+lowerFormType+'_how_heard > option:selected').text();
        }
        if($('#'+lowerFormType+'_body_style').length)
        {
            formData += '&body_style=' + $('#'+lowerFormType+'_body_style > option:selected').text();
        }
        if($('#'+lowerFormType+'_vehicle_make').length)
        {
            formData += '&vehicle_make=' + $('#'+lowerFormType+'_vehicle_make > option:selected').text();
        }

        formData += '&';

        $.ajax({
		  url: '/frontend-operations/submit-form/',
		  dataType: 'json',
		  data: formData + $( '#form' + formType ).serialize(),
		  success: function(data){

				if( data != 0 ){

                    itForm(data.intellitracker);

					// Submitted ok.
					setupCustomForm( formType );
                    clearFormElements( '#form' + formType );
					updateTips('Thank You','Your details have been submitted successfully','highlight','','alertBox' + formType);

                    alert("Thank you. Your details have been submitted successfully");

					//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){

	if ( $('#form' + formType).length > 0 ) {
		// 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 save a vehicle to favourites via Ajax
*/
function addToMyFavourites( vehicleId ){

	$('body').css('cursor', 'progress');

	$.ajax({
	  url: '/frontend-operations/save-vehicle-to-favourites/',
	  dataType: 'json',
	  data: 'auto_car_detail_id=' + vehicleId,
	  success: function(data){

			if( data == true ){

				// Favourite has been added successfully
				alert( 'Vehicle has been saved' );
				showMyFavourites();
			}else{

				alert('Vehicle has already been saved');
			}
			$('body').css('cursor', 'default');
		},
	error: function( objRequest ){
			// Could not save favourite
			$('body').css('cursor', 'default');
		}
	});
}



/**
* @ desc This adds a vehicle to compare via Ajax
*/
function addToCompare( vehicleId ){

	$('body').css('cursor', 'progress');

	$.ajax({
	  url: '/frontend-operations/add-vehicle-to-compare/',
	  dataType: 'json',
	  data: 'auto_car_detail_id=' + vehicleId,
	  success: function(data){

			if( data['error'] != null && data['error'] != '' ){

				$('input[value='+vehicleId+']').attr('checked', false);
				alert( data['error'] );

			}
			$('body').css('cursor', 'default');
		},
	error: function( objRequest ){

			$('body').css('cursor', 'default');
		}
	});
}


/**
* @ desc This removes vehicle from compare via Ajax
*/
function removeFromCompare( vehicleId ){

	$('body').css('cursor', 'progress');

	$.ajax({
	  url: '/frontend-operations/remove-vehicle-from-compare/',
	  dataType: 'json',
	  data: 'auto_car_detail_id=' + vehicleId,
	  success: function(data){

			$('body').css('cursor', 'default');

			if ( $('.saveCompareTable tbody tr:first td:visible').length <= 2 ) {
				$('.saveCompareTable').html("");
				$('#compareNoVehiclesSelected').show();
			} else {
				$('#compare_'+vehicleId).fadeOut();
			}

		},
	error: function( objRequest ){

			$('body').css('cursor', 'default');
		}
	});
}


/**
* @desc Removes all vehicles stored for compare via Ajax
*/
function removeAllFromCompare() {

	$('body').css('cursor', 'progress');

	$.ajax({
	  url: '/frontend-operations/remove-all-from-compare/',
	  dataType: 'json',
	  data: '',
	  success: function(data){

			$('body').css('cursor', 'default');
			$('#CompareTbl').html("");
			$('#compareNoVehiclesSelected').show();
		},
	error: function( objRequest ){

			$('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 = netdirector.baseUrl + '/' + netdirector.franchiseUrl + 'used-cars/favourites';
			}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;
                if(item.imageSrc !== null){
                    text = '<a href="' + netdirector.baseUrl + '/' + netdirector.franchiseUrl + 'used-cars/' + item.id + '/' + vehicleTitle.toLowerCase().replace( ' ', '-' ) + '" title="' + vehicleTitle + '"><img src="' + netdirector.baseUrl + '/upload/images/stock/small/' + item.imageSrc + '" alt="' + vehicleTitle + '" /></a>';
                }
                else{
                    text = '<a href="' + netdirector.baseUrl + '/' + netdirector.franchiseUrl + 'used-cars/' + item.id + '/' + vehicleTitle.toLowerCase().replace( ' ', '-' ) + '" title="' + vehicleTitle + '"><img src="' + netdirector.baseUrl + '/local/images/saveCompareNoImage_65x50.png" alt="' + vehicleTitle + '" /></a>';

                }

                 $('#favouriteItem_' + ( 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');
			}
		});
	}
}



/**
* @ desc This will populate the select boxes with data according to vehicle type
*/
function setupStockTypeData( vehicleType ){

	setupMarqueData( 'auto_marque_detail_id', vehicleType );
	$('#auto_model_detail_id').removeOption(/./); // Remove models because we have re-generated marques
	setupBodystyleData( 'auto_body_style_detail_id', vehicleType );
	setupFuelData( 'auto_fuel_type_detail_id', vehicleType );
	setupTransmissionData( 'auto_transmission_detail_id', vehicleType );
}


/**
* @ desc This will populate the Marque List select box
*/
function setupMarqueData( elementId, vehicleType ){

	var thisSelection = '#' + elementId;

	// Remove all options
	$( thisSelection ).attr('disabled', 'disabled').removeOption(/./).addOption('', '- Select Make -');

	// Add Options
	if( $.inArray(vehicleType, possibleVehicleTypes) > -1 ){
		$.each(selectMarqueList[vehicleType], function(i,item){

			if( parseInt( item.count ) > 0 ){
				$( thisSelection ).addOption(item.id, item.marqueName.toUpperCase());
			}
		});
	}
	$( thisSelection ).removeAttr('disabled').attr( "selectedIndex", 0);

	// Remember Search Params
	if( searchParams.makeId > 0 ){

		$( thisSelection ).selectOptions( searchParams.makeId );

		collectAvailableModels( searchParams.modelId, true);

	}else{

        // If no previous search data, use defaults
        $( thisSelection ).selectOptions( netdirector.defaultAutoMarqueDetailId );
        collectAvailableModels( searchParams.modelId, true);
    }
}


/**
* @ desc This will populate the Bodystyle List select box
*/
function setupBodystyleData( elementId, vehicleType ){

	var thisSelection = '#' + elementId;

	// Remove all options
	$( thisSelection ).attr('disabled', 'disabled').removeOption(/./).addOption('', '- Select Body Style -');

	// Add Options
	if( $.inArray(vehicleType, possibleVehicleTypes) > -1 ){
		$.each(selectBodystyleList[vehicleType], function(i,item){
			$( thisSelection ).addOption(item.id, item.bodyStyleName.toUpperCase());
		});
	}
	$( thisSelection ).removeAttr('disabled').attr( "selectedIndex", 0);
}


/**
* @ desc This will populate the Fuel List select box
*/
function setupFuelData( elementId, vehicleType ){

	var thisSelection = '#' + elementId;

	// Remove all options
	$( thisSelection ).attr('disabled', 'disabled').removeOption(/./).addOption('', '- Select Fuel Type -');

	// Add Options
	if( $.inArray(vehicleType, possibleVehicleTypes) > -1 ){
		$.each(selectFuelList[vehicleType], function(i,item){
			$( thisSelection ).addOption(item.id, item.fuelTypeName.toUpperCase());
		});
	}
	$( thisSelection ).removeAttr('disabled').attr( "selectedIndex", 0);
}

/**
* @ desc This will populate the Transmission List select box
*/
function setupTransmissionData( elementId, vehicleType ){

	var thisSelection = '#' + elementId;

	// Remove all options
	$( thisSelection ).attr('disabled', 'disabled').removeOption(/./).addOption('', '- Select Transmission Type -');

	// Add Options
	if( $.inArray(vehicleType, possibleVehicleTypes) > -1 ){
		$.each(selectTransmissionList[vehicleType], function(i,item){
			$( thisSelection ).addOption(item.id, item.transmissionTypeName.toUpperCase());
		});
	}
	$( thisSelection ).removeAttr('disabled').attr( "selectedIndex", 0);
}

function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
    thisfield.value = "";
    }
}

function clickrecall(thisfield, defaulttext) {
if (thisfield.value == "") {
    thisfield.value = defaulttext;
    }
}
/*

 */
function getRanksFromBranches(elementId, branch){
    //alert('branch: '+ branch);
    //alert('elementId: '+ elementId);
    $( elementId ).removeOption(/./).addOption('', '- Select Title -');
    var title = new Array();
    if(branch == 1){
        title[25]='1st Lt'; title[60]='2 Lt'; title[17]='Airtrooper'; title[144]='Bombardier'; title[22]='Brigadier';
        title[132]='C/Sgt'; title[42]='Capt'; title[13]='Cfn'; title[35]='Col'; title[54]='Cpl'; title[4]='Dr';
        title[20]='Fusilier'; title[18]='Gdsmn'; title[31]='General'; title[12]='Gnr'; title[24]='Hldr';
        title[23]='Kgn'; title[9]='L/Bdr'; title[33]='L/Cpl'; title[15]='L/Sgt'; title[175]='LCOH'; title[48]='Lt';
        title[37]='Lt/Col'; title[26]='Lt/Gen'; title[29]='Maj Gen'; title[27]='Major'; title[40]='Major (Retd)';
        title[2]='Miss'; title[1]='Mr'; title[3]='Mrs'; title[5]='Ms'; title[39]='Musn'; title[174]='OCdt'; title[172]='Padre';
        title[16]='Private'; title[19]='Ranger'; title[6]='Reverand'; title[21]='Rfn'; title[8]='S/Sgt'; title[14]='Sapper';
        title[57]='Sgt'; title[11]='Sig'; title[7]='Sir'; title[10]='Trooper'; title[51]='WO1'; title[45]='WO2';
    }
    if(branch == 2){
        title[73]='AB'; title[152]='Able Rate'; title[149]='Admiral'; title[142]='AET'; title[44]='Capt'; title[77]='Chaplain RN'; title[67]='Commander';
        title[151]='Commodore'; title[69]='CPO'; title[101]='Dr'; title[143]='ETME'; title[71]='Flag Officer'; title[72]='Leading Hand'; title[49]='Lt';
        title[65]='Lt/Cmdr'; title[75]='Midshipman'; title[96]='Miss'; title[106]='Mr'; title[111]='Mrs'; title[116]='Ms'; title[159]='Naval Airman';
        title[66]='Petty Officer'; title[150]='Rear Admiral'; title[121]='Reverand'; title[127]='Sir'; title[74]='Sub/Lt'; title[76]='Vice Admiral';
        title[52]='WO1'; title[46]='WO2';
    }
    if(branch == 3){
        title[91]='AC'; title[92]='AET'; title[94]='Air Commodore'; title[154]='Capt'; title[88]='Chf Tech'; title[55]='Cpl'; title[104]='Dr'; title[81]='Flt/Lt';
        title[84]='Flt/Sgt'; title[87]='Flying Officer'; title[82]='Gp Capt'; title[86]='JT'; title[146]='L/Cpl'; title[89]='LAC'; title[161]='MACR'; title[176]='Major';
        title[99]='Miss'; title[109]='Mr'; title[114]='Mrs'; title[118]='Ms'; title[93]='Pilot Officer'; title[153]='RAF Tech Officer'; title[124]='Reverand';
        title[80]='Sac'; title[178]='SAC TECH'; title[58]='Sgt'; title[131]='Sir'; title[83]='Sqn/Ldr'; title[145]='Stn Cmdr'; title[85]='Wing Com'; title[90]='WO';
    }
    if(branch == 4){
        title[148]='2 Lt'; title[63]='C/Sgt'; title[43]='Capt'; title[36]='Col'; title[56]='Cpl'; title[100]='Dr'; title[32]='General'; title[34]='L/Cpl'; title[50]='Lt';
        title[38]='Lt/Col'; title[30]='Maj Gen'; title[28]='Major'; title[41]='Major (Retd)'; title[95]='Miss'; title[62]='Mne'; title[105]='Mr'; title[110]='Mrs';
        title[115]='Ms'; title[64]='Musn'; title[147]='Private'; title[120]='Reverand'; title[59]='Sgt'; title[126]='Sir'; title[53]='WO1'; title[47]='WO2';
    }
    if(branch == 5){
        title[133]='Assistant Chief Constable'; title[134]='Chief Constable'; title[135]='Chief Inspector'; title[136]='Chief Superintendent'; title[137]='Constable';
        title[138]='Deputy Chief Constable'; title[160]='Detective Chief Inspector'; title[158]='Detective Constable'; title[103]='Dr'; title[139]='Inspector';
        title[98]='Miss'; title[108]='Mr'; title[113]='Mrs'; title[117]='Ms'; title[123]='Reverand'; title[140]='Sergeant'; title[130]='Sir'; title[141]='Superintendent';
    }
    if(branch == 6){
        title[78]='Diplomat, Secretary.'; title[102]='Dr'; title[177]='Lady'; title[173]='Major'; title[97]='Miss'; title[107]='Mr'; title[112]='Mrs';
        title[119]='Ms'; title[156]='NATO'; title[122]='Reverand'; title[129]='Sir'; title[157]='UKBC'; title[79]='US Diplomat'; title[155]='US Military';
    }
    if(branch == 8){
        title[165]='Miss'; title[162]='Mr'; title[163]='Mrs'; title[164]='Ms';
    }
    if(branch == 9){
        title[171]='Dr'; title[168]='Miss'; title[167]='Mr'; title[169]='Mrs'; title[170]='Ms';
    }
    if(branch == 10){
        title[166]='Diplomat, Secretary';
    }
    
    //console.dir(title);
    for (var item in title){
      //  console.log(title[item]);
        $( elementId ).addOption(item,title[item] );
    }
    $( elementId ).attr( "selectedIndex", 0);
    
    
}

