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

	if( 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 ) ]);

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

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


	if( netdirector.usedStockListing &&
		netdirector.usedStockListing.autoCarDetailIdList ){

		var autoCarDetailIdList = netdirector.usedStockListing.autoCarDetailIdList;

		var examples = $('.codeWeaversExample');

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

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

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

		function updateFinanceQuotes( params, callback ){

			examples = $();

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

            if (autoCarDetailIdList.length == 0) {

                return;

            }

			params = params || [];

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

			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").append( 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();
	}
})

