﻿function ShopsClass() {
    this.objCountrySelectionDropDownList = new Object();
    this.objMapContainer = new Object();
    this.objMap = new Object();
    this.objShopsMapContainer = new Object();
    this.objShopsMap = new Object();

    this.objShopsFiltersArray = new Array();
    this.objListContainer = new Object();
    this.objShopsTableRows = new Array();
    this.objShopsArray = new Array();

    this.nLatitude = new Number();
    this.nLongitude = new Number();
    this.nDefaultZoomLevel = new Number();

    if (ShopsClass._initialized === undefined) {

        ShopsClass.prototype.ToggleContainerVisibility = function(objClickedElement, strContainerID, strContainerBackgroundID, strMapContainerID, strListContainerID) {
            var objContainer = $("#" + strContainerID);
            var objContainerBackground = strContainerBackgroundID ? $("#" + strContainerBackgroundID) : null;

            if (objContainer.hasClass("hiddenContainer")) {
                this.objMapContainer = document.getElementById(strMapContainerID);
                this.objListContainer = document.getElementById(strListContainerID);

                var iBrowserHeight = document.documentElement.clientHeight;
                var iBrowserWidth = document.documentElement.clientWidth;

                var strBlockHeight = "250px";
                if (500 < iBrowserHeight) {
                    if (iBrowserHeight < 700)
                        strBlockHeight = "400px";
                    else {
                        if (iBrowserHeight < 900)
                            strBlockHeight = "500px";
                        else
                            strBlockHeight = "600px";
                    }
                }

                var strBlockWidth = "500px";
                if (700 < iBrowserWidth) {
                    if (iBrowserWidth < 1024)
                        strBlockWidth = "700px";
                    else {
                        if (iBrowserWidth < 1280)
                            strBlockWidth = "900px";
                        else
                            strBlockWidth = "1100px";
                    }
                }

                $(this.objMapContainer).css({ "height": strBlockHeight, "width": strBlockWidth });
                $(this.objListContainer).css({ "height": strBlockHeight, "width": strBlockWidth });

                var iMarginTop = (iBrowserHeight - objContainer.height()) / 3;
                var iMarginLeft = (iBrowserWidth - objContainer.width()) / 2;

                if (objContainerBackground)
                    objContainerBackground.height($(document).height());

                objContainer.css({ "top": iMarginTop + "px", "left": iMarginLeft + "px" });
            }

            if (objContainerBackground !== undefined)
                objContainerBackground.toggleClass("hiddenContainer");

            objContainer.toggleClass("hiddenContainer");
            if (!objContainer.hasClass("hiddenContainer")) {
                $(document).bind("ToggleContainerVisibilitybyEscKey", function(e) {
                    Shops.ToggleContainerVisibilitybyEscKey(e, { ContainerID: strContainerID, ContainerBackgroundID: strContainerBackgroundID });
                });
                $(document).keyup(function(e) {
                    $(document).trigger("ToggleContainerVisibilitybyEscKey", e);
                });
            }
            else
                $(document).unbind("ToggleContainerVisibilitybyEscKey");
        };

        ShopsClass.prototype.ToggleContainerVisibilitybyEscKey = function(e, data) {
            if (e == null) { // IE
                keycode = event.keyCode;
            } else { // FireFox
                keycode = e.which;
            }
            if (keycode == 27) {
                Shops.ToggleContainerVisibility(null, data.ContainerID, data.ContainerBackgroundID);
            }
        };

        ShopsClass.prototype.CountryChanging = function(objCountrySelectionDropDownList, strMapContainerID, strListContainerID) {
            var nSelectedCountryID = objCountrySelectionDropDownList.options[objCountrySelectionDropDownList.selectedIndex].value;
            this.Load(strMapContainerID, strListContainerID, nSelectedCountryID);
        };

        ShopsClass.prototype.SwitchSelectionMode = function(objControlLinkClicked, strActiveContainerID) {
            if (!$(objControlLinkClicked).hasClass("controlLinkActive")) {
                $(objControlLinkClicked).parent().parent().children().find("a.controlLinkActive").each(function() {
                    $(this).toggleClass("controlLinkActive").toggleClass("controlLink");
                });
                $(objControlLinkClicked).toggleClass("controlLink").toggleClass("controlLinkActive");

                if (!$(this.objMapContainer).hasClass("hiddenContainer"))
                    $(this.objMapContainer).toggleClass("hiddenContainer");

                if (!$(this.objListContainer).hasClass("hiddenContainer"))
                    $(this.objListContainer).toggleClass("hiddenContainer");

                switch (strActiveContainerID) {
                    case this.objMapContainer.id:
                        $(this.objMapContainer).toggleClass("hiddenContainer");
                        break;
                    case this.objListContainer.id:
                        $(this.objListContainer).toggleClass("hiddenContainer");
                        break;
                }
            }
        }

        ShopsClass.prototype.Load = function(strMapContainerID, strListContainerID, nCountryID) {
            var objShopsMapper = new ShopsMapperClass();

            var objCountry = objShopsMapper.GetShopsCountryByID(nCountryID);

            var objShopsCitiesArray = new Object();
            if (objCountry != null)
                objShopsCitiesArray = objShopsMapper.GetShopsCitiesByCountryID(nCountryID);

            if (objCountry != null && objCountry.Coordinate != null) {
                this.nLatitude = parseFloat(objCountry.Coordinate.GMapLatitude);
                this.nLongitude = parseFloat(objCountry.Coordinate.GMapLongitude);
                this.nDefaultZoomLevel = parseInt(objCountry.Coordinate.GMapDefaultZoomLevel);

                if (GBrowserIsCompatible())
                    this.LoadMap(strMapContainerID, objShopsCitiesArray);
                else
                    alert("Sorry, the Google Maps API is not compatible with your browser");
            }

            if (objShopsCitiesArray.length !== undefined && 0 < objShopsCitiesArray.length)
                this.LoadList(strListContainerID, objShopsCitiesArray);
        };

        ShopsClass.prototype.LoadMap = function(strMapContainerID, objShopsCitiesArray) {
            var bIsHidden = $(this.objMapContainer).hasClass("hiddenContainer");

            //Если контейнер, в котором нужно отрисовать карту, скрыт, карта не сможет правильно спозиционироваться на странице,
            //а будет все время появляться в левом верхнем углу. Чтобы избежать этого недоразумения, надо принудительно показать пустой контейнер
            //перед инициализацией объекта карты, а потом снова выключить его
            if (bIsHidden)
                $(this.objMapContainer).toggleClass("hiddenContainer");
            this.objMap = new GMap2(this.objMapContainer);
            if (bIsHidden)
                $(this.objMapContainer).toggleClass("hiddenContainer");

            this.objMap.setMapType(G_PHYSICAL_MAP);
            this.objMap.addControl(new GSmallZoomControl3D());

            //Отрисоввываем карту страны
            this.objMap.setCenter(new GLatLng(this.nLatitude, this.nLongitude), this.nDefaultZoomLevel);

            //Добавляем на отрисованную карту леденцы городов
            if (objShopsCitiesArray.length !== undefined) {
                var mgr = new MarkerManager(this.objMap);
                for (var i = 0; i < objShopsCitiesArray.length; i++) {
                    var objCity = objShopsCitiesArray[i];

                    var objIcon = new GIcon();
                    objIcon.image = "/img/gmap_marker.png";
                    objIcon.iconSize = new GSize(44, 42);
                    objIcon.shadow = "/img/gmap_marker_shadow.png";
                    objIcon.shadowSize = new GSize(44, 42);
                    objIcon.iconAnchor = new GPoint(17, 41);

                    if (objCity.Coordinate != null) {
                        var objPoint = new GLatLng(parseFloat(objCity.Coordinate.GMapLatitude), parseFloat(objCity.Coordinate.GMapLongitude));
                        var objCityMarker = this.CreateCityMarker(objPoint, objIcon, objCity);

                        if (objCity.IsDefault)
                            this.objMap.addOverlay(objCityMarker);
                        else {
                            if (!objCity.IsSatellite)
                                mgr.addMarker(objCityMarker, 3);
                            else
                                mgr.addMarker(objCityMarker, 7); //показываем города-спутники на карте только когда зум больше 7
                        }
                    }
                }
            }
        }

        ShopsClass.prototype.CreateCityMarker = function(objPoint, objIcon, objShopsCity) {
            var objMarker = new GMarker(objPoint, { icon: objIcon, title: objShopsCity.LocalizedName });
            GEvent.addListener(objMarker, "click", function() {
                window.location.href = "/Shops/?city=" + objShopsCity.ID;
            });
            return objMarker;
        }

        ShopsClass.prototype.LoadCityShops = function(nCityID, strShopsFilterID, strMapContainerID, strListContainerID) {
            if (!isNaN(parseInt(nCityID)) && GBrowserIsCompatible()) {
                var objShopsMapper = new ShopsMapperClass();
                var objShopsCity = objShopsMapper.GetShopsCityByID(nCityID);
                if (objShopsCity != null && objShopsCity.Coordinate != null) {
                    this.objShopsMapContainer = document.getElementById(strMapContainerID);
                    this.objShopsMap = new GMap2(this.objShopsMapContainer);
                    this.objShopsMap.enableContinuousZoom();
                    this.objShopsMap.setCenter(new GLatLng(parseFloat(objShopsCity.Coordinate.GMapLatitude), parseFloat(objShopsCity.Coordinate.GMapLongitude)), parseInt(objShopsCity.Coordinate.GMapDefaultZoomLevel));
                    this.objShopsMap.addControl(new GLargeMapControl3D());
                    this.objShopsMap.addControl(new GScaleControl());
                    this.objShopsMap.addControl(new GMenuMapTypeControl());

                    this.objShopsArray = objShopsMapper.GetShopsArray(nCityID);
                    if (this.objShopsArray !== undefined && 0 < this.objShopsArray.length) {
                        this.objShopsFiltersArray = $("#" + strShopsFilterID).find(":checkbox");
                        this.objShopsTableRows = $("#" + strListContainerID).find("table :first").find("tr");
                        this.RefreshCityShopsMap(this.objShopsArray);
                        var objShopsListContainer = $("#" + strListContainerID);
                        objShopsListContainer.find("#ShopsListHeader").text(objShopsCity.LocalizedName);
                    }

                    var objCitySatellitesArray = objShopsMapper.GetCitySatellites(nCityID);
                    if (objCitySatellitesArray !== undefined && 0 < objCitySatellitesArray.length)
                        this.RefreshCitySatellitesMap(objCitySatellitesArray);
                }
            }
            else
                alert("Sorry, the Google Maps API is not compatible with your browser");
        }

        ShopsClass.prototype.LoadSingleBranch = function(nShopID, strMapContainerID) {
            if (!isNaN(parseInt(nShopID)) && GBrowserIsCompatible()) {
                var objShopsMapper = new ShopsMapperClass();
                var objShopProfile = objShopsMapper.GetShopByID(nShopID);
                if (objShopProfile != null) {
                    this.objShopsMapContainer = document.getElementById(strMapContainerID);
                    this.objShopsMap = new GMap2(this.objShopsMapContainer);
                    this.objShopsMap.enableContinuousZoom();

                    var fLatitude = new Number(NaN);
                    var fLongitude = new Number(NaN);

                    if (objShopProfile.Address.Coordinate != null) {
                        fLatitude = parseFloat(objShopProfile.Address.Coordinate.GMapLatitude);
                        fLongitude = parseFloat(objShopProfile.Address.Coordinate.GMapLongitude);

                        if (!isNaN(fLatitude) && !isNaN(fLongitude)) {
                            if (!isNaN(objShopProfile.Address.Coordinate.GMapDefaultZoomLevel))
                                this.objShopsMap.setCenter(new GLatLng(fLatitude, fLongitude), parseInt(objShopProfile.Address.Coordinate.GMapDefaultZoomLevel));
                            else
                                this.objShopsMap.setCenter(new GLatLng(fLatitude, fLongitude));
                        }
                    }

                    this.objShopsMap.addControl(new GLargeMapControl3D());
                    this.objShopsMap.addControl(new GScaleControl());
                    this.objShopsMap.addControl(new GMenuMapTypeControl());

                    this.objShopsArray = new Array();
                    this.objShopsArray[0] = objShopProfile;
                    this.RefreshCityShopsMap(this.objShopsArray);
                }
            }
            else
                alert("Sorry, the Google Maps API is not compatible with your browser");
        }

        ShopsClass.prototype.RefreshCityShopsMap = function(objLocalShopsArray) {
            if (objLocalShopsArray.length !== undefined) {
                for (var i = 0; i < objLocalShopsArray.length; i++) {
                    var objShopProfile = objLocalShopsArray[i];

                    var fLatitude = new Number(NaN);
                    var fLongitude = new Number(NaN);

                    if (objShopProfile.Address.Coordinate != null) {
                        fLatitude = parseFloat(objShopProfile.Address.Coordinate.GMapLatitude);
                        fLongitude = parseFloat(objShopProfile.Address.Coordinate.GMapLongitude);

                        if (!isNaN(fLatitude) && !isNaN(fLongitude)) {
                            var objPoint = new GLatLng(fLatitude, fLongitude);
                            var objMarker = this.CreateShopMarker(objPoint, objShopProfile);
                            this.objShopsMap.addOverlay(objMarker);
                        }
                    }
                }
            }
        }

        ShopsClass.prototype.RefreshCitySatellitesMap = function(objLocalCitiesArray) {
            if (objLocalCitiesArray.length !== undefined) {
                var mgr = new MarkerManager(this.objShopsMap);
                for (var i = 0; i < objLocalCitiesArray.length; i++) {
                    var objCity = objLocalCitiesArray[i];

                    var objIcon = new GIcon();
                    objIcon.image = "/img/gmap_marker.png";
                    objIcon.iconSize = new GSize(44, 42);
                    objIcon.shadow = "/img/gmap_marker_shadow.png";
                    objIcon.shadowSize = new GSize(44, 42);
                    objIcon.iconAnchor = new GPoint(17, 41);

                    if (objCity.Coordinate != null) {
                        var objPoint = new GLatLng(parseFloat(objCity.Coordinate.GMapLatitude), parseFloat(objCity.Coordinate.GMapLongitude));
                        var objCityMarker = this.CreateCityMarker(objPoint, objIcon, objCity);

                        mgr.addMarker(objCityMarker, 7); //показываем города-спутники на карте только когда зум больше 7
                    }
                }
            }
        }

        ShopsClass.prototype.CreateShopMarker = function(objPoint, objShopProfile) {
            var objIcon = new GIcon();
            objIcon.image = "/img/gmap_marker.png";
            objIcon.iconSize = new GSize(44, 42);
            objIcon.shadow = "/img/gmap_marker_shadow.png";
            objIcon.shadowSize = new GSize(44, 42);
            objIcon.iconAnchor = new GPoint(17, 41);
            objIcon.infoWindowAnchor = new GPoint(15, 0); //new GPoint(15, 44);

            var objMarker = new GMarker(objPoint, { icon: objIcon, title: objShopProfile.LocalizedName });
            GEvent.addListener(objMarker, "click", function() {
                var strBranchBubbleContent = "<div style=\"width: 350px;\">";
                strBranchBubbleContent += "<p style=\"font-size: 11pt; line-height: 15pt;\"><a class=\"darkGreen\" href=\"/Shops/ShopDetails.aspx?ID=" + objShopProfile.ID + "\">" + objShopProfile.LocalizedName + "</a></p>";
                strBranchBubbleContent += "<p>" + objShopProfile.Address.StreetAddress + "</p>";

                if (objShopProfile.WorkingHours !== undefined && objShopProfile.WorkingHours != "")
                    strBranchBubbleContent += "<p style=\"margin-top: 0.3em; line-height: 11pt;\" class=\"gray\">Режим работы: " + objShopProfile.WorkingHours + "</p>";

                /*if (objShopProfile.IsTwentyFourHour || objShopProfile.LiveTV || objShopProfile.Bar) {
                    strBranchBubbleContent += "<div style=\"margin-top: 0.5em; padding-bottom: 1.5em;\"><ul class=\"inlineItems\">"
                    if (objShopProfile.IsTwentyFourHour)
                        strBranchBubbleContent += "<li style=\"margin-right: 25px;\"><img src=\"/img/empty_pixel.gif\" width=\"19\" height=\"19\" class=\"branchAttribute1\" alt=\"Открыт круглосуточно\" title=\"Открыт круглосуточно\" /></li>";
                    if (objShopProfile.LiveTV)
                        strBranchBubbleContent += "<li style=\"margin-right: 25px;\"><img src=\"/img/empty_pixel.gif\" width=\"19\" height=\"19\" class=\"branchAttribute2\" alt=\"Прямые трансляции соревнований\" title=\"Прямые трансляции соревнований\" /></li>";
                    if (objShopProfile.Bar)
                        strBranchBubbleContent += "<li style=\"margin-right: 25px;\"><img src=\"/img/empty_pixel.gif\" width=\"19\" height=\"19\" class=\"branchAttribute3\" alt=\"Бар\" title=\"Бар\" /></li>";
                    strBranchBubbleContent += "</ul></div>";
                }*/
                strBranchBubbleContent += "</div>";
                objMarker.openInfoWindowHtml(strBranchBubbleContent);
            });
            return objMarker;
        }

        ShopsClass.prototype.LoadList = function(strListContainerID, objShopsCitiesArray) {
            if (objShopsCitiesArray.length !== undefined) {
                var nContainerWidth = $(this.objListContainer).width();

                var nColumnsCount = 3;
                if (500 < nContainerWidth) {
                    nColumnsCount = 4;
                    if (900 < nContainerWidth)
                        nColumnsCount = 5;
                    else
                        nColumnsCount = 4;
                }

                var nCitiesNumber = objShopsCitiesArray.length;

                var nItemsPerColumn = (nCitiesNumber / nColumnsCount) | 0;
                if (nCitiesNumber % nColumnsCount != 0)
                    nItemsPerColumn += 1;

                var nColumnWidth = nContainerWidth / nColumnsCount | 0;
                var nColumnLeftMargin = nColumnWidth * 0.3 | 0
                var nCapsLeftMargin = 0 - (nColumnWidth * 0.15 | 0);

                var strShopsCitiesList = "";
                var chFirstChar = "";
                for (var i = 0; i < nColumnsCount; i++) {
                    var strColumn = "<div class=\"column\" style=\"width: " + nColumnWidth + "px;\"><div class=\"columnContent\" style=\"margin-left: " + nColumnLeftMargin + "px;\">";

                    var nStartPos = i * nItemsPerColumn;
                    var nEndPos = nStartPos + nItemsPerColumn;

                    strColumn += "<ul>";

                    for (var elem = nStartPos; elem < nEndPos; elem++) {
                        var objCity = objShopsCitiesArray[elem];
                        if (objCity !== undefined) {
                            var chItemFirstChar = objCity.LocalizedName.substring(0, 1);

                            strColumn += "<li>";

                            if (chItemFirstChar != chFirstChar) {
                                strColumn += "<span class=\"caps lightGray\" style=\"margin-left: " + nCapsLeftMargin + "px;\">" + chItemFirstChar + "</span>";
                            }
                            chFirstChar = chItemFirstChar;

                            strColumn += "<a href=\"/Shops/?city=" + objCity.ID + "\">" + objCity.LocalizedName + "</a></li>";
                        }
                    }

                    strColumn += "</ul>";

                    strColumn += "</div></div>";

                    strShopsCitiesList += strColumn;
                }

                /*var strShopsCitiesList = "<ul class=\"shopsCities\">";
                for (var i = 0; i < objShopsCitiesArray.length; i++) {
                var objCity = objShopsCitiesArray[i];
                strShopsCitiesList += "<li><a href=\"/Shops/?city=" + objCity.ID + "\">" + objCity.LocalizedName + "</a></li>";
                }
                strShopsCitiesList += "</ul>";*/

                $(this.objListContainer).html(strShopsCitiesList);
            }
            else
                $(this.objListContainer).html("");
        }

        ShopsClass.prototype.RebuildFilterHashtable = function() {
            var objCheckedFiltersArray = new Array();
            this.objShopsFiltersArray.each(function() {
                if (this.checked)
                    objCheckedFiltersArray.push($(this).val());
            });
            return objCheckedFiltersArray;
        }

        ShopsClass.prototype.ApplyAttributesFilter = function() {
            var objCheckedFiltersArray = this.RebuildFilterHashtable();

            var bAreAllFiltersDisabled = objCheckedFiltersArray == 0;
            if (!bAreAllFiltersDisabled) {
                var objShopProfilePositionsFilteredArray = new Array();
                for (var i in this.objShopsArray) {
                    var objShopProfile = this.objShopsArray[i];

                    var bAcceptable = new Boolean();
                    for (var n in objCheckedFiltersArray) {
                        var strFilterName = objCheckedFiltersArray[n];
                        if (objShopProfile.hasOwnProperty(strFilterName) && objShopProfile[strFilterName])
                            bAcceptable = true;
                        else {
                            bAcceptable = false;
                            break;
                        }
                    }

                    if (bAcceptable)
                        objShopProfilePositionsFilteredArray.push(i);
                }

                if (0 < objShopProfilePositionsFilteredArray.length) {
                    this.objShopsTableRows.each(function() {
                        $(this).hide();
                    });
                    this.objShopsMap.clearOverlays();

                    var objShopsFilteredArray = new Array();
                    for (var pos in objShopProfilePositionsFilteredArray) {
                        var iRowPosition = objShopProfilePositionsFilteredArray[pos] * 2;
                        $(this.objShopsTableRows[iRowPosition]).show();
                        $(this.objShopsTableRows[iRowPosition + 1]).show();

                        var iBranchPosition = objShopProfilePositionsFilteredArray[pos];
                        objShopsFilteredArray.push(this.objShopsArray[iBranchPosition]);
                    }
                    this.RefreshCityShopsMap(objShopsFilteredArray);
                }
            }
            else {
                this.RefreshCityShopsMap(this.objShopsArray);
                this.objShopsTableRows.each(function() {
                    $(this).show();
                });
            }
        }

        ShopsClass.prototype.Dispose = function() {
            GUnload();
        }

        ShopsClass._initialized = true;
    }
}

var Shops = new ShopsClass();