$(document).ready(function() {

	// Set-up Lightbox ready for action
	$('a.lightBoxImageLinks').lightBox();

	// Create tabs and start them working
    $("#tabUsedVehicleInfo").tabs();
	$('#tabFinanceInsuranceOptions').tabs();

	// Choose to animate the tabs
	$("#tabUsedVehicleInfo").tabs({ fx: { opacity: 'toggle', duration: 'fast' } });

	$('#testdrive_preferred_date, #testdrive_replacement_date').datepicker({
		showAnim : 'fadeIn',
		dateFormat : 'dd/mm/yy',
		minDate : new Date()
	});

	/**
	* @ desc This is the pop up dialog box for Enquiry Form
	*/
	$("#dialogOffersEnquiry").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitForm('Enquiry');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});


	/**
	* @ desc This is the pop up dialog box for Test Drive Form
	*/
	$("#dialogOffersFinance").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitForm('Finance');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});


	/**
	* @ desc This is the pop up dialog box for Share With Friend
	*/
	$("#dialogUsedVehicleShareWithFriend").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitForm('ShareWithFriend');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});


	/**
	* @ desc This is the pop up dialog box for Value My Vehicle
	*/
	$("#dialogUsedVehicleValueMyVehicle").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitForm('ValueMyVehicle');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

    /**
	* @ desc This is the pop up dialog box for Newsletter Form
	*/
	$("#dialogOffersNewsletter").dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		resizable: false,
		draggable: true,
		buttons: {
			'Submit': function() {
				submitForm('Newsletter');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});
	
	
	// Add more friends.
	$('#formUsedVehicleShareWithFriend fieldset').after('<a href="#">Add another friend</a>').next().click(function () {
		addMoreFriends();
		return false;
	});

	// 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');

    $('#sliderThumbs').cycle({
        fx:'scrollHorz',
        next: '#usedVehicleDetails .thumbRight',
        prev: '#usedVehicleDetails .thumbLeft',
        timeout: 0,
        manualTrump: false
    });

	//$('#btnPrint').click(function(){ window.open(this.href); itEvent("print"); return false; })

});


/**
* @ 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':
			dialogName   = 'dialogOffersEnquiry';
			formName     = 'formOffersEnquiry';
			alertBoxName = 'alertBoxEnquiry';
		break;

		case 'finance':
			dialogName   = 'dialogOffersFinance';
			formName     = 'formOffersFinance';
			alertBoxName = 'alertBoxFinance';
		break;

		case 'sharewithfriend':
			dialogName   = 'dialogUsedVehicleShareWithFriend';
			formName     = 'formUsedVehicleShareWithFriend';
			alertBoxName = 'alertBoxShareWithFriend';
		break;

        case 'newsletter':
            dialogName   = 'dialogOffersNewsletter';
            formName     = 'formOffersNewsletter';
            alertBoxName = 'alertBoxNewsletter';
        break;

        case 'valuemyvehicle':
			dialogName   = 'dialogUsedVehicleValueMyVehicle';
			formName     = 'formUsedVehicleValueMyVehicle';
			alertBoxName = 'alertBoxValueMyVehicle';

			collectAllMakes('#valuemyvehicle_my_make_id', 0);
		break;
	}

	if( dialogName != '' ){

		// Clear the form values
		clearFormElements('#' + formName);

		// Removes validation messages
		var validator = $('#' + formName).validate();
		validator.resetForm();

		// Clear Alert Box Text
		resetTips( alertBoxName, true );

		// 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 lowerFormType = formType.toLowerCase();
        
		// Check if form is valid before proceeding
		if( $( "#formOffers" + formType ).valid() && !$( "#formOffers" + formType ).data('disable') ){
			
			var params = $( '#formOffers' + formType ).serialize();
			
			formStatus(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 = '';

			if( formType == 'ValueMyVehicle' ){

				var formData = 'my_make=' + $('#valuemyvehicle_my_make_id > option:selected').text() + '&my_model=' + $('#valuemyvehicle_my_model_id > option:selected').text() + '&';
			}

            formData += 'my_title=' + $('#'+lowerFormType+'_title > option:selected').text() + '&my_branch_of_service=' + $('#'+lowerFormType+'_branch_of_service > option:selected').text() + '&how_did_you_hear_about_us=' + $('#'+lowerFormType+'_how_heard > option:selected').text() + '&';

            $.ajax({
				url: '/frontend-operations/submit-form/',
				dataType: 'json',
				data: formData + params,
				success: function(data){
					
					if( data.status == true ){
						itForm(data.intellitracker);
						// Submitted ok.
						if( formType == 'ShareWithFriend' ){
							updateTips('Email sent','Your friend should recieve the email shortly.','highlight','','alertBox' + formType);
						}else if( formType == 'Newsletter'){
							updateTips('Email address received','Thank you for your signing up for our newsletter.','highlight','','alertBox' + formType);
						}else{
                            updateTips('Enquiry sent','Thank you for your enquiry. We will respond as soon as possible','highlight','','alertBox' + formType);
                        }
						
						clearFormElements("#formOffers" + formType);
						
						//Google analytics tracking
						var _gaq = _gaq || [];
						_gaq.push(['_trackPageview', '/submit-form/' + encodeURIComponent( formType ) ]);
						
						setTimeout(function () {
							formStatus(formType, false);
							autoCloseDialog('dialogOffers' + formType);
						}, 4000);
						
					}else{
						
						displayFormCaptchaImage( '#formUsedVehicle' + 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);
						}
						
						formStatus(formType, false);
					}
				},
				error: function( objRequest ){
					updateTips('Request Failed','The submission request failed, please try again.','error','','alertBox' + formType);
					formStatus(formType, false);
				}
			});
		}
	}
}



function formStatus(formType, disable) {
	
	var id = '#formOffers' + 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 will share this page URL on facebook
*/
function shareOnFacebook(){

	var url = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(document.location)
	window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
}


/**
* @ desc This is a generic ajax request function
*/
function ndCollector( target, params, successFunction, errorFunction ){

	$.ajax({
		url: target,
		dataType: 'json',
		data: params,
		success: successFunction,
		error: errorFunction
	});
}



