$(document).ready(function() {

	/**
	* @ desc This is the pop up dialog box for Enquiry Form
	*/
	$("#dialogUsedVehicleEnquiryListing").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitForm('EnquiryListing');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});


});


/**
* @ desc This will open the dialog and show the correct form
*/
function showForm( formType ){
	
	var dialogName = '';
	var formName   = '';
	
	// Using switch will stop JS errors from passing incorrect dialog names
	switch( formType ){
		case 'enquiry-listing':
			dialogName   = 'dialogUsedVehicleEnquiryListing';
			formName     = 'formUsedVehicleEnquiryListing';
			alertBoxName = 'alertBoxEnquiryListing';
		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('open');
		// highlight first input
		$('#' + dialogName + ' :input:text:first').focus();
		
		//displayFormCaptchaImage( '#' + formName );
	}
}


/**
* @ desc This will save the selected areas for this franchise via Ajax
*/
function submitForm( formType ){

	if( formType != '' ){
		var $form = $( "#formUsedVehicle" + formType );

		// Check if form is valid before proceeding
		if( $( "#formUsedVehicle" + formType ).valid() ){

			// Disable the dialog buttons
			var dialogSelector = '#dialogUsedVehicle'+ formType;
			$(dialogSelector).parent().find('button').attr('disabled', 'disabled');

			$('body').css('cursor', 'progress');
			dataTypeReturn='json';
			var useIframe=false;
			if("#formUsedVehicle" + formType=="#formUsedVehicleValueMyVehicle"){
				dataTypeReturn='html';
				useIframe=true;
			}
			$("#formUsedVehicle" + formType ).ajaxSubmit({
			  url: '/frontend-operations/submit-form/',
			  dataType: dataTypeReturn,
			  iframe:useIframe,
			  success: function(data){
					valid=false;
					
					if( dataTypeReturn == 'html'){
						valid=true;
					}else{
						if( data.status == true ){
							valid=true;
						}
					}
					if(valid==true){
						itForm(data.intellitracker);
						// Submitted ok.
						if( formType == 'ShareWithFriend' ){
							updateTips('Email sent','Your friend should recieve the email shortly.','highlight','','alertBox' + formType);
						}else{
							updateTips('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','','alertBox' + formType);
						}

						//Google analytics tracking
						window._gaq = window._gaq || [];
						window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);

						var stockId = $('.criteo_vehicle_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);

						clearFormElements("#formUsedVehicle" + formType);
						setTimeout( "autoCloseDialog('dialogUsedVehicle" + formType + "');",4000);

					}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);
						}
					}
					$(dialogSelector).parent().find('button').attr('disabled', '');
				},
			error: function( objRequest ){
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
					$(dialogSelector).parent().find('button').attr('disabled', '');
				}
			});
			$('body').css('cursor', 'default'); 
		}
	}
}

