/*
 * captcha			disable captcha will also remove sc fields from the form so they are not submitted
 * inline			toggles weather the form is inside a popup dialog or if its on the page
 * message			selector for message area defalt should be fine while we keep forms how they are
 * messageHide		delay before hiding the message
 * url				where we want to send the forms data deaults is correct in most cases except wishlist currently
 * 
*/


//setup an array with form data not best solution but maintains compatibility with current forms layout, but would be less code if we used selectors
//some of these may be wrong in particular the recruitment and custom forms have not been tested or may vary
//using this array also means that we can have different enquirys forms for the same button for example if we have a jump we can use the new-cars enquiry when the jump is clicked on a new-cars page
//and fall back to a standard one if we are not, or we can hard code an area when calling showform

//used-stock
var formList=Array();
formList[2]=Array();
formList[2]['requestbrochure']=Array('UsedVehicleRequestBrochure','alertBoxRequestBrochure');
formList[2]['testdrive']=Array('UsedVehicleTestDrive','alertBoxForm');
formList[2]['enquiry']=Array('UsedVehicleEnquiry','alertBoxEnquiry');
formList[2]['sharewithfriend']=Array('UsedVehicleShareWithFriend','alertBoxShareWithFriend');
formList[2]['valuemyvehicle']=Array('UsedVehicleValueMyVehicle','alertBoxValueMyVehicle');

//new-cars
formList[4]=Array();
formList[4]['customEnquiry']=Array('CapNewVehiclesRequestBrochure','alertBoxForm');
formList[4]['requestbrochure']=Array('CapNewVehiclesRequestBrochure','alertBoxForm');
formList[4]['testdrive']=Array('CapNewVehiclesTestDrive','alertBoxForm');
formList[4]['enquiry']=Array('CapNewVehiclesEnquiry','alertBoxForm');
formList[4]['valuemyvehicle']=Array('CapNewVehiclesValueMyVehicle','alertBoxForm');
formList[4]['sharewithfriend']=Array('CapNewVehiclesShareWithFriend','alertBoxForm');


//recruitment Area
formList[6]=Array();
formList[6]['RecruitmentVacancyApply']=Array('RecruitmentVacancyApplication','alertBoxForm');
formList[6]['RecruitmentVacancyApplication']=Array('RecruitmentVacancyApplication','alertBoxForm');



//locations
formList[5]=Array();
formList[5]['customContactUs']=Array('LocationsContactUs','alertBoxLocationsContactUs');
formList[5]['valuemyvehicle']=Array('CapNewVehiclesValueMyVehicle','alertBoxForm');

//standard cms page
formList[1]=Array();
formList[1]['customContactUs']=Array('CustomContactUs','alertBoxForm');
formList[1]['customEnquiry']=Array('CustomContactUs','alertBoxForm');
formList[1]['enquiry']=Array('UsedVehicleEnquiry','alertBoxEnquiry');
formList[1]['customRecruitment']=Array('CustomRecruitment','alertBoxForm');
formList[1]['valuemyvehicle']=Array('CapNewVehiclesValueMyVehicle','alertBoxForm');


//unknown area // any area
formList[0]=Array();
formList[0]['saveFavourites']=Array('SaveFavourites','alertBoxSaveFavourites');
formList[0]['retrieveFavourites']=Array('RetrieveFavourites','alertBoxRetrieveFavourites');
formList[0]['valuemyvehicle']=Array('CapNewVehiclesValueMyVehicle','alertBoxForm');

//servicing matrix
formList[3]=Array();
formList[3]['servicesomethingelse']=Array('GlobalSomethingElse','alertBoxGlobalsomethingelse');



(function(jQuery){
	jQuery.fn.popupForm = function(options){
		var defaults = {
			captcha:false,
			message:'.ui-corner-all',
			messageHide:2000,
			url:'/frontend-operations/submit-form/',
			inline:false       
		};

		var options = jQuery.extend(defaults, options); 
		if(options.captcha==false){
			$('form input[name="sc[id]"]',this).remove();
			$('form input[name="sc[input]"]',this).remove();
		}

		var dialogId=$(this);	
		var formId=$('form:first',this);	
		var formType=formId.attr('id');
		var dialogMessage=$(options.message,this);
		var validator = formId.validate();
		dialogId.data('inline',options.inline);
		
		//create a dialog for the form to popup inside
		if(options.inline==false){
			dialogId.dialog({
				autoOpen: false,
				width: 600,
				modal: true,
				resizable: false,
				buttons: {
					"submit":{
					  text:'Submit',
					  className:'btnSubmit',
					  click:function(){submitForm();}
					},
					"cancel":{
					  text:'Cancel',
					  className:'btnCancel',
					  click:function(){$(this).dialog('close');}
					}
				},
				open: function() {
					clearMsg();
					//dialogMessage.hide();
					$('fieldset:first',dialogId).slideDown();
					//focus first element in form only do this for popup forms else the page will move
					$('form:input:text:first',this).focus();
				},
				close: function() {
					// This is needed as any other captcha image opening will break the one in the quote form
					//displayFormCaptchaImage( '#formCapNewVehiclesQuote' );
				}
			});
		//no dialog this is an inline form so handle the submit event differently
		}else{
			
			formId.submit(function(e){
				e.preventDefault();
				clearMsg();
				submitForm();
				return false;
			});
		}
		
		function submitForm(){			
			//validator.resetForm();
			$('.error',dialogId).removeClass('.error');

			if(dialogId.data('name')=='valuemyvehicle' || dialogId.data('name')=='testdrive' || dialogId.data('name')=='servicesomethingelse'){
				$(dialogId.data('formId')).append('<input type="hidden" name="my_make" value="'+$('#'+dialogId.data('name')+'_my_make_id > option:selected').text()+'" />');
				$(dialogId.data('formId')).append('<input type="hidden" name="my_model" value="'+$('#'+dialogId.data('name')+'_my_model_id > option:selected').text()+'" />');
			}

			$('body').css('cursor', 'progress'); 

			
			if ($('form:first',dialogId).valid()){
				var form=$('form:first',dialogId);
				showMsg('Submitting Form','Please wait while we submit your details.','highlight','');
				if(dialogId.data('inline')==false){
					$('fieldset:first',dialogId).slideUp(1500);
				}
				$.ajax({
				  url: options.url,
				  dataType: 'json',
				  data: form.serialize(),
				  success: function(data){

						if( data.status == true || data==true ){
							if(data.intellitracker){
								itForm(data.intellitracker);
							}
							
							showMsg('Thank You','Your details have been submitted successfully','highlight','');
							setTimeout( "autoCloseDialog('" + dialogId.attr('id') + "');",4000);
							
							//Google analytics tracking
							window._gaq = window._gaq || [];
							window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);

						}else{
							if(options.captcha){
								displayFormCaptchaImage( '#form' + formType );
							}
							if( data.error != null ){
								showMsg('Request Failed',data.error,'error','','');
							}else{
								// Show generic message
								showMsg('Request Failed','The request to submit failed, please try again.','error','');
							}
						}
						clearFormElements(form);
					},
					error: function( objRequest ){
						showMsg('Request Failed','The request failed to submit, please try again.','error','');
						$('fieldset:first',dialogId).slideDown(1000);
					}
				});
				
			}else{

			}
			if(dialogId.data('inline')==true){
				setTimeout(function(){dialogMessage.hide();},2500);
			}
			
			$('body').css('cursor', 'default'); 
		}
		
		//reset submit response message from top of form
		function clearMsg(){
			dialogMessage.removeClass('ui-state-error ui-state-highlight');
			dialogMessage.html('');
		}
		
		//display a message at top of form just before submitting
		function showMsg(header,text,msgType,highlightInput) {
			dialogMessage.show();
			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>";
					dialogMessage.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>";
					dialogMessage.addClass('ui-state-highlight').html(msg);
				break;
				default:
					console.log('Error: No valid message type set');
				break;
			}	

			if( highlightInput != '' ){
				$('#'+highlightInput).addClass('ui-state-error');
			}
			//dialogMessage.delay(options.messageHide).fadeOut('fast');
		}
	}	
})(jQuery);




/**
* @ desc This will open the dialog and show the correct form
*/
function showForm( formType,area ){
	if(area==undefined){
		var area=netdirector.areaType;
	}
	//if we could not find the form lets fall back to global forms
	if(!(formType in formList[area])){
		var area=0;
	}

	var dialogID=$('#dialog' +formList[area][formType][0]);
	dialogID.data('formMsg',formList[area][formType][1]);
	dialogID.data('name',formType);
	dialogID.data('formId','#form' +formList[area][formType][0]);

	

	if($('#valuemyvehicle_my_make_id')){
		collectAllMakes('#valuemyvehicle_my_make_id', 0);
	}

	if($('#testdrive_my_make_id')){
		collectAllMakes('#testdrive_my_make_id', 0);
	}

	if($('#brochure_my_make_id')){
		collectAllMakes('#brochure_my_make_id', 0);
	}
	
	if($('#globalSomethingElse_my_make')){
		collectAllMakes('#globalSomethingElse_my_make', 0);
	}
	
	resetTips( formList[area][formType][1] );
	
	//reset the form, Removes validation messages
	if ($(dialogID.data('formId')).length!=1){
		clearFormElements($(dialogID.data('formId')));
	}

	//check if this was created as a dialog form and open the dialog if needed
	if(!dialogID.data('inline')){
		$(dialogID).dialog( "option", "position", 'center' );
		$(dialogID).dialog('open');
	}
	//displayFormCaptchaImage( '#' + formName );
}




// *****************************************************
// Quickly handle popup form with out using inline code
// *****************************************************

(function(jQuery){
	jQuery.fn.popoutForms = function(options){
		var defaults = {
			enquiry:'#enquire,.enquire,.btnEnquiry,#btnEnquireNow,#btnMakeEnquiry,#btnAskQuestion',
            sendToFriend:'.send,#btnShare,#sendTo',
            brochure:'#btnRequestBrochure,#btnBrochure',
            testDrive:'#btnBookTestDrive,#btnRequestTestDrive,#btnTestDrive',
            print:'.print,#btnPrintDetails',
            valueMyVechile:'.btnValueMyVehicle,.jumpPartExchange,#btnPartEx,#btnValuation,#btnValueMy,#btnValue',
            serviceSomethingElse:'#openSomethingElse'
		};

		var options = jQuery.extend(defaults, options);
		
		$(options.print).click(function(e){
			e.preventDefault();
			window.print();
			return false;
		})

		$(options.enquiry).click(function(e){
			e.preventDefault();
			showForm( 'enquiry' );
			return false;
		})

		$(options.testDrive).click(function(e){
			e.preventDefault();
			showForm( 'testdrive' );
			return false;
		})
		
		$(options.sendToFriend).click(function(e){
			e.preventDefault();
			showForm( 'sharewithfriend' );
			return false;
		})

		$(options.valueMyVechile).click(function(e){
			e.preventDefault();
			showForm( 'valuemyvehicle' );
			return false;
		})


		$(options.brochure).click(function(e){
			e.preventDefault();
			showForm( 'requestbrochure' );
			return false;
		})
		
		$(options.serviceSomethingElse).click(function(e){
			e.preventDefault();
			showForm( 'servicesomethingelse' );
			return false;
		})	
	}	
})(jQuery);


// *****************************************************
// Setup all the forms attached to current page
// *****************************************************


$(document).ready(function(){
	$('#options,.btns,.carBtns,.formButtons,#newVehicleOptions,#newCarOptions,.financeTableButtons,#newVehicleOptions,#usedVehicleOptions').popoutForms();
	
	$('.popupForm').each(function(){
		$('#'+$(this).attr('id')).popupForm();
	})
	
	$('.inlineForm').each(function(){
		$('#'+$(this).attr('id')).popupForm({inline:true});
	})
	
	$('#dialogRetrieveFavourites').popupForm({url:'/frontend-operations/retrieve-favourites/'});
	$('#dialogSaveFavourites').popupForm({url:'/frontend-operations/save-favourites/'});
	
	$('.date').datepicker();
    $('.date').datepicker('option', {showAnim: 'fadeIn',dateFormat: 'dd/mm/yy'});
	$('.datefuture').datepicker();
	$('.datefuture').datepicker('option', {showAnim: 'fadeIn',dateFormat: 'dd/mm/yy', minDate:new Date});

})

