function toggleAdvancedSearch( el ){

    $( el ).animate({opacity: 'toggle', height: 'toggle'}, function() { updateAdvancedFlag() });   
}



function updateAdvancedFlag ()  {
    if ( $('#moreSearchOptions').is(':hidden') ) {
        $('#is_advanced_search').val(0);
    } else {
        $('#is_advanced_search').val(1);
    }
}


var leasingVehicleSearchLoaded = false;

$(document).ready(function() {



	// Create tabs and start them working
	$("#tabSaveCompare").tabs();

    collectCAPLeasingVehicleMarqueLists('car');

    //show the option buttons
    $('.searchType').fadeIn('slow');    

	//$(".datepicker").datepicker();

    // populate the title
    $('.prePopulateTitleList').each( function (item){
        // remove items
        $(this).removeOption(/./);

        // add titles
        $(this).addOption('', 'Please Select');
        $(this).addOption('mr', 'Mr');
        $(this).addOption('mrs', 'Mrs');
        $(this).addOption('miss', 'Miss');
        $(this).addOption('ms', 'Ms');
        $(this).addOption('dr', 'Dr');
        $(this).addOption('prof', 'Prof');
    });
    
	// Stock updates.
	if (!netdirector.franchiseUrl.length)
	{
		$('#stockupdate_marqueList option').bind
		(
			'click', 
			function ()
			{
				checkSelectedStockMarques();
			}
		);
	}
	
	setTimeout
	(
		function ()
		{
			var checked = document.getElementsByName('signup_to_mailing_list');
			for (i = 0; i < checked.length; i++)
			{
			    checked[i].checked = true;
			}
		},
		10
	);
});

function checkSelectedStockMarques()
{
	$('#stockupdate_marqueList option').each
	(
		function ()
		{
			var ele = $('#marque' + $(this).attr('value'));
			
			if ($(this).is('option:selected'))
			{
				ele.slideDown(400);
			}
			
			else
			{
				ele.slideUp(400);
			}
		}
	);
};


/**
* @ desc This will close the dialog box
*/
function autoCloseDialog(dialogFormType){

	$( "#" + dialogFormType ).dialog('close');
}


function doPostcodeLookup( prefix ) {
    if ( $('#' + prefix + '_postcode').val() ) {
        $.ajax({
        url: '/frontend-operations/postcode-lookup-custom/',
        dataType: 'json',
        data: "postcode=" + $('#' + prefix + '_postcode').val(),
        success: function(data){
             if ( data.addresses.length > 0 && typeof data.addresses[0].error_number == 'undefined' ) {
                if( data.addresses != null ){
                    $('#' + prefix + '_postcode_results').show();
                    $('#' + prefix + '_postcode_addresses').attr("disabled", "disabled");
                    $('#' + prefix + '_postcode_addresses').removeOption(/./);

                    $.each(data.addresses, function(i,item){

                        $('#' + prefix + '_postcode_addresses').addOption(item.id, item.description);

                    });

                    $('#' + prefix + '_postcode_addresses').removeAttr('disabled').attr( "selectedIndex", 0);
                }
             } else {
                alert("Please enter a valid postcode, or manually supply your address.");
             }

            },
        error: function(objRequest){

        }
        });
    }
}


function selectPostcode( prefix ) {
    if ( $('#' + prefix + '_postcode_addresses').val() ) {
        $.ajax({
        url: '/frontend-operations/postcode-address-custom/',
        dataType: 'json',
        data: "address=" + $('#' + prefix + '_postcode_addresses').val(),
        success: function(data){
                if( data.address[0] != null ){
                    $('#' + prefix + '_postcode_results').hide();
                    $('#' + prefix +'_addressline1').val(data.address[0].line1);

                    if ( typeof data.address[0].line2 != 'undefined' ) {
                        $('#' + prefix +'_addressline2').val(data.address[0].line2);
                    } else {
                        $('#' + prefix +'_addressline2').val("");
                    }

                    if ( typeof data.address[0].line3 != 'undefined' ) {
                        $('#' + prefix +'_addressline2').val( $('#' + prefix +'_addressline2').val() + ", " + data.address[0].line3);
                    }

                    $('#' + prefix +'_town').val(data.address[0].post_town);

                    if ( typeof data.address[0].county != 'undefined' ) {

                        if ( $('#' + prefix +'_county').length > 0 ) {
                            $('#' + prefix +'_county').val(data.address[0].county);
                        } else {
                            $('#' + prefix +'_town').val($('#' + prefix +'_town').val() + ", " + data.address[0].county);
                        }

                    }

                    $('#' + prefix +'_postcode').val(data.address[0].postcode);

                }
            },
        error: function(objRequest){

        }
        });
    }
}



/**
* @ desc This will collect Available Models
*/
function collectAvailableLeasingModels(selectedId){

	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');
                
            

			},
		error: function(objRequest){

			modelId.removeAttr('disabled');
		}
	});
}


/**
* @ 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);
                    
                    if ( typeof defaultMarque != 'undefined' ) {
                        $('#auto_leasing_marque_detail_id').val(defaultMarque);
                    }
				},
			error: function(objRequest){

				$('#auto_leasing_marque_detail_id').removeAttr('disabled').removeOption(/./).addOption('', '-  Select Make  -');
			}
		});
	}
}

function collectCAPQuoteVariants(){


	var marqueId = $('#financeenquiry_marque').val();
	var modelId = $('#financeenquiry_model').val();
	var classId = $('#financeenquiry_class');

    classId.attr('disabled', 'disabled');

    $.ajax({
        url: '/frontend-operations/cap-leasing-vehicle-variant-list/',
        dataType: 'json',
        data: 'model_id=' + modelId,
        success: function(data){

                // Remove all options
                classId.removeOption(/./);
                
                // Add Options
                $.each(data.variants, function(i,item){

                    classId.addOption(item.capVariantId, item.variantName);
                });

                // If previously selected..
               
                    // select 1st one if only one available
                    var preSelect = ( data.length == 1 ) ? 1: 0;
                    classId.attr( "selectedIndex", preSelect);
                
                classId.removeAttr('disabled');

            },
        error: function(objRequest){

            classId.removeAttr('disabled');
        }
    });
}

function collectCAPLeasingVariants(){

    
    if($('#searchVans').attr('checked')) {
        quote = 'lcv';
    } else {
        quote = 'car';
    }


	var marqueId = $('#auto_leasing_marque_detail_id').val();

	var modelId = $('#auto_leasing_model_detail_id').val();

	var classId = $('#auto_leasing_class_detail_id');


    classId.attr('disabled', 'disabled');

    $.ajax({
        url: '/frontend-operations/cap-leasing-vehicle-variant-list/',
        dataType: 'json',
        data: 'model_id=' + modelId + '&quote=' + quote,
        success: function(data){

                // Remove all options
                classId.removeOption(/./);

                // Add Options
                $.each(data.variants, function(i,item){

                    classId.addOption(item.capVariantId, item.variantName);
                });

                // If previously selected..

                    // select 1st one if only one available
                    var preSelect = ( data.length == 1 ) ? 1: 0;
                    classId.attr( "selectedIndex", preSelect);

                classId.removeAttr('disabled');

            },
        error: function(objRequest){

            classId.removeAttr('disabled');
        }
    });
}

function collectCAPLeasingModels(selectedId, quote){

	quote = typeof quote === 'undefined' ? false : true;
	
	if (quote)
	{
		var marqueId = $('#financeenquiry_marque').val();
		var modelId = $('#financeenquiry_model');
	}
	
	else
	{
		var marqueId = $("#auto_leasing_marque_detail_id").val();
    	var modelId  = $("#auto_leasing_model_detail_id");
	}
	

    modelId.attr('disabled', 'disabled');

    $.ajax({
        url: '/frontend-operations/cap-leasing-vehicle-model-list/',
        dataType: 'json',
        data: 'marque_id=' + marqueId,
        success: function(data){

                // Remove all options
                modelId.removeOption(/./);
                
                // Add Options
                $.each(data.models, function(i,item){

                    modelId.addOption(item.capModelId, item.modelName);
                });

                // If previously selected..
                if( selectedId != null && selectedId > 0){

                    modelId.val(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');
        }
    });
}

/**
* @ desc This will collect New Vehicle Marque Lists
*/
function collectCAPLeasingVehicleMarqueLists( quote ){

    if (typeof quote === 'undefined'){
        quote = 'car';
    }


    // Only load lists once
    //if( leasingVehicleSearchLoaded != true ){

        // Remove all options and disable
        $('#auto_leasing_marque_detail_id').attr('disabled', 'disabled');

        $.ajax({
            url: '/frontend-operations/cap-leasing-vehicle-marque-list/',
            dataType: 'json',
            data: 'type=' + quote,
            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.makes != null ){
                        $.each(data.makes, function(i,item){
                            $("#auto_leasing_marque_detail_id, #financeenquiry_marque").addOption(item.capMakeId, item.makeName);
                        });
                    }
                    
                    $('#auto_leasing_marque_detail_id, #financeenquiry_marque').removeAttr('disabled').attr( "selectedIndex", 0);
                    
                    if ( typeof defaultMarque != 'undefined' ) {
                        $('#auto_leasing_marque_detail_id').val(defaultMarque);
                        if ( typeof defaultModel != 'undefined' ) {
                            collectCAPLeasingModels(defaultModel);
                        } else {
                            collectCAPLeasingModels();
                        }
                    }
					
					if (typeof financeenquiry_marque !== 'undefined')
					{
						$('#financeenquiry_marque option').each
						(
							function ()
							{
								if ($(this).html().toString().toLowerCase() === financeenquiry_marque.toLowerCase())
								{
									$(this).attr('selected', true);
								}
							}
						);
					}
					
                },
            error: function(objRequest){

                $('#auto_leasing_marque_detail_id, #financeenquiry_marque').removeAttr('disabled').removeOption(/./).addOption('', '-  Select Make  -');
            }
        });
    //}
}

/**
* @ 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 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);
				}else{

					// Show generic message
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
				}
				$('body').css('cursor', 'default');
			},
		error: function( objRequest ){
				updateTips('Request Failed','The request failed to submit, please try again.','error','','alertBox' + formType);
				$('body').css('cursor', 'default');
			}
		});
	}
}

/**
* @ desc This will setup form
*/
function setupCustomForm(formType){

	// Clear the form values
	clearFormElements('#form' + formType);

	// Removes validation messages
	var validator = $('#form' + formType).validate();
	validator.resetForm();

	// Clear Alert Box Text
	$('#alertBox' + formType).html('');

	// highlight first input
	//$('#form' + formType + ' :input:text:first').focus();
}

/**
* @ 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 updates the dialog alert box, passes in a header, text, type of msg, and optional input to highlight
*/
function updateTips(header,text,msgType,highlightInput,alertBoxId) {

	// Clear Alert Box Text
	resetTips(alertBoxId);
	var alertBox = ( alertBoxId != null && alertBoxId != '' ) ? $('#'+alertBoxId) : $('#dialogAlertBox');

	txt = '<strong>'+header+':</strong> '+ text;
	switch( msgType ){
		case 'error':
			msg = "<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin: 0px 5px;\"></span>"+txt+"</p>";
			alertBox.addClass('ui-state-error').html(msg);
		break;

		case 'highlight':
			msg = "<p><span class=\"ui-icon ui-icon-info\" style=\"float: left; margin: 0px 5px;\"></span>"+txt+"</p>";
			alertBox.addClass('ui-state-highlight').html(msg);
		break;

		default:
			console.log('Error: No valid message type set');
		break;
	}

	if( highlightInput != '' ){
		$('#'+highlightInput).addClass('ui-state-error');
	}
}


/**
* @ desc This Resets the dialog alert box
*/
function resetTips(alertBoxId){

	alertBox = ( alertBoxId != null && alertBoxId != '' ) ? $('#'+alertBoxId) : $('#dialogAlertBox');
	alertBox.removeClass('ui-state-error ui-state-highlight').html('');
}

