/**
*  Tabs and menu controller
*  These functions controll the search menu and search areas
*/

var searchOptions = new function() {
    this.init = function() {
        $('.prkng_term_form, .car_term_form, .lounge_term_form, .all_term_form').hide();
    }
}

/**
*  Form Controls
*  These functions perform the changing of the fields and similar in the search boxes
*/
var formControls = new function() {
    this.init = function() {
        travellerNumChange();
        $('#insurance_trav_number').change(travellerNumChange);
        $('.show_hide_box').click(showList);
        $('input#policy_type').click(insuranceRange);
        $('#insurance_search #insurance_details input#policy_type').click(insuranceRange);
        insuranceRange();

        /* For the Landing Pages, here if the page has a "list trigger" we set the page to load the lists
        input and select the ones that matches best the URI""*/
        try {
            if (list_trigger == 'true') {
                var x = $('.show_hide_box');
                $('.show_hide_box:eq(0)').trigger('click');
            }
        }
        catch(e) {}
    }

    function insuranceRange() {
        var x = $("#insurance_details input[@name='policy_type']:checked").val();
        if (x == 'multi_trip') {
            $('#insurance_ret_date').attr("DISABLED", true);
        } else {
            $('#insurance_ret_date').removeAttr("DISABLED");
        }
    }

    function showList() {
        $(this).parent().parent().find('.switchvalidation').toggleClass('required cancel');
        $(this).parent().parent().children('.auto_input').toggleClass('hidden');
        $(this).parent().parent().children('.list_input').toggleClass('hidden');
        $(this).parent().find('.switchvalidation').toggleClass('required cancel');
        $(this).parent().children('.auto_input').toggleClass('hidden');
        $(this).parent().children('.list_input').toggleClass('hidden');
        if ($('#carhire_auto').hasClass('hidden') && !$('#car_return_loc_h').hasClass('hidden')) {
            $('#car_return_loc_h, #car_return_loc_d').addClass('hidden');
        }
    }

    function travellerNumChange() {
        var trav_num = $('#insurance_trav_number').val();
        var ele_num = $('.trav_num').size();
        for (var i = 1; i <= ele_num; i++) {
            var elem = '#insurance_t_age_' + i;
            var e = $(elem);
            var f = $(elem + ' input').first();
            if (f.hasClass('required')) f.removeClass('required');
            if (i > trav_num) {
                e.hide();
            } else {
                e.show();
                f.addClass('required');
            }
        }
    }

}

var autocomplete = new function() {
    this.init = function() {
        $('#insurance_destination').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: BASE_URI + "scripts/php/autocomplete.php",
                    dataType: "json",
                    data: {query:this.term},
                    success: function(data) {
                        response($.map(data.countries, function(item) {
                            return {
                                label: '<strong>' + item.name + '</strong> ' + item.description,
                                value: item.name,
                                code : item.region
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                $('#insurance_iso_code_hidden').val(ui.item.code);
            },
            open: function() {
            },
            close: function() {

            }
        });
    }
}

var carhire_functions = new function () {
    this.init = function() {
        $('#carhire_auto_return, #carhire_auto_return_2').click(car_return_toggle);
        $('#carhire_lists, #carhire_no_lists').click(car_hire_list_toggle);
        $('#car_hire_details').submit( function () {
            if ($('#car_hire_region').is(':hidden')) {
                $('#car_hire_region').val('');
            }

        });
    }

    function car_return_toggle() {
        $('#car_return_loc_d, #car_return_loc_h').toggle();
        $('#carhire_auto_return, #carhire_auto_return_2').toggle();
        $('#car_destination').toggleClass('required cancel');
    }

    function car_hire_list_toggle() {
        $('#carhire_lists, #carhire_no_lists').toggle();
        var call_id = this.id;
        if (call_id == 'carhire_lists') {
            $('#carhire_list_switch_text, #car_return_loc_d, #car_return_loc_h, #carhire_auto, #carhire_auto_text').hide();
            $('#car_hire_list_region_text, #car_hire_list_region, #car_hire_list_pickup_text, #car_hire_list_pickup, #car_hire_list_dropoff_text, #car_hire_list_dropoff').show();
            $('#car_destination').removeClass('required');
            $('#car_destination').addClass('cancel');

            $('#car_hire_region, #car_hire_pickup, #car_hire_dropoff').removeClass('cancel');
            $('#car_hire_region, #car_hire_pickup, #car_hire_dropoff').addClass('required');
        } else if (call_id == 'carhire_no_lists') {
            $('#carhire_list_switch_text, #carhire_auto, #carhire_auto_text, #carhire_auto_return').show();
            $('#car_hire_list_region_text, #car_hire_list_region, #car_hire_list_pickup_text, #car_hire_list_pickup, #car_hire_list_dropoff_text, #car_hire_list_dropoff, #carhire_auto_return_2').hide();
            $('#car_return').val('');
            $('#car_destination').addClass('required');
            $('#car_destination').removeClass('cancel');

            $('#car_hire_region, #car_hire_pickup, #car_hire_dropoff').removeClass('required');
            $('#car_hire_region, #car_hire_pickup, #car_hire_dropoff').addClass('cancel');
        }
    }
}


var autocomplete_parking = new function () {
    this.init = function() {
        highlight: false,
        $('#parking_destination_box').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: BASE_URI + "scripts/php/parking_autocomplete.php",
                    dataType: "json",
                    data: {query:this.term},
                    success: function(data) {
                        response($.map(data.parking, function(item) {
                            return {
                                label: '<strong>' + item.name + '</strong>',
                                value: item.name,
                                code : item.code
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                $('#parking_destination_code_hidden').val('' + ui.item.code + '');
            },
            open: function() {
            },
            close: function() {

            }
        });
    }
}

var autocomplete_carhire = new function () {
    this.init = function() {
        $('#car_destination, #car_return').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: BASE_URI + "scripts/php/carhire/carHireAutoComplete.php",
                    dataType: "json",
                    data: {query:this.term},
                    success: function(data) {
                        response($.map(data.carhire, function(item) {

                            var regex = new RegExp('(' + request.term + ')', 'gi');

                            var points = item.points.replace(regex, '<strong>$1</strong>');

                            return {
                                label: '' + points + '',
                                value: item.points,
                                code: item.code
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                if (this.id == 'car_destination') {
                    $('#car_destination_code_hidden').val('' + ui.item.code + '');
                } else {
                    $('#car_recode_hidden').val('' + ui.item.code + '');
                }

            },
            open: function() {
            },
            close: function() {

            }
        });
    }
}

/* Auto Complete */
var dropdowns = new function() {

    /*
    @public
    */
    this.init = function() {
        $('#transfer_airport').change(handleGatewayChange);
        $('#car_hire_region').change(handleRegionChange);
        $('#lounge_destination_list').change(handleLoungeTerminals);
        $('#car_hire_pickup').change(changePickupPoint)
        handleGatewayChange();
        handleLoungeTerminals();
    }

    function handleLoungeTerminals() {
        var term = $('#lounge_destination_list').val();
        /*
        handling display of terminals, cancelled a travelops doesn't handle..
        if (!term) return;
        var box = $('#lounge_terminal_list');
        if (term.length == 3) {
        $('.lounge_term_form').show();
        if (!box.hasClass('required')) box.addClass('required');
        if (!box.hasClass('cancel')) box.addClass('cancel');
        $.ajax({
        url: BASE_URI + 'scripts/php/lounges/getTerminals.php',
        data: {query:$('#lounge_destination_list').val()},
        success: function(data) {
        $('#lounge_terminal_list').html(data);
        }
        });
        } else {
        box.removeClass('required cancel');
        $('.lounge_term_form').hide();
        } */
    }
    /*
    @private
    */
    function handleGatewayChange() {
        var gatewayCode = $('#transfer_airport').val();
        var resort = $('#previous_resort').val();
        $.get(BASE_URI+'scripts/php/transfers/getResorts.php?gatewayCode=' + encodeURIComponent(gatewayCode) + '&resort=' + encodeURIComponent(resort), gatewayChangeCallback);
    }

    /*
    @private
    */
    function gatewayChangeCallback(data) {
        $('#transfer_resort').html('');
        if (data != '') {
            $('#transfer_resort').html(data);
        }
    }
    function handleRegionChange() {
        var gatewayCode = $('#car_hire_region').val();
        $.get(BASE_URI + 'scripts/php/carhire/getCarHirePoints.php?countryId=' + encodeURIComponent(gatewayCode), regionChangeCallback);
    }

    /*
    @private
    */
    function regionChangeCallback(data) {
        $('#car_hire_dropoff').html('');
        $('#car_hire_pickup').html('');
        if (data != '') {
            $('#car_hire_pickup').html(data);
            $('#car_hire_dropoff').html(data);
        }
    }

    function changePickupPoint() {
        $('#car_hire_dropoff').val($('#car_hire_pickup').val());
    }

}

var validationSearch = new function() {
    this.init = function() {
        $('#parking_details').validate({
            errorClass: 'invalidField',
            validClass: 'validField',
            wrapper: 'p'
        });
        $('#car_hire_details').validate({
            errorClass: 'invalidField',
            validClass: 'validField',
            wrapper: 'p'
        });
        $('#transfer_details').validate({
            errorClass: 'invalidField',
            validClass: 'validField',
            wrapper: 'p'
        });
        $('#insurance_details').validate({
            errorClass: 'invalidField',
            validClass: 'validField',
            wrapper: 'p'
        });
        $('#lounge_details').validate({
            errorClass: 'invalidField',
            validClass: 'validField',
            wrapper: 'p'
        });
        $('#feedback_details, #tickets_details').validate({
            errorClass: 'invalidField',
            validClass: 'validField',
            wrapper: 'p'
            //wrapper: 'span class="fail"'
        });

        $('#car_hire_details, #transfer_details, #insurance_details, #lounge_details, #tickets_details').submit(function() {
            if (!$(this.id).valid()) return false;
            else {
                return true;
            }
        });
    }
}

var parking_function = new function() {
    this.init = function() {
        $('#parking_search_button').click( function () {
            if ($('#parking_destination_box').is(':hidden')) {
                $('#parking_destination_box').val('');
                $('#parking_destination_code_hidden').val('');
            }
            if ($('#parking_dropdown').is(':hidden')) {
                $('#parking_destination_list').val('');
                $('#parking_destination_list').val($('option:first', this).val());
            }
            return true;
        });
    }
}


var ticket_function = new function() {
    this.init = function() {
        $('#attraction_type_list').change(handleTicketTypeChange);
        $('#attraction_destination_list').change(handleTicketCountryChange);
        handleTicketCountryChange();
    };

    function handleTicketTypeChange() {

        $('#attraction_main_location_list').html('');

        var code = $('#attraction_type_list').val();

        if (code == 'XA') {
            $('#attraction_main_location, #attraction_main_location_list_label').show();
            $('#attraction_main_location_list').removeClass('cancel');
            $('#attraction_main_location_list').addClass('required');
        } else {
            $('#attraction_main_location, #attraction_main_location_list_label').hide();
            $('#attraction_main_location_list').addClass('cancel');
            $('#attraction_main_location_list').removeClass('required');
        }

        if (code == 'XK') {
            $('#attraction_adult_number_label, #attraction_adult_box').hide();
            $('#attraction_adult_number').removeClass('required');
            $('#attraction_adult_number').addClass('cancel');
            $('#attraction_child_number').removeClass('cancel');
            $('#attraction_child_number').addClass('required');
            $("#attraction_child_number").rules("add", {
                required: true,
                min: 1
            });
        } else {
            $('#attraction_adult_number_label, #attraction_adult_box').show();
            $('#attraction_adult_number').removeClass('cancel');
            $('#attraction_adult_number').addClass('required');
            $('#attraction_child_number').removeClass('required');
            $('#attraction_child_number').addClass('cancel');
            $("#attraction_child_number").rules("remove");
        }

        $.get(BASE_URI + 'scripts/php/attractions/getTicketCountries.php?query=' + encodeURIComponent(code), ticketChangeCallback);

        handleTicketCountryChange();
    }

    function handleTicketCountryChange() {
        var code = $('#attraction_destination_list').val();
        var type_code = $('#attraction_type_list').val();
        $.get(BASE_URI + 'scripts/php/attractions/getTicketdestinations.php?query=' + encodeURIComponent(code) + '&type=' + encodeURIComponent(type_code), countryChangeCallback);
    }

    function countryChangeCallback(data) {
        $('#attraction_main_location_list').html('');
        if (data != '') {
            $('#attraction_main_location_list').html(data);
        }
    }

    function ticketChangeCallback(data) {
        $('#attraction_destination_list').html('');
        if(data != '') {
            $('#attraction_destination_list').html(data);
        }
        if (trip_dest_id !== undefined) {
            $('#attraction_destination_list').val(trip_dest_id);
        }
    }

}



$(document).ready(parking_function.init);
$(document).ready(carhire_functions.init);
//autocomplete.init = Insurance Auto complete
$(document).ready(autocomplete.init);
$(document).ready(autocomplete_parking.init);
$(document).ready(autocomplete_carhire.init);
$(document).ready(searchOptions.init);
$(document).ready(dropdowns.init);
$(document).ready(formControls.init);
$(document).ready(validationSearch.init);
$(document).ready(ticket_function.init);
