var advancedSearchLoaded   = false;
var newVehicleSearchLoaded = false;
var advancedSearchCarCount = 0;
var advancedSearchVanCount = 0;

var resultDisplayKeyboardHighlight = 0;
var currentISearch = '';
var totalResults   = 0;
var favouritesLimit  = 4;
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).ready(function() {
    // Display search form (is set to display:none to prevent fouc)
    $('#tabVehicleSearch').css('display', 'block');
	$('#tabOffersListing').css('display', 'block');
	$('#tabUsedVehicleInfo').css('display', 'block');

	// Create tabs and start them working
    $("#tabVehicleSearch").tabs();
	$("#tabOffersListing").tabs();
	$("#tabUsedVehicleInfo").tabs();

	$('input[name=addToCompare]').change( function( event ) {
		if ( event.target.checked ) {
			addToCompare( event.target.value );
		} else {
			removeFromCompare( event.target.value );
		}
	});

    priceListing();
    rememberSearchSettings();
	showMyFavourites();

  /**
	* 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);
	});
	
	$( '.prePopulateCountryList', this ).each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select Country -').addOption('United Kingdom', 'United Kingdom');

		// Add Options
		$.each(selectCountryList, function(i,item){
			$( thisSelection ).addOption(item.country, item.country);
		});
		$( thisSelection ).attr( "selectedIndex", 0);
	});
	
	
	/**
	* Looks for any form county fields and populates the county select box
	*/
	$( '.prePopulateCountyList', this ).each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( 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', this ).change(function(){

		// Find the formId of the form this element sits in
		var thisFormId = '#' + $( this ).get( 0 ).form.id;

		// Then adjust the county field where necessary
		if( this.options[ this.selectedIndex].value == 'United Kingdom' ){

			$( thisFormId + ' .countySelectboxField').show();
			$( thisFormId + ' .countyInputField').hide();

		}else{

			$( thisFormId + ' .countySelectboxField').hide();
			$( thisFormId + ' .countyInputField').show();
		}
	});

        /**
        * @ 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() {
            }
        });

    $('.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 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 ){
    //alert('test');

	$('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 ( $('#CompareTbl tbody tr:first td:visible').length <= 2 ) {
				$('#CompareTbl').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 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 );
		}
		
		// Open the dialog box
		$('#' + dialogName ).dialog('open');
		
		// highlight first input
		$('#' + dialogName + ' :input:text:first').focus();
	}
}


/**
* @ desc sets category and submits form
*/
function submitCategorySearch( category ){

	$('#category_search').val( category );
	$('#frmSearchUsedCars').submit();
}


/**
* @ desc This will empty all form elements
*/
function clearFormElements(el) {

	$(el).find(':input').each(function() {
		switch(this.type) {
			case 'password':
			case 'select-multiple':
			case 'select-one':
			case 'text':
			case 'textarea':
				$(this).val('');
				break;
			case 'checkbox':
			case 'radio':
				this.checked = false;
		}
		$(this).removeClass('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 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 Make -');

				// 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 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 -');
		}
	});
}


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 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', 'disabled');

	$.ajax({
		url: '/frontend-operations/available-model-list/',
		dataType: 'json',
		data: 'marque_id=' + marqueId.val() + '&is_van=' + isVan,
		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 > 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();
			},
		error: function(objRequest){

			modelId.removeAttr('disabled');
		}
	});
}


/**
* @ desc This will collect Count of stock available
*/
function collectAdvancedSearchCount(){




	if( $('#tabVansSearch').hasClass('active')){

		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( $('#tabVansSearch').hasClass('active') == true ){

					advancedSearchVanCount = data;
					$('#vehicleCountDisplay').html(data);
				}else{*/
					advancedSearchCarCount = data;
					$('#vehicleCountDisplay').html(data+' Cars Found');
				/*}*/
			},
		error: function(objRequest){

		}
	});
}


function rememberSearchSettings(){

	// Remember Search Params
	if( parseInt( searchParams.makeId ) > 0 ){

		$("#auto_marque_detail_id").selectOptions( searchParams.makeId );
		collectAvailableModels( searchParams.modelId, 0);
		
	}else{
        if(netdirector.franchiseUrl) {
            $("#auto_marque_detail_id").selectOptions( netdirector.defaultAutoMarqueDetailId );
            collectAvailableModels( searchParams.modelId, 0);
        }
        else {
             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)
{
	var imageSrc = ($(el + ':visible').length) ? 'btnMoreOptions.gif' : 'btnLessOptions.gif';
	
	$('.btnMoreOptions').attr('src', '/local/images/' + imageSrc);
	$(el).animate
	(
		{
			opacity : 'toggle',
			height : 'toggle'
		},
		300
	);
}




/**
* @ 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();
}

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").attr( "selectedIndex", 0);
	$("#price").addOption('999998', String.fromCharCode(163) + '30,000+').attr( "selectedIndex", 0);
}


/**
* @ desc Adds commas in the right places to make long prices presentable
*/
function addCommas(nStr){

	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = ( x.length > 1 ) ? '.' + ( ( x[1].length == 1 )? x[1] + '0' : x[1] ) : '';
	var rgx = /(\d+)(\d{3})/;
	
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/**
* @ desc 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 -');
			}
		});
	}
}


//////////////////////////////////////////////////////////////////////////FORMS//////////////////////////////////////////////////////////////


/**
* @ 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();

    if(formType == 'UsedVehicleValueMyVehicle')
        collectAllMakes('#valuemyvehicle_my_make', 0);

    if(formType == 'CapNewVehiclesValueMyVehicle')
        collectAllMakes('#valuemyvehicle_my_make_id', 0);
}

/**
* @ 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 will post the (custom cms) form via Ajax
*/
function submitCustomForm( formType ){

	if( formType == '' ){
		return;
	}

	// Check if form is valid before proceeding
	if( $( "#form" + formType ).valid() ){

		$('body').css('cursor', 'progress');

		$.ajax({
		  url: '/frontend-operations/submit-form/',
		  dataType: 'json',
		  data: $( '#form' + formType ).serialize(),
		  success: function(data){

				if( data != 0 ){

					// Submitted ok.
					setupCustomForm( formType );
					updateTips('Thank You','Your details have been submitted successfully','highlight','','alertBox' + formType);

					if ( typeof itForm == 'function' ) {
						itForm(data.intellitracker);
					}

					//Google analytics tracking
					window._gaq = window._gaq || [];
					window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);

				}else{

					// Show generic message
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
				}
				$('body').css('cursor', 'default');
			},
		error: function( objRequest ){
				updateTips('Request Failed','The request failed to submit, please try again.','error','','alertBox' + formType);
				$('body').css('cursor', 'default');
			}
		});
	}
}
/**
* @ desc This will close the dialog box
*/
function autoCloseDialog(dialogFormType){

	$( "#" + dialogFormType ).dialog('close');
}

/**
* @ 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 + 'previously-enjoyed/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');
                }
            });
        }
    }

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.franchiseUrl + 'used-cars/' + item.id + '/' + vehicleTitle.toLowerCase().replace( ' ', '-' ) + '" title="' + vehicleTitle + '"><img src="' + netdirector.baseUrl + '/upload/images/stock/small/' + item.imageSrc + '" alt="' + vehicleTitle + '" onerror="this.src=' + netdirector.baseUrl + '\'local/images/image_not_available_listing.jpg\'" style="width:61px; height:46px;" /></a><div class="frame"><img src="' + netdirector.baseUrl + '/local/images/frame61x46.png" alt=""></div>';
					$('#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');
		}
	});
}

function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
    thisfield.value = "";
    }
}

function clickrecall(thisfield, defaulttext) {
if (thisfield.value == "") {
    thisfield.value = defaulttext;
    }
}

