/**
 * Enquiry form handler
 *
 * @author          Malcolm Clark
 * @modifiedby      $LastChangedBy: Mal $
 * @copyright       Copyright Flight Centre Ltd. All rights reserved.
 * @version         $Revision: 3873 $
 * @lastmodified    $Date: 2011-01-24 17:06:23 +1000 (Mon, 24 Jan 2011) $
 * @requires        RTW, RTW.SETTINGS, FCL.DATETIME, FCL.UTIL, FCL.FORMS, FCL.GIMP
 */

;RTW.ENQUIRY = {

    name: 'RTW.ENQUIRY',

    $form: null,

    fieldMappings: {
        dayPhone: 'Phone',
        departureDate: 'Depart',
        returnDate: 'Return'
    },
	
    enquiryType: 'Contact',
	
	defaultOptions: {
		formReset: true
	},
	
	successMessage: "Your enquiry has been sent successfully! ",
	submitButton: "NULL",

    init: function() {
		//FCL.UTIL.handleErrors(this);
		$("document").ready(function() {
			RTW.ENQUIRY.$form = $('#enquiryForm');
			if (RTW.ENQUIRY.$form.length == 0) { return; }
			RTW.ENQUIRY.setupForm();
			RTW.ENQUIRY.setupValidation();
			RTW.ENQUIRY.initDates();
		});
    },

	/**
	 * @description Initialises the dates. Calculates 1 year ahead
	 *
	 */

	 initDates: function() {
		$('#monthYearStart').setDates().initMonthYear();
		$('#monthYearEnd').setDates().initMonthYear();
		$('#monthYearStart').change(function() {
			$(this).setDates().updateDays();
		});
		$('#monthYearEnd').change(function() {
			$(this).setDates().updateDays();
		});
	 },
	 	 
    /**
     * Look for sku in url and if not found return 'null' for reporting purposes
     */
    getSku: function() {
        try
        {
            var url = window.location.pathname;
            var sku = url.substring( url.lastIndexOf('-') ).match(/\d+/);

            if(sku == null)
            {
                return 'null';
            }

            return sku[0];
        }
        catch(e)
        {
            return 'null';
        }
    },

    setupForm: function() {
        var _this = this;

        // Setup defaults and hidden values
        this.$form.find('#en_pageURL').val(window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.search);

        /**
         * Check for existence of "referringUrl" query string variable as if we are on portable enquiry form of
         * main enquiry page, then recording this page's url in the enquiry data is useless. In these instances
         * we want to know where they've come from and change the default value of #en_pageURL accordingly
         */
         if(FCL.UTIL.getUrlVar('referringUrl') != '')
         {
             this.$form.find('#en_pageURL').val(FCL.UTIL.getUrlVar('referringUrl'));
         }
		 
		/* Apply the click events for the Step headings so someone can return if they want to make a change */
		$("#Button-Appointment").bind("click", function() {
			RTW.ENQUIRY.showAppointment();
			return false;
		});
		
		$("#Button-Callback").bind("click", function() {
			RTW.ENQUIRY.showCallback();
			return false;
		});

		// capture the submit button clicked and save it in order to manipulate it upon submission success
		$('#enquiryForm').find('input[type="image"][value="send"]').click( function(e) {
			RTW.ENQUIRY.submitButton = this;
		});

    },
	
	/* Setup the validation for the form and apply the submit handlers */
    setupValidation: function()
    {
        var _this = this;

		// Yuin - 28/11/11 - custom validation rules for names
		$.validator.addMethod("textOnly", function(value, element) {return !/^[0-9]+$/.test(value);}, "");
		// Yuin - 28/11/11 - custom validation rules for telephone numbers
		$.validator.addMethod("numOnly", function(value, element) {return !/[:alpha:]+/.test(value);}, "");
		
		if (this.$form.validate({ // LG: to avoid trying to validate forms w/o validate object
				onfocusout: false,
				onkeyup: false,
				onclick: false,
				errorLabelContainer: "#errorMessage",
				focusCleanup: false,
				rules: {	
					// firstName: 'required',
					// lastName: 'required',
					firstName: {
						required: true,
						textOnly: true
					},
					lastName: {
						required: true,
						textOnly: true
					},
					email: {
						required: true,
						email: true
					},
					phone: {
						numOnly: true
					},
					altphone: {
						numOnly: true
					}
				},
				messages: {
					firstName: "",
					lastName: "",
					phone: "",
					email: "",
					flightNumber_1: "",
					flightNumber_2: "",
					flightNumber_3: "",
					flightNumber_4: "",
					flightNumber_5: "",
					flightNumber_6: "",
					flightNumber_7: "",
					flightNumber_8: "",
					flightNumber_9: "",
					flightNumber_10: "",
					passenger2FirstName: "",
					passenger2LastName: "",
					passenger3FirstName: "",
					passenger3LastName: "",
					passenger4FirstName: "",
					passenger4LastName: "",
					passenger5FirstName: "",
					passenger5LastName: "",
					passenger6FirstName: "",
					passenger6LastName: ""
				},

				invalidHandler: function(e, validator) {
					FCL.FORMS.invalidForm(e, validator, _this.fieldMappings);
				},

				submitHandler: function(form) {
					
					// Record enquiry type in Google Analytics
					// Removed by campm as rtw.tracking.js now exists.
					//FCL.UTIL.registerGAPageView({ path: RTW.ENQUIRY.enquiryType });

					/**
					 * Add in form field to record this is a Tourism Media enquiry in case GA fails
					 * timestamp is included so GA stats can be matched up with enquiries
					 */
					if(FCL.TM.isWithinThreeClicks() || FCL.UTIL.getUrlVar('tourismMediaTracking') == 'true') {
						var timestamp = function() { d = new Date(); return d.getTime(); }();
						_this.$form.append('<input type="hidden" name="timestamp" value="'+ timestamp +'" />');
						FCL.UTIL.googleAnalyticsReporting(timestamp);
					}
					
					// Dates
					$('#en_departureDate').val($('#dayStart').val()+'/'+$('#monthYearStart').val());
					$('#en_returnDate').val($('#dayEnd').val()+'/'+$('#monthYearEnd').val());

					// Setting values of checkboxes
					/*
					$(':checkbox').each(function() {
						$this = $(this);
						if ($this.attr('checked')) {
							$this.val('yes');
						} else {
							$this.attr('checked',true);
							$this.val('no');
						}
					});
					*/

					// Find all checked checkboxes, collect values in an array and convert to a single string value
					// Insert concatenated string into a hidden field 'sExtras' value
					var checkedVals = [];
					var sExtras = "";
					var count = 0;
					$('#extras').find('.form-item input:checkbox').each( function(i) {
					    $this = $(this);
					    if($this.attr('checked')) {
					        checkedVals[count] = $this.next('input:hidden').val();
					        count++;
					    }
					});
					sExtras = checkedVals.join(', ');
					$('#extras').find('#sExtras').val(sExtras);

					
					// Setting input fields to empty where the sections are removed (hidden)
					if (_this.$form.hasClass('contactUsForm')) {
						$('div[id^=passenger]:hidden').find('input[name*=FirstName]').each(function() {
							$this = $(this);
							var index = $this.attr("name").match(/^(passenger\d)/);
							if (index && index[1]) {
								var title1 = "#"+index[1] + "Title1";
								var firstname = "#"+index[1] + "FirstName";
								var lastname = "#"+index[1] + "LastName";
								var agegroup1 = "#"+index[1] + "AgeGroup1";
								$(title1).val("");
								$(firstname).val("");
								$(lastname).val("");
								$(agegroup1).val("");
							}
						});
						$('div[id^=passenger]:visible').find('input[name*=FirstName]').each(function() {
							$this = $(this);
							var index = $this.attr("name").match(/^(passenger\d)/);
							if (index && index[1]) {
								var title = "#"+index[1] + "Title";
								var title1 = "#"+index[1] + "Title1";
								$(title1).val($(title).val());
								var agegroup = "#"+index[1] + "AgeGroup";
								var agegroup1 = "#"+index[1] + "AgeGroup1";
								$(agegroup1).val($(agegroup).val());
							}
						});
						
						if ($('.appointment').hasClass('hide')) {
							$('#appStore1').val("");
							$('#preferedAppDate').val("");
							$('#preferedBackupDate').val("");
						} else if ($('.appointment').hasClass('show')) {
							$('#appStore1').val($('#appStore option:selected').text());
							$('#preferedAppDate').val($('#preferedAppday').val()+'/'+$('#preferedAppmonthYear').val()+' '+$('#preferedAppTime').val());
							$('#preferedBackupDate').val($('#preferedBackupday').val()+'/'+$('#preferedBackupmonthYear').val()+' '+$('#preferedBackupTime').val());
						}
						if ($('.callback').hasClass('hide')) {
							$('#preferedCallDate').val("");
						} else if ($('.callback').hasClass('show')) {
							$('#preferedCallDate').val($('#preferedCallday').val()+'/'+$('#preferedCallmonthYear').val()+' '+$('#preferedCallTime').val());
						}
					}
					
					// Inserting (non-existent) empty fields of travel butler form
					var numFlights = $('.tbform .flightSet .flightDetails').size();
					if(_this.$form.hasClass('tbform')) {
						if(numFlights<8) {							
							for(var i=numFlights+1;i<=8;i++) {
								var newFlightFieldset = $("#flightTemplate").clone(true);
								newFlightFieldset.find('.addFlight').remove();
								newFlightFieldset.attr('id','flight_'+(i)+'').css('display', 'none');
								
								$(newFlightFieldset).find("input, select, label").each(function(j) {
									if(this.tagName=="SELECT" || this.tagName=="INPUT") {
										var elId = $(this).attr('id');
										var elName = $(this).attr('name');
										$(this).attr('id', elId+'_'+(i));
										$(this).attr('name', elName+'_'+(i));
										if(this.tagName=="INPUT") {
											$(this).val(" - ");
										}
									}
								});
								newFlightFieldset.appendTo("#flightSet");	
							}
						}
					}
					
					// Process via AJAX
					$.get(FCL.GIMP.getUrl(_this.$form), function(data) {
						if (data.indexOf('Enquiry Success') > -1) {

							var trackingCode = _this.$form.find('input[name="trackingCode"]').val();
							RTW.TRACKING.enquirySuccess(trackingCode);
							
							$(RTW.ENQUIRY.submitButton).attr('disabled',true).css('opacity', '0.5');

							if(!_this.$form.hasClass('tbform')) {
								setTimeout(function() {								
		                        	//_this.$form.slideUp();
									$('#enquiryForm').after('<a name="successMessage"><div class="section message" style="display: block; "><span class="mandatory floatLeft">'+RTW.ENQUIRY.successMessage+'</span><div class="clearing"></div></div></a>');
									location.href = "#successMessage";
		                        },1000);
							}
							//$('.close').hide();
							//var temp = $('.open').html();
							//$('.open').html('Your request has been sent successfully!')
							//$('.open').show();
							
							//setTimeout(function() {$('.message.hide').hide();},3000)
							//setTimeout(function() {$('.open').html(temp);},3000)
							//setTimeout(function() {_this.$form.next().fadeIn();},750);
							if (_this.$form.hasClass('tbform')) {
								// LG: Commented remove 'send' for consistency with the rest of the enquiry forms
								$('#tbSend').hide(); // JP:14/12/11 uncommented as per JIRA UK-457
								$('#enquiryForm').after('<a name="successMessage"><div class="section message" style="display: block; "><span class="mandatory floatLeft">'+RTW.ENQUIRY.successMessage+'</span><div class="clearing"></div></div></a>');
								// handler to hide success message and display 'send' button again on focus
								$('.tbform input[type="text"]').focus( function() {
									if($('#tbMsg:visible')) {
										$('#tbMsg').hide();
										$('#tbSend').show();
									}	
								});
							}
							
						} else {
							setTimeout(function() { _this.$form.prev().fadeIn('slow'); },750);
						}
						if (_this.$form.hasClass('contactUsForm')) {
							$("#en_template").val("ukrtw/ct-generalEnquiryContactUs");
							$("#en_bounceBackTemplate").val("ukrtw/bb-generalEnquiryContactUs");
						}
						if (RTW.ENQUIRY.defaultOptions.formReset) {
							// Resets checkboxes as they artificially (because of required status "checked" by email) are set before submit
							//_this.$form.resetForm();
							$(':checkbox').resetForm();
							// Reset Travel Butler form
							if(_this.$form.hasClass('tbform')) {
								// LG: For consistency with other forms, leave personal data filled after submit. To get back old behaviour, swap comments to next 2 lines
								$('.tbform .flightSet input, .travelButlerForm textarea').resetForm();
								//$('.tbform .flightSet input, .travelButlerForm input, .travelButlerForm textarea').not('.travelButlerForm input[type=image]').resetForm();
								var button = $('.flightSet .flightDetails .addFlight').clone();
								var num = $('.flightSet .flightDetails:visible').size();
								
								$('.tbform .flightSet .flightDetails').not(':first').remove();
								if(num>1) {
									$('.flightSet .flightDetails:first #addFlightPlaceholder').append(button);
								}
								$("#flightSet .flightDetails .enableFlightReroute").attr("checked", false);
								$("#flightSet .flightDetails .enableFlightReroute").parent().next().find('input[type="text"]')
									.attr("disabled", "true").val("");
							} 
						}

					});
					return false;
				}
			})) {
		}
    }
};
RTW.ENQUIRY.init();


