$(document).ready(function() {
    
   /* 
    *//**
 }
	* @ desc This is the pop up dialog box for Enquiry Form
	*//*
	$("#dialogformUsedVehicleValueMyVehicle").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitCustomForm('formUsedVehicleValueMyVehicle');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});
	
	
	*//**
	* @ desc This is the pop up dialog box for Test Drive Form
	*//*
	$("#dialogformBookAService").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitCustomForm('formBookAService');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});


	*//**
	* @ desc This is the pop up dialog box for Test Drive Form
	*//*
	$("#dialogformSignUp").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitCustomForm('formSignUp');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: 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);
    createDialog('CustomerComments',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":{
              text:'Submit',
              className:'btnSubmit',
              click:function(){submitForm(dialogFormName);}
            },
            "cancel":{
              text:'Cancel',
              className:'btnCancel',
              click: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() ){
			var params = $( '#' + formName ).serialize();
			formStatus(formName, true);
			updateTips('<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: params,
				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(function () {
							setTimeout($( "#" +dialogName).dialog("close") ,6000);
							formStatus(formName, false);
						});
                        
                        }
						
					
					}else{
						
						displayFormCaptchaImage( '#' + formName );
						ormStatus(formName, false);
						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');
}




function formStatus(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);
	}
}
