$(document).ready(function() {
    
    
    createDialog('ValueMyVehicle',false,600,true,false,true,true);
    createDialog('TestDrive',false,600,true,false,true,false);
    
    // For unique styling of dialog buttons

	$('.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');
    
    $('#testdrive_preferred_date, #testdrive_replacement_date').datepicker({
		showAnim : 'fadeIn',
		dateFormat : 'dd/mm/yy',
		minDate : new Date()
	});

});


/*Create the dialog form the form details
	*sets the options
	*/
	
	function createDialog(dialogFormName,autoOpenIn,widthIn,modalIn,resizableIn,draggableIn,collectMakeModelData)
	{
        //adds #dialog to the form name ie #dialogContactUs
		$("#dialog"+dialogFormName).dialog({
        //options 
		autoOpen: autoOpenIn,
		width: widthIn,
		modal: modalIn,
		resizable: resizableIn,
		draggable: draggableIn,
  
            buttons: {
			'Submit': function() {
				submitFormSpecial(dialogFormName)
			},
			Cancel: function() {
				$(this).dialog('close');
			}
            
            
         
        },
		close: function() {
		}
		});
        //if we need amke/model inputs prepopulated
        if(collectMakeModelData) {
            collectAllMakes('#'+dialogFormName+'_my_make', 0);
        }
        
    }   

/**
* pass in the formName
* this is called using showForm(formName);
*/
function showFormSpecial( formNameIn ){
	
	//check if name is not null
		if (formNameIn) { 

			var dialogName = 'dialog'+formNameIn;
			var formName   = 'form'+formNameIn;
			var alertName  = 'alert'+formNameIn;
            
            $('#'+formName).css('height','auto');
            
			// Clear the form values
				clearFormElements('#' + formName); 

				var validator = $('#' + formName).validate();
				validator.resetForm();
				
			// Clear Alert Box Text
				resetTips( alertName );
				
			// Open the dialog box
				$('#' + dialogName ).dialog( "option", "position", 'center' );
				$('#' + dialogName ).dialog('open');
				
			// highlight first input
				$('#' + dialogName + ' :input:text:first').focus();
				
				displayFormCaptchaImage( '#' + formName );	
            
		} 
		else {
			// there is no formName so error - could prob do with email being sent to client/us informing of the error
			alert('Error Loading Form')
		
		}
}


/**
* @ desc This updates the dialog alert box, passes in a header, text, type of msg, and optional input to highlight
*/
function updateTipSpecial(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');
	}
}
/**
*Attempts to submit the form via ajax
*/
function submitFormSpecial ( formNameIn ) {

		var dialogName = 'dialog'+formNameIn;
		var formName   = 'form'+formNameIn;
		var alertName  = 'alert'+formNameIn;

    
	    
    if( formName != '' ){
        
            //console.log(formNameIn);
            var formData = 'Make=' + $('#'+formNameIn+'_my_make > option:selected').text() + '&Model=' + $('#'+formNameIn+'_my_model > option:selected').text() + '&';
        
	

		// Check if form is valid before proceeding
		if( $( "#" + formName ).valid() ){
			var params = $( '#' + formName ).serialize();
			formStatusSpecial(formName, true);
			updateTipsSpecial('<img src="/local/images/loading.gif" width="15" style="position:relative; display:inline; top:4px; margin:0 5px" />Submiting Form', '', 'highlight', '', alertName);
			
			$.ajax({
			  url: '/frontend-operations/submit-form/',
			  dataType: 'json',
			  data: formData + params,
				success: function(data){
					if( data.status ){
						itForm(data.intellitracker);
						// Submitted ok.
							updateTipsSpecial('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','',alertName);
					
					
						clearFormElements("#" + formName);

                       
						setTimeout(function () {
						formStatusSpecial(formName, false);
						autoCloseDialogSpecial(dialogName);
                    
					}, 4000);
					
					}else{
						
						displayFormCaptchaImage( '#' + formName );
						formStatusSpecial(formName, false);
						if( data.error != null ){
						
							updateTipsSpecial('Request Failed',data.error,'error','',alertName);

						}else{
							// Show generic message
							updateTipsSpecial('Request Failed','The request to submit failed, please try again.','error','',alertName);
						}
					}	
							},
				error: function( objRequest ){
					updateTipsSpecial('Request Failed','The submission request failed, please try again.','error','',alertName);
				}
			});
			
			$('body').css('cursor', 'default'); 
		}
	
	
	}
}

/**
* @ desc This will close the dialog box
*/
function autoCloseDialog(dialogFormType){

	$( "#" + dialogFormType ).dialog('close');
}




function formStatusSpecial(formType, disable) {

	var id = '#' + 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 updates the dialog alert box, passes in a header, text, type of msg, and optional input to highlight
*/
function updateTipsSpecial(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>" + txt + "</p>";
			alertBox.addClass('ui-state-error').html(msg);
		break;

		case 'highlight':
			msg = "<p>" + 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');
	}

	alertBox.slideDown(200);
}

/**
* @ desc This will close the dialog box
*/
function autoCloseDialogSpecial(dialogFormType){

	$( "#" + dialogFormType ).dialog('close');
}

