/*
 * 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');
formList[2]['emailQuote']=Array('UsedVehicleEmailQuote','alertBoxEmailQuote');

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

(function(jQuery){

	jQuery.fn.popupForm = function(options){
		var defaults = {
			captcha:false,
			message:'.ui-corner-all',
			messageHide:2000,
			url:'/frontend-operations/submit-form/',
			extensions:['pdf', 'doc', 'docx'],
			submit:false,
			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();
					//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' );
				}
			});

			if ((formType == 'formCapNewVehiclesValueMyVehicle') || (formType == 'formUsedVehicleValueMyVehicle')) {
				dialogId.dialog('widget').attr('id', 'partExFrm');
			}
		//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(){
			
			$('.error',dialogId).removeClass('.error');
			if(options.submit==true){
				if ($('form:first',dialogId).valid()){
					//showMsg('Submitting Form','Please wait while we submit your details.','highlight','');
					//$('fieldset:first',dialogId).slideUp(1000);
					$('form:first',dialogId).submit();
					showMsg('Thank You','Your details have been submitted successfully','highlight','');
					setTimeout( "autoCloseDialog('" + dialogId.attr('id') + "');",4000);
				}
				
				return true;
			}	
			


			clearFormElements($('form:first',dialogId).attr('id')); 
			if(dialogId.data('name')=='valuemyvehicle'){
				//alert('test'+$(dialogId).data('formId'));
				$(dialogId.data('formId')).append('<input type="hidden" name="my_make" value="'+$('#valuemyvehicle_my_make_id > option:selected').text()+'" />');
				$(dialogId.data('formId')).append('<input type="hidden" name="my_model" value="'+$('#valuemyvehicle_my_model_id > option:selected').text()+'" />');
			}
			$('body').css('cursor', 'progress'); 
			//$('form:first',dialogId).resetForm();
			if ($('form:first',dialogId).valid()){
				$.ajax({
				  url: options.url,
				  dataType: 'json',
				  data: $('form:first',dialogId).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 ) ]);
							validator.resetForm();
						}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','');
							}
						}
					},
					error: function( objRequest ){
						showMsg('Request Failed','The request failed to submit, please try again.','error','');
					}
				});
			}else{
				
			}
			
			$('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');
			clearFormElements(formId); 
		}
	}	
})(jQuery);




/**
* @ desc This will open the dialog and show the correct form
*/
function showForm( formType,area ){
	if(area==undefined){
		var area=netdirector.areaType;
	}
  
    if(formType=='valuemyvehicle'){
		var area=0;
	}
    
	//if we could not find the form lets fall back to global forms
	if (formList[area] != undefined){
        if(!(formType in formList[area])){
            var area=0;
        }
    }else{
       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(formType=='valuemyvehicle'){
		collectAllMakes('#valuemyvehicle_my_make_id', 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',
            testDrive:'#btnBookTestDrive,#btnRequestTestDrive,#btnTestDrive',
            print:'.print',
            valueMyVechile:'.btnValueMyVehicle,.jumpPartExchange,#btnPartEx,#btnValuation'
		};

		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;
		})
	}	
})(jQuery);


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

$(document).ready(function(){
	$('#options,.carBtns,.formButtons,#newVehicleOptions,#newCarOptions,.financeTableButtons').popoutForms();

	//useful to popup form in dialog but submit in standard way instead of via ajax
	$('.popupSubmitForm').each(function(){
		$('#'+$(this).attr('id')).popupForm({submit:true});
	})
	
	$('.popupForm').each(function(){
		$('#'+$(this).attr('id')).popupForm();
	})
	
	$('.inlineForm').each(function(){
		$('#'+$(this).attr('id')).popupForm({inline:true});
	})
	
	$('#dialogRetrieveFavourites').popupForm({url:'/frontend-operations/save-favourites/'});
	$('#dialogSaveFavourites').popupForm({url:'/frontend-operations/retrieve-favourites/'});
	
	$('.date').datepicker();
	$('.datefuture').datepicker();
	$('.datefuture').datepicker('option', {showAnim: 'fadeIn',dateFormat: 'dd/mm/yy', minDate:new Date});

	
})

