﻿(function ($) {

    $.fn.makeSearchTab = function (options) {

        // settings object
        var settings = {};
        settings.nav = {
            container$: null,
            btnSimple$: null,
            btnAdvanced$: null
        };
        settings.content = {
            container$: null,
            hSimple: 210,
            hAdvanced: 420,
            $simpleSearchButton: null,
            $simpleSearchTable: null,
            $advancedSearchButton: null,
            $advancedSearchTable: null,
            $clearSearchFieldsButton: null
        };
        settings.debug = {
            container$: $("#debugOutput"),
            enabled: false,
            counter: 0
        };
        settings.activeTab = 0;
        settings.animate = false;
        settings.webSiteID = 1; // 1-etrips, 2-zidanice
        settings.syncWithMap = false;

        // combo object
        settings.combos = {
            $comboAccommodationTypes: null,
            $comboRegion: null,
            $comboSubregion: null,
            $comboCommunity: null,
            $comboCity: null
        };

        settings.minMaxAndCount = {
            $accommodationBedsMinMax: null,
            $priceMinMax: null,
            $propertyCountTop: null,
            $accommodationCountTop: null,
            $propertyCountBottom: null,
            $accommodationCountBottom: null,
            intervalId: null,
            doSearch: true,
            collectedData: null,
            pageLoad: true,
            countSkipedRequest: 0
        }

        init($(this));
        initEvents();

        function init(self) {
            settings.nav.container$ = self.find("#tabNavigation");
            settings.nav.btnSimple$ = settings.nav.container$.find("#navSimple");
            settings.nav.btnAdvanced$ = settings.nav.container$.find("#navAdvanced");
            settings.content.container$ = self.find("#tabContent");
            settings.content.$simpleSearchButton = settings.content.container$.find("#btnSimpleSearch");
            settings.content.$simpleSearchTable = settings.content.container$.find("#tableSimpleSearch");
            settings.content.$advancedSearchButton = settings.content.container$.find("#btnAdvancedSearch");
            settings.content.$advancedSearchTable = settings.content.container$.find("#tableAdvancedSearch");
            settings.content.$clearSearchFieldsButton = settings.content.container$.find("#btnClearSearchFields");
            if (options.hSimple)
                settings.content.hSimple = options.hSimple;
            if (options.hAdvanced)
                settings.content.hAdvanced = options.hAdvanced;
            if (options.debug)
                settings.debug.enabled = options.debug;
            if (options.activeTab) {
                if (options.activeTab == 0 || options.activeTab == 'simple')
                    settings.activeTab = 0;
                if (options.activeTab == 1 || options.activeTab == 'advanced')
                    settings.activeTab = 1;
            }
            if (options.syncWithMap) {
                settings.syncWithMap = options.syncWithMap; // if there is no map on page than sync must be false
            }
            if (options.webSiteID) {
                settings.webSiteID = options.webSiteID;
            }

            if (options.animate)
                settings.animate = options.animate;

            switch (settings.activeTab) {
                case 1:
                    // advanced view
                    setActiveTab(settings.nav.btnAdvanced$, settings.content.hAdvanced, false);
                    break;
                default:
                    // simple view
                    setActiveTab(settings.nav.btnSimple$, settings.content.hSimple, false);
                    break;
            } // end switch

            settings.combos.$comboAccommodationTypes = $("#cmbAccommodationTypes", settings.content.container$);
            settings.combos.$comboRegion = $("#cmbRegion", settings.content.container$);
            settings.combos.$comboSubregion = $("#cmbSubregion", settings.content.container$);
            settings.combos.$comboCommunity = $("#cmbCommunity", settings.content.container$);
            settings.combos.$comboCity = $("#cmbCity", settings.content.container$);

            settings.minMaxAndCount.$accommodationBedsMinMax = $("#accommodationBedsMinMax", settings.content.container$);
            settings.minMaxAndCount.$priceMinMax = $("#priceMinMax", settings.content.container$);
            
            settings.minMaxAndCount.$propertyCountTop = $("#propertyCountTop", settings.content.container$);
            settings.minMaxAndCount.$accommodationCountTop = $("#accommodationCountTop", settings.content.container$);
            settings.minMaxAndCount.$propertyCountBottom = $("#propertyCountBottom", settings.content.container$);
            settings.minMaxAndCount.$accommodationCountBottom = $("#accommodationCountBottom", settings.content.container$);

            loadComboData("init=true", true);
            setFormActionAttribute();
        }

        function setFormActionAttribute() {
            $("form").attr("action", $("#hiddenFormSubmitUrl").val());
        }

        function initEvents() {
            // events initialization
            settings.nav.btnSimple$.click(function (event) {
                event.preventDefault();
                settings.activeTab = 0;
                setActiveTab($(this), settings.content.hSimple, settings.animate);
            });

            settings.nav.btnAdvanced$.click(function (event) {
                event.preventDefault();
                settings.activeTab = 1;
                setActiveTab($(this), settings.content.hAdvanced, settings.animate);
            });

            settings.content.$clearSearchFieldsButton.click(function () {
                clearSearchFields();
            });

            settings.combos.$comboRegion.change(function () {
                var queryString = "";
                queryString += "region=" + settings.combos.$comboRegion.val();

                loadComboData(queryString, true);

            });

            settings.combos.$comboSubregion.change(function () {
                var queryString = "";
                queryString += "region=" + settings.combos.$comboRegion.val();
                queryString += "&subregion=" + settings.combos.$comboSubregion.val();

                loadComboData(queryString, true);
            });

            settings.combos.$comboCommunity.change(function () {
                var queryString = "";
                queryString += "region=" + settings.combos.$comboRegion.val();
                queryString += "&subregion=" + settings.combos.$comboSubregion.val();
                queryString += "&community=" + settings.combos.$comboCommunity.val();

                loadComboData(queryString, true);
            });

            $("#imagemap").find("area").click(function () {
                var regionOrSubregion = $(this).attr("alt");
                setMap(regionOrSubregion);
            });

            $("#search,#mapSlovenia,#imagemap").bind("click change keydown", function () {
                settings.minMaxAndCount.doSearch = true;
            });

            settings.minMaxAndCount.intervalId = setInterval(doMinMaxPriceAndBedsSearch, 3000);
        }

        function doMinMaxPriceAndBedsSearch() {
            if (settings.minMaxAndCount.doSearch == false) {
                // user is sleeping
                settings.minMaxAndCount.countSkipedRequest++;
                return;
            }

            // stop next search unless user changes any input field
            settings.minMaxAndCount.doSearch = false;

            var collectedData
            if (settings.activeTab == 0) {
                // collect simple search fields
                collectedData = $("#search #tableSimpleSearch,#search #tableSimpleSearchPart2").find("input,select").serialize();
            }
            else {
                // collect all fields (advanced search)
                collectedData = $("#search").find("input,select").serialize();
            }

            if (settings.minMaxAndCount.collectedData == collectedData) {
                // no input has changed
                settings.minMaxAndCount.countSkipedRequest++;
                log("no input has changed (skipped: " + settings.minMaxAndCount.countSkipedRequest + ")");
                return;
            }

            settings.minMaxAndCount.collectedData = collectedData;

            log("min/max/count executed (skipped: " + settings.minMaxAndCount.countSkipedRequest + ")");
            settings.minMaxAndCount.countSkipedRequest = 0;
            loadMinMaxPriceAndBedsData(collectedData);
        }

        function loadMinMaxPriceAndBedsData(collectedData) {
            var url = "/Services/GetMinMaxPriceAndBedsData.aspx";

            $.ajax({
                timeout: 5000,
                type: 'POST',
                url: url,
                data: collectedData,
                dataType: 'json',
                error: function (xhr, status) {
                    log("ERROR accured: " + status);
                },
                success: function (data) {
                    updateMinMaxFields(data);
                }
            });
        }

        function updateMinMaxFields(data) {
            if ($("#chkIncludeAccommodationAdditionalBeds:checked"))
                settings.minMaxAndCount.$accommodationBedsMinMax.html(getMinMaxBeds(data.MinAccommodationBeds, data.MaxAccommodationBedsWithAdditionalBeds, data.AccommodationBedsFormatString, data.NoResultsString));
            else
                settings.minMaxAndCount.$accommodationBedsMinMax.html(getMinMaxBeds(data.MinAccommodationBeds, data.MaxAccommodationBeds, data.AccommodationBedsFormatString, data.NoResultsString));

            settings.minMaxAndCount.$priceMinMax.html(getMinMaxPrice(data.MinPrice, data.MaxPrice, data.PriceFormatString, data.NoResultsString));
            // end comment

            // results display top
            settings.minMaxAndCount.$propertyCountTop.text(getString(data.PropertyCount, '0'));
            settings.minMaxAndCount.$accommodationCountTop.text(getString(data.AccommodationCount, '0'));

            // results display bottom
            settings.minMaxAndCount.$propertyCountBottom.text(getString(data.PropertyCount, '0'));
            settings.minMaxAndCount.$accommodationCountBottom.text(getString(data.AccommodationCount, '0'));
        }

        function getMinMaxBeds(min, max, bedsFormatString, noResultsString) {
            var minVal = getString(min, 'error');
            var maxVal = getString(max, 'error');

            if (minVal != 'error' && maxVal != 'error') {
                return bedsFormatString.format(minVal, maxVal);
            }
            else return '<b class="error">' + noResultsString + '</b>';
        }

        function getMinMaxPrice(min, max, priceFormatString, noResultsString) {
            var minVal = getString(min, 'error');
            var maxVal = getString(max, 'error');

            if (minVal != 'error' && maxVal != 'error') {
                return priceFormatString.format(minVal, maxVal);
            }
            else return '<b class="error">' + noResultsString + '</b>';
        }

        function getString(value, defaultValue) {
            if (value == null || value == undefined)
                return defaultValue;
            return value;
        }

        // functions

        function clearSearchFields() {

            // acc types and regions/subregions...
            $("#cmbAccommodationTypes").val("");
            $("#cmbRegion").val("");
            $("#cmbSubregion").val("");
            $("#cmbCommunity").val("");
            $("#cmbCity").val("");
            
            // beds
            $("#txtNumAccommodationBeds").val("");
            $("#chkIncludeAccommodationAdditionalBeds").prop("checked", false);

            // price
            $("#txtPriceFrom").val("");
            $("#txtPriceTo").val("");

            // category
            $("#categoryStars").find('input[type="checkbox"]').prop("checked", false);
            $("#categoryApples").find('input[type="checkbox"]').prop("checked", false);
            
            // offer
            $("#offers").find('input[type="checkbox"]').prop("checked", false);

            // propertyTypes
            $("#propertyTypes").find('input[type="checkbox"]').prop("checked", false);

            // reset combox values
            loadComboData("", true);
        }

        function setActiveTab(activeButton$, contentHeight, animate) {
            if (activeButton$.hasClass("selected")) {
                // this tab is already active
                log(activeButton$.attr("id") + ": is already active");
                return;
            }

            settings.nav.container$.find("a.selected").removeClass("selected");
            activeButton$.addClass("selected");

            showHideSearchButtons();

            //setContentHeight(settings.content.container$, contentHeight, animate);
        }

        // funkcija se ne uporablja
        function setContentHeight(content$, exptectedHeight, animate) {
            if (animate) {
                log("animating...");
                var hDiff = exptectedHeight - content$.height();
                content$.animate({ 'height': '+=' + hDiff + 'px' }, 'fast', function () {
                    // animation completed
                });
            }
            else {
                content$.height(exptectedHeight);
            }
        }

        function showHideSearchButtons() {
            if (settings.nav.btnSimple$.hasClass("selected")) {
                settings.content.$simpleSearchButton.show();

                settings.content.$advancedSearchButton.hide();
                settings.content.$advancedSearchTable.hide();
            }
            else {
                settings.content.$advancedSearchButton.show();
                settings.content.$advancedSearchTable.show();

                settings.content.$simpleSearchButton.hide();
            }
        }

        function loadComboData(queryString, bUpdateMap) {
            var url = "/Services/GetComboData.aspx";

            var d = new Date();
            queryString += "&time=" + d.getTime();
            log("ajax start");
            $.ajax({
                timeout: 15000,
                type: 'GET',
                url: url,
                data: queryString,
                dataType: 'json',
                error: function (xhr, status) {
                    log("ERROR accured: " + status);
                },
                success: function (data) {
                    log("ajax completed");
                    populateData(data, bUpdateMap);
                    log("combos populated");

                    // if page is loaded show beds and price stats
                    if (settings.minMaxAndCount.pageLoad == true) {
                        settings.minMaxAndCount.pageLoad = false;
                        doMinMaxPriceAndBedsSearch();
                    }
                }
            });
        }

        function populateData(data, bUpdateMap) {
            loadCombo(data.AccommodationType, settings.combos.$comboAccommodationTypes);
            loadCombo(data.Region, settings.combos.$comboRegion);
            loadCombo(data.Subregion, settings.combos.$comboSubregion);
            loadCombo(data.Community, settings.combos.$comboCommunity);
            loadCombo(data.City, settings.combos.$comboCity);

            if (settings.syncWithMap == false) {
                // do not update map
                return;
            }

            // if bUpdateMap is undefined or false, map will not be updated
            if (bUpdateMap) {
                if (settings.combos.$comboRegion.val().length == 0 && settings.combos.$comboSubregion.val().length == 0) {
                    updateMap('ALL');
                }
                else if (settings.combos.$comboSubregion.val().length > 0) {
                    updateMap(convertId2Tag(settings.combos.$comboSubregion.val()), false);
                }
                else {
                    updateMap(convertId2Tag(settings.combos.$comboRegion.val()), true);
                }
            }
        }

        function loadCombo(comboCategory, $combo) {
            if (comboCategory.LoadItemList) {
                addOptions(comboCategory.ItemList, $combo);
            }

            if (comboCategory.SelectedItemID) {
                $combo.val(comboCategory.SelectedItemID);
            }
        }

        function addOptions(items, $combo) {
            $combo.empty();
            var optionItems = [];    // empty array of option elements
            $.each(items, function (index, item) {
                optionItems.push(createOptionElement(item));
            });

            $combo.append(optionItems);
        }

        function createOptionElement(item) {
            var $option = $("<option></option>").attr("value", item.Value).text(item.Text);
            if (item.Selected) {
                option.attr("selected", true);
            }

            return $option.get(0);
        }

        function updateCombo(tag) {
            if (tag.length == 1) {
                loadComboData("region=" + convertTag2Id(tag), false);
            }
            else if (tag.length == 2) {
                loadComboData("subregion=" + convertTag2Id(tag), false);
            }
        }

        function convertTag2Id(tag) {
            switch (tag) {
                case 'A': return '1';
                case 'A1': return '2';
                case 'A2': return '8';
                case 'B': return '15';
                case 'B1': return '33';
                case 'B2': return '16';
                case 'B3': return '25';
                case 'B4': return '20';
                case 'C': return '201';
                case 'C1': return '207';
                case 'C2': return '202';
                case 'D': return '95';
                case 'E': return '175';
                case 'E1': return '185';
                case 'E2': return '189';
                case 'E3': return '197';
                case 'E4': return '176';
                case 'F': return '114';
                case 'F1': return '122';
                case 'F2': return '139';
                case 'F3': return '115';
                case 'G': return '217';
                case 'H': return '41';
                case 'H1': return '59';
                case 'H2': return '65';
                case 'H3': return '78';
                case 'H4': return '42';
                case 'I': return '146';
                case 'I1': return '155';
                case 'I2': return '147';
            } // end switch
        }

        function convertId2Tag(id) {
            switch (id) {
                case '1': return 'A';
                case '2': return 'A1';
                case '8': return 'A2';
                case '15': return 'B';
                case '33': return 'B1';
                case '16': return 'B2';
                case '25': return 'B3';
                case '20': return 'B4';
                case '201': return 'C';
                case '207': return 'C1';
                case '202': return 'C2';
                case '95': return 'D';
                case '175': return 'E';
                case '185': return 'E1';
                case '189': return 'E2';
                case '197': return 'E3';
                case '176': return 'E4';
                case '114': return 'F';
                case '122': return 'F1';
                case '139': return 'F2';
                case '115': return 'F3';
                case '217': return 'G';
                case '41': return 'H';
                case '59': return 'H1';
                case '65': return 'H2';
                case '78': return 'H3';
                case '42': return 'H4';
                case '146': return 'I';
                case '155': return 'I1';
                case '147': return 'I2';
            } // end switch
        }

        var m_Regions = [];
        var m_RegionsNotSelectable = [];
        if (settings.webSiteID == 2) {
            // zidanice
            m_Regions = ['E3', 'E2', 'E1', 'E4'];
            m_RegionsNotSelectable = ['I1', 'I2', 'H4', 'H3', 'H1', 'F2', 'F1', 'H2', 'F3', 'G', 'D', 'C1', 'C2', 'B3', 'B2', 'B4', 'B1', 'A1', 'A2'];
        }
        else {
            // etrips
            m_Regions = ['I1', 'I2', 'H4', 'H3', 'H1', 'F2', 'E3', 'F1', 'H2', 'F3', 'G', 'E2', 'E1', 'E4', 'D', 'C1', 'C2', 'B3', 'B2', 'B4', 'B1', 'A1', 'A2'];
            m_RegionsNotSelectable = [];
        }

        //var m_Regions = ['I1', 'I2', 'H4', 'H3', 'H1', 'F2', 'E3', 'F1', 'H2', 'F3', 'G', 'E2', 'E1', 'E4', 'D', 'C1', 'C2', 'B3', 'B2', 'B4', 'B1', 'A1', 'A2'];
        //var m_RegionsNotSelectable = [];


        function setMap(p_Region) {
            var regionOrSubregion = updateMap(p_Region);

            updateCombo(regionOrSubregion, false);
        }

        function updateMap(p_Region, bShowAllRegion) {
            var nI;
            // if ALL, then selects all overlays
            if (p_Region == 'ALL') {
                // iterates through all (sub)regions and selects them
                for (nI = 0; nI < m_Regions.length; nI++) {
                    document.getElementById(m_Regions[nI]).style.visibility = 'hidden';
                }
                // hide regions that user cannot select
                for (nI = 0; nI < m_RegionsNotSelectable.length; nI++) {
                    document.getElementById(m_RegionsNotSelectable[nI]).style.visibility = 'visible';
                }

                return p_Region;
            }
            // if (sub)region is clicked
            else {
                var nCountUnselectedOther = 0;

                if (bShowAllRegion == undefined) {
                    // determines whether any other (sub)region, which is not in this group, is selected
                    // if so, then all respective region should be selected
                    // if not, only the clicked (sub)region should be selected
                    for (nI = 0; nI < m_Regions.length; nI++) {
                        nCountUnselectedOther++;

                        if (document.getElementById(m_Regions[nI]).style.visibility == 'hidden') {
                            if (p_Region[0] != m_Regions[nI][0]) {
                                bShowAllRegion = true;
                                break;
                            }
                        }
                        else {
                            nCountUnselectedOther--;
                        }
                    }
                    // if all other (sub)regions are visible, then selects all region
                    if (nCountUnselectedOther == 0) {
                        bShowAllRegion = true;
                    }
                } // end if bShowAllReion == undefined

                // iterates through all (sub)regions and takes appropriate action
                for (nI = 0; nI < m_Regions.length; nI++) {
                    if (p_Region[0] != m_Regions[nI][0]) {
                        document.getElementById(m_Regions[nI]).style.visibility = 'visible';
                    }
                    else {
                        if (bShowAllRegion || p_Region == m_Regions[nI]) {
                            document.getElementById(m_Regions[nI]).style.visibility = 'hidden';
                        }
                        else {
                            document.getElementById(m_Regions[nI]).style.visibility = 'visible';
                        }
                    }
                }

                if (bShowAllRegion) {
                    return p_Region[0];
                }
                else {
                    return p_Region;
                }
            }
        }

        function log(text) {
            if (settings.debug.enabled) {
                $("<div></div>").addClass("item").text((++settings.debug.counter) + ". " + text).appendTo(settings.debug.container$);
            }
        }
    };

})(jQuery);
