$(document).ready(function() {

    /**
	* @ desc This is the pop up dialog box for Contact us
	*/
	$('#dialogContact').dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitCustomLayoutForm('Contact');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});


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



/**
* @ desc This will opend the dialog and show the correct form
*/
function showCustomLayoutForm( formType ){

	var dialogName = '';
	var formName   = '';

	// Using switch will stop JS errors from passing incorrect dialog names
	switch( formType ){

        case 'contactus':
			dialogName   = 'dialogContact';
			formName     = 'formContact';
			alertBoxName = 'alertBoxContact';
		break;

	}

	if( dialogName != '' ){

		// Clear the form values
		clearFormElements('#' + formName);

		// Removes validation messages
		var validatorCustom = $('#' + formName).validate();
		validatorCustom.resetForm();

		// Clear Alert Box Text
		resetTips( alertBoxName, true );

		// Open the dialog box
		$('#' + 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 submitCustomLayoutForm( formType, isUsingDialogBox ){

	if( formType != '' ){

		// Check if form is valid before proceeding
		if( $( "#form" + formType ).valid() && !$( "#form" + formType ).data('disable') ){

			var params = $( '#form' + formType ).serialize();

			formCustomLayoutStatus(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 = '';

			$.ajax({
				url: '/frontend-operations/submit-form/',
				dataType: 'json',
				data: formData + params,
				success: function(data) {

					// Enable submit button and default cursor.
					$( '#form' + formType + ' input, #form' + formType + ' textarea, #form' + formType + ' select').removeAttr('disabled');
					$( '#form' + formType ).data('disable', false);
					$('body').css('cursor', 'default');

					if( data.status == true ){
                        if ( typeof itForm == 'function' ) {
						    itForm(data.intellitracker);
                        }

						if( isUsingDialogBox == true ){
							// Submitted ok.

								updateTips('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','','alertBox' + formType);


							clearFormElements("#form" + formType);

						}else{
							updateTips('Thank You','Your details have been submitted successfully','highlight','','alertBox' + formType);
						}

						//Google analytics tracking
						window._gaq = window._gaq || [];
						window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);

						setTimeout(function(){
							autoCloseDialog('dialog' + formType);
							formCustomLayoutStatus(formType, false);
						}, 4000);

					}else{

						displayFormCaptchaImage( '#form' + formType );

						if( data.error != null ){
							updateTips('Request Failed',data.error,'error','','alertBox' + formType);
						}else{
							updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
						}

						formCustomLayoutStatus(formType, false);
					}
				},
				error: function( objRequest ){
					formCustomLayoutStatus(formType, false);
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
				}
			});
		}
	}
}


function formCustomLayoutStatus(formType, disable) {

	var id = '#form' + 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);
	}
}


