(function($, $V) {

    var log;

    $V.Searchform = function(options) {
        $.extend(true, this, options);
        log = $.logger('ADT.Views.Searchform');
    };

    $.extend($V.Searchform.prototype, {

        attachDatepickers: function(model) {

            var bdl = ADTUtil.getVisibleItem("BookDateLeaving");
            var dates = bdl.attr("rel").split("|");
            var dateFormat = $(bdl).attr("datetimeformat");

            var minDate = $.datepicker.parseDate(dateFormat, dates[0]);
            var maxDate = $.datepicker.parseDate(dateFormat, dates[1]);

            $("[id^='ADT-BookDateLeaving']").datepicker({
                dateFormat: dateFormat,
                changeMonth: true,
                changeYear: true,
                minDate: minDate,
                maxDate: maxDate,
                onSelect: function() { $(this).trigger("UpdateReturnDate") }
            });
            $("[id^='ADT-BookDateReturning']").datepicker({
                dateFormat: dateFormat,
                changeMonth: true,
                changeYear: true,
                minDate: minDate,
                maxDate: maxDate,
                onSelect: function() { $(this).trigger("CheckReturnDate") }
            });
        },


        showform: function(model) {
            var forms = $(".ADT-SearchPanel");
            if (forms.length > 2) { // only need to do this if combo search
                log.debug('showing form %s', model.search);
                $(".ADT-SearchPanel").hide();

                $("#ADT-" + model.search + "BookingForm").show();
                $("#ADT-ComboSearchRadios a").removeClass("ADT-SearchSelected");
                var searchInput = $("#ADT-ComboSearchRadios").find("input[id*=" + model.search + "]");
                $(searchInput).attr("checked", "checked");
                $(searchInput).parent().addClass("ADT-SearchSelected");

                var flyingIn = $("[id^=ADT-BookDirection-In]:visible");
                var flyingOut = $("[id^=ADT-BookDirection-Out]:visible");

                if (model.direction != undefined) {
                    if (model.direction == "In") {
                        if (!$(flyingIn).attr('checked') || $(flyingOut).attr('checked')) {
                            $(flyingIn).attr('checked', true);
                            $(flyingOut).attr('checked', false);
                            this.changeDirection({ direction: "In" });
                        }
                    }
                    else {
                        if ($(flyingIn).attr('checked') || !$(flyingOut).attr('checked')) {
                            $(flyingIn).attr('checked', false);
                            $(flyingOut).attr('checked', true);
                            this.changeDirection({ direction: "Out" });
                        }
                    }
                }
                else {
                    if (model.search == "FlightAndHotel") {
                        if ($("#ADT-BookDirection-In-F").attr("checked")) {
                            $("#ADT-BookDirection-In-FH").attr('checked', true);
                        } else {
                            $("#ADT-BookDirection-Out-FH").attr('checked', true);
                        }
                    }
                    else if (model.search == "FlightOnly") {
                        if ($("#ADT-BookDirection-In-FH").attr("checked")) {
                            $("#ADT-BookDirection-In-F").attr('checked', true);
                        } else {
                            $("#ADT-BookDirection-Out-F").attr('checked', true);
                        }
                    }
                }

                this.sendIframeUpdateMessage();
            }
        },

        togglepanel: function(model) {
            $("#ADT-" + model.panelid + "-" + model.searchtype).toggle();
            this.sendIframeUpdateMessage();
        },


        changeDirection: function(model) {
            $(".ADT-BookDestination:visible label").eq(0).html(model.direction == "Out" ? "Destination" : "Departing");
            if (model.direction == "Out") {
                $(".ADT-SearchPanel:visible .ADT-BookDestinationAirport").hide();
                $(".ADT-SearchPanel:visible .ADT-BookDestinationResort").show();

            }
            else {
                $(".ADT-SearchPanel:visible .ADT-BookDestinationAirport").show();
                $(".ADT-SearchPanel:visible .ADT-BookDestinationResort").hide();

            }
            var depairport = ADTUtil.getVisibleItem("BookLeaving").val();
            if (depairport == undefined) return;
            if (depairport.length == 0) return;
            $(document).trigger('RecreateSearchForm', [null, depairport, null, null, null, model.direction == "Out" ? "true" : "false"]);
        },

        removeRoom: function(model) {

            if (model.roomnumber == 2) {
                $(".ADT-Search:visible *[id^='ADT-BookRoomLabel2']").hide();
                $(".ADT-Search:visible *[id^='ADT-BookRoom2']").hide();
            }
            $(".ADT-Search:visible *[id^='ADT-BookRoomLabel3']").hide();
            $(".ADT-Search:visible *[id^='ADT-BookRoom3']").hide();
            this.sendIframeUpdateMessage();
        },

        addRoom: function(model) {
            if ($(".ADT-Search:visible *[id^='ADT-BookRoomLabel2']:visible").length > 0) { // room 2 already visible so must need room 3
                $(".ADT-Search:visible *[id^='ADT-BookRoomLabel3']").show();
                $(".ADT-Search:visible *[id^='ADT-BookRoom3']").show();
            }
            else { // add room 2
                $(".ADT-Search:visible *[id^='ADT-BookRoomLabel2']").show();
                $(".ADT-Search:visible *[id^='ADT-BookRoom2']").show();
            }

            this.sendIframeUpdateMessage();
        },


        setDeparture: function(model) {
            ADTUtil.getVisibleItem("BookLeaving").val(model.set);
        },

        setOneWay: function(model) {

            var searchtype = model.searchtype;
            if ($("#ADT-BookOneWayOnly-" + searchtype)[0].checked) {
                $("#ADT-BookDateReturning-" + searchtype).parent().hide();
            }
            else {
                $("#ADT-BookDateReturning-" + searchtype).parent().show();
            }
        },


        setCountries: function(model) {
            var me = this;
            $("[id*='BookDestinationCountry']").each(function(i, n) {
                me.fillDropDown($(n), model.options, model.set);
            });

            if (ADTUtil.getVisibleItem("BookDestinationAirport").length > 0) {
                this.fillDropDown(ADTUtil.getVisibleItem("BookDestinationAirport"), null);
            }
            else {
                this.fillDropDown(ADTUtil.getVisibleItem("BookDestinationResort"), null);
            }
        },

        waitCountries: function(model) {
            this.waitDropDown(ADTUtil.getVisibleItem("BookDestinationCountry"));
            if (ADTUtil.getVisibleItem("BookDestinationAirport").length > 0) {
                this.fillDropDown(ADTUtil.getVisibleItem("BookDestinationAirport"), null);
            }
            else {
                this.fillDropDown(ADTUtil.getVisibleItem("BookDestinationResort"), null);
            }
        },


        setResorts: function(model) {
            this.fillDropDown(ADTUtil.getVisibleItem("BookDestinationResort"), model.resorts, model.set);
        },
        waitResorts: function(model) {
            this.waitDropDown(ADTUtil.getVisibleItem("BookDestinationResort"));
        },

        setAirports: function(model) {
            this.fillDropDown(ADTUtil.getVisibleItem("BookDestinationAirport"), model.airports, model.set);
        },
        waitAirports: function(model) {
            this.waitDropDown(ADTUtil.getVisibleItem("BookDestinationAirport"));
        },

        resetDates: function(model) {
            ADTUtil.getVisibleItem("BookDateLeaving").datepicker("setDate", Date.parseExact(model.depdate, "dd-MM-yyyy"));
            ADTUtil.getVisibleItem("BookDateReturning").datepicker("setDate", Date.parseExact(model.retdate, "dd-MM-yyyy"));
        },

        updateReturnDate: function(model) {
            var mindate = new Date(model.mindate.y, model.mindate.m, model.mindate.d);
            var returndate = new Date(model.returndate.y, model.returndate.m, model.returndate.d);
            model.targetpicker.datepicker("setDate", returndate).datepicker('option', 'minDate', mindate);
        },


        /* Utility fns; */
        sendIframeUpdateMessage: function() {
            if (typeof (ADT_IFrame_Resize) != "undefined") ADT_IFrame_Resize();
        },

        waitDropDown: function(dropdown) {
            dropdown.empty().append('<option value="" selected> loading... </option>');
        },

        fillDropDown: function(dropdown, items, set) { // set items == null to empty and disable
            var optionElems;
            var re = new RegExp('%20', "g"); // /g enables "global" matching
            var unencodedSet = set != null ? set.replace(re, ' ') : null;

            if (items) {
                optionElems = '<option value="">Please select</option>';
                for (var i = 0; i < items.length; i++) {
                    optionElems += '<option ' + ((items[i].value == unencodedSet) ? 'selected' : '') + ' value="' + items[i].value + '">' + items[i].text + '</option>';
                }
            }
            else {
                optionElems = '<option value="" selected> - </option>';
            }
            dropdown.empty().append(optionElems);
        }


    });

})(jQuery, ADT.Views);

