/**
* @ desc This will send the selected form via ajax.
*/
function submitForm( formType ){

	if( formType != '' ){
		var $form = $( "#formUsedVehicle" + formType );

		// Check if form is valid before proceeding
		if( $( "#formUsedVehicle" + formType ).valid() && !$( "#formUsedVehicle" + formType ).data('disable') ){

			var params = $( '#formUsedVehicle' + formType ).serialize();

			formStatus(formType, true);
			updateTips('<img src="/local/images/loading.gif" width="15" style="position:relative; display:inline; top:4px; margin:0 5px" />Submiting Form', '', 'highlight', '', 'alertBox' + formType);

			var formData = '';

			if( formType == 'ValueMyVehicle' ){

				var formData = 'my_make=' + $('#valuemyvehicle_my_make_id > option:selected').text() + '&my_model=' + $('#valuemyvehicle_my_model_id > option:selected').text() + '&';
			}

			$.ajax({
				url: '/frontend-operations/submit-form/',
				dataType: 'json',
				data: formData + params,
				success: function(data){

					if( data.status == true ){

                        if ( typeof itForm == 'function' ) {
						    itForm(data.intellitracker);
                        }
						updateTips('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','','alertBox' + formType);
						clearFormElements("#formUsedVehicle" + formType);

						//Google analytics tracking
						window._gaq = window._gaq || [];
						window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);

						var stockId = $('.auto_car_detail_id', $form).val();
						var crtR = Math.floor(Math.random()*99999999999);
						var criteo = '<img src="https://sslwidget.criteo.com/'+ netdirector.criteo.PoolId +'/display.js?p1='
							+ encodeURIComponent("v=2&wi="+ netdirector.criteo.SalesCampaignId +"&t="+ crtR +"&s=1&i1="+ stockId +"&p1=1&q1=1")
							+'&t1=transaction&resptype=gif" width="1" height="1" />';
						$("body").append(criteo);

						setTimeout(function () {
							autoCloseDialog('dialogUsedVehicle' + formType);
							formStatus(formType, false);
						});

					}else{

						displayFormCaptchaImage( '#formUsedVehicle' + formType );

						if( data.error != null ){

							updateTips('Request Failed',data.error,'error','','alertBox' + formType);

						}else{
							// Show generic message
							updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
						}

						formStatus(formType, false);
					}
				},
				error: function( objRequest ){
					updateTips('Request Failed','The submission request failed, please try again.','error','','alertBox' + formType);
					formStatus(formType, false);
				}
			});
		}
	}
}


function formStatus(formType, disable) {

	var id = '#formUsedVehicle' + 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 open the dialog and show the correct form
 */
function showForm(formType, id, locDetId, isBike, isVan, title, customInt) {

    var dialogName = '';
    var formName = '';

    // Using switch will stop JS errors from passing incorrect dialog names
    switch (formType) {

        case 'enquiry':
            dialogName = 'dialogUsedVehicleEnquiry';
            formName = 'formUsedVehicleEnquiry';
            alertBoxName = 'alertBoxEnquiry';
            break;

    }

    if (dialogName != '') {

        // Clear the form values
        clearFormElements('#' + formName);
        // Removes validation messages
        var validator = $('#' + formName).validate();
        validator.resetForm();

        // Clear Alert Box Text
        resetTips(alertBoxName);

        // Open the dialog box
        $('#' + dialogName).dialog("option", "position", 'center');
        $('#' + dialogName).dialog("option", "title", 'Make an Enquiry: '+title);
        $('#' + dialogName).dialog('open');

        $('#' + dialogName + ' .auto_car_detail_id').val(id);
        $('#' + dialogName + ' .location_detail_id').val(locDetId);
        $('#' + dialogName + ' .is_bike').val(isBike);
        $('#' + dialogName + ' .is_van').val(isVan);

        if(customInt){
            $('#formUsedVehicleEnquiry').prepend("<input type=\"hidden\" name=\"great_smc_sale\" value=\"true\" class=\"greatSmcSale\" />")
        }
        else if($(".greatSmcSale").length) {
            $(".greatSmcSale").remove();
        }
     

        //$('#' + dialogName + ' input[name=signup_to_mailing_list]').attr('checked', true);

        displayFormCaptchaImage('#' + formName);
        //alert(id);
    }
}

/**
 * Finance Quoting via Codeweavers or Webzation usually
 */
$( function(){

    /**
     * @ desc This is the pop up dialog box for Reservation
     */
    $("#dialogUsedVehicleEnquiry").dialog({
        autoOpen: false,
        width: 600,
        modal: true,
        resizable: false,
        draggable: true,
        buttons: {
            'Submit': function() {
                submitForm('Enquiry');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        },
        close: function() {
        }
    });


    if( $("#adjustFinance").length &&
		netdirector.usedStockListing &&
		netdirector.usedStockListing.autoCarDetailIdList ){

		var autoCarDetailIdList = netdirector.usedStockListing.autoCarDetailIdList;

		var examples = $();

		$("#financeQuotesForm").submit( function(){

			examples.slideUp( function(){ $(this).remove() } )

			updateFinanceQuotes( $(this).serializeArray() );
			return false;
		});

		function updateFinanceQuotes( params, callback ){

			examples = $();

			$("#financeQuotesForm :input").attr("disabled", true)

			params = params || [];

			params.push({
				name: "autoCarDetailId",
				value: autoCarDetailIdList.join(",")
			})

			params.push({
				name: "usedStockBaseUrl",
				value: netdirector.baseUrl + "/" + netdirector.areaUrl + "/search/"
			})

			callback = callback || $.noop;

			$.getJSON(
				netdirector.baseUrl + "/" + netdirector.franchiseUrl + "finance-quotes/used-multiple-quote/",
				params,

				function( data ){

					$("#financeQuotesForm :input").attr("disabled", false);

					callback.apply( this, arguments );

					var example = $(data.representativeExample).hide();

					$("#adjustFinance").after( example );

					examples = examples.add( example );

					$.each( autoCarDetailIdList, function(k, id){

						if( data.html[id] ){

							var example = $( data.html[id] ).hide();

							examples = examples.add( example );

							$("#list .listItem-" + id ).append( example );
						}

					});

					examples.slideDown();
				}
			);
		}

		updateFinanceQuotes();
	}
})




