$(document).ready(function() {
    

    
    //name forms, dialogs and alerts in a way they can be easily referenced
    //ie for used car enquiries we use 'usedEnquiry' and use it to reference the form, dialog and alert.
    //ie formName = formUsedEnquiry, dialogUsedEnquiry, alertUsedEnquiry
    //we can then use form+formName, dialog+dialogName, alert+UsedEnquiry
    
    /**
	*calls createDialog 
	*params = form/dialog name,autoOpen,width,modal,resizable,draggable,collectMakeModelData
	*/
	//createDialog('ValueMyVehicle',false,600,true,false,true,true);
   // createDialog('SignUp',false,600,true,false,true,true);
    createDialog('BookAService',false,600,true,false,true,true);

    
    
    // For unique styling of dialog buttons
	$('.ui-dialog-buttonpane button').each( function () {
		var html = $(this).html();
		$(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'); 
});


/***********************************************************************************************************************************
 * 
 * test stuff
 */
/**
	*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() {
				submitForm(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 showForm( formNameIn ){
	
	//check if name is not null
		if (formNameIn) { 

			var dialogName = 'dialog'+formNameIn;
			var formName   = 'form'+formNameIn;
			var alertName  = 'alert'+formNameIn;
            
			// 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 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');
	}
}


/**
*Attempts to submit the form via ajax
*/
function submitForm ( formNameIn ) {

		var dialogName = 'dialog'+formNameIn;
		var formName   = 'form'+formNameIn;
		var alertName  = 'alert'+formNameIn;

	if( formName != '' ){
	

		// Check if form is valid before proceeding
		if( $( "#" + formName ).valid() ){
		
			$('body').css('cursor', 'progress');
			
			$.ajax({
			  url: '/frontend-operations/submit-form/',
			  dataType: 'json',
			  data: $( '#'+ formName ).serialize(),
				success: function(data){
					if( data.status ){
						itForm(data.intellitracker);
						// Submitted ok.
							updateTips('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','',alertName);
					
					
						clearFormElements("#" + formName);

                        if (dialogName == "dialogSignUp") {
                        setTimeout('$("#dialogSignUp").dialog("close")' ,6000);
                        }
                        else {
                        setTimeout($( "#" +dialogName).dialog("close") ,6000);
                        }
						
					
					}else{
						
						displayFormCaptchaImage( '#' + formName );
						
						if( data.error != null ){
						
							updateTips('Request Failed',data.error,'error','',alertName);

						}else{
							// Show generic message
							updateTips('Request Failed','The request to submit failed, please try again.','error','',alertName);
						}
					}	
							},
				error: function( objRequest ){
					updateTips('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');
}





