;ET.ALTITUDE = 
{
    $form: null,
    
    fieldMappings: 
    {
        startCity:      'From city',
        startDate:      'Departure date',
        startTime:      'Departure time',
        endCity:        'To city',
        endDate:        'Arrival date',
        endTime:        'Arrival time',
        numAdults:      'Adults',
        numChildren:    'Children',
        numInfants:     'Infants',
        flightClass:    'Class'
    },
    
    resultCity: '',
    
    NZCity: ['AKL','BHE','CHC','DUD','GIS','HLZ','HKK','IVC','KAT','KKE','NPE','NSN','NPL','OAM','PMR','ZQN','ROT','TUO','TRG','TIU','WKA','WAG','WLG','WSZ','WHK','WRE'],
    
    init: function()
    {
        this.$form = $('#altitudeForm');
        this.setupForm();
        this.setupValidation();
    },
    
    setupForm: function()
    {
        _this = this;
        // Set hidden and default values
        this.$form.find('#alt_todaysDate').val(ET.DATETIME.todaysDate());
        this.$form.find('#alt_startDate').val(ET.DATETIME.tomorrowsDate());
        this.$form.find('#alt_todaysTime').val(ET.DATETIME.timeHHMM());
        this.$form.find('#alt_endDate').val(ET.DATETIME.weekFromToday());

        // Toggle return fields depending upon return or one way trip
        this.$form.find('#alt_return').bind('click', function(e)
        {
            ET.ALTITUDE.$form.find('#alt_endDate').datepicker('enable');
            ET.ALTITUDE.$form.find('#alt_endTime').attr('disabled', '');
        });
        this.$form.find('#alt_oneWay').bind('click', function(e)
        {
            ET.ALTITUDE.$form.find('#alt_endDate').datepicker('disable')
            ET.ALTITUDE.$form.find('#alt_endTime').attr('disabled', 'disabled');
        });

        $(document).ready(function()
        {
            ET.ALTITUDE.$form.find('#alt_startDate').datepicker($.extend(ET.SETTINGS.datePicker, { minDate: 0}));
            ET.ALTITUDE.$form.find('#alt_endDate').datepicker($.extend(ET.SETTINGS.datePicker, { minDate: 0}));
        });
		
		//If we are on a product page change the From and To fields to reflect the current product
		if(window.location.pathname.split('/')[1] === 'product')
		{
			this.$form.find('#alt_startCity').val($('meta[name="product.departure"]').attr('content'));
			this.$form.find('#alt_endCity').val($('meta[name="product.destination"]').attr('content'));
		};

        this.$form.find('#alt_startDate').bind('change', function(e) 
        {
            var toOffsetFromDate = ET.DATETIME.compareDates(new Date(), ET.DATETIME.stringToDate(_this.$form.find('#alt_startDate').val()));
           _this.$form.find('#alt_endDate').datepicker('option', 'minDate', toOffsetFromDate.days);
        });

        ET.FORMS.replaceSubmitButton(ET.ALTITUDE.$form.find('.submitButton'));
    },

    setupValidation: function()
    {    
        // Check that destination and departure cities are not the same
        jQuery.validator.addMethod('checkDestination', function(value, element, params) 
        {
            return !(ET.ALTITUDE.$form.find('#alt_startCity').val() == ET.ALTITUDE.$form.find('#alt_endCity').val());
        }, jQuery.format('Your departure and destination cities cannot be the same.'));
        
        
        // Check departure date is before arrival date
        jQuery.validator.addMethod('altitudeDepartureArrivalDates', function(value, element, params) 
        {
            // If one way, it doesn't matter what return date is
            if(ET.ALTITUDE.$form.find('#alt_oneWay:checked').length > 0) { return true; }
            
            return ET.DATETIME.stringToDate(ET.ALTITUDE.$form.find('#alt_endDate').val()) >= ET.DATETIME.stringToDate(ET.ALTITUDE.$form.find('#alt_startDate').val());
        }, jQuery.format('Return date cannot be before departure date'));
        
        
        // If return flight and departure date and arrival date are the same, ensure arrival time is after departure time
        jQuery.validator.addMethod('departureArrivalTimes', function(value, element, params) 
        {              
            // If return, timings don't matter because they must be on different days
            if(ET.ALTITUDE.$form.find('#alt_return:checked').length == 0) { return true; }
            
            if(ET.ALTITUDE.$form.find('#alt_startDate').val() != ET.ALTITUDE.$form.find('#alt_endDate').val()) { return true; }
           
            // If either time is "anytime", then we don't need to validate
            if(ET.ALTITUDE.$form.find('#alt_startTime').val() == 'anytime' || ET.ALTITUDE.$form.find('#alt_endTime').val() == 'anytime')
            {
                return true;
            }

            return parseFloat(ET.ALTITUDE.$form.find('#alt_startTime').val().match(/\d{2}:\d{2}/)[0].replace(/:/g, '.')) < parseFloat(ET.ALTITUDE.$form.find('#alt_endTime').val().match(/\d{2}:\d{2}/)[0].replace(/:/g, '.'));
            
        }, jQuery.format('Please select a return time later than your departure time'));
        
        
        // Check number of adults >= number of infants
        jQuery.validator.addMethod('checkInfantsToAdults', function(value, element, params) 
        {             
            return parseInt(ET.ALTITUDE.$form.find('#alt_numAdults').val(), 10) >=
            parseInt(ET.ALTITUDE.$form.find('#alt_numInfants').val(), 10);
        }, jQuery.format('Number of infants must be less or equal to number of adults as each infant must be accompanied by an adult.'));
        
        
        // Check booking quantity does not exceed 9
        jQuery.validator.addMethod('checkBookingQuantity', function(value, element, params)
        {
            return (parseInt(ET.ALTITUDE.$form.find('#alt_numAdults').val(), 10) 
                 + parseInt(ET.ALTITUDE.$form.find('#alt_numChildren').val(), 10)) <= 9;
        }, jQuery.format('For group bookings of more than 9 people please call our customer service centre on 1300 301 900.'));
        
        
        // Trans-tasman (to NZ) flights with infants cannot be booked online
        jQuery.validator.addMethod('checkNZDestinationInfants', function(value, element, params)
        {
            var destination = ET.ALTITUDE.$form.find('#alt_endCity').val();
            for(var i=0; i<ET.ALTITUDE.NZCity.length; i++)
            {
                if(ET.ALTITUDE.NZCity[i] == destination)
                {
                    if(parseInt(ET.ALTITUDE.$form.find('#alt_numInfants').val(),10) > 0)
                    return false;
                }
            }
            return true;
        }, jQuery.format('If you are traveling with infants (< 2 years) to New Zealand, please contact our Online Customer Service Team on 1300 556 855 to complete your booking.'));
        
        
        // Once validation passes, set destination to match in intDestinations object
        this.$form.validate(
        {
            rules: 
            {
                flightType: 'required',
                startCity:  'required',
                startDate:  'required',
                endCity:
                {
                    required: true,
                    checkDestination: true,
                    checkNZDestinationInfants: true
                },
                endDate:    'altitudeDepartureArrivalDates',
                endTime:    'departureArrivalTimes',
                numAdults:  'checkBookingQuantity',
                numInfants: 'checkInfantsToAdults'
            },
            
            invalidHandler: function(e, validator) 
            {
               ET.FORMS.invalidForm(e, validator, ET.ALTITUDE.fieldMappings);
            },

            submitHandler: function(form)
            {
			    /**
				 *	Check to see if tundra is under maintenance 
				 */
			    if (typeof(TUNDRA) != 'undefined' && TUNDRA.MAINTENENCE.enabled === true) {
				    if (typeof(TUNDRA.MAINTENENCE.message) != 'undefined') {
					    alert(TUNDRA.MAINTENENCE.message);
						return false;
				    }
			    }
				
                ET.ALTITUDE.$form.trigger('replaceSubmit');
                form.submit();
            }
        }); 
    }
};
ET.ALTITUDE.init();
