//отмена запроса
const CT = axios.CancelToken;
let cancel,
    cancelCoord,
    cancelFullStats,
    lastTime,
    cancelPromices = {
        checkUpdateHeating: null,
        UpdateHydrantsFromGoogleSheet: null,
        UpdateHeatingPointsFromGoogleSheet: null,
        UpdateStopsSheltersFromGoogleSheet: null,
        UpdateFoodOutletsromGoogleSheet: null,
        UpdateHospitalsFromGoogleSheet: null,
        UpdatePolyclinicsFromGoogleSheet: null,
        UpdatePharmaciesFromGoogleSheet: null,
        UpdateGasStationsFromGoogleSheet: null,
        UpdateVetClinicsFromGoogleSheet: null,
        UpdatePetShopsFromGoogleSheet: null,
        UpdateNonFoodShopsFromGoogleSheet: null,
        UpdateLsMarketsFromGoogleSheet: null,
        UpdateFoodShopsFromGoogleSheet: null,
        UpdatePoliceFromGoogleSheet: null,
        UpdateSheltersFromGoogleSheet: null,
        UpdateWaterSourcesFromGoogleSheet: null,
        UpdateInvicibilityFromGoogleSheet: null,
        UpdateBombSheltersFromGoogleSheet: null,
        UpdateWaterDrinkPointsFromGoogleSheet: null,
    };

//источник данных
const store = new Vuex.Store({
    state: {
        mapStore: {
            map: null,
            //подложки
            basis: [
                {
                    id: 0,
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer',
                    type: 'dynamic',
                    dataType: 'basic',
                    visibility: true,
                    map_visibility:false,
                    layerIds: [/*5,*/ 7, 6],
                    name: 'Підоснова Харків',                    
                    opacity: 1,
                    identScale: 8000,
                    identify: [
                        //{
                        //    id: 5,
                        //    title: 'Вулиці міста',
                        //    identityFields: [
                        //        { name: 'FULL_UA', description: 'Назва' },
                        //        { name: 'DEKOMMUN_UA', description: 'Інша назва' }
                        //    ],
                        //    tocName: 'Вулиці міста',
                        //    controller: false,
                        //    mainField: 'FULL_UA'
                        //},
                        {
                            id: 6,
                            title: 'Будівлі',
                            identityFields: [
                                { name: 'FULLADDRUA', description: 'Адреса' },
                                { name: 'FLOOR', description: 'Поверховість' },
                                //{ name: 'BT_ID', description: 'Призначення' },
                                {
                                    name: 'bindToServices',
                                    description: 'Обслуговуючі установи',
                                    bindToServices: [
                                        {
                                            name: 'Мед установи',
                                            pre_url: 'Home/GetHospitalsByAddress?addressId=',
                                            url: 'Home/GetHospitalsByAddress?addressId=',
                                            type: 'medicine',
                                            layerId: 2,
                                            preField:'AR_ID',
                                            field: 'OBJECTID'
                                        },
                                        {
                                            name: 'Школа',
                                            pre_url: 'Home/GetPrimarySchoolByAddress?addressId=',
                                            //url: '/Home/GetPrimarySchoolByAddress?addressId=',
                                            url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer/0/query?where=institutionIdentifier_=',
                                            //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer/0/query?where=institutionIdentifier_=',
                                            url_second_part: '&outFields=*&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&returnGeometry=true&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=pjson',
                                            type: 'scool',
                                            layerId: 3,
                                            preField: 'AR_ID',
                                            field:'institutionIdentifier_'
                                        },
                                        //{
                                        //    name: 'Укриття',
                                        //    pre_url: 'Home/GetBombSheltersByAddress?addressId=',
                                        //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer/14/query?where=inData_AID=',
                                        //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer/14/query?where=inData_AID=',
                                        //    url_second_part: '&outFields=*&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&returnGeometry=true&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=pjson',
                                        //    type: 'bombshelters',
                                        //    layerId: 15,
                                        //    preField: 'AR_ID',
                                        //    field:'inData_AID'
                                        //},
                                        {
                                            //новий сервіс
                                            name: 'Укриття',
                                            pre_url: 'Home/GetBombSheltersByAddress?addressId=',
                                            url: 'https://smart.khmr.gov.ua/arcgis/rest/services/googlesheetsdata/MapServer/0/query?where=AR_ID=',
                                            //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/googlesheetsdata/MapServer/0/query?where=AR_ID=',
                                            url_second_part: '&outFields=*&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&returnGeometry=true&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=pjson',
                                            type: 'bombshelters',
                                            layerId: 15,
                                            preField: 'AR_ID',
                                            field: 'AR_ID'
                                        },
                                        //{
                                        //    name: 'Об\'єднання',
                                        //    type: 'osbb_nom',
                                        //    layerId: 10,
                                        //    field: 'osbb_nom',
                                        //    eventName: 'showMoreForBuilds',
                                        //}
                                    ]
                                },
                            ],
                            tocName: 'Будівлі і споруди',
                            controller: false,
                            mainField: 'FULLADDRUA',
                            addAdmRayon:true
                        }
                    ],
                    token: {
                        need: false,
                        str: ''
                    }
                },
                //{
                //    id: 2,
                //    Name: 'Satelite',
                //    alias: 'World Imagery by ESRI',
                //    url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
                //    attributions: ['Powered by Esri', 'Source: Esri, DigitalGlobe, GeoEye, Earthstar Geographics, CNES/Airbus DS, USDA, USGS, AeroGRID, IGN, and the GIS User Community'],
                //    zoom: 5,
                //    maxZoom: 18,
                //    minZoom: 5,
                //    type: 'base',
                //    service: "tile",
                //    serviceType: "tile",
                //    visible: false,
                //},
                //{
                //    id: 1,
                //    url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
                //    type: 'basemap',
                //    dataType: 'basic',
                //    visibility: true,
                //  map_visibility:true,
                //    //layerIds: [0],
                //    name: 'World Imagery by ESRI',
                //    //opacity: 0.2,
                //    token: {
                //        need: false,
                //        str: ''
                //    }
                //},
                //{
                //    id: 1,
                //    url: 'https://ar.citynet.kharkov.ua/arcgis/rest/services/web_500_cl/MapServer',
                //    type: 'dynamic',
                //    dataType: 'basic',
                //    visibility: false,
                //  map_visibility:false,
                //    layerIds: [0],
                //    name: 'карта М 1:500',
                //    opacity: 0.2,
                //    token: {
                //        need: true,
                //        str:''
                //    }
                //},
                //{
                //    id: 2,
                //    url: 'https://ar.citynet.kharkov.ua/arcgis/rest/services/web_500_New_Dyn_cl/MapServer',
                //    type: 'dynamic',
                //    dataType: 'basic',
                //    visibility: false,
                //  map_visibility:false,
                //    layerIds: [0],
                //    name: 'карта М 1:500 NEW',
                //    opacity: 0.2,
                //    token: {
                //        need: true,
                //        str: ''
                //    }
                //},
                //{
                //    id: 3,
                //    url: 'https://ar.citynet.kharkov.ua/arcgis/rest/services/web_2000_cl/MapServer',
                //    type: 'dynamic',
                //    dataType: 'basic',
                //    visibility: false,
                //  map_visibility:false,
                //    layerIds: [0],
                //    name: 'карта М 1:2000',
                //    opacity: 0.2,
                //    token: {
                //        need: true,
                //        str: ''
                //    }
                //},
                //{
                //    id: 4,
                //    url: 'https://ar.citynet.kharkov.ua/arcgis/rest/services/web_ortho2012_cl/MapServer',
                //    type: 'dynamic',
                //    dataType: 'basic',
                //    visibility: false,
                //  map_visibility:false,
                //    layerIds: [0],
                //    name: 'Ортофотоплан',
                //    opacity: 0.7,
                //    token: {
                //        need: true,
                //        str: ''
                //    }
                //}
                //,
                //{
                //    id: 5,
                //    url: 'https://map.land.gov.ua/geowebcache/service/wms?tiled=true',
                //    type: 'wms',
                //    dataType: 'basic',
                //    visibility: true,
                //  map_visibility:false,
                //    layerIds: [2],
                //    name: 'Кадастрова карта',
                //    opacity: 1,
                //    token: {
                //        need: false,
                //        str: ''
                //    }
                //}
                //,
                // {
                //    id: 6,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    // url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/zhill_fond_munic/MapServer',
                //    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //     dataType: 'basic',
                //    type: 'feature',
                //    visibility: true,
                //  map_visibility:false,
                //    name: 'clear',
                //    layerIds: [10],
                //    //tolerance: 10,
                //    //order:1,
                //    //dataType: 'layer',
                //    geometryType: 'Polygon',
                //     nameVectorLayer: 'clear',
                //    opacity: 0,
                //    identScale: 0,
                //    identify: [
                //        {
                //            id: 6,
                //            title: "clear",
                //            identityFields: [
                //                { name: 'FULLADDRUA', description: 'Адреса' },
                //                { name: 'FLOOR', description: 'Поверховість' },
                //                { name: 'BAL_TYPE', description: 'Вид об\'єднання' },
                //                { name: 'BAL_NAME', description: 'Найменування об\'єднання' },
                //                { name: 'BAL_BOSS', description: 'ПІБ голови об\'єднання (за&#160;наявністю)' },
                //                { name: 'DIST', description: 'Район міста' },
                //                { name: 'STR_TYPE', description: 'Тип вулиці' },
                //                { name: 'STR_NAME', description: 'Найменування вулиці' },
                //                { name: 'STR_NUM', description: '№ будинку' },
                //                { name: 'STR_SUFF', description: 'Літера, дробова частина №' },
                //                { name: 'STR_BLOCK', description: 'Корпус, під\'їзд' },
                //                { name: 'commnts', description: 'Ділянка КП Жилкомсевіс' },
                //                { name: 'balancer', description: 'Обслуговування' },
                //            ],
                //            tocName: 'clear',
                //            controller: false,
                //            bindToAddress: false
                //        }
                //     ],
                //                        token: {
                //        need: false,
                //        str: ''
                //    }
                //},
            ],
            //проекты
            projects: [
                //{
                //    id: 0,
                //    visibility: false,
                //    name: 'Розриття',
                //    iconNav: 'Розриття <i class="material-icons"><img src="/opendataportal/Images/nav_head_icon_0.png"></i>',
                //    //iconNav: 'Розриття <span class="material-icons"> <i class="fa fa-road" aria-hidden="true"></i></span>',
                //    iconToc: '<i class="material-icons"><img src="/opendataportal/Images/toc_form_icon_0.png"></i><span class="caret"></span>Розриття ',
                //    //iconToc: '<span class="material-icons"> <i class="fa fa-road" aria-hidden="true"></i></span><span class="caret"></span>Розриття ',
                //    statistic: {
                //        data: [
                //            {
                //                id: 0,
                //                labels: [],
                //                datasets: [
                //                    {
                //                        label: 'Кількість по районно',
                //                        backgroundColor: [
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)',
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)',
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)'
                //                        ],
                //                        data: []
                //                    }
                //                ],
                //                title: 'Кількість аварійних розриттів з поділом по районах',
                //                isShowed: false,
                //                content: '',
                //                fields: [],
                //                notifyData: [],
                //                method: 'GetDugStat',
                //                filtering: false,
                //                type: 0,
                //                class: 'short',
                //                vuexMethod: 'GetDugShortStatistic'
                //            },
                //            {
                //                id: 1,
                //                labels: [],
                //                datasets: [
                //                    {
                //                        label: 'Статистика за тематикою',
                //                        backgroundColor: [
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)',
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)',
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)'
                //                        ],
                //                        data: []
                //                    }
                //                ],
                //                method: 'GetDugStat',
                //                title: 'Розподіл аварійних заявок за типом комунікації',
                //                filtering: false,
                //                type: 1,
                //                isShowed: true
                //                //class: 'short'
                //            },
                //            {
                //                id: 2,
                //                datasets: [
                //                    {
                //                        label: 'Кіль-ть аварійних заявок',
                //                        data: [],
                //                        type: 'line',
                //                        backgroundColor: 'rgba(255, 255, 255, 1)',
                //                        borderColor: 'rgba(141, 108, 160, 1)',
                //                        fill: false,
                //                        borderDash: [3],
                //                        pointBorderWidth: 2,
                //                        pointRadius: 3,
                //                        pointHoverRaius: 5,
                //                        lineTension: 0.3,
                //                        //order: 2,
                //                        yAxisID: 'B',
                //                        lineTension: 0,
                //                    },
                //                    {
                //                        type: 'bar',
                //                        label: 'Середній час виконання заявок (дні)',
                //                        data: [],
                //                        backgroundColor: [
                //                            'rgba(255, 99, 132, 0.8)',
                //                            'rgba(54, 162, 235, 0.8)',
                //                            'rgba(255, 206, 86, 0.8)',
                //                            'rgba(75, 192, 192, 0.8)',
                //                            'rgba(255, 99, 132, 0.8)',
                //                            'rgba(54, 162, 235, 0.8)',
                //                            'rgba(255, 206, 86, 0.8)',
                //                            'rgba(75, 192, 192, 0.8)',
                //                            'rgba(255, 99, 132, 0.8)',
                //                            'rgba(54, 162, 235, 0.8)',
                //                            'rgba(255, 206, 86, 0.8)',
                //                            'rgba(75, 192, 192, 0.8)'
                //                        ],
                //                        //order: 1,
                //                        yAxisID: 'A',
                //                    }
                //                ],
                //                labels: [],
                //                method: 'GetDurationStat',
                //                title: 'Аварійні заявки та швидкість їх закриття (усереднено)',
                //                filtering: false,
                //                type: 2,
                //                class: 'long',
                //                vuexMethod: 'GetDugMixedStatistic'
                //            },
                //            {
                //                id: 3,
                //                datasets: [
                //                    {
                //                        label: 'Кіль-ть аварійних заявок',
                //                        data: [],
                //                        type: 'line',
                //                        backgroundColor: 'rgba(255, 255, 255, 1)',
                //                        borderColor: 'rgba(141, 108, 160, 1)',
                //                        borderDash: [3],
                //                        pointBorderWidth: 2,
                //                        pointRadius: 3,
                //                        pointHoverRaius: 5,
                //                        lineTension: 0.3,
                //                        fill: false,
                //                        //order: 2,
                //                        yAxisID: 'B',
                //                    },
                //                    {
                //                        type: 'bar',
                //                        label: 'Середній час виконання заявок (дні)',
                //                        data: [],
                //                        backgroundColor: [
                //                            'rgba(255, 99, 132, 0.8)',
                //                            'rgba(54, 162, 235, 0.8)',
                //                            'rgba(255, 206, 86, 0.8)',
                //                            'rgba(75, 192, 192, 0.8)',
                //                            'rgba(255, 99, 132, 0.8)',
                //                            'rgba(54, 162, 235, 0.8)',
                //                            'rgba(255, 206, 86, 0.8)',
                //                            'rgba(75, 192, 192, 0.8)',
                //                            'rgba(255, 99, 132, 0.8)',
                //                            'rgba(54, 162, 235, 0.8)',
                //                            'rgba(255, 206, 86, 0.8)',
                //                            'rgba(75, 192, 192, 0.8)'
                //                        ],
                //                        //order: 1,
                //                        yAxisID: 'A',
                //                    }
                //                ],
                //                labels: [],
                //                method: 'GetYearsDurationStat',
                //                title: 'По роках',
                //                filtering: false,
                //                type: 3,
                //                class: 'long',
                //                vuexMethod: 'GetDugYearsMixedStatistic',
                //                types: [],
                //                data: []
                //            }
                //        ],
                //        filtering: false,
                //        defaultDays: 0,
                //    },
                //    notify: {
                //        title: 'Чи знаєте ви що:',
                //        content: 'проект "Розриття" дає змогу дізнатись тип розриття та його граничний строк!'
                //    }
                //},
                {
                    id: 7,
                    visibility: false,
                    name: 'Житло',
                    title: 'Комунальне житло, ОСББ, ЖК та ЖБК',
                    //iconNav: 'Житло <i class="material-icons"><img src="/opendataportal/Images/nav_head_icon_0.png"></i>',
                    iconNav: '<span class="project-item-name">Житло</span> <span class="material-icons"> <i class="fa fa-home" aria-hidden="true"></i></span>',
                    //iconToc: '<i class="material-icons"><img src="/opendataportal/Images/toc_form_icon_0.png"></i><span class="caret"></span>Житло ',
                    iconToc: `<span class="material-icons">
                                <i class="fa fa-home" aria-hidden="true"></i>
                            </span>
                            <span style="display: flex; flex-wrap: wrap;">
                                Житло
                            </span>
                            
                            <div class="caret-container"><span class="caret"></span></div>`,

                    //проект з опаленням
                    //iconToc: `<span class="material-icons">
                    //            <i class="fa fa-home" aria-hidden="true"></i>
                    //        </span>
                    //        <span class="caret"></span>
                    //        <span style="display: flex; flex-wrap: wrap;">
                    //            Житло
                    //                <span style="text-transform:lowercase;">
                    //                    <span class="item-group-space">&#160;</span>
                    //                    (підключення опалення)
                    //                </span>
                    //        </span>`,
                    statistic: {
                        data: [
                            {
                                id: 0,
                                labels: [],
                                datasets: [
                                    {
                                        datalabels: {
                                            align: 'left',
                                            textShadowColor: 'white',
                                            textShadowBlur: 10,
                                            formatter: function (value, context) {
                                                return (value == 0 ? '' : value );
                                            }
                                        },
                                        label: 'Очікується',
                                        backgroundColor: 'rgba(54, 162, 235, 1)',
                                        data: []
                                    },
                                    {
                                        datalabels: {
                                            align: 'center',
                                            textShadowColor: 'white',
                                            textShadowBlur: 10,
                                            formatter: function (value, context) {
                                                return (value == 0 ? '' : value );
                                            }
                                        },
                                        label: 'Підключено',
                                        backgroundColor:  'rgba(255, 99, 132, 1)',
                                        data: []
                                    },
                                    {
                                        datalabels: {
                                            align: 'right',
                                            textShadowColor: 'white',
                                            textShadowBlur: 10,
                                            formatter: function (value, context) {
                                                return (value == 0 ? '' : value);
                                            }
                                        },
                                        label: 'Завоздушено',
                                        backgroundColor: 'rgba(255, 206, 86, 1)',
                                        data: []
                                    },
                                ],
                                title: 'Кількість будинків підключених до опалення по районах',
                                isShowed: false,
                                content: '',
                                fields: [],
                                notifyData: [],
                                method: 'GetHeatingStat',
                                filtering: false,
                                type: 4,
                                class: 'short',
                                vuexMethod: 'GetStatistic'
                            },
                            {
                                id: 1,
                                labels: ['Очікується','Підключено','Завоздушення'],
                                datasets: [
                                    {
                                        label: 'Статистика за тематикою',
                                        backgroundColor: [
                                            'rgba(54, 162, 235, 1)',
                                            'rgba(255, 99, 132, 1)',
                                            'rgba(255, 206, 86, 1)',
                                        ],
                                        data: []
                                    }
                                ],
                                method: 'GetHeatingStat',
                                title: 'Загальна статистика по підключенням опалення',
                                filtering: false,
                                type: 1,
                                isShowed: true
                                //class: 'short'
                            },
                        ],
                        filtering: false,
                        defaultDays: 0,
                    },
                    notify: {
                        title: 'Чи знаєте ви що:',
                        content: 'проект "Житло" дає змогу дізнатись про будинки, їх обслуговуючі організації та стан підключення опалення!'
                    }
                },
                //{
                //    id: 1,
                //    visibility: false,
                //    name: 'Реклама та МАФ',
                //    title: 'Рекламні конструкції (дозволи на розміщення та власники), МАФ',
                //    iconNav: '<span class="project-item-name">Реклама та МАФ</span> <i class="material-icons"><img src="/opendataportal/Images/nav_head_icon_1.png"></i>',
                //    iconToc: '<i class="material-icons"><img src="/opendataportal/Images/toc_form_icon_1.png"></i><span class="caret"></span>Реклама та МАФ ',
                //    notify: {
                //        title: 'Чи знаєте ви що:',
                //        content: 'проект "Реклама" відображає замовника та тип дозволеної реклами!'
                //    }
                //},
                //{
                //    id: 1,
                //    visibility: false,
                //    name: 'Реклама',
                //    title: 'Рекламні конструкції (дозволи на розміщення та власники)',
                //    iconNav: '<span class="project-item-name">Реклама</span> <i class="material-icons"><img src="/opendataportal/Images/nav_head_icon_1.png"></i>',
                //    iconToc: '<i class="material-icons"><img src="/opendataportal/Images/toc_form_icon_1.png"></i><span class="caret"></span>Реклама ',
                //    notify: {
                //        title: 'Чи знаєте ви що:',
                //        content: 'проект "Реклама" відображає замовника та тип дозволеної реклами!'
                //    }
                //},
                //{
                //    id: 1,
                //    visibility: false,
                //    name: 'МАФ',
                //    title: 'МАФ',
                //    //iconNav: '<span class="project-item-name">МАФ</span> <span class="material-icons"><i class="fa fa-shopping-basket"></i></span>',
                //    //iconToc: '<span class="material-icons"><i class="fa fa-shopping-basket"></i></span><span class="caret"></span>МАФ ',
                //    iconNav: '<span class="project-item-name">МАФ</span> <span class="material-icons">storefront</span>',
                //    iconToc: '<span class="material-icons">storefront</span><span class="caret"></span>МАФ ',
                //    notify: {
                //        title: 'Чи знаєте ви що:',
                //        content: 'проект "МАФ" відображає місцезнаходження архітектурної форми!'
                //    }
                //},
                {
                    id: 11,
                    visibility: false,
                    name: 'Життєзабезпечення',
                    title: 'Життєзабезпечення',
                    iconNav: '<span class="project-item-name">Життєзабезпечення</span> <span class="material-icons">groups</span>',
                    iconToc: '<span class="material-icons">groups</span>Життєзабезпечення<div class="caret-container"><span class="caret"></span></div> ',
                    //iconNav: '<span class="project-item-name">Інфраструктура</span> <i class="material-icons">electricbolt</i>',
                    //iconToc: '<i class="material-icons">electricbolt</i><span class="caret"></span>Інфраструктура ',
                    //notify: {
                    //    title: 'Чи знаєте ви що:',
                    //    content: 'проект "МАФ" відображає місцезнаходження архітектурної форми!'
                    //}
                },
                //{
                //    id: 2,
                //    visibility: false,
                //    name: 'Медицина',
                //    title: 'Медичні заклади (первинна допомога та амбулаторії)',
                //    iconNav: '<span class="project-item-name">Медицина</span> <i class="material-icons">local_hospital</i>',
                //    iconToc: '<i class="material-icons">local_hospital</i>Медицина <div class="caret-container"><span class="caret"></span></div>',

                    //statistic: {
                    //    short: {                            
                    //        labels: ['Сьогодні', 'За поточний місяць', 'За поточний рік', 'Всього'],
                    //        datasets: [
                    //            {
                    //                label: 'Загальна статистика',
                    //                backgroundColor: [
                    //                    'rgba(255, 99, 132, 0.2)',
                    //                    'rgba(54, 162, 235, 0.2)',
                    //                    'rgba(255, 206, 86, 0.2)',
                    //                    'rgba(75, 192, 192, 0.2)'],
                    //                data: [55, 60, 70, 80]
                    //            }
                    //        ],
                    //        title: 'Кіль-ть зареєстрованих декларацій',
                    //        isShowed: false,
                    //        content: ''
                    //    },
                    //    full: [
                    //        {
                    //            labels: ['10% - Діти', '20% - Підлітки', '30% - Дорослі', '40% - Пенсіонери'],
                    //            datasets: [
                    //                {
                    //                    label: 'Статистика за віком',
                    //                    backgroundColor: [
                    //                        'rgba(255, 99, 132, 0.2)',
                    //                        'rgba(54, 162, 235, 0.2)',
                    //                        'rgba(255, 206, 86, 0.2)',
                    //                        'rgba(75, 192, 192, 0.2)'],
                    //                    data: [10, 20, 30, 40]
                    //                }
                    //            ]
                    //        }
                    //    ],
                    //    defaultDays: 7
                    //},  


                //    notify: {
                //        title: 'Чи знаєте ви що:',
                //        content: 'проект "Медицина" допомагає знайти первинну медичну допомогу!'
                //    }
                //},
                {
                    id: 3,
                    visibility: false,
                    name: 'Освіта та медицина',
                    title: 'Вищі навчальні заклади, школи та дитсадки',
                    iconNav: '<span class="project-item-name">Освіта та медицина</span> <i class="material-icons">school</i>',
                    iconToc: '<i class="material-icons">school</i>Освіта та медицина<div class="caret-container"><span class="caret"></span></div> ',
                    notify: {
                        title: 'Чи знаєте ви що:',
                        content: 'проект "Освіта" надає контакти дошкільних, шкільних закладів та ВНЗ міста!'
                    }
                },
                {
                    id: 4,
                    visibility: false,
                    name: 'Міські послуги',
                    title: 'Міська інфраструктура, цифрові можливості',
                    iconNav: '<span class="project-item-name">Міські послуги</span> <i class="material-icons">wifi</i>',
                    iconToc: '<i class="material-icons">wifi</i>Міські послуги<div class="caret-container"><span class="caret"></span></div>',
                    notify: {
                        title: 'Чи знаєте ви що:',
                        content: 'проект "Міські послуги" допоможе дізнатись про доступність інфраструктури!'
                    }
                },
                //{
                //    id: 5,
                //    visibility: false,
                //    name: 'Звернення',
                //    iconNav: 'Звернення <i class="material-icons"><img src="/opendataportal/Images/nav_head_icon_8.png"></i>',
                //    iconToc: '<i class="material-icons"><img src="/opendataportal/Images/toc_form_icon_8.png"></i><span class="caret"></span>Звернення ',
                //    statistic: {
                //        data: [
                //            {
                //                id: 0,
                //                labels: ['САЙТ', 'Сьогодні', 'За поточний місяць', 'За поточний рік', 'За весь час', 'АСД', 'Сьогодні', 'За поточний місяць', 'За поточний рік', 'За весь час'],
                //                datasets: [
                //                    {
                //                        label: 'Звернення у ХМР',
                //                        backgroundColor: [
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)'
                //                        ],
                //                        data: []
                //                    }
                //                ],
                //                title: 'Статистика Звернень у ХМР з сайту',
                //                isShowed: false,
                //                content: '',
                //                fields: [
                //                    {
                //                        name: 'site',
                //                        desc: 'САЙТ:',
                //                        inStatWin: false
                //                    },
                //                    {
                //                        name: 'VOrderToday',
                //                        desc: 'Сьогодні',
                //                        inStatWin: true
                //                    },
                //                    {
                //                        name: 'web_prof_since_month',
                //                        desc: 'За поточний місяць',
                //                        inStatWin: true
                //                    },
                //                    {
                //                        name: 'web_prof_since_year',
                //                        desc: 'За поточний рік',
                //                        inStatWin: true
                //                    },
                //                    {
                //                        name: 'web_prof_all',
                //                        desc: 'За весь час',
                //                        inStatWin: true
                //                    },
                //                    {
                //                        name: 'pc',
                //                        desc: 'АСД:',
                //                        inStatWin: false
                //                    },
                //                    {
                //                        name: 'VCardToday',
                //                        desc: 'Сьогодні',
                //                        inStatWin: false
                //                    },
                //                    {
                //                        name: 'doc_prof_since_month',
                //                        desc: 'За поточний місяць',
                //                        inStatWin: false
                //                    },
                //                    {
                //                        name: 'doc_prof_since_year',
                //                        desc: 'За поточний рік',
                //                        inStatWin: false
                //                    },
                //                    {
                //                        name: 'doc_prof_all',
                //                        desc: 'За весь час',
                //                        inStatWin: false
                //                    }
                //                ],
                //                notifyData: [],
                //                method: 'GetWebDocProfShortStatistic',
                //                type: 0,
                //                class: 'short',
                //                filtering: false,
                //                vuexMethod: 'GetWDPShortStatistic'
                //            }
                //            ,
                //            {
                //                id: 1,
                //                labels: [],
                //                datasets: [
                //                    {
                //                        label: 'Статистика за тематикою',
                //                        backgroundColor: [
                //                            'rgba(255, 99, 132, 1)',
                //                            'rgba(54, 162, 235, 1)',
                //                            'rgba(255, 206, 86, 1)',
                //                            'rgba(75, 192, 192, 1)'],
                //                        data: []
                //                    }
                //                ],
                //                title: 'Статистика Звернень у ХМР по типам',
                //                defaultDays: 7,
                //                method: 'GetWebDocProfFullStatistic',
                //                weekMethod: 'CalcLastWeekStat',
                //                type: 1,
                //                class: 'date',
                //                filtering: true,
                //                vuexMethod: 'GetWDPDatesStatistic'
                //            }
                //        ],
                //        filtering: true,
                //        defaultDays: 7
                //    },
                //    notify: {
                //        title: 'Чи знаєте ви що:',
                //        content: 'проект "Звернення" відображає кожне звернення до Харківської міської ради!'
                //    }
                //},  
                 {
                    id:8,
                    visibility: false,
                    name: 'Громадська безпека, укриття',
                    title: 'Пожежні частини, укриття для населення, відділи поліції',
                     iconNav: '<span class="project-item-name">Громадська безпека, укриття</span> <i class="material-icons">security</i>',
                     iconToc: '<i class="material-icons">security</i>Громадська безпека, укриття<div class="caret-container"><span class="caret"></span> </div>',
                }, 
                // {
                //    id: 9,
                //    visibility: false,
                //     name: 'Укриття',
                //     title: 'Укриття (бомбосховища)',
                //     iconNav: '<span class="project-item-name">Укриття</span> <span class="material-icons"> <i class="fa fa-bullhorn" aria-hidden="true"></i></span>',
                //     iconToc: '<span class="material-icons"> <i class="fa fa-bullhorn" aria-hidden="true"></i></span><span class="caret"></span>Укриття ',
                //},                
                //{
                //    id: 6,
                //    visibility: false,
                //    name: 'Інше',
                //    title: "Пам'ятки архітектури, громадські вбиральні",
                //    iconNav: '<span class="project-item-name">Інше</span><i class="material-icons"><img src="/opendataportal/Images/nav_head_icon_6.png"></i>',
                //    iconToc: '<i class="material-icons"><img src="/opendataportal/Images/toc_form_icon_6.png"></i><span class="caret"></span>Інше ',
                //},
                //{
                //    id: 10,
                //    visibility: false,
                //    name: 'Торгівля',
                //    title: "МАФ",
                //    iconNav: 'Торгівля <i class="material-icons">storefront</i>',
                //    iconToc: '<i class="material-icons">storefront</i><span class="caret"></span>Торгівля ',
                //},
                {
                    id: 12,
                    visibility: false,
                    name: 'ДСНС',
                    title: 'ДСНС',
                    iconNav: '<span class="project-item-name">ДСНС</span> <i class="material-icons">contact_emergency</i>',
                    iconToc: '<i class="material-icons">contact_emergency</i>ДСНС<div class="caret-container"><span class="caret"></span> </div>',
                }, 
            ],
            //слои
            layers: [
                //{
                //    id: 0,
                //    pId: 0,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/dug_multi_web/MapServer',
                //    url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/dug_multi_web/MapServer',
                //    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/dug_multi_web/MapServer',

                //    type: 'dynamic',
                //    visibility: false,
                //  map_visibility:false,
                //    name: 'розриття міста',
                //    layerIds: [0],
                //    tolerance: 50,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Polygon',
                //    nameVectorLayer: 'Текущие разрытия',
                //    identScale: 0,
                //    identify: [
                //        {
                //            id: 0,
                //            title: 'Поточні розриття',
                //            identityFields: [{ name: 'Address', description: 'Адреса' },
                //            { name: 'AddressDescription', description: 'Додатково' },
                //            { name: 'Name', description: 'Тип' },
                //            { name: 'NameWork', description: 'Роботи' },
                //            { name: 'Owner', description: 'Замовник' },
                //            { name: 'ResNumber', description: '№' },
                //            { name: 'ResDate', description: 'Реєстрація' },
                //            { name: 'WhenStarted', description: 'Початок' },
                //            { name: 'WhenFinish', description: 'Кінець' }],
                //            tocName: 'Текущие разрытия',
                //            controller: true,
                //            method: 'GetDugById',
                //            bindToAddress: false
                //        }
                //    ]
                //},
                //{
                //    id: 1,
                //    pId: 4,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //  //  url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //  url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'dynamic',
                //    visibility: false,
                //    map_visibility:false,
                //    name: 'Рекламні конструкції',
                //    layerIds: [20],
                //    tolerance: 90,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'Рекламні конструкції',
                //    identScale: 0,
                    //cluster: {
                    //    on: true,
                    //    size: [16, 16],
                    //    options: [
                    //        {
                    //            countFeatures: 2,
                    //            radius: 15,
                    //            fillColor: [250, 65, 74, 0.8],
                    //            line: {
                    //                width: 8,
                    //                lineColor: [200, 52, 59, 0.8]
                    //            }
                    //        },
                    //        {
                    //            countFeatures: 10,
                    //            radius: 20,
                    //            fillColor: [250, 65, 74, 0.8],
                    //            line: {
                    //                width: 12,
                    //                lineColor: [200, 52, 59, 0.8]
                    //            }
                    //        },
                    //        {
                    //            countFeatures: 100,
                    //            radius: 30,
                    //            fillColor: [250, 65, 74, 0.8],
                    //            line: {
                    //                width: 16,
                    //                lineColor: [200, 52, 59, 0.8]
                    //            }
                    //        },
                    //        {
                    //            countFeatures: 1000,
                    //            radius: 40,
                    //            fillColor: [250, 65, 74, 0.8],
                    //            line: {
                    //                width: 20,
                    //                lineColor: [200, 52, 59, 0.8]
                    //            }
                    //        }
                    //    ]
                    //},
                    //identify: [
                    //    {
                    //        id: 7,
                    //        title: 'Реклама',
                    //        identityFields: [{ name: 'Id', description: '№' },
                    //                        { name: 'ADDRESS_FULL', description: 'Адреса' },
                    //                        { name: 'SIZES', description: 'Розмір' },
                    //                        { name: 'PERMIT_NUM', description: 'Дозвіл' },
                    //                        { name: 'PERMIT_VALID', description: 'до' },
                    //                        { name: 'CUST_SMALL', description: 'Замовник' },
                    //                        { name: 'CUST_PHONE', description: 'Тел.' },
                    //                        { name: 'CUST_EMAIL', description: 'Email' },
                    //                        { name: 'blobs', description: '' }],
                    //        tocName: 'Рекламні конструкції',
                    //       // controller: true,
                    //       // method: 'GetAdwerts',
                    //        bindToAddress: false,
                    //        mainField: 'ADDRESS_FULL',
                    //    }
                    //],
                    //typesColors: {
                    //    fieldName: 'CT_ID',
                    //    fieldName2: null,
                    //    fieldName3: null,
                    //    types: [
                    //        { value: "0", desc: "Наземні", value1: '0',  ext: '.svg' },
                    //        { value: "1", desc: "Фасадні", value1: '1', ext: '.svg' },
                    //    ]
                    //},

                    //iconSize: { "width": 24, "height": 24 },
                    //selectIconSize: { "width": 16, "height": 16 },

                    ////token: {
                    ////    need: true,
                    ////    str: ''
                    ////},
               // },
                {
                    id: 2,
                    pId: 3,
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'медичні заклади',
                    layerIds: [1],
                    tolerance: 30,
                    //tolerance: {
                    //    '200': [40, 2],
                    //    '300': [40, 2],
                    //    '500': [45, 5],
                    //    '1000': [50, 15],
                    //    '5000': [55, 50],
                    //},
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'asys.SDE.munic_medicine',
                    identScale: 0,
                    identify: [
                        {
                            id: 1,
                            title: 'Медичні заклади',
                            identityFields: [{ name: 'name', description: 'Назва' },
                            { name: 'adres', description: 'Адреса' },
                            { name: 'tel', description: 'Телефон' },
                            { name: 'tel_office', description: 'Телефон приймальні' }],
                            tocName: 'asys.SDE.munic_medicine',
                            controller: false,
                            bindToAddress: true,
                            bindToAddressField: 'OBJECTID',
                            mainField: 'name',
                            type:'medicine'
                        }
                    ],
                },
                {
                    id: 3,
                    pId: 3,
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'дошкільні та шкільні заклади',
                    layerIds: [0],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'asys.SDE.munic_education',
                    identScale: 0,
                    identify: [
                        {
                            id: 0,
                            title: 'Дошкільні та шкільні заклади',
                            identityFields: [{ name: 'name', description: 'Назва' },
                            { name: 'address', description: 'Адреса' },
                            { name: 'own_type', description: 'Власність' },
                            { name: 'phone', description: 'Телефон' },
                            { name: 'url', description: 'Сайт' },
                            { name: 'mail', description: 'Email' }],
                            tocName: 'asys.SDE.munic_education',
                            controller: false,
                            bindToAddress: true,
                            bindToAddressField: 'institutionIdentifier_',
                            mainField: 'name',
                            type: 'scool',
                        }
                    ],
                    //раскрасска по типам
                    typesColors: {
                        fieldName: 'type',
                        types: [
                            { value: 1, desc: 'Дитячі садки', ext: '.svg' },
                            { value: 2, desc: 'Школи', ext: '.svg' }
                            //{ value: 3, desc: 'Спеціалізовані школи' },
                            //{ value: 4, desc: 'Спеціалізовані заклади' }
                        ]
                    },
                    iconSize: { "width": 16, "height": 16 },
                },
                //{
                //    id: 4,
                //    pId: 4,                    
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //   //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'feature',
                //    visibility: false,
                //    map_visibility: false,
                //    name: 'міський Wi-Fi',
                //    layerIds: [6],
                //    tolerance: 40,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'WIFI',
                //    identScale: 0,
                //    cluster: {
                //        on: true,
                //        size: [16, 25],
                //        options: [
                //            {
                //                countFeatures: 2,
                //                radius: 10,
                //                fillColor: [8, 96, 150, 0.8],
                //                line: {
                //                    width: 8,
                //                    lineColor: [9, 100, 156, 0.8]
                //                }
                //            },
                //            {
                //                countFeatures: 10,
                //                radius: 10,//20,
                //                fillColor: [8, 96, 150, 0.8],
                //                line: {
                //                    width: 12,
                //                    lineColor: [9, 100, 156, 0.8]
                //                }
                //            },
                //            {
                //                countFeatures: 100,
                //                radius: 30,
                //                fillColor: [8, 96, 150, 0.8],
                //                line: {
                //                    width: 16,
                //                    lineColor: [9, 100, 156, 0.8]
                //                }
                //            },
                //            {
                //                countFeatures: 1000,
                //                radius: 40,
                //                fillColor: [8, 96, 150, 0.8],
                //                line: {
                //                    width: 20,
                //                    lineColor: [9, 100, 156, 0.8]
                //                }
                //            }
                //        ]
                //    },
                //    identify: [
                //        {
                //            id: 6,
                //            title: 'міський Wi-Fi',
                //            identityFields: [{ name: 'SHOW_NAME', description: 'Точка' },
                //            { name: 'DEPT_NAME', description: 'Організація' },
                //            { name: 'UPTIME', description: 'В мережі' },
                //            { name: 'CLIENT_COUNT', description: 'Підключень' },
                //            { name: 'RX_AVR', description: 'прийом' },
                //            { name: 'TX_AVR', description: 'передача' },
                //            { name: 'RX_TOTAL', description: 'прийом' },
                //            { name: 'TX_TOTAL', description: 'передача' }],
                //            tocName: 'WIFI',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'SHOW_NAME',
                //            identScale: 2000,
                //        }
                //    ],
                //    features: null,
                //    loadMethod: 'GetAllWifiMap'
                //},
                {
                    id: 5,
                    pId: 3,
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'заклади вищої освіти',
                    layerIds: [3],
                    tolerance: 16,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'OPENDATAPORTAL.%V_HIGH_SCHOOL Events',
                    identScale: 0,
                    identify: [
                        {
                            id: 3,
                            title: 'Заклади вищої освіти',
                            identityFields: [{ name: 'UNIVERSITY_NAME', description: 'Назва' },
                            { name: 'REGISTRATION_YEAR', description: 'Заснування' },
                            { name: 'UNIVERSITY_TYPE_NAME', description: 'Тип вишу' },
                            { name: 'EDUCATION_TYPE_NAME', description: 'Тип освіти' },
                            { name: 'FINANCING_TYPE_NAME', description: 'Форма фінансування' },
                            { name: 'GOVERNANCE_TYPE_NAME', description: 'Підпорядкування' },
                            { name: 'POST_INDEX_U', description: 'Індекс' },
                            { name: 'REGION_NAME_U', description: 'Область' },
                            { name: 'KOATUU_NAME_U', description: 'Місто' },
                            { name: 'UNIVERSITY_ADDRESS_U', description: 'Юр. адреса' },
                            { name: 'UNIVERSITY_PHONE', description: 'Телефон' },
                            { name: 'UNIVERSITY_EMAIL', description: 'Email' },
                            { name: 'UNIVERSITY_SITE', description: 'Сайт' },
                            { name: 'UNIVERSITY_DIRECTOR_POST', description: 'Посада керівника' },
                            { name: 'UNIVERSITY_DIRECTOR_FIO', description: 'Керівник' }],
                            tocName: 'OPENDATAPORTAL.%V_HIGH_SCHOOL Events',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'UNIVERSITY_NAME',
                        }
                    ]
                },
                {
                    id: 6,
                    pId: 3,
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'професійно-технічні заклади освіти',
                    layerIds: [2],
                    tolerance: 16,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'OPENDATAPORTAL.%V_PROF_SCHOOL Events',
                    identScale: 0,
                    identify: [
                        {
                            id: 2,
                            title: 'Професійно-технічні заклади освіти',
                            identityFields: [{ name: 'UNIVERSITY_NAME', description: 'Назва' },
                            { name: 'REGISTRATION_YEAR', description: 'Заснування' },
                            { name: 'UNIVERSITY_TYPE_NAME', description: 'Тип вишу' },
                            { name: 'EDUCATION_TYPE_NAME', description: 'Тип освіти' },
                            { name: 'FINANCING_TYPE_NAME', description: 'Форма фінансування' },
                            { name: 'GOVERNANCE_TYPE_NAME', description: 'Підпорядкування' },
                            { name: 'POST_INDEX_U', description: 'Індекс' },
                            { name: 'REGION_NAME_U', description: 'Область' },
                            { name: 'KOATUU_NAME_U', description: 'Місто' },
                            { name: 'UNIVERSITY_ADDRESS_U', description: 'Юр. адреса' },
                            { name: 'UNIVERSITY_PHONE', description: 'Телефон' },
                            { name: 'UNIVERSITY_EMAIL', description: 'Email' },
                            { name: 'UNIVERSITY_SITE', description: 'Сайт' },
                            { name: 'UNIVERSITY_DIRECTOR_POST', description: 'Посада керівника' },
                            { name: 'UNIVERSITY_DIRECTOR_FIO', description: 'Керівник' }],
                            tocName: 'OPENDATAPORTAL.%V_PROF_SCHOOL Events',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'UNIVERSITY_NAME',
                        }
                    ]
                },
                {
                    id: 7,
                    pId: 3,
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'первинна медична допомога',
                    layerIds: [4],
                    tolerance: 16,
                    //tolerance: {
                    //    '200': [40, 2],
                    //    '300': [40, 2],
                    //    '500': [45, 5],
                    //    '1000': [50, 10],
                    //    '5000': [55, 15],
                    //},
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'OPENDATAPORTAL.%V_MEDECINE Events',
                    identScale: 0,
                    identify: [
                        {
                            id: 4,
                            title: 'Первинна мед допомога',
                            identityFields: [{ name: 'DIVISION_TYPE', description: 'Підрозділ' },
                            { name: 'DIVISION_RESIDENCE_ADDRESSES', description: 'Адреса' },
                            { name: 'DIVISION_NAME', description: 'Підрозділ' },
                            { name: 'LEGAL_ENTITY_NAME', description: 'Установа' },
                            { name: 'REGISTRATION_ADDERESSES', description: 'Адреса установи' },
                            { name: 'GOVERNANCE_TYPE_NAME', description: 'Форма фінансування' }],
                            tocName: 'OPENDATAPORTAL.%V_MEDECINE Events',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'DIVISION_NAME',
                        }
                    ]
                },
                {
                    id: 8,
                    pId: 8,                   
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'Оповіщення громадян',
                    layerIds: [5],
                    tolerance: 50,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Оповіщення громадян',
                    identScale: 0,
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                    identify: [
                        {
                            id: 8,
                            title: 'Оповіщення громадян',
                            identityFields: [
                                { name: 'F1', description: 'Приналежність' },
                                { name: 'F0', description: 'Вид об\'єкту' },
                                { name: 'F3', description: 'Статус' },
                                { name: 'F4', description: 'Кількість поверхів' },
                                { name: 'F5', description: 'Дільниця КП ЖКС або найменування об\'єкту' },
                                { name: 'F6', description: 'Кількість під\'їздів' },
                                { name: 'F7', description: '№ під\'їзду' },
                                { name: 'F8', description: 'Район' },
                                { name: 'F9', description: 'Металоконструкція для кріплення КЗО' },
                                { name: 'F10', description: 'Електропостачання (КП "Міськсвітло")' },
                                { name: 'F11', description: 'Мачта (КСП "Харківспецбуд")' },
                                { name: 'F12', description: 'Заземлення мачти (КП "Міськсвтло")' },
                                { name: 'F13', description: 'Гучномовці монтаж (КП "МІЦ")' },
                                { name: 'F14', description: 'Гучномовці підключення (КП "МІЦ")' },
                                { name: 'F15', description: 'Інвентарний номер групи гучномовців (8 шт) (КП "МІЦ")' },
                                { name: 'F16', description: 'Інтернет кабель (КП "МІЦ")' },
                                { name: 'F17', description: 'Інтернет підключення (КП "МІЦ")' },
                                { name: 'F18', description: 'Реєстраційний номер 4-х портового маршрутизатора (КП "МІЦ")' },
                                { name: 'F19', description: 'Охорона (вхід, шафа, відеоспостереження) (ТОВ "Бріг")' },
                                { name: 'F20', description: 'Шафа та SIM для Інтернету, передача (розробник)' },
                                { name: 'F21', description: 'Номер телефону SIM' },
                                { name: 'F22', description: 'Шафа, інвентраний номер (КП "МІЦ")' },
                                { name: 'F23', description: 'Шафа, монтаж (КП "МІЦ")' },
                                { name: 'F24', description: 'Заземлення шафи (КП "МІЦ")' },
                                { name: 'F25', description: 'Шафа підключення (SIM та EHTERNET) (КП "МІЦ")' },
                                { name: 'F26', description: 'Монтаж акумуляторів для ДБЖ (КП "МІЦ")' },
                                { name: 'F27', description: 'Інвентарний номер АБ 1 (КП "МІЦ")' },
                                { name: 'F28', description: 'Інвентарний номер АБ 2 (КП "МІЦ")' },
                                { name: 'F29', description: 'Підключення до АРМ (КП "МІЦ", розробник)' },
                                { name: 'F30', description: 'Ключи від входу на дах будинку' },
                                { name: 'F31', description: 'Дублікати ключів від входу на дах будинку (ДНС)' },
                                { name: 'F32', description: 'Дублікати ключів від входу до ліфтового приміщення (ДНС)' },
                                { name: 'F33', description: 'Закриття інших виходів на дах (КП "Житлокомсервіс")' },
                                { name: 'F34', description: 'Закриття розбитих вікон в ліфтових надбудовах (КП "Житлокомсервіс")' },
                                { name: 'F39', description: 'Місце розміщення КПО' },
                                { name: 'F40', description: 'Типові проєкти' },
                                { name: 'F41', description: 'Доступ в під\'їзд(ДНС)' },
                                { name: 'F42', description: 'Наявність в ДНС ключа від домофону, код (ДНС)' },
                                { name: 'F43', description: 'Проблемні питання' },

                            ],
                            tocName: 'Оповіщення громадян',
                            controller: false,
                            bindToAddress: false,
                            photoField: "PHOTOS",
                            mainField: 'F1',
                            selectedMarkerFileName: "select_55.svg",
                        }
                    ],
                    selectIconSize: { "width": 25, "height": 25 }
                },
                {
                    id: 9,
                    pId: 4,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'Громадські вбиральні',
                    layerIds: [8],
                    tolerance: 16,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'asys.SDE.toilets',
                    identScale: 0,
                    identify: [
                        {
                            id: 9,
                            title: 'Громадські вбиральні',
                            identityFields: [
                                { name: 'ORG_NAME', description: 'Назва утримувача' },
                                { name: 'DESCRIPTIO', description: 'Опис' },
                                { name: 'TYPE', description: 'Тип' },
                                { name: 'ADD_FACIL', description: 'Додаткові зручності' },
                                { name: 'AVAIL_TYPE', description: 'Доступність для людей з інвалідністю' },
                                { name: 'PRICE', description: 'Вартість' },
                                { name: 'PAY_TYPE', description: 'Тип оплати' },
                                { name: 'WORK_HOURS', description: 'Графік роботи' },
                                { name: 'AVAIL_REST', description: 'Обмеження в роботі' },
                                { name: 'POSTCODE', description: 'Поштовий індекс' },
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADR_STREET', description: 'Вулиця' },
                                { name: 'ADR_NUMBER', description: 'Номер будівлі' },

                            ],
                            tocName: 'asys.SDE.toilets',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'WORK_HOURS',
                        }
                    ]
                },
                //{
                //    id: 10,
                //    pId: 7,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'feature',
                //    visibility: false,
                //    map_visibility: false,
                //    name: 'Житло2008',
                //    layerIds: [9],
                //    tolerance: 50,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Polygon',
                //    nameVectorLayer: 'Житло2008',
                //    identScale: 0,
                //},
                //{
                //    id: 15,
                //    pId: 8,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'feature',
                //    visibility: false,
                //    map_visibility: false,
                //    //checkUpdate: {
                //    //    method: 'UpdateBombsheltersFromGoogleSheet',
                //    //    url: '/opendataportal/Home/UpdateBombsheltersFromGoogleSheet',
                //    //},
                //    name: 'Укриття для населення',
                //    layerIds: [14],
                //    tolerance: 16,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'asys.SDE.bombshelters',
                //    identScale: 0,
                //    identify: [
                //        {
                //            id: 14,
                //            title: 'Укриття для населення',
                //            identityFields: [
                //                { name: 'District', description: 'Район' },
                //                { name: 'inData_ADD', description: 'Адреса' },
                //                { name: 'inData_DIS', description: 'Приміщення' },
                //            ],
                //            tocName: 'asys.SDE.bombshelters',
                //            controller: false,
                //            bindToAddress: true,
                //            bindToAddressField: 'inData_AID',
                //            type: 'bombshelters',
                //            mainField: 'inData_ADD'

                //        }
                //    ]
                //},
                {
                    id: 15,
                    pId: 8,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/googlesheetsdata/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/googlesheetsdata/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateBombSheltersFromGoogleSheet',
                        url: '/opendataportal/Home/UpdateBombSheltersFromGoogleSheet',
                    },
                    name: 'Укриття для населення',
                    layerIds: [0],
                    tolerance: 50,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'asys.SDE.bombshelters',
                    identScale: 0,
                    identify: [
                        {
                            id: 14,
                            title: 'Укриття для населення',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса місця для укриття' },
                                { name: 'BOMBSHELTER_PLACE', description: 'Місце для укриття' },
                                { name: 'BOMBSHELTER_PLACEMENT', description: 'Розміщення укриття' },
                            ],
                            tocName: 'asys.SDE.bombshelters',
                            controller: false,
                            bindToAddress: true,
                            bindToAddressField: 'AR_ID',
                            type: 'bombshelters',
                            mainField: 'ADDRESS'

                        }
                    ]
                },
                {
                    id: 21,
                    pId: 4,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'Центри доступу до цифрових можливостей',
                    layerIds: [17],
                    tolerance: 16,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'asys.SDE.CyfraAccess',
                    identScale: 0,
                    identify: [
                        {
                            id: 17,
                            title: 'Центри доступу до цифрових можливостей',
                            identityFields: [
                                //{ name: 'identifier', description: 'Ідентифікатор' },
                                { name: 'name', description: 'Назва об\'єкта' },
                                { name: 'description', description: 'Опис' },
                                { name: 'equipment', description: 'Оснащ. робочого місця' },
                                { name: 'working_places', description: 'Кіль-ть робочих місць' },
                                { name: 'consultant', description: 'Наявність консультанта' },
                                { name: 'authoritytIdentifier', description: 'Ідент-р закладу' },
                                { name: 'institution_name', description: 'Заклад, де розміщено центр' },
                                { name: 'Country', description: 'Країна' },
                                { name: 'Origin', description: 'Регіон' },
                                { name: 'OriginDitrict', description: 'Район' },
                                { name: 'City', description: 'Населений пункт' },
                                { name: 'Street', description: 'Вулиця' },
                                { name: 'StreetType', description: 'Тип вулиці' },
                                { name: 'HouseNumber', description: 'Номер будівлі' },
                                { name: 'address_post_code', description: 'Індекс' },
                                { name: 'website', description: 'Веб-сайт' },
                                { name: 'addressPostCode', description: 'Email' },
                                { name: 'telephone', description: 'Телефон' },
                                { name: 'openingHours', description: 'Графік роботи/прийому' },
                                { name: 'availabilityRestriction', description: 'Обмеження прийому/в роботі' },
                                { name: 'availabilityType', description: 'Доступність для осіб маломобільних груп населення' },

                            ],
                            tocName: 'asys.SDE.CyfraAccess',
                            controller: false,
                            //bindToAddress: false,
                            //bindToAddressField: '',                            
                            mainField: 'name'
                        }
                    ]
                },
                //{
                //    id: 22,
                //    pId: 8,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'feature',
                //    map_visibility: false,
                //    name: 'Сирени (доступність)',
                //    layerIds: [0],
                //    tolerance: 16,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'Сирени (доступність)',
                //    identScale: 0,
                //    identify: [
                //        {
                //            id: 0,
                //            title: 'Сирени (доступність)',
                //            identityFields: [
                //                { name: 'TypeName', description: 'Доступність' },
                //                { name: 'District', description: 'Район' },
                //                { name: 'Street', description: 'Вулиця' },
                //                { name: 'House', description: 'Номер будинку' }

                //            ],
                //            tocName: 'Сирени (доступність)',
                //            controller: false,
                //            bindToAddress: false,
                //            bindToAddressField: '',                            
                //            mainField: 'TypeName',
                //            objectIdField:"OBJECTID"
                //        }
                //    ],
                //    token: {
                //        need: true,
                //        str: ''
                //    },
                //    features: null,
                //    loadMethod: 'Siren',
                //    //loadMethodUrl: 'https://smart.khmr.gov.ua/arcgis/rest/services/WEBACC_LOCALL/MapServer/',
                //    //loadMethodUrl: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/WEBACC_LOCALL/MapServer/',
                //    //loadMethodUrl: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/WEBACC_LOCALL/MapServer/',
                //    //раскрасска по типам
                //    typesColors: {
                //        fieldName: 'TypeId',
                //        fieldName2: null,
                //        fieldName3: null,
                //        types: [
                //            { value: "1", desc: "Не чути", value1: 1, ext: '.svg'},
                //            { value: "2", desc: "Погано чути", value1: 2, ext: '.svg' },                           
                //        ]
                //    },
                //    iconSize: { "width": 24, "height": 24 },
                //    selectIconSize: { "width": 25, "height": 25 }
                //},
                {
                    id: 11,
                    pId: 7,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS_ZHITLO/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'Не комунальне житло',
                    layerIds: [1],//10
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Polygon',
                    nameVectorLayer: 'Не комунальне житло',
                    identScale: 0,
                    identify: [
                        {
                            id: 11,
                            title: "Не комунальне житло",
                            //identityFields: [
                            //    { name: 'FULLADDRUA', description: 'Адреса' },
                            //    { name: 'FLOOR', description: 'Поверховість' },
                            //    { name: 'BAL_TYPE', description: 'Вид об\'єднання' },
                            //    { name: 'BAL_NAME', description: 'Найменування об\'єднання' },
                            //    { name: 'BAL_BOSS', description: 'ПІБ голови об\'єднання (за&#160;наявністю)' },
                            //    { name: 'DIST', description: 'Район міста' },
                            //    { name: 'STR_TYPE', description: 'Тип вулиці' },
                            //    { name: 'STR_NAME', description: 'Найменування вулиці' },
                            //    { name: 'STR_NUM', description: '№ будинку' },
                            //    { name: 'STR_SUFF', description: 'Літера, дробова частина №' },
                            //    { name: 'STR_BLOCK', description: 'Корпус, під\'їзд' },
                            //    { name: 'commnts', description: 'Ділянка КП Жилкомсевіс' },
                            //    { name: 'balancer', description: 'Обслуговування' },
                            //    { name: 'solid_garbage_export', description: 'Вивезення твердих побутових відходів' },
                            //    { name: 'plastic_garbage_export', description: 'Вивезення пластикової тари та ПЕТ відходів' },
                            //    { name: 'sewerage_service', description: 'Обслуговування внутрішньобудинкових систем холодного водопостачання та каналізації' },
                            //    { name: 'warm_service', description: 'Обслуговування внутрішньобудинкових систем опалення та гарячого водопостачання' },
                            //    { name: 'elevator_service', description: 'Обслуговування ліфтів' },
                            //    { name: 'network_service', description: 'Обслуговування внутрішньобудинкових електромереж' },
                            //    { name: 'heating', description: 'Централізоване опалення' },
                            //    { name: 'warm_firm', description: 'Централізоване гаряче водопостачання' },
                            //    { name: 'warm_auto', description: 'Автоматика системи опалення' },
                            //    { name: 'water_firm', description: 'Централізоване холодне водопостачання та водовідведення' },
                   
                            //    {
                            //        name: 'bindToServices',
                            //        description: 'Обслуговуючі установи',
                            //        bindToServices: [
                            //            {
                            //                name: 'Об\'єднання',
                            //                type: 'osbb_nom',
                            //                layerId: 10,
                            //                field: 'osbb_nom',
                            //                eventName:'showMoreForBuilds',
                            //            }
                            //        ]
                            //    },                                
                            //],
                            identityFields: [
                                { name: 'F1', description: 'Адреса' },
                                { name: 'F0', description: 'Район' },
                                { name: 'F2', description: 'Кількість поверхів' },
                                { name: 'F3', description: 'Кількість під’їздів' },
                                { name: 'F4', description: 'Форма власності (управління)' },
                                { name: 'F5', description: 'Найменування організації-управителя' },
                                { name: 'F6', description: 'Матеріал покрівлі' },
                                { name: 'F7', description: 'Матеріал зовнішніх стін' },
                                { name: 'F8', description: 'Централізоване теплопостачання' },
                                { name: 'F9', description: 'Обслуговування ВБС теплопостачання' },
                                { name: 'F10', description: 'Централізоване гаряче водопостачання' },
                                { name: 'F11', description: 'Обслуговування ВБС гар. водопостачання' },
                                { name: 'F12', description: 'Централізоване водопостачання' },
                                { name: 'F13', description: 'Обслуговування ВБС хол. водопостачання' },
                                { name: 'F14', description: 'Централізоване водовідведення' },
                                { name: 'F15', description: 'Обслуговування ВБС водовідведення та внутр. зливової каналізації' },
                                { name: 'F16', description: 'Обслуговування зовнішніх мереж зливової каналізації' },
                                { name: 'F17', description: 'Обслуговування ВБС електропостачання та освітлення' },
                                { name: 'F18', description: 'Обслуговування ліфтового господарства' },
                                { name: 'F19', description: 'Обслуговування систем диспетчеризації' },
                                { name: 'F20', description: 'Обслуговування димовентканалів' },
                                { name: 'F21', description: 'Прибирання прибудинкової території' },
                                { name: 'F22', description: 'Вивезення ТПВ' },
                                { name: 'F23', description: 'Доставка газу' },
                            ],
                            tocName: 'Не комунальне житло',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'FULLADDRUA'
                        }
                    ]
                },
                {
                    id: 12,
                    pId: 8,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'Пожежні частини',
                    layerIds: [12],
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Polygon',
                    nameVectorLayer: 'Пожежні частини',
                    identScale: 0,
                    identify: [
                        {
                            id: 12,
                            title: "Пожежні частини",
                            identityFields: [
                                { name: 'NAZN', description: 'Назва' },
                                { name: 'OBJ_COMMENT', description: 'Опис' },
                                { name: 'ADM_RAYON', description: 'Адмін. район' },
                                { name: 'STR_TYPE', description: 'Тип вулиці' },
                                { name: 'STR_NAME', description: 'Назва вулиці' },
                                { name: 'NUMB', description: 'Номер' },
                                { name: 'NUMB_SUFF', description: 'Суфікс' },
                            ],
                            tocName: 'Пожежні частини',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAZN'
                        }
                    ],
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                },
                {
                    id: 13,
                    pId: 7,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/zhill_fond_munic/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS_ZHITLO/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'Комунальне житло',
                    layerIds: [0],//13
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Polygon',
                    nameVectorLayer: 'Комунальне житло',
                    identScale: 0,
                    identify: [
                        {
                            id: 13,
                            title: "Комунальне житло",
                            //identityFields: [
                            //    { name: 'FULLADDRUA', description: 'Адреса' },
                            //    { name: 'FLOOR', description: 'Поверховість' },
                            //    { name: 'zks_N', description: 'Ділянка КП Жилкомсевіс' },
                            //    { name: 'dist', description: 'Район міста' },
                            //    { name: 'str_type', description: 'Тип вулиці' },
                            //    { name: 'str_name', description: 'Найменування вулиці' },
                            //    { name: 'house_num', description: '№ будинку' },
                            //    //{ name: 'house_bld', description: '№ будівлі' },
                            //    { name: 'house_sect', description: '№ секції' },
                            //    { name: 'house_suff', description: 'Літера, дробова частина №' },
                            //    { name: 'house_block', description: 'Корпус' },
                            //    { name: 'entrances_nums', description: '№ під\'їздів' },
                            //    { name: 'house_reg_number', description: '№ реєстрації' },
                            //    { name: 'build_year', description: 'Рік забудови' },
                            //    { name: 'entrances_count', description: 'Кіль-ть під\'їздів' },
                            //    { name: 'floors_count', description: 'Поверховість' },
                            //    { name: 'flats_count', description: 'Кіль-ть квартир' },                               
                            //    { name: 'roof_material', description: 'Матеріал покрівлі' }, 
                            //    { name: 'wall_material', description: 'Матеріал стін' }, 
                            //    { name: 'elevators_count', description: 'Кіль-ть ліфтів' }, 
                            //    { name: 'switchboards_count', description: 'Кіль-ть щитових' }, 
                            //    { name: 'gas_firm', description: 'Постачальник газу' }, 
                            //    { name: 'warm_firm', description: 'Постачальник опалення' },
                            //    { name: 'warm_auto', description: 'Автоматика системи опалення' },
                            //    //{ name: 'warmcon', description: 'Опалення' },
                            //    { name: 'heatwater_firm', description: 'Постачальник гарячої води' }, 
                            //    { name: 'sewerage_firm', description: 'Обслуг. каналізації' }, 
                            //    { name: 'water_firm', description: 'Постачальник холодної води' }, 


                            //    //{ name: 'balancer', description: 'Обслуговування' },
                            //],
                            identityFields: [
                                { name: 'F1', description: 'Адреса' },
                                { name: 'F0', description: 'Район' },
                                { name: 'F2', description: 'Кількість поверхів' },
                                { name: 'F3', description: 'Кількість під’їздів' },
                                { name: 'F4', description: 'Форма власності (управління)' },
                                { name: 'F5', description: 'Найменування організації-управителя' },
                                { name: 'F6', description: 'Матеріал покрівлі' },
                                { name: 'F7', description: 'Матеріал зовнішніх стін' },
                                { name: 'F8', description: 'Централізоване теплопостачання' },
                                { name: 'F9', description: 'Обслуговування ВБС теплопостачання' },
                                { name: 'F10', description: 'Централізоване гаряче водопостачання' },
                                { name: 'F11', description: 'Обслуговування ВБС гар. водопостачання' },
                                { name: 'F12', description: 'Централізоване водопостачання' },
                                { name: 'F13', description: 'Обслуговування ВБС хол. водопостачання' },
                                { name: 'F14', description: 'Централізоване водовідведення' },
                                { name: 'F15', description: 'Обслуговування ВБС водовідведення та внутр. зливової каналізації' },
                                { name: 'F16', description: 'Обслуговування зовнішніх мереж зливової каналізації' },
                                { name: 'F17', description: 'Обслуговування ВБС електропостачання та освітлення' },
                                { name: 'F18', description: 'Обслуговування ліфтового господарства' },
                                { name: 'F19', description: 'Обслуговування систем диспетчеризації' },
                                { name: 'F20', description: 'Обслуговування димовентканалів' },
                                { name: 'F21', description: 'Прибирання прибудинкової території' },
                                { name: 'F22', description: 'Вивезення ТПВ' },
                                { name: 'F23', description: 'Доставка газу' },
                            ],
                            tocName: 'Комунальне житло',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'FULLADDRUA'
                        }
                    ]
                },
                //{
                //    id: 14,
                //    pId: 6,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'feature',
                //    visibility: false,
                //    map_visibility: false,
                //    name: 'Пам\'ятки архітектури',
                //    //layerIds: [0],
                //    tolerance: 100,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'Пам\'ятки архітектури',
                //    identScale: 0,
                //    cluster: {
                //        on: true,
                //        size: [16, 25],
                //        options: [
                //            {
                //                countFeatures: 2,
                //                radius: 15,
                //                fillColor: [255, 102, 0, 0.8],
                //                line: {
                //                    width: 8,
                //                    lineColor: [184, 83, 17, 0.8]
                //                }
                //            },
                //            {
                //                countFeatures: 10,
                //                radius: 20,
                //                fillColor: [255, 102, 0, 0.8],
                //                line: {
                //                    width: 12,
                //                    lineColor: [184, 83, 17, 0.8]
                //                }
                //            },
                //            {
                //                countFeatures: 100,
                //                radius: 30,
                //                fillColor: [255, 102, 0, 0.8],
                //                line: {
                //                    width: 16,
                //                    lineColor: [184, 83, 17, 0.8]
                //                }
                //            },
                //            {
                //                countFeatures: 1000,
                //                radius: 40,
                //                fillColor: [255, 102, 0, 0.8],
                //                line: {
                //                    width: 20,
                //                    lineColor: [184, 83, 17, 0.8]
                //                }
                //            }
                //        ]
                //    },
                //    identify: [
                //        {
                //            id: 0,
                //            title: 'Пам\'ятки архітектури',
                //            identityFields: [
                //                { name: 'NAME', description: 'Назва' },
                //                { name: 'HIST_NAME', description: 'Історична назва/Первісне призначення' },
                //                { name: 'ADDRESS', description: 'Адреса' },
                //                { name: 'HIST_ADDRESS', description: 'Історична адреса' },
                //                { name: 'BLOB_URL', description: 'Фото' },
                //            ],
                //            tocName: 'Пам\'ятки архітектури',
                //            controller: false,
                //            bindToAddress: false
                //        }
                //    ],
                //    features: null,
                //    loadMethod: 'GetAllHistBuilds'
                //},
                {
                    id: 16,
                    pId: 4,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/WEBACC_LOCALL/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    name: 'Доступність інфраструктури',
                    layerIds: [0],
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'WEBACCESS.FFEATURES_W_BLOBS_ID Events',
                    identScale: 0,
                    identify: [
                        {
                            id: 0,
                            title: 'Доступність інфраструктури',
                            identityFields: [
                                {name: 'FEATURE_TYPE', description: 'Статус'},
                                { name: 'FEATURE_DESC_UKR', description: 'Назва' },
                                { name: 'HASENTRANCE', description: 'В наявності' },
                                { name: 'BLOBS_ID', description: 'Фото' },

                            ],
                            tocName: 'Доступність інфраструктури',
                            controller: false,
                            bindToAddress: false,
                            bindToAddressField: '',
                            mainField: 'FEATURE_DESC_UKR',
                            objectIdField: "FEATURE_ID"
                        }
                    ],
                    features: null,
                    loadMethod: 'GetWebACC',
                    loadMethodUrl: 'https://smart.khmr.gov.ua/arcgis/rest/services/WEBACC_LOCALL/MapServer/',
                    //loadMethodUrl: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/WEBACC_LOCALL/MapServer/',
                    //loadMethodUrl: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/WEBACC_LOCALL/MapServer/',
                    //раскрасска по типам
                    typesColors: {
                        fieldName: 'FEATURE_TYPE',
                        fieldName2: 'FEATURE_CODE',
                        fieldName3: null,
                        types: [
                            { value: "1:1", desc: "Заклади охорони здоров'я", value1: 1, value2: 1, ext: '.png', ext: '.png' },
                            { value: "2:1", desc: "Заклади охорони здоров'я", value1: 2, value2: 1, ext: '.png' },
                            { value: "3:1", desc: "Заклади охорони здоров'я", value1: 3, value2: 1, ext: '.png' },
                            { value: "1:2", desc: "Заклади освіти", value1: 1, value2: 2, ext: '.png' },
                            { value: "2:2", desc: "Заклади освіти", value1: 2, value2: 2, ext: '.png' },
                            { value: "3:2", desc: "Заклади освіти", value1: 3, value2: 2, ext: '.png' },
                            { value: "1:3", desc: "Органи судової влади", value1: 1, value2: 3, ext: '.png' },
                            { value: "2:3", desc: "Органи судової влади", value1: 2, value2: 3, ext: '.png' },
                            { value: "3:3", desc: "Органи судової влади", value1: 3, value2: 3, ext: '.png' },
                            { value: "1:4", desc: "Органи місцевого самоврядування", value1: 1, value2: 4, ext: '.png' },
                            { value: "2:4", desc: "Органи місцевого самоврядування", value1: 2, value2: 4, ext: '.png' },
                            { value: "3:4", desc: "Органи місцевого самоврядування", value1: 3, value2: 4, ext: '.png' },
                            { value: "1:5", desc: "Адміністративні послуги", value1: 1, value2: 5, ext: '.png' },
                            { value: "2:5", desc: "Адміністративні послуги", value1: 2, value2: 5, ext: '.png' },
                            { value: "3:5", desc: "Адміністративні послуги", value1: 3, value2: 5, ext: '.png' },
                            { value: "1:6", desc: "Заклади торговлі", value1: 1, value2: 6, ext: '.png' },
                            { value: "2:6", desc: "Заклади торговлі", value1: 2, value2: 6, ext: '.png' },
                            { value: "3:6", desc: "Заклади торговлі", value1: 3, value2: 6, ext: '.png' },
                            { value: "1:19", desc: "Банки", value1: 1, value2: 19, ext: '.png' },
                            { value: "2:19", desc: "Банки", value1: 2, value2: 19, ext: '.png' },
                            { value: "3:19", desc: "Банки", value1: 3, value2: 19, ext: '.png' },
                            { value: "1:8", desc: "Розваги та дозвілля", value1: 1, value2: 8, ext: '.png' },
                            { value: "2:8", desc: "Розваги та дозвілля", value1: 2, value2: 8, ext: '.png' },
                            { value: "3:8", desc: "Розваги та дозвілля", value1: 3, value2: 8, ext: '.png' },
                            { value: "1:9", desc: "Релігійні установи", value1: 1, value2: 9, ext: '.png' },
                            { value: "2:9", desc: "Релігійні установи", value1: 2, value2: 9, ext: '.png' },
                            { value: "3:9", desc: "Релігійні установи", value1: 3, value2: 9, ext: '.png' },
                            { value: "1:11", desc: "Транспорт (Зупинки)", value1: 1, value2: 11, ext: '.png' },
                            { value: "2:11", desc: "Транспорт (Зупинки)", value1: 2, value2: 11, ext: '.png' },
                            { value: "3:11", desc: "Транспорт (Зупинки)", value1: 3, value2: 11, ext: '.png' },
                            { value: "1:16", desc: "Підприємства, установи, заклади", value1: 1, value2: 16, ext: '.png' },
                            { value: "2:16", desc: "Підприємства, установи, заклади", value1: 2, value2: 16, ext: '.png' },
                            { value: "3:16", desc: "Підприємства, установи, заклади", value1: 3, value2: 16, ext: '.png' },
                            { value: "1:13", desc: "Готелі", value1: 1, value2: 13, ext: '.png' },
                            { value: "2:13", desc: "Готелі", value1: 2, value2: 13, ext: '.png' },
                            { value: "3:13", desc: "Готелі", value1: 3, value2: 13, ext: '.png' },
                            { value: "1:14", desc: "Заклади харчування", value1: 1, value2: 14, ext: '.png' },
                            { value: "2:14", desc: "Заклади харчування", value1: 2, value2: 14, ext: '.png' },
                            { value: "3:14", desc: "Заклади харчування", value1: 3, value2: 14, ext: '.png' }
                        ]
                    },
                    iconSize: { "width": 24, "height": 28 },
                    selectIconSize: { "width": 24, "height": 28 }
                    
                },
                //{
                //    id: 17,
                //    pId: 6,
                //    url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/MAFS/MapServer',
                //    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MAFS/MapServer',
                //    type: 'dynamic',
                //    dataType: 'layer',
                //    visibility: false,
                //    map_visibility: false,
                //    layerIds: [0, 1],
                //    //tolerance: 20,
                //    tolerance: {
                //        '200':[40, 2],
                //        '300':[40, 2],
                //        '500': [45, 5],
                //        '1000':[ 50, 10],
                //        '5000': [55, 15],
                //    },
                //    geometryType: 'Point',
                //    name: 'МАФи (тест)',
                //    nameVectorLayer: 'МАФ',
                //    opacity: 1,
                //    identScale: 8000,
                //    identify: [
                //        {
                //            id: 0,
                //            title: 'МАФ',
                //            identityFields: [
                //                { name: 'NAME', description: 'Назва' },
                //                { name: 'MAF_OWNER', description: 'Власник' },
                //                { name: 'MAF_ADDRESS', description: 'Адреса' },
                //                { name: 'MAF_OWNER_CONTACT', description: 'Контактні дані власника' },
                //                { name: 'MAF_OBJECT_PURPOSE', description: 'Цільове призначення' },
                //                { name: 'AGREE_PROPERTIES', description: 'Реквізити договору оренди' },
                //                { name: 'MAF_AGREE_END', description: 'Cтрок дії договору' }
                //            ],
                //            tocName: 'МАФ',
                //            controller: false,
                //            bindToAddress: false
                //        },
                //        {
                //            id: 1,
                //            title: 'МАФ (земельна ділянка)',
                //            identityFields: [
                //                { name: 'OBJECTID', description: '№' },
                //                { name: 'CADS', description: 'Кад. номер' },
                //                { name: 'OWNER_NAME', description: 'Власник' },
                //                //{ name: 'OWNER_EDRPOU', description: 'Код власника' },
                //                { name: 'CUSTOMER_NAME', description: 'Користувач' },
                //                //{ name: 'CUSTOMER_EDRPOU', description: 'Код користувача' },
                //                { name: 'NGO', description: 'НГО' },
                //                { name: 'NGO_DATE', description: 'Дата НГО' },
                //                { name: 'KVCPZ_CODE', description: 'Клас КВЦПЗ' },
                //                //{ name: 'KVCPZ_NAME', description: 'Клас КВЦПЗ' },
                //                { name: 'LAND_SIZE', description: 'Площа' },
                //                { name: 'AGREE_NUMBER', description: 'Договір' },
                //                //{ name: 'AGREE_SIGN_DATE', description: 'Дата підписання договору' },
                //                { name: 'AGREE_TYPE', description: 'Тип договору' },
                //                { name: 'AGREE_STATE', description: 'Стан договору' },
                //                { name: 'AGREE_START_DATE', description: 'Початок строку' },
                //                { name: 'AGREE_END_DATE', description: 'Завершення строку' },
                //                { name: 'LAND_COST', description: 'Вартість' },
                //                { name: 'NGO_PERCENT', description: 'Розмір від НГО' },
                //                { name: 'COST_CORRECTION', description: 'Уточнення вартості' },
                //                //{ name: 'AGREE_LINK', description: 'Посилання на договір', link: true },
                //                { name: 'RESOLUTION_NUMBER', description: 'Рішення' },
                //                //{ name: 'RESOLUTION_DATE', description: 'Дата рішення' },
                //                //{ name: 'RESOLUTION_LINK', description: 'Посилання на рішення', link: true },
                //                { name: 'RESOLUTION_PUBLISHER_NAME', description: 'Видавник' },
                //                //{ name: 'RESOLUTION_PUBLISHER_EDRPOU', description: 'Код видавника' }
                //            ],
                //            tocName: 'МАФ (земельна ділянка)',
                //            controller: false,
                //            bindToAddress: false
                //        }
                //    ],
                //    token: {
                //        need: false,
                //        str: ''
                //    }
                //},
                //{
                //    id: 17,
                //    pId: 1,
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/MAFS/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MAFS/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MAFS/MapServer',
                //    type: 'feature',
                //    dataType: 'layer',
                //    visibility: false,
                //    map_visibility: false,
                //    layerIds: [0],
                //    tolerance: 20,
                //    //tolerance: {
                //    //    '200': [40, 2],
                //    //    '300': [40, 2],
                //    //    '500': [45, 5],
                //    //    '1000': [50, 10],
                //    //    '5000': [55, 15],
                //    //},
                //    geometryType: 'Point',
                //    name: 'МАФи (тест)',
                //    nameVectorLayer: 'МАФ',
                //    opacity: 1,
                //    identScale: 8000,
                //    identify: [
                //        {
                //            id: 0,
                //            title: 'МАФ (тест)',
                //            identityFields: [
                //                { name: 'NAME', description: 'Назва' },
                //                { name: 'MAF_OWNER', description: 'Власник' },
                //                { name: 'MAF_ADDRESS', description: 'Адреса' },
                //                { name: 'MAF_OWNER_CONTACT', description: 'Контактні дані власника' },
                //                { name: 'MAF_OBJECT_PURPOSE', description: 'Цільове призначення' },
                //                { name: 'AGREE_PROPERTIES', description: 'Реквізити договору оренди' },
                //                { name: 'MAF_AGREE_END', description: 'Cтрок дії договору' }
                //            ],
                //            tocName: 'МАФ',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'NAME'
                //        }
                //    ],
                //    //token: {
                //    //    need: false,
                //    //    str: ''
                //    //}
                //},
                //{
                //    id: 18,
                //    pId: 1,
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/MAFS/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MAFS/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MAFS/MapServer',
                //    type: 'feature',
                //    dataType: 'layer',
                //    visibility: false,
                //    map_visibility: false,
                //    layerIds: [1],
                //    tolerance: 10,
                //    //tolerance: {
                //    //    '200': [40, 2],
                //    //    '300': [40, 2],
                //    //    '500': [45, 5],
                //    //    '1000': [50, 10],
                //    //    '5000': [55, 15],
                //    //},
                //    geometryType: 'Polygon',
                //    name: 'Оренда комунальних земель (тест)',
                //    nameVectorLayer: 'МАФ (земельна ділянка)',
                //    opacity: 1,
                //    identScale: 8000,
                //    identify: [
                //        {
                //            id: 1,
                //            title: 'Оренда комунальних земель (тест)',
                //            identityFields: [
                //                { name: 'OBJECTID', description: '№' },
                //                { name: 'CADS', description: 'Кад. номер' },
                //                { name: 'OWNER_NAME', description: 'Власник' },
                //                //{ name: 'OWNER_EDRPOU', description: 'Код власника' },
                //                { name: 'CUSTOMER_NAME', description: 'Користувач' },
                //                //{ name: 'CUSTOMER_EDRPOU', description: 'Код користувача' },
                //                { name: 'NGO', description: 'НГО' },
                //                { name: 'NGO_DATE', description: 'Дата НГО' },
                //                { name: 'KVCPZ_CODE', description: 'Клас КВЦПЗ' },
                //                //{ name: 'KVCPZ_NAME', description: 'Клас КВЦПЗ' },
                //                { name: 'LAND_SIZE', description: 'Площа' },
                //                { name: 'AGREE_NUMBER', description: 'Договір' },
                //                //{ name: 'AGREE_SIGN_DATE', description: 'Дата підписання договору' },
                //                { name: 'AGREE_TYPE', description: 'Тип договору' },
                //                { name: 'AGREE_STATE', description: 'Стан договору' },
                //                { name: 'AGREE_START_DATE', description: 'Початок строку' },
                //                { name: 'AGREE_END_DATE', description: 'Завершення строку' },
                //                { name: 'LAND_COST', description: 'Вартість' },
                //                { name: 'NGO_PERCENT', description: 'Розмір від НГО' },
                //                { name: 'COST_CORRECTION', description: 'Уточнення вартості' },
                //                //{ name: 'AGREE_LINK', description: 'Посилання на договір', link: true },
                //                { name: 'RESOLUTION_NUMBER', description: 'Рішення' },
                //                //{ name: 'RESOLUTION_DATE', description: 'Дата рішення' },
                //                //{ name: 'RESOLUTION_LINK', description: 'Посилання на рішення', link: true },
                //                { name: 'RESOLUTION_PUBLISHER_NAME', description: 'Видавник' },
                //                //{ name: 'RESOLUTION_PUBLISHER_EDRPOU', description: 'Код видавника' }
                //            ],
                //            tocName: 'МАФ (земельна ділянка)',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'CUSTOMER_NAME'
                //        }
                //    ],
                //    //token: {
                //    //    need: false,
                //    //    str: ''
                //    //}
                //},
                //{
                //    id: 19,
                //    pId: 7,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS_ZHITLO/MapServer',
                //    type: 'dynamic',
                //    visibility: false,
                //    map_visibility: false,
                //    name: 'Відомче житло',
                //    layerIds: [2],
                //    tolerance: 10,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Polygon',
                //    nameVectorLayer: 'Відомче житло',
                //    identScale: 0,
                //    identify: [
                //        {
                //            id: 15,
                //            title: "Відомче житло",
                //            //identityFields: [
                //            //    { name: 'FULLADDRUA', description: 'Адреса' },
                //            //    { name: 'FLOOR', description: 'Поверховість' },
                //            //    { name: 'BAL_TYPE', description: 'Вид об\'єднання' },
                //            //    { name: 'BAL_NAME', description: 'Найменування об\'єднання' },
                //            //    //{ name: 'BAL_BOSS', description: 'ПІБ голови об\'єднання (за&#160;наявністю)' },
                //            //    { name: 'DIST', description: 'Район міста' },
                //            //    { name: 'STR_TYPE', description: 'Тип вулиці' },
                //            //    { name: 'STR_NAME', description: 'Найменування вулиці' },
                //            //    { name: 'STR_NUM', description: '№ будинку' },
                //            //    { name: 'STR_SUFF', description: 'Літера, дробова частина №' },
                //            //    { name: 'STR_BLOCK', description: 'Тип житла' },
                //            //    //{ name: 'zks_num', description: 'Постачальник опалення' },
                //            //    //{ name: 'balancer', description: 'Обслуговування' },
                //            //    //{ name: 'warmcon', description: 'Опалення' },
                //            //    { name: 'warm_firm', description: 'Централізоване опалення' },
                //            //    { name: 'heatwater_firm', description: 'Централізоване гаряче водопостачання' },
                //            //    { name: 'water_firm', description: 'Централізоване холодне водопостачання та водовідведення' },
                //            //    { name: 'warm_auto', description: 'Автоматика системи опалення' },
                //            //    { name: 'sewerage_firm', description: 'Обслуговування внутрішньобудинкових систем холодного водопостачання та каналізації' },
                //            //    { name: 'warm_service', description: 'Обслуговування внутрішньобудинкових систем опалення та гарячого водопостачання' },
                //            //    { name: 'elevator_service', description: 'Обслуговування ліфтів' },
                //            //    { name: 'network_service', description: 'Обслуговування внутрішньобудинкових електромереж' },
                //            //],
                //            identityFields: [
                //                { name: 'F1', description: 'Адреса' },
                //                { name: 'F0', description: 'Район' },
                //                { name: 'F2', description: 'Кількість поверхів' },
                //                { name: 'F3', description: 'Кількість під’їздів' },
                //                { name: 'F4', description: 'Форма власності (управління)' },
                //                { name: 'F5', description: 'Найменування організації-управителя' },
                //                { name: 'F6', description: 'Матеріал покрівлі' },
                //                { name: 'F7', description: 'Матеріал зовнішніх стін' },
                //                { name: 'F8', description: 'Централізоване теплопостачання' },
                //                { name: 'F9', description: 'Обслуговування ВБС теплопостачання' },
                //                { name: 'F10', description: 'Централізоване гаряче водопостачання' },
                //                { name: 'F11', description: 'Обслуговування ВБС гар. водопостачання' },
                //                { name: 'F12', description: 'Централізоване водопостачання' },
                //                { name: 'F13', description: 'Обслуговування ВБС хол. водопостачання' },
                //                { name: 'F14', description: 'Централізоване водовідведення' },
                //                { name: 'F15', description: 'Обслуговування ВБС водовідведення та внутр. зливової каналізації' },
                //                { name: 'F16', description: 'Обслуговування зовнішніх мереж зливової каналізації' },
                //                { name: 'F17', description: 'Обслуговування ВБС електропостачання та освітлення' },
                //                { name: 'F18', description: 'Обслуговування ліфтового господарства' },
                //                { name: 'F19', description: 'Обслуговування систем диспетчеризації' },
                //                { name: 'F20', description: 'Обслуговування димовентканалів' },
                //                { name: 'F21', description: 'Прибирання прибудинкової території' },
                //                { name: 'F22', description: 'Вивезення ТПВ' },
                //                { name: 'F23', description: 'Доставка газу' },
                //            ],
                //            tocName: 'Відомче житло',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'FULLADDRUA'
                //        }
                //    ]
                //},
                {
                    id: 20,
                    pId: 7,
                    //старі підключення
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS_ZHITLO/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'Приватний сектор',
                    layerIds: [4],
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Polygon',
                    nameVectorLayer: 'Приватний сектор',
                    identScale: 0,
                    identify: [
                        {
                            id: 16,
                            title: "Приватний сектор",
                            //identityFields: [
                            //    { name: 'FULLADDRUA', description: 'Адреса' },
                            //    { name: 'FLOOR', description: 'Поверховість' },
                            //    { name: 'DIST', description: 'Район міста' },
                            //    { name: 'STR_NAME', description: 'Найменування вулиці' },
                            //    { name: 'STR_NUM', description: '№ будинку' },
                            //],
                            identityFields: [
                                { name: 'F1', description: 'Адреса' },
                                { name: 'F0', description: 'Район' },
                                { name: 'F2', description: 'Кількість поверхів' },
                                { name: 'F3', description: 'Кількість під’їздів' },
                                { name: 'F4', description: 'Форма власності (управління)' },
                                { name: 'F5', description: 'Найменування організації-управителя' },
                                { name: 'F6', description: 'Матеріал покрівлі' },
                                { name: 'F7', description: 'Матеріал зовнішніх стін' },
                                { name: 'F8', description: 'Централізоване теплопостачання' },
                                { name: 'F9', description: 'Обслуговування ВБС теплопостачання' },
                                { name: 'F10', description: 'Централізоване гаряче водопостачання' },
                                { name: 'F11', description: 'Обслуговування ВБС гар. водопостачання' },
                                { name: 'F12', description: 'Централізоване водопостачання' },
                                { name: 'F13', description: 'Обслуговування ВБС хол. водопостачання' },
                                { name: 'F14', description: 'Централізоване водовідведення' },
                                { name: 'F15', description: 'Обслуговування ВБС водовідведення та внутр. зливової каналізації' },
                                { name: 'F16', description: 'Обслуговування зовнішніх мереж зливової каналізації' },
                                { name: 'F17', description: 'Обслуговування ВБС електропостачання та освітлення' },
                                { name: 'F18', description: 'Обслуговування ліфтового господарства' },
                                { name: 'F19', description: 'Обслуговування систем диспетчеризації' },
                                { name: 'F20', description: 'Обслуговування димовентканалів' },
                                { name: 'F21', description: 'Прибирання прибудинкової території' },
                                { name: 'F22', description: 'Вивезення ТПВ' },
                                { name: 'F23', description: 'Доставка газу' },
                            ],
                            tocName: 'Приватний сектор',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'FULLADDRUA'
                        }
                    ]
                },
                //{
                //    id: 23,
                //    pId: 7,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'feature',
                //    visibility: false,
                //    map_visibility: false,
                //    checkUpdate: {
                //        method: 'checkUpdateHeating',
                //        url: '/opendataportal/Home/UpdateDataFromGoogleSheet',
                //    },
                //    name: 'Підключення опалення',
                //    layerIds: [18],
                //    tolerance: 10,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Polygon',
                //    nameVectorLayer: 'Опалення',
                //    identScale: 0,
                //    identify: [
                //        {
                //            id: 16,
                //            title: "Підключення опалення",
                //            identityFields: [
                //                { name: 'RAYON', description: 'Район' },
                //                { name: 'FULLADDRUA', description: 'Адреса' },
                //                //{ name: 'FLOOR', description: 'Поверховість' },
                //                { name: 'WARMCON', description: 'Стан підключення' },
                //                { name: 'WARMORDER', description: 'Номер у черзі' },
                //                //{ name: 'DATEWARMCONS', description: 'Дати підключення' },
                //                //{ name: 'EXPDATEWARMCON', description: 'Строк підключеня' },
                //                //{ name: 'RAYON', description: 'Район' }
                //                //{ name: 'commnts', description: 'Ділянка КП Жилкомсевіс' },
                //                //{ name: 'balancer', description: 'Обслуговування' },
                //                //{ name: 'warmcon', description: 'Опалення' },
                //            ],
                //            tocName: 'Опалення',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'FULLADDRUA'
                //        }
                //    ],
                //    token: {
                //        need: true,
                //        str: ''
                //    },
                //},
                //{
                //    id: 24,
                //    pId: 8,
                //    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                //    type: 'feature',
                //    visibility: false,
                //    map_visibility: false,
                //    checkUpdate: {
                //        method: 'UpdateHydrantsFromGoogleSheet',
                //        url: '/opendataportal/Home/UpdateHydrantsFromGoogleSheet',
                //    },
                //    name: 'Гідранти',
                //    layerIds: [19],
                //    tolerance: 30,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'Гідранти',
                //    identScale: 5000,
                //    identify: [
                //        {
                //            id: 16,
                //            title: "Гідранти",
                //            identityFields: [
                //                { name: 'DISTRICT', description: 'Район' },
                //                { name: 'ADDRESS', description: 'Адреса' },
                //                { name: 'TYPE_', description: 'Тип вододжерела' },
                //                { name: 'STATE', description: 'Технічний стан' },
                //                { name: 'DEFECT', description: 'Дефект' },
                //                { name: 'INDEXPRESENCE', description: 'Наявність покажчику' },
                //                { name: 'TYPE_DIAMETER', description: 'Тип та диаметр мережі' },
                //                { name: 'PLACE', description: 'Місце знаходження ПГ' },
                //                { name: 'OWNER', description: 'Відомча належність' },
                //                { name: 'VOLUME', description: 'Об\'єм(куб.м)' },
                //                { name: 'WATERINTAKE', description: 'Наявність водозабору' },
                //                { name: 'NIPPLES', description: 'Патрубки' },
                //                { name: 'MAXTECHNICS', description: 'Макс. кількість пожежної техніки' },
                //                { name: 'NETWORKTYPE', description: 'Тип мережі' },
                //                { name: 'DIAMETER', description: 'Диаметр мережі' },
                //                { name: 'NUMBER_', description: 'Номер' },
                //                { name: 'DIVISION', description: 'Підрозділ' }],
                //            tocName: 'Гідранти',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'ADDRESS'
                //        }
                //    ],
                //    token: {
                //        need: true,
                //        str: ''
                //    },
                //    typesColors: {
                //        fieldName: 'TYPE_',
                //        fieldName2: 'STATE',
                //        fieldName3: null,
                //        types: [
                //            { value: "ВВ:справний", desc: "Водонапірна вежа", value1: 'ВВ', value2: 'справний', ext: '.svg' },
                //            { value: "ВВ:не справний", desc: "Водонапірна вежа", value1: 'ВВ', value2: 'не справний', ext: '.svg' },
                //            { value: "ВВ:демонтований", desc: "Водонапірна вежа", value1: 'ВВ', value2: 'демонтований', ext: '.svg' },
                //            { value: "ВВ:дані відсутні", desc: "Водонапірна вежа", value1: 'ВВ', value2: 'дані відсутні', ext: '.svg' },

                //            { value: "Г:справний", desc: "Градирні", value1: 'Г', value2: 'справний', ext: '.svg' },
                //            { value: "Г:не справний", desc: "Градирні", value1: 'Г', value2: 'не справний', ext: '.svg' },
                //            { value: "Г:демонтований", desc: "Градирні", value1: 'Г', value2: 'демонтований', ext: '.svg' },
                //            { value: "Г:дані відсутні", desc: "Градирні", value1: 'Г', value2: 'дані відсутні', ext: '.svg' },

                //            { value: "П:справний", desc: "Пожежні крани", value1: 'П', value2: 'справний', ext: '.svg' },
                //            { value: "П:не справний", desc: "Пожежні крани", value1: 'П', value2: 'не справний', ext: '.svg' },
                //            { value: "П:демонтований", desc: "Пожежні крани", value1: 'П', value2: 'демонтований', ext: '.svg' },
                //            { value: "П:дані відсутні", desc: "Пожежні крани", value1: 'П', value2: 'дані відсутні', ext: '.svg' },

                //            { value: "ПB:справний", desc: "Пожежні водойми", value1: 'ПB', value2: 'справний', ext: '.svg' },
                //            { value: "ПB:не справний", desc: "Пожежні водойми", value1: 'ПB', value2: 'не справний', ext: '.svg' },
                //            { value: "ПB:демонтований", desc: "Пожежні водойми", value1: 'ПB', value2: 'демонтований', ext: '.svg' },
                //            { value: "ПB:дані відсутні", desc: "Пожежні водойми", value1: 'ПB', value2: 'дані відсутні', ext: '.svg' },

                //            { value: "ПГ:справний", desc: "Пожежні гідранти", value1: 'ПГ', value2: 'справний', ext: '.svg' },
                //            { value: "ПГ:не справний", desc: "Пожежні гідранти", value1: 'ПГ', value2: 'не справний', ext: '.svg' },
                //            { value: "ПГ:демонтований", desc: "Пожежні гідранти", value1: 'ПГ', value2: 'демонтований', ext: '.svg' },
                //            { value: "ПГ:дані відсутні", desc: "Пожежні гідранти", value1: 'ПГ', value2: 'дані відсутні', ext: '.svg' },
                //        ]
                //    },
                //    iconSize: { "width": 13, "height": 13 },
                //    selectIconSize: { "width": 16, "height": 16 },
                //    labelingInfo: {
                //        "labelExpressionInfo": { "value": "{TYPE_}-{STATE}" },
                //        "labelPlacement": "above-center",
                //        "minScale": 3001, //specified scale range where labels are visible
                //        "maxScale": 0,
                //    },
                //},
                {
                    id: 41,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateInvicibilityFromGoogleSheet',
                        url: '/opendataportal/home/UpdateInvicibilityFromGoogleSheet',
                    },
                    typesColors: {
                        fieldName: 'RESERVE_5',
                        fieldName2: null,
                        fieldName3: null,
                        types: [
                          // { value: "цілодобово", desc: "Цілодобово", value1: 'цілодобово', value2: '', ext: '.svg' },
                           // { value: 'цілодобово, у разі аварійного відключення постачання електричної енергії та/або постачання теплової енергії більш ніж на 3 год', desc: " ", value1: 'цілодобово', value2: '', ext: '.svg' },
                            //{ value: 'щоденно з 08:00 до 20:00, а також у разі аварійного відключення постачання електричної енергії та/або постачання теплової енергії більш ніж на 3 год', desc: " ", value1: 'цілодобово', value2: '', ext: '.svg' },

                            //{ value: "в режимі \"очікування\"", desc: 'В режимі "очікування"', value1: "в режимі \"очікування\"", value2: '', ext: '.svg' },
                            //{ value: null, desc: 'В режимі "очікування"', value1: 'Null', value2: '', ext: '.svg' }
                            { value: "1", desc: "Комунальна власність", value1: '1', value2: '', ext: '.svg' },
                            { value: '2', desc: "Не комунальна власність", value1: '2', value2: '', ext: '.svg' },
                        ]
                    },
                    name: 'Пункти незламності',
                    layerIds: [16],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    expression: {
                        string: "RESERVE_5 = 1",
                        auth_string: {
                            string: "",
                            roles:["Admins"]
                        },
                    },
                    geometryType: 'Point',
                    nameVectorLayer: 'Пункти незламності',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Пункти незламності',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'LOCATION', description: 'Місце розташування' },
                                // { name: 'RESERVE_1', description: 'Вид укриття' },
                                { name: 'RESERVE_2', description: 'Режим роботи' },
                                //{ name: 'RESERVE_3', description: 'Вид укриття' },
                                //{ name: 'RESERVE_4', description: 'Ключі від укриття' },
                                //{ name: 'RESERVE_5', description: 'Вид укриття' }
                                { name: 'POINTTYPE', description: 'Тип пункту' },
                                { name: 'HEATING', description: 'Обігрів' },
                                { name: 'GENERATOR', description: 'Генератор' },
                                { name: 'PHONECHARGER', description: 'Зарядка для телефонів' },
                                { name: 'WATER', description: 'Вода' },
                                { name: 'INTERNET', description: 'Інтернет' },
                                { name: 'NETWORK', description: 'Зв\'язок' },
                                { name: 'MEDCHEST', description: 'Аптечка' },
                            ],
                            tocName: 'Пункти незламності',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'ADDRESS',
                        }
                    ],
                    iconSize: { "width": 30, "height": 30 },
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},

                },
                //{
                //    id: 25,
                //    pId: 11,
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                //    type: 'feature',
                //    visibility: false,
                //    map_visibility: false,
                //    checkUpdate: {
                //        method: 'UpdateHeatingPointsFromGoogleSheet',
                //        url: '/opendataportal/Home/UpdateHeatingPointsFromGoogleSheet',
                //    },
                //    name: 'Пункти обігріву',
                //    layerIds: [1],
                //    tolerance: 30,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'Пункти обігріву',
                //    identScale: 50000,
                //    identify: [
                //        {
                //            id: 16,
                //            title: "Пункти обігріву",
                //            identityFields: [
                //                { name: 'DISTRICT', description: 'Район' },
                //                { name: 'ADDRESS', description: 'Адреса' },
                //                { name: 'PLACE', description: 'Місце знаходження ПГ' },
                //                { name: 'WORKTIME', description: 'Часи роботи' },
                //                { name: 'AREA', description: 'Площа, м.кв' },
                //                { name: 'PEOPLE_COUNT', description: 'Можливо розмістити, осіб' },
                //                { name: 'HAS_LIGHTING', description: 'Наявність освітлення' },
                //                { name: 'HAS_WATERSUPPLY', description: 'Наявність водопостачання' },
                //                { name: 'HAS_BATHROOM', description: 'Наявність санвузлу' },
                //                { name: 'PHONE', description: 'Контактний номер телефону' },
                //                { name: 'HAS_FOODOUTLET', description: 'Можливість харчування' },
                //                { name: 'FOODOUTLET_WORKTIME', description: 'Час роботи пункту харчування' },

                //            ],
                //            tocName: 'Пункти обігріву',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'ADDRESS'
                //        }
                //    ],
                //    //token: {
                //    //    need: true,
                //    //    str: ''
                //    //},
                //},
                {
                    id: 26,
                    pId: 8,
                    //pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateStopsSheltersFromGoogleSheet',
                        url: '/opendataportal/Home/UpdateStopsSheltersFromGoogleSheet',
                    },
                    name: 'Зупинки-укриття "Захист"',
                    layerIds: [2],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Зупинки-укриття "Захист"',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Зупинки-укриття "Захист"',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'AREA', description: 'Площа, м.кв' },
                                { name: 'PEOPLE_COUNT', description: 'Можливо розмістити, осіб' },
                                { name: 'HAS_HEATING', description: 'Наявність обігріву' },
                                { name: 'HAS_LIGHTING', description: 'Наявність освітлення' },
                                { name: 'HAS_WATERSUPPLY', description: 'Наявність водопостачання' },
                                { name: 'HAS_BATHROOM', description: 'Наявність санвузлу' },
                                { name: 'PEOPLE_COUNT', description: 'Можливо розмістити, осіб' },
                                { name: 'PHONE', description: 'Контактний номер телефону' },
                                { name: 'EL_SOCKET_COUNT', description: 'Кіль-ть електричних розеток 220В' }
                            ],
                            tocName: 'Зупинки-укриття "Захист"',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'ADDRESS'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 27,
                    pId: 11,
                    //url: 'https://www.google.com/maps/d/u/0/viewer?mid=1Q9sVNcUtVW9M9oENKnlUWHX_3lHJVkE&ll=49.99725900600058%2C36.2918713630875&z=12',
                    url: 'https://www.google.com/maps/d/u/0/viewer?mid=1Q9sVNcUtVW9M9oENKnlUWHX_3lHJVkE&ll=49.99608496190264%2C36.2871175&z=11',
                    type: 'link',
                    visibility: false,
                    map_visibility: false,                  
                    name: 'Тимчасові маршрути на період відключення електроенергії в м. Харкові',
                    dataType: 'layer',
                    geometryType: 'Line'
                },
                {
                    id: 28,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateFoodOutletsromGoogleSheet',
                        url: '/opendataportal/Home/UpdateFoodOutletsromGoogleSheet',
                    },
                    name: 'Пункти харчування населення',
                    layerIds: [3],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Пункти харчування населення',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Пункти харчування населення',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'PLACE', description: 'Місце розташування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'COMMENTS', description: 'Примітка' }],
                            tocName: 'Пункти харчування населення',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'ADDRESS'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 29,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',// 'dynamic'
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateHospitalsFromGoogleSheet',
                        url: '/opendataportal/Home/UpdateHospitalsFromGoogleSheet',
                    },
                    name: 'Лікарні',
                    layerIds: [4],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Лікарні',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Лікарні',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'PHONE', description: 'Контактний номер телефону' }],
                            tocName: 'Лікарні',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'ADDRESS'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 30,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdatePolyclinicsFromGoogleSheet',
                        url: '/opendataportal/Home/UpdatePolyclinicsFromGoogleSheet',
                    },
                    name: 'Поліклініки',
                    layerIds: [5],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Поліклініки',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Поліклініки',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'PHONE', description: 'Контактний номер телефону' }],
                            tocName: 'Поліклініки',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 31,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateVetClinicsFromGoogleSheet',
                        url: '/opendataportal/home/UpdateVetClinicsFromGoogleSheet',
                    },
                    name: 'Ветеринарні клініки',
                    layerIds: [6],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Ветеринарні клініки',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Ветеринарні клініки',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'PHONE', description: 'Контактний номер телефону' }],
                            tocName: 'Ветеринарні клініки',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 32,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdatePharmaciesFromGoogleSheet',
                        url: '/opendataportal/home/UpdatePharmaciesFromGoogleSheet',
                    },
                    name: 'Аптеки',
                    layerIds: [7],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Аптеки',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Аптеки',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'PHONE', description: 'Контактний номер телефону' }],
                            tocName: 'Аптеки',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 33,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateGasStationsFromGoogleSheet',
                        url: '/opendataportal/home/UpdateGasStationsFromGoogleSheet',
                    },
                    name: 'АЗС',
                    layerIds: [8],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'АЗС',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'АЗС',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'GASOLINE', description: 'Бензин' },
                                { name: 'DIESEL', description: 'Дизель' },
                                { name: 'GAS', description: 'Газ' }],
                            tocName: 'АЗС',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 34,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdatePetShopsFromGoogleSheet',
                        url: '/opendataportal/home/UpdatePetShopsFromGoogleSheet',
                    },
                    name: 'Зоомагазини',
                    layerIds: [9],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Зоомагазини',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Зоомагазини',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' }],
                            tocName: 'Зоомагазини',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 35,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateFoodShopsFromGoogleSheet',
                        url: '/opendataportal/home/UpdateFoodShopsFromGoogleSheet',
                    },
                    name: 'Продовольчі магазини',
                    layerIds: [10],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Продовольчі магазини',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Продовольчі магазини',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'PRODUCT_TYPES', description: 'Типи продукції' },
                            ],
                            tocName: 'Продовольчі магазини',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 36,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateNonFoodShopsFromGoogleSheet',
                        url: '/opendataportal/home/UpdateNonFoodShopsFromGoogleSheet',
                    },
                    name: 'Непродовольчі магазини',
                    layerIds: [11],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Непродовольчі магазини',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Непродовольчі магазини',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'PRODUCT_TYPES', description: 'Типи продукції' },
                            ],
                            tocName: 'Непродовольчі магазини',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 37,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateLsMarketsFromGoogleSheet',
                        url: '/opendataportal/home/UpdateLsMarketsFromGoogleSheet',
                    },
                    name: 'Ринки',
                    layerIds: [12],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Ринки',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Ринки',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' },
                                { name: 'WORKTIME', description: 'Часи роботи' },
                                { name: 'PRODUCT_TYPES', description: 'Типи продукції' },
                            ],
                            tocName: 'Ринки',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                {
                    id: 38,
                    pId: 8,
                    //pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdatePoliceFromGoogleSheet',
                        url: '/opendataportal/home/UpdatePoliceFromGoogleSheet',
                    },
                    name: 'Відділи поліції',
                    layerIds: [13],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Відділи поліції',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Відділи поліції',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Адреса' },
                                { name: 'NAME', description: 'Найменування' }
                            ],
                            tocName: 'Відділи поліції',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'NAME'
                        }
                    ],
                    token: {
                        need: true,
                        role: 'DSNSLayers',
                        str: '',
                    },
                },
                {
                    id: 39,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'feature',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateWaterSourcesFromGoogleSheet',
                        url: '/opendataportal/home/UpdateWaterSourcesFromGoogleSheet',
                    },
                    name: 'Джерела водопостачання',
                    layerIds: [14],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Джерела водопостачання',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Джерела водопостачання',
                            identityFields: [
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'LOCATION', description: 'Місцезнаходження' },
                                { name: 'TYPE', description: 'Вид' }
                            ],
                            tocName: 'Джерела водопостачання',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'LOCATION'
                        }
                    ],
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                //{
                //    id: 40,
                //    pId: 11,
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                //    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                //    type: 'dynamic',
                //    visibility: false,
                //    map_visibility: false,
                //    checkUpdate: {
                //        method: 'UpdateSheltersFromGoogleSheet',
                //        url: '/opendataportal/home/UpdateSheltersFromGoogleSheet',
                //    },
                //    name: 'Укриття',
                //    layerIds: [15],
                //    tolerance: 30,
                //    order: 0,
                //    dataType: 'layer',
                //    geometryType: 'Point',
                //    nameVectorLayer: 'Укриття',
                //    identScale: 50000,
                //    identify: [
                //        {
                //            id: 16,
                //            title: 'Укриття',
                //            identityFields: [
                //                { name: 'DISTRICT', description: 'Район' },
                //                { name: 'ADDRESS', description: 'Адреса' },
                //                { name: 'BUILDING', description: 'Споруда' },
                //                { name: 'TYPE', description: 'Вид укриття' },
                //                { name: 'WHERE_KEYS', description: 'Ключі від укриття' }
                //            ],
                //            tocName: 'Укриття',
                //            controller: false,
                //            bindToAddress: false,
                //            mainField: 'ADDRESS',
                //            mainField2: 'BUILDING',
                //        }
                //    ],
                //    //token: {
                //    //    need: true,
                //    //    str: ''
                //    //},
                //},
                {
                    id:42,
                    pId: 4,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/dug_multi_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/dug_multi_web/MapServer',//RenameStreets

                    type: 'dynamic',
                    visibility: false,
                    map_visibility:false,
                    name: 'Перейменування вулиць',
                    layerIds: [17],
                    tolerance: 50,
                    order: 0,
                    dataType: 'layer',
                    //geometryType: 'Line',
                    nameVectorLayer: 'Перейменування вулиць',
                    identScale: 0,
                    identify: [
                        {
                            id: 0,
                            title: 'Перейменування вулиць',
                            identityFields: [
                                { name: 'FULL_UA', description: 'Назва' },
                                { name: 'ALT_NAME', description: 'Застаріла назва' },
                                { name: 'COMMENTS', description: 'Опис' },],
                            tocName: 'Перейменування вулиць',
                            //controller: true,
                            //method: 'GetDugById',
                            bindToAddress: false,
                            mainField: 'FULL_UA',
                        }
                    ],
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                },
                {
                    id:43,
                    pId: 4,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/dug_multi_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/dug_multi_web/MapServer',//RenameStreets

                    type: 'dynamic',
                    visibility: false,
                    map_visibility:false,
                    name: 'Пропозиції щодо перейменування вулиць 2024',
                    layerIds: [18],
                    tolerance: 50,
                    order: 0,
                    dataType: 'layer',
                    //geometryType: 'Line',
                    nameVectorLayer: 'Пропозиції щодо перейменування вулиць 2024',
                    identScale: 0,
                    identify: [
                        {
                            id: 0,
                            title: 'Пропозиції щодо перейменування вулиць 2024',
                            identityFields: [
                                { name: 'FULL_UA', description: 'Назва' },
                                { name: 'ALT_NAME', description: 'Застаріла назва' },
                                { name: 'COMMENTS', description: 'Опис' },],
                            tocName: 'Пропозиції щодо перейменування вулиць 2024',
                            //controller: true,
                            //method: 'GetDugById',
                            bindToAddress: false,
                            mainField: 'FULL_UA',
                        }
                    ],
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                },
                //{
                //    id: 44,
                //    pId: 11,
                //    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',

                //    type: 'dynamic',
                //    visibility: false,
                //    map_visibility: false,
                //    name: 'Місця для збору небезпечних відходів',
                //    layerIds: [19],
                //    tolerance: 50,
                //    order: 0,
                //    dataType: 'layer',
                //    //geometryType: 'Line',
                //    nameVectorLayer: 'Відходи',
                //    identScale: 0,
                //    //Район	Адреса	Розташовано в районі	Часи роботи	Перелік речовин	Фото
                //    identify: [
                //        {
                //            id: 0,
                //            title: 'Місця для збору небезпечних відходів',
                //            identityFields: [
                //                { name: 'f1', description: 'Район' },
                //                { name: 'f2', description: 'Адреса' },
                //                { name: 'f3', description: 'Розташовано в районі' },
                //                { name: 'f4', description: 'Часи роботи' },
                //                { name: 'f5', description: 'Перелік речовин' },
                //            ],
                //            tocName: 'Місця для збору небезпечних відходів',
                //            //controller: true,
                //            //method: 'GetDugById',
                //            bindToAddress: false,
                //            mainField: 'f2',
                //            photoField: "PHOTOS",
                //            selectedMarkerFileName: "select_55.svg",
                //        }
                //    ],
                //    //iconSize: { "width": 30, "height": 30 },
                //    selectIconSize: { "width": 40, "height": 40 },
                //    //token: {
                //    //    need: true,
                //    //    str: ''
                //    //},
                //},
                {
                    id: 45,
                    pId: 11,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/MCS/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/MCS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    checkUpdate: {
                        method: 'UpdateWaterDrinkPointsFromGoogleSheet',
                        url: '/opendataportal/home/UpdateWaterDrinkPointsFromGoogleSheet',
                    },
                    name: 'Точки питної води',
                    layerIds: [20],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'Точки питної води',
                    identScale: 50000,
                    identify: [
                        {
                            id: 16,
                            title: 'Точки питної води',
                            identityFields: [
                                { name: 'TYPE', description: 'Вид' },
                                { name: 'DISTRICT', description: 'Район' },
                                { name: 'ADDRESS', description: 'Місцезнаходження' },   
                                { name: 'WORKTIME', description: 'Час роботи' },
                                { name: 'PRICE', description: 'Вартість послуги' },
                                { name: 'SUPPORT_PHONE', description: 'Номер техпідтримки' }
                                
                            ],
                            tocName: 'Точки питної води',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'ADDRESS'
                        }
                    ],
                    selectIconSize: { "width": 40, "height": 40 },
                    //token: {
                    //    need: true,
                    //    str: ''
                    //},
                },
                //------------------
                {
                    id: 51,
                    pId: 12,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'DSNSZones',
                    layerIds: [2],
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Polygon',
                    nameVectorLayer: 'DSNSZones',
                    legendName:'Зони ДСНС',
                    identScale: 50000,
                    identify: [
                        {
                            id: 51,
                            title: 'Зони ДСНС',
                            identityFields: [
                                { name: 'Name', description: 'Номер' },
                                { name: 'PopupInfo', description: 'Деталі' }
                            ],
                            tocName: 'DSNSZones',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'Name',
                            //table: "DSNS_1_TB",
                            //photoField: "PHOTOS",
                           // documField: "DOCUMS",
                            //selectedMarkerFileName: "select_51.png",
                           // printIdentity: true
                        }
                    ],
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                },
                {
                    id: 52,
                    pId: 12,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'DSNSHydrants',
                    layerIds: [3],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'DSNSHydrants',
                    legendName:'Гідранти',
                    identScale: 50000,
                    identify: [
                        {
                            id: 51,
                            title: 'Гідранти',
                            identityFields: [
                                { name: 'Name', description: 'Назва' },
                                { name: 'PopupInfo', description: 'Деталі' }
                            ],
                            tocName: 'DSNSHydrants',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'Name',
                            //table: "DSNS_1_TB",
                            //photoField: "PHOTOS",
                           // documField: "DOCUMS",
                            //selectedMarkerFileName: "select_51.png",
                           // printIdentity: true
                        }
                    ],
                    selectIconSize: { "width": 40, "height": 40 },
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                },
                {
                    id: 53,
                    pId: 12,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'DSNS_1_TB',                   
                    layerIds: [0],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'DSNS_1_TB',
                    legendName: '',
                    identScale: 50000,
                    identify: [
                        {
                            id: 53,
                            title: '',
                            identityFields: [],
                            tocName: 'DSNS_1_TB',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'f2',
                            table: "DSNS_1_TB",
                            //photoField: "PHOTOS",
                            documField: "DOCUMS",
                            selectedMarkerFileName: "select_53.png",
                            printIdentity:true
                        }
                    ],
                    selectIconSize: { "width": 20, "height": 20 },
                    token: {
                        need: true,
                        str: '',
                        role:'DSNSLayers'
                    },
                    table: {
                        tableName: "DSNS_1_TB",
                        columns: [],
                        currentData: [],
                        filters:[],
                    },
                    expression: {
                        string: "",
                        auth_string: {
                            string: "",
                            roles: ["DSNSLayers"]
                        },
                    },
                },
                {
                    id: 54,
                    pId: 12,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'DSNS_2_TB',
                    layerIds: [1],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'DSNS_2_TB',
                    legendName: '',
                    identScale: 50000,
                    identify: [
                        {
                            id: 54,
                            title: '',
                            identityFields: [],
                            tocName: 'DSNS_2_TB',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'f2',
                            table: "DSNS_2_TB",
                            //photoField: "PHOTOS",
                            documField: "DOCUMS",
                            selectedMarkerFileName: "select_54.png",
                            printIdentity: true
                        }
                    ],
                    selectIconSize: { "width": 20, "height": 20 },
                    token: {
                        need: true,
                        str: '',
                        role:'DSNSLayers'
                    },
                    table: {
                        tableName: "DSNS_2_TB",
                        columns: [],
                        currentData: [],
                        filters: [],
                    },
                    expression: {
                        string: "",
                        auth_string: {
                            string: "",
                            roles: ["DSNSLayers"]
                        },
                    },
                },
                {
                    id: 55,
                    pId: 12,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'DSNS_3_TB',
                    layerIds: [4],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'DSNS_3_TB',
                    legendName: '',
                    identScale: 50000,
                    identify: [
                        {
                            id: 54,
                            title: '',
                            identityFields: [],
                            tocName: 'DSNS_3_TB',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'f2',
                            table: "DSNS_3_TB",
                            //photoField: "PHOTOS",
                            documField: "DOCUMS",
                            selectedMarkerFileName: "select_55.svg",
                            printIdentity: true
                        }
                    ],
                    selectIconSize: { "width": 24, "height": 24 },
                    token: {
                        need: true,
                        str: '',
                        role:'DSNSLayers'
                    },
                    table: {
                        tableName: "DSNS_3_TB",
                        columns:[],
                        currentData: [],
                        filters: [],
                    },
                    expression: {
                        string: "",
                        auth_string: {
                            string: "",
                            roles: ["DSNSLayers"]
                        },
                    },
                },
                {
                    id: 56,
                    pId: 12,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'DSNS_4_TB',
                    layerIds: [5],
                    tolerance: 40,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'DSNS_4_TB',
                    legendName: '',
                    identScale: 50000,
                    identify: [
                        {
                            id: 54,
                            title: '',
                            identityFields: [],
                            tocName: 'DSNS_4_TB',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'f1',
                            table: "DSNS_4_TB",
                            //photoField: "PHOTOS",
                            documField: "DOCUMS",
                            selectedMarkerFileName: "select_55.svg",
                            printIdentity: true
                        }
                    ],
                    selectIconSize: { "width": 24, "height": 24 },
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                    table: {
                        tableName: "DSNS_4_TB",
                        columns: [],
                        currentData: [],
                        filters: [],
                    },
                    expression: {
                        string: "",
                        auth_string: {
                            string: "",
                            roles: ["DSNSLayers"],
                        },
                    },
                },
                {
                    id: 57,
                    pId: 12,
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'DSNS_5_TB',
                    layerIds: [6],
                    tolerance: 30,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Point',
                    nameVectorLayer: 'DSNS_5_TB',
                    legendName: '',
                    identScale: 50000,
                    identify: [
                        {
                            id: 54,
                            title: '',
                            identityFields: [],
                            tocName: 'DSNS_5_TB',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'f1',
                            table: "DSNS_5_TB",
                            //photoField: "PHOTOS",
                            documField: "DOCUMS",
                            selectedMarkerFileName: "select_55.svg",
                            printIdentity: true,
                        }
                    ],
                    selectIconSize: { "width": 24, "height": 24 },
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                    table: {
                        tableName: "DSNS_5_TB",
                        columns: [],
                        currentData: [],
                        filters: [],
                    },
                    expression: {
                        string: "",
                        auth_string: {
                            string: "",
                            roles: ["DSNSLayers"],
                        },
                    },
                },
                {
                    id: 58,
                    pId: 7,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS_ZHITLO/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'Комбіноване житло',
                    layerIds: [3],//10
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Polygon',
                    nameVectorLayer: 'Комбіноване житло',
                    identScale: 0,
                    identify: [
                        {
                            id: 58,
                            title: "Комбіноване житло",
                            identityFields: [
                                { name: 'F1', description: 'Адреса' },
                                { name: 'F0', description: 'Район' },
                                { name: 'F2', description: 'Кількість поверхів' },
                                { name: 'F3', description: 'Кількість під’їздів' },
                                { name: 'F4', description: 'Форма власності (управління)' },
                                { name: 'F5', description: 'Найменування організації-управителя' },
                                { name: 'F6', description: 'Матеріал покрівлі' },
                                { name: 'F7', description: 'Матеріал зовнішніх стін' },
                                { name: 'F8', description: 'Централізоване теплопостачання' },
                                { name: 'F9', description: 'Обслуговування ВБС теплопостачання' },
                                { name: 'F10', description: 'Централізоване гаряче водопостачання' },
                                { name: 'F11', description: 'Обслуговування ВБС гар. водопостачання' },
                                { name: 'F12', description: 'Централізоване водопостачання' },
                                { name: 'F13', description: 'Обслуговування ВБС хол. водопостачання' },
                                { name: 'F14', description: 'Централізоване водовідведення' },
                                { name: 'F15', description: 'Обслуговування ВБС водовідведення та внутр. зливової каналізації' },
                                { name: 'F16', description: 'Обслуговування зовнішніх мереж зливової каналізації' },
                                { name: 'F17', description: 'Обслуговування ВБС електропостачання та освітлення' },
                                { name: 'F18', description: 'Обслуговування ліфтового господарства' },
                                { name: 'F19', description: 'Обслуговування систем диспетчеризації' },
                                { name: 'F20', description: 'Обслуговування димовентканалів' },
                                { name: 'F21', description: 'Прибирання прибудинкової території' },
                                { name: 'F22', description: 'Вивезення ТПВ' },
                                { name: 'F23', description: 'Доставка газу' },
                            ],
                            tocName: 'Комбіноване житло',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'FULLADDRUA'
                        }
                    ]
                },
                {
                    id: 59,
                    pId: 7,
                    //url: 'https://smart.city.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'https://smart.khmr.gov.ua/arcgis/rest/services/munic_web/MapServer',
                    //url: 'http://cdr.citynet.kharkov.ua/arcgis/rest/services/munic_web/MapServer',
                    url: 'https://smart.khmr.gov.ua/arcgis/rest/services/DSNS/MapServer',
                    type: 'dynamic',
                    visibility: false,
                    map_visibility: false,
                    name: 'Будинки з QR-кодами',
                    layerIds: [7],//10
                    tolerance: 10,
                    order: 0,
                    dataType: 'layer',
                    geometryType: 'Polygon',
                    nameVectorLayer: 'Будинки з QR-кодами',
                    identScale: 0,
                    identify: [
                        {
                            id: 59,
                            title: "Будинки з QR-кодами",
                            identityFields: [
                                { name: 'MAIN_DATA_ADDRESS', description: 'Адреса' },
                                { name: 'MAIN_DATA_DISTRICT', description: 'Район міста' },
                                { name: 'MAIN_DATA_FLOORS', description: 'Кількість поверхів' },
                                { name: 'MAIN_DATA_ENTRANCES', description: 'Кількість під’їздів' },
                                { name: 'MAIN_DATA_FLATS', description: 'Кількість квартир' },
                                { name: 'MAIN_DATA_SHELTER_HAVING', description: 'Наявність в будинку укриття' },
                                { name: 'MAIN_DATA_SHELTER_AUTO_HAVING', description: 'Автоматика доступу в укриття' },
                                { name: 'MAIN_DATA_OWNERSHIP_TYPE', description: 'Форма власності (управління)' },
                                { name: 'MAIN_DATA_MANAGEMENT_ORG_NAME', description: 'Найменування організації-управителя' },
                                { name: 'MAIN_DATA_ZKS_CONTACT_DATA', description: 'Дільниці КП "Житлокомсервіс"' },
                                { name: 'MAIN_DATA_DZKG_CONTACT_DATA', description: 'ДЖКГ з приводу діяльності ОСББ' },                               
                            ],
                            tocName: 'Будинки з QR-кодами',
                            controller: false,
                            bindToAddress: false,
                            mainField: 'MAIN_DATA_ADDRESS'
                        }
                    ],
                    token: {
                        need: true,
                        str: '',
                        role: 'DSNSLayers'
                    },
                },
            ],
            //идентификация------------
            identify: {
                tasks: [],
                queries: []
            },
            //виджеты
            widgets: null,
            //линейка
            measurment: {
                visibilityMeasureDiv: false,
                displayMeasurementDiv: true
            },
            //ектент
            extentDelta: 100,
            //полный екстент
            fullExtent: [3617.71875, 300, 32413.462890625, 27313.279827328], //2700.0, 3500.0, 34000.0, 24000.0
            //не помню!!!!! :))))
            currentClickEventData: null,
            initScales: [
                {
                    name: 'before768',
                    M: 100000,
                    extent: [15253.71875, 14265.36328125, 16050.462890625, 15360.337890625],
                    level: 10
                },
                {
                    name: 'before1280',
                    M: 100000,
                    //extent: [3617.71875, 300, 32413.462890625, 27313.279827328], 
                    extent: [13600.71875, 13750.36328125, 17800.462890625, 16050.337890625],
                    level: 1
                },
                {
                    name: 'before1920',
                    M: 100000,
                    extent: [13600.71875, 13750.36328125, 17800.462890625, 16050.337890625],
                    level: 1
                },
                {
                    name: 'after1920',
                    M: 100000,
                    extent: [13600.71875, 13750.36328125, 17800.462890625, 16050.337890625],
                    level: 1
                }
            ],
            tokenExpiration: 1, //minutes
            tokenInterval: null,
            addressObjectsList: [],
            addressesObjectsList: {},
            coordinatesResult: {},
        },
        mapToolStore: {
            ToggleSearcherSelected: true,
            GeolocationSelected: false,
            PanSelected: false,
            ZoominSelected: false,
            ZoomoutSelected: false,
            IdentifySelected: true,
            MesurmentSelected: false,
            CoordinatesSelected: false,
            visibility: false
        },
        searchStore: {
            searchType: '',
            searchPlaceholder: 'Введіть адресу',
            searchText: '',
            searchResult: [],
            currentSearchResult: null,
            visibility: true,
            minSearchStringLength: 3,
            findedStreets: [],
            findedAddresses:[],
        },
        init: {
            isMapInit: false,
            isSpinnerInit: false,
            isSearcherInit: false,
            isMapToolsInit: false,
            isTocInit: false,
            //isLegendInit: false
        },
        ndl: {
            host: '/opendataportal',
            ajax: [
                {
                    name: 'getAddressByText',
                    url: '/opendataportal/Home/getAddressByText2'
                },
                {
                    name: 'getCadByText',
                    url: 'https://map.land.gov.ua/kadastrova-karta/get-parcel-Info'
                },
                {
                    name: 'Login',
                    url: '/opendataportal/Account/LoginAjax'
                },
                {
                    name: 'Register',
                    url: '/opendataportal/Account/RegisterAjax'
                },
                {
                    name: 'ConfirmPhoneAjax',
                    url: '/opendataportal/Account/ConfirmPhoneAjax'
                },
                {
                    name: 'ForgotPassword',
                    url: '/opendataportal/Account/ForgotPasswordAjax'
                },
                {
                    name: 'Feedback',
                    url: '/opendataportal/Home/Feedback'
                },
                {
                    name: 'UserInfo',
                    url: '/opendataportal/Account/UserInfo'
                },
                {
                    name: 'SendCodeToPhone',
                    url: '/opendataportal/Account/SendCodeToPhone'
                },
                {
                    name: 'SendConfirmEmail',
                    url: '/opendataportal/Account/SendConfirmEmail'
                },
                {
                    name: 'ResetPasswordAjax',
                    url: '/opendataportal/Account/ResetPasswordAjax'
                },
                {
                    name: 'LogOff',
                    url: '/opendataportal/Account/LogOffAjax'
                },
                {
                    name: 'socialAuth',
                    url: '/opendataportal/Account/ExternalLoginAjax'
                },
                {
                    name: 'convertCoordinates',
                    url: '/opendataportal/Home/convertCoordinates'
                },
                {
                    name: 'GetDugById',
                    url: '/opendataportal/Home/GetDugById'
                },
                {
                    name: 'GetAdwertById',
                    url: '/opendataportal/Home/GetAdwertById'
                },
                {
                    name: 'GetAdwerts',
                    url: '/opendataportal/Home/GetAdwerts'
                },
                {
                    name: 'GetAllWifiMap',
                    url: '/opendataportal/Home/GetAllWifiMap'
                },
                {
                    name: 'GetProjectStatistic',
                    url: '/opendataportal/Home/GetProjectStatistic'
                },
                {
                    name: 'GetWebDocProfShortStatistic',
                    url: '/opendataportal/Home/GetWDP_InputStat'
                },
                {
                    name: 'GetWebDocProfFullStatistic',
                    url: '/opendataportal/Home/GetWDPStat'
                },
                {
                    name: 'CalcLastWeekStat',
                    url: '/opendataportal/Home/CalcLastWeekStat'
                },
                {
                    name: 'GetDugStat',
                    url: '/opendataportal/Home/GetDugStat'
                },
                {
                    name: 'GetDurationStat',
                    url: '/opendataportal/Home/GetDurationStat'
                },
                {
                    name: 'GetYearsDurationStat',
                    url: '/opendataportal/Home/GetYearsDurationStat'
                },
                {
                    name: 'GetHeatingStat',
                    url: '/opendataportal/Home/GetStatistic'
                },
                {
                    name: 'GISToken',
                    url: '/opendataportal/Home/GISToken'
                },
                {
                    name: 'GetAddressesByPrimarySchool',
                    url: '/opendataportal/Home/GetAddressesByPrimarySchool?schoolGuid='
                },
                {
                    name: 'GetAllHistBuilds',
                    url: '/opendataportal/Home/Monuments'
                },
                {
                    name: 'GetAddressesByBombShelter',
                    url: '/opendataportal/Home/GetAddressesByBombShelter?bombGuid='
                },
                {
                    name: 'GetAddressesByHospital',
                    url: '/opendataportal/Home/GetAddressesByHospital?MED_ID='
                },
                {
                    name: 'Siren',
                    url: '/opendataportal/Home/Siren'
                },
                {
                    name: 'GetDSNSConfig',
                    url: '/opendataportal/Home/GetSheetTitles'
                },
                {
                    name: 'findStreet',
                    url: '/opendataportal/Home/FindStreet'
                },
                {
                    name: 'findAddress',
                    url: '/opendataportal/Home/FindAddress'
                },
                {
                    name: 'getWGSCoordinates',
                    url: '/opendataportal/Home/ConvertCoordinatesToWGS'
                },
                {
                    name: 'GetSheetData',
                    url: '/opendataportal/Home/GetSheetData?table='
                },
            ]
        },
        tocStore: {
            visibility: false,
            layers: []
        },
        layersStore: {
            visibility: false,
        },
        messagesStore: {
            messagesTexts: {
                youHaveNoPermission: 'Зареєструйтесь, щоб додавати об\'єкти на карту',
                yourBrowserGeolocationNotSupport: 'Ваш браузер не підтримує геолокацію',
                serverError: 'Помилка серверу! Спробуйте пізніше!',
                phoneNotConfirmed: 'Ви не підтвердили свої реєстраційні дані! <br>Надіслати код підтвердження на ваш телефон?',
                emailNotConfirmed: 'Ви не підтвердили свої реєстраційні дані! <br>Надіслати повторний запит на Ваш Email?',
                emailSending: 'Cерверу не вдалося відправити запит! Спробуйте пізніше.',
                repeatedRequest: 'Повторний запит на підтвердження реєстраційних даних надіслано на ваш Email! Перевірте вашу поштову скриньку та перейдіть за посиланням у листі!',
                enterISNotCompleted: 'ВХІД НЕ ВИКОНАНО!',
                badLoginPassword: 'Неправильний логін або пароль.',
                badLogin: 'Неправильний логін.',
                needVerification: '',
                userBlocked: 'Користувач заблокований.  <br />Зверніться за тел. 760-71-61',
                thereIsNoRequiredFields: 'Не всі поля заповнені!',
                passwordsDoNotCoinsides: 'Паролі не співпадають!',
                loginIsBusy: 'Цей логін вже зайнятий!',
                emailIsBusy: 'Цей email вже зайнятий!',
                confirmRegistration: 'Перевірте Вашу електронну пошту! <br />\
                                  Увага! При відсутності листа перевірте папку "Спам"!',
                confirmRegistration2: 'Для підтвердження реєстрації зверніться за телефоном 760-71-61! <br />',
                resetPassword: 'На Ваш email відправлено листа для відновлення паролю!',
                confirmButtonText: "Так",
                cancelButtonText: "Ні",
                geolocationPermissionDenided: 'Користувач заблокував геолокацію!',
                geolocationPositionUnavailable: 'Геопозиція відсутня',
                geolocationTimeout: 'Час отримання місцеположення користувача закінчився.',
                geolocationUnknowError: 'Помилка невідома',
                geolocationIsNotSupportingByBrowser: 'Геолокація не підтримується браузером',
                legendTypesIsNotDefined: 'Типи об\'єктів не визначено',
                ConfirmPhoneAjaxError: 'Невірний код.',
                UserNotFound: 'Ви не зареєстровані в системі',
                featureNotFound: 'Заявка перенесена до архіву',
                youHaveNoPermissionForStats: 'Для перегляду статистики увійдіть в систему!',
                attention: 'УВАГА!',
                noSelectedProjectWithStat: 'Жоден проект зі статистикою не вибраний!',
                dateFromLessDateTo: 'Дата початку повинна бути раніше ніж дата кінця!',
                hasNoData: 'Дані відсутні!',
            },
            //confirmButtonColor: '#026b02',
            //cancelButtonColor: '#026b02',
            confirmButtonColor: '#480358',
            cancelButtonColor: '#480358',
        },
        userStore: {
            //
            Confirmed: false,
            //user login --
            Loginn: 'guest',
            //user roles types --
            roles: {
                Viewers: true,
                Informants: false,
                Moderators: false,
                Admins: false,
                InformantsPlus: false,
                DSNSLayers:false,
            },
            //user email -- 
            Email: '',
            // user name --
            FullName: 'Вхід',
            //login is locked
            Locked: false,
            //user phone
            Phone: '',
            //current token
            Token: '',
            //workerTimer---------
            workerTimer: null,
            lastWorkTime: null,
            //------------------
            loginView: false, //true - используется вьюха для входа Account/Login, false - вход через модальное окно на главной вьюхе home/index
        },
        leftNavbarStore: {
            navbarItems: [
                //{
                //    id:0,
                //    name: 'Базові шари',
                //    faclass: 'fa-file-o',
                //    type: 'basic',
                // tagId:'lnbBasics
                //},
                {
                    id: 1,
                    name: 'Проекти',
                    faclass: 'fa-list',
                    iel: 'Проекти<i class= "fa fa-list"></i>',
                    type: 'projects',
                    tagId: 'lnbProjects',
                    isFaclass: true
                },
                {
                    id: 2,
                    name: 'Легенда',
                    faclass: 'material-icons',
                    iel: 'Легенда<i class= "material-icons"> category</i>',
                    type: 'legend',
                    tagId: 'lnbLegend',
                    isFaclass: false
                },
                {
                    id: 3,
                    name: 'Посилання',
                    faclass: 'fa-link',
                    iel: 'Посилання<i class= "fa fa-link"></i>',
                    type: 'links',
                    tagId: 'lnbLinks',
                    isFaclass: true
                },
                {
                    id: 4,
                    name: 'Друк',
                    faclass: 'fa-print',
                    iel: 'Друк<i class= "fa fa-print"></i>',
                    type: 'print',
                    tagId: 'lnbPrint',
                    isFaclass: true
                }
            ]
        },
        legendStore: {
            visibility: false
        },
        linksStore: {
            items: [
                {
                    id: 0,
                    name: 'Єдиний адресний реєстр міста Харкова',
                    href: 'https://geo-portal.com.ua/kharkiv/index.html'
                },
                {
                    id: 1,
                    name: 'Єдиний міський реєстр актів',
                    href: 'https://doc.city.kharkov.ua'
                },
                {
                    id: 2,
                    name: 'Харківська міська диспетчерська служба 1562',
                    href: 'https://1562.kharkivrada.gov.ua/'
                    //href: 'http://www.1562.kharkov.ua/'
                },
                //{
                //    id: 3,
                //    name: 'Реклама online',
                //    href: 'http://cdr.citynet.kharkov.ua/webadreg'
                //},
                //{
                //    id: 4,
                //    name: 'Система Обліку розриттів',
                //    href: 'http://cdr.citynet.kharkov.ua/dug'
                //},
                //{
                //    id: 5,
                //    name: 'Звернення громадян',
                //    href: 'http://cdr.citynet.kharkov.ua/webdocprof'
                //},
                //{
                //    id: 6,
                //    name: 'Харків проти наркотиків',
                //    href: 'http://safe.city.kharkov.ua'
                //},
                //{
                //    id: 7,
                //    name: 'WIFI Харків',
                //    href: 'http://wifi.city.kharkov.ua'
                //}
            ]
        },
        statisticStore: {
            dateFrom: null,
            dateTo: null,
            statisticProjects: [],
            currentStatisticProjectId: 0,
        },
        housesStore: {
            methods: {
                GetByAddress: {
                    name: 'GetHouseByAddressId',
                    url:'/houses/GetByAddress?address_id='
                },
                HouseByOSBB: {
                    name: 'HouseByOSBB',
                    url:'/houses/HouseByOSBB?osbb_nom='
                },
            }
        },
        //hideBlockStoere: {
        //    blockIsHide: false
        //}
    },
    mutations: {
        set_User(state, data) {
            store.commit('reset_User');
            if (data.Confirmed) {
                var roles = (data.Roles.length > 0) ? data.Roles.join(',') : '';
                state.userStore = {
                    Loginn: data.Loginn,
                    Confirmed: data.Confirmed,
                    roles: {
                        Viewers: true,
                        Informants: roles.lastIndexOf('Informants') >= 0,
                        Moderators: roles.lastIndexOf('Moderators') >= 0,
                        Admins: roles.lastIndexOf('Admins') >= 0,
                        InformantsPlus: roles.lastIndexOf('InformantsPlus') >= 0,
                        DSNSLayers: roles.lastIndexOf('DSNSLayers') >= 0,
                    },
                    Email: data.Email,
                    FullName: data.FullName,
                    Locked: data.Locked,
                    Phone: data.Phone,
                    Token: data.Token,
                    loginView: state.userStore.loginView,
                }
            }
            else {
                this.$store.dispatch(showNeedVerificationMessage, data);
                return false;
            }
        },        
        setUserFromSessionStorage(state, data) {
            store.commit('reset_User');
            state.userStore = data;
        },
        reset_User(state) {
            state.userStore = {
                Confirmed: false,
                Loginn: 'guest',
                roles: {
                    Viewers: true,
                    Informants: false,
                    Moderators: false,
                    Admins: false,
                    InformantsPlus: false,
                    DSNSLayers:false,
                },
                //user email -- 
                Email: '',
                // user name --
                FullName: 'Вхід',
                Locked: false,
                Phone: '',
                Token: '',
                loginView: state.userStore.loginView,
            }
        },
        startWorkTimer(state) {
            this.state.userStore.lastWorkTime = (new Date()).getTime();

            this.state.userStore.workerTimer = setInterval(function () {
                if (!this.state.userStore.workerTimer) {
                    clearInterval(this.state.userStore.workerTimer);
                    this.state.userStore.workerTimer = null;
                    this.state.userStore.lastWorkTime = null;
                }
                else {
                    var currentTime = (new Date()).getTime();
                    if (currentTime > (this.state.userStore.lastWorkTime + 2000 * 10)) {  // ignore small delays
                        this.dispatch('LogOff',
                            JSON.stringify({
                                ajax: this.getters.getAjaxUrlByName('LogOff'),
                            }));
                        //console.log('stopWorkTimer - currentTime');
                        this.commit('stopWorkTimer');
                    }
                    this.state.userStore.lastWorkTime = currentTime;
                }
            }.bind(this), 10000);
        },
        stopWorkTimer(state) {
            clearInterval(this.state.userStore.workerTimer);
            this.state.userStore.workerTimer = null;
            this.state.userStore.lastWorkTime = null;
        },
        //searcherStore----------------
        //тип поиска
        set_searchType(state, type) {
            state.searchStore.searchType = type;
            state.searchStore.searchPlaceholder = (type == 'address' || type == 'street') ? 'Введіть адресу' : 'Введіть кадастровий №';
        },
        set_searchText(state, text) {
            if (text != '') {
                state.searchStore.searchText = text;
                state.init.isSearcherInit = false;
            }
        },
        set_searchResult(state, result) {
            var res = [];
            //если данніе по улицам, то откидіваем аннулированніе
            if (Array.isArray(result) && result.length > 0 && state.searchStore.searchType == 'street') {
                result.forEach(function (rItem) {
                    if (rItem.Valid !== "ANNULLED")
                        res.push(rItem);
                }.bind(this));
            }
            else
                res = result;
            state.searchStore.searchResult = res;
            //евент что данніе пришли
            eventVue.$emit('dataIsResponsed', res);
            //віключаем хинт
            //state.init.isSearcherInit = true;
        },
        // новий пошук вулиць
        set_findedStreets(state, result) {
            var res = [...result];
            Vue.set(state.searchStore,'findedStreets', res);
        },

        // новий пошук адрес
        set_findedAddresses(state, result) {

            //var res = [...this.getters.compareAddressNumber(result)];
            var res = [...result];
            Vue.set(state.searchStore, 'findedAddresses', res);
        },


        set_currentSearchResult(state, result) {
            state.searchStore.currentSearchResult = result.currentResult;
            state.searchStore.searchType = result.type;

        },
        set_searchVisibility(state) {
            var currentSearcherVisibility = state.searchStore.visibility;
            state.searchStore.visibility = !currentSearcherVisibility;
            state.mapToolStore.ToggleSearcherSelected = !currentSearcherVisibility;
        },
        clearSearchResult(state) {
            state.searchStore.currentSearchResult = null;
            // state.searchStore.searchType = null;
        },
        //TOC
        set_toggleToc(state) {
            var currentTocVisibility = state.tocStore.visibility;
            state.tocStore.visibility = !currentTocVisibility;
            //Vue.set(state.tocStore,'visibility', !currentTocVisibility);
        },
        clearTocStoreLayers(state) {
            state.tocStore.layers.length = 0;
        },
        set_tocIsVisible(state, visibility) {
            state.tocStore.visibility = visibility;
        },
        //
        set_maptoolbarButtonClick(state, type) {
            var currentPanSelected = state.mapToolStore.PanSelected,
                currentZoominSelected = state.mapToolStore.ZoominSelected,
                currentZoomoutSelected = state.mapToolStore.ZoomoutSelected,
                currentIdentifySelected = state.mapToolStore.IdentifySelected,
                currentMesurmentSelected = state.mapToolStore.MesurmentSelected;
                currentCoordinatesSelected = state.mapToolStore.CoordinatesSelected;

            state.mapToolStore.PanSelected = false,
            state.mapToolStore.ZoominSelected = false,
            state.mapToolStore.ZoomoutSelected = false,
            state.mapToolStore.IdentifySelected = false,
            state.mapToolStore.MesurmentSelected = false;
            state.mapToolStore.CoordinatesSelected = false;

            if (type == 'pan') {
                state.mapToolStore.PanSelected = currentPanSelected ? false : true;
                state.mapToolStore.IdentifySelected = !state.mapToolStore.PanSelected ? true : false;
            }
            if (type == 'zoomin') {
                state.mapToolStore.ZoominSelected = currentZoominSelected ? false : true;
                state.mapToolStore.IdentifySelected = !state.mapToolStore.ZoominSelected ? true : false;

            }
            if (type == 'zoomout') {
                state.mapToolStore.ZoomoutSelected = currentZoomoutSelected ? false : true;
                state.mapToolStore.IdentifySelected = !state.mapToolStore.ZoomoutSelected ? true : false;

            }
            if (type == 'identify') {
                state.mapToolStore.IdentifySelected = true;
            }
            if (type == 'mesurment') {
                state.mapToolStore.MesurmentSelected = (!state.mapStore.measurment.visibilityMeasureDiv) ? true : false;
                state.mapToolStore.IdentifySelected = !state.mapToolStore.MesurmentSelected ? true : false;
            }
            if (type == 'coordinates') {
                state.mapToolStore.CoordinatesSelected = currentCoordinatesSelected ? false : true;
                state.mapToolStore.IdentifySelected = state.mapToolStore.CoordinatesSelected ? false : true;
            }

        },
        set_toggleMaptoolVisibility(state) {
            var currentVisibility = state.mapToolStore.visibility;
            state.mapToolStore.visibility = !currentVisibility
        },
        set_geolocationButtonClick(state) {
            var currentGeolocationSelected = state.mapToolStore.GeolocationSelected;
            state.mapToolStore.GeolocationSelected = !currentGeolocationSelected
            if (state.mapToolStore.GeolocationSelected)
                eventVue.$emit('startGeolocation');
            else
                eventVue.$emit('stopGeolocation');

        },
        //mapStore--------------------------
        set_arcgisWidgets(state, widgets) {
            state.mapStore.widgets = widgets;
        },
        set_measureDivVisibility(state) {
            var currentMeasurmentVisibility = state.mapStore.measurment.visibilityMeasureDiv;
            state.mapStore.measurment.visibilityMeasureDiv = !currentMeasurmentVisibility;
            state.mapStore.measurment.displayMeasurementDiv = !currentMeasurmentVisibility;
            state.mapToolStore.MesurmentSelected = !currentMeasurmentVisibility;
            state.mapToolStore.IdentifySelected = !state.mapToolStore.MesurmentSelected ? true : false;
        },
        set_project(state, projectId) {
            store.commit('clearTocStoreLayers');
            //store.commit('remove_allProjectFromStat');
            //выключаем все слои
            for (var j = 0; j < state.mapStore.layers.length; j++) {
                state.mapStore.layers[j].visibility = false;
                state.mapStore.layers[j].map_visibility = false;
                
            }
            //перебираем проекты
            for (var i = 0; i < state.mapStore.projects.length; i++) {
                state.mapStore.projects[i].visibility = false;
                if (state.mapStore.projects[i].id == projectId) {
                    //state.mapStore.projects[i].visibility = true;
                    for (var k = 0; k < state.mapStore.layers.length; k++) {
                        //if (state.mapStore.layers[k].id == 22)
                        //    var T = '';
                        //state.mapStore.layers[k].visibility = (state.mapStore.layers[k].pId == projectId && (!state.mapStore.layers[k].token || !state.mapStore.layers[k].token.need || (state.mapStore.layers[k].token && state.mapStore.layers[k].token.need && this.getters.getUser.roles.Admins))) ? true : false;
                        if (state.mapStore.layers[k].pId == projectId) {
                            if (state.mapStore.layers[k].type != 'link') {
                                if (state.mapStore.layers[k].token && state.mapStore.layers[k].token.need && this.getters.getUser.roles.Admins)
                                    state.mapStore.layers[k].visibility = true;
                                else if (state.mapStore.layers[k].token && state.mapStore.layers[k].token.need && !this.getters.getUser.roles.Admins)
                                    state.mapStore.layers[k].visibility = false;
                                else if ((state.mapStore.layers[k].token && !state.mapStore.layers[k].token.need) || !state.mapStore.layers[k].token)
                                    state.mapStore.layers[k].visibility = true;
                                else
                                    state.mapStore.layers[k].visibility = true;
                            }
                        }
                        if (state.mapStore.layers[k].visibility) {
                            store.commit('set_addToMapList', state.mapStore.layers[k]);
                            store.commit('set_layerVisibility', state.mapStore.layers[k].id);
                            if (state.mapStore.projects[i].statistic)
                                store.dispatch('StartProjectStatistic', { projectId: state.mapStore.projects[i].id, datefrom: null, dateto: null });
                        }
                    }
                }
            }
        },
        set_layerVisibility(state, layerId) {
            var layers = state.mapStore.layers;
            for (var k = 0; k < layers.length; k++)
                if (layers[k].id == layerId) {
                    //var currentVisibility = layers[k].visibility;
                    //layers[k].visibility = !currentVisibility;
                    var currentVisibility = layers[k].map_visibility;
                    layers[k].map_visibility = !currentVisibility;
                }
        },
        set_addLayer(state, layerId) {

        },
        set_map(state, map) {
            state.mapStore.map = map;
        },
        set_currentMapClick(state, event) {
            state.mapStore.currentClickEventData = event;
        },
        set_mapListLayers: (state, layers) => {
            //обновляем на Токе
            state.tocStore.layers.length = 0;
            for (var i = 0; i < layers.length; i++) {
                store.commit('set_layerOrder', { order: layers[i].length - i, layerId: layers[i].id });
                state.tocStore.layers.push(layers[i]);
            }
        },
        set_removeFromMapList: (state, layerId) => {
            for (var i = 0; i < state.tocStore.layers.length; i++)
                if (state.tocStore.layers[i].id == layerId)
                    state.tocStore.layers.splice(i, 1);
        },
        set_addToMapList: (state, layer) => {
            var visLayers = store.getters.getVisibileLayers;
            state.tocStore.layers.length = 0;
            visLayers.forEach(function (item, index, visLayers) {
                state.tocStore.layers.unshift(item);
            });
            if (state.tocStore.layers.length > 0) {
                store.commit('set_tocIsVisible', true);
            }

        },
        set_onOffLayer: (state, layerId) => {
            var isOn,
                currentLayer,
                currentLayerVisibility,
                pId,
                projects = store.getters.getAllProjectsFull;
            for (var i = 0; i < state.mapStore.layers.length; i++)
                if (state.mapStore.layers[i].id == layerId) {
                    currentLayerVisibility = state.mapStore.layers[i].visibility;
                    currentLayer = state.mapStore.layers[i];
                    pId = currentLayer.pId;
                    state.mapStore.layers[i].visibility = !currentLayerVisibility;
                    currentLayerVisibility = state.mapStore.layers[i].visibility;
                    currentLayer.order = currentLayerVisibility ? store.getters.getNewOrder : 0;
                    if (currentLayer.order == 0)
                        store.commit('set_removeFromMapList', layerId);                    
                    else {
                        store.commit('set_layerOrder', { order: currentLayer.order, layerId: layerId });
                        store.commit('set_addToMapList', state.mapStore.layers[i]);
                        if (store.getters.getProjectById(pId).statistic)
                            store.dispatch('StartProjectStatistic', { projectId: pId, datefrom: null, dateto: null });
                    }
                    store.commit('set_layerVisibility', layerId); 
                    break;
                }
            store.commit('reorderLayers');
        },
        set_layerOrder(state, data) {
            for (var i = 0; i < state.mapStore.layers.length; i++)
                if (state.mapStore.layers[i].id == data.layerId)
                    state.mapStore.layers[i].order = data.order;
        },
        reorderLayers(state) {
            var visibleLayers = store.getters.getTocVisibleLayers,
                currentOrder = 1;
            for (var i = 0; i < visibleLayers.length; i++) {
                var currentLayerId = visibleLayers[i].id,
                    currentLayerOrder = visibleLayers[i].order;
                if (Math.abs(currentLayerOrder - currentOrder) > 0) {
                    store.commit('set_layerOrder', { order: currentOrder, layerId: currentLayerId });
                }
                else if (Math.abs(currentLayerOrder - currentOrder) == 0)
                    ++currentOrder
            }

        },
        removeAllLayers(state) {
            var layers = store.getters.getAllMapLayers;
            layers.forEach(function (item, index, layers) {
                item.visibility = false;
                item.map_visibility = false;
            });
            store.commit('clearTocStoreLayers');
            eventVue.$emit('removeAllLayers');
            //store.commit('remove_allProjectFromStat');
        },
        set_featuresToLayer(state, data) {
            var layers = state.mapStore.layers;
            for (var k = 0; k < layers.length; k++)
                if (layers[k].id == store.state.mapStore.loadLayer) {
                    layers[k].features = data;
                    //eventVue.$emit('selectLayer', layers[k].id);
                }

        },
        set_layerToLoad(state, layerId) {
            state.mapStore.loadLayer = layerId;
        },
        set_webdocprofExpression(state) {
            //yesterday = formatDateDD_MM_YYYY(new Date(Date.now() - 24 * 5 * 60 * 60 * 1000)),
            //tomorrow = formatDateDD_MM_YYYY(new Date(Date.now() + 24 * 60 * 60 * 1000)),
            var layers = state.mapStore.layers;
            layers.forEach(function (item, index, layers) {
                if (item.expression)
                    //state.mapStore.layers[index].expression.string = "CARTDATE > timestamp '" + yesterday + " 00:00:00' AND CARTDATE < timestamp '" + tomorrow + " 00:00:00'";
                    state.mapStore.layers[index].expression.string = "CARTDATE >= timestamp '" + formatDateDD_MM_YYYY(new Date(Date.now() - (24 * state.mapStore.layers[index].expression.daysInterval * 60 * 60 * 1000))) + " 00:00:00'";
            });

            function formatDateDD_MM_YYYY(date) {
                var d = [+date.getFullYear().toString(), date.getMonth() + 1, date.getDate()];
                d.forEach(function (v, i, a) {
                    if (v < 10) return a[i] = '0' + v;
                });
                return d.join('-');
            }
        },
        updateRasters(state, token) {
            state.mapStore.basis.forEach(function (item) {
                if (item.token.need)
                    item.token.str = token;
            });
            eventVue.$emit('updateRasters');
        },
        startTokenTiks(state) {
            state.mapStore.tokenInterval = setInterval(function () {
                this.dispatch('getToken');
            }.bind(this), state.mapStore.tokenExpiration * 7000000); //раз в 2 часа
        },
        stopTokenTiks(state) {
            clearInterval(state.mapStore.tokenInterval);
            state.mapStore.tokenInterval = null;
        },
        setAddressObjectsList(state, data) {
            state.mapStore.addressObjectsList = data;
        },
        clearAddressObjectsList(state) {
            state.mapStore.addressObjectsList = [];
            state.mapStore.addressesObjectsList = {};
        },

        setServiceAddresses(state, data) {
            state.mapStore.addressesObjectsList = data;
        },

        //------
        set_isShowedTrue(state, prop) {
            state.mapStore.projects.forEach(function (item, index) {
                if (item.id === prop.projectId) {                    
                    item.statistic.data.forEach(function (feat) {
                        if (feat.id == prop.statId)
                            feat.isShowed = true;
                    }.bind(this));
                }
            });
        },
        add_projectToStat(state, project) {
            var cntProjectLayers = 0;
            state.statisticStore.statisticProjects.forEach(function (item, index) {
                if (item == project.id)
                    cntProjectLayers++;
            });
            if (cntProjectLayers == 0)
                state.statisticStore.statisticProjects.push(project.id);
        },
        add_allProjectsToStat(state) {
            var statProjects = store.getters.getStatProjects;
            statProjects.forEach(function (item, index) {
                state.statisticStore.statisticProjects.push(item.id);
            });
        },
        remove_projectFromStat(state, projectId) {
            var cntProjectLayers = 0;
            state.tocStore.layers.forEach(function (item, index) {
                if (state.tocStore.layers[index].pId == projectId)
                    cntProjectLayers++;
            });

            if (cntProjectLayers == 0) {
                state.statisticStore.statisticProjects.forEach(function (item, index) {
                    if (item == projectId) {
                        state.statisticStore.statisticProjects.splice(index, 1);
                    }
                });
            }
        },
        remove_allProjectFromStat(state) {
            //state.statisticStore.statisticProjects.length = 0;
            state.statisticStore.statisticProjects.splice(0, state.statisticStore.statisticProjects.length);
            state.statisticStore.currentStatisticProjectId = null;
        },
        set_currentStatisticProject(state, pId) {
            if (state.statisticStore.statisticProjects.length > 0) {
                for (var i = 0; i < state.statisticStore.statisticProjects.length; i++) {
                    if (state.statisticStore.statisticProjects[i] == pId) {
                        state.statisticStore.currentStatisticProjectId = pId;

                        eventVue.$emit('fillData');
                        break;
                    }
                }
            }
            else
                state.statisticStore.currentStatisticProjectId = null;
        },
        clear_currentStatisticProject(state, pId) {
            state.mapStore.projects.forEach(function (pItem) {
                if (pItem.id == pId) {
                    switch (pItem.id) {
                        case 7: {
                            pItem.statistic.data[1].labels = [];
                            pItem.statistic.data[1].datasets[0].data = [];
                            pItem.statistic.data[0].labels = [];
                            pItem.statistic.data[0].datasets[0].data = [];
                            pItem.statistic.data[0].datasets[1].data = [];
                            pItem.statistic.data[0].datasets[2].data = [];
                        }
                            break;
                    }
                }
            }.bind(this));
        },
        //store.commit('add_projectToStat', project);
        //init----------------------------        
        set_isMapInit(state, isMapInit) {
            state.init.isMapInit = isMapInit;
            console.log('isMapInit = ' + state.init.isMapInit);
        },
        set_isSpinnerInit(state, isSpinnerInit) {
            state.init.isSpinnerInit = isSpinnerInit;
            console.log('isSpinnerInit = ' + state.init.isSpinnerInit);
        },
        set_isSearcherInit(state, isSearcherInit) {
            state.init.isSearcherInit = isSearcherInit;
            console.log('isSearcherInit = ' + state.init.isSearcherInit);
        },
        set_isMapToolsInit(state, isMapToolsInit) {
            state.init.isMapToolsInit = isMapToolsInit;
            console.log('isMapToolsInit = ' + state.init.isMapToolsInit);
        },
        set_isTocInit(state, isTocInit) {
            state.init.isTocInit = isTocInit;
            console.log('isTocInit = ' + state.init.isTocInit);
        },
        //-
        set_toggleLoginForm(state, logg) {
            var currentState = state.authorizeStore.loginStore.show;
            state.authorizeStore.loginStore.show = !currentState;
        },
        //
        toggleLegend(state) {
            var currentState = state.legendStore.visibility;
            state.legendStore.visibility = !currentState;
        },
        showLegend(state) {
            if (!state.legendStore.visibility)
                state.legendStore.visibility = true;
        },
        set_isLegendInit(state, isLegendInit) {
            state.init.isLegendInit = isLegendInit;
            console.log('isMapInit = ' + state.init.isLegendInit);
        },
        set_responseShortStatistic(state, response) {
            var resProject = store.getters.getProjectById(response.projectId);
            for (var i = 0; i < state.mapStore.projects.length; i++) {
                if (state.mapStore.projects[i].id == resProject.id) {
                    state.mapStore.projects[i].statistic.data.forEach(function (item, index) {
                        for (var i = 0; i < response.data.length; i++) {
                            if (item.id == response.data[i].statId) {
                                item.labels.length = 0;
                                item.labels = response.data[i].labels;
                                item.datasets[0].data.length = 0;
                                item.datasets[0].data = response.data[i].datasetsData;
                                if (item.class == 'short') {
                                    item.notifyData.length = 0;
                                    item.notifyData = response.notifyData;
                                }
                                eventVue.$emit('updateChart');
                            }
                        }
                    }.bind(response));
                    eventVue.$emit('updateChart');
                }
            }
        },
        set_responseFullStatistic(state, response) {
            //if (response.data.length > 0) {
            //var prop = JSON.parse(response.config.data).prop,
            //    layerId = prop.layerId || null,
            //projectId = prop.projectId || null,
            //   resLayer,
            //var     resProject = response.projectId || null;
            //if (projectId)
            //    resProject = store.getters.getProjectById(projectId);
            //else {
            //    resLayer = store.getters.geLayerById(layerId),
            //    resProject = store.getters.getProjectById(resLayer.pId);
            //}

            for (var i = 0; i < state.mapStore.projects.length; i++) {
                if (state.mapStore.projects[i].id == response.projectId) {
                    //обнуляем
                    state.mapStore.projects[i].statistic.full.labels.length = 0;
                    state.mapStore.projects[i].statistic.full.datasets[0].data.length = 0;
                    //for (var j = 0; j < response.data.length; j++) {
                    state.mapStore.projects[i].statistic.full.labels = response.labels;
                    state.mapStore.projects[i].statistic.full.datasets[0].data = response.datasetsData;
                    eventVue.$emit('updateChart');
                    //setTimeout(function () {
                    //    eventVue.$emit('updateChart');
                    //}, 200);
                    //}
                }
            }
            //}
        },
        set_responseMixedStatistic(state, response) {
            var resProject = store.getters.getProjectById(response.projectId);
            for (var i = 0; i < state.mapStore.projects.length; i++) {
                if (state.mapStore.projects[i].id == resProject.id) {
                    state.mapStore.projects[i].statistic.data.forEach(function (item, index) {
                        for (var i = 0; i < response.data.length; i++) {
                            if (item.id == response.statId) {
                                item.labels.length = 0;
                                item.labels = response.data[0].labels;
                                item.datasets.forEach(function (itemm, i) {
                                    itemm.data.length = 0;
                                    itemm.data = (itemm.type == 'bar') ? response.data[0].datasetsBarData : response.data[0].datasetsLineData;
                                }.bind(response));
                                eventVue.$emit('updateMixedChart');
                            }
                        }
                    }.bind(response));
                    //eventVue.$emit('updateMixedChart');
                }
            }
        },
        set_responseDateStatistic(state, response) {
            var resProject = store.getters.getProjectById(response.projectId);
            for (var i = 0; i < state.mapStore.projects.length; i++) {
                if (state.mapStore.projects[i].id == resProject.id) {
                    state.mapStore.projects[i].statistic.data.forEach(function (item, index) {
                        for (var i = 0; i < response.data.length; i++) {
                            if (item.id == response.statId) {
                                item.labels.length = 0;
                                item.labels = response.data[0].labels;
                                item.datasets.forEach(function (itemm, i) {
                                    itemm.data.length = 0;
                                    itemm.data = (itemm.type == 'bar') ? response.data[0].datasetsBarData : response.data[0].datasetsLineData;
                                }.bind(response));
                                eventVue.$emit('updateChart');
                            }
                        }
                    }.bind(response));
                    eventVue.$emit('updateChart');
                }
            }
        },
        set_responseTypesMixedStatistic(state, response) {
            var resProject = store.getters.getProjectById(response.projectId);
            for (var i = 0; i < state.mapStore.projects.length; i++) {
                if (state.mapStore.projects[i].id == resProject.id) {
                    for (var j = 0; j < state.mapStore.projects[i].statistic.data.length; j++) {
                        var ddt = state.mapStore.projects[i].statistic.data[j];
                        if (ddt.id == response.statId) {
                            ddt.labels.length = 0;
                            ddt.labels = response.data.labels;
                            ddt.types.length = 0;
                            ddt.types = response.data.types;
                            ddt.data.length = 0;
                            ddt.data = response.data.res;
                            for (var k = 0; k < ddt.datasets.length; k++) {
                                ddt.datasets[k].data.length = 0;
                                ddt.datasets[k].data = (ddt.datasets[k].type == 'bar') ? ddt.data[0].datasetsBarData : ddt.data[0].datasetsLineData;
                            }
                            eventVue.$emit('updateMixedTypeChart');
                        }
                    }
                    eventVue.$emit('updateMixedTypeChart');
                }
            }
        },
        changeDataInMixedStatisticByType(state, response) {
            var resProject = store.getters.getProjectById(response.projectId);
            for (var i = 0; i < state.mapStore.projects.length; i++) {
                if (state.mapStore.projects[i].id == resProject.id) {
                    for (var j = 0; j < state.mapStore.projects[i].statistic.data.length; j++) {
                        var ddt = state.mapStore.projects[i].statistic.data[j];
                        if (ddt.id == response.statId) {

                            //seek
                            var datasetsBarrData = [], datasetsLineeData = [];
                            for (var k = 0; k < ddt.data.length; k++) {
                                if (ddt.data[k].typeId == response.type) {
                                    datasetsBarrData = [...ddt.data[k].datasetsBarData];
                                    datasetsLineeData = [...ddt.data[k].datasetsLineData];
                                }
                            }

                            for (var k = 0; k < ddt.datasets.length; k++) {
                                //ddt.datasets[k].data.length = 0;
                                ddt.datasets[k].data = (ddt.datasets[k].type === 'bar') ? datasetsBarrData : datasetsLineeData;
                            }
                            //eventVue.$emit('updateMixedTypeChart');
                        }
                    }
                    eventVue.$emit('updateMixedTypeChart');
                }
            }
        },
        set_HeatingStatistic(state, response) {
            var resProject = store.getters.getProjectById(response.config.prop.projectId);
            for (var i = 0; i < state.mapStore.projects.length; i++) {
                if (state.mapStore.projects[i].id == resProject.id) {
                    state.mapStore.projects[i].statistic.data[1].labels = [];
                    state.mapStore.projects[i].statistic.data[1].datasets[0].data = [];
                    state.mapStore.projects[i].statistic.data[0].labels = [];
                    state.mapStore.projects[i].statistic.data[0].datasets[0].data = [];
                    state.mapStore.projects[i].statistic.data[0].datasets[1].data = [];
                    state.mapStore.projects[i].statistic.data[0].datasets[2].data = [];

                   //заполняем полную
                    var fullstatLabels = [], fullstatDatasets = [], words = ["Очікується", "Підключено", "Завоздушено"],
                        label0 = '', label1 = '', label2 = '', data0 = 0, data1 = 0, data2 = 0;

                    if (Array.isArray(response.data.statisticData) && response.data.statisticData.length > 0) {
                        response.data.statisticData.forEach(function (sItem, index, arr) {
                            if (sItem.type == 0) {
                                label0 = words[sItem.type] + " - " + sItem.count;
                                data0 = sItem.percent;
                            }
                            else if (sItem.type == 1) {
                                label1 = words[sItem.type] + " - " + sItem.count;
                                data1 = sItem.percent;
                            }
                            else if (sItem.type == 2) {
                                label2 = words[sItem.type] + " - " + sItem.count;
                                data2 = sItem.percent;
                            }
                        }.bind(this));

                        fullstatLabels = [label0, label1, label2];
                        fullstatDatasets = [data0, data1, data2];
                    }
                    state.mapStore.projects[i].statistic.data[1].labels = fullstatLabels;
                    state.mapStore.projects[i].statistic.data[1].datasets[0].data = fullstatDatasets;
                    //обновляем чартs
                    //eventVue.$emit('updateChart');
                    //заполняем порайонно
                    var diststatLabels = [], diststatDatasets1 = [], diststatDatasets2 = [], diststatDatasets3 = [];
                    if (Array.isArray(response.data.statisticDataByRayon) && response.data.statisticDataByRayon.length > 0) {
                        response.data.statisticDataByRayon.forEach(function (sItem, index,arr) {
                            diststatLabels.push(sItem.district + " - " + sItem.districtCount);
                            var statValue = 0;
                            if (Array.isArray(sItem.statisticData) && sItem.statisticData.length > 0) {
                                data0 = 0, data1 = 0, data2 = 0
                                sItem.statisticData.forEach(function (sdItem, index, arr) {
                                    if (sdItem.type == 0)
                                        data0 = sdItem.count;
                                    else if (sdItem.type == 1)
                                        data1 = sdItem.count;
                                    else if (sdItem.type == 2)
                                        data2 = sdItem.count;
                                }.bind(this));
                                diststatDatasets1.push(data0);
                                diststatDatasets2.push(data1);
                                diststatDatasets3.push(data2);
                            }

                        }.bind(this));
                    }
                    state.mapStore.projects[i].statistic.data[0].labels = diststatLabels;
                    state.mapStore.projects[i].statistic.data[0].datasets[0].data = diststatDatasets1;
                    state.mapStore.projects[i].statistic.data[0].datasets[1].data = diststatDatasets2;
                    state.mapStore.projects[i].statistic.data[0].datasets[2].data = diststatDatasets3;

                    //обновляем чартs
                    //setTimeout(function () {
                    //    eventVue.$emit('updateStakedChart');
                    //}.bind(this), 300);
                    eventVue.$emit('updateChart');
                }
            }
        },
        //this.$store.commit('changeDataInMixedStatisticByType', { type: +e.target.value, projectId: this.selectedProject, statId: +e.target.attributes['data-statid'].value });  
        //addHideBlock(state) {
        //    state.hideBlockStoere = true;
        //},
        //removeHideBlock(state) {
        //    state.hideBlockStoere = false;
        //},
        set_monumentsFeatures(state, data) {
            store.state.mapStore.layers.forEach(function (lItem) {
                if (lItem.id == 14 && Array.isArray(data.features)) {
                    var features = lItem.cluster.on ? this.getters.getFeaturesArrayFromGeoJsonCollectionForCluster(data.features) : this.getters.getFeaturesArrayFromGeoJsonCollection(data.features) ;
                    lItem.features = features;
                }
            }.bind(this));
            eventVue.$emit('selectLayer', data.layer.id);
            var T = '';
        },
        set_WebACCFeatures(state, data) {
            store.state.mapStore.layers.forEach(function (lItem) {
                if (lItem.id == data.layer.id && Array.isArray(data.features) && Array.isArray(data.features)) {

                    //var features = this.getters.getFeaturesArrayFromJsonCollection(data.features, data.layer);
                    var features =data.features
                    lItem.features = features;
                }
            }.bind(this));
            eventVue.$emit('selectLayer', data.layer.id);
            var T = '';
        },
        set_SirenFeatures(state, data) {
            store.state.mapStore.layers.forEach(function (lItem) {
                if (lItem.id == data.layer.id && Array.isArray(data.features) && Array.isArray(data.features)) {

                    //var features = this.getters.getFeaturesArrayFromJsonCollection(data.features, data.layer);
                    var features =data.features
                    lItem.features = features;
                }
            }.bind(this));
            eventVue.$emit('selectLayer', data.layer.id);
            var T = '';
        },
        //--
        updateLayersAfterLogOff(state, data) {
            store.state.mapStore.layers.forEach(function (lItem) {
                if (lItem.visibility && lItem.token && lItem.token.need && !this.getters.getUser.roles.Admins) {
                    this.commit('set_onOffLayer', lItem.id);
                    eventVue.$emit('selectLayer', lItem.id);
                    //чтобы почистился графиклеер
                    eventVue.$emit('searcherInputIsCleared');
                }
            }.bind(this));

        },
        //-----------
        set_DSNSConfig(state, data) {
            if (Array.isArray(data) && data.length > 0) {                
                let donelayersids = [];
                data.forEach(function (dItem) { 

                    let isOk;

                    store.state.mapStore.layers.forEach(function (lItem, index, array) {
                        let fields = [];
                        let columns = [];
                        if (lItem.id > 52 && lItem.pId === 12 && lItem.identify && !donelayersids.includes(lItem.id) && !isOk) {
                            donelayersids.push(lItem.id);
                            lItem.legendName = dItem.layerName;
                            lItem.identify.forEach(function (item) {                              
                                fields = this.getters.getDSNSIdentityFieldsByConfig(dItem.identityFields);
                                Vue.set(item, 'identityFields', [...fields])
                                //item.identityFields = [...fields];
                                item.title = dItem.layerName;                                
                            }.bind(this)); 

                            if (fields.length > 0) {
                                fields.forEach(function (fItem) {
                                    columns.push({ title: fItem.description, field: fItem.name.toUpperCase(), sorter: 'string', minWidth: 200, width: 200, headerFilter: 'input', formatter:'textarea' });
                                }.bind(this));
                                Vue.set(lItem.table,'columns',columns);
                            }
                            
                            isOk = true;

                            Vue.set(store.state.mapStore.layers, index, { ...lItem });
                        }
                    }.bind(this));
                }.bind(this));
            }
        },
        set_DSNSTableData(state, data) {
            if (Array.isArray(data.data) && data.data.length > 0) {                
                store.state.mapStore.layers.forEach(function (lItem, index, array) {
                        let fields = [];
                    let columns = [];
                    if (lItem.id > 52 && lItem.pId === 12 && lItem.table && lItem.table.tableName === data.tableName) {
                        lItem.table.currentData = [...data.data];
                        Vue.set(store.state.mapStore.layers, index, { ...lItem });
                    }
                }.bind(this));
            }
        },
        //------------
        set_expression_toLayer(state, data) {
            state.mapStore.layers.forEach(function (lItem, index) {
                if (lItem.id === data.layer.id && lItem.expression) {
                    lItem.expression.auth_string.string = data.where
                }
            });
        },
        //------------
        set_coordinatesResult(state, data) {
            //state.mapStore.coordinatesResult = data.data ? data.data : {};
            Vue.set(state.mapStore, 'coordinatesResult', (data?.data ? { data: data.data, clickData: data.clickData } : {}));
        },

    },
    getters: {
        getLinks: (state) => {
            return state.linksStore.items;
        },
        getUser: (state) => {
            return state.userStore;
        },
        getHost: (state) => {
            return state.host;
        },
        //searcher
        getSearchPlaceholder: (state, getters) => {
            return state.searchStore.searchPlaceholder;
        },
        getSearchResult: (state, getters) => {
            return state.searchStore.searchResult;
        },


        getSearchType: (state, getters) => {
            return state.searchStore.searchType;
        },
        getFindedStreets: (state, getters) => {
            return state.searchStore.findedStreets;
        },
        getFindedAddresses: (state, getters) => {
            return state.searchStore.findedAddresses;
        },
        getСurrentSearchResult: (state, getters) => {
            return { currentResult: state.searchStore.currentSearchResult, type: state.searchStore.searchType };
        },
        getSearcherVisibility: (state, getters) => {
            return state.searchStore.visibility;
        },
        getMinSearchStringLength: (state) => {
            return state.searchStore.minSearchStringLength;
        },
        //mapStore--
        getVisibleBasis: (state) => {
            var layers = state.mapStore.basis,
                res = [];
            if (layers.length > 0) {
                for (var i = 0; i < layers.length; i++)
                    if (layers[i].visibility)
                        res.push(layers[i]);
            }
            return res;
            //return state.mapStore.basis.find(x => x.visibility === true);
        },
        getBasics: (state) => {
            return state.mapStore.basis;
        },
        getAllMapLayers: (state, getters) => {
            return state.mapStore.layers;
        },
        getArcGisWidgets: (state, getters) => {
            return state.mapStore.widgets;
        },
        getMeasureDivVisibility: (state, getters) => {
            return state.mapStore.measurment.visibilityMeasureDiv;
        },
        getMeasurementDivVisibility: (state, getters) => {
            return state.mapStore.measurment.displayMeasurementDiv;
        },
        getAllProjects: (state) => {
            return state.mapStore.projects;
        },
        getAllProjectsFull: (state, getters) => {
            var projects = state.mapStore.projects,
                layers = getters.getAllMapLayers;
            for (var i = 0; i < projects.length; i++) {
                var isShowProjectData = false;
                projects[i].layers = [];
                for (var j = 0; j < layers.length; j++) {
                    let isOK = false;
                    if (
                        projects[i].id == layers[j].pId &&
                        (
                            !layers[j].token ||
                            (layers[j].token && layers[j].token.need && layers[j].token.role && state.userStore.roles[layers[j].token.role]) ||
                            (layers[j].token && layers[j].token.need && !layers[j].token.role)
                        )
                    ) {
                        //console.log(layers[j], layers[j].identify)
                        if (layers[j].identify) {
                            layers[j].identify.forEach(function (item) {
                                //console.log(item.identityFields.length, item)
                                isOK = item.identityFields.length > 0
                            }.bind(this));
                        }
                        else {
                            isOK = true;
                        }
                   

                    }
                    if (isOK) {
                        projects[i].layers.push(layers[j]);
                        if (layers[j].visibility == true)
                            isShowProjectData = true;
                    }
                }
                projects[i].isShowProjectData =  isShowProjectData;
            }
            let out_projects = [];
            projects.forEach(function (pItem) {
                if (pItem.layers.length > 0) {
                    out_projects.push(pItem);
                }
            });
            return out_projects;
        },
        getvisibleProject: (state, getters) => {
            var projects = state.mapStore.projects;
            for (var i = 0; i < projects.length; i++) {
                if (projects[i].visibility)
                    return projects[i];
            }
            //return state.mapStore.projects.find(x => x.visibility === true);
        },
        getExtentDelta: (state) => {
            return state.mapStore.extentDelta;
        },
        getMap: (state) => {
            return state.mapStore.map
        },
        getVisibileLayers: (state) => {
            var layers = state.mapStore.layers,
                res = [];
            if (layers.length > 0) {
                for (var i = 0; i < layers.length; i++)
                    if (layers[i].visibility)
                        res.push(layers[i]);
            }
            return res;
        },
        getAllLayers: (state) => {
            return state.mapStore.layers;
        },
        getProjectById: (state) => (id) => {
            return state.mapStore.projects.find(x => x.id === id);
        },
        getFullExtent: (state) => {
            return state.mapStore.fullExtent;
        },
        getCurrentClickEventData: (state) => {
            return state.mapStore.currentClickEventData;
        },
        getAllBasicsData: (state) => {
            return state.mapStore.basis;
        },
        geLayerById: (state) => (id) => {
            return state.mapStore.layers.find(x => x.id === id);
        },
        geLayerByVectorLayerName: (state) => (vName) => {
            return state.mapStore.layers.find(x => x.nameVectorLayer === vName);
        },

        geLayerByLayerName: (state) => (vName) => {
            return state.mapStore.layers.find(x => x.name === vName);
        },
        getLayerByTocName: (state) => (vName) => {
            var Layers = state.mapStore.layers,
                Basis = state.mapStore.basis,
                fullLayers = Layers.concat(Basis),
                result;
            fullLayers.forEach(function (item, index, fullLayers) {
                var identifys = item.identify;
                if (identifys && identifys.length > 0) {
                    for (var i = 0; i < identifys.length; i++) {
                        if (identifys[i].tocName == vName)
                            result = item;
                    }
                }
            });
            return result;
        },
        getLayerByLayerId: (state) => (layerId) => {
            var Layers = state.mapStore.layers,
                Basis = state.mapStore.basis,
                fullLayers = Layers.concat(Basis),
                result;
            Layers.forEach(function (item, index, fullLayers) {
                if (item.id == layerId)
                    result = item;
            });
            return result;
        },
        getNewOrder: (state, getters) => {
            var visibleLayers = getters.getVisibileLayers,
                currentOrder = 0;
            for (var i = 0; i < visibleLayers.length; i++)
                if (visibleLayers[i].order > currentOrder)
                    currentOrder = visibleLayers[i].order;
            return ++currentOrder;
        },
        getInitScales: (state) => {
            var winW = document.documentElement.clientWidth,
                name = '';
            if (winW <= 768)
                name = 'before768';
            if (winW > 768 && winW <= 1280)
                name = 'before1280';
            if (winW > 1280 && winW <= 1920)
                name = 'before1920';
            if (winW > 1920)
                name = 'after1920';
            return state.mapStore.initScales.find(x => x.name === name);
        },
        getLoadLayerId: (state) => {
            return state.mapStore.loadLayer
        },
        getStatProjects: (state) => {
            var result = [];
            //список всех проектов со статистикой
            state.mapStore.projects.forEach(function (item) {
                if (item.statistic)
                    result.push(item);
            });

            //state.statisticStore.statisticProjects.forEach(function (item) {
            //    state.mapStore.projects.forEach(function (itemm) {
            //        if (item == itemm.id)
            //            result.push(itemm);
            //    });
            //});
            //return state.statisticStore.statisticProjects;
            return result;
        },
        getIsProjectInStats: (state) => (projectId) => {
            var result = false;
            state.statisticStore.statisticProjects.forEach(function (item, index) {
                if (item.id == projectId)
                    result = true;
            });
            return result;
        },
        getBarData: (state) => {
            var result = null;
            if (state.statisticStore.currentStatisticProjectId >= 0 && state.statisticStore.statisticProjects.length > 0) {
                for (var i = 0; i < state.mapStore.projects.length; i++) {
                    if (state.mapStore.projects[i].id == state.statisticStore.currentStatisticProjectId) {
                        result = state.mapStore.projects[i].statistic.short;
                    }
                }

            }
            return result;
        },
        getPieData: (state) => {
            var result = null;
            if (state.statisticStore.currentStatisticProjectId >= 0 && state.statisticStore.statisticProjects.length > 0) {
                for (var i = 0; i < state.mapStore.projects.length; i++) {
                    if (state.mapStore.projects[i].id == state.statisticStore.currentStatisticProjectId) {
                        result = state.mapStore.projects[i].statistic.full;
                    }
                }
            }
            return result;
        },
        getMixedData: (state) => {
            var result = null;
            if (state.statisticStore.currentStatisticProjectId >= 0 && state.statisticStore.statisticProjects.length > 0) {
                for (var i = 0; i < state.mapStore.projects.length; i++) {
                    if (state.mapStore.projects[i].id == state.statisticStore.currentStatisticProjectId) {
                        result = state.mapStore.projects[i].statistic.mixed;
                    }
                }
            }
            return result;
        },
        getChartData: (state) => {
            var result = null;
            if (state.statisticStore.currentStatisticProjectId >= 0 && state.statisticStore.statisticProjects.length > 0) {
                for (var i = 0; i < state.mapStore.projects.length; i++) {
                    if (state.mapStore.projects[i].id == state.statisticStore.currentStatisticProjectId) {
                        result = state.mapStore.projects[i].statistic.data;
                    }
                }
            }
            return result;
        },
        getFiltering: (state) => {
            var result = null;
            if (state.statisticStore.currentStatisticProjectId && state.statisticStore.statisticProjects.length > 0) {
                for (var i = 0; i < state.mapStore.projects.length; i++) {
                    if (state.mapStore.projects[i].id == state.statisticStore.currentStatisticProjectId) {
                        result = state.mapStore.projects[i].statistic.filtering;
                    }
                }
            }
            return result;
        },
        getShortStatContent: (state) => (prop) => {
            //создаем контент
            if (prop.class == 'short') {
                var data = prop.notifyData,
                    statStr = '<table>',
                    redIndex = 0;
                data.forEach(function (item, index, data) {
                    if (item.label.indexOf(':') < 0) {
                        statStr += '<tr><td>' + item.label + '</td><td> ' + item.data + ' </td></tr>';
                    }
                    else if (item.label.indexOf(':') >= 0) {
                        statStr += '<tr><td>' + item.label + '</td><td></td></tr>';
                    }
                }.bind(this));
                statStr += '</table>';
                return { title: prop.title, content: statStr };
            }
        },
        getAddressObjectsList: (state) => {
            return state.mapStore.addressObjectsList;
        },  
        getAddressesObjectsList: (state) =>  {
            return state.mapStore.addressesObjectsList;
        },

        //toolbar
        getHideBlock: (state) => {
            return !state.mapToolStore.visibility;
        },
        getToggleSearcherSelected: (state) => {
            return state.mapToolStore.ToggleSearcherSelected;
        },
        getPanSelected: (state) => {
            return state.mapToolStore.PanSelected;
        },
        getZoominSelected: (state) => {
            return state.mapToolStore.ZoominSelected;
        },
        getZoomoutSelected: (state) => {
            return state.mapToolStore.ZoomoutSelected;
        },
        getIdentifySelected: (state) => {
            return state.mapToolStore.IdentifySelected;
        },
        getMesurmentSelected: (state) => {
            return state.mapToolStore.MesurmentSelected;
        },
        getGeolocationSelected: (state) => {
            return state.mapToolStore.GeolocationSelected;
        },
        getCoordinatesSelected: (state) => {
            return state.mapToolStore.CoordinatesSelected;
        },
        getTokenExpiration: (state) => {
            return state.mapStore.tokenExpiration;
        },
        //init---
        getFullInit: (state, getters) => {
            var fullCount = Object.keys(state.init).length,
                currentCount = 0;
            if (state.init.isMapInit)
                currentCount++;
            if (state.init.isSpinnerInit)
                currentCount++;
            if (state.init.isSearcherInit)
                currentCount++;
            if (state.init.isMapToolsInit)
                currentCount++;
            if (state.init.isTocInit)
                currentCount++;
            return fullCount == currentCount;
        },
        //TOC
        getTocVisibility: (state) => {
            return state.tocStore.visibility;
        },
        getTocVisibleLayers: (state, getters) => {
            var res = state.tocStore.layers,
                tempRes = [];
            if (res.length == 0) {
                var layers = getters.getVisibileLayers;
                for (var i = 0; i < layers.length; i++)
                    tempRes.unshift(layers[i]);
                res = tempRes;
            }
            return res;
        },
        getIsProjectLayerAddedToTOC: (state) => (projectId) => {
            return state.tocStore.layers.find(x => x.pId === projectId);
        },
        //ndl-----
        getAjaxUrlByName: (state, getters) => (name) => {
            return state.ndl.ajax.find(x => x.name === name);
        },
        getNDL: (state) => {
            return state.ndl;
        },
        //--
        getShowLogin: (state) => {
            return state.authorizeStore.loginStore.show;
        },
        getMessagesStore: (state) => {
            return state.messagesStore;
        },
        //left nav
        getLeftNavbarItems: (state) => {
            return state.leftNavbarStore.navbarItems;
        },
        //
        getLegendVisibility: (state) => {
            return state.legendStore.visibility;
        },
        //date
        getDateddmmyyyy: (state) => (date) => {
            var d = [date.getDate(), date.getMonth() + 1, +date.getFullYear().toString()];
            d.forEach(function (v, i, a) {
                if (v < 10) return a[i] = '0' + v;
            });
            return d.join('.');
        },
        //getBlockIsHide: (state) => {
        //    state.hideBlockStoere.blockIsHide;
        //}
        //houses----------------------
        getHousesStore: (state) => {
            return state.housesStore;
        },
        //--------
        getFeaturesArrayFromGeoJsonCollection: (state) => (data) => {
            var features = [];
            data.forEach(function (item) {
                var attr = item.properties,
                    geometry = new state.mapStore.widgets.Point(item.geometry.coordinates[1], item.geometry.coordinates[0], new window.esri.SpatialReference({ 'wkid': 28467 }));
                //console.log('x = ' + item.geometry.coordinates[1] + ' ; y = ' + item.geometry.coordinates[0]);
                var graphic = new state.mapStore.widgets.Graphic(geometry);
                graphic.setAttributes(attr);
                features.push(graphic);
            });
            return features;
        },
        getFeaturesArrayFromGeoJsonCollectionForCluster: (state) => (data) => {
            var res = [];
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function (fItem) {
                    res.push({
                        "x": fItem.geometry.coordinates[1],
                        "y": fItem.geometry.coordinates[0],
                        "attributes": fItem.properties
                    });
                }.bind(this));
            }
            return res;
        },
        getFeaturesArrayFromJsonCollection: (state) => (data,layer) => {
            var features = [];
            data.forEach(function (item) {
                var attr = item.attributes,
                    geometry = new state.mapStore.widgets.Point(item.geometry.x, item.geometry.y, new window.esri.SpatialReference({ 'wkid': 28467 }));
                //console.log('x = ' + item.geometry.coordinates[1] + ' ; y = ' + item.geometry.coordinates[0]);
                var graphic = new state.mapStore.widgets.Graphic(geometry);
                if (layer && layer.id == 16) {
                    attr.FEATURE_COLOR_NUM = this.getFeatureConlorNum;
                }
                graphic.setAttributes(attr);
                features.push(graphic);
            });
            return features;
        },
        getFeatureConlorNum: (state) => (feature) => {
            var res = 1;
            return res;
        },
        getDSNSIdentityFieldsByConfig: (state) => (config) => {
            let res = [];
            
            let temp_res = [
                { name: 'f1', description: '' },
                { name: 'f2', description: '' },
                { name: 'f3', description: '' },
                { name: 'f4', description: '' },
                { name: 'f5', description: '' },
                { name: 'f6', description: '' },
                { name: 'f7', description: '' },
                { name: 'f8', description: '' },
                { name: 'f9', description: '' },
                { name: 'f10', description: '' },
                { name: 'f11', description: '' },
                { name: 'f12', description: '' },
                { name: 'f13', description: '' },
                { name: 'f14', description: '' },
                { name: 'f15', description: '' },
                { name: 'f16', description: '' },
                { name: 'f17', description: '' },
                { name: 'f18', description: '' },
                { name: 'f19', description: '' },
                { name: 'f20', description: '' },
                { name: 'f21', description: '' },
                { name: 'f22', description: '' },
                { name: 'f23', description: '' },
                { name: 'f24', description: '' },
                { name: 'f25', description: '' },
                { name: 'f26', description: '' },
                { name: 'f27', description: '' },
                { name: 'f28', description: '' },
                { name: 'f29', description: '' },
                { name: 'f30', description: '' },
                { name: 'f31', description: '' },
                { name: 'f32', description: '' },
                { name: 'f33', description: '' },
                { name: 'f34', description: '' },
                { name: 'f35', description: '' },
                { name: 'f36', description: '' },
                { name: 'f37', description: '' },
                { name: 'f38', description: '' },
                { name: 'f39', description: '' },
                { name: 'f40', description: '' },
                { name: 'f41', description: '' }
            ];
            if (config.length > 0) {
              //  let temp_config = config.slice(7);
                config.slice(6).forEach(function (cItem, index) {
                    let out_field = { ...temp_res[index] };
                    out_field.description = cItem ? cItem : out_field.name ;
                    res.push(out_field);
                }.bind(this));
            }
            return res;
        },
        getNumberFromText:(state) => (config) => {
            let res = [];
                       
            return res;
        },
        compareAddressNumber: (state) => (data) => {
            let res = [];
            if (data.length > 0) {
                function getNumberFromText(sortdata) {
                    let res = "0",
                        others="";
                    if (sortdata.length > 0) {
                        res = "";
                        sortdata.split("").forEach(function (dItem) {
                            if ((!isNaN(dItem) || dItem === "0") && others.length === 0) {
                                res += dItem;
                            }
                            else if (isNaN(dItem) && res.length > 0) {
                                others += dItem;
                            }
                        });
                    }
                    return {number : res, others:others};
                }

               // res = data;
                res = data.sort(function (a, b) {
                    let aupd = a ? getNumberFromText(a.addressNumber) : null,
                        bupd = b ? getNumberFromText(b.addressNumber) : null;

                    if (a && b && aupd.number !== bupd.number) {
                        return aupd.number - bupd.number;
                    }
                    else if (a && b && aupd.number === bupd.number) {
                        return aupd.others - bupd.others;
                    }

                }.bind(this));
            }
            return res;
        },
        getDSNSVisibleLayers: (state) => {
            const res = state.mapStore.layers.filter(l => l.pId === 12 && l.id > 52);
            return res;
        },
        getDSNSLayersWidthFilters: (state) => {
            const res = state.mapStore.layers.filter(l => l.pId === 12 && l.id > 52 && l.expression.auth_string.string.length > 0);
            return res;
        },
        //----------------
        getCoordinatesResult: (state) => {
            return state.mapStore.coordinatesResult;
        },
    },
    actions: {
        //AJAXes------------------------------------------------------------

        //запрос на адрес по строке
        getAddressByText({ commit }, properties) {
            //alert('getAddressByText before parsing properties, cancel = ' + cancel);
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                store.commit('set_searchResult', []);
                //alert('before axios, cancel = ' + cancel);
                //console.log('before axios, cancel = ' + cancel);
                if (cancel) {
                    cancel();
                    cancel = null;
                    //console.log('before axios, cancel = null');
                }
                axios.get(prop.ajax.url + '?text=' + prop.text, {
                    cancelToken: new CT(function executor(c) {
                        cancel = c;
                        console.log('request is cancelled');
                    })
                })
                    .then(response => {
                        //console.log('in axios response, cancel = ' + cancel);
                        //alert('in axios response, cancel = ' + cancel);
                        store.commit('set_searchResult', response.data);
                        store.commit('set_isSearcherInit', true);
                        cancel = null;
                    })
                    .catch(function (thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                            console.log('Request canceled', thrown.message);
                            store.commit('set_isSearcherInit', true);
                        }
                    });
            }
        },

        //новий пошук
        findStreet({ commit }, prop) {
          
            if (prop) {
                store.commit('set_isSearcherInit', false);
    
                if (cancel) {
                    cancel();
                    cancel = null;
                    //console.log('before axios, cancel = null');
                }
                axios.get(prop.ajax.url + '?query=' + prop.text, {
                    cancelToken: new CT(function executor(c) {
                        cancel = c;
                        console.log('request is cancelled');
                    })
                })
                    .then(response => {
                        //console.log('in axios response, cancel = ' + cancel);
                        //alert('in axios response, cancel = ' + cancel);
                        store.commit('set_findedStreets', response.data);
                        store.commit('set_isSearcherInit', true);
                        cancel = null;
                    })
                    .catch(function (thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                            console.log('Request canceled', thrown.message);
                            store.commit('set_isSearcherInit', true);
                        }
                    });
            }
        },

        findAddress({ commit }, prop) {
            if (prop) {
                store.commit('set_isSearcherInit', false);
                axios.get(prop.ajax.url + '?streetId=' + prop.streetId)
                    .then(response => {
                        //console.log('in axios response, cancel = ' + cancel);
                        //alert('in axios response, cancel = ' + cancel);
                        store.commit('set_findedAddresses', response.data);
                        store.commit('set_isSearcherInit', true);
           
                    })
                    .catch(function (thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                            console.log('Request canceled', thrown.message);
                            store.commit('set_isSearcherInit', true);
                        }
                    });
            }
        },

        //запос на участок в ДЗК
        getCadByText({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop.text.length == 22) {
                store.commit('set_isSearcherInit', false);
                const requestId = 'my_sample_request';
                var cd = prop.text.split(':')
                if (cancel)
                    cancel();
                axios.get(prop.ajax.url, {
                    params: {
                        'koatuu': cd[0],
                        'zone': cd[1],
                        'quartal': cd[2],
                        'parcel': cd[3]
                    }
                }, {
                        Accept: 'application / json, text/javascript, */ *; q=0.01',
                        cancelToken: new CT(function executor(c) {
                            // An executor function receives a cancel function as a parameter
                            cancel = c;
                            //console.log('request is cancelled');
                        })
                    })
                    .then(response => {
                        store.commit('set_searchResult', response.data.data);
                        store.commit('set_isSearcherInit', true);
                    }).catch(function (thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                        }
                    });
            }
        },
        //логин
        Login({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                axios.post(prop.ajax.url + '?Email=' + prop.Email + '&Password=' + prop.Password, {
                    cancelToken: new CT(function executor(c) {
                        // An executor function receives a cancel function as a parameter
                        cancel = c;
                        //console.log('request is cancelled');
                    })
                })
                    .then(response => {
                        store.commit('set_isSearcherInit', true);
                        switch (response.data) {
                            case 'ERROR':
                                eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.serverError);
                                break;
                            case 3:
                                eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.badLoginPassword);
                                break;
                            case 2: {
                                eventVue.$emit('closeLoginForm');
                                this.showNeedVerificationMessage(store.userStore);
                            }
                                break;
                            case 1:
                                eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.userBlocked);
                                break;
                            case 0: {
                                if (!this.state.userStore.loginView)
                                    eventVue.$emit('closeLoginForm');
                                this.dispatch('getUserInfo');
                               // if (!this.state.userStore.loginView) {
                                   // this.dispatch('getToken');
                                   // this.commit('startTokenTiks');
                              //  }
                            }
                                break;
                        }
                    }).catch(function (thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                            eventVue.$emit('showSimpleMessage', thrown.message);
                            store.commit('set_isSearcherInit', true);
                        }
                    });
            }
        },
        //логофф
        LogOff({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                axios.post(prop.ajax.url)
                    .then(response => {
                        store.commit('set_isSearcherInit', true);
                        store.commit('reset_User');
                        store.commit('stopTokenTiks');
                        if (this.state.userStore.loginView) {
                            //window.location = '/opendataportal/Account/Login';
                            window.location = '/opendataportal';
                        }
                        store.commit('updateLayersAfterLogOff');
                    }).catch(function (thrown) {
                        store.commit('stopWorkTimer');
                        store.commit('stopTokenTiks');
                        store.commit('reset_User');
                        store.commit('set_isSearcherInit', true);
                        if (this.state.userStore.loginView) {
                            //window.location = '/opendataportal/Account/Login';
                            window.location = '/opendataportal';
                        }
                    });
            }
        },
        //регистрация
        Register({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                //var ddata = new FormData();
                //ddata.append()
                axios.post(prop.ajax.url + '?Email=' + prop.Email + '&Password=' + prop.Password, {
                    prop: prop
                })
                    .then((response) => {
                        store.commit('set_isSearcherInit', true);
                        if (response.data.Succeeded) {
                            eventVue.$emit('closeRegisterForm');
                            if (JSON.parse(response.config.data).prop.isPhone)
                                eventVue.$emit('openSmsForm', { phone: JSON.parse(response.config.data).prop.Email, isForgot: false });
                            else {
                                eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.confirmRegistration);
                                if (store.getters.getUser.loginView)
                                    eventVue.$emit('loginLinkOnClick');
                            }
                        }
                        else {
                            eventVue.$emit('showErrorMessage', response.data.Errors);
                        }

                    }).catch(function (thrown) {

                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                            console.log('Request canceled', thrown.message);
                        }
                        store.commit('set_isSearcherInit', true);
                    });
            }
        },
        //забіл пароль
        ForgotPasswordAjax({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                axios.post(prop.ajax.url + '?loginn=' + prop.Email, {
                    prop: prop
                })
                    .then(response => {
                        var resData = response.data;
                        if (resData == "ERROR") {
                            store.commit('set_isSearcherInit', true);
                            eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.serverError);
                        }
                        else if (resData == "USER_NOT_FOUND") {
                            store.commit('set_isSearcherInit', true);
                            eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.UserNotFound);
                        }
                        else {
                            if (JSON.parse(response.config.data).prop.isPhone)
                                eventVue.$emit('openSmsForm', { phone: JSON.parse(response.config.data).prop.Email, isForgot: true });
                            else {
                                eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.resetPassword); 
                                if (store.getters.getUser.loginView)
                                    eventVue.$emit('loginLinkOnClick');
                            }

                            eventVue.$emit('closeForgotPasswordForm');
                            store.commit('set_isSearcherInit', true);
                        }
                    }).catch(function (thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                        }
                        store.commit('set_isSearcherInit', true);
                    });
            }
        },
        //обратная связь
        Feedback({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                //string name, string email, string textmail, string captcha
                axios.post(prop.ajax.url + '?name=' + prop.name + '&email=' + prop.email + '&textmail=' + prop.textmail + '&captcha=' + prop.captcha)
                    .then(response => {
                        //store.commit('set_searchResult', response.data);
                        store.commit('set_isSearcherInit', true);
                        var resp = JSON.parse(response.data);
                        switch (resp) {
                            case 'ERROR':
                                eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.severError);
                                break;
                            case 'ERROR_CAPTCHA': {
                                eventVue.$emit('updateCaptchaOnFeedbackForm');
                                eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.ConfirmPhoneAjaxError);
                            }
                                break;
                            default:
                                eventVue.$emit('closefeedbackForm');
                        }
                    })
                    .catch(function (thrown) {
                        console.log('Request canceled', thrown.message);
                        store.commit('set_isSearcherInit', true);
                    });

            }
        },
        //подтверждение телефона
        ConfirmPhoneAjax({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                //string name, string email, string textmail, string captcha
                axios.post(prop.ajax.url + '?code=' + prop.code + '&phone=' + prop.phone)
                    .then(response => {
                        var resData = response.data;
                        if (resData.Succeeded) {
                            eventVue.$emit('hideSmsForm');
                            if (store.getters.getUser.loginView)
                                eventVue.$emit('loginLinkOnClick');
                            else
                                this.dispatch('getUserInfo');
                        }
                        else if (resData.Errors.length > 0) {
                            eventVue.$emit('showErrorMessage', resData.Errors);
                        }
                        store.commit('set_isSearcherInit', true);
                    }).catch(function (thrown) {
                        eventVue.$emit('showSimpleMessage', thrown.message);
                        store.commit('set_isSearcherInit', true);
                    });
            }
        },
        //смена пароля
        ResetPasswordAjax({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (prop) {
                store.commit('set_isSearcherInit', false);
                const requestId = 'my_sample_request';
                if (cancel)
                    cancel();
                //string name, string email, string textmail, string captcha
                axios.post(prop.ajax.url + '?code=' + prop.code + '&newPassword=' + prop.newPassword + '&phone=' + prop.phone)
                    .then(response => {
                        //store.commit('set_searchResult', response.data);
                        eventVue.$emit('closeResetPasswordForm'); 
                        store.commit('set_isSearcherInit', true);
                        if (!response.data.Succeeded) {
                            eventVue.$emit('showErrorMessage', response.data.Errors);
                        }
                        else
                            this.dispatch('getUserInfo');
                                               
                    })
                    .catch(function (thrown) {
                        eventVue.$emit('showSimpleMessage', thrown.message);
                        store.commit('set_isSearcherInit', true);
                    });
            }
        },
        //инфа об юзере
        getUserInfo({ commit, state }) {
            store.commit('set_isSearcherInit', false);
            //string name, string email, string textmail, string captcha
            axios.get(store.getters.getAjaxUrlByName('UserInfo').url)
                .then(response => {
                   
                    if (response.data) {
                        if (response.data.Confirmed) {
                            //ставим юзера
                            this.commit('set_User', response.data);
                            //this.commit('startWorkTimer');
                            //якщо шари дснс, то завантажуємо поля
                            if (response.data.Roles.includes("DSNSLayers")) {
                                const properties = state.ndl.ajax.find((a => a.name === 'GetDSNSConfig'));
                                if (properties)
                                    this.dispatch(properties.name, properties);
                            }
                            else {
                                //прибираємо лоадер
                                store.commit('set_isSearcherInit', true);
                            }

                            if (this.state.userStore.loginView)
                                eventVue.$emit('closeLoginForm');
                            
                        }
                        else
                            this.dispatch('showNeedVerificationMessage', response.data);
                    }

                }).catch(function (thrown) {
                    eventVue.$emit('showSimpleMessage', thrown.message);
                    store.commit('set_isSearcherInit', true);
                });
        },

        getToken({ commit }) {
            //store.commit('set_isSearcherInit', false);
            axios.get(store.getters.getAjaxUrlByName('GISToken').url)
                .then(response => {
                    //store.commit('set_isSearcherInit', true);
                    //console.log('token = ' + response.data + '; time= ' + new Date());
                    if (response.data != "not enough rights") {
                        store.commit('updateRasters', response.data);
                    }

                }).catch(function (thrown) { });
        },

        //код на телефон
        SendCodeToPhone({ commit }) {
            store.commit('set_isSearcherInit', false);
            //string name, string email, string textmail, string captcha
            axios.post(store.getters.getAjaxUrlByName('SendCodeToPhone').url)
                .then(response => {
                    store.commit('set_isSearcherInit', true);
                }).catch(function (thrown) {
                    eventVue.$emit('showSimpleMessage', thrown.message);
                    store.commit('set_isSearcherInit', true);
                });
            store.commit('set_isSearcherInit', true);
        },
        //подтверждение міла
        SendConfirmEmail({ commit }) {
            store.commit('set_isSearcherInit', false);
            const requestId = 'my_sample_request';
            if (cancel)
                cancel();
            //string name, string email, string textmail, string captcha
            axios.post(store.getters.getAjaxUrlByName('SendConfirmEmail').url, {
                cancelToken: new CT(function executor(c) {
                    // An executor function receives a cancel function as a parameter
                    cancel = c;
                    //console.log('request is cancelled');
                })
            })
                .then(response => {
                    store.commit('set_isSearcherInit', true);
                    if (response.data == "") {
                        eventVue.$emit('showSimpleMessage',  store.state.messagesStore.messagesTexts.confirmRegistration);
                        if (store.getters.getUser.loginView)
                            eventVue.$emit('loginLinkOnClick');
                    }
                    else
                        this.dispatch('showNeedVerificationMessage', response.data);
                }).catch(function (thrown) {
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                        console.log('Request canceled', thrown.message);
                    }
                    store.commit('set_isSearcherInit', true);
                });
        },
        //аутентификация через соц сети
        socialAuth({ commit }, properties) {
            var prop = JSON.parse(properties);
            store.commit('set_isSearcherInit', false);
            axios.post(prop.ajax.url + '?login_provider=' + prop.login_provider + '&token=' + prop.token + '&providerKey=' + prop.providerKey)
                .then(response => {
                    switch (response.data) {
                        case 'INVALID_TOKEN': {
                            eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.serverError);
                            store.commit('set_isSearcherInit', true);
                        }
                            break;
                        default: {
                            eventVue.$emit('closeLoginForm');
                            //this.dispatch('getUserInfo');
                            //this.dispatch('getToken');
                            //this.commit('startTokenTiks');
                            store.commit('set_isSearcherInit', true);
                        }
                    }
                })
                .catch(function (thrown) { });
        },
        //конверт координат
        convertCoordinates({ commit }, properties) {
            var prop = JSON.parse(properties);
            if (!cancelCoord) {
                var ddata = new FormData();
                ddata.append('longitudes', JSON.stringify(prop.longitudes));
                ddata.append('latitudes', JSON.stringify(prop.latitudes));
                // alert(JSON.stringify(prop.longitudes) + ' , ' + JSON.stringify(prop.latitudes));
                axios.post(prop.ajax.url, ddata, {
                    cancelToken: new CT(function executor(c) {
                        // An executor function receives a cancel function as a parameter
                        cancelCoord = c;
                        //console.log('request is cancelled');
                    }),
                    prop: prop
                })
                    .then(response => {
                        eventVue.$emit('showLocation', { newCoords: response.data[0], prop: prop });
                        cancelCoord = null;
                    })
                    .catch(function (thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                        }
                    });

            }
        },
        //инфа по разрітиям
        GetDugById({ commit }, properties) {
            var prop = JSON.parse(properties);
            const requestId = 'my_sample_request';
            store.commit('set_isSearcherInit', false);
            axios.get(prop.ajax.url + '?dugId=' + prop.dugId, {
                prop: prop
            })
                .then(response => {
                    eventVue.$emit('showInfoWindow', { responce: response.data, prop: response.config.prop });
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });

        },
        //инфа о рекламе
        GetAdwertById({ commit }, properties) {
            var prop = JSON.parse(properties);
            const requestId = 'my_sample_request';
            store.commit('set_isSearcherInit', false);
            axios.get(prop.ajax.url + '?adwertId=' + prop.adwertId, {
                prop: prop
            })
                .then(response => {
                    eventVue.$emit('showInfoWindow', { responce: response.data, prop: response.config.prop });
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });

        },
        GetAdwerts({ commit }, properties) {
            var prop = JSON.parse(properties);
            const requestId = 'my_sample_request';
            store.commit('set_isSearcherInit', false);
            var ddata = new FormData();
            for (var i = 0; i < prop.ids.length; i++)
                ddata.append('ids', prop.ids[i]);
            axios.post(prop.ajax.url, ddata, {
                prop: prop
            })
                .then(response => {
                    eventVue.$emit('showInfoWindow', { responce: response.data, prop: response.config.prop });
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });

        },
        GetAllWifiMap({ commit }, properties) {
            var prop = JSON.parse(properties);
            const requestId = 'my_sample_request';
            store.commit('set_isSearcherInit', false);
            store.commit('set_layerToLoad', prop.layer.id);
            axios.post(prop.ajax.url, {
                prop: prop
            })
                .then(response => {
                    store.commit('set_featuresToLayer', response.data);
                   // eventVue.$emit('selectLayer', (JSON.parse(response.config.data)).prop.layer.id);
                    eventVue.$emit('buildLayer', (JSON.parse(response.config.data)).prop.layer.id);
                    store.commit('set_isSearcherInit', true);
                    //eventVue.$emit('GetAllWifiMap', { responce: response.data, prop: response.config.prop });
                    //    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });

        },
        //Школы
        //this.$store.dispatch('GetAddressesByPrimarySchool', JSON.stringify({ ajax: this.$store.getters.getAjaxUrlByName('GetAddressesByPrimarySchool'), schoolGuid: data }));
        //@@@
        GetAddressesByPrimarySchool({ commit }, properties) {
            var prop = JSON.parse(properties);
           // store.commit('set_isSearcherInit', false);
            axios.get(prop.ajax.url + prop.schoolGuid, {
                prop: prop
            })
                .then(response => {
                    store.commit('set_isSearcherInit', true);
                    if (response.data == 'SCHOOL_NOT_FOUND')
                        eventVue.$emit('showSimpleMessage', store.messagesStore.messagesTexts.hasNoData);
                    else if (Array.isArray(response.data) && response.data.length > 0) {
                        eventVue.$emit('getAddressObjectsGeometriesByAddressObjectsList', { response: response.data, res: response.config.prop });
                       // store.commit('setAddressObjectsList', response.data);
                    }
                    else if (Array.isArray(response.data) && response.data.length == 0) {
                        eventVue.$emit('addressesNotFound');
                       // store.commit('setAddressObjectsList', response.data);
                    }                    
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('showSimpleMessage', thrown.message);
                });

        },
        GetAddressesByBombShelter({ commit }, properties) {
            var prop = JSON.parse(properties);
            //store.commit('set_isSearcherInit', false);
            axios.get(prop.ajax.url + prop.bombGuid, {
                prop: prop
            })
                .then(response => {
                    store.commit('set_isSearcherInit', true);
                    if (response.data == 'ADDRESSES_NOT_FOUND')
                        eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.hasNoData);
                    else if (Array.isArray(response.data) && response.data.length > 0) {
                        eventVue.$emit('getAddressObjectsGeometriesByAddressObjectsList', { response: response.data, res: response.config.prop });
                    }
                    else if (Array.isArray(response.data) && response.data.length == 0) {
                        eventVue.$emit('addressesNotFound');
                        //eventVue.$emit('showServiceObject', { response: response.config.prop.res, prop: { bindToServices: { layerId: 15 } }, identity: response.config.prop.identity });
                    }                    
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('showSimpleMessage', thrown.message);
                });
        },
        GetAddressesByHospital({ commit }, properties) {
            var prop = JSON.parse(properties);
            //store.commit('set_isSearcherInit', false);
            axios.get(prop.ajax.url + prop.medGuid, {
                prop: prop
            })
                .then(response => {
                    store.commit('set_isSearcherInit', true);
                    if (response.data == 'HOSPITAL_NOT_FOUND')
                        eventVue.$emit('showSimpleMessage', store.messagesStore.messagesTexts.hasNoData);
                    else if (Array.isArray(response.data) && response.data.length > 0) {
                        response.config.prop.loaded = true;
                        eventVue.$emit('getAddressObjectsGeometriesByAddressObjectsList', { response: response.data, res: response.config.prop });
                       // store.commit('setAddressObjectsList', response.data);
                    }
                    else if (Array.isArray(response.data) && response.data.length == 0) {
                        eventVue.$emit('addressesNotFound');
                        // store.commit('setAddressObjectsList', response.data);
                    }      
                    
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('showSimpleMessage', thrown.message);
                });

        },

        GetServiceObject({ commit }, properties) {
            var prop = JSON.parse(properties);
            store.commit('set_isSearcherInit', false);
            axios.get(prop.url, {
                prop: prop
            })
            .then(response => {
                store.commit('set_isSearcherInit', true);
                if (response.data == 'SCHOOL_NOT_FOUND')
                    eventVue.$emit('showSimpleMessage', store.messagesStore.messagesTexts.hasNoData);
                else if (response.data.GUID || (response.data.features && Array.isArray(response.data.features) && response.data.features.length > 0)) {
                    eventVue.$emit('showServiceObject', { response: response.data, prop: response.config.prop });
                }
            })
            .catch(function (thrown) {
                store.commit('set_isSearcherInit', true);
                eventVue.$emit('showSimpleMessage', thrown.message);
            });

        },
        GetServiceObjects({ commit }, properties) {
            var prop = JSON.parse(properties);
            store.commit('set_isSearcherInit', false);
            console.log(prop.bindToServices.type + ' - 1');
            if (prop.AR_ID) {
                var href = window.location.pathname == '/' ? window.location.origin + '/opendataportal/' : window.location.href;
                axios.get(href + prop.bindToServices.pre_url + prop.AR_ID, {
                    prop: prop
                }).then(response => {
                    var bsArr = [], config = response.config;
                    if (response.data.GUID) {
                        bsArr.push(
                            axios.get(href + prop.bindToServices.url + prop.AR_ID, {
                                prop: prop
                            })
                        );
                    }
                    else if (Array.isArray(response.data) && response.data.length > 0) {
                        response.data.forEach(function (rdItem) {
                            bsArr.push(
                                axios.get(prop.bindToServices.url + rdItem + prop.bindToServices.url_second_part, {
                                    prop: prop
                                })
                            );
                        }.bind(this));
                    }
                    else if (typeof response.data === 'string' && response.data !== 'SCHOOL_NOT_FOUND' && response.data !== 'BOMBSHELTERS_NOT_FOUND' && response.data !== 'HOSPITALS_NOT_FOUND') {
                        var res = JSON.parse(response.data);
                        if (res.features.length > 0) {
                            res.features.forEach(function (fItem, index) {
                                if (fItem.attributes[prop.bindToServices.field] == prop.bindToServices.feature.attributes[prop.bindToServices.field])
                                    bsArr.push(
                                        axios.get(href + prop.bindToServices.url + prop.AR_ID, {
                                            prop: prop
                                        })
                                    );
                            }.bind(this));
                        }
                    }
                    if (bsArr.length > 0) {
                        console.log(prop.bindToServices.type + ' - 2');
                        Promise.all(bsArr)
                            .then(response => {
                                if (Array.isArray(response) && response.length > 0) {
                                    var fArr = [], prop;
                                    response.forEach(function (RItem) {
                                        prop = RItem.config.prop;
                                        if (RItem.data == 'SCHOOL_NOT_FOUND')
                                            eventVue.$emit('showSimpleMessage', store.messagesStore.messagesTexts.hasNoData);
                                        else if (RItem.data.GUID || (RItem.data.features && Array.isArray(RItem.data.features) && RItem.data.features.length > 0)) {
                                            fArr.push(RItem.data);
                                        }
                                        else if (typeof RItem.data === 'string' && RItem.data !== 'SCHOOL_NOT_FOUND' && RItem.data !== 'BOMBSHELTERS_NOT_FOUND' && RItem.data !== 'HOSPITALS_NOT_FOUND') {
                                            var res = JSON.parse(RItem.data);
                                            if (res.features.length > 0) {
                                                var feature;
                                                res.features.forEach(function (fItem, index) {
                                                    if (fItem.attributes[prop.bindToServices.field] == prop.bindToServices.feature.attributes[prop.bindToServices.field])
                                                        feature = fItem;
                                                }.bind(this));
                                                if (feature) {
                                                    res.features.length = 0;
                                                    res.features.push(feature);
                                                    fArr.push(res);
                                                }
                                            }
                                        }
                                    }.bind(this));
                                    //собираем адреса по объектам
                                    var fAdrArr = [],
                                        method,
                                        field;
                                    if (prop.bindToServices.type == "bombshelters") {
                                        method = this.getters.getAjaxUrlByName('GetAddressesByBombShelter');
                                        field = prop.bindToServices.field;
                                    }
                                    else if (prop.bindToServices.type == "scool") {
                                        method = this.getters.getAjaxUrlByName('GetAddressesByPrimarySchool');
                                        field = 'GUID';
                                    }
                                    else if (prop.bindToServices.type == "medicine") {
                                        method = this.getters.getAjaxUrlByName('GetAddressesByHospital');
                                        field = 'OBJECTID';
                                    }
                                    fArr.forEach(function (fItem, index, arr) {

                                        if (fItem.features) {
                                            fItem.features.forEach(function (fiItem) {
                                                fAdrArr.push(axios.get(method.url + fiItem.attributes[field], { prop: prop, obj: fItem, OID: fiItem.attributes[field] }))
                                            }.bind(this));
                                        }
                                        else
                                            fAdrArr.push(axios.get(method.url + fItem[field], { prop: prop, obj: fItem, OID: fItem[field] }))
                                    });
                                    if (fAdrArr.length > 0) {
                                        console.log(prop.bindToServices.type + ' - 3');

                                        Promise.all(fAdrArr)
                                            .then(response => {
                                                if (Array.isArray(response) && response.length > 0) {
                                                    var outArr = [], adrArr = [], objArdArr = [], objTempId;
                                                    response.forEach(function (rItem, index, arr) {
                                                        //object
                                                        outArr.push(rItem.config.obj);
                                                        //setAddresses
                                                        if (objTempId != rItem.config['OID']) {
                                                            if (objArdArr.length > 0) {
                                                                var o_ = {};
                                                                // Vue.set(o_, objTempId, objArdArr);
                                                                o_.objTempId = objArdArr;
                                                                o_.ID = objTempId;
                                                                adrArr.push(o_);
                                                            }
                                                            objTempId = rItem.config['OID'];
                                                            objArdArr = [];
                                                            if (rItem.data.length > 0) {
                                                                rItem.data.forEach(function (ridItem) {
                                                                    objArdArr.push(ridItem);
                                                                }.bind(this));
                                                            }

                                                            if (arr.length == (index + 1)) {
                                                                var o_ = {};
                                                                o_.objTempId = objArdArr;
                                                                o_.ID = objTempId;
                                                                adrArr.push(o_);
                                                            }
                                                        }
                                                    }.bind(this));
                                                    if (adrArr.length > 0) {
                                                        var res = [], ids = [];
                                                        //обнуляем

                                                        //СИТУАЦИЯ КОГДА  БОЛЬШЕ 1000 НЕ ОБРАБОТАНО !!!!!!!!!!!!!!
                                                        // if (data.response.length < 1000) {

                                                        adrArr.forEach(function (drItem) {
                                                            var q = new this.getters.getArcGisWidgets.Query();
                                                            q.outFields = ["*"];
                                                            q.returnGeometry = true;
                                                            q.orderByFields = ["ADDRESSID", "FULLADDRUA"];
                                                            q.where = "AR_ID IN (" + drItem.objTempId.join(',') + ") AND TypeOfBuild = 1";
                                                            res.push(new this.getters.getArcGisWidgets.QueryTask("https://smart.khmr.gov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/6")
                                                                .execute(q)
                                                            );
                                                        }.bind(this));
                                                        console.log(prop.bindToServices.type + ' - 4');

                                                        promices = this.getters.getArcGisWidgets.all(res);
                                                        promices.then(e => {
                                                            if (e.length > 0) {
                                                                var outObj = {};
                                                                e.forEach(function (eItem, index) {
                                                                    var name = adrArr[index].ID;
                                                                    Vue.set(outObj, name, eItem);
                                                                    //outObj.name = eItem;
                                                                }.bind(this));
                                                                store.commit('setServiceAddresses', outObj);
                                                                //this.handleIdentityResult(data.res.res);
                                                                if (outArr.length > 0)
                                                                    eventVue.$emit('showServiceObject', { response: outArr, prop: prop });

                                                            }

                                                            store.commit('set_isSearcherInit', true);
                                                        }).catch(function (thrown) {
                                                            store.commit('set_isSearcherInit', true);
                                                            eventVue.$emit('showSimpleMessage', thrown.message);
                                                        });
                                                        // this.commit('setServiceAddresses',adrArr );
                                                    }
                                                    else
                                                        store.commit('set_isSearcherInit', true);
                                                }
                                                //запулить адреса
                                            })
                                            .catch(function (thrown) {
                                                store.commit('set_isSearcherInit', true);
                                                eventVue.$emit('showSimpleMessage', thrown.message);
                                            });
                                    }
                                    else
                                        store.commit('set_isSearcherInit', true);                                    
                                }
                                else
                                    store.commit('set_isSearcherInit', true);  
                            })
                            .catch(function (thrown) {
                                store.commit('set_isSearcherInit', true);
                                eventVue.$emit('showSimpleMessage', thrown.message);
                            });
                    }
                    else {
                        if (response.config.prop.bindToServices.type == "bombshelters")
                            eventVue.$emit('removeInfoWindowBtn', "bombshelters");
                        else if (response.config.prop.bindToServices.type == "scool")
                            eventVue.$emit('removeInfoWindowBtn', "scool");

                        store.commit('set_isSearcherInit', true);
                    }
                   
                })
                    .catch(function (thrown) {
                        store.commit('set_isSearcherInit', true);
                        eventVue.$emit('showSimpleMessage', thrown.message);
                    });
            }
        },

        getServicesObjects({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var fullProp = properties;
           // store.commit('set_isSearcherInit', false);
            var servicesAxiosArr = [],
                href =( window.location.pathname == '/' ||  window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href;
            properties.services.bindToServices.forEach(function (bsItem) {
                var prop = JSON.parse(bsItem.dtObject),
                    ax = axios.get(href + prop.bindToServices.pre_url + prop.AR_ID, {
                        prop: prop,
                        fullProp: fullProp
                    });

                servicesAxiosArr.push(ax);
            }.bind(this));
            if (servicesAxiosArr.length > 0) {
                //проверка на наличие объектов в сервисах
                Promise.all(servicesAxiosArr).then(response => {
                    var secondServicesAxiosRequest = [],
                        secondURLS = [];
                    response.forEach(function (rItem, index) {
                        var config = rItem.config,
                            prop = rItem.config.prop,
                            currentSecondURL;
                        
                        if (rItem.data.GUID) {
                            currentSecondURL = prop.bindToServices.url + rItem.data.GUID + prop.bindToServices.url_second_part;
                            if ((secondURLS.length > 0 && secondURLS.join(';').indexOf(currentSecondURL) < 0) || secondServicesAxiosRequest.length == 0) {
                                secondURLS.push(currentSecondURL);
                                secondServicesAxiosRequest.push(
                                    //axios.get(href + prop.bindToServices.url + prop.AR_ID, {
                                    //    prop: prop
                                    //})
                                    axios.get(currentSecondURL, {
                                        prop: prop
                                    })
                                );
                            }
                            }
                        else if (Array.isArray(rItem.data) && rItem.data.length > 0) {
                            rItem.data.forEach(function (rdItem) {
                                currentSecondURL = prop.bindToServices.url + rdItem + prop.bindToServices.url_second_part;
                                if ((secondURLS.length > 0 && secondURLS.join(';').indexOf(currentSecondURL) < 0) || secondServicesAxiosRequest.length == 0) {
                                    secondURLS.push(currentSecondURL);
                                    secondServicesAxiosRequest.push(
                                        axios.get(currentSecondURL, {
                                            prop: prop
                                        })
                                    );
                                }
                            }.bind(this));
                        }
                        else if (typeof rItem.data === 'string' && rItem.data !== 'SCHOOL_NOT_FOUND' && rItem.data !== 'BOMBSHELTERS_NOT_FOUND' && rItem.data !== 'HOSPITALS_NOT_FOUND') {
                            var res = JSON.parse(rItem.data);
                            if (res.features.length > 0) {
                                res.features.forEach(function (fItem, index) {
                                    // if (fItem.attributes[prop.bindToServices.field] == prop.bindToServices.feature.attributes[prop.bindToServices.field])
                                    currentSecondURL = href + prop.bindToServices.url + prop.AR_ID;
                                    if ((secondURLS.length > 0 && secondURLS.join(';').indexOf(currentSecondURL) < 0) || secondServicesAxiosRequest.length == 0) {
                                        secondURLS.push(currentSecondURL);
                                        secondServicesAxiosRequest.push(
                                            axios.get(currentSecondURL, {
                                                prop: prop
                                            })
                                        );
                                    }
                                }.bind(this));
                            }
                        }
                        
                       //                   
                    }.bind(this));
                    if (secondServicesAxiosRequest.length > 0) {
                        // store.commit('set_isSearcherInit', true);
                        Promise.all(secondServicesAxiosRequest).then(response => {
                            //получаем список объектов по сервисно
                            var resData = [];
                            response.forEach(function (rItem) {
                                var newService,
                                    data,
                                    layerId = rItem.config.prop.bindToServices.layerId,
                                    layer = this.getters.geLayerById(layerId);
                                switch (rItem.config.prop.bindToServices.type) {
                                    case 'bombshelters': {
                                        data = rItem.data;
                                        var feature = {
                                            attributes: {},
                                            displayFieldName: data.displayFieldName,
                                            geometry: {
                                                x: -1,
                                                y: -1,
                                                spatialReference: { wkid: 28467, latestWkid: 28467 }
                                            },
                                            geometryType: data.geometryType,
                                            layerId: layerId,
                                            layerName: layer.nameVectorLayer
                                        };
                                        data.features.forEach(function (fItem) {
                                            var copyFeature = JSON.parse(JSON.stringify(Object.assign({}, feature)));
                                            copyFeature.geometry.x = fItem.geometry.x;
                                            copyFeature.geometry.y = fItem.geometry.y;
                                            copyFeature.attributes = fItem.attributes;
                                            newService = {
                                                name: 'Укриття',
                                                feature: copyFeature,
                                                prop: rItem.config.prop
                                            };
                                            resData.push(newService);
                                        }.bind(this));

                                    }
                                        break;
                                    case 'scool': {
                                        data = rItem.data;
                                        var feature = {
                                            attributes: {},
                                            displayFieldName: data.displayFieldName,
                                            geometry: {
                                                x: -1,
                                                y: -1,
                                                spatialReference: { wkid: 28467, latestWkid: 28467 }
                                            },
                                            geometryType: data.geometryType,
                                            layerId: layerId,
                                            layerName: layer.nameVectorLayer
                                        };
                                        data.features.forEach(function (fItem) {
                                            var copyFeature = JSON.parse(JSON.stringify(Object.assign({}, feature)));
                                            copyFeature.geometry.x = fItem.geometry.x;
                                            copyFeature.geometry.y = fItem.geometry.y;
                                            copyFeature.attributes = fItem.attributes;
                                            newService = {
                                                name: 'Школа',
                                                feature: copyFeature,
                                                prop: rItem.config.prop
                                            };
                                            resData.push(newService);
                                        }.bind(this));

                                    }
                                        break;
                                    case 'medicine': {
                                        data = JSON.parse(rItem.data);
                                        var feature = {
                                            attributes: {},
                                            displayFieldName: data.displayFieldName,
                                            geometry: {
                                                x: -1,
                                                y: -1,
                                                spatialReference: { wkid: 28467, latestWkid: 28467 }
                                            },
                                            geometryType: data.geometryType,
                                            layerId: layerId,
                                            layerName: layer.nameVectorLayer
                                        };
                                        data.features.forEach(function (fItem) {
                                            var copyFeature = JSON.parse(JSON.stringify(Object.assign({}, feature)));
                                            copyFeature.geometry.x = fItem.geometry.x;
                                            copyFeature.geometry.y = fItem.geometry.y;
                                            copyFeature.attributes = fItem.attributes;
                                            newService = {
                                                name: (function () {
                                                    var newServiceName = '',
                                                        lowerCaseCompanyName = fItem.attributes.name.toLowerCase();
                                                    if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('дитяч') >= 0 && lowerCaseCompanyName.indexOf('поліклін') >= 0)
                                                        newServiceName = 'Дитяча поліклініка';
                                                    else if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('поліклін') >= 0)
                                                        newServiceName = 'Поліклініка';
                                                    else if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('дитяч') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                        newServiceName = 'Дитяча лікарня';
                                                    else if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                        newServiceName = 'Лікарня';
                                                    else if (lowerCaseCompanyName.indexOf('стомат') >= 0 && lowerCaseCompanyName.indexOf('дитяч') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                        newServiceName = 'Дитяча стоматологічна поліклініка';
                                                    else if (lowerCaseCompanyName.indexOf('стомат') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                        newServiceName = 'Стоматологічна поліклініка';
                                                    else if (lowerCaseCompanyName.indexOf('пологов') >= 0)
                                                        newServiceName = 'Пологовий будинок';
                                                    else if (lowerCaseCompanyName.indexOf('венеролог') >= 0)
                                                        newServiceName = 'Вендиспансер';
                                                    return newServiceName;
                                                })(),
                                                feature: copyFeature,
                                                prop: rItem.config.prop
                                            };
                                            resData.push(newService);
                                        }.bind(this));
                                    }
                                        break;
                                }
                            }.bind(this));

                            //if (resData.length > 0)
                                eventVue.$emit('setServicesObjects', resData);

                            store.commit('set_isSearcherInit', true);
                        }).catch(function (thrown) {
                            store.commit('set_isSearcherInit', true);
                            //eventVue.$emit('showSimpleMessage', thrown.message);
                            console.log('Ошибка сервиса: ' + thrown.message);
                            eventVue.$emit('setServicesObjects', []);
                        });
                    }
                    else {
                        store.commit('set_isSearcherInit', true);
                        eventVue.$emit('setServicesObjects', []);
                    }

                }).catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    console.log('Ошибка сервиса: ' + thrown.message);
                    eventVue.$emit('setServicesObjects', []);
                    //eventVue.$emit('showSimpleMessage', thrown.message);
                });
            }  





            //if (prop.AR_ID) {
                
            //    axios.get(href + prop.bindToServices.pre_url + prop.AR_ID, {
            //        prop: { prop:prop, full: }
            //    }).then(response => {
            //        var bsArr = [], config = response.config;
            //        if (response.data.GUID) {
            //            bsArr.push(
            //                axios.get(href + prop.bindToServices.url + prop.AR_ID, {
            //                    prop: prop
            //                })
            //            );
            //        }
            //        else if (Array.isArray(response.data) && response.data.length > 0) {
            //            response.data.forEach(function (rdItem) {
            //                bsArr.push(
            //                    axios.get(prop.bindToServices.url + rdItem + prop.bindToServices.url_second_part, {
            //                        prop: prop
            //                    })
            //                );
            //            }.bind(this));
            //        }
            //        else if (typeof response.data === 'string' && response.data !== 'SCHOOL_NOT_FOUND' && response.data !== 'BOMBSHELTERS_NOT_FOUND' && response.data !== 'HOSPITALS_NOT_FOUND') {
            //            var res = JSON.parse(response.data);
            //            if (res.features.length > 0) {
            //                res.features.forEach(function (fItem, index) {
            //                    if (fItem.attributes[prop.bindToServices.field] == prop.bindToServices.feature.attributes[prop.bindToServices.field])
            //                        bsArr.push(
            //                            axios.get(href + prop.bindToServices.url + prop.AR_ID, {
            //                                prop: prop
            //                            })
            //                        );
            //                }.bind(this));
            //            }
            //        }
            //        if (bsArr.length > 0) {
            //            console.log(prop.bindToServices.type + ' - 2');
            //            Promise.all(bsArr)
            //                .then(response => {
            //                    if (Array.isArray(response) && response.length > 0) {
            //                        var fArr = [], prop;
            //                        response.forEach(function (RItem) {
            //                            prop = RItem.config.prop;
            //                            if (RItem.data == 'SCHOOL_NOT_FOUND')
            //                                eventVue.$emit('showSimpleMessage', store.messagesStore.messagesTexts.hasNoData);
            //                            else if (RItem.data.GUID || (RItem.data.features && Array.isArray(RItem.data.features) && RItem.data.features.length > 0)) {
            //                                fArr.push(RItem.data);
            //                            }
            //                            else if (typeof RItem.data === 'string' && RItem.data !== 'SCHOOL_NOT_FOUND' && RItem.data !== 'BOMBSHELTERS_NOT_FOUND' && RItem.data !== 'HOSPITALS_NOT_FOUND') {
            //                                var res = JSON.parse(RItem.data);
            //                                if (res.features.length > 0) {
            //                                    var feature;
            //                                    res.features.forEach(function (fItem, index) {
            //                                        if (fItem.attributes[prop.bindToServices.field] == prop.bindToServices.feature.attributes[prop.bindToServices.field])
            //                                            feature = fItem;
            //                                    }.bind(this));
            //                                    if (feature) {
            //                                        res.features.length = 0;
            //                                        res.features.push(feature);
            //                                        fArr.push(res);
            //                                    }
            //                                }
            //                            }
            //                        }.bind(this));
            //                        //собираем адреса по объектам
            //                        var fAdrArr = [],
            //                            method,
            //                            field;
            //                        if (prop.bindToServices.type == "bombshelters") {
            //                            method = this.getters.getAjaxUrlByName('GetAddressesByBombShelter');
            //                            field = prop.bindToServices.field;
            //                        }
            //                        else if (prop.bindToServices.type == "scool") {
            //                            method = this.getters.getAjaxUrlByName('GetAddressesByPrimarySchool');
            //                            field = 'GUID';
            //                        }
            //                        else if (prop.bindToServices.type == "medicine") {
            //                            method = this.getters.getAjaxUrlByName('GetAddressesByHospital');
            //                            field = 'OBJECTID';
            //                        }
            //                        fArr.forEach(function (fItem, index, arr) {

            //                            if (fItem.features) {
            //                                fItem.features.forEach(function (fiItem) {
            //                                    fAdrArr.push(axios.get(method.url + fiItem.attributes[field], { prop: prop, obj: fItem, OID: fiItem.attributes[field] }))
            //                                }.bind(this));
            //                            }
            //                            else
            //                                fAdrArr.push(axios.get(method.url + fItem[field], { prop: prop, obj: fItem, OID: fItem[field] }))
            //                        });
            //                        if (fAdrArr.length > 0) {
            //                            console.log(prop.bindToServices.type + ' - 3');

            //                            Promise.all(fAdrArr)
            //                                .then(response => {
            //                                    if (Array.isArray(response) && response.length > 0) {
            //                                        var outArr = [], adrArr = [], objArdArr = [], objTempId;
            //                                        response.forEach(function (rItem, index, arr) {
            //                                            //object
            //                                            outArr.push(rItem.config.obj);
            //                                            //setAddresses
            //                                            if (objTempId != rItem.config['OID']) {
            //                                                if (objArdArr.length > 0) {
            //                                                    var o_ = {};
            //                                                    // Vue.set(o_, objTempId, objArdArr);
            //                                                    o_.objTempId = objArdArr;
            //                                                    o_.ID = objTempId;
            //                                                    adrArr.push(o_);
            //                                                }
            //                                                objTempId = rItem.config['OID'];
            //                                                objArdArr = [];
            //                                                if (rItem.data.length > 0) {
            //                                                    rItem.data.forEach(function (ridItem) {
            //                                                        objArdArr.push(ridItem);
            //                                                    }.bind(this));
            //                                                }

            //                                                if (arr.length == (index + 1)) {
            //                                                    var o_ = {};
            //                                                    o_.objTempId = objArdArr;
            //                                                    o_.ID = objTempId;
            //                                                    adrArr.push(o_);
            //                                                }
            //                                            }
            //                                        }.bind(this));
            //                                        if (adrArr.length > 0) {
            //                                            var res = [], ids = [];
            //                                            //обнуляем

            //                                            //СИТУАЦИЯ КОГДА  БОЛЬШЕ 1000 НЕ ОБРАБОТАНО !!!!!!!!!!!!!!
            //                                            // if (data.response.length < 1000) {

            //                                            adrArr.forEach(function (drItem) {
            //                                                var q = new this.getters.getArcGisWidgets.Query();
            //                                                q.outFields = ["*"];
            //                                                q.returnGeometry = true;
            //                                                q.orderByFields = ["ADDRESSID", "FULLADDRUA"];
            //                                                q.where = "AR_ID IN (" + drItem.objTempId.join(',') + ") AND TypeOfBuild = 1";
            //                                                res.push(new this.getters.getArcGisWidgets.QueryTask("https://ar.citynet.kharkov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/6")
            //                                                    .execute(q)
            //                                                );
            //                                            }.bind(this));
            //                                            console.log(prop.bindToServices.type + ' - 4');

            //                                            promices = this.getters.getArcGisWidgets.all(res);
            //                                            promices.then(e => {
            //                                                if (e.length > 0) {
            //                                                    var outObj = {};
            //                                                    e.forEach(function (eItem, index) {
            //                                                        var name = adrArr[index].ID;
            //                                                        Vue.set(outObj, name, eItem);
            //                                                        //outObj.name = eItem;
            //                                                    }.bind(this));
            //                                                    store.commit('setServiceAddresses', outObj);
            //                                                    //this.handleIdentityResult(data.res.res);
            //                                                    if (outArr.length > 0)
            //                                                        eventVue.$emit('showServiceObject', { response: outArr, prop: prop });

            //                                                }

            //                                                store.commit('set_isSearcherInit', true);
            //                                            }).catch(function (thrown) {
            //                                                store.commit('set_isSearcherInit', true);
            //                                                eventVue.$emit('showSimpleMessage', thrown.message);
            //                                            });
            //                                            // this.commit('setServiceAddresses',adrArr );
            //                                        }
            //                                        else
            //                                            store.commit('set_isSearcherInit', true);
            //                                    }
            //                                    //запулить адреса
            //                                })
            //                                .catch(function (thrown) {
            //                                    store.commit('set_isSearcherInit', true);
            //                                    eventVue.$emit('showSimpleMessage', thrown.message);
            //                                });
            //                        }
            //                        else
            //                            store.commit('set_isSearcherInit', true);                                    
            //                    }
            //                    else
            //                        store.commit('set_isSearcherInit', true);  
            //                })
            //                .catch(function (thrown) {
            //                    store.commit('set_isSearcherInit', true);
            //                    eventVue.$emit('showSimpleMessage', thrown.message);
            //                });
            //        }
            //        else {
            //            if (response.config.prop.bindToServices.type == "bombshelters")
            //                eventVue.$emit('removeInfoWindowBtn', "bombshelters");
            //            else if (response.config.prop.bindToServices.type == "scool")
            //                eventVue.$emit('removeInfoWindowBtn', "scool");

            //            store.commit('set_isSearcherInit', true);
            //        }
                   
            //    })
            //        .catch(function (thrown) {
            //            store.commit('set_isSearcherInit', true);
            //            eventVue.$emit('showSimpleMessage', thrown.message);
            //        });
            //}
            //}.bind(this));

           // console.log(prop.bindToServices.type + ' - 1');
        },

        GetAllHistBuilds({ commit }, properties) {
            var prop = JSON.parse(properties);
 
            //store.commit('set_monumentsFeatures', prop);
            store.commit('set_isSearcherInit', false);
            axios.get(prop.ajax.url, {
                    prop: prop
                })
                .then(response => {
                    response.config.prop.features = response.data.features;
                    store.commit('set_monumentsFeatures', response.config.prop);
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('showSimpleMessage', thrown.message);
                });

        },

        GetWebACC({ commit }, properties) {
            var prop = JSON.parse(properties);
            var URL = prop.layer.loadMethodUrl + prop.layer.layerIds[0] + `/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=
                &spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=
                &geometryPrecision=&outSR=&havingClause=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false
                &returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&returnExtentOnly=false&datumTransformation=&parameterValues=
                &rangeValues=&quantizationParameters=&featureEncoding=esriDefault&f=pjson`;
            //store.commit('set_monumentsFeatures', prop);
            store.commit('set_isSearcherInit', false);
            axios.get(URL, {
                    prop: prop
                })
                .then(response => {
                    response.config.prop.features = response.data.features;
                    store.commit('set_WebACCFeatures', response.config.prop);
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('showSimpleMessage', thrown.message);
                });

        },

        Siren({ commit }, properties) {
            //store.commit('set_isSearcherInit', false);
            var prop = JSON.parse(properties);
            axios.get(prop.ajax.url, {
                prop: prop
                })
                .then(response => {
                    //response.config.prop.features = response.data.features;
                    store.commit('set_SirenFeatures', { layer: store.getters.getLayerByLayerId(22), features: response.data });
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('showSimpleMessage', thrown.message);
                });
            //var data = [
            //    { attributes: { OBJECTID: 7141, address: "вул. Дружби Народів, 202", type: 1 }, geometry: { x: 24001.077087402344, y: 18140.368103027344 } },
            //    { attributes: { OBJECTID: 7142, address: "вул. Дружби Народів, 204", type: 2 }, geometry: { x: 23981.166076660156, y: 18118.948120117188 } },
            //];
            //store.commit('set_SirenFeatures', { layer: store.getters.getLayerByLayerId(22), features: data });

        },
        //статистика==========================================================
        StartProjectStatistic({ commit }, properties) {
            //console.log('project = ' + properties.projectId);
            var currentProject = store.getters.getProjectById(properties.projectId),
                shortArr = [], longArr = [], dateArr = [];
            store.dispatch('showNotify', currentProject);
            currentProject.statistic.data.forEach(function (item, index) {
                if (item.datasets[0].data /*&& item.datasets[0].data.length == 0*/ && item.class && item.class == 'short')
                    shortArr.push({
                        method: 'GetProjectShortStatistic',
                        ajax: JSON.stringify({
                            ajax: store.getters.getAjaxUrlByName(item.method),
                            layerId: null,
                            projectId: currentProject.id,
                            statId: item.id,
                            vuexMethod: item.vuexMethod
                        })
                    });

                //else if (item.datasets[0].data && item.datasets[0].data.length > 0 && item.class && item.class == 'short')
                //    store.dispatch('showNotify', currentProject);
            

                if (item.datasets[0].data /*&& item.datasets[0].data.length == 0 */&& item.class && item.class == 'long')
                    longArr.push({
                        method: 'GetProjectMixedStatistic',
                        ajax: JSON.stringify({
                            ajax: store.getters.getAjaxUrlByName(item.method),
                            layerId: null,
                            projectId: currentProject.id,
                            statId: item.id,
                            vuexMethod: item.vuexMethod
                        })
                    });
                if (item.datasets[0].data /*&& item.datasets[0].data.length == 0 */&& item.class && item.class == 'date') {
                    dateArr.push({
                        method: 'GetProjectDateStatistic',
                        ajax: JSON.stringify({
                            ajax: store.getters.getAjaxUrlByName(item.method),
                            layerId: null,
                            projectId: currentProject.id,
                            statId: item.id,
                            datefrom: properties.datefrom,
                            dateto: properties.dateto,
                            vuexMethod: item.vuexMethod
                        })
                    });
                }
            }.bind(this));

            if (shortArr.length > 0)
                store.dispatch('GetProjectShortStatistic', shortArr);
            if (longArr.length > 0)
                store.dispatch('GetProjectMixedStatistic', longArr);
            if (dateArr.length > 0)
                store.dispatch('GetProjectDateStatistic', dateArr);
        },
        //short статистика
        GetProjectShortStatistic({ commit }, properties) {
            var prop = JSON.parse(properties[0].ajax),
                layer, project;
            if (prop && (prop.layerId >= 0 || prop.projectId >= 0)) {
                if (prop.projectId >= 0)
                    project = store.getters.getProjectById(prop.projectId);
                else {
                    layer = store.getters.geLayerById(prop.layerId);
                    project = store.getters.getProjectById(layer.pId);
                }
                if (project.statistic && !store.getters.getIsProjectInStats(project.id)) {
                    //добавить проект в статистику
                    //store.commit('add_projectToStat', project);
                    switch (project.id) {
                        case 0:
                            store.dispatch('GetDugShortStatistic', { projectId: project.id, ajax: prop.ajax.url, statId: prop.statId });
                            break;
                        case 5:
                            store.dispatch('GetWDPShortStatistic', { projectId: project.id, ajax: prop.ajax.url, statId: prop.statId });
                            break;
                        case 7:
                            store.dispatch('GetHeatingStat', { projectId: project.id, ajax: prop.ajax.url, statId: prop.statId });
                            break;
                    }
                }
            }
        },
        GetProjectFullStatistic({ commit }, properties) {
            var prop = JSON.parse(properties),
                layer, project;
            if (prop && (prop.layerId >= 0 || prop.projectId >= 0)) {
                if (prop.projectId >= 0)
                    project = store.getters.getProjectById(prop.projectId);
                else {
                    layer = store.getters.geLayerById(prop.layerId);
                    project = store.getters.getProjectById(layer.pId);
                }
                if (project.statistic && !store.getters.getIsProjectInStats(project.id)) {
                    if (cancelFullStats) {
                        cancelFullStats();
                        cancelFullStats = null;
                    }

                    switch (project.id) {
                        case 0:
                            store.dispatch('GetDugDatesStatistic', { project: project, ajax: prop.ajax.url });
                            break;
                        case 5:
                            store.dispatch('GetWDPDatesStatistic', { project: project, ajax: prop.ajax.url, datefrom: prop.datefrom, dateto: prop.dateto });
                            break;
                    }
                }
            }
        },
        GetProjectDateStatistic({ commit }, properties) {
            var ajaxArr = [];
            properties.forEach(function (item, index) {
                var prop = JSON.parse(properties[0].ajax),
                    layer, project;
                if (prop && (prop.layerId >= 0 || prop.projectId >= 0)) {
                    if (prop.projectId >= 0)
                        project = store.getters.getProjectById(prop.projectId);
                    else {
                        layer = store.getters.geLayerById(prop.layerId);
                        project = store.getters.getProjectById(layer.pId);
                    }
                    if (project.statistic && !store.getters.getIsProjectInStats(project.id))
                        ajaxArr.push({ method: prop.vuexMethod, option: { projectId: project.id, ajax: prop.ajax.url, statId: prop.statId, datefrom: prop.datefrom, dateto: prop.dateto} })
                }
            });

            //запускаем методы
            if (ajaxArr.length > 0)
                ajaxArr.forEach(function (item, index) {
                    store.dispatch(item.method, item.option);
                }.bind(this));
         },
        GetProjectMixedStatistic({ commit }, properties) {
            var ajaxArr = [];
                    //собираем методы в массив
            properties.forEach(function (item, index) {
                var prop = JSON.parse(item.ajax),
                    layer, project;
                if (prop && (prop.layerId >= 0 || prop.projectId >= 0)) {
                    if (prop.projectId >= 0)
                        project = store.getters.getProjectById(prop.projectId);
                    else {
                        layer = store.getters.geLayerById(prop.layerId);
                        project = store.getters.getProjectById(layer.pId);
                    }
                    if (project.statistic && !store.getters.getIsProjectInStats(project.id))
                        ajaxArr.push({ method: prop.vuexMethod, option: { projectId: project.id, ajax: prop.ajax.url, statId: prop.statId } })
                }
            }.bind(this));
                    //запускаем методы
            if(ajaxArr.length > 0)
                ajaxArr.forEach(function (item, index) {
                    store.dispatch(item.method, item.option);
                }.bind(this));
        },

        GetProjectWeekStatistic({ commit }, properties) {
            var prop = JSON.parse(properties),
                layer, project;
            if (prop && (prop.layerId || prop.projectId)) {
                if (prop.projectId)
                    project = store.getters.getProjectById(prop.projectId);
                else {
                    layer = store.getters.geLayerById(prop.layerId);
                    project = store.getters.getProjectById(layer.pId);
                }
                if (project.statistic && !store.getters.getIsProjectInStats(project.id)) {
                    axios.post(prop.ajax.url, {
                        prop: prop
                    })
                    .then(response => {
                        store.commit('set_responseFullStatistic', response);
                        store.commit('set_isSearcherInit', true);
                    })
                    .catch(function (thrown) {
                        store.commit('set_isSearcherInit', true);
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                        }
                    });
                }
            }
        },

        //WDP statistic------------------------------------------
        GetWDPShortStatistic({ commit }, properties) {
            store.commit('set_isSearcherInit', false);
            axios.post(properties.ajax, {
                prop: properties
            })
                .then(response => {                   
                    var notifyData = [],
                        labelsShort = [],labelsFull = [],
                        datasetsDataShort = [], datasetsFull = [],
                        project = store.getters.getProjectById(JSON.parse(response.config.data).prop.projectId),
                        fields = project.statistic.data[0].fields,
                        Rez = response.data[0].LastWeekStat.Rez; //статистика за неділю

                    for (var j = 0; j < fields.length; j++) {
                        if (response.data[0][fields[j].name] >= 0)
                            notifyData.push({ label: fields[j].desc, data: response.data[0][fields[j].name] });
                        else
                            notifyData.push({ label: fields[j].desc, data: 0 });

                        if (fields[j].inStatWin) {
                            labelsShort.push(fields[j].desc);
                            datasetsDataShort.push(response.data[0][fields[j].name]);
                        }
                    }

                    for (var i = 0; i < Rez.length; i++) {
                        labelsFull.push(Rez[i].Name);
                        datasetsFull.push(+(Rez[i].Percent.replace(',','.')));
                    }
                    store.commit('set_responseShortStatistic', { projectId: project.id, notifyData: notifyData, data: [{ labels: labelsShort, datasetsData: datasetsDataShort, statId: 0 }] });
                    store.dispatch('showNotify', JSON.stringify(project));
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });
        },
        GetWDPDatesStatistic({ commit }, properties) {
            store.commit('set_isSearcherInit', false);
            var prop = JSON.stringify({
                projectId: properties.projectId,
                datefrom: properties.datefrom,
                dateto: properties.dateto,
                statId:properties.statId
            });
            axios.post(properties.ajax + '?datefrom=' + properties.datefrom + '&dateto=' + properties.dateto, {
                prop: prop,
                cancelToken: new CT(function executor(c) {
                    cancelFullStats = c;
                    //console.log('request is cancelled');
                })
            })
                .then(response => {
                    if (response.data && response.data.length > 0) {
                        var prop = JSON.parse(JSON.parse(response.config.data).prop);
                        var labelsFull = [],
                            datasetsFull = [];
                        for (var i = 0; i < response.data.length; i++) {
                            labelsFull.push(response.data[i].Name);
                            datasetsFull.push(+(response.data[i].Percent.replace(',', '.')));
                        }
                        store.commit('set_responseShortStatistic', { projectId: prop.projectId, data: [{ labels: labelsFull, datasetsData: datasetsFull, statId: prop.statId }] });

                        setTimeout(function () { store.commit('set_isSearcherInit', true); }.bind(this), 1000);
                    }
                    //store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    //store.commit('set_isSearcherInit', true);
                    setTimeout(function () { store.commit('set_isSearcherInit', true); }.bind(this), 1000);

                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });
        },
        //DUG statistic ---------------------------
        GetDugShortStatistic({ commit }, properties) {
            store.commit('set_isSearcherInit', false);
            axios.post(properties.ajax, {
                prop: properties
            })
                .then(response => {
                    var notifyData = [],
                        labelsShort = [], labelsFull = [],
                        datasetsDataShort = [], datasetsFull = [],
                        projectId = JSON.parse(response.config.data).prop.projectId;
                        //fields = project.statistic.short.fields;

                    for (var j = 0; j < response.data.Districts.length; j++) {
                        notifyData.push({ label: response.data.Districts[j].Name, data: response.data.Districts[j].Count });
                        labelsShort.push(response.data.Districts[j].Name);
                        datasetsDataShort.push(response.data.Districts[j].Count);
                    }


                    for (var i = 0; i < response.data.DugTypes.length; i++) {
                        labelsFull.push(response.data.DugTypes[i].Name);
                        datasetsFull.push(+(response.data.DugTypes[i].Percent.replace(',', '.')));
                    }

                    store.commit('set_responseShortStatistic', { projectId: projectId, notifyData: notifyData, data : [{ labels: labelsShort, datasetsData: datasetsDataShort, statId:0 }, {labels: labelsFull, datasetsData: datasetsFull, statId:1}] });

                    store.dispatch('showNotify', { id: projectId, statistic: store.getters.getProjectById(projectId).statistic });


                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });
        },
        GetDugMixedStatistic({ commit }, properties) {
            store.commit('set_isSearcherInit', false);
            axios.post(properties.ajax, {
                prop: properties
            })
                .then(response => {
                    if (response.data) {
                        var res = [],
                            prop = JSON.parse(response.config.data).prop;
                        if (response.data.DugTypes && response.data.DugTypes.length > 0) {
                            var labels = [],
                                datasetsBarData = [],
                                datasetsLineData = [];
                            for (var j = 0; j < response.data.DugTypes.length; j++) {
                                labels.push(response.data.DugTypes[j].Name + " " + response.data.DugTypes[j].Percent.replace(',', '.') + '%');
                                datasetsBarData.push(response.data.DugTypes[j].AvrSum);
                                datasetsLineData.push(response.data.DugTypes[j].Count);
                            }
                            res.push({ labels: labels, datasetsBarData: datasetsBarData, datasetsLineData: datasetsLineData });
                        }
                      
                            store.commit('set_responseMixedStatistic', { projectId: prop.projectId, data: res, statId: prop.statId });
                        
                    }
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    if (axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                    }
                });
        },
        GetDugYearsMixedStatistic({ commit }, properties) {
            store.commit('set_isSearcherInit', false);
            axios.post(properties.ajax, {
                prop: properties
            })
            .then(response => {
                if (response.data) {
                    var types = new Set(), //список типов комуникаций
                        res = [], //массив коммуникаций по годам {datasetsBarData, datasetsLineData}
                        labels = [],
                        prop = JSON.parse(response.config.data).prop
                        ;
                    response.data.Years.forEach(function (item) {
                        //заполняем лейблы
                        labels.push(item.Year);
                        item.DugTypes.forEach(function (itemm) {
                            //проверка res на наличие объекта по соотв соммуникации
                            var isTypeThere = false;
                            res.forEach(function (feat) {
                                if (feat.typeId === itemm.Id)
                                    isTypeThere = true;
                            }.bind(this));

                            if (isTypeThere) {
                                res.forEach(function (feat) {
                                    if (feat.typeId === itemm.Id) {
                                        feat.datasetsBarData.push(itemm.AvrSum);
                                        feat.datasetsLineData.push(itemm.Count);
                                    }                                            
                                }.bind(this));
                            }
                            else {
                                types.add({ id: itemm.Id, name: itemm.Name });
                                res.push({ typeId: itemm.Id, datasetsBarData: [itemm.AvrSum], datasetsLineData: [itemm.Count] });
                            }

                        }.bind(this));
                    }.bind(this));
                    store.commit('set_responseTypesMixedStatistic', { projectId: prop.projectId, data: { types: Array.from(types), res: res, labels: labels }, statId: prop.statId });
                }
                store.commit('set_isSearcherInit', true);
            })
            .catch(function (thrown) {
                store.commit('set_isSearcherInit', true);
                if (axios.isCancel(thrown)) {
                    console.log('Request canceled', thrown.message);
                } else {
                }
            });
        },

        GetHeatingStat({ commit }, properties) {
            store.commit('set_isSearcherInit', false);
            axios.get(properties.ajax, {
                prop: properties
            })
                .then(response => {
                    if (response.data)
                        this.commit("set_HeatingStatistic", response);
                store.commit('set_isSearcherInit', true);
            })
            .catch(function (thrown) {
                store.commit('set_isSearcherInit', true);
                if (axios.isCancel(thrown)) {
                    console.log('Request canceled', thrown.message);
                } else {
                }
            });
        },
        //статистика==========================================================

        showNotify({ commit }, properties) {
            var prop = (typeof(properties) == 'string') ? JSON.parse(properties) : properties;
            if (prop.statistic) {
                prop.statistic.data.forEach(function (item) {
                    //console.log('id = '+ item.id + '; isSowed = ' + item.isSowed);
                    if (item.class == "short" && !item.isShowed && store.getters.getIsProjectLayerAddedToTOC(prop.id)) {
                        setTimeout(function () {
                            var content = store.getters.getShortStatContent(item);
                            //показываем министатистику
                            eventVue.showNotify(content.title, content.content, null, 'glyphicon glyphicon-stats');
                            //меняем isSowed на true
                            store.commit('set_isShowedTrue', { projectId:prop.id, statId:item.id });
                        }.bind(this), 600);
                    }
                }.bind(this));
            }
            //if (prop.statistic && !prop.statistic.short.isShowed && store.getters.getIsProjectLayerAddedToTOC(prop.id)) {
            //    setTimeout(function () {
            //        var content = store.getters.getShortStatContent(prop.id);
            //        //показываем министатистику
            //        eventVue.showNotify(content.title, content.content, null, 'glyphicon glyphicon-stats');
            //        //меняем isSowed на true
            //        store.commit('set_isShowedTrue', prop.id);
            //    }.bind(this), 500);
            //}
        },
        //-------------------------------------------------------

        GetHouseByAddressId({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            store.commit('set_isSearcherInit', false);
            axios.get(this.getters.getNDL.host + prop.url+ prop.address_id, {
                prop: prop
            })
                .then(response => {
                    eventVue.$emit('setHouseToView', response );
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    eventVue.$emit('showSimpleMessage', thrown.message);
                    store.commit('set_isSearcherInit', true);
                });

        },

        HouseByOSBB({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            store.commit('set_isSearcherInit', false);
            axios.get(this.getters.getNDL.host + prop.url + prop.osbb_nom, {
                prop: prop
            })
                .then(response => {
                    eventVue.$emit('setHouseToView', response );
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                   // eventVue.$emit('showSimpleMessage', thrown.message);
                    store.commit('set_isSearcherInit', true);
                });

        },
        //OTHERS-------------------------------------------------
        showNeedVerificationMessage({ commit }, userDdata) {
            swal({
                title: store.state.messagesStore.messagesTexts.enterISNotCompleted,
                html: (userDdata.Phone) ? store.state.messagesStore.messagesTexts.phoneNotConfirmed : store.state.messagesStore.messagesTexts.emailNotConfirmed,
                type: "warning",
                showCancelButton: true,
                cancelButtonText: store.state.messagesStore.messagesTexts.cancelButtonText,
                confirmButtonColor: store.state.messagesStore.confirmButtonColor,
                cancelButtonColor: store.state.messagesStore.cancelButtonColor,
                confirmButtonText: store.state.messagesStore.messagesTexts.confirmButtonText,
                closeOnConfirm: false
            }).then(function (result) {
                    if (!result.dismiss) {
                        if (userDdata.Phone) {
                            swal.close();
                            eventVue.$emit('openSmsForm', { phone: userDdata.Phone, isForgot: false });
                            this.dispatch('SendCodeToPhone');
                        }
                        else {
                            swal.close();
                            this.dispatch('SendConfirmEmail');
                        }
                    }
                }.bind(this)).catch(swal.noop);
        },
        showNeedAuthorizeMessage({ commit }, userDdata) {
            swal({
                //title: store.state.messagesStore.messagesTexts.attention,
                html: store.state.messagesStore.messagesTexts.UserNotFound,
                //type: "warning",
                showCancelButton: false,
                //cancelButtonText: '',
                confirmButtonColor: store.state.messagesStore.confirmButtonColor,
                //cancelButtonColor: store.state.messagesStore.cancelButtonColor,
                confirmButtonText: store.state.messagesStore.messagesTexts.confirmButtonText,
                closeOnConfirm: false
            }).then(function (result) {
                eventVue.$emit('loginLinkOnClick');
            }.bind(this)).catch(swal.noop);
        },
        //-----------------------
        checkUpdateHeating({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Опалення початок оновлення: ' + new Date());
            if (cancelPromices['checkUpdateHeating']) {
                cancelPromices['checkUpdateHeating']();
                cancelPromices['checkUpdateHeating'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['checkUpdateHeating'] = c;
                }),
            })
                .then(response => {
                    if (response.data == "OK") {
                       // eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Опалення оновлено: ' + new Date());
                    }
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                   // eventVue.$emit('showSimpleMessage', thrown.message);
                    store.commit('set_isSearcherInit', true);
                });
        },

        UpdateHydrantsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            console.log('Гідранти початок оновлення: ' + new Date());
            if (cancelPromices['UpdateHydrantsFromGoogleSheet']) {
                cancelPromices['UpdateHydrantsFromGoogleSheet']();
                cancelPromices['UpdateHydrantsFromGoogleSheet'] = null;
            }
            //store.commit('set_isSearcherInit', false);
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateHydrantsFromGoogleSheet'] = c;
                }),
            })
                .then(response => {
                    if (response.data == "OK") {
                        console.log('Гідранти оновлено: ' + new Date());
                        //eventVue.$emit('buildLayer', response.config.prop);
                    }
                    //store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                   // eventVue.$emit('showSimpleMessage', thrown.message);
                    //store.commit('set_isSearcherInit', true);
                });

        },

        UpdateHeatingPointsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            console.log('Пункти обігріву початок оновлення: ' + new Date());
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            if (cancelPromices['UpdateHeatingPointsFromGoogleSheet']) {
                cancelPromices['UpdateHeatingPointsFromGoogleSheet']();
                cancelPromices['UpdateHeatingPointsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateHeatingPointsFromGoogleSheet'] = c;
                }),
            })
                .then(response => {
                    if (response.data == "OK") {
                        console.log('Пункти обігріву оновлено: ' + new Date());
                        //eventVue.$emit('buildLayer', response.config.prop);                        
                    }
                    //store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                   // eventVue.$emit('showSimpleMessage', thrown.message);
                    //store.commit('set_isSearcherInit', true);
                });

        },

        UpdateStopsSheltersFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            console.log('Зупинки-укриття початок оновленя: ' + new Date());
            //store.commit('set_isSearcherInit', false);
            if (cancelPromices['UpdateStopsSheltersFromGoogleSheet']) {
                cancelPromices['UpdateStopsSheltersFromGoogleSheet']();
                cancelPromices['UpdateStopsSheltersFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateStopsSheltersFromGoogleSheet'] = c;
                }),
            })
                .then(response => {
                    if (response.data == "OK") {
                        console.log('Зупинки-укриття оновлено: ' + new Date());
                        //eventVue.$emit('buildLayer', response.config.prop);
                    }
                    //store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                   // eventVue.$emit('showSimpleMessage', thrown.message);
                    //store.commit('set_isSearcherInit', true);
                });

        },

        UpdateFoodOutletsromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            console.log('Пункти харчування початок оновленя: ' + new Date());
            //store.commit('set_isSearcherInit', false);
            if (cancelPromices['UpdateFoodOutletsromGoogleSheet']) {
                cancelPromices['UpdateFoodOutletsromGoogleSheet']();
                cancelPromices['UpdateFoodOutletsromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateFoodOutletsromGoogleSheet'] = c;
                }),
            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Пункти харчування оновлено: ' + new Date());
                    }
                    //store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                   // eventVue.$emit('showSimpleMessage', thrown.message);
                    //store.commit('set_isSearcherInit', true);
                });

        },

        UpdateHospitalsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Лікарні початок оновлення: ' + new Date());
            if (cancelPromices['UpdateHospitalsFromGoogleSheet']) {
                cancelPromices['UpdateHospitalsFromGoogleSheet']();
                cancelPromices['UpdateHospitalsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateHospitalsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK_FIRE") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Лікарні оновлені: ' + new Date())
                    }
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Лікарні - оновлення відсутні ')
                    }
                   // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                   // eventVue.$emit('showSimpleMessage', thrown.message);
                   // store.commit('set_isSearcherInit', true);
                });
        },
        UpdatePolyclinicsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Поліклініки початок оновлення: ' + new Date());
            if (cancelPromices['UpdatePolyclinicsFromGoogleSheet']) {
                cancelPromices['UpdatePolyclinicsFromGoogleSheet']();
                cancelPromices['UpdatePolyclinicsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdatePolyclinicsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Поліклініки оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdatePharmaciesFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Аптеки початок оновлення: ' + new Date());
            if (cancelPromices['UpdatePharmaciesFromGoogleSheet']) {
                cancelPromices['UpdatePharmaciesFromGoogleSheet']();
                cancelPromices['UpdatePharmaciesFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdatePharmaciesFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Аптеки оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateGasStationsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('АЗС початок оновлення: ' + new Date());
            if (cancelPromices['UpdateGasStationsFromGoogleSheet']) {
                cancelPromices['UpdateGasStationsFromGoogleSheet']();
                cancelPromices['UpdateGasStationsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateGasStationsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('АЗС оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateVetClinicsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Вет клиники початок оновлення: ' + new Date());
            if (cancelPromices['UpdateVetClinicsFromGoogleSheet']) {
                cancelPromices['UpdateVetClinicsFromGoogleSheet']();
                cancelPromices['UpdateVetClinicsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateVetClinicsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Вет клиники  оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdatePetShopsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('АЗС початок оновлення: ' + new Date());
            if (cancelPromices['UpdatePetShopsFromGoogleSheet']) {
                cancelPromices['UpdatePetShopsFromGoogleSheet']();
                cancelPromices['UpdatePetShopsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdatePetShopsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('АЗС оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateNonFoodShopsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Непроловольчі магазини початок оновлення: ' + new Date());
            if (cancelPromices['UpdateNonFoodShopsFromGoogleSheet']) {
                cancelPromices['UpdateNonFoodShopsFromGoogleSheet']();
                cancelPromices['UpdateNonFoodShopsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateNonFoodShopsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Непроловольчі магазини оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateLsMarketsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Ринки початок оновлення: ' + new Date());
            if (cancelPromices['UpdateLsMarketsFromGoogleSheet']) {
                cancelPromices['UpdateLsMarketsFromGoogleSheet']();
                cancelPromices['UpdateLsMarketsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateLsMarketsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Ринки оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateFoodShopsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Продовольчі магазини оновлення: ' + new Date());
            if (cancelPromices['UpdateFoodShopsFromGoogleSheet']) {
                cancelPromices['UpdateFoodShopsFromGoogleSheet']();
                cancelPromices['UpdateFoodShopsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateFoodShopsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Продовольчі магазини оновлені: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdatePoliceFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Поліція початок оновлення: ' + new Date());
            if (cancelPromices['UpdatePoliceFromGoogleSheet']) {
                cancelPromices['UpdatePoliceFromGoogleSheet']();
                cancelPromices['UpdatePoliceFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdatePoliceFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Поліція оновлено: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateSheltersFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Укриття початок оновлення: ' + new Date());
            if (cancelPromices['UpdateSheltersFromGoogleSheet']) {
                cancelPromices['UpdateSheltersFromGoogleSheet']();
                cancelPromices['UpdateSheltersFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateSheltersFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Укриття оновлено: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateWaterSourcesFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Джерела води початок оновлення: ' + new Date());
            if (cancelPromices['UpdateWaterSourcesFromGoogleSheet']) {
                cancelPromices['UpdateWaterSourcesFromGoogleSheet']();
                cancelPromices['UpdateWaterSourcesFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateWaterSourcesFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Джерела води оновлено: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },
        UpdateInvicibilityFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Пункти незламності початок оновлення: ' + new Date());
            if (cancelPromices['UpdateInvicibilityFromGoogleSheet']) {
                cancelPromices['UpdateInvicibilityFromGoogleSheet']();
                cancelPromices['UpdateInvicibilityFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateInvicibilityFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Пункти незламності оновлено: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },

        UpdateBombSheltersFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);
            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            console.log('Укриття початок оновленя: ' + new Date());
            //store.commit('set_isSearcherInit', false);
            if (cancelPromices['UpdateBombSheltersFromGoogleSheet']) {
                cancelPromices['UpdateBombSheltersFromGoogleSheet']();
                cancelPromices['UpdateBombSheltersFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateBombSheltersFromGoogleSheet'] = c;
                }),
            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Укриття оновлено: ' + new Date());
                    }
                    //store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    //store.commit('set_isSearcherInit', true);
                });

        },
        UpdateWaterDrinkPointsFromGoogleSheet({ commit }, properties) {
            //var prop = JSON.parse(properties);

            var prop = properties;
            if (prop.properties)
                eventVue.$emit('buildLayer', prop.properties);
            //store.commit('set_isSearcherInit', false);
            console.log('Джерела води початок оновлення: ' + new Date());
            if (cancelPromices['UpdateWaterDrinkPointsFromGoogleSheet']) {
                cancelPromices['UpdateWaterDrinkPointsFromGoogleSheet']();
                cancelPromices['UpdateWaterDrinkPointsFromGoogleSheet'] = null;
            }
            axios.get(prop.url, {
                prop: prop.properties,
                cancelToken: new CT(function executor(c) {
                    cancelPromices['UpdateWaterDrinkPointsFromGoogleSheet'] = c;
                }),

            })
                .then(response => {
                    if (response.data == "OK") {
                        //eventVue.$emit('buildLayer', response.config.prop);
                        console.log('Точки питної води оновлено: ' + new Date())
                    }
                    // store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    // store.commit('set_isSearcherInit', true);
                });

        },

        GetDSNSConfig({ commit, state }, prop) {
           // var prop = JSON.parse(properties);
            //store.commit('set_isSearcherInit', false);
            const test_data = [
                {
                    name: 'Тестовий шар',
                    identityFields: [
                        { name: 'f1', description: 'Адреса' },
                        { name: 'f2', description: 'Балансер' },
                        { name: 'f4', description: 'Робочий час' }
                    ],
                    photo: 'f3'
                },
                {
                    name: 'Тестовий шар2',
                    identityFields: [
                        { name: 'f1', description: 'Адреса' },
                        { name: 'f2', description: 'Балансер' },
                        { name: 'f4', description: 'Робочий час' }
                    ],
                    photo: 'f3'
                },
            ];

            //this.commit("set_DSNSConfig", test_data);

            axios.get(prop.url, {
                prop: prop.properties,
            })
                .then(response => {
                    if (response.status === 200)
                        this.commit("set_DSNSConfig", response.data);
                    else {
                        console.log("!!! поля шарів проекту ДСНС неможливо ініціювати !!!")
                    }
                    store.commit('set_isSearcherInit', true);
                })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    store.commit('set_isSearcherInit', true);
                });

        },

        GetSheetData({ commit }, prop) {
            if (prop) {
               store.commit('set_isSearcherInit', false);
                axios.get(prop.url + prop.tableName, {
                    prop: prop,
                })
                    .then(response => {
                        if (Array.isArray(response.data) && response.data.length > 0)
                            this.commit("set_DSNSTableData", { data: response.data, tableName: response.config.prop.tableName });
                        else {
                            console.log("!!! або даних нема, або помилка !!!")
                            
                        }
                        store.commit('set_isSearcherInit', true);
                    })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    //store.commit('set_isSearcherInit', true);
                });
            }
 

        },
        getWGSCoordinates({ commit }, prop) {
            if (prop) {
                store.commit('set_isSearcherInit', false);
                let ddata = new FormData();
                ddata.append('longitudes', prop.coordinates.x);
                ddata.append('latitudes', prop.coordinates.y);

                axios.post(prop.ajax.url, ddata,{
                    prop: prop,
                })
                    .then(response => {
                        if (Array.isArray(response.data) && response.data.length > 0)
                            this.commit("set_coordinatesResult", { data: response.data[0], clickData: response.config.prop.e });
                        else {
                            console.log("!!! або даних нема, або помилка !!!")                            
                        }
                        store.commit('set_isSearcherInit', true);
                    })
                .catch(function (thrown) {
                    console.log(thrown.message);
                    // eventVue.$emit('showSimpleMessage', thrown.message);
                    //store.commit('set_isSearcherInit', true);
                });
            }
 

        },
    }
});

//модуль проброса евентов и общих методов
var eventVue = new Vue({   
    data: {
        timerCloseModal: null,
        closeModalElement: null
    },
    methods: {
        centerModal: function (element) {
            if (element.$el) {
                //var el = document.getElementsByClassName('modal fade in');
                var el = [element.$el];
                for (var i = 0; i < el.length; i++) {
                    //if (el[i].classList.contains('in')) {
                    console.log(el[i])
                    
                    el[i].style.display = 'block';
                    var dialog = el[i].getElementsByClassName("modal-content");

                    //console.log('wH = ' + window.outerHeight + '; mdH = ' + dialog[0].offsetHeight);
                    //console.log('================================================================');

                    if (window.innerHeight > dialog[0].offsetHeight)
                        offset = (window.innerHeight - dialog[0].offsetHeight) / 2 + 'px';
                    else
                        offset = "10"+ 'px';
                    if (window.innerWidth > dialog[0].offsetWidth)
                        offset2 = (window.innerWidth - dialog[0].offsetWidth) / 2 + 'px';
                    else
                        offset2 = "0";
                    //if (window.outerHeight > dialog[0].offsetHeight + 40)
                    //    offset = (window.outerHeight - dialog[0].offsetHeight - (window.outerHeight / 100) * 2) / 2 - 20 + 'px';
                    //else
                    //    offset = "0";
                    //if (window.innerWidth > dialog[0].offsetWidth + 40)
                    //    offset2 = (window.innerWidth - dialog[0].offsetWidth - (window.innerWidth / 100) * 2) / 2 + 15 + 'px';
                    //else
                    //    offset2 = "0";

                    dialog[0].style.marginTop = offset;
                    dialog[0].style.marginLeft = offset2;
                    //}
                }
            }
        },
        showSimpleMessage: function (text) {
            swal({
                confirmButtonColor: store.getters.getMessagesStore.confirmButtonColor,
                html: text
            }).catch(swal.noop);
        },
        showErrorMessage: function (errors) {
            if (errors && errors.length > 0) {
                var str = '<h3><b>Помилки</b></h3></br>';
                for (var i = 0; i < errors.length; i++) {
                    str += i == 0 ? ' - ' : '</br> - ';
                    str += '<span>' + errors[i] + '</span>';
                }
                this.showSimpleMessage(str);
            }
        },
        hideCollapseNavbar: function () {
            $('.collapse').collapse('hide');
        },
        startCloseModal: function (element) {
            this.closeModalElement = element;
            this.timerCloseModal = setTimeout(function () {
                var id = this.closeModalElement.$el.attributes.id.value;
                switch (id) {
                    case 'Login':
                        eventVue.$emit('closeLoginForm');
                        break;
                    case 'Register':
                        eventVue.$emit('closeRegisterForm');
                        break;
                    case 'forgotPassword':
                        eventVue.$emit('closeForgotPasswordForm');
                        break;
                    case 'smsCodeForm':
                        eventVue.$emit('hideSmsForm');
                        break;
                    case 'resetPasswordForm':
                        eventVue.$emit('closeResetPasswordForm');
                        break;
                    case 'feedbackForm':
                        eventVue.$emit('closefeedbackForm');
                        break;
                    case 'linksForm':
                        eventVue.$emit('closeLinks');
                        break;
                }
                this.undoCloseModal();
            }.bind(this), 300000);
        },
        undoCloseModal: function (element) {
            clearTimeout(this.timerCloseModal);
            this.timerCloseModal = null;
            this.closeModalElement = null;
        },
        scaleToOne: function () {
            var vp = 'width = device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover';
            document.querySelector('meta[name="viewport"]').setAttribute('content', vp);
        },
        initClearable: function () {
            setTimeout(function () {
    var input_class = 'zbz-input-clearable',
                    input_class_x = input_class + '__x',
                    input_class_x_over = input_class + '__x-over',
                    input_selector = '.' + input_class,
                    input_selector_x = '.' + input_class_x,
                    input_selector_x_over = '.' + input_class_x_over,
                    event_main = input_class + '-init',
                    event_names = [event_main, 'focus drop paste input change'].join(' '), //keydown keypress
                    btn_width = 13,
                    btn_height = 13,
                    btn_margin = 7;

                function tog(v) {
                    //console.log('TOG; acton = ' + (v ? 'addClass' : 'removeClass')+'; value = ' + v);
                    return v ? 'addClass' : 'removeClass';
                }

                $(document).on(event_names, input_selector, function (e) {
                    //console.log('EVENT = ' + e.handleObj.origType+'; class = ' + input_class_x + '; value = ' + this.value);
                    $(this)[tog(this.value)](input_class_x);
                    //console.log('======================================================================');
                });

                $(document).on('mousemove', input_selector_x, function (e) {
                    var input = $(this),
                        input_width = this.offsetWidth,
                        input_height = this.offsetHeight,
                        input_border_bottom = parseFloat(input.css('borderBottomWidth')),
                        input_border_right = parseFloat(input.css('borderRightWidth')),
                        input_border_left = parseFloat(input.css('borderLeftWidth')),
                        input_border_top = parseFloat(input.css('borderTopWidth')),
                        input_border_hr = input_border_left + input_border_right,
                        input_border_vr = input_border_top + input_border_bottom,
                        client_rect = this.getBoundingClientRect(),
                        input_cursor_pos_x = e.clientX - client_rect.left,
                        input_cursor_pos_y = e.clientY - client_rect.top,
                        is_over_cross = true;

                    is_over_cross = is_over_cross && (input_cursor_pos_x >= input_width - input_border_hr - btn_margin - btn_width);
                    is_over_cross = is_over_cross && (input_cursor_pos_x <= input_width - input_border_hr - btn_margin);
                    is_over_cross = is_over_cross && (input_cursor_pos_y >= (input_height - input_border_vr - btn_height) / 2);
                    is_over_cross = is_over_cross && (input_cursor_pos_y <= (input_height - input_border_vr - btn_height) / 2 + btn_height);

                    $(this)[tog(is_over_cross)](input_class_x_over);
                });

                $(document).on('click', input_selector_x_over, function (e) {
                    $(this).removeClass([input_class_x, input_class_x_over].join(' ')).val('').trigger('input');
                    //$(window).trigger('clickOnXclearable');
                    eventVue.$emit('clearAutocomplette');               
                    //switch (e.currentTarget.id) {
                    //    case 'searchPanelInput':
                    //        AP.clearSearchInput();
                    //        break;
                    //}
                });

                $(function () {
                    $(input_selector).trigger(event_main);
                });
            }.bind(this), 1000);
            
        },
        showNotify: function (title, content, duration, icon) {
            this.$notify({
                placement: 'bottom-right',
                title: title ? title : 'Добрий день!',
                content: content ? content : `Ми раді ВАС бачити на порталі геоданих!`,
                type: title ? "info" : "success",
                duration: duration ? duration : 10000,
                offsetX: 70,
                html: true,
                icon: icon ? icon : "glyphicon glyphicon-question-sign"
            });
        }
    }
});


//авторизатор--------------------------------------
//id="loginText",  id="passwordText"
const loginComponent = {
    template: `<modal v-model="showw" id="Login"
                        class="entrance-form" 
                        :class="{useStrictEntranceMode : getUser.loginView}"
                        title="Вхід" size="lg"
                        :backdrop="true"
                        :dismiss-btn="true"
                        @show="showModal" 
                        @hide="hiddenModal">
                <div class="row row-input">
            <div class= "input-group enter-input-group col-xs-12" >
                <input type="text" class="form-control enter-modal-input errorInput" 
                                    placeholder="Email або +380XXXXXXXXX" 
                                    id="lText" minlength="5"
                                    name="username"
                                    spellcheck="false" 
                                    autocomplete="username"
                                    @input="inputEvents" 
                                    @change="inputEvents"
                                    @copy="inputEvents" 
                                    @paste="inputEvents"
                                    v-model="email" >
           </div>
            <div class="input-group enter-input-group col-xs-12">

                <!--if type="text" ==>  class="noselect pw"-->
                <input type="password"
                                        class="form-control enter-modal-input errorInput noselect pw"
                                        placeholder="Пароль" 
                                        id="pText"
                                        name="password"
                                        spellcheck="false" 
                                        autocomplete="current-password"
                                        @input="inputEvents" 
                                        @change="inputEvents" 
                                        @copy="inputEvents" 
                                        @paste="inputEvents"
                                        @cut="inputEvents"
                                        v-model="password"/>

                </div>
                <div class="input-group enter-input-group password-lost col-xs-12 text-center">
                    <a href id="resetPasswordLink" @click="openForgotPassword">Забули пароль?</a>
                </div>
            </div>
            <button type="button" class="btn btn-primary col-xs-12 enter-modal-footer-right disabeled-btn"
                                    :disabled="disabledEnterBtn"
                                    id="loginButton" 
                                    @click="buttonClick">
                                         УВІЙТИ
                </button>
                <div slot="footer" class="login-footer">
                   <div v-if="getUser.loginView" class="row social-group">
                        <button id="googleButton" type="button" class= "btn col-xs-12 " @click="buttonClick">
                            <div><img src="/opendataportal/Content/img/btn_google_signin_light_pressed_web@2x.png"></div>
                                        </button>
                        <!--<button id="facebookButton" type="button" class="btn col-xs-12 " @click="buttonClick">
                            <div class="img-box"><img src="/opendataportal/Content/img/f_logo_RGB-White_58.png"></div>
                                <div class="social-name">Sign in with Facebook</div>
                                    </button>-->
                        </div>
                        <div class="registry-row row">
                            
                            <div class="col-xs-12 text-center">
                                Не маєте акаунту? <a href  @click="openRegister">Зареєструйтесь!</a>
                            </div>
                            
                        </div>
                        <div class="registry-row row">
                            <div class="col-xs-12 text-justify" style="font-size: 1.2rem">
                                Реєструючись, ви погоджуєтесь з правилами
                                <a href="../opendataportal/Home/Privacy" target="_blanc">політики конфіденційності</a>
                            </div>

                            
                        </div>
                  </div>
                </modal>`,
    computed: {
        getUser() {
            return store.getters.getUser;
        }
    },
    data: function () {
        return {
            showw: false,
            shown: false,
            disabledEnterBtn: true,
            email: '',
            password: '',
            currentFBToken: '',
            currentGOToken: '',
            opacity: 0,
        }
    },
    methods: {
        closeModal: function (e) {
            this.showw = false;
        },
        openModal: function (e) {
            this.showw = true;
        },
        showModal: function (e) {
            this.shown = true;
            this.validationElement(this.$el.querySelector('#lText'));
        },
        hiddenModal: function (e) {
            eventVue.$emit('undoStartCloseModal', this);
            this.shown = false;
            this._clearForm();
        },
        openRegister: function (e) {
            e.preventDefault();
            this.closeModal();
            eventVue.$emit('openRegister', this.email);
        },
        openForgotPassword: function (e) {
            e.preventDefault();
            this.closeModal();
            eventVue.$emit('openForgotPassword', this.email);
        },
        inputEvents: function (e) {
            this.validationElement(e.currentTarget);
        },
        buttonClick: function (e) {
            switch (e.currentTarget.id) {
                case 'loginButton': {
                    this.$store.dispatch('Login',
                        JSON.stringify({
                            ajax: this.$store.getters.getAjaxUrlByName('Login'),
                            //Email: this.$el.querySelector('#lText').value,
                            //Password: this.$el.querySelector('#pText').value
                            Email: this.email,
                            Password: this.password
                        }));
                }
                    break;
                case 'googleButton':
                    break;
                case 'facebookButton':
                    this._fbLogin();

                    break;
            }
        },
        validationElement: function (e) {
            switch (e.id) {
                case 'lText': {
                    if (this._checkEmail(e.value))
                        e.classList.remove('errorInput');
                    else if (this._checkPhone(e.value))
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
                case 'pText': {
                    if (e.value.length > 2)
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
            }
            this._enabilityButtonLoginForm();
        },
        _enabilityButtonLoginForm: function () {
            this.disabledEnterBtn = (this.$el.getElementsByClassName('errorInput').length > 0) ? true : false;
        },
        _checkEmail: function (data) {
            var re3 = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
            return re3.test(String(data).toLowerCase());
        },
        _checkPhone: function (data) {
            var re = /(\+380)[0-9]{9}/;
            if (data.length < 14)
                //return (data.match(re)) ? true : false;
                return re.test(String(data).toLowerCase()) ? true : false
            else
                return false;
        },
        _clearForm: function () {
            this.email = '',
                this.password = '';
            var inputs = this.$el.getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].value = '';
                this.validationElement(inputs[i]);
            }
            this._enabilityButtonLoginForm();
        },
        _handleFbData: function (response) {
            FB.api('/me', { fields: 'name,first_name,last_name,email' }, function (response) {
                if (response.error) {
                    // eventVue.$emit('showErrorMessage', ['from Facebook: ' + response.error.message]);
                }
                else {
                    var outhData = response;
                    outhData.token = this.currentFBToken;
                    this.$store.dispatch('socialAuth',
                        JSON.stringify({
                            ajax: this.$store.getters.getAjaxUrlByName('socialAuth'),
                            login_provider: 'facebook',
                            token: this.currentFBToken,
                            providerKey: response.id
                        }));
                    this.closeModal();
                }
            }.bind(this));
        },
        _fbLogin: function () {
            FB.getLoginStatus(function (response) {
                if (response.status == 'connected') {
                    this._setAuthTocken(response, 'facebook');
                    this._handleFbData(response);
                }
                else {
                    FB.login(function (response) {
                        if (response.authResponse)
                            this._setAuthTocken(response, 'facebook');
                        this._handleFbData(response);
                    }.bind(this), {
                            scope: 'email',
                            return_scopes: true
                        }, { perms: 'user_mobile_phone' });
                }
            }.bind(this));
        },
        _gplInit: function () {
            gapi.load('auth2', function () {
                // Retrieve the singleton for the GoogleAuth library and set up the client.
                auth2 = gapi.auth2.init({
                    client_id: '629421282209-k2ef7acise8mk0d6mbue8dcd7f5vj2vo.apps.googleusercontent.com',
                    cookiepolicy: 'single_host_origin',
                    // Request scopes in addition to 'profile' and 'email'
                    //scope: 'userinfo.profile'
                });
                this._gplAttachSignin(this.$el.querySelector('#googleButton'));
            }.bind(this));
        },
        _gplAttachSignin: function (element) {
            auth2.attachClickHandler(element, {},
                function (googleUser) {
                    this._setAuthTocken(googleUser, 'google');
                    var outhData = googleUser.getBasicProfile();
                    outhData.token = this.currentGOToken;
                    this.$store.dispatch('socialAuth',
                        JSON.stringify({
                            ajax: this.$store.getters.getAjaxUrlByName('socialAuth'),
                            login_provider: 'google',
                            token: this.currentGOToken,
                            providerKey: outhData.getId(),
                            email: outhData.getEmail()
                        }));
                    this.closeModal();
                    //$(document).trigger('app_enteredToGoogle', { data: outhData });

                }.bind(this), function (error) {
                    if (error.error === "popup_closed_by_user") {
                        //  $(document).trigger('app_errorSocialEnter');                       
                        //this.closeModal();
                    }
                }.bind(this));
        },
        _setAuthTocken: function (data, type) {
            if (type == 'facebook')
                this.currentFBToken = data.authResponse.accessToken;
            else
                this.currentGOToken = data.getAuthResponse().id_token;
        }
    },
    mounted: function () {
        //если loginView = true то делаем modal-backdrop прозрачным
        if (this.getUser.loginView) {
            setTimeout(function () {
                $('.modal-backdrop').hasClass('backdrope-transparent') ? true : $('.modal-backdrop').addClass('backdrope-transparent')
            }, 50)
        }
    },
    beforeUpdate: function (e) {
        if (this.showw && !this.shown) {
            this.opacity = 0;
            eventVue.$emit('centerModal', this);
                setTimeout(function () {
                    this.opacity = 1;
                eventVue.$emit('startCloseModal', this);
            }.bind(this), 700);
        }
    }
}

const registerComponent = {
    template: '<modal v-model="showw" id="Register" class="entrance-form" :style="{ opacity: opacity}" title="Реєстрація" size="lg" @show="showModal" @hide="hiddenModal" :dismiss-btn="true" :backdrop="getUser.loginView">\
                <div class="row row-input">\
                    <div class= "input-group enter-input-group col-xs-12" >\
                        <input type="text" class="form-control enter-modal-input errorInput" placeholder="Email або +380XXXXXXXXX" id="regLoginText" minlength="5" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="email">\
                    </div>\
                    <!-- <div class="input-group enter-input-group col-xs-12">\
                        <input type="text" class="form-control enter-modal-input errorInput" placeholder="Ваше ім\'я" id="regFIOText" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents">\
                    </div> -->\
                    <div class="input-group enter-input-group col-xs-12">\
                        <input type="password" class="form-control enter-modal-input errorInput" placeholder="Пароль" id="regPasswordText" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="password">\
                    </div>\
                    <div class="input-group enter-input-group col-xs-12">\
                        <input type="password" class="form-control enter-modal-input errorInput" placeholder="Підтвердження паролю" id="confirmRegPasswordText" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="confirmPassword">\
                    </div>\
                </div>\
                <div slot="footer" class="registry-footer">\
                    <button type="button" class="btn btn-primary col-xs-12 col-sm-6 enter-modal-footer-right disabeled-btn" id="RegisterButton" :disabled="disabledEnterBtn" @click="buttonClick">ЗАРЕЄСТРУВАТИСЯ</button>\
                    <button type="button" class="btn btn-primary col-xs-12 col-sm-6 enter-modal-footer-left disabeled-btn" id="back-register-button" @click="buttonClick">ПОВЕРНУТИСЯ</button>\
                  </div>\
                </modal>',
    computed: {
        getUser() {
            return store.getters.getUser;
        }
    },
    data: function () {
        return {
            showw: false,
            shown: false,
            disabledEnterBtn: true,
            email: '',
            password: '',
            confirmPassword: '',
            opacity: 0,
        }
    },
    methods: {
        closeModal: function (e) {
            this.showw = false;
        },
        openModal: function (e) {
            this.showw = true;
        },
        showModal: function (e) {
            this.shown = true;
            this.validationElement(this.$el.querySelector('#regLoginText'));
        },
        hiddenModal: function (e) {
            eventVue.$emit('undoStartCloseModal', this);
            this.shown = false;
            this._clearForm();
        },
        inputEvents: function (e) {
            this.validationElement(e.currentTarget);
        },
        buttonClick: function (e) {
            switch (e.currentTarget.id) {
                case 'RegisterButton': {
                    if (this.password == this.confirmPassword) {
                        this.$store.dispatch('Register',
                            JSON.stringify({
                                ajax: this.$store.getters.getAjaxUrlByName('Register'),
                                //Email: this.$el.querySelector('#regLoginText').value,
                                //Password: this.$el.querySelector('#regPasswordText').value,
                                //ConfirmPassword: this.$el.querySelector('#confirmRegPasswordText').value
                                Email: this.email,
                                Password: this.password,
                                ConfirmPassword: this.confirmPassword,
                                isPhone: this._checkPhone(this.email)
                            }));
                    }
                    else {
                        eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.passwordsDoNotCoinsides);
                        this.password = '';
                        this.confirmPassword = '';
                        this.$el.querySelector('#regPasswordText').classList.add('errorInput');
                        this.$el.querySelector('#regPasswordText').focus();
                        this.$el.querySelector('#confirmRegPasswordText').classList.add('errorInput');
                    }
                }
                    break;
                case 'back-register-button': {
                    this.closeModal();
                    eventVue.$emit('bakToLoginForm', this.email);
                }
                    break;
            }

        },
        validationElement: function (e) {
            switch (e.id) {
                case 'regLoginText': {
                    if (this._checkEmail(e.value))
                        e.classList.remove('errorInput');
                    else if (this._checkPhone(e.value))
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
                case 'regFIOText':
                case 'regPasswordText':
                case 'confirmRegPasswordText': {
                    if (e.value.length > 2)
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
            }
            this._enabilityButtonLoginForm();
        },
        _enabilityButtonLoginForm: function () {
            this.disabledEnterBtn = (this.$el.getElementsByClassName('errorInput').length > 0) ? true : false;
        },
        _checkEmail: function (data) {
            var re3 = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
            return re3.test(String(data).toLowerCase());
        },
        _checkPhone: function (data) {
            var re = /(\+380)[0-9]{9}/;
            if (data.length < 14)
                //return (data.match(re)) ? true : false;
                return re.test(String(data).toLowerCase()) ? true : false
            else
                return false;
        },
        _clearForm: function () {
            this.email = '',
                this.password = '',
                this.confirmPassword = '';
            var inputs = this.$el.getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].value = '';
                this.validationElement(inputs[i]);
            }
            this._enabilityButtonLoginForm();
        }
    },
    beforeUpdate: function () {
        if (this.showw && !this.shown) {
            this.opacity = 0;
            eventVue.$emit('centerModal', this);
            setTimeout(function () {
                this.opacity = 1;
                eventVue.$emit('startCloseModal', this);
            }.bind(this), 700);
        }

        //если loginView = true то делаем modal-backdrop прозрачным
        if (this.getUser.loginView) {
            setTimeout(function () {
                $('.modal-backdrop').hasClass('backdrope-transparent') ? true : $('.modal-backdrop').addClass('backdrope-transparent')
            }, 50)
        }
    }
}

const forgotPasswordComponent = {
    template: '<modal v-model="showw" id="forgotPassword" :style="{ opacity: opacity}" class="entrance-form" title="Відновлення паролю" size="lg" @show="showModal" @hide="hiddenModal"   :backdrop="getUser.loginView">\
                <div class="row row-input">\
                    <div class= "input-group enter-input-group col-xs-12" >\
                        <input type="text" class="form-control enter-modal-input errorInput" placeholder="Email або +380XXXXXXXXX" id="forgotLoginText" minlength="5" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="email">\
                    </div>\
                </div>\
            <div slot="footer" class="registry-footer">\
                <button type = "button" class="btn btn-primary col-xs-12 col-sm-6 enter-modal-footer-right disabeled-btn" id ="forgotButton" :disabled="disabledEnterBtn"  @click="buttonClick" > ВІДНОВИТИ</button >\
                <button type="button" class="btn btn-primary col-xs-12 col-sm-6 enter-modal-footer-left disabeled-btn" id="back-forgot-button" @click="buttonClick">ПОВЕРНУТИСЯ</button>\
                  </div>\
                </modal>',
    computed: {
        getUser() {
            return store.getters.getUser;
        }
    },
    data: function () {
        return {
            showw: false,
            shown: false,
            disabledEnterBtn: true,
            email: '',
            opacity: 0,
        }
    },
    methods: {
        closeModal: function (e) {
            this.showw = false;
        },
        openModal: function (e) {
            this.showw = true;
        },
        showModal: function (e) {
            this.shown = true;
            this.validationElement(this.$el.querySelector('#forgotLoginText'));
        },
        hiddenModal: function (e) {
            eventVue.$emit('undoStartCloseModal', this);
            this.shown = false;
            this._clearForm();
        },
        inputEvents: function (e) {
            this.validationElement(e.currentTarget);
        },
        buttonClick: function (e) {
            switch (e.currentTarget.id) {
                case 'forgotButton': {
                    this.$store.dispatch('ForgotPasswordAjax',
                        JSON.stringify({
                            ajax: this.$store.getters.getAjaxUrlByName('ForgotPassword'),
                            //Email: this.$el.querySelector('#forgotLoginText').value,
                            Email: this.email,
                            isPhone: this._checkPhone(this.email)
                        }));
                }
                    break;
                case 'back-forgot-button': {
                    this.closeModal();
                    eventVue.$emit('bakToLoginForm', this.email);
                }
                    break;
            }

        },
        validationElement: function (e) {
            switch (e.id) {
                case 'forgotLoginText': {
                    if (this._checkEmail(e.value))
                        e.classList.remove('errorInput');
                    else if (this._checkPhone(e.value))
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
            }
            this._enabilityButtonLoginForm();
        },
        _enabilityButtonLoginForm: function () {
            this.disabledEnterBtn = (this.$el.getElementsByClassName('errorInput').length > 0) ? true : false;
        },
        _checkEmail: function (data) {
            var re3 = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
            return re3.test(String(data).toLowerCase());
        },
        _checkPhone: function (data) {
            var re = /(\+380)[0-9]{9}/;
            if (data.length < 14)
                //return (data.match(re)) ? true : false;
                return re.test(String(data).toLowerCase()) ? true : false
            else
                return false;
        },
        _clearForm: function () {
            this.email = '';
            var inputs = this.$el.getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].value = '';
                this.validationElement(inputs[i]);
            }
            this._enabilityButtonLoginForm();
        }
    },
    beforeUpdate: function () {
        if (this.showw && !this.shown) {
            this.opacity = 0;
            eventVue.$emit('centerModal', this);
            setTimeout(function () {
                this.opacity = 1;
                eventVue.$emit('startCloseModal', this);
            }.bind(this), 700);
        }

        //если loginView = true то делаем modal-backdrop прозрачным
        if (this.getUser.loginView) {
            setTimeout(function () {
                $('.modal-backdrop').hasClass('backdrope-transparent') ? true : $('.modal-backdrop').addClass('backdrope-transparent')
            }, 50)
        }
    }
}

const smsComponent = {
    template: '<modal v-model="showw" id="smsCodeForm" class="entrance-form" :style="{ opacity: opacity}" title="Підтвердження" size="lg" @show="showModal" @hide="hiddenModal" :data-phone="phone" :dismiss-btn="true" :backdrop="getUser.loginView">\
                <div class="row row-input">\
                    <div class= "input-group enter-input-group col-xs-12" >\
                        <input type="text" class="form-control enter-modal-input errorInput" :placeholder="placeHolder" id="smsText" minlength="5" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="code">\
                    </div>\
                </div>\
            <div slot="footer" class="registry-footer">\
                <button type = "button" class="btn btn-primary col-xs-6 enter-modal-footer-right disabeled-btn" id ="forgotSmsButton" :disabled="disabledEnterBtn"  @click="buttonClick" >ПІДТВЕРДИТИ</button >\
                  </div>\
                </modal>',
    computed: {
        getUser() {
            return store.getters.getUser;
        }
    },
    data: function () {
        return {
            showw: false,
            shown: false,
            disabledEnterBtn: true,
            code: '',
            phone: '',
            isForgot: false,
            placeHolder: 'Код підтвердження',
            opacity: 0,
        }
    },
    methods: {
        closeModal: function (e) {
            this.showw = false;
        },
        openModal: function (phone, isForgot) {
            this.isForgot = isForgot;
            this.phone = phone;
            this.showw = true;
        },
        showModal: function (e) {
            this.shown = true;
            this.validationElement(this.$el.querySelector('#smsText'));
        },
        hiddenModal: function (e) {
            eventVue.$emit('undoStartCloseModal', this);
            this.shown = false;
            this._clearForm();
        },
        inputEvents: function (e) {
            this.validationElement(e.currentTarget);
        },
        buttonClick: function (e) {
            switch (e.currentTarget.id) {
                case 'forgotSmsButton': {
                    if (this.isForgot) {
                        eventVue.$emit('openResetPasswordForm', {
                            phone: this.phone,
                            code: this.code
                        });
                        this.showw = false;
                    }
                    else
                        this.$store.dispatch('ConfirmPhoneAjax',
                            JSON.stringify({
                                ajax: this.$store.getters.getAjaxUrlByName('ConfirmPhoneAjax'),
                                code: this.code,
                                phone: this.phone
                            }));
                }
                    break;
            }

        },
        validationElement: function (e) {
            switch (e.id) {
                case 'smsText': {
                    if (!isNaN(e.value) && e.value != '' && e.value.length > 3)
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
            }
            this._enabilityButtonLoginForm();
        },
        _enabilityButtonLoginForm: function () {
            this.disabledEnterBtn = (this.$el.getElementsByClassName('errorInput').length > 0) ? true : false;
        },
        _clearForm: function () {
            this.code = '';
            var inputs = this.$el.getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].value = '';
                this.validationElement(inputs[i]);
            }
            this._enabilityButtonLoginForm();
        }
    },
    beforeUpdate: function () {
        if (this.showw && !this.shown) {
            this.opacity = 0;
            eventVue.$emit('centerModal', this);
            setTimeout(function () {
                this.opacity = 1;
                eventVue.$emit('startCloseModal', this);
            }.bind(this), 700);
        }

        //если loginView = true то делаем modal-backdrop прозрачным
        if (this.getUser.loginView) {
            setTimeout(function () {
                $('.modal-backdrop').hasClass('backdrope-transparent') ? true : $('.modal-backdrop').addClass('backdrope-transparent')
            }, 50)
        }
    }
}

const resetPasswordComponent = {
    template: '<modal v-model="showw" id="resetPasswordForm" class="entrance-form" :style="{ opacity: opacity}" title="Зміна пароля" size="lg" @show="showModal" @hide="hiddenModal" :data-code="code" :data-phone="phone" :dismiss-btn="true"  :backdrop="getUser.loginView">\
                <div class="row row-input">\
                    <div class= "input-group enter-input-group col-xs-12" >\
                        <input type="password" class="form-control enter-modal-input errorInput" :placeholder="placeHolder" id="newpasswordText" minlength="5" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="newpassword">\
                    </div>\
                    <div class= "input-group enter-input-group col-xs-12" >\
                        <input type="password" class="form-control enter-modal-input errorInput" :placeholder="placeHolder2" id="newpasswordTextConfirm" minlength="5" spellcheck="false" autocomplete="nope" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="newpasswordconfirm">\
                    </div>\
                </div>\
            <div slot="footer" class="registry-footer">\
                <button type = "button" class="btn btn-primary col-xs-6 enter-modal-footer-right disabeled-btn" id ="resetPasswordButton" :disabled="disabledEnterBtn"  @click="buttonClick" >ПІДТВЕРДИТИ</button >\
                  </div>\
                </modal>',
    computed: {
        getUser() {
            return store.getters.getUser;
        }
    },
    data: function () {
        return {
            showw: false,
            shown: false,
            disabledEnterBtn: true,
            newpassword: '',
            newpasswordconfirm: '',
            code: '',
            phone: '',
            placeHolder: 'Новий пароль',
            placeHolder2: 'Підтвердження нового пароля',
            opacity: 0,

        }
    },
    methods: {
        closeModal: function (e) {
            this.showw = false;
        },
        openModal: function (phone, code) {
            this.phone = phone ? phone : '';
            this.code = code ? code : '';
            this.showw = true;
        },
        showModal: function (e) {
            this.shown = true;
        },
        hiddenModal: function (e) {
            eventVue.$emit('undoStartCloseModal', this);
            this.shown = false;
            this._clearForm();
        },
        inputEvents: function (e) {
            this.validationElement(e.currentTarget);
        },
        buttonClick: function (e) {
            switch (e.currentTarget.id) {
                case 'resetPasswordButton': {
                    if (this.newpassword == this.newpasswordconfirm) {
                        this.$store.dispatch('ResetPasswordAjax',
                            JSON.stringify({
                                ajax: this.$store.getters.getAjaxUrlByName('ResetPasswordAjax'),
                                code: this.code,
                                newPassword: this.newpassword,
                                phone: this.phone
                            }));
                    }
                    else
                        eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.passwordsDoNotCoinsides);
                }
                    break;
            }

        },
        validationElement: function (e) {
            switch (e.id) {
                case 'newpasswordText':
                case 'newpasswordTextConfirm': {
                    if (e.value != '' && e.value.length > 2)
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
            }
            this._enabilityButtonLoginForm();
        },
        _enabilityButtonLoginForm: function () {
            this.disabledEnterBtn = (this.$el.getElementsByClassName('errorInput').length > 0) ? true : false;
        },
        _clearForm: function () {
            this.code = '';
            this.phone = '';
            this.newpassword = '';
            this.newpasswordconfirm = '';
            var inputs = this.$el.getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].value = '';
                this.validationElement(inputs[i]);
            }
            this._enabilityButtonLoginForm();
        }
    },
    beforeUpdate: function () {
        if (this.showw && !this.shown) {
            this.opacity = 0;
            eventVue.$emit('centerModal', this);
            setTimeout(function () {
                this.opacity = 1;
                eventVue.$emit('startCloseModal', this);
            }.bind(this), 700);
        }

        //если loginView = true то делаем modal-backdrop прозрачным
        if (this.getUser.loginView) {
            setTimeout(function () {
                $('.modal-backdrop').hasClass('backdrope-transparent') ? true : $('.modal-backdrop').addClass('backdrope-transparent')
            }, 50)
        }
    }
}
var projsComponent = {//{{ ress.name }}
    template: `<nav class="dropdown-nav-menu" 
                                            @mouseover.prevent="onProjectMouseOver" 
                                            @mouseout.prevent="onProjectMouseOut">
                        <div class= "nav-head-items"> Доступні проекти</div>
                        <a v-show="showLeftArrow" 
                                                @click.prevent="clickOnLeftArrow" 
                                                @mouseover.prevent="startShowLeftArrow" 
                                                class="dropdown-nav-menu-arrow dropdown-nav-menu-arrow-left">
                                <span aria-hidden="true" class="glyphicon glyphicon-menu-left"></span>
                        </a>
                        <a v-show="showRightArrow" 
                                                @click.prevent="clickOnRightArrow" 
                                                @mouseover.prevent="startShowRightArrow" 
                                                class="dropdown-nav-menu-arrow dropdown-nav-menu-arrow-right">
                                <span aria-hidden="true" class="glyphicon glyphicon-menu-right"></span>
                        </a>
                        <ul v-if="itemss.length > 0" class="nav navbar-nav navbar-left" ref="content">
                            <li v-for="ress in itemss" class="project-item">
                                <a v-on:click="onProject(ress.id)"
                                        v-html="ress.iconNav"
                                        :title="ress.title"></a>
                                                                   <!-- <div v-if="ress.layers.length > 0" class="dropdown-sub-menu">
                                                                        <ul>
                                                                            <li v-for="layer in ress.layers" 
                                                                                                            class="li-menu" 
                                                                                                            v-on:click(onLayer(layer.id))>
                                                                                {{ layer.name }}
                                                                            </li>
                                                                        </ul>
                                                                    </div> -->
                            </li >
                        </ul>
                        </nav>`,
    computed: {
        getAllProjectsFull() {
            return this.$store.getters.getAllProjectsFull;
        },
    },
    watch: {
        getAllProjectsFull(oldVal, newVal) {
            this.itemss = this.getAllProjectsFull;
        }
    },
    data: function () {
        return {
            itemss: this.$store.getters.getAllProjectsFull,
            showLeftArrow: false,
            showRightArrow: false,
            scrollDuration: 800,
            scrollPixels: 200,
            deltaClientX: 150,
            minClientX:350,
            max_Leftt : -7,
            min_Leftt : ((-1 * this.$store.getters.getAllProjectsFull.length * 200) / 2 )
        }
    },
    methods: {
        onProject: function (projectId) {
            this.$store.commit('set_project', projectId);
            setTimeout(function () { eventVue.$emit('selectProject'); }.bind(this), 200);
            
        },
        onLayer: function (layerId) {
            this.$store.commit('set_addLayer', layerId);
        },
        onProjectMouseOver: function () {
            var el = this.$el.querySelector('.dropdown-nav-menu');
            if (this.$el.scrollWidth - this.$el.offsetWidth > 50) {
                this.startShowRightArrow();
                //setTimeout(function () {
                //    console.log(el.querySelector('.dropdown-nav-menu-arrow-right').right);
                //}.bind(this), 100);
            }
        },
        onProjectMouseOut: function (e) {
            //console.log('el = ' + e.currentTarget + '; x = ' + e.clientX + '; y = ' + e.clientY + '; clientHeight = ' + this.$el.clientHeight + '; clientLeft+clientWidth = ' + (this.$el.clientLeft + this.$el.clientWidth));
            //if (e.clientY > this.$el.clientHeight || e.clientX > (this.$el.clientLeft + this.$el.clientWidth - this.deltaClientX) || e.clientX < this.minClientX) {
                if (e.clientY > this.$el.clientHeight || e.clientX < this.minClientX) {
                this.hideLeftArrow();
                this.hideRightArrow();
                this.$refs.content.style.left = this.max_Leftt + 'px';
            }

        },
        startShowLeftArrow: function () {
            this.showLeftArrow = true;
        },
        startShowRightArrow: function () {
            this.showRightArrow = true;
        },
        hideLeftArrow: function () {
            this.showLeftArrow = false;
        },
        hideRightArrow: function () {
            this.showRightArrow = false;
        },
        clickOnLeftArrow: function () {
            //console.log('clickOnLeftArrow');
            const content = this.$refs.content;
            this.scrollTo(content, this.scrollPixels);
        },
        clickOnRightArrow: function () {
            //console.log('clickOnRightArrow');
            const content = this.$refs.content;
            this.scrollTo(content, -1 * this.scrollPixels);
        },
        scrollTo(element, scrollPixels, duration) {
            var currentLeft = parseInt(element.style.left) || parseInt(element.offsetLeft);
            if (currentLeft) {
                var sumLeft = currentLeft + scrollPixels;
                element.style.left = sumLeft + 'px';
                //console.log(element.style.left);
                if (sumLeft == this.max_Leftt) {
                    this.startShowRightArrow();
                    this.hideLeftArrow()
                }
                else if (sumLeft < this.max_Leftt && sumLeft > this.min_Leftt) {
                    this.startShowLeftArrow();
                    this.startShowRightArrow();
                }
                else {
                    this.hideRightArrow();
                    this.startShowLeftArrow();
                }


            }
        },
        //itemss() {
        //    return this.$store.getters.getAllProjectsFull;
        //},
    }
};
var vueLayout = new Vue({
    el: '#layoutNav',
    template: '<projects-comp ref="projNav"></projects-comp>',
    store,
    components: {
        'projects-comp': projsComponent       
    },
    computed: {
        getUser() {
            var user = store.getters.getUser;
            return user;
        }
    },
    mounted: function () {
    },
    created: function () {
        //var dataKey = document.getElementsByTagName('body')[0].attributes["data-key"].value;
        //if (this.getUser.FullName == "Вхід" && !sessionStorage.getItem('odp_user') && this.getUser.loginView && (window.location.href.toLowerCase()).indexOf('house') < 0 && (window.location.href.toLowerCase()).indexOf('account') < 0) {
        //    if (dataKey != '')
        //        sessionStorage.odp_data_key = dataKey;
        //    window.location = '/opendataportal/Account/Login';
        //}
    },
});

var loginNav = new Vue({
    el: '#loginNav',
    template: '<ul class="nav navbar-nav navbar-right">\
                            <li v-show="getUser.Loginn == \'guest\'">\
                                <a id="loginLink" v-on:click="loginClick">\
                                    <span class="text-login">Увійти</span>\
                                    <a title="Увійти"><img src="/opendataportal/Content/img/enter.png" style="height: 24px"></a></a>\
                            </li>\
                            <li v-show="getUser.Loginn != \'guest\'">\
                                <a id="logoutLink" v-on:click="logoutClick">Вийти</a>\
                            </li>\
                            <li>\
                                <a id="userLogin" title="">{{getUser.FullName ? getUser.FullName : getUser.Loginn}}</a>\
                            </li>\
                        </ul>',
    store,
    computed: {
        getUser() {
            var user = store.getters.getUser;
            if (user.FullName == "Вхід" && sessionStorage.getItem('odp_user') && user.loginView) {
                    user = JSON.parse(sessionStorage.getItem('odp_user'));
                    store.commit('setUserFromSessionStorage', user);
                    sessionStorage.removeItem('odp_user');
                }
            return user;
        }
    },
    data: function () {
        return {
            lastTime: null
        }
    },
    methods: {
        loginClick: function (e) {
            eventVue.$emit('loginLinkOnClick'); 
            eventVue.$emit('hideCollapse');
        },
        logoutClick: function () {
            eventVue.$emit('hideCollapse');
            this.$store.dispatch('LogOff',
                JSON.stringify({
                    ajax: this.$store.getters.getAjaxUrlByName('LogOff'),
                }));
            console.log('stopWorkTimer - logoutClick');
            this.$store.commit('stopWorkTimer');
        }
    },
    created: function () {
        //var dataKey = document.getElementsByTagName('body')[0].attributes["data-key"].value;
        //if (this.getUser.FullName == "Вхід" && !sessionStorage.getItem('odp_user') && this.getUser.loginView && (window.location.href.toLowerCase()).indexOf('house') < 0 && (window.location.href.toLowerCase()).indexOf('account') < 0) {
        //    if (dataKey != '')
        //        sessionStorage.odp_data_key = dataKey;
        //    window.location = '/opendataportal/Account/Login';
        //}
    },
    mounted: function () {
        setTimeout(function () {
            document.querySelector('body > div.navbar-fixed-top').style.opacity = 1;
        }.bind(this), 500);
    },
});

var leftNavbar = new Vue({
    el: '#leftNavbar',
    template: '<div class="main-menu"  @mouseover="onOverMainMenu" @mouseout="onOutMainMenu"><ul>\
                    <li v-for="item in getLeftNavbarItems" :id="item.tagId" class= "li-menu" @click="liclick(item.type)" v-html="item.iel"></li>\
               </ul></div>',
    store,
    computed: {
        getLeftNavbarItems() {
            return store.getters.getLeftNavbarItems;
        },
    },
    methods: {
        liclick: function (e) {
            eventVue.$emit('hideCollapse');
            switch (e) {
                case 'basic':
                    break;
                case 'projects':
                    eventVue.$emit('openProjectWindow', e);
                    break;
                case 'legend':
                    this.$store.commit('showLegend');
                    break;
                case 'links':
                    eventVue.$emit('showLinks');
                    break;
                case 'print':
                    document.getElementsByClassName('esriPrint')[0].getElementsByTagName('input')[0].click();
                    break;
            }
        },
        onOverMainMenu: function () {
            document.querySelector('.nav_bookmark').classList.add('navBlock');
        },
        onOutMainMenu: function () {
            document.querySelector('.nav_bookmark').classList.remove('navBlock');
        },
    },

});


//var iconNavMenu = new Vue({
//    el: '#iconNavMenu',
//    template: '<div v-bind:class="{ hideBlock:getBlockIsHide }" icon-nav-menu">\
//                <span class="glyphicon" aria-hidden="true">\
//                <div class="logo"><img src="./Content/img/logo.svg" /></div>\
//                    </span>\
//            <div class="nav_bookmark" >\
//                <i class="material-icons">\
//                    list</i>\
//            </div>\
//                </div >',
//    store,
//    computed: {
//        getBlockIsHide() {
//            return store.getters.getBlockIsHide;
//        }
//    }  
//});
var ODP_DSNS_DATA_TOOLBAR = {
    template: `<BtnGroup class="btnGroup-modal" >
                <Btn v-if="showRefresh"
                        class="btnGroup-modal_btn" type="success" active title="Завантажити дані" @click="refreshClick">
                    <span class="material-icons">
                        {{refresh_label == 'Завантажити дані' ? "content_paste_search" : "refresh"}}
                    </span>
                    <span>{{refresh_label ? refresh_label : 'Оновити дані'}}</span>
                </Btn>
                <Btn v-if="showOnMap" 
                       class="btnGroup-modal_btn"
                        :title="showonmap_label ? showonmap_label : 'Застосувати на мапі'"
                        :type="showOnMapBtnInfo ? 'info' : 'success'"
                        :disabled="showOnMapDisabled"
                        @click="showOnMapClick">
                    <span class="material-icons" >
                        location_on
                    </span>
                    <span>{{showonmap_label ? showonmap_label : 'Застосувати на мапі'}}</span>
                </Btn>
                <Btn v-if="showCancel"
                        class="btnGroup-modal_btn" type="success" title="Скинути фільтри" @click="cancelClick" :disabled="cancelFiltersDisabled">
                    <span class="material-icons">
                        cancel
                    </span>
                    <span>Скинути</span>
                </Btn>

                <Btn v-if="showRefreshAll"
                        class="btnGroup-modal_btn btn-info" title="Оновити все" @click="()=>{}">
                    <span class="material-icons">
                        refresh
                    </span>
                    <span>Оновити дані</span>
                </Btn>

                <Btn v-if="showCancelAll"
                        class="btnGroup-modal_btn"
                            title="Скинути всі фільтри"
                            type="info"
                            @click="cancelAllClick"
                            :disabled="cancelAllFiltersDisabled">
                    <span class="material-icons">
                        cancel
                    </span>
                    <span>Скинути всі фільтри</span>
                </Btn>

                </BtnGroup>`,
    props: {
        showRefresh: Boolean,
        showRefreshAll: Boolean,
        showOnMap: Boolean,
        showOnMapBtnInfo: Boolean,
        showCancel: Boolean,
        showCancelAll: Boolean,
        showonmap_label: String,
        refresh_label: String,
        showOnMapDisabled: Boolean,
        cancelFiltersDisabled: Boolean,
        cancelAllFiltersDisabled: Boolean
    },
    data: function () {
        return {}
    },
    methods: {
        refreshClick: function () { this.$emit("refresh_click") },
        showOnMapClick: function () { this.$emit("showonmap_click") },
        cancelClick: function () { this.$emit("cancel_click") },
        cancelAllClick: function () { this.$emit("cancel_allclick") },
    }
}

var ODP_DSNS_DATA_TAB = {
    template: `<div  style="height: 100%">
            <div class="row" style="height: 54px">
                <div class="col-md-12">
                    <div v-if="showTitle" class="col-md-6 text-left tableTitleBox">
                        <span class="material-icons">
                            list_alt
                        </span>
                        <span>
                            {{title}}
                        </span>
                    </div>
                    <tabletoolbar
                        :showRefresh="true"
                        :showOnMap="true"
                        :showCancel = "true"
                        :refresh_label="refresh_label"
                        :showOnMapDisabled="data.length === 0"
                        :cancelFiltersDisabled="data.length === 0"
                        showonmap_label="Застосувати на мапі"
                        @refresh_click="refreshTable"
                        @showonmap_click="showOnMap"
                        @cancel_click="cancelFilters"

                    ></tabletoolbar>
                </div>
            </div>
            <div class="row" style="height: calc(100% - 54px)">
                <div class="col-md-12" style="height: 100%">
                     <tabulatorlocal
                         ref='tC'  
                         :key="\'tabulator_\' +tagId"
                         :columns='columns'
                         :data='data'
                         :tagId="tagId"
                        @tableIsInited="setTableIsInited"
                    ></tabulatorlocal>                 
                </div>
            </div>
            </div>`,
    props: {
        tagId: String,
        columns: Array,
        data: Array,
        tableName: String,
        title: String,
        showTitle: Boolean
    },
    computed: {
        refresh_label() {
            return this.data.length > 0 ? 'Оновити дані' : 'Завантажити дані';
        }
    },
    watch: {
        tagId(newVal, oldVal) {
            console.log("tagId", newVal);
            //if (newVal && this.tagId) {
            //    this.$refs.tC.initTable();
            //}
        },
        columns(newVal, oldVal) {
            console.log("columns", newVal);
            //if (newVal && this.tagId) {
            //    this.$refs.tC.initTable();
            //}
        },
        data(newVal, oldVal) {
            console.log("data", newVal);
            //if (newVal && this.tagId) {
            //    this.$refs.tC.initTable();
            //}
        },
    },
    components: {
        'tabletoolbar': ODP_DSNS_DATA_TOOLBAR,
        'tabulatorlocal': tabulator_table_local,
    },
    data: function () {
        return {
            tableIsInited : false,
        }
    },
    methods: {
        setTableIsInited: function () {
            this.tableIsInited = true;
        },
        refreshTable: function () {
            this.$emit("refreshTable", this.tableName);
        },
        showOnMap: function () {
            let filteredData = this.$refs.tC.getFilteredRows();
            let filters = this.$refs.tC.getAllFilters();
            let out_oids = [];
            //if (filteredData.length > 0 && filters.length > 0) {
            //    filteredData.forEach(function (fItem) {
            //        out_oids.push(fItem.OBJECTID);
            //    }.bind(this));
            //}

            if (filters.length > 0) {
                filters.forEach(function (fItem) {
                    out_oids.push(fItem);
                }.bind(this));
            }
            this.$emit('showOnMap', { tableName: this.tableName, oids: out_oids, afterCancel:false})

        },
        cancelFilters: function () {
            this.$refs.tC.removeAllTableFiters();
            this.$emit('showOnMap', { tableName: this.tableName, oids: [], afterCancel:true })
        },
        cancelFiltersIfHasNot: function () {
            this.$refs.tC.removeFiltersIfHasNot();
        },
        getAllFilters: function () {
            return this.$refs.tC.getAllFilters();
        },
    },
    mounted() {
        if (!this.tableIsInited)
            this.$refs.tC.initTable();
    }
}

var ODP_DSNS = {
    template: `<modal v-model="show"
                        id="dsnstables"
                        title="Дані ДСНС"
                        size="lg"
                        transition="50"                       
                        :footer="false"
                        @show="shownModal"
                        >
                    
                        <div class="row toolbarModalRow-lg">
                            <div class="col-md-12 text-left">
                                <div class="toolbarModalRow-box">
                                    <div class="toolbarModalRow-boxTitle">Всі завантажені таблиці даних</div>
                                    <tabletoolbar
                                        @cancel_allclick="cancelFiltersInAllTables"
                                        @showonmap_click="showOnMapAllSelectedData"
                                        :showOnMap="true"
                                        :showCancelAll = "true"
                                        showonmap_label="Застосувати на мапі"
                                        showOnMapBtnInfo
                                        :showOnMapDisabled="showOnMapDisabled"
                                        :cancelAllFiltersDisabled="showOnMapDisabled"
                                    ></tabletoolbar> 
                                </div>
                            </div>
                        </div>
                        <div class="row contentModalRow-lg">
                            <div class="col-md-12 text-right" style="height: 100%">
                                <Tabs v-show="DSNSLAYERS.length > 0"
                                    @change="changeTab"
                                    style="height: 100%">
                                    <Tab v-for="layer,index in DSNSLAYERS"
                                        style="height: 100%"
                                        :group="getDropDownName"
                                        :title="layer.legendName"
                                        :key="\'tab_\' +index" :id="\'tab_\' +index">
                                           <dsnstab
                                                :title="DSNSLAYERS.length > 5 ? layer.legendName : ''"
                                                :showTitle="DSNSLAYERS.length > 5"
                                                :tableName="layer.table.tableName"
                                                :tagId="layer.table.tableName"
                                                :columns="layer.table.columns"
                                                :data="layer.table.currentData"   
                                                :key="\'dsnstab_\' +index"
                                                :ref="\'tab_\' +layer.table.tableName"
                                                @refreshTable="refreshTable"
                                                @showOnMap="showFilteredLayerOnMap"
                                            ></dsnstab>                   
                                    </Tab> 
                                </Tabs>
                            </div>
                        </div>
                        <template #footer>
                            <div class="row footerModalRow-lg">
                                 <div class="col-md-12 text-right">
                                    <Btn size="lg" @click="closeModal">
                                        Закрити
                                    </Btn>
                                </div>
                            </div>
                        </template>
                    <!--<div slot="footer" class="customFooter text-center">
                        <Btn size="lg"
                            type="success"
                            @click="closeModal">
                            Показати
                        </Btn>
                    </div>-->

            </modal>`,
    //v-bind:class= "{ in : project.isShowProjectData }"  :aria-expanded="project.isShowProjectData" data-toggle="collapse"
    components: {
        'tabletoolbar': ODP_DSNS_DATA_TOOLBAR,
        'dsnstab': ODP_DSNS_DATA_TAB,
        'tabulatorlocal': tabulator_table_local
    },
    data: function () {
        return {
            show: false,
            //btnCancelVisible: false,
            footer: false,
            DSNSLAYERS: [],

        }
    },
    computed: {
        getDSNSVisibleLayers() {
            return this.$store.getters.getDSNSVisibleLayers;
        },
        getSheetDataAjaxProperties() {
            return this.$store.getters.getAjaxUrlByName("GetSheetData");
        }, 
        getDropDownName() {
            return this.DSNSLAYERS.length > 5 ? "Вибір таблиці даних " : "";
        }, 
        showOnMapDisabled() {
            let res = true;
            if (this.DSNSLAYERS.length > 0) {
                this.DSNSLAYERS.forEach(function (layer) {
                    if (layer.table.currentData.length > 0) {
                        res = false;
                    }
                }.bind(this));
                //
            }
            return res;
        }, 
    },
    watch: {
        getDSNSVisibleLayers: function (newData, oldData) {
            //console.log("getDSNSVisibleLayers", );
            this.DSNSLAYERS = newData;
        },
        DSNSLAYERS: function (newData, oldData) {
            console.log("DSNSLAYERS", newData);
           // this.DSNSLAYERS = newData;
        },
    },
    methods: {
        stopTheEvent: function (event) {
            event.stopPropagation();
        },
        closeModal: function (e) {
            this.show = false;
        },
        openModal: function (e) {
            this.show = true;
        },
        shownModal: function () {
            var T = "";
            this.getDSNSVisibleLayers.forEach(function (lItem) {
                if (lItem.visibility && lItem.expression.auth_string.string.length === 0) {
                    this.$refs['tab_' + lItem.table.tableName][0].cancelFilters();
                }
            }.bind(this));
        },
        changeTab: function (e) {
            setTimeout(function () {
                let tableName = this.DSNSLAYERS[e].table.tableName;
                this.getDSNSVisibleLayers.forEach(function (lItem) {
                    if (lItem.table.tableName === tableName && lItem.expression.auth_string.string.length === 0) {
                        this.$refs['tab_' + lItem.table.tableName][0].cancelFiltersIfHasNot();                       
                    }
                }.bind(this));
            //    if (this.DSNSLAYERS[e].expression.auth_string.string.length === 0)
            //        this.$refs['tab_' + this.DSNSLAYERS[e].table.tableName][0].cancelFiltersIfHasNot();
            }.bind(this), 800);
        },
        refreshAllTables: function () {
        },
        showOnMapAllSelectedData: function () {
            this.DSNSLAYERS.forEach(function (layer) {
                //якщо завантажені дані
                if (layer.table.currentData.length > 0) {
                    //отримуємо фільтри з таблиці
                    const filters = this.$refs['tab_' + layer.table.tableName][0].getAllFilters();
                    let where = "";
                    if (filters.length > 0) {
                        filters.forEach(function (fItem, index) {
                            where += (index > 0 ? " AND " : "");
                            where += fItem.field.toLowerCase();
                            where += " LIKE ";
                            where += "'%" + fItem.value + "%'";
                        }.bind(this));
                    }
                    this.$emit('showLayerDataInMap', { layer: layer, where: where });
                }

            }.bind(this));
            this.closeModal();

        },
        refreshTable: function (tableName) {
            this.$store.dispatch(this.getSheetDataAjaxProperties.name, { url: this.getSheetDataAjaxProperties.url, tableName: tableName });
        },
        showFilteredLayerOnMap: function (data) {
            let where = "";
            //{ tableName: tableName, oids: out_oids}
            //if (data.oids.length > 0) {
            //    where = "OBJECTID IN ("
            //    where += data.oids.join(",");
            //    where += ")";
            //}
            if (data.oids.length > 0) {
                data.oids.forEach(function (fItem, index) {
                    where += (index > 0 ? " AND " : "");
                    where += fItem.field.toLowerCase();
                    where += " LIKE ";
                    where += "'%" + fItem.value+"%'";
                }.bind(this));
                //where = "OBJECTID IN ("
                //where += data.oids.join(",");
                //where += ")";
            }
            let layer = this.DSNSLAYERS.find(l => l.table.tableName === data.tableName)
            this.$emit('showLayerDataInMap', { layer: layer, where: where });

            if (!data.afterCancel)
                this.closeModal();
        },
        cancelFiltersInAllTables: function () {
            let where = "";
            //{ tableName: tableName, oids: out_oids}
            if (this.getDSNSVisibleLayers.length > 0) {
                //this.getDSNSVisibleLayers.forEach(function (lItem) {
                //    if (lItem.visibility) {
                //        let layer = lItem;
                //        this.$emit('showLayerDataInMap', { layer: layer, where: where });
                //    }

                //}.bind(this));
                this.getDSNSVisibleLayers.forEach(function (lItem) {
                    if (lItem.visibility) {
                        this.$refs['tab_' + lItem.table.tableName][0].cancelFilters();
                    }
                }.bind(this));
            }

            //this.closeModal();
        },
    },
};
//const { max } = require("underscore");


//show blobs in magnific popup
function showBlobs(blobs, printerUrl, titles, type) {
    let out_type = 'image';
    if (type) {
        out_type = type;
    }
    //photo from printer
    if (printerUrl && Array.isArray(printerUrl) && printerUrl.length > 0) {
        var items = [], ttitles=[];
        if (titles) {
            var T = '';
            var arrT = titles.split('#$#'),
                titles = [];
            arrT.forEach(function (item, index) {
                var title = arrT[index].substring(arrT[index].indexOf('_')).replace('_', "");
                ttitles.push(title);
            }.bind(this));
        }
        for (var i = 0; i < printerUrl.length; i++)
            items.push({
                src: printerUrl[i], title: (ttitles.length == printerUrl.length ? ttitles[i]: "")
            });
        $.magnificPopup.open({
            items: items,
            gallery: {
                enabled: true
            },
            type: out_type // this is default type
        });
    }
    else if (printerUrl) {
            $.magnificPopup.open({
                items: {
                    src: printerUrl
                },
                type: out_type
            });
    }
    //photo from features
    else if (blobs.length > 0) {
        if (blobs.length == 1) {
            $.magnificPopup.open({
                items: {
                    src: '/opendataportal/Home/Blob?id=' + blobs[0]
                },
                type: out_type
            });
        }
        else {
            var items = [];
            for (var i = 0; i < blobs.length; i++)
                items.push({ src: '/opendataportal/Home/Blob?id=' + blobs[i]});
            $.magnificPopup.open({
                items:items,
                gallery: {
                    enabled: true
                },
                type: out_type // this is default type
            });
        }
    }
}

function copyToClipboard(text) {
    if (!navigator.clipboard) {
        console.log("копіювання до буферу не підтримується");
        return;
    }
    navigator.clipboard.writeText(text).then(function () {
        console.log('дані скопійовані');
    }, function (err) {
        console.error('Async: Could not copy text: ', err);
    });

}

function showPDF(blobs) {
    let out_type = 'iframe';
    let items = [];
    //photo from printer
    for (var i = 0; i < blobs.length; i++)
        //items.push({
        //    src: blobs[i],
        //  //  type:'iframe'
           
        //});
        items.push({//style="height:calc(100vh - 50px);width:calc(100% - 50px);" 
          //  src: '<iframe src="' + blobs[i] + '" title="Iframe Example" style="height:80vh;width:80vw;"  frameborder="0" allowfullscreen></iframe>',
            src: `<div class="mfp-iframe-scaler" >
            <div class="mfp-s-loading"></div>
            <div class="mfp-close"></div>
            <iframe src="` + blobs[i] + `" class="mfp-iframe" frameborder="0" allowfullscreen></iframe>
            </div>`,
            type: 'inline'
            //src: ' <iframe src="https://www.w3schools.com" class= "mfp-iframe" frameborder="0" allowfullscreen></iframe>', type:  "inline"
        });
    $.magnificPopup.open({
        items: items,
        type: out_type,
        closeBtnInside: false,
        showCloseBtn: true,
        gallery: {
                    enabled: true
                },

    });

        //if (blobs.length > 0) {
        //if (blobs.length == 1) {
        //    $.magnificPopup.open({
        //        items: {
        //            src: '/opendataportal/Home/Blob?id=' + blobs[0]
        //        },
        //        type: out_type
        //    });
        //}
        //else {
        //    var items = [];
        //    for (var i = 0; i < blobs.length; i++)
        //        items.push({ src: '/opendataportal/Home/Blob?id=' + blobs[i] });
        //    $.magnificPopup.open({
        //        items: items,
        //        gallery: {
        //            enabled: true
        //        },
        //        type: out_type // this is default type
        //    });
        //}
    //}
}
//компоненты-----------------------------
//---------------------------------------
//modal ListAreaAddresses

//const listAreaAddresses = {
//    template: `<div class="testComponent"></div>`
//};

const listAreaAddresses = {
    template: `<div id="listAreaAddresses" 
                                        v-bind:class="[
                                                {listAreaAddresses__hidden : !show}, 
                                                {listAreaAddresses : show}, 
                                                {minimizeActive: Isminimized}
                                        ]">
                <div class="listAreaAddresses_header">
                    <div class="listAreaAddresses_title">
                       Територія обслуговування 
                        <span>
                            {{addressesObjectsListType ?
                                activeListMode[addressesObjectsListType].headerName :
                                ''}}
                        </span>                       
                          
                    </div>
                    <button class="backIdentifyBtn" 
                            :title="(addressesObjectsListType ? activeListMode[addressesObjectsListType].title : '')"
                             @click="zoomToEducation"
                          >
                        <span class="material-icons">
                            arrow_right_alt
                        </span>
                        <span class="material-icons">
                           {{addressesObjectsListType ?
                                activeListMode[addressesObjectsListType].icon :
                                ''}}
                        </span> 
                    </button>
                    <span class="minimizeBtn material-icons" 
                            @click="toggleMinimize"
                                {{minimizeIcon}}
                        </span> 
                    <span aria-hidden="true" class="close" 
                            @click="zoomToEducation">
                                &#10005
                            </span>
                </div>
                <div class="listAreaAddresses_content">
                    <table>
                        <thead>
                            <tr>
                                <!--<th>Перелік адрес</th>-->
                            </tr>
                        </thead>
                       <tbody>
                            <tr v-for="aObject in objectsList"
                                      @click="selectAddressObject(aObject)" >
                                <td>
                                    {{aObject.out}} 
                                    <span class="material-icons pinMapPosition">
                                        place
                                    </span>
                                </td>
                            </tr>                            
                        </tbody>
                    </table>
                </div>
                </div>`,
    data: function () {
        return {
            Isminimized: false,
            minimizeIcon: 'minimize',
            activeListMode: {
                'scool': {
                    headerName: 'навчального закладу',
                    title: 'До навчального закладу',
                    icon: 'school'
                },
                'bombshelters': {
                    headerName: 'укриття',
                    title: 'До укриття',
                    icon: 'change_history'
                },
                'medicine': {
                    headerName: 'мед закладу',
                    title: 'До мед закладу',
                    icon: 'local_hospital'
                },
            }
        }
    },
    props: {
        'show': {
            type: Boolean,
            default:false
        },
        'objectsList': {
            type: Array,
            default: []
        },

        'addressesObjectsListType': {
            type: String,
            default: ''
        },
        'mainObject': Object,
    },
    watch: {
        //mainObject: function (newVal, oldVal) {
        //    var T = '';
        //}, 
        objectsList: function (newVal, oldVal) {
            var T = '';
        }, 
        //addressesObjectsListType: function(newVal, oldVal) {
        //    var T = '';
        //}, 
    },
    methods: {
        toggleVisibilityListArea: function () {
            this.$emit('toggleVisibilityListArea');
        },
        selectAddressObject: function (aObject) {
            this.$emit('selectObject', aObject);
        },
        zoomToEducation: function () {
            this.$emit('zoomToMainObject', true);
        },
        toggleMinimize: function () {
            if (this.Isminimized == false) {
                this.Isminimized = true;
                this.minimizeIcon = 'fullscreen';
            }
            else if (this.Isminimized == true) {
                this.Isminimized = false; 
                this.minimizeIcon = 'minimize';
            }
        },

    },
    //mounted: {
        
    //},
    //updated: function () {
    //}
};

//identityPanelComponent

const identityPanelComponent = {
    template: `<div id="identityPanel" v-show="showIdentity">
                <div class="identityPanel_header listAreaAddresses_title">
                    <div class="identityPanel_title">
                       <span>Відображення даних</span>                    
                    </div>
                    <div class="identityPanel_navblock">
                        <span class="material-icons">arrow_left</span>
                        <span class="material-icons">arrow_right</span>
                    </div>
                    <span class="minimizeBtn material-icons" @click="toggleMinimize">
                            {{minimizeIcon}}
                        </span>
                    <span aria-hidden="true" class="close">&#10005</span>
                </div>
                <div class="identityPanel_content">
                    <table>
                        <thead>
                           
                        </thead>
                        <tbody>      
                            <tr v-for="item in listItems" :key="item.name">
                              <td class="left-side">
                                    {{item.name}}
                                </td>
                              <td class="right-side">
                                    {{item.description}}
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
`,
    props: {},
    data: function () {
        return {
            showIdentity: false,
            Isminimized: false,
            minimizeIcon: 'minimize',
            listItems: [
                {
                    name: '№',
                    description: '5'
                },
                {
                    name: 'призначення',
                    description: 'побутове обслуговування населення'
                },
                {
                    name: 'обслуговуюча організація',
                    description: 'КП "ХТМ"'
                },
            ]
        }
    },
    methods: {
        toggleMinimize: function () {
            if (this.Isminimized == false) {
                this.Isminimized = true;
                this.minimizeIcon = 'fullscreen';
            }
            else if (this.Isminimized == true) {
                this.Isminimized = false;
                this.minimizeIcon = 'minimize';
            }
        },
    },


};



const APP_IDENTIFY = {
    template: `<aside class="identify-panel"
                                :class="{'hideIdentify' : hideIdentify}"  >

                    <div class="card">
                      <div class="card-body">
                        <h5 class="card-title" @touchstart.stop="touchStartMethod">
                            <span aria-hidden="true" title="Інформація" class="card-title-icon glyphicon glyphicon-info-sign"></span>
                            <span>Інформація про об'єкт</span>
                            <button type="button"
                                    class="identify-close btn"
                                    @click="toggleIdentify">

                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
                                                                        fill="currentColor"
                                                                        class="bi bi-caret-down-fill"
                                                                        viewBox="0 0 16 16">
                                  <path d="M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z"/>
                                </svg>
                            </button>
                        </h5>
                        <div class="col" v-show="!showObjectDescription && !showObjectServices">
                            <ul class="list-group list-group-flush">
                                <li v-for="item in identityFeature"
                                                class="list-group-item">
                                    <div class="list-item-title">
                                        <div class="col">
                                            {{item.content[item.layerIdentityProp.mainField] && item.content[item.layerIdentityProp.mainField] == 'Null' ? '' : item.content[item.layerIdentityProp.mainField]}}
                                            {{item.layerIdentityProp.addAdmRayon && item.content['odp_adm_rayon'] && item.content['odp_adm_rayon']['NAME_UA']  ? ('(' + item.content['odp_adm_rayon']['NAME_UA'] + " район)"): ''}}

                                                <span class="serviceListContainer"
                                                            v-show="item && item.layerIdentityProp.title == 'Будівлі'">
                                                    <div v-if="item.content.services" class="col-xs-12 col-sm-12 padding-0">
                                                        <a @click="showServiceList(item)" style="font-size:10px; " ><i class="material-icons">security</i> Укриття <i class="material-icons">local_hospital</i> медицина <i class="material-icons">school</i>освіта</a>
                                                    </div>
                                                </span>
                                        </div>
                                        <div class="col identify-layerName">
                                            <span class="badge badge-secondary">
                                                {{item.title}}
                                            </span>
                                        </div>
                                    </div>
<!--                                            v-if="(item.content[item.layerIdentityProp.mainField] && item.content[item.layerIdentityProp.mainField] != 'Null') || (item.layerIdentityProp.mainField2 && item.content[item.layerIdentityProp.mainField2] && item.content[item.layerIdentityProp.mainField2] != 'Null')"
-->
                                    <button type="button"
                                            class="identify-listBtn btn"
                                            title="Детальний опис"

                                            @click="setDetailedObject(item)">

                                       <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
                                          <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/>
                                        </svg>
                                    </button>
                                </li>
                            </ul>


                        </div>
<!--Детально обьект-->
                        <div v-show="showObjectDescription && !showObjectServices"
                                        class="col objectDescription">
                            <div class="col-xs-12 identify-panel-freeDiv">
                                <button type="button"
                                        class="detaile-close btn identify-listBtn"
                                        title="назад"
                                        @click="hideDetailedObject">

                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
                                        <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
                                    </svg>
                                </button>
                                <span class="badge badge-light">{{currentTitle}}</span>
                            </div>
                            <ul v-if="tableData" class="tableData list-group list-group-flush">
                                <li v-html="tableData" class="list-group-item"></li>
                            </ul>
                            <ul v-else class="NO-tableData list-group list-group-flush">
                                <li v-show="item && name != 'services' && name != 'eventServices' && name != 'content' && name != 'bindToServices'"
                                                v-for="(item, name) in currentDetailedObject"
                                                class="list-group-item">
                                   <div v-show.trim ="item != ''" class="col-xs-5 labelName padding-0">
                                        {{name}}
                                    </div>
                                    <div v-show.trim ="item != ''" class="col-xs-7 identify-value padding-0"
                                                :class="{'font-1rem' : (name == 'Email' || name == 'Веб-сайт' || name == 'Сайт')}">
                                        
                                        <span v-if="name == 'Вартість' && item == 0">
                                            безкоштовно
                                        </span>
                                        <span v-else-if="name == 'Стан підключення'" v-html="item"></span>                                          
                                        <span v-else-if="name == 'Номер у черзі'">{{item == '0' ? '' : item}}</span>  
                                        <span v-else  v-html="item == 'Null'  ? '' : item">
                                            <!--{{item == 'Null' ? '' : item}}-->
                                        </span>
                                    </div>   
                                </li>
                            
                                <ul class="list-group list-group-flush"
                                        :class="{listOfBtn : (outUrls && (outUrls.length > 0 || outDocumUrls.length > 0))}"
                                        v-show="currentDetailedObject && (currentDetailedObject['bindToServices'] || outUrls.length > 0 || outDocumUrls.length > 0)">

                                    <li class="list-group-item"
                                                v-show="item && name == 'bindToServices'"
                                                v-for="(item, name) in currentDetailedObject">
                                        <div v-if="currentTitle != 'Будівлі'" class="col-xs-12 col-sm-6 padding-0">
                                            <button @click="showObjectServiceList" class="identify-btnDefault">
                                                <span class="material-icons">manage_search</span>
                                                <span>Служби</span>
                                            </button>
                                        </div>

                                    </li>
                                    <li v-if="outUrls.length > 0" class="list-group-item">
                                        <div class="col-xs-12 col-sm-6 padding-0">
                                            <button
                                                    @click="startShowBlobs(null,outUrls, null, null)"
                                                    class="photoBtn identify-btnDefault" >
                                                <span class="material-icons">photo_library</span>
                                                <span>Фото</span>
                                            </button>
                                        </div>
                                    </li>
                                    <li v-if="outDocumUrls.length > 0" class="list-group-item">
                                        <div class="col-xs-12 col-sm-6 padding-0">
                                            <button
                                                    @click="startShowDocums(null,outDocumUrls, null, null)"
                                                    class="photoBtn identify-btnDefault" >
                                                <span class="material-icons">photo_library</span>
                                                <span>Документи</span>
                                            </button>
                                        </div>
                                    </li>
                                    <li v-if="printIdentity" class="list-group-item">
                                        <div class="col-xs-12 col-sm-6 padding-0">
                                            <button class="identify-btnDefault" @click="printIdentityData">
                                                <span class="material-icons">print</span>
                                                <span>Друк</span>
                                            </button>
                                        </div>
                                    </li>
                                </ul>
                                <li class="list-group-item"
                                        v-show="currentFullContentObject && currentFullContentObject.layerIdentityProp.bindToAddress">
                                            
                                    <div class="col-xs-12 padding-0">
                                        <div  class="identify-labelAddress" >
                                            <span>Територія обслуговування:</span>
                                           <!-- <button  v-show="currentFullContentObject && currentFullContentObject.layerIdentityProp.bindToAddress && !mapListAdresses.list && !showingAddressesNotFound"
                                                    @click="getServiceTerritory"
                                                    class="identify-btnDefault">
                                                <span class="material-icons">file_download</span>
                                            </button>-->
                                            <div v-show="currentFullContentObject && currentFullContentObject.layerIdentityProp.bindToAddress && !mapListAdresses.list && !showingAddressesNotFound"
                                                class="localSpiner">
                                                <img src="/opendataportal/Content/img/VZvw.gif">
                                            </div>
                                            <span v-show="showingAddressesNotFound" class="noDataText">
                                                <span class="material-icons">sentiment_very_dissatisfied</span>
                                                Дані відсутні
                                            </span>

                                        </div>
                                        <div class="col-xs-12 identify-panel-freeDiv" style="justify-content: space-around"
                                                    v-show="currentFullContentObject && currentFullContentObject.layerIdentityProp.bindToAddress && mapListAdresses.list">
                                            <button 
                                                    class="showAreaBtn identify-btnDefault" @click="showAddressesObjectsOnMap">
                                                <span class="material-icons">apartment</span>
                                                <span>Карта</span>
                                            </button>
                                            <button @click="showAddressesObjectsListInPanel"
                                                    class="identify-btnDefault">
                                                <span class="material-icons">list</span>
                                                <span>Список</span>
                                            </button>
                                        </div>
                                    </div>
                                    
                                </li>

                               
                            </ul>

                          <!--  <APP_IDENTIFY_CONDITION ref="ICond">
                            </APP_IDENTIFY_CONDITION> -->
                        </div>
<!-- END Детально-->

<!-- Services list-->
                        <div v-show="showObjectServices"
                                        class="col objectDescription">
                            <div class="col-xs-12 identify-panel-freeDiv">
                                <button type="button"
                                        class="detaile-close identify-listBtn btn"
                                        title="назад"
                                        @click="hideObjectServiceList">

                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
                                        <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
                                    </svg>

                                </button>
                            </div>
                            <ul v-if="currentDetailedObject.services" class="list-group">
                                <li v-for="(item, name) in currentDetailedObject.services"
                                                class="list-group-item list-column service-item">
                                    <div class="col-xs-12 service-itemLabel padding-0">
                                       <div v-html="item.name">
                                        </div>
                                        <button type="button"
                                                class="identify-listBtn btn"
                                                title="Перейти"
                                                @click="gotoServiceObject(item)">
                                            <span class="material-icons">
                                                zoom_in
                                            </span>
                                        </button>
                                    </div>
                                    <div class="col-xs-12 identify-value padding-0">
                                                            <!--<ul v-if="item.feature.attributes" class="list-group">
                                                                <li v-for="(elem, elemName) in item.feature.attributes"
                                                                            class="list-group-item">
                                                                    {{elem}}
                                                                </li>
                                                            </ul>-->
                                        <div>{{item.feature.attributes.name}}</div>
                                        <div v-if="item.feature.attributes.adre">{{item.feature.attributes.adres}}</div>
                                        <div v-if="item.feature.attributes.address">{{item.feature.attributes.address}}</div>
                                        <div v-if="item.feature.attributes.AR_ID">{{item.feature.attributes.ADDRESS}}</div>

                                    </div>
                                </li>

                            </ul>
                            <ul v-if="currentDetailedObject.eventServices" class="list-group">
                                <li v-for="(itemes, name) in currentDetailedObject.eventServices"
                                                class="list-group-item list-column service-item">
                                    <div class="col-xs-12 service-itemLabel padding-0">
                                       <div class="col-xs-5" v-html="itemes.name">
                                        </div>
                                        <button type="button"
                                                class="identify-listBtn btn"
                                                title="Перейти"
                                                @click="gotoServiceObject(itemes)">

                                           <span class="material-icons">
                                                open_in_new
                                            </span>
                                        </button>
                                    </div>
                                            <!--<div v-if class="col-xs-7 identify-value padding-0" v-html="itemes"></div>-->
                                </li>
                            </ul>
                            <div v-if="!currentDetailedObject.eventServices && !hasServices && loadingServices"
                                class="localSpiner">
                                <img src="/opendataportal/Content/img/VZvw.gif">
                            </div>
                            <span v-if="!hasServices && !loadingServices" class="col-xs-7 noDataText">
                                <span class="material-icons scaleFaceIcon">sentiment_very_dissatisfied</span>
                                <span>Дані відсутні</span>
                            </span>
                        </div>
<!--END Services -->
                      </div>
                    </div>
                       
                </aside>`,
    components: {
       
    },
    //data: function () {
    //    return {
    //        //listTemplate: [
    //        //    { elem: 'шар даних 1' },
    //        //    { elem: 'шар даних 2' },
    //        //    { elem: 'шар даних 3' },
    //        //],
    //        hideIdentify: true,
    //        showObjectDescription: false,
    //        currentDetailedObject: {
    //            type: Object,
    //            default: () => ({})
    //        },
    //        currentTitle: '',
    //    }
    //},
    props: {
        selectedFeature: {
            type: Object,
            default: () => ({}),
        },
        identityFeatures: Array,
        flags: {
            type: Object,
            default: () => ({})
        },
        showingAddressesNotFound: Boolean,
        showAddressesObjectsList: Boolean
    },
    computed: {
        mapListAdresses() {
            return {
                ID: this.currentFullContentObject.content[this.currentFullContentObject.layerIdentityProp.bindToAddressField],
                type: this.currentFullContentObject.layerIdentityProp.type,
                list: this.$store.getters.getAddressesObjectsList[this.currentFullContentObject.content[this.currentFullContentObject.layerIdentityProp.bindToAddressField]]
            };
        }
    },
    watch: {
        identityFeatures: function (newVal, oldVal) {
            this.clearTableData();
            this.identityFeature.splice(0);
            if (newVal && Array.isArray(newVal) && newVal.length > 0) {
                this.identityFeature = this.updateBindServices(newVal);
            }

            if (Array.isArray(this.identityFeature) && this.identityFeature.length > 0)
                this.hideIdentify = false;
            else
                this.hideIdentify = true;
            this.showObjectDescription = false;
            this.showObjectServices = false;
        },
        selectedFeature: function (newVal, oldVal) {
            var T = '';
        },
        flags: function (newVal, oldVal) {
            this.flags = newVal;
        },
        showAddressesObjectsList: function (newVal, oldVal) {
            newVal ? this.hideIdentify = true : this.hideIdentify = false
            let V;
        }
    },
    data: function () {
        return {
            tableData: null,
            hideIdentify: true,
            showObjectDescription: false,
            showObjectServices: false,
            currentTitle: '',
            currentDetailedObject: {},
            currentFullContentObject: null,
            identityFeature: [],
            printIdentity: false,
            //photos-------------
            OID: -1,
            imgs: [],
            outUrls: [],
            outDocumUrls:[],
            is_num: 0,
            AID: -1,
            isJpg: false,
            isPng: false,
            //--------------------
            hasServices: false,
           // loadedServices: false,
            loadingServices: false,
            isClickByRightArrow: null,

        }

    },
    methods: {
        toggleIdentify: function (str) {
            this.hideIdentify ?
                this.hideIdentify = false :
                this.hideIdentify = true;

        },
        showDetailedObject: function () {
            this.showObjectDescription = true;
        },
        //показываем лист, запускаем попап, запускаем поиск сервисов
        showObjectServiceList: function () {
            this.showObjectServices = true;
            this.isClickByRightArrow = true;
            this.hideDetailedObject();
            //if (!this.currentDetailedObject.services )
            //    this.currentFullContentObject.layerIdentityProp.identityFields.forEach(function (ifItem) {
            //        if (ifItem.name == 'bindToServices' && ifItem.bindToServices.length > 0) {
            //            this.loadingServices = true;
            //            this.$emit('get_services', { services: ifItem, fullData: this.currentFullContentObject });
            //        }
            //    }.bind(this));

        },
        //отображаем сервисы, закрываем поппап,  показываем сервис лист
        showServiceList: function (item) {
            this.setDetailedObject(item);
            this.showObjectServiceList();      
            this.isClickByRightArrow = false;            
        },
        setServicesList: function (services) {
            if (Array.isArray(services) && services.length > 0) {
                if (services[0].prop.AR_ID) {
                    this.identityFeature.forEach(function (ifItem) {
                        if (ifItem.content.AR_ID == services[0].prop.AR_ID && ifItem.layerIdentityProp.tocName == 'Будівлі і споруди') {
                            if (!ifItem.content.services)
                                Vue.set(ifItem.content, 'services', services);
                            //Vue.set(ifItem.content, 'services', services);
                            //services.forEach(function (sItem) {
                            //    ifItem.content.services.push(sItem);
                            //}.bind(this));
                        }
                        //Vue.set(ifItem.content, 'services', services);
                    }.bind(this));
                    //Vue.set(this.currentDetailedObject, 'services', services);
                }
                else {

                }



                if (!this.currentDetailedObject.services)
                    Vue.set(this.currentDetailedObject, 'services', []);
                services.forEach(function (sItem) {
                    this.currentDetailedObject.services.push(sItem);
                }.bind(this));
                this.hasServices = true;
            }
            else
                this.hasServices = false;

            this.loadingServices = false;
        },

        gotoServiceObject: function (data) {
            if (data.feature) {
                var infoData = {
                    displayFieldName: data.feature.displayFieldName,
                    feature: data.feature,
                    geometryType: data.feature.geometryType,
                    layerId: data.feature.layerId,
                    layerName: data.feature.layerName,
                    value: "вулиця Данилевського, 36"
                };

                this.$emit('goto_service_object', { highlightData: [data], infoData: [[infoData]], fromServiceObject: true });
            }
            else if (data.eventName) {
                this.$emit('goto_service_object', { eventName: data.eventName, GUID: data.GUID });                
            }
        },
        hideDetailedObject: function () {
            this.showObjectDescription = false;
            if (!this.showObjectServices)
                this.$emit('hide_feature_identify');

        },
        hideObjectServiceList: function () {            
            this.showObjectServices = false;
            this.showDetailedObject();
            if (!this.isClickByRightArrow) {
                this.hideDetailedObject();
            }
            this.isClickByRightArrow = null;
        },
        setDetailedObject: function (content) {
            this.printIdentity = false;
            this.hasServices = false;
            this.clearTableData();
            this.clearPhotosData();
            this.currentFullContentObject = content;
            this.selectionObjectEvent(content);
            this.clearDetailedObject();
            this.showDetailedObject();
            this.currentTitle = content.title ? content.title : '';
            let outPutFelds = [];
            outPutFelds = content.layerIdentityProp.іd != 1 ? content.layerIdentityProp.identityFields : [];

            //формируем обьект на вывод
            outPutFelds.forEach((el) => {
                //for (let key in content.content)
                //    if (el.name == key) {
                //        this.currentDetailedObject[el.description] = (content.content[key] != 'Null') ?
                //            content.content[key] : '';
                //    }
                //    else if (el.name == 'bindToServices')
                //        this.currentDetailedObject['bindToServices'] = 'bindToServices';
                for (let key in content.content) {
                    //console.log(key + ' = ' + content.content[key]);

                    if (el.name == key && key == 'DATEWARMCONS') {
                        this.currentDetailedObject[el.description] = content.content[key] == ''? "Null":content.content[key];
                    }
                    else if (el.name == key && content.content[key] && content.content[key] != 'Null'  && +content.content[key] != 0 && content.content[key].toString().trim() != '') {
                        if (key == 'WARMCON') {
                            var color = (+content.content[key] == 0 ? 'color:#0898c3;' : (+content.content[key] == 1 ? 'color:#ff2525;' : (+content.content[key] == 2 ? 'color:#d4d015;' : ''))),
                                outSTR = "";
                            if (+content.content[key] == 0) {
                                outSTR += '<span class="material-icons" style="transform: scale(0.9);">thermostat</span> очікуєсться';
                                if (content.content['EXPDATEWARMCON'] && content.content['EXPDATEWARMCON'] != "Null")
                                    outSTR += " " + content.content['EXPDATEWARMCON'];
                            }
                            else if (+content.content[key] == 1) {
                                outSTR += '<span class="material-icons" style="transform: scale(0.9);">thermostat</span> підключено';
                                if (content.content['DATEWARMCON'] && content.content['DATEWARMCON'] != "Null")
                                    outSTR += " " + content.content['DATEWARMCON'];
                            }
                            else if (+content.content[key] == 2) {
                                outSTR += '<span class="material-icons" style="transform: scale(0.9);">thermostat</span> завоздушення';
                                //if (content.content['DATEWARMCON'] && content.content['DATEWARMCON'] != "Null")
                                //    outSTR += " " + content.content['DATEWARMCON'];
                            }
                            this.currentDetailedObject[el.description] = '<span style="' + color + '; font-weight:400; display: flex; align-items: center;">' + outSTR + '</span>';
                        }
                        else
                            this.currentDetailedObject[el.description] = content.content[key];
                    }
                    else if (el.name == 'bindToServices')
                        this.currentDetailedObject['bindToServices'] = 'bindToServices';
                }
            });

            if (content.content['services']) {
                //this.currentDetailedObject['services'] = content.content['services'];
                Vue.set(this.currentDetailedObject, 'services', content.content['services']);
                this.hasServices = true;
            }

            if (content.content['eventServices']) {
               // this.currentDetailedObject['eventServices'] = content.content['eventServices'];
                Vue.set(this.currentDetailedObject, 'eventServices', content.content['eventServices']);
                this.hasServices = true;
            }
 
            //photos-----------------------------------------------------------------
            if (this.currentFullContentObject.title == "Не комунальне житло") {                
                this.AID = content.content['AR_ID'];
                this.OID = content.content['OBJECTID'];
                this.chackImages();
            }
           
            if (this.currentFullContentObject.title == "МАФи (тест)") {     
                var href = (window.location.pathname == '/' || window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href;
                var str = (href+'Content/maf/maf_17_1_');
                for (var i = 0; i < 2; i++)
                    this.outUrls.push(str + (i + 1) + ".jpg");
            }

            if (this.currentFullContentObject.title == "Рекламні конструкції" && this.currentFullContentObject.feature.attributes.BLOBS  && this.currentFullContentObject.feature.attributes.BLOBS.length > 0) {     
                var href = (window.location.pathname == '/' || window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href,
                    ids = this.currentFullContentObject.feature.attributes.BLOBS.split(", ");
                
                var str = (href + 'Home/Blob?id=');
                for (var i = 0; i < ids.length; i++)
                    this.outUrls.push(str + ids[i]);
                var T = '';
            }

            if (this.currentFullContentObject.title == "Пункти незламності" && this.currentFullContentObject.content && this.currentFullContentObject.content.RESERVE_1 && this.currentFullContentObject.content.RESERVE_1 != 'Null') {
                setTimeout(function () {
                    this.currentFullContentObject.content.RESERVE_1.split(',').forEach(function (item) {
                        //this.outUrls.push("https://drive.google.com/uc?export=view&id=" + item.trim());
                        this.outUrls.push("https://lh3.googleusercontent.com/d/" + item.trim());
                        //this.outDocumUrls.push("https://drive.google.com/file/d/" + item.trim() + "/preview");                        
                    }.bind(this));
                }.bind(this), 200);
            }
            if (this.currentFullContentObject.layerIdentityProp.photoField &&
                this.currentFullContentObject.content[this.currentFullContentObject.layerIdentityProp.photoField] &&
                !["Null", "null", null, ""].includes(this.currentFullContentObject.content[this.currentFullContentObject.layerIdentityProp.photoField])) {
                setTimeout(function () {
                    this.currentFullContentObject.content[this.currentFullContentObject.layerIdentityProp.photoField].split(',').forEach(function (item) {
                        //this.outUrls.push("https://drive.google.com/uc?export=view&id=" + item.trim());
                        this.outUrls.push("https://lh3.googleusercontent.com/d/" + item.trim());
                    }.bind(this));
                }.bind(this), 100);
            }
            //--Документи-----------------------------
            if (this.currentFullContentObject.layerIdentityProp.documField && this.currentFullContentObject.content[this.currentFullContentObject.layerIdentityProp.documField]) {
                setTimeout(function () {
                    this.currentFullContentObject.content[this.currentFullContentObject.layerIdentityProp.documField].split(',').forEach(function (item) {
                        //&#zoom=100,0,0&toolbar=0&view=FitH&navpanes=0
                        this.outDocumUrls.push("https://drive.google.com/file/d/" + item.trim() +"/preview");
                        //this.outDocumUrls.push("https://docs.google.com/viewer?srcid=" + item.trim() + "&pid=explorer&efh=false&a=v&chrome=false&embedded=true");
                    }.bind(this));
                }.bind(this), 100);
            }

            this.printIdentity = this.currentFullContentObject.layerIdentityProp.printIdentity ? this.currentFullContentObject.layerIdentityProp.printIdentity : false;
            //-------------------------------
            if (content.contentTable)
                this.tableData = content.contentTable;

            this.getServiceTerritory();

            this.loadingServices = false;
        },
        selectionObjectEvent: function (data) {
            this.$emit('select_feature_identify', [data]);
        },
        clearDetailedObject: function () {
            this.currentDetailedObject = {};
        },
        clearTableData: function () {
            this.tableData = null;
        },
        getServiceTerritory: function () {
            if (this.currentFullContentObject.layerIdentityProp.bindToAddress && !this.mapListAdresses.list) {
                //загружаем данные по адресам
                var layer = this.$store.getters.getLayerByTocName(this.currentFullContentObject.layerIdentityProp.tocName),
                    field = layer.identify[0].bindToAddressField;

                var type = this.mapListAdresses.type,
                    method;
                var prop = {
                    identityData: {
                        infoData: [[{
                            displayFieldName: this.currentFullContentObject.feature.displayFieldName,
                            feature: this.currentFullContentObject.feature,
                            geometryType: this.currentFullContentObject.content.feature.geometryType,
                            layerId: this.currentFullContentObject.content.feature.layerId,
                            layerName: this.currentFullContentObject.content.feature.layerName
                        }]]
                    }
                },
                    method;
                if (this.currentFullContentObject.feature.attributes[field] != 'Null') {
                    if (type == "bombshelters") {
                        method = this.$store.getters.getAjaxUrlByName('GetAddressesByBombShelter');
                        Vue.set(prop, 'bombGuid', this.currentFullContentObject.feature.attributes[field]);
                    }
                    else if (type == "scool") {
                        method = this.$store.getters.getAjaxUrlByName('GetAddressesByPrimarySchool');
                        Vue.set(prop, 'schoolGuid', this.currentFullContentObject.feature.attributes[field]);
                    }
                    else if (type == "medicine") {
                        method = this.$store.getters.getAjaxUrlByName('GetAddressesByHospital');
                        Vue.set(prop, 'medGuid', this.currentFullContentObject.feature.attributes[field]);
                    }
                    Vue.set(prop, 'ajax', method);
                    this.$store.dispatch(method.name, JSON.stringify(prop));
                }
                else
                    this.$emit('no_service_territory', true);
            }
        },
        updateBindServices: function (data) {
            var res = [];
            if (Array.isArray(data) && data.length > 0) {
                var currentData;
                data.forEach(function (dItem, index) {
                    currentData = dItem;
                    if (currentData.title == "Підоснова Харків" && currentData.layerIdentityProp && currentData.layerIdentityProp.title) {
                        currentData.title = currentData.layerIdentityProp.title;
                    }

                    dItem.layerIdentityProp.identityFields.forEach(function (ifItem) {
                        if (ifItem.name == 'bindToServices') {
                            var resBS = [];
                            ifItem.bindToServices.forEach(function (bsItem) {
                                //onclick="eventVue.$emit(\'showServieceObjectMap\', ' + JSON.stringify(bsItem) + ')"
                                if (bsItem.url) {
                                    var href = (window.location.pathname == '/' || window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href;
                                    bsItem.dtObject = JSON.stringify({
                                        //url: (window.location.pathname == '/' ? window.location.origin + '/opendataportal/' : window.location.href) + bsItem.url + +attributes.AR_ID ,
                                        url: (bsItem.type != 'bombshelters' ? href : '') + bsItem.url + +currentData.content.AR_ID + (bsItem.url_second_part ? bsItem.url_second_part : ''),
                                        bindToServices: bsItem,
                                        AR_ID: (currentData.content.AR_ID ? currentData.content.AR_ID : 0)
                                    });
                                    bsItem.btnClass = bsItem.type + '-btn';
                                    //btnsSTR += `<button class='` + (bsItem.type == 'bombshelters' ? 'bombshelters-btn' : 'school-btn') + `' onclick='eventVue.$emit("getServiceObjectOnMap",` + dtObject + `)'>` + bsItem.name + `</button>`;

                                    bsItem.btnsSTR = `<button class='` + bsItem.btnClass + `' onclick='eventVue.$emit("getServiceObjectOnMap",` + bsItem.dtObject + `)'>` + bsItem.name + `<span class="material-icons">launch</span></button>`;
                                    resBS.push(bsItem);
                                }
                                else {
                                    if (currentData.content[bsItem.field] != 'Null') {
                                        var service = {
                                            name: bsItem.name,
                                            GUID: currentData.content[bsItem.field],
                                            field: bsItem.field,
                                            
                                        };
                                        if (bsItem.eventName)
                                            Vue.set(service, 'eventName', bsItem.eventName);
                                        if (!currentData.content.eventServices)
                                            Vue.set(currentData.content, 'eventServices', []);
                                        currentData.content.eventServices.push(service);
                                    }
                                }
                            }.bind(this));
                            ifItem.bindToServices = resBS;
                            this.$emit('get_services', { services: { bindToServices: resBS }, fullData: dItem });
                        }
                    }.bind(this));
                    
                    res.push(dItem);
                }.bind(this));
               // return data;
            }  
           // else
                return res;
        },
        chackImages: function () {
            var img = new Image();
            img.classList.add('zf_' + this.OID);
            //если есть блоб то добавляем его в список
            img.onload = function (e) {
                this.imgs.push(e.target);
                this.outUrls.push(e.target.src);
                //isJpg = false; isPng = false;
                if (this.is_) {
                    
                    this.chackImages();
                }
                else {
                //    var boxId = e.target.getBoxId(e.target);
                //    var parent = document.querySelector('.photoBoxBtn .' + boxId),
                //        node = document.createElement('button');
                //    node.classList.add('photoBtn');
                //    node.innerHTML = '<i class="material-icons">photo_library</i >Фото';
                //    node.onclick = function () { showBlobs(null, outUrls[0]); };
                //    if (parent)
                //        parent.append(node);

                //    osbbPhotosData = { parent: parent, boxId: boxId, node: node, outUrls: outUrls };
                //    eventVue.$emit('updateInfoTamplateOSBB', osbbPhotosData);

                    this.isJpg = false; this.isPng = false;
                }
            }.bind(this)
            //если ошибка, то не грузим блоб
            img.onerror = function (e) {
                if (this.is_) {
                    if (this.outUrls.length > 0) {
                        //var boxId = e.target.getBoxId(e.target);
                        //var parent = document.querySelector('.photoBoxBtn .' + boxId),
                        //    node = document.createElement('button');
                        //node.innerHTML = '<i class="material-icons">photo_library</i >Фото';
                        //node.classList.add('photoBtn');
                        //node.onclick = function () { showBlobs(null, outUrls); };
                        ////node = document.createElement(`<button onclick="showBlobs(null, ` + outUrls[0] + `);" > <i class="material-icons">photo_library</i >Фото</button>`);
                        //if (parent)
                        //    parent.append(node);
                        //osbbPhotosData = { parent: parent, boxId: boxId, node: node, outUrls: outUrls };
                        //eventVue.$emit('updateInfoTamplateOSBB', osbbPhotosData);
                    }
                    else if (!this.isPng) {
                        //isPng = true;
                        this.is_ = true;
                        this.chackImages();
                    }
                    else
                        this.clearPhotosData();
                }
                else {

                    if (this.isJpg == this.isPng == true) {
                        this.isJpg = false;
                        this.isPng = false;
                        this.is_ = true;
                        this.chackImages();
                    }
                    else {
                        //isPng = true;
                        this.is_ = false;
                        this.chackImages();
                    }
                }
                //  document.querySelector('.photoBoxBtn').append(`<button onclick="showBlobs(` + outUrls + `);" > <i class="material-icons">photo_library</i >Фото</button>`);
            }.bind(this);

            //img.getBoxId = function (e) {
            //    var res = 0, cls;
            //    e.classList.forEach(function (cItem) {
            //        if (cItem.indexOf('zf_') >= 0)
            //            cls = cItem;
            //    }.bind(this));
            //    //res = cls.substring(3);
            //    res = cls;
            //    return res;
            //}.bind(this);

            var tp = '';
            //var href = window.location.pathname == '/' ? window.location.origin + '/opendataportal/' : window.location.href;
            if (!this.is_) {
                if (!this.isJpg) {
                    tp = '.jpg';
                    this.isJpg = true;
                }
                else {
                    tp = '.png';
                    this.isPng = true;
                }
               // img.src = (`https://smart.khmr.gov.ua/opendataportal/Images/builds/` + this.AID + tp);
                img.src = (`https://smart.khmr.gov.ua/opendataportal/Images/builds/` + this.AID + tp);
                //img.src = (href + `Images/builds/` + this.AID + `_` + this.is_num + tp);
                //img.src = (`https://cdr.citynet.kharkov.ua/opendataportal/Images/builds/` + this.AID + `_` + this.is_num + tp);
            }
            else {
                if (this.outUrls.length == 0) {
                    if (!this.isJpg) {
                        tp = '.jpg';
                        this.isJpg = true;
                        this.is_num++;
                    }
                    else {
                        tp = '.png';
                        this.isPng = true;
                        this.is_num = 1;
                    }
                }
                else {
                    if (this.isJpg && this.isPng) {
                        tp = '.png';
                        this.is_num++;
                    }
                    else {
                        tp = '.jpg';
                        this.is_num++;
                    }
                }

                img.src = (`https://smart.khmr.gov.ua/opendataportal/Images/builds/` + this.AID + `_` + this.is_num + tp);
                //img.src = (`https://cdr.citynet.kharkov.ua/opendataportal/Images/builds/` + this.AID + `_` + this.is_num + tp);

            }
        },
        clearPhotosData: function () {
            this.imgs = [],
            this.outUrls = [],
            this.outDocumUrls = [],
            this.is_num = 0,
            this.AID = -1,
            this.isJpg = false,
            this.isPng = false,
            this.OID = -1;
            this.is_ = false;
        },
        touchStartMethod: function (touchEvent) {
            if (touchEvent.changedTouches.length !== 1) { // We only care if one finger is used
                return;
            }
            let panel = document.querySelector('.identify-panel');
            let togglePanel = this.toggleIdentify;
            //let maxPanelHeit = window.innerHeight * 0.4;
            //let minPanelHeight = window.innerHeight - 70;

            const posYStart = touchEvent.changedTouches[0].clientY;

            //addEventListener('touchend', function (touchEvent) {
            //    const posYSEnd = touchEvent.changedTouches[0].clientY;
            //    if (posYStart > posYSEnd) {
            //        if (posYSEnd < maxPanelHeit) posYSEnd = maxPanelHeit;
            //        panel.style.top = posYSEnd + 'px';
            //        togglePanel();
            //    }
                
            //    if (posYStart < posYSEnd) {
            //        if (posYSEnd > maxPanelHeit) posYSEnd = minPanelHeight;
            //        panel.style.top = posYSEnd + 'px';
            //        togglePanel();
            //    };
            //}, { once: true });
            addEventListener('touchend', function (touchEvent) {
                const posYSEnd = touchEvent.changedTouches[0].clientY;
                if (posYStart != posYSEnd)
                togglePanel()
            }, { once: true });
         
        },
        startShowBlobs: function (blobs, printerUrl, titles) {
            showBlobs(blobs, printerUrl, titles, 'image');
        },
        startShowDocums: function (blobs, printerUrl, titles) {
            showPDF(printerUrl);
           // this.$refs.tgDp.showWin(printerUrl);
        },
        printIdentityData: function () {
            let element_for_print = this.$el.querySelector("div.objectDescription").cloneNode(true);
            let remove_element;
            //кнопку назад видаляємо
            remove_element = element_for_print.querySelector("button.detaile-close.identify-listBtn");
            remove_element.remove();
            //кнопки знизу та інше видаляємо
            remove_element = element_for_print.querySelector("ul ul.list-group");
            remove_element.remove();
            sessionStorage.setItem('printIdentity', element_for_print.outerHTML);
            window.open('/opendataportal/Home/Print', "_blank");
        },
        showAddressesObjectsOnMap: function () {
            eventVue.$emit('showAddressesObjectsOnMap', this.mapListAdresses.ID);
        },
        showAddressesObjectsListInPanel: function () {
            eventVue.$emit('showAddressesObjectsList', this.mapListAdresses);
        }
    },

};

//карта
osbbPhotosData = null;
const mapComponent = {   
    template: `<div id="map">
                <div id="lnbPrintContainer" style="position:absolute; visibility:collapse; z-index:-1;"></div>
                <div id="measureDiv" v-bind:style="getMeasureDivVisibility">
                    <button id="measureCloseButton" class="closeButton" v-on:click="closeMeasurment();"></button>
                    <div class="roundedCorners" id="measureWindow">
                        <div class="innerDiv roundedCorners">
                            <div id="measurementDiv"></div>
                        </div>
                    </div>
                </div>
                <listAreaAddresses-comp
                            :show="showAddressesObjectsList"
                            :addressesObjectsListType="addressesObjectsListType"
                            :objectsList="listOfObjects"
                            @toggleVisibilityListArea="showAddressesObjectsListPanel"
                            @selectObject="selectAddressesObject"
                            @zoomToMainObject="showAddressesObjectsListPanel"
                            ref="listArea">
                </listAreaAddresses-comp>
                <identify_component ref="ic2"
                    :identityFeatures="identityFeatures"
                    :showingAddressesNotFound="showingAddressesNotFound"
                    :showAddressesObjectsList="showAddressesObjectsList"
                    @select_feature_identify="addSelectGeometry"
                    @hide_feature_identify="clearCraphicLayer"
                    @get_services="getServices"
                    @goto_service_object="showServiceObject"
                    @no_service_territory="showAddressesNotFound"
                ></identify_component>
            </div>`,
    components: {
        'listAreaAddresses-comp': listAreaAddresses,
        'identify_component': APP_IDENTIFY
    },
    computed: {
        getMeasureDivVisibility() {
            var visib = store.getters.getMeasureDivVisibility ? 'visible' : 'collapse';
            return {
                'position': 'absolute',
                'right': '20px',
                'top': '150px',
                'z-index': '999',
                'visibility': visib
            };
        },
        sortedBasicsArray() {
            function compare(a, b) {
                if (a.id < b.id)
                    return -1;
                if (a.id > b.id)
                    return 1;
                return 0;
            }
            return this.basicsTemp.sort(compare);
        },
        housesStore() {
            return this.$store.getters.getHousesStore;
        },
        getUser() {
            return this.$store.getters.getUser;
        },
        getVisibileLayers() {
            return store.getters.getVisibileLayers;
        },
        getCoordinatesSelected() {
            return this.$store.getters.getCoordinatesSelected;
        },
        getCoordinatesResult() {
            return this.$store.getters.getCoordinatesResult;
        },
    },
    watch: {
        getUser(oldValue, newValue) {
            this.updateLayersDataWidthExpression();
        },

        getCoordinatesResult(newValue, oldValue ) {
            this.handlingCoordinatesResult(oldValue, newValue);
        },
    },
    data: function () {
        return {
            map: this.$store.getters.getMap,
            mapOptions: {
                //basemap: "satellite",
                zoom: 15,
                logo: false,
                fadeOnZoom: true,
                force3DTransforms: true,
                navigationMode: "css-transforms",
                infoWindow:null,
                isKeyboardNavigation: false,
                sliderPosition: "top-right",
                minScale: 115000,
                maxScale: 500,
                showLabels: true
            },
            fullExtent: null,
            widgets: null,
            navToolbar: null,
            measurement: null,
            printer:null,
            identifyTask: null,
            identifyParams: null,
            projects: this.$store.getters.getAllProjects,
            currentProject: this.$store.getters.getvisibleProject,
            QT: [], //queryTaskArray,
            IT: [], //indentofyTaskArray,
            CIT:[],
            countLayerss: 0,
            watchId: null,
            graphic: null,
            geoLayer:null,
            legendDijit: null,
            cFFeature: null,
            gFeature: null,
            addressInterval: null,
            addressOpacity: 0,
            initScales: this.$store.getters.getInitScales,
            currentClickEventData: null,
            InfoWindow: null,
            basicsTemp: [],
            showedAddressObjects: false,
            polygonHighlightSymbol: null,
            showAddressesObjectsList: false,
            listOfObjects: [],
            addressesObjectsListType: '',
            zoomToMainObjectFromList: false,
            clearInited: false,
            clickOnZKS: false,
            clickOnGraphicLayerWidthLoadData: false,
            hasClusterLayer: false,
            //----------------------------------
            identityFeatures: [],
            clusterIdentityFeatures:[],
            addingLayers: [],
            showingAddressesNotFound: false,
            lastUpdateGoogleData: null,
            //------------------
            temp_point_address_result:null, // точка адреси якщо нічого не знайдено, то показуємо її
        }
    },
    methods: {
        initMap: function (widgets) {
            //добавляем виджеты в стор
            this.$store.commit('set_arcgisWidgets', widgets);
            //получаем их из стор
            this.widgets = this.$store.getters.getArcGisWidgets;

            //добавляем попап в свойства карты
            //this.mapOptions.infoWindow = this.popup;
            //this.InfoWindow = new this.widgets.InfoWindow({}, this.widgets.domConstruct.create("div"));
            //this.InfoWindow.startup();
            //this.mapOptions.infoWindow = this.InfoWindow;

            //добавляем в вебдокпроф 
            //this.$store.commit('set_webdocprofExpression');
            //создаем карту
            this.map = new widgets.Map("map", this.mapOptions);
            //this.$store.commit('set_map', this.map);
            this.map.on("layers-add-result", function (evt) {

            });
            //добавляем слои подложки
            //var basics = ;

            //this.map.addLayer();
            this.$store.getters.getBasics.forEach(function (item) {
                if (!item.token.need || (item.token.need && item.token.str != ''))
                    this.createLayer(item, widgets);
                //this.createLayer(this.$store.getters.getVisibleBasis[0], widgets);
            }.bind(this));

            this.addBasics();

            this.countLayerss++;
            this.initLegend();
            //устанавливаем екстент
            this.fullExtent = this.createExtent(this.$store.getters.getFullExtent);
            //new window.esri.geometry.Extent(, new window.esri.SpatialReference({ wkid: 28467 }));
            //this.map.setExtent(this.fullExtent);
            this.zoomToExtent(this.fullExtent);
            //подключаем тулбар
            this.onNavToolbar();

            this.polygonHighlightSymbol = new this.widgets.SimpleFillSymbol(
                this.widgets.SimpleFillSymbol.STYLE_SOLID,
                new this.widgets.SimpleLineSymbol(
                    this.widgets.SimpleLineSymbol.STYLE_SOLID,
                    new this.widgets.Color([255, 0, 0]), 3
                ),
                new this.widgets.Color([125, 125, 125, 0.35])
            );
            //создаем линейку
            this.measurement = new this.widgets.Measurement({
                map: this.map,
                defaultAreaUnit: this.widgets.Units.SQUARE_METERS,
                defaultLengthUnit: this.widgets.Units.METERS
            }, this.widgets.dom.byId("measurementDiv"));
            this.measurement.startup();
            this.measurement.hideTool("location");
            //создаем принтер
            this.printer = new this.widgets.Print({
                map: this.map,
                url: "https://smart.khmr.gov.ua/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task",
                templates: [{
                    format: "png32",
                    layout: "A4 Portrait",
                    exportOptions: {
                        width: 1027,
                        height: 768,
                        dpi: 96
                    },
                    preserveScale: true
                }]
            }, this.widgets.dom.byId("lnbPrintContainer"));
            this.printer.startup();
            this.printer.on('print-start', function (evt) {
                this.$store.commit('set_isSearcherInit', false);
            }.bind(this));
            this.printer.on('print-complete', function (evt) {
                //window.open(evt.result.url, '_blank');
                showBlobs(null, evt.result.url);
                this.$store.commit('set_isSearcherInit', true);
                    setTimeout(function () {
                        this.reInitEsriPrint();
                    }.bind(this), 2000);
            }.bind(this));
            this.printer.on('error', function (evt) {
                this.$store.commit('set_isSearcherInit', true);
                eventVue.$emit('showSimpleMessage', evt);                    
            }.bind(this));
            //добавляем все проекты
            //this.addAllProjects();
            this.updateIT();
            //подписки
            eventVue.$on('zoomToSearchObject', async(data) => {
                if (data.currentResult) {
                    this.temp_point_address_result = null;
                    var delta = this.$store.getters.getExtentDelta,
                        extent, where;
                    if (data.type == 'address') {
                        try {
                            let long = data.currentResult.longitude,
                                lati = data.currentResult.latitude;
                            const res = await axios.post('/opendataportal/Home/ConvertToLocalCoordinates?longitudes=' + long + '&latitudes=' + lati);
                            if (Array.isArray(res.data) && !isNaN(res.data[0].x) && !isNaN(res.data[0].y)) {
                                data.currentResult.local_X = res.data[0].x;
                                data.currentResult.local_Y = res.data[0].y;
                                this.temp_point_address_result = { ...data.currentResult };
                            }
                        }
                        finally{
                            where = data.currentResult.Id;
                            this.updateQT('searcher');
                            this.searchObjects(null, where);
                        }
                      //  extent = this.createExtent([data.currentResult.local_X - delta, data.currentResult.local_Y - delta, data.currentResult.local_X + delta, data.currentResult.local_Y + delta]);
                     //   this.zoomToExtent(extent);
                        //this.addressOpacity = 1;
                        //this.addressInterval = setInterval(function () {
                        //    this.addressOpacity -= 0.1;
                        //    var pt = new this.widgets.Point(data.currentResult.local_X, data.currentResult.local_Y);
                        //    var symbol = new this.widgets.SimpleMarkerSymbol(
                        //        this.widgets.SimpleMarkerSymbol.STYLE_CIRCLE,
                        //        70,
                        //        new this.widgets.SimpleLineSymbol(
                        //            this.widgets.SimpleLineSymbol.STYLE_SOLID,
                        //            new this.widgets.Color([232, 12, 12, this.addressOpacity]),
                        //            3
                        //        ),
                        //        new this.widgets.Color([232, 12, 12, 0])
                        //    );
                        //    var graphic = new this.widgets.Graphic(pt, symbol);
                        //    this.clearCraphicLayer();
                        //    this.addGraphic(graphic);                                                       
                        //}.bind(this), 300);
                        //setTimeout(function () {
                        //    clearInterval(this.addressInterval);
                        //    this.clearCraphicLayer();
                        //}.bind(this), 3000);


                    }
                    else if (data.type == 'street') {
                        //extent = this.createExtent([data.currentResult.leftTopX - delta, data.currentResult.rightBottomY - delta, data.currentResult.rightBottomX + delta, data.currentResult.leftTopY + delta]);
                        //extent = this.createExtent([data.currentResult.leftBottomX - delta, data.currentResult.leftBottomY - delta, data.currentResult.rightTopX + delta, data.currentResult.rightTopY + delta]);

                        //extent = this.createExtent([data.currentResult.leftBottomX - delta, data.currentResult.leftBottomY - delta, data.currentResult.rightTopX + delta, data.currentResult.rightTopY + delta]);
                        //this.zoomToExtent(extent);

                        where = data.currentResult.typeName + ' ' + data.currentResult.streetName;
                        this.updateQT('searcher');
                        this.searchObjects(null, where);
                    }
                }
            });

            this.map.on('click', function (e) {
                //this.clickMapExecute(e);
                this.showedAddressObjects = false;
                if (this.showAddressesObjectsList)
                    this.showAddressesObjectsListPanel();
               // this.hideInfowindow();
                this.$store.commit('clearAddressObjectsList');
                eventVue.$emit('mapOnClick', e);
            }.bind(this));
            //!!!
            this.map.on('zoom-end', function (e) {
                //this.clickMapExecute(e);
                //this.hideInfowindow();
                this.updateIT();
                //this.setMinMaxScale();
                if (!this.lastUpdateGoogleData || ((this.lastUpdateGoogleData - new Date().getTime()) > 60000)) {
                    this.$emit('updateGoogleData', e);
                    this.lastUpdateGoogleData = new Date().getTime();
                }
            }.bind(this));

            let p = false;
            this.map.on('mouse-wheel', function (e) {
                if (this.map.getScale() >= (this.map.getMinScale() - this.map.getMinScale() / 10) && !p) {
                    e.preventDefault();
                    p = true;
                  // this.zoomToExtent(this.fullExtent);

                }
            }.bind(this));

            this.map.on('update-end', function (e) {
                if (!this.lastUpdateGoogleData || ((new Date().getTime() - this.lastUpdateGoogleData) > 60000)) {
                    this.$emit('updateGoogleData', e);
                    this.lastUpdateGoogleData = new Date().getTime();
                }
            }.bind(this));

            this.map.on('extent-change', function (event) {
                if (this.map.getScale() >= (this.map.getMinScale() - this.map.getMinScale() / 10) && p) {
                    //e.preventDefault();
                    setTimeout(function () {
                        this.zoomToExtent(this.fullExtent);
                        p = false;
                    }.bind(this), 300);

                }
                else {
                    //edge where it moved out
                    var currentCenter = this.map.extent.getCenter();
                    if (!this.fullExtent.contains(currentCenter) &&
                        event.delta && event.delta.x !== 0 && event.delta.y !== 0) {

                        var newCenter = this.map.extent.getCenter();

                        //check each side of the initial extent and if the 
                        //current center is outside that extent, 
                        //set the new center to be on the edge that it went out on
                        if (currentCenter.x < this.fullExtent.xmin) {
                            newCenter.x = this.fullExtent.xmin;
                        }
                        if (currentCenter.x > this.fullExtent.xmax) {
                            newCenter.x = this.fullExtent.xmax;
                        }
                        if (currentCenter.y < this.fullExtent.ymin) {
                            newCenter.y = this.fullExtent.ymin;
                        }
                        if (currentCenter.y > this.fullExtent.ymax) {
                            newCenter.y = this.fullExtent.ymax;
                        }
                        this.map.centerAt(newCenter);
                    }
                }
                
            }.bind(this));


            //this.map.infoWindow.on('hide', function () {
            //    this.showedAddressObjects = false;
            //    this.gFeature = this.map.graphics.graphics.find(x =>  x.symbol );
            //    this.clearCraphicLayer();
            //    this.clearClusterLayer();
            //    //this.$store.commit('clearAddressObjectsList');
            //    //this.updateIT();

            //}.bind(this));

            //this.map.infoWindow.on("selection-change", function (e) {

            //    //setTimeout(function () {
            //        this.removeAddressObjectsFromGraphicLayer();
            //    //}.bind(this), 1000);

            //    var point = this.map.infoWindow.getSelectedFeature(),
            //        pop = document.getElementsByClassName('esriPopupVisible');

            //    if (point && point.geometry && point.geometry.type == 'point' && pop && pop.length > 0 && !pop[0].classList.contains('esriPopupMaximized')) {
            //        var pt = new this.widgets.screenUtils.toScreenPoint(this.map.extent, this.map.width, this.map.height, point.geometry);
            //        document.getElementsByClassName('esriPopup')[0].style.left = pt.x+'px';
            //        document.getElementsByClassName('esriPopup')[0].style.top = pt.y + 'px';
            //        if (document.getElementsByClassName('esriPopupVisible').length > 0 )
            //            this.repositionInfoWindow(pt, point.geometry);

            //    }


            //if (osbbPhotosData)
            //    this.updateInfoTamplateOSBB(osbbPhotosData);
            //}.bind(this));

            if (this.initScales)
                this.zoomToExtent(this.createExtent(this.initScales.extent));
            //устанавливаем что карта поринициализирована
            this.$store.commit('set_isMapInit', true);
        },
        //Layer-------------------------------------
        createLayer_old: function (properties, widgets) {
            if (properties.type == 'wms' || (properties.type == 'feature' && properties.loadMethod))
                this.buildLayer(properties);
            else {
                var layer, layer2, type,
                    url = (properties.type == 'feature' || properties.type == 'dynamic' || (properties.cluster && properties.cluster.on)) ? properties.url + '/' + properties.layerIds[0] : properties.url,
                    url2 = url + ((properties.token && properties.token.need && properties.token.str != '') ? '?token=' + properties.token.str : '');
                this.widgets.esriRequest({
                    url: url2,
                    content: {
                        f: 'json'
                    },
                    handleAs: 'json',
                    properties: properties
                })
                    .then(function (response) {
                        this.widgets.esriRequest({
                            url: url + '/query?where=' + (properties.expression ? properties.expression.string : '1=1') + ((properties.token && properties.token.need && properties.token.str != '') ? '&token=' + properties.token.str : ''),
                            content: {
                                f: 'json'
                            },
                            handleAs: 'json',
                            properties: properties
                        }).then(function (response) {
                            if ((response.features && response.features.length > 0) || (response.layers && response.layers.length > 0)) {
                                this.buildLayer(properties);
                            }
                            else if ((response.features && response.features.length == 0) || (response.layers && response.layers.length == 0)) {
                                eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.hasNoData);
                                eventVue.$emit('toggleLayer', properties.id);
                            }
                            else
                                this.layerErrorMessage(properties.id);
                        }.bind(this))
                            .catch(function (error) {
                                if (error.stack.toLowerCase().indexOf('error') >= 0) {
                                    //eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.serverError);
                                    //eventVue.$emit('toggleLayer', properties.id);
                                    this.layerErrorMessage(properties.id);
                                }
                            }.bind(this));
                        //---------------------                
                    }.bind(this))
                    .catch(function (error) {
                        if (error.stack.toLowerCase().indexOf('error') >= 0) {
                            //eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.serverError);
                            //eventVue.$emit('toggleLayer', properties.id);
                            this.layerErrorMessage(properties.id);
                        }
                    }.bind(this));
            }
        },
        createLayer: function (properties, widgets) {
                store.commit('set_isSearcherInit', false);
                this.addingLayers.push(properties.id);
                //console.log('createLayer; arr = ' + this.addingLayers.join(','));

                //проверка гугл оновлень
                if (properties.checkUpdate) {
                    if (!this.lastUpdateGoogleData)
                        this.lastUpdateGoogleData = new Date().getTime();
                   // console.log(this.lastUpdateGoogleData);
                    this.$store.dispatch(properties.checkUpdate.method, { url: properties.checkUpdate.url, properties: properties });
                }
                //якщо 
                else if (['wms', 'basemap'].includes(properties.type)  || (properties.type == 'feature' && properties.loadMethod && !properties.cluster))
                    this.buildLayer(properties);
                else if (properties.type == 'feature' && properties.loadMethod && properties.cluster && (!properties.features || (Array.isArray(properties.features) && !properties.features.length === 0))) {
                    this.loadFeatures(properties);
                }
                   
                else {
                    var layer, layer2, type,
                        url = (properties.type == 'feature' || properties.type == 'dynamic' || (properties.cluster && properties.cluster.on)) ? properties.url + '/' + properties.layerIds[0] : properties.url,
                        url2 = url + ((properties.token && properties.token.need && properties.token.str != '') ? '?token=' + properties.token.str : '');
                    //this.widgets.esriRequest({
                    //    url: url2,
                    //    content: {
                    //        f: 'json'
                    //    },
                    //    handleAs: 'json',
                    //    properties: properties
                    //})
                    axios.get(url2, {
                        content: {
                            f: 'json'
                        },
                        handleAs: 'json',
                        properties: properties})
                        .then(function (response) {
                            this.buildLayer(properties);
                            this.closeLoaderByAddingLayers();

                            //this.widgets.esriRequest({
                            //    url: url + '/query?where=' + (properties.expression ? properties.expression.string : '1=1') + ((properties.token && properties.token.need && properties.token.str != '') ? '&token=' + properties.token.str : ''),
                            //    content: {
                            //        f: 'json'
                            //    },
                            //    handleAs: 'json',
                            //    properties: properties
                            //})
                            //.then(function (response) {
                            //    if ((response.features && response.features.length > 0) || (response.layers && response.layers.length > 0)) {
                            //        this.buildLayer(properties);
                            //    }
                            //    else if ((response.features && response.features.length == 0) || (response.layers && response.layers.length == 0)) {
                            //        eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.hasNoData);
                            //        eventVue.$emit('toggleLayer', properties.id);
                            //        this.removeFromAddingLayers(properties.id);

                            //    }
                            //    else
                            //        this.layerErrorMessage(properties.id);
                            //    this.closeLoaderByAddingLayers();
                            //}.bind(this))
                            //.catch(function (error) {
                            //    if (error.stack.toLowerCase().indexOf('error') >= 0) {
                            //        //eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.serverError);
                            //        //eventVue.$emit('toggleLayer', properties.id);
                            //        this.removeFromAddingLayers(properties.id);
                            //        this.layerErrorMessage(properties.id);
                            //        this.closeLoaderByAddingLayers();
                            //    }
                            //}.bind(this));

                            //---------------------                
                        }.bind(this))
                        .catch(function (error) {
                            if (error.stack.toLowerCase().indexOf('error') >= 0) {
                                //eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.serverError);
                                //eventVue.$emit('toggleLayer', properties.id);
                                this.removeFromAddingLayers(properties.id);
                                this.layerErrorMessage(properties.id);
                                this.closeLoaderByAddingLayers();
                            }
                        }.bind(this));
                }
        },
        buildLayer: function (properties) {
            var layer, layer2, type,
                url = properties.url;

            if (properties.cluster && properties.cluster.on && !properties.loadMethod) { 
                url += '/' + properties.layerIds[0];

            }
            if (properties.token && properties.token.need && properties.token.str != '')
                url += '?token=' + properties.token.str;

            if (properties.cluster && properties.cluster.on && !properties.loadMethod) {
                var singleRenderer = null,
                    singleSymbol= new this.widgets.PictureMarkerSymbol({
                        "angle": 0, "xoffset": 0, "yoffset": -3, "type": "esriPMS",
                        "url": "/opendataportal/Images/default_" + properties.id + ".svg",
                        "contentType": "image/svg", "width": properties.cluster.size[0], "height": properties.cluster.size[1]
                    });
                if (properties.typesColors ) {
                    if (properties.typesColors.fieldName) {
                        singleRenderer = new this.widgets.UniqueValueRenderer(null, properties.typesColors.fieldName, null, null, ":");
                        properties.typesColors.types.forEach(function (tItem) {
                            singleRenderer.addValue({
                                value: tItem.value,
                                symbol: new this.widgets.PictureMarkerSymbol({
                                    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                                    "url": "/opendataportal/Images/default_" + properties.id + "_" + tItem.value1 + tItem.ext,
                                    "contentType": "image/png", "width": properties.iconSize.width, "height": properties.iconSize.height
                                }),
                                label: tItem.desc,
                                description: tItem.desc
                            });
                          //  console.log("/opendataportal/Images/default_" + properties.id + "_" + tItem.value1 + (tItem.value2 ? ("_" + tItem.value2) : "") + tItem.ext);
                        }.bind(this));
                    }
                }
                layer = new this.widgets.ClusterLayer({
                    //url: properties.url + '/' + properties.layerIds[0],
                    url: url,
                    distance: 70,
                   // id: 'layer' + (this.CIT.length + 1) * 100,
                   // id: 'layer' + properties.id,
                    //id: this.getClusterLayerID(properties.id), // отето метод создания леер ид
                    where: properties.expression ? properties.expression.string : '',
                    labelColor: "#FFF",
                    labelOffset: -5,
                    resolution: this.map.extent.getWidth() / this.map.width,
                    spatialReference: new window.esri.SpatialReference({ wkid: 28467 }),
                    outFields: ["*"],
                    //singleSymbol: new this.widgets.PictureMarkerSymbol({
                    //    "angle": 0, "xoffset": 0, "yoffset": -3, "type": "esriPMS",
                    //    "url": "/opendataportal/Images/default_" + properties.id + ".svg",
                    //    "contentType": "image/svg", "width": properties.cluster.size[0], "height": properties.cluster.size[1]
                    //}),
                    singleRenderer: singleRenderer,
                    singleSymbol: singleRenderer ? null : singleSymbol,
                    //"zoomOnClick": true,
                    //"showSingles": true,
                    //clusterRatio: 75,
                    //disablePopup: false
                    "zoomOnClick": true,
                    "showSingles": true,
                    clusterRatio: 75,
                    disablePopup: false,
                    maxSingles: 50
                });
                var defaultPointSymbol = new this.widgets.PictureMarkerSymbol({
                    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                    "url": "/opendataportal/Images/toc_form_icon_1.png",
                    "contentType": "image/svg", "width": 16, "height": 16
                });

                var renderer = new this.widgets.ClassBreaksRenderer(defaultPointSymbol, "clusterCount");
                for (var i = 0; i < properties.cluster.options.length; i++) {
                    var symbol = new this.widgets.SimpleMarkerSymbol(this.widgets.SimpleMarkerSymbol.STYLE_CIRCLE,
                        properties.cluster.options[i].radius,
                        new this.widgets.SimpleLineSymbol(this.widgets.SimpleLineSymbol.STYLE_SOLID, new this.widgets.Color(properties.cluster.options[i].line.lineColor), properties.cluster.options[i].line.width),
                        new this.widgets.Color(properties.cluster.options[i].fillColor));
                    if (i + 1 == properties.cluster.options.length)
                        renderer.addBreak(properties.cluster.options[i].countFeatures, Infinity, symbol);
                    else
                        renderer.addBreak(properties.cluster.options[i].countFeatures, properties.cluster.options[i + 1].countFeatures - 1, symbol);
                }

                layer.setRenderer(renderer);
                layer.on('cluster-click', function (e) {
                   // var layerProperties = this.$store.getters.geLayerById(e.point.graphic.getLayer()._attrs.id);
                    //if (layerProperties.id == 1)
                    //    setTimeout(function () { this.map.setScale(this.map.getScale() - 2); }.bind(this), 5);
                    //else {
                        
                    //}
                    //var features
                    this.clusterIdentityFeatures = [];
                    this.map.setScale(this.map.getScale() - 10);
                    this.clearCraphicLayer();
                    var layerProperties = this.$store.getters.geLayerById(e.point.graphic.getLayer()._attrs.id);
                    this.clearIdentityFeatures();
                    this.hasClusterLayer = true;
                    var obj = e.point;
                        obj.isCluster = true;
                    this.cFFeature = e.features;
                    this.currentClickEventData = e.point;
                   
                        this.cFFeature.forEach(function (cfItem, index, array) {
                            var cFeatureTemplate,
                                resInfo = JSON.parse(JSON.stringify(Object.assign({}, cfItem.attributes))),
                                layerInfoId = layerProperties.layerIds.length == 1 ? layerProperties.layerIds[0] : layerProperties.id;
                            resInfo.layerName = cfItem.getLayer()._attrs.name;
                            resInfo.feature = cfItem;
                            cFeatureTemplate = this.createInfoTemplate(resInfo, layerProperties);
                            //дата в рекламе
                            if (resInfo.PERMIT_VALID) {
                                var newDate = new Date(resInfo.PERMIT_VALID),
                                    date = newDate.getDate(),
                                    month = newDate.getMonth() + 1,
                                    year = newDate.getFullYear();
                                resInfo.PERMIT_VALID = date + '.' + (month < 10 ? ('0' + month) : month) + '.' + year;
                            }
                            var outObject = {
                                title: layerProperties.name,
                                content: resInfo,
                                feature: cfItem,
                                layerIdentityProp: this.getLayerIdentityPropertiesById(layerInfoId, layerProperties, resInfo.layerName),
                                //contentTable: cFeatureTemplate.content
                            };
                            //this.identityFeatures.push(outObject);
                            this.clusterIdentityFeatures.push(outObject);

                          //  this.addSelectGeometry([{ feature: cfItem, geometryType: cfItem.geometryType, layerName: resInfo.layerName }], cFeatureTemplate);
                    }.bind(this));


                    
                    this.map.setScale(this.map.getScale() - 1);
                    this.clickMapExecute(e.point);
                    
                    //--------------------------------------------------------------
                        //qGeom = this.getSearchExtent(e.point.mapPoint);
                        //this.identifyObjects(e.point.mapPoint, qGeom, e.point.screenPoint);

                        //if (layerProperties.identify[0].controller)
                        //    this.getFeaturesInfo(layerProperties.identify[0].method, e);
                        //else
                        //    this.showInfoWindow(null, e.target._attrs);
                    
                    //else {
                    //    this.hideInfowindow();
                    //    this.clearClusterLayer();
                    //}
                }.bind(this));
                layer.on('needRepositionInfoWindow', function (e) {
                    this.repositionInfoWindow();
                }.bind(this));

                layer.attr('isCluster', true);
                layer.attr('isLoadData', false);
                layer.attr('initUrl', properties.url);
                layer.attr('layerIds', properties.layerIds);
            }
            else if (properties.cluster && properties.cluster.on && properties.loadMethod) {
                    
                var renderer;

                var defaultPointSymbol = new this.widgets.PictureMarkerSymbol({
                    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                    "url": "/opendataportal/Images/default_" + properties.id + ".svg",
                    "contentType": "image/svg", "width": 16, "height": 16
                });

                var defaultPointHighlightSymbol = new this.widgets.PictureMarkerSymbol({
                    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                    "url": "/opendataportal/Images/select_" + properties.id + ".svg",
                    "contentType": "image/svg", "width": 16, "height": 16
                });

                var infoTemplate = new this.widgets.InfoTemplate(), content = '<table>';
                infoTemplate.setTitle("<b>" + properties.identify[0].title + "</b>");
                for (var i = 0; i < properties.identify[0].identityFields.length; i++) {                   
                    if (properties.identify[0].identityFields[i].name == 'BLOB_URL')
                        content += '<tr><td colspan="2" class="blobTD_${id}" style="padding:0; width: 100%; min-height: 200px; height: auto;"><div class="img-wrapper">${BLOB_URL:createHref}</div></td></tr>';
                    else
                        content += '<tr><td>' + properties.identify[0].identityFields[i].description + '</td><td>${' + properties.identify[0].identityFields[i].name + '}</td></tr>';
                }
                content += '</table>';
                infoTemplate.setContent(content);

                createHref = function (value, key, data) {
                    if (value) {
                        var img = new Image();

                        //если есть блоб то добавляем его в список
                        img.onload = function (e) {
                            var parent = document.querySelector('.blobTD_' + data.id),
                                parentChildCollect = parent.children,
                                imgWrapper,
                                //imgWrapper = parentChildCollect[0],
                                node = document.createElement('img');
                            //node.style.width = '300px';
                            node.src = e.path[0].currentSrc; //.replace('https', 'http')
                            node.onclick = function () { showBlobs(null, e.path[0].currentSrc); };

                            for (i = 0; i < parentChildCollect.length; i++) {
                                if (parentChildCollect[i].classList.contains("img-wrapper"))
                                    imgWrapper = parentChildCollect[i];
                                    imgWrapper.style.height = '200px';
                            }

                            if (parent && imgWrapper) {       
                                
                                imgWrapper.append(node);
                                //parent.append(node);
                                
                            }
                            setTimeout(function () {
                                eventVue.$emit('repositionInfoWindow');
                            }.bind(this), 30);

                        }

                        //img.onerror = function (e) {
                        //    var T = '';
                        //}
                        img.src = (`/opendataportal/home/DownloadBlob?url=` + encodeURI(`http://arch.kharkov.ua` + value));
                      //  img.src = (`https://smart.khmr.gov.ua/opendataportal/Home/Blob?id=229174`);
                    }
                    else return '';
                }

                layer = new this.widgets.ClusterLayer2({
                    //url: properties.url + '/' + properties.layerIds[0],
                    data: properties.features,
                    distance: 100,
                    //id: 'graphicsLayer' + properties.id,
                    id: this.getClusterLayerID(properties.id),
                    where: properties.expression ? properties.expression.string : '',
                    labelColor: "#FFF",
                    labelOffset: -5,
                    resolution: this.map.extent.getWidth() / this.map.width,
                    spatialReference: new window.esri.SpatialReference({ wkid: 28467 }),
                    outFields: ["*"],
                    singleSymbol: defaultPointSymbol,
                    //"zoomOnClick": true,
                    "showSingles": true,
                    clusterRatio: 75,
                    disablePopup: false,
                    "singleTemplate": infoTemplate
                });

                var renderer = new this.widgets.ClassBreaksRenderer(defaultPointSymbol, "clusterCount");
                for (var i = 0; i < properties.cluster.options.length; i++) {
                    var symbol = new this.widgets.SimpleMarkerSymbol(this.widgets.SimpleMarkerSymbol.STYLE_CIRCLE,
                        properties.cluster.options[i].radius,
                        new this.widgets.SimpleLineSymbol(this.widgets.SimpleLineSymbol.STYLE_SOLID, new this.widgets.Color(properties.cluster.options[i].line.lineColor), properties.cluster.options[i].line.width),
                        new this.widgets.Color(properties.cluster.options[i].fillColor));
                    if (i + 1 == properties.cluster.options.length)
                        renderer.addBreak(properties.cluster.options[i].countFeatures, Infinity, symbol);
                    else
                        renderer.addBreak(properties.cluster.options[i].countFeatures, properties.cluster.options[i + 1].countFeatures - 1, symbol);
                }
                layer.setRenderer(renderer);
                layer.attr('isCluster', true);
                layer.attr('isLoadData', true);
                layer.on('click', function (e) {
                    this.currentClickEventData = e;
                }.bind(this));

            }
            else if (!properties.cluster  && properties.loadMethod) {

                var renderer;

                var defaultPointSymbol = new this.widgets.PictureMarkerSymbol({
                    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                    "url": "/opendataportal/Images/default_" + properties.id + ".png",
                    "contentType": "image/png", "width": properties.iconSize.width, "height": properties.iconSize.height
                });

                var defaultPointHighlightSymbol = new this.widgets.PictureMarkerSymbol({
                    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                    "url": "/opendataportal/Images/select_" + properties.id + ".png",
                    "contentType": "image/png", "width": properties.selectIconSize.width, "height": properties.selectIconSize.height
                });


                //пересоздаем фичи
                var features = [];

                properties.features.forEach(function (item) {
                    var attr = item.attributes,
                        geometry = new this.widgets.Point(item.geometry.x, item.geometry.y, new window.esri.SpatialReference({ 'wkid': 28467 }));
                    var graphic = new this.widgets.Graphic(geometry);
                    graphic.setAttributes(attr);
                    features.push(graphic);
                }.bind(this));

                properties.features = [];
                properties.features = features;

                var featureCollection = {
                    "layerDefinition": {
                        "geometryType": "esriGeometryPoint",
                        "objectIdField": properties.identify[0].objectIdField,
                    },
                    "featureSet": {
                        "features": features,
                        "geometryType": "esriGeometryPoint"
                    }
                };

                layer = new this.widgets.FeatureLayer(featureCollection, {
                    outFields: ['*'],
                    webglEnabled:true,
                });

                if (properties.typesColors) {
                    renderer = new this.widgets.UniqueValueRenderer(null, properties.typesColors.fieldName, properties.typesColors.fieldName2, null, ":");
                    properties.typesColors.types.forEach(function (tItem) {
                        renderer.addValue({
                            value: tItem.value,
                            symbol: new this.widgets.PictureMarkerSymbol({
                                "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                                "url": "/opendataportal/Images/default_" + properties.id + "_" + tItem.value1 + (tItem.value2 ? ("_" + tItem.value2) : "") + tItem.ext,
                                "contentType": "image/png", "width": properties.iconSize.width, "height": properties.iconSize.height
                            }),
                            label: tItem.desc,
                            description: tItem.desc
                        });
                        //console.log("/opendataportal/Images/default_" + properties.id + "_" + tItem.value + ".png");
                    }.bind(this));
                }
                else {

                    renderer = new this.widgets.SimpleRenderer({
                        type: "simple",
                        symbol: defaultPointSymbol
                    });
                }

                layer.setRenderer(renderer);
                //layer.setInfoTemplate(infoTemplate);
                layer.attr('isCluster', false);
                layer.attr('isLoadData', true);
                layer.on('click', function (e) {
                    this.currentClickEventData = e;
                }.bind(this));

            }
            else {               
                if (type == 'tile' || properties.type == 'tile') {
                    layer = new this.widgets.Tiled(url, { opacity: properties.opacity });
                }
                else if (type == 'wms' || properties.type == 'wms') {
                    layer = new this.widgets.WMSLayer("https://map.land.gov.ua/geowebcache/service/wms?tiled=true", {
                        format: "png",
                        resourceInfo: {
                            copyright: "KADASTR",
                            description: "Africa Wind Data",
                            extent: new this.widgets.Extent(-180, -90, 180, 90, { wkid: 4326 }),
                            layerInfos: [
                                new this.widgets.WMSLayerInfo({
                                    name: "kadastr",
                                    queryable: true,
                                    showPopup: true
                                })
                            ],
                            spatialReferences: [28467],
                            version: "1.1.1"
                        },
                        WIDTH: 256,
                        HEIGHT: 256,
                        version: "1.1.1",
                        visibleLayers: [
                            "kadastr"
                        ]
                    });
                }
                else if (type == 'geometry' || properties.type == 'geometry') {
                    layer = new this.widgets.GeometryService(url);
                }
                else if (type == 'dynamic' || properties.type == 'dynamic') {

                    if (properties.dataType == 'layer') {
                        layer = new this.widgets.ArcGISDynamicMapServiceLayer(url, {
                            "opacity": (properties.opacity >= 0 ? properties.opacity : 1),
                        });
                        layer.setVisibleLayers(properties.layerIds);
                    }
                    else
                        layer = new this.widgets.ArcGISDynamicMapServiceLayer(url, { opacity: (properties.opacity >= 0 ? properties.opacity : 1) });
                }
                else if (type == 'feature' || properties.type == 'feature') {
                    if (properties.geometryType == 'Point') {
                        var renderer;

                        layer = new this.widgets.FeatureLayer(properties.url + '/' + properties.layerIds[0], {
                            outFields: ['*'],
                            mode : this.widgets.FeatureLayer.MODE_SNAPSHOT
                        });

                        var w = 16, h = 16;
                        if (properties.id == 4) {
                            h = 36; w = 18;
                        }
                        else if (properties.id == 41 || properties.id == 25 || properties.id == 26 || properties.id == 28 || properties.id == 29 || properties.id == 30 ||
                            properties.id == 31 || properties.id == 32 || properties.id == 33 || properties.id == 34 || properties.id == 35 || properties.id == 36 ||
                            properties.id == 37 || properties.id == 38 || properties.id == 39 || properties.id == 40) {
                            h = 30; w = 30;
                        }

                        var defaultPointSymbol = new this.widgets.PictureMarkerSymbol({
                            "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                            "url": "/opendataportal/Images/default_" + properties.id + ".svg",
                            "contentType": "image/svg", "width": w, "height": h
                        });
                       
                        var defaultPointHighlightSymbol = new this.widgets.PictureMarkerSymbol({
                            "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                            "url": "/opendataportal/Images/select_" + properties.id + ".svg",
                            "contentType": "image/svg", "width": w, "height": h
                        });

                        if (properties.typesColors) {
                            if (properties.typesColors.fieldName && !properties.typesColors.fieldName2) {
                                renderer = new this.widgets.UniqueValueRenderer(null, properties.typesColors.fieldName, null, null, ":");
                                properties.typesColors.types.forEach(function (tItem) {
                                    var url;

                                    if (properties.id == 41) {
                                        var VAL =( tItem.value1 == "Null" || tItem.value1 == null )? ("в режимі \"очікування\"").replaceAll('"', '') : tItem.value1.replaceAll('"', '');
                                        url = "/opendataportal/Images/default_" + properties.id + "_" + VAL + tItem.ext;
                                    }
                                    else
                                        url = "/opendataportal/Images/default_" + properties.id + "_" + tItem.value.toString().replaceAll('"', '') + tItem.ext;
                                    //"url": "/opendataportal/Images/default_" + properties.id + "_" + tItem.value + ".svg",
                                    renderer.addValue({
                                        value: tItem.value,
                                        symbol: new this.widgets.PictureMarkerSymbol({
                                            "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                                            "url": url,
                                            "contentType": "image/png", "width": properties.iconSize.width, "height": properties.iconSize.height
                                        }),
                                        label: tItem.desc,
                                        description: tItem.desc
                                    });
                                   // console.log("/opendataportal/Images/default_" + properties.id + "_" + tItem.value1 + (tItem.value2 ? ("_" + tItem.value2) : "") + tItem.ext);
                                }.bind(this));
                            }
                            else if (properties.typesColors.fieldName && properties.typesColors.fieldName2) {
                                renderer = new this.widgets.UniqueValueRenderer(null, properties.typesColors.fieldName, properties.typesColors.fieldName2, null, ":");
                                properties.typesColors.types.forEach(function (tItem) {
                                    renderer.addValue({
                                        value: tItem.value,
                                        symbol: new this.widgets.PictureMarkerSymbol({
                                            "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                                            "url": "/opendataportal/Images/default_" + properties.id + "_" + tItem.value1 + (tItem.value2 ? ("_" + tItem.value2) : "") + tItem.ext,
                                            "contentType": "image/png", "width": properties.iconSize.width, "height": properties.iconSize.height
                                        }),
                                        label: tItem.desc,
                                        description: tItem.desc
                                    });
                                   // console.log("/opendataportal/Images/default_" + properties.id + "_" + tItem.value1 + (tItem.value2 ? ("_" + tItem.value2) : "") + tItem.ext);
                                }.bind(this));
                            }
                            else {
                                renderer = new this.widgets.UniqueValueRenderer(null, properties.typesColors.fieldName);
                                properties.typesColors.types.forEach(function (tItem) {
                                    renderer.addValue({
                                        value: tItem.value,
                                        symbol: new this.widgets.PictureMarkerSymbol({
                                            "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                                            "url": "/opendataportal/Images/default_" + properties.id + "_" + tItem.value + ".svg",
                                            "contentType": "image/svg", "width": 16, "height": 16
                                        }),
                                        label: tItem.desc,
                                        description: tItem.desc
                                    });
                                    //console.log("/opendataportal/Images/default_" + properties.id + "_" + tItem.value + ".svg");
                                }.bind(this));
                            }
                        }
                        else {
                            renderer = new this.widgets.SimpleRenderer({
                                type: "simple",
                                symbol: defaultPointSymbol
                            });
                        }
                        layer.setRenderer(renderer);
                        layer.setSelectionSymbol(defaultPointHighlightSymbol);
                        //layer.attr('mode',this.widgets.FeatureLayer.MODE_SNAPSHOT);
                    }

                    else
                        layer = new this.widgets.FeatureLayer(properties.url + '/' + properties.layerIds[0]);
                }
                else if (type == 'basemap' || properties.type == 'basemap') {

                    layer = new this.widgets.BasemapLayer({
                        url: properties.url,
                        type: "VectorTileLayer"
                    });
                }
                //if (layer && properties.expression) {
                //    var expression = this.getExpression(properties);
                //    if (type == 'dynamic' || properties.type == 'dynamic') {
                //        var layerDefinitions = [];
                //        layerDefinitions[properties.layerIds[0]] = expression;
                //        layer.setLayerDefinitions(layerDefinitions);
                //    }
                //    else {
                //        layer.setDefinitionExpression(expression);
                //    }

                //}
 

                if (layer && properties.labelingInfo) {
                    var labelClass = new this.widgets.LabelClass(properties.labelingInfo);
                    //properties.labelingInfo[0].symbol = new this.widgets.TextSymbol({
                    //    font: new this.widgets.Font("12", this.widgets.Font.STYLE_NORMAL, this.widgets.Font.VARIANT_NORMAL, this.widgets.Font.WEIGHT_BOLD, "Helvetica"),
                    //    color: new this.widgets.Color("#666633")
                    //});
                    var statesLabel = new this.widgets.TextSymbol().setColor(new this.widgets.Color("#666633"));
                    statesLabel.font.setSize("9pt");
                    statesLabel.font.setFamily("arial");

                    statesLabel.setHaloColor(new this.widgets.Color("#FFFFFF"));
                    statesLabel.setHaloSize("1");
                    labelClass.symbol = statesLabel;
                    layer.setLabelingInfo([labelClass]);
                   // layer.setShowLabels(true);
                }
            }

            if (layer) {

                if (properties.expression) {
                    var expression = this.getExpression(properties);
                    if (type == 'dynamic' || properties.type == 'dynamic') {
                        var layerDefinitions = [];
                        layerDefinitions[properties.layerIds[0]] = expression;
                        layer.setLayerDefinitions(layerDefinitions);
                    }
                    else {
                        layer.setDefinitionExpression(expression);
                    }
                }

                if (!['geometry', 'basemap'].includes(properties.type)) {
                    layer.attr('type', properties.type);
                    layer.attr('dataType', properties.dataType);
                    layer.attr('id', properties.id);
                    layer.attr('layerId', properties.id);
                    layer.attr('name', properties.name);
                    layer.attr('legendName',( properties.legendName ? properties.legendName : null));
                    if ( properties.opacity >=0)
                    layer.attr('opacity', properties.opacity);
                    if (properties.token)
                        layer.attr('token', properties.token);
                    if (properties.id == 24) {
                        //var imageParameters = new this.widgets.ImageParameters();
                        //imageParameters.imageSpatialReference = '';
                        //layer.attr('imageParameters', imageParameters);

                    }
                }
                layer.setVisibility(properties.visibility);
                //return layer;
                if (properties.dataType == 'basic')
                    this.basicsTemp.push(layer);
                else {
                    this.map.addLayer(layer);
                    //if (properties.id != 3)
                    this.initLegend();
                    this.updateIT();
                    //если слой с предзагрузкой фичеров, то фичи олжны добавляться уже после того, как слой есть на карте
                    if (properties.loadMethod) {
                        setTimeout(function () {
                            for (var i = 0; i < this.map.layerIds.length; i++) {
                                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType != 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.id == properties.id && this.map._layers[this.map.layerIds[i]]._attrs.name != 'geoLayer')
                                    this.map._layers[this.map.layerIds[i]].applyEdits(properties.features, null, null);
                            }
                            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                                if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType != 'basic' && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id == properties.id && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.name != 'geoLayer' && !this.map._layers[this.map.graphicsLayerIds[j]]._attrs.isCluster && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.isLoadData )     //     && !this.map._layers[this.map.graphicsLayerIds[j]]._attrs.isCluster                           
                                    this.map._layers[this.map.graphicsLayerIds[j]].applyEdits(properties.features, null, null);
                            }
                            
                        }.bind(this), 100);
                    }                    
                }


            }

            this.removeFromAddingLayers(properties.id);
            this.closeLoaderByAddingLayers();
           // console.log(properties.name + ' створено: ' + new Date());

        },
        getExpression: function (layerProperties) {
            var expression = "";
            if (layerProperties.expression) {
                expression = layerProperties.expression.string;
                if (Object.keys(layerProperties.expression).includes("auth_string") && this.getUser.Loginn !== 'guest') {
                    layerProperties.expression.auth_string.roles.forEach(function (rItem) {
                        if (this.getUser.roles[rItem]) {
                            expression = layerProperties.expression.auth_string.string;
                        }
                    }.bind(this))                    
                }
 
            }
            return expression;
        },
        removeFromAddingLayers: function (id) {
            var newArr = this.addingLayers.filter(e => e !== id);
            this.addingLayers = newArr;
          //  console.log('removeFromAddingLayers; arr = ' + this.addingLayers.join(','));
        },
        getClusterLayerID: function (layerId) {
            var res = 'layer' + layerId,
                isLayerOK = true,
                isGraphicsLayerOK = true,
                maxNum = 0;
            for (var i = 0; i < this.map.layerIds.length; i++) {
                var num = +this.map.layerIds[i].substring(5);
                if (this.map.layerIds[i].indexOf(layerId.toString())) 
                    isLayerOK = false;
                if (maxNum < num)
                    maxNum = num;
            }
            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                var num = +this.map.graphicsLayerIds[j].substring(12);
                if (this.map.graphicsLayerIds[j].indexOf(layerId.toString()))
                    isGraphicsLayerOK = false;
                if (maxNum < num)
                    maxNum = num;
            }
            if (!isLayerOK)
                res = ('layer' + (maxNum + 1));
            else if (!isGraphicsLayerOK)
                res = ('graphicsLayer' + (maxNum + 1));
            return res;
        },
        closeLoaderByAddingLayers: function () {
          //  console.log('closeLoaderByAddingLayers; arr = ' + this.addingLayers.join(','));
            if (this.addingLayers.length == 0)
                store.commit('set_isSearcherInit', true);
        },
        clearClusterLayer: function () {
            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType != 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.name != 'geoLayer' && (this.map._layers[this.map.layerIds[i]]._attrs.hasOwnProperty('isCluster') && this.map._layers[this.map.layerIds[i]]._attrs.isCluster))
                    this.map._layers[this.map.layerIds[i]].clearSingles();
            }
            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType != 'basic' && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.name != 'geoLayer' && (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.hasOwnProperty('isCluster') && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.isCluster) )
                    this.map._layers[this.map.graphicsLayerIds[j]].clearSingles();
            }
        },
        getFeaturesForClusters: function (feauresArray) {
            var res = [];
            if (Array.isArray(feauresArray) && feauresArray.length > 0) {
                feauresArray.forEach(function (fItem) {
                    res.push({
                        "x": fItem.geometry.x,
                        "y": fItem.geometry.y,
                        "attributes": fItem.attributes
                    });
                }.bind(this));
            }
            return res;
        },
        addBasics: function () {
            var tempArr = [],
                basicslength = this.$store.getters.getBasics.length,
                basicsWithoutToken = this._getBasicsWithoutToken(this.$store.getters.getBasics),
                inter = null;
            inter = setInterval(function () {
                if (this.basicsTemp.length == basicsWithoutToken && basicsWithoutToken > 0) {
                    clearInterval(inter);
                    function compare(a, b) {
                        if (a._attrs.id < b._attrs.id)
                            return -1;
                        if (a._attrs.id > b._attrs.id)
                            return 1;
                        return 0;
                    }
                    var sortLayers = this.basicsTemp.sort(compare);
                    sortLayers.forEach(function (item) {
                        this.map.addLayer(item);
                        this.initLegend();
                        this.updateIT();
                       // this.zoomToXY([36,50], 9);
                    }.bind(this));
                    this.basicsTemp.length = 0;                    
                }
                //else
                //    this.basicsTemp.length = 0;
            }.bind(this), 100);
        },
        updateRasters: function () {
            var tempArr = [],
                basicsWithTokenCount = this._getBasicsWithToken(this.$store.getters.getBasics),
                layersWithTokenOnMapCount = this._getLayersWithTokenOnMapCount();
                inter = null;
            if (layersWithTokenOnMapCount > 0) {
                this.updateTokenInLayerOnMap();
            }
            else {
                if (this.basicsTemp.length == 0)
                    this.$store.getters.getBasics.forEach(function (item) {
                        if (item.token.need)
                            this.createLayer(item, this.widgets);
                    }.bind(this));

                inter = setInterval(function () {
                    if (this.basicsTemp.length == basicsWithTokenCount && basicsWithTokenCount > 0) {
                        clearInterval(inter);
                        this.basicsTemp.forEach(function (item) {
                            this.map.addLayer(item);
                        }.bind(this));
                        this.basicsTemp.length = 0;
                    }
                }.bind(this), 100);
            }
        },
        _getBasicsWithoutToken: function (basics) {
            var res = 0;
            if (basics.length > 0) {
                basics.forEach(function (item) {
                    if (!item.token.need)
                        res++;
                });
            }
            return res;
        },
        _getBasicsWithToken: function (basics) {
            var res = 0;
            if (basics.length > 0) {
                basics.forEach(function (item) {
                    if (item.token.need)
                        res++;
                });
            }
            return res;
        },
        _getLayersWithTokenOnMapCount: function () {
            var count = 0;

            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType == 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.name != 'geoLayer' && this.map._layers[this.map.layerIds[i]]._attrs.token.need)
                    count++;
            }
            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType == 'basic' && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.name != 'geoLayer' && this.map._layers[this.map.graphicsLayerIds[i]]._attrs.token.need)
                    count++;
            }
            return count;
        },
        updateTokenInLayerOnMap: function () {
            var basics = this.$store.getters.getBasics;
            basics.forEach(function (item) {
                for (var i = 0; i < this.map.layerIds.length; i++) {
                    if (this.map.getLayer(this.map.layerIds[i])._attrs.dataType == 'basic' && this.map.getLayer(this.map.layerIds[i])._attrs.token.need && item.id == this.map.getLayer(this.map.layerIds[i])._attrs.id)
                        this.map.getLayer(this.map.layerIds[i]).url = item.url + "?token=" + item.token.str;
                }
                for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                    if (this.map.getLayer(this.map.graphicsLayerIds[j])._attrs.dataType == 'basic' && this.map.getLayer(this.map.graphicsLayerIds[j])._attrs.token.need && item.id == this.map.getLayer(this.map.graphicsLayerIds[j])._attrs.id)
                        this.map.getLayer(this.map.graphicsLayerIds[j]).url = item.url + "?token=" + item.token.str;
                }
            }.bind(this));

        },
        layerErrorMessage: function (layerId) {
            eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.serverError);
            eventVue.$emit('toggleLayer', layerId);
        },
        clearCraphicLayer: function () {
            if (this.map._layers.map_graphics)
            this.map._layers.map_graphics.clear();
        },
        removeAddressObjectsFromGraphicLayer: function () { 
            //console.log(this.map.graphics.graphics.length);
            for (var j = 0; j < this.map.graphics.graphics.length; j++) {
                //console.log(this.map.graphics.graphics.length);
                //console.log(this.map.graphics.graphics[j].geometry.type);
                //if (this.map.graphics.graphics[j].geometry.type != 'point') {
                //    console.log(j + ' ; seek ' + this.map.graphics.graphics[j].attributes.FULLADDRUA);
                //}
                if (this.map.graphics.graphics[j].geometry && (this.map.graphics.graphics[j].geometry.type != 'point' || this.map.graphics.graphics[j].geometry.rings)) {
                   // console.log(j + ' ; deleted ' + this.map.graphics.graphics[j].attributes.FULLADDRUA);
                    this.map.graphics.remove(this.map.graphics.graphics[j]);
                }
            }
            //почему-то не все удаляет из графиков за 1 раз!!!!!!!!!!!!!
            var c = 0;
            this.map.graphics.graphics.forEach(function (item) {
                if (item.geometry && item.geometry.type != 'point')
                    c++;
            }.bind(this));
            if (c > 0)
                this.removeAddressObjectsFromGraphicLayer();
        },
        setLayerVisibility: function (layerId) {
            var layersCount = this.$store.getters.getAllLayers.length;
            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType != 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.id == layerId) {
                    var currentVisibility = this.map._layers[this.map.layerIds[i]].visible;
                    this.map._layers[this.map.layerIds[i]].setVisibility(!currentVisibility);
                }
            }
            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType != 'basic' && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id == layerId) {
                    var currentVisibility = this.map._layers[this.map.graphicsLayerIds[j]].visible;
                    this.map._layers[this.map.graphicsLayerIds[j]].setVisibility(!currentVisibility);
                }
            }
            this.updateIT();
        },
        addLayer: function (layerId) {
            var Layer = this.$store.getters.geLayerById(layerId);
            if (!Layer.url && !Layer.features) {
                this.loadFeatures(Layer);
            }
            else {
                this.map.addLayer(this.createLayer(Layer, this.$store.getters.getArcGisWidgets));
                this.countLayerss++;
                //this.initLegend();
                //this.updateIT();
            }
        },
        removeLayer: function (layerId) {
            var layersCount = this.countLayerss + 1;
            var isOK = false, i = 0, layerCounters = 0;
            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType != 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.id == layerId && this.map._layers[this.map.layerIds[i]]._attrs.name != 'geoLayer')
                    this.map.removeLayer(this.map._layers[this.map.layerIds[i]]);
            }
            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType != 'basic' && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id == layerId && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.name != 'geoLayer')
                    this.map.removeLayer(this.map._layers[this.map.graphicsLayerIds[j]]);
            }
            this.clearIdentityFeatures();
            this.updateIT();
            this.initLegend();
        },
        reorderLayer: function (layerId, order) {
            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType != 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.id != layerId)
                    this.map.reorderLayer(this.map._layers[this.map.layerIds[i]], order);
            }
        },
        reorderLayers: function (value) {
            for (var i = 0; i < value.length; i++)
                this.reorderLayer(value[i].id, i + 1);
        },
        updateProjectLayers: function (projectId) {
            //var cntL = this.map.layerIds.slice(0),
            //    cntGl = this.map.graphicsLayerIds.slice(0);
            //for (var i = 0; i < cntL.length; i++) {
            //    if (this.map._layers[cntL[i]]._attrs.dataType != 'basic' && this.map._layers[cntL[i]]._attrs.name != 'geoLayer')
            //        this.map.removeLayer(this.map._layers[cntL[i]]);
            //}
            //for (var j = 0; j < cntGl.length; j++) {
            //    if (this.map._layers[cntGl[j]]._attrs.dataType != 'basic' && this.map._layers[cntGl[j]]._attrs.name != 'geoLayer')
            //        this.map.removeLayer(this.map._layers[cntGl[j]]);
            //}
            this.$store.getters.getAllProjects.forEach(function (p) {
                if (p.id === projectId) {
                    p.layers.forEach(function (l) {
                        var layerOnVuex = this.$store.getters.geLayerById(l.id);
                        if (!layerOnVuex.visibility)
                            this.addLayer(l.id);
                        else
                            this.removeLayer(l.id);
                    }.bind(this));
                }
            }.bind(this));
        },
        updateLayerOnMap: function (layerId) {
            var layerOnVuex = this.$store.getters.geLayerById(layerId);
            if (layerOnVuex.visibility)
                this.addLayer(layerId);
            else
                this.removeLayer(layerId);
        },
        loadFeatures: function (Layer) {
            this.$store.dispatch(Layer.loadMethod, JSON.stringify({ ajax: this.$store.getters.getAjaxUrlByName(Layer.loadMethod), layer: Layer}));
        },
        getLayerVisibilityOnMap: function (layerId) {
            var layersCount = this.$store.getters.getAllLayers.length;
            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (this.map._layers[this.map.layerIds[i]]._attrs.id == layerId) {
                    return this.map._layers[this.map.layerIds[i]].visible;
                }
                for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                    if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id == layerId) {
                        return this.map._layers[this.map.graphicsLayerIds[j]].visible;
                    }
                }
            }
        },
        //obsolette---------------------------------
        addAllProjects: function () {
            //this.$store.commit('set_isMapInit', false);
            if (this.projects.length > 0) {
                for (var i = 0; i < this.projects.length; i++) {
                    var newP = this.createLayer(this.projects[i], this.widgets);
                    this.map.addLayer(newP);
                }
            }
            this.$store.commit('set_isMapInit', true);
        },
        //zoom and extent---------------------------
        zoomToExtent: function (extent) {
            this.map.setExtent(extent);
        },
        createExtent: function (coordinates) {
            return new window.esri.geometry.Extent(coordinates[0], coordinates[1], coordinates[2], coordinates[3], new window.esri.SpatialReference({ wkid: 28467 }))
        },
        zoomToXY: function (coordinates, level) {
            var location = new this.widgets.Point(coordinates[0], coordinates[1] , new window.esri.SpatialReference({ wkid: 28467 }));
            this.map.centerAndZoom(location, level ? level : 9);
        },
        //NavToolbar--------------------------------
        onNavToolbar: function () {
            this.navToolbar = new this.widgets.Navigation(this.map);
        },
        extentHistoryChangeHandler: function () {
            registry.byId("zoomprev").disabled = this.navToolbar.isFirstExtent();
            registry.byId("zoomnext").disabled = this.navToolbar.isLastExtent();
        },
        setNavToolbarAction: function (type) {
            this.hideInfowindow();
            //this.navToolbar.activate(this.widgets.Navigation.PAN);
            
            if (type == 'mesurment') {
                this.navToolbar.deactivate();
                this.closeMeasurment();
            }
            else {
                this.navToolbar.deactivate();
                if (store.getters.getMeasureDivVisibility)                 
                    this.closeMeasurment();                
                switch (type) {
                    case 'zoomin':
                        if (this.$store.getters.getZoominSelected) 
                            this.navToolbar.activate(this.widgets.Navigation.ZOOM_IN);
                        break;
                    case 'zoomout':
                        if (this.$store.getters.getZoomoutSelected) {
                            //this.navToolbar.deactivate();
                            this.navToolbar.activate(this.widgets.Navigation.ZOOM_OUT);
                        }
                        break;
                    case 'zoomtofullextent': {
                        this.zoomToExtent(this.fullExtent);
                        setTimeout(function () {
                            this.map.setScale(114000);
                        }.bind(this), 500);

                        this.clearSelectioHidePopup();
                    }
                        break;
                    case 'identify':
                        //this.navToolbar.deactivate();
                        break;
                    case 'mesurment':
                           // this.navToolbar.deactivate();
                        //this.closeMeasurment();
                        break;
                    case 'pan': {
                       // this.navToolbar.deactivate();
                        this.navToolbar.activate(this.widgets.Navigation.PAN);
                    }
                        break;
                    //case 'coordinates': {
                    //}
                    //    break;
                }
                //this.navToolbar.activate(this.widgets.Navigation.PAN);
            }   
        },
        closeMeasurment: function () {
            this.measurement.clearResult();
            this.measurement.setTool("area", false);
            this.measurement.setTool("distance", false);
            this.$store.commit('set_measureDivVisibility');
        },
        //-----------------------
        //project------------------------------------------
        updateProject: function () {
            //var currentProject = this.$store.getters.getvisibleProject;
            //if (currentProject && currentProject.layers.length > 0) {
            //    this.hideAllProjects();
            //    for (var i = 0; i < currentProject.layers.length; i++)
            //        this.addLayer(currentProject.layers[i].id);
            //        //this.map.addLayer(this.createLayer(currentProject.layers[i], this.$store.getters.getArcGisWidgets));                
            //    //this.updateIT();
            //}
            //this.clearCraphicLayer();
            this.clearSelectioHidePopup();
            if (this.showAddressesObjectsList)
                this.showAddressesObjectsListPanel();
            var VisibileLayers = this.$store.getters.getVisibileLayers;
            if (VisibileLayers.length > 0) {
                this.hideAllProjects();
                for (var i = 0; i < VisibileLayers.length; i++)
                        this.addLayer(VisibileLayers[i].id);


                    //this.map.addLayer(this.createLayer(currentProject.layers[i], this.$store.getters.getArcGisWidgets));                
                //this.updateIT();
            }


        },
        hideAllProjects: function () {
            //var isOK = false, i = 0;
            var cntL = this.map.layerIds.slice(0),
                cntGl = this.map.graphicsLayerIds.slice(0);
            for (var i = 0; i < cntL.length; i++) {
                if (this.map._layers[cntL[i]]._attrs.dataType != 'basic' && this.map._layers[cntL[i]]._attrs.name != 'geoLayer')
                    this.map.removeLayer(this.map._layers[cntL[i]]);
            }
            for (var j = 0; j < cntGl.length; j++) {
                if (this.map._layers[cntGl[j]]._attrs.dataType != 'basic' && this.map._layers[cntGl[j]]._attrs.name != 'geoLayer')
                    this.map.removeLayer(this.map._layers[cntGl[j]]);
            }
            this.initLegend();
            this.updateIT();
        },
        getSearchExtent: function (point) {
            var pxWidth = this.map.extent.getWidth() / this.map.width,
                //padding = 3 * pxWidth;
                padding = 100 * pxWidth,
                qGeom;

            if (this.cFFeature && this.cFFeature.length > 0) {
                qGeom = new this.widgets.graphicsUtils.graphicsExtent(this.cFFeature);
                var xmin = qGeom.xmin,
                    xmax = qGeom.xmax,
                    ymin = qGeom.ymin,
                    ymax = qGeom.ymax;
                qGeom.xmin = xmin - 200;
                qGeom.ymin = ymin - 200;
                qGeom.xmax = xmax + 200;
                qGeom.ymax = ymax + 200;

            }
            else
                qGeom = new this.widgets.Extent({
                    "xmin": point.x - padding,
                    "ymin": point.y - padding,
                    "xmax": point.x + padding,
                    "ymax": point.y + padding,
                    "spatialReference": point.spatialReference
                });
            return qGeom;
        },
        clickMapExecute: function (e) {
            this.clearIdentityFeatures();
            this.$store.commit("set_coordinatesResult");
            //if (this.clusterIdentityFeatures.length > 0)
            //    this.identityFeatures = this.clusterIdentityFeatures;
            this.cFFeature = null;
            if (!this.clickOnGraphicLayerWidthLoadData) {
                this.clearCraphicLayer();

                this.$store.commit('set_currentMapClick', e);

                //this.$store.commit('clearAddressObjectsList');

                var keys = Object.keys(pressedKeys);
               // console.log(keys);
                //['control', 'shift']
                if (this.getCoordinatesSelected || (keys.includes('control') && keys.includes('shift'))) {
                    this.$store.dispatch('getWGSCoordinates', { ajax: this.$store.getters.getAjaxUrlByName('getWGSCoordinates'), coordinates: e.mapPoint, e });
                }
                else if (this.$store.getters.getIdentifySelected && !this.$store.getters.getMeasureDivVisibility) {
                    //this.clearCraphicLayer();
                    //eventVue.$emit('clearAutocomplette');
                    //this.updateIT();
                    var qGeom, point, pxWidth, padding, screenPoint;
                    //обновляем QT
                    //this.updateQT('mapClick');
                    //получаем екстент поиска
                    point = e.mapPoint;
                    qGeom = this.getSearchExtent(point);

                    screenPoint = e.screenPoint;


                    if (e.isCluster) {
                        //this.identifyClusterObjects(point, qGeom, screenPoint);
                        this.clusterIdentityFeatures.forEach(function (cItem) {
                            this.identityFeatures.push(cItem);
                        }.bind(this));
                        this.identifyObjects(point, qGeom, screenPoint);
                    }
                    else if (!e.isCluster && e.graphic && e.graphic.getLayer()._attrs.isLoadData) {
                        var layerProperties = this.$store.getters.geLayerById(e.graphic.getLayer()._attrs.layerId),
                            cFeatureTemplate,
                            resInfo = JSON.parse(JSON.stringify(Object.assign({}, e.graphic.attributes)));
                        resInfo.layerName = e.graphic.getLayer()._attrs.name;
                        resInfo.feature = e.graphic;
                        cFeatureTemplate = this.createInfoTemplate(resInfo, layerProperties);
                        var outObject = {
                            title: layerProperties.name,
                            content: resInfo,
                            feature: e.graphic,
                            layerIdentityProp: layerProperties.identify[layerProperties.layerIds[0]],
                            //исключаем таблицу у сирен
                            contentTable: layerProperties.id != 22 ? cFeatureTemplate.content : null

                        };
                        this.identityFeatures.push(outObject);
                        //this.identifyObjects(point, qGeom, screenPoint);
                    }

                    else
                        this.identifyObjects(point, qGeom, screenPoint);
                }
            }
        },
        clearIdentityFeatures: function () {
            this.identityFeatures.splice(0);
        },
        //identity------------------------------------------
        identifyObjects: function (geometry, extent, screenPoint) {
            var promices, res = [];
            //this.updateIT();
            for (var n = 0; n < this.IT.length; n++) {
                this.IT[n].params.geometry = geometry;
                this.IT[n].params.mapExtent = extent;
                res.push(this.IT[n].task.execute(this.IT[n].params));                   
            }
            store.commit('set_isSearcherInit', false);
            promices = this.widgets.all(res);
            promices.then(this.handleIdentityResult);
        },
        identifyClusterObjects: function (geometry, extent, screenPoint) {
            store.commit('set_isSearcherInit', false);
            this.hasClusterLayer = true;
            var promices, res = [];
            for (var n = 0; n < this.CIT.length; n++) {
                this.CIT[n].params.geometry = geometry;
                this.CIT[n].params.mapExtent = extent;
                res.push(this.CIT[n].task.execute(this.CIT[n].params));                
            }
            promices = this.widgets.all(res);
            promices.then(this.handleIdentityResult);
        },
        handleIdentityResult_: function (e) {
            this.clearCraphicLayer();
            var res = e;
            if (e.length > 0) {
                this.currentClickEventData = this.$store.getters.getCurrentClickEventData;
                var addedData = false, hasData = false;
                for (var i = 0; i < e.length; i++) {
                    if (e[i].length > 0 && !hasData) {
                        hasData = true;
                        var cFeature = e[i][0].feature,
                            cFeatureTemplate,
                            layerName = e[i][0].layerName,
                            bindedObject = e[i][0].bindedObject || false,

                            layerProperties= JSON.parse(JSON.stringify(this.$store.getters.getLayerByTocName(e[i][0].layerName)));

                        //Object.assign({}, this.$store.getters.getLayerByTocName(e[i][0].layerName))
                       // if (layerName != 'clear' && layerProperties.visibility) {
                            //!!!!!!!!!!!!!!!!!
                            if (layerName == 'Житло' || layerName == 'Жилкомсервіс') {
                                // this.cFFeature = e[i];
                                var atrArr = [], geoms = [];
                                e[i].forEach(function (eItem) {
                                    geoms.push(eItem.feature);
                                    atrArr.push(eItem.feature.attributes);
                                }.bind(this));
                                this.cFFeature = geoms;
                                this.showInfoWindow(atrArr, layerProperties);
                                if (!this.clickOnZKS) {
                                    this.clickOnZKS = true;
                                    this.updateIT();
                                }
                            }
                            //если здания и сооружения и первичное
                            else if (layerName == "Будівлі і споруди" && e[i][0].feature.attributes.TypeOfBuild == 'Основне') {
                                var prArr = [];
                                this.$store.getters.getBasics.forEach(function (bItem) {
                                    if (bItem.id == 0)
                                        bItem.identify.forEach(function (niItem) {
                                            if (niItem.tocName == layerName && niItem.identityFields)
                                                niItem.identityFields.forEach(function (niifItem) {
                                                    if (niifItem.name == 'bindToServices')
                                                        niifItem.bindToServices.forEach(function (niifbsItem) {
                                                            var href = (window.location.pathname == '/' || window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href;
                                                            //prArr.push(axios.get(((niifbsItem.type != 'bombshelters' ? href : '') + niifbsItem.url + +e[i][0].feature.attributes.AR_ID + (niifbsItem.url_second_part ? niifbsItem.url_second_part : '')), { buildig: e[i], serviceBindig: niifbsItem, layerProperties: layerProperties }));
                                                            prArr.push(axios.get(( href + niifbsItem.pre_url + +e[i][0].feature.attributes.AR_ID ), { buildig: e[i], serviceBindig: niifbsItem, layerProperties: layerProperties }));
                                                        }.bind(this));
                                                }.bind(this));
                                        }.bind(this));
                                }.bind(this));

                                if (prArr.length > 0)
                                    store.commit('set_isSearcherInit', true);

                                Promise.all(prArr)
                                    .then(response => {
                                        var addedData = false;
                                        if (response && response.length) {
                                            var pRArr = [];
                                            response.forEach(function (RItem) {
                                                if (Array.isArray(RItem.data) && RItem.data.length > 0) {
                                                    var config = RItem.config;
                                                    RItem.data.forEach(function (riiItem) {
                                                        var href = (window.location.pathname == '/' || window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href;
                                                        pRArr.push(axios.get(((config.serviceBindig.type != 'bombshelters' ? href : '') + config.serviceBindig.url + +riiItem + (config.serviceBindig.url_second_part ? config.serviceBindig.url_second_part : '')), { buildig: config.buildig, serviceBindig: config.serviceBindig, layerProperties: config.layerProperties }));
                                                    }.bind(this));
                                                }
                                            }.bind(this));
                                            Promise.all(pRArr)
                                                .then(response => {
                                            if (response && response.length) {
                                                var bindToServices = [], layerProperties, build;
                                                response.forEach(function (rItem) {
                                                    if (typeof rItem.data == 'object' && (rItem.data.GUID || (rItem.data.features && Array.isArray(rItem.data.features) && rItem.data.features.length > 0))) {
                                                        var isOk = true;
                                                        if (bindToServices.length > 0) {
                                                            bindToServices.forEach(function (bsItem) {
                                                                if (bsItem == rItem.config.serviceBindig)
                                                                    isOk = false;
                                                            }.bind(this));
                                                        }
                                                        if (isOk || bindToServices.length == 0)
                                                            bindToServices.push(rItem.config.serviceBindig);
                                                    }
                                                    if (!build)
                                                        build = rItem.config.buildig;

                                                    if (!layerProperties)
                                                        layerProperties = rItem.config.layerProperties;

                                                }.bind(this));
                                            layerProperties.identify.forEach(function (lpiItem) {
                                                var delIndex = -1;
                                                lpiItem.identityFields.forEach(function (lpiifItem, index) {
                                                    if (lpiifItem.name == 'bindToServices' && bindToServices.length > 0)
                                                        lpiifItem.bindToServices = bindToServices;
                                                    else if (lpiifItem.name == 'bindToServices' && bindToServices.length == 0)
                                                        delIndex = index;
                                                }.bind(this));
                                                if (delIndex >= 0)
                                                    lpiItem.identityFields.splice(delIndex, 1);
                                            }.bind(this));

                                            var cFeatureTemplate = this.createInfoTemplate(build[0], layerProperties);
                                            if (cFeature.setInfoTemplate)
                                                cFeature.setInfoTemplate(cFeatureTemplate);
                                            var ncFeature = this.addSelectGeometry(build, cFeatureTemplate);
                                            this.map.infoWindow.setFeatures([ncFeature]);
                                            addedData = true;
                                        }

                                        if (addedData) {
                                            this.map.infoWindow.show(this.currentClickEventData.mapPoint, this.map.getInfoWindowAnchor(this.currentClickEventData.screenPoint));
                                            this.repositionInfoWindow();
                                        }
                                        else
                                            this.hideInfowindow();
                                                })
                                                .catch(function (thrown) {
                                                    store.commit('set_isSearcherInit', true);
                                                    console.log('Request canceled', thrown.message);
                                                });

                                        }

                                    })
                                    .catch(function (thrown) {
                                        store.commit('set_isSearcherInit', true);
                                        console.log('Request canceled', thrown.message);
                                    });
                            }

                            //остальные
                            else {
                                //если у обьекта есть привяки к адресам
                                //if (layerProperties.identify[0].bindToAddress && this.$store.getters.getAddressObjectsList.length == 0 && !isNaN(+cFeature.attributes.institutionIdentifier_)) {
                                if (layerProperties.identify[0].bindToAddress && this.$store.getters.getAddressObjectsList.length == 0 && !isNaN(+cFeature.attributes[layerProperties.identify[0].bindToAddressField])) {
                                    //eventVue.$emit('getAddressesIdsListByCurrentObject', { id: +cFeature.attributes.institutionIdentifier_, res: res });
                                    eventVue.$emit('getAddressesIdsListByCurrentObject', { id: +cFeature.attributes[layerProperties.identify[0].bindToAddressField], res: res });

                                }
                                //если берем геометрию селектирования с контроллера
                                else if (layerProperties.identify[0].controller) {
                                    this.cFFeature = e[i][0].feature.clone();
                                    this.getFeaturesInfo(layerProperties.identify[0].method, e[i]);
                                }
                                //если берем геометрию селектирования с клиента
                                else {
                                    //для зданий
                                    if (layerName == "Будівлі і споруди") {
                                        layerProperties.identify.forEach(function (lpiItem) {
                                            var delIndex = -1;
                                            lpiItem.identityFields.forEach(function (lpiifItem, index) {
                                                if (lpiifItem.name == 'bindToServices')
                                                    delIndex = index;
                                            }.bind(this));
                                            if (delIndex >= 0)
                                                lpiItem.identityFields.splice(delIndex, 1);
                                        }.bind(this));
                                    }

                                    cFeatureTemplate = this.createInfoTemplate(e[i][0], layerProperties);
                                    if (cFeature.setInfoTemplate)
                                        cFeature.setInfoTemplate(cFeatureTemplate);
                                    ncFeature = this.addSelectGeometry(e[i], cFeatureTemplate);
                                    this.map.infoWindow.setFeatures([ncFeature]);
                                    addedData = true;
                                }

                                if (addedData) {
                                    if (bindedObject) {
                                        var delta = 500,
                                            extent = new esri.geometry.Extent({
                                                "xmin": cFeature.geometry.x - delta,
                                                "ymin": cFeature.geometry.y - delta,
                                                "xmax": cFeature.geometry.x + delta,
                                                "ymax": cFeature.geometry.y + delta,
                                                "spatialReference": { "wkid": 28467 }
                                            });

                                        this.map.setExtent(extent, true);

                                        setTimeout(function () {
                                            this.map.infoWindow.show(cFeature.geometry);
                                        }.bind(this), 600);
                                    }
                                    else {
                                        this.map.infoWindow.show(this.currentClickEventData.mapPoint, this.map.getInfoWindowAnchor(this.currentClickEventData.screenPoint));
                                        this.repositionInfoWindow();
                                    }
                                }
                                else
                                    this.hideInfowindow();
                            }
                            break;
                        }
                        //else
                        //    this.clearInited = true;
                        
                    }                   
               // }
            }
            else
                this.hideInfowindow();
        },
        handleIdentityResult_2: function (e) {
            this.clearCraphicLayer();            
            var res = e;
            if (e.length > 0) {
                this.currentClickEventData = this.$store.getters.getCurrentClickEventData;
                var addedData = false, hasData = false;
                for (var i = 0; i < e.length; i++) {
                    if (e[i].length > 0 && !hasData) {
                        hasData = true;
                        var cFeature = e[i][0].feature,
                            cFeatureTemplate,
                            layerName = e[i][0].layerName,
                            bindedObject = e[i][0].bindedObject || false,

                            layerProperties = JSON.parse(JSON.stringify(this.$store.getters.getLayerByTocName(e[i][0].layerName)));

                        //Object.assign({}, this.$store.getters.getLayerByTocName(e[i][0].layerName))
                        // if (layerName != 'clear' && layerProperties.visibility) {
                        //!!!!!!!!!!!!!!!!!
                        if (layerName == 'Житло' || layerName == 'Жилкомсервіс') {
                            // this.cFFeature = e[i];
                            var atrArr = [], geoms = [];
                            e[i].forEach(function (eItem) {
                                geoms.push(eItem.feature);
                                atrArr.push(eItem.feature.attributes);
                            }.bind(this));
                            this.cFFeature = geoms;
                            this.showInfoWindow(atrArr, layerProperties);
                            if (!this.clickOnZKS) {
                                this.clickOnZKS = true;
                                this.updateIT();
                            }
                        }
                        //else if (layerName == 'МАФ' || layerName == 'МАФ (земельна ділянка)') {
                        //    this.cFFeature = e[i];
                        //    var atrArr = [], geoms = [];

                        //    var cFeatureTemplate = this.createInfoTemplate(e[i][0], layerProperties);
                        //    if (e[i][0].feature.setInfoTemplate)
                        //        e[i][0].feature.setInfoTemplate(cFeatureTemplate);
                        //    this.cFFeature = [e[i][0]];
                        //    //this.map.infoWindow.setFeatures([e[i][0]]);
                        //    addedData = true;
                        //    this.showInfoWindow(atrArr, layerProperties);
                        //}
                        //если здания и сооружения и первичное
                        else if (layerName == "Будівлі і споруди" && e[i][0].feature.attributes.TypeOfBuild == 'Основне') {
                            var prArr = [];
                            this.$store.getters.getBasics.forEach(function (bItem) {
                                if (bItem.id == 0)
                                    bItem.identify.forEach(function (niItem) {
                                        if (niItem.tocName == layerName && niItem.identityFields)
                                            niItem.identityFields.forEach(function (niifItem) {
                                                if (niifItem.name == 'bindToServices')
                                                    niifItem.bindToServices.forEach(function (niifbsItem) {
                                                        var href = (window.location.pathname == '/' || window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href;
                                                        //prArr.push(axios.get(((niifbsItem.type != 'bombshelters' ? href : '') + niifbsItem.pre_url + +e[i][0].feature.attributes.AR_ID + (niifbsItem.url_second_part ? niifbsItem.url_second_part : '')), { buildig: e[i], serviceBindig: niifbsItem, layerProperties: layerProperties }));
                                                        //prArr.push(axios.get(( href + niifbsItem.pre_url + +e[i][0].feature.attributes.AR_ID ), { buildig: e[i], serviceBindig: niifbsItem, layerProperties: layerProperties }));
                                                        prArr.push(axios.get((href + niifbsItem.pre_url + +e[i][0].feature.attributes.AR_ID), { buildig: e[i], serviceBindig: niifbsItem, layerProperties: layerProperties }));

                                                    }.bind(this));
                                            }.bind(this));
                                    }.bind(this));
                            }.bind(this));

                            if (prArr.length > 0)
                                store.commit('set_isSearcherInit', true);

                            Promise.all(prArr)
                                .then(response => {
                                    var addedData = false;
                                    if (response && response.length) {
                                        var bindToServices = [], layerProperties, build;
                                        response.forEach(function (rItem) {
                                            if (typeof rItem.data == 'object' && (rItem.data.GUID || (rItem.data && Array.isArray(rItem.data) && rItem.data.length > 0))) {
                                                bindToServices.push(rItem.config.serviceBindig);
                                            }
                                            else if (typeof rItem.data === 'string' && rItem.data !== 'SCHOOL_NOT_FOUND' && rItem.data !== 'BOMBSHELTERS_NOT_FOUND' && rItem.data !== 'HOSPITALS_NOT_FOUND') {
                                                var mabeArray = JSON.parse(rItem.data);
                                                if (Array.isArray(mabeArray.features) && mabeArray.features.length > 0) {
                                                    mabeArray.features.forEach(function (maItem, index, array) {
                                                        var copyService = Object.assign({}, rItem.config.serviceBindig),
                                                            newServiceName = copyService.name,
                                                            lowerCaseCompanyName = maItem.attributes.name.toLowerCase();
                                                        copyService.feature = maItem;
                                                        if (rItem.config.serviceBindig.type == 'medicine') {
                                                            if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('дитяч') >= 0 && lowerCaseCompanyName.indexOf('поліклін') >= 0)
                                                                newServiceName = 'Дитяча поліклініка';
                                                            else if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('поліклін') >= 0)
                                                                newServiceName = 'Поліклініка';
                                                            else if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('дитяч') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                                newServiceName = 'Дитяча лікарня';
                                                            else if (lowerCaseCompanyName.indexOf('міськ') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                                newServiceName = 'Лікарня';
                                                            else if (lowerCaseCompanyName.indexOf('стомат') >= 0 && lowerCaseCompanyName.indexOf('дитяч') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                                newServiceName = 'Дитяча стоматологічна поліклініка';
                                                            else if (lowerCaseCompanyName.indexOf('стомат') >= 0 && lowerCaseCompanyName.indexOf('лікарн') >= 0)
                                                                newServiceName = 'Стоматологічна поліклініка';
                                                            else if (lowerCaseCompanyName.indexOf('пологов') >= 0)
                                                                newServiceName = 'Пологовий будинок';
                                                            else if (lowerCaseCompanyName.indexOf('венеролог') >= 0)
                                                                newServiceName = 'Вендиспансер';
                                                            copyService.name = newServiceName;
                                                        }                                                        
                                                        bindToServices.push(copyService);
                                                    }.bind(this));

                                                }
                                            }
                                            if (!build)
                                                build = rItem.config.buildig;

                                            if (!layerProperties)
                                                layerProperties = rItem.config.layerProperties;

                                        }.bind(this));

                                        layerProperties.identify.forEach(function (lpiItem) {
                                            var delIndex = -1;
                                            lpiItem.identityFields.forEach(function (lpiifItem, index) {
                                                if (lpiifItem.name == 'bindToServices' && bindToServices.length > 0)
                                                    lpiifItem.bindToServices = bindToServices;
                                                else if (lpiifItem.name == 'bindToServices' && bindToServices.length == 0)
                                                    delIndex = index;
                                            }.bind(this));
                                            if (delIndex >= 0)
                                                lpiItem.identityFields.splice(delIndex, 1);
                                        }.bind(this));

                                        var cFeatureTemplate = this.createInfoTemplate(build[0], layerProperties);
                                        if (cFeature.setInfoTemplate)
                                            cFeature.setInfoTemplate(cFeatureTemplate);
                                        var ncFeature = this.addSelectGeometry(build, cFeatureTemplate);
                                        this.map.infoWindow.setFeatures([ncFeature]);
                                        addedData = true;
                                    }

                                    if (addedData) {
                                        this.map.infoWindow.show(this.currentClickEventData.mapPoint, this.map.getInfoWindowAnchor(this.currentClickEventData.screenPoint));
                                        this.repositionInfoWindow();
                                    }
                                    else
                                        this.hideInfowindow();
                                })
                                .catch(function (thrown) {
                                    store.commit('set_isSearcherInit', true);
                                    console.log('Request canceled', thrown.message);
                                });
                        }
                        //остальные
                        else {
                            //если у обьекта есть привяки к адресам
                            //if (layerProperties.identify[0].bindToAddress && this.$store.getters.getAddressObjectsList.length == 0 && !isNaN(+cFeature.attributes.institutionIdentifier_)) {
                            if (layerProperties.identify[0].bindToAddress && this.$store.getters.getAddressObjectsList.length == 0 && !e[i][0].addressesLoaded && !isNaN(+cFeature.attributes[layerProperties.identify[0].bindToAddressField])) {
                                this.cFFeature = [e[i][0].feature];
                                //eventVue.$emit('getAddressesIdsListByCurrentObject', { id: +cFeature.attributes.institutionIdentifier_, res: res });
                                eventVue.$emit('getAddressesIdsListByCurrentObject', { id: +cFeature.attributes[layerProperties.identify[0].bindToAddressField], res: res, identity: layerProperties.identify[0]});

                            }
                            //если берем геометрию селектирования с контроллера
                            else if (layerProperties.identify[0].controller) {
                                this.cFFeature = e[i][0].feature.clone();
                                this.getFeaturesInfo(layerProperties.identify[0].method, e[i]);
                            }
                            //если берем геометрию селектирования с клиента
                            else {
                                //для зданий
                                if (layerName == "Будівлі і споруди") {
                                    layerProperties.identify.forEach(function (lpiItem) {
                                        var delIndex = -1;
                                        lpiItem.identityFields.forEach(function (lpiifItem, index) {
                                            if (lpiifItem.name == 'bindToServices')
                                                delIndex = index;
                                        }.bind(this));
                                        if (delIndex >= 0)
                                            lpiItem.identityFields.splice(delIndex, 1);
                                    }.bind(this));
                                }

                                cFeatureTemplate = this.createInfoTemplate(e[i][0], layerProperties);
                                if (cFeature.setInfoTemplate)
                                    cFeature.setInfoTemplate(cFeatureTemplate);
                                ncFeature = this.addSelectGeometry(e[i], cFeatureTemplate);
                                this.map.infoWindow.setFeatures([ncFeature]);
                                addedData = true;
                            }

                            if (addedData) {
                                if (bindedObject) {
                                    var delta = 500,
                                        extent = new esri.geometry.Extent({
                                            "xmin": cFeature.geometry.x - delta,
                                            "ymin": cFeature.geometry.y - delta,
                                            "xmax": cFeature.geometry.x + delta,
                                            "ymax": cFeature.geometry.y + delta,
                                            "spatialReference": { "wkid": 28467 }
                                        });

                                    this.map.setExtent(extent, true);

                                    setTimeout(function () {
                                        this.map.infoWindow.show(cFeature.geometry);
                                    }.bind(this), 600);
                                }
                                else {
                                    this.map.infoWindow.show(this.currentClickEventData.mapPoint, this.map.getInfoWindowAnchor(this.currentClickEventData.screenPoint));
                                    if (layerProperties.id != 17)
                                        this.repositionInfoWindow();
                                    if (layerProperties.id == 18) {
                                        var el = document.querySelector('.esriPopup .titlePane .title b');
                                        el.style.maxWidth = '100%';
                                    }
                                }
                            }
                            else
                                this.hideInfowindow();
                        }
                        break;
                    }
                    //else
                    //    this.clearInited = true;

                }
                // }
            }
            else
                this.hideInfowindow();
        },
        handleIdentityResult: function (e) {
            //this.clearCraphicLayer();
            var res = e;
            if (e.length > 0) {
                this.currentClickEventData = this.$store.getters.getCurrentClickEventData;
                var addedData = false, hasData = false, forFeatureInfo = [];

                for (var i = 0; i < e.length; i++) {
                   
                    if (e[i].length > 0 && !hasData) {
                        let adm_rayon = null;
                        e[i].forEach(function (eItem, index, array) {
                            var cFeature = eItem.feature,
                                cFeatureTemplate,
                                layerName = eItem.layerName,
                                layerId = eItem.layerId,
                                bindedObject = eItem.bindedObject || false;

                            if (layerName === "Адміністративні райони") {
                                adm_rayon = cFeature.attributes
                            }
                            else {
                                
                                var layerProperties = JSON.parse(JSON.stringify(this.$store.getters.getLayerByTocName(layerName))),
                                    layerInfoId,
                                    resInfo = JSON.parse(JSON.stringify(Object.assign({}, cFeature.attributes)));
                                resInfo.layerName = layerName;
                                resInfo.feature = cFeature;

                                layerProperties.identify.forEach(function (iItem) {
                                    if (iItem.id === layerId && iItem.addAdmRayon) {
                                        resInfo.odp_adm_rayon = adm_rayon;
                                    }
                                }.bind(this));
                              

                                cFeatureTemplate = this.createInfoTemplate(resInfo, layerProperties);

                                var outObject = {
                                    title: layerProperties.identify.find(i => i.tocName === layerName).title,
                                    content: resInfo,
                                    feature: cFeature,
                                    layerIdentityProp: this.getLayerIdentityPropertiesById(layerInfoId, layerProperties, layerName),
                                    // contentTable: cFeatureTemplate.content
                                };

                                this.identityFeatures.push(outObject);
                            }
                            
                            
                        }.bind(this));
                    }
                }
            }
            else
                this.hideInfowindow();
            store.commit('set_isSearcherInit', true);
        },
        getLayerIdentityPropertiesById: function (layerId, layerProperties, layerName) {
            var res;
            layerProperties.identify.forEach(function (iItem) {
                if (iItem.id == layerId || (layerName && iItem.tocName.toLowerCase() == layerName.toLowerCase()))
                    res = iItem;                
            }.bind(this));
            return res;
        },
        getFeaturesInfo: function (method, reponse) {
            if (method == 'GetDugById')
                this.$store.dispatch(method, JSON.stringify({ ajax: this.$store.getters.getAjaxUrlByName(method), dugId: reponse[0].feature.attributes.ID, prop: reponse}));
            if (method == 'GetAdwerts') {
                var ids = [];
                for (var i = 0; i < reponse.features.length; i++) 
                    ids.push(+reponse.features[i].attributes.OBJECTID);
                this.$store.dispatch(method, JSON.stringify({ ajax: this.$store.getters.getAjaxUrlByName(method), ids: ids, prop: reponse.target._attrs }));
            }
        },
        setMinMaxScale: function () {
            if (this.map.getScale() > 115000)
                this.map.setScale(115000);
            if (this.map.getScale() < 500)
                this.map.setScale(500);
        },
        updateIT: function (addedPoly) {
            this.IT.length = 0;
            this.CIT.length = 0;
            var prj = [],
                prjCIT = [],
                projects = this.$store.getters.getvisibleProject,
                layers = this.$store.getters.getVisibileLayers,
                basics = this.$store.getters.getVisibleBasis,
                task, params,
                hasPoly = false;

            if (layers.length > 0) {
                //если подключен хотя проект, то добавляем его слои в identity
                for (var i = 0; i < layers.length; i++) {
                    if (!layers[i].loadMethod) {
                        if (layers[i].geometryType == 'Polygon')
                            hasPoly = true;
                        var isVisible = this.getLayerVisibilityOnMap(layers[i].id);
                        if (isVisible && layers[i].visibility && layers[i].identify && (layers[i].identScale >= this.map.getScale() || layers[i].identScale == 0) && !layers[i].cluster) {
                            //добавляем в список видимых проектов
                            prj.push(layers[i].id);
                            //переменные
                            var layersIds = [];
                            task = new this.widgets.IdentifyTask((layers[i].type == 'feature') ? layers[i].url.replace('FeatureServer', 'MapServer') : layers[i].url),
                                params = new this.widgets.IdentifyParameters();
                            params.layerIds = layers[i].layerIds;
                            if (layers[i].geometryType == 'Point' && this.map.getScale() < 1000)
                                params.spatialReference = this.map.spatialReference;
                            var tolerance = this.getTolerance2(layers[i]);
                            //addedPoly && 
                            params.tolerance = (((layers[i].geometryType !== 'Polygon' && this.clickOnZKS) || this.clickOnZKS) && this.map.getScale() < 3000) ? tolerance / 6 : tolerance;
                            // params.tolerance = layers[i].tolerance;
                            params.tolerance = tolerance;

                            if (layers[i].expression) {
                                let out_expression = this.getExpression(layers[i]);
                                if (out_expression.length > 0) {
                                    params.layerDefinitions = [];
                                    params.layerDefinitions[layers[i].layerIds[0]] = out_expression;
                                }                    
                            } 
                            //
                            //собираем
                            //console.log('scale = ' + this.map.getScale() + '; tolerance = ' + params.tolerance + '; layer = ' + layers[i].name + '; geomType = ' + layers[i].geometryType);
                            this.IT.push({
                                task: task,
                                params: params
                            });
                        }
                        //else if (layers[i].visibility && layers[i].identify && (layers[i].identScale >= this.map.getScale() || layers[i].identScale == 0) && layers[i].cluster && !layers[i].loadMethod && !layers[i].features) {
                        //    //добавляем в список видимых проектов
                        //    prj.push(layers[i].id);
                        //    //переменные
                        //    var layersIds = [];
                        //    task = new this.widgets.IdentifyTask((layers[i].type == 'feature') ? layers[i].url.replace('FeatureServer', 'MapServer') : layers[i].url),
                        //    params = new this.widgets.IdentifyParameters();
                        //    params.layerIds = layers[i].layerIds;
                        //    //params.tolerance = layers[i].tolerance;
                        //    //params.tolerance = this.getTolerance(layers[i]);
                        //    params.returnGeometry = true;
                        //    params.tolerance = this.getTolerance2(layers[i]);
                        //    //собираем
                        //    console.log('scale = ' + this.map.getScale() + '; tolerance = ' + params.tolerance + '; layer = ' + layers[i].name + '; geomType = ' + layers[i].geometryType);
                        //    this.CIT.push({
                        //        task: task,
                        //        params: params
                        //    });
                        //}
                    }
                }
            }
            if (basics.length > 0) {
                this.clearInited = false;
                for (var j = 0; j < basics.length; j++) {
                    if (basics[j].visibility && basics[j].identify && (basics[j].identScale >= this.map.getScale() || basics[j].identScale == 0)) {
                        //добавляем в список видимых проектов
                        //prj.push(layers[j].id);
                        //переменные
                        if (basics[j].name != 'clear' ) {
                            var layersIds = [];
                            task = new this.widgets.IdentifyTask(basics[j].url),
                            params = new this.widgets.IdentifyParameters();
                            params.layerIds = basics[j].layerIds;
                            params.tolerance = 10;
                            if (basics[j].name == 'clear') {
                                params.tolerance = 1500;                                
                            }
              
                            //console.log('scale = ' + this.map.getScale() + '; tolerance = ' + params.tolerance + '; layer = ' + basics[j].name + '; geomType = ' + basics[j].geometryType);

                            //собираем
                            this.IT.push({
                                task: task,
                                params: params
                            });
                        }
                    }
                }
            }           
            //всем IT добавляем параметры
            for (var n = 0; n < this.IT.length; n++) {                
                this.IT[n].params.returnGeometry = true;
                this.IT[n].params.layerOption = this.widgets.IdentifyParameters.LAYER_OPTION_ALL;
                this.IT[n].params.width = this.map.width;
                this.IT[n].params.height = this.map.height;
            }


            if (hasPoly && layers.length > 1 && !addedPoly)
                this.updateIT(true);
        },
        getTolerance2: function (layer) {
            var koef = layer.tolerance,
                mapExtent = this.map.extent,
                windowWidth = window.innerWidth,
                resolution = this.map.getResolution(),
                tolerance;
            tolerance = (mapExtent.xmax - mapExtent.xmin) / windowWidth * koef;
            //console.log('tolerance = ' + ('('+ mapExtent.xmax +' - ' + mapExtent.xmin + ') / '+ windowWidth + ' * ' +  koef + ') = ' + tolerance));
            //if (layer.id == 21 && this.map.getScale() < 1000 && tolerance < 15)
            //    tolerance = 15;
            if ((layer.geometryType == 'Point' || layer.geometryType == 'Line') && this.map.getScale() < 2000 && tolerance < layer.tolerance)
                tolerance = layer.tolerance;
            //if ((layer.id == 25 || layer.id == 26 || layer.id == 28 || layer.id == 29 || layer.id == 30 || layer.id == 21 || layer.id == 31 || layer.id == 32 || layer.id == 33 || layer.id == 34 || layer.id == 35 || layer.id == 36 || layer.id == 37 || layer.id == 38 || layer.id == 39 || layer.id == 40) && this.map.getScale() < 2000 && tolerance < layer.tolerance)
            //    tolerance = layer.tolerance;
            return tolerance;
        },
        getTolerance: function (layer) {
            var res = 10, currentMapScale = this.map.getScale(), koef = 1;
            var koefs = {
                '500': 0.025,
                '1000': 0.051,
                '5000': 0.254,
                '10000': 0.508,
                '25000': 1.270,
                '63360': 3.210,
                '100000': 5.080,
                '200000': 10.130,
            }
            if (layer.geometryType == 'Point' || layer.geometryType == 'Line') {
               // if (currentMapScale < 500)
               //     koef = koefs['500'];
               // else if (currentMapScale < 1000)
               //     koef = koefs['1000'];
               // else if (currentMapScale < 5000)
               //     koef = koefs['5000'];
               // else if (currentMapScale < 10000)
               //     koef = koefs['10000'];
               // else if (currentMapScale < 25000)
               //     koef = koefs['25000'];
               // else if (currentMapScale < 63360)
               //     koef = koefs['63360'];
               // else if (currentMapScale < 100000)
               //     koef = koefs['100000'];
               // else if (currentMapScale < 200000)
               //     koef = koefs['200000'];
               // else 
               //     koef = koefs['200000'];

               // if (window.innerWidth <= 768) {
               //     koef = 0.3; 
               //     res = (window.devicePixelRatio * currentMapScale) / 12 * koef;
               //}
                console.log('type = ' + layer.geometryType + '; tolerance = ' + res + '; scale = ' + currentMapScale + '; devicePixelRatio = ' + window.devicePixelRatio);
                // if (layer.geometryType == 'Point' && window.innerWidth > 768) {
                if (typeof (layer.tolerance) == 'object') {
                    var hasClusterL = this.hasClusterLayer?1:0 ;
                    if (currentMapScale < 200)
                        res = layer.tolerance['200'][hasClusterL];
                    else if (currentMapScale < 300)
                        res = layer.tolerance['300'][hasClusterL];
                    else if (currentMapScale < 498)
                        res = layer.tolerance['500'][hasClusterL];
                    else if (currentMapScale < 798)
                        res = layer.tolerance['1000'][hasClusterL];
                    else if (currentMapScale < 1000)
                        res = layer.tolerance['1000'][hasClusterL];
                    else if (currentMapScale < 5000)
                        res = layer.tolerance['5000'][hasClusterL];
                }
                else {
                    if (currentMapScale < 200)
                        res = 20;
                    else if (currentMapScale < 300)
                        res = 30;
                    else if (currentMapScale < 498)
                        res = 40;
                    else if (currentMapScale < 798)
                        res = 50;
                    else if (currentMapScale < 1000)
                        res = 60;
                    else if (currentMapScale < 5000)
                        res = 100;
                }
                //if (res >= 100)
                //        res = 30;

                //}
                //res = 50;
            }
            //else if (layer.geometryType == 'Line') {
            //    if (currentMapScale > 1500)
            //        koef = 5;
            //}
            else if (layer.geometryType == 'Polygon') {
                //if (currentMapScale > 1500)
                //    koef = 0.025;
                //else
                //    koef = 0.051;
                res = 5;
            }


            if (layer.geometryType == 'Line' && res < 15)
                res = 15;
            //console.log('type = ' + layer.geometryType + '; tolerance = ' + res + '; scale = ' + currentMapScale + '; devicePixelRatio = ' + window.devicePixelRatio);
            return res;
        },
        hideInfowindow: function () {
            if (!this.showedAddressObjects) {
                this.map.infoWindow.hide();    
            }
            this.clearClusterLayer();

        },
        createInfoTemplate: function (resInfo, layerProperties) {
            var infoTemplate = new this.widgets.InfoTemplate();
            var node = document.querySelector('button.photoBtn');
            if (node)
                node.remove();
            if (layerProperties && layerProperties.identify && layerProperties.identify.length > 0) {
                for (var i = 0; i < layerProperties.identify.length; i++)
                    if (resInfo.layerName == layerProperties.identify[i].tocName ||
                        (resInfo.layerName == "ОСББ, ЖК та ЖБК" && layerProperties.identify[i].tocName == 'Житло') ||
                        (resInfo.layerName == "Комунальне житло" && layerProperties.identify[i].tocName == 'Жилкомсервіс') ||
                        layerProperties.identify[i].bindToAddress) {
                        var rows = '' ;
                        infoTemplate.setTitle("<b>" +
                            (layerProperties.identify[i].title == 'МАФ (земельна ділянка)' ? 'МАФ <br> (земельна ділянка)' : layerProperties.identify[i].title) +
                            "</b>");

                        if (layerProperties.identify[i].identityFields.length > 0) {
                                if (resInfo.hasOwnProperty(layerProperties.identify[i].identityFields[0].name))
                                    rows = this.getInfoRows(resInfo, layerProperties, layerProperties.identify[i].identityFields, resInfo.layerName);
                                else if (resInfo.feature.attributes.hasOwnProperty(layerProperties.identify[i].identityFields[0].name))
                                    rows = this.getInfoRows(resInfo.feature.attributes, layerProperties, layerProperties.identify[i].identityFields, resInfo.layerName);
                        }
                        if (layerProperties.nameVectorLayer && layerProperties.nameVectorLayer == "asys.SDE.CyfraAccess") {
                            infoTemplate.setContent('<table class="digitalInfoTable">' + rows + '</table>');
                        }
                        else {
                            infoTemplate.setContent('<table>' + rows + '</table>');
                        }
                        
                    }                
            }
 
            return infoTemplate;
        },
        getInfoRows: function (attributes, type, identityFields, layerName) {
            var template = '';
            if (identityFields && identityFields.length > 0) {
                var WIFITR = {
                    'RX_AVR': null,
                    'TX_AVR': null,
                    'RX_TOTAL': null,
                    'TX_TOTAL ': null
                    },
                    director = {
                        'UNIVERSITY_DIRECTOR_FIO': null,
                        'UNIVERSITY_DIRECTOR_POST': null
                    },
                    card = {                    
                        'CARD_NUMBER': null,
                        'CARTDATE': null,
                        'INDTEMA_VK': null,
                        'THEME_NAME': null,
                        'EXECUTOR_NAME': null,
                        'EXECUTOR_PHONE': null,
                        'EXECUTOR_DEPARTMENT': null,
                        'EXECUTOR_RANK':null,
                        'REGISTRATOR_PHONE':null
                    };
                for (var i = 0; i < identityFields.length; i++) {
                    //console.log(identityFields[i].name);
                    if (identityFields[i].name == 'balancer')
                        var T = '';
                    //blobs ----------------------------------------------
                    if (identityFields[i].name == 'blobs' && attributes[identityFields[i].name] && attributes[identityFields[i].name].length > 0)
                        template += '<tr><td></td><td><button onclick="showBlobs([' + attributes[identityFields[i].name] + '])"><i class="material-icons">photo_library</i >Фото</button></td></tr>';
                    //wifi trafic & state-------------------------------
                    else if (identityFields[i].name == 'RX_AVR' || identityFields[i].name == 'TX_AVR' || identityFields[i].name == 'RX_TOTAL' || identityFields[i].name == 'TX_TOTAL') {
                        if (attributes[identityFields[i].name] && attributes[identityFields[i].name] != '0b') {
                            WIFITR[identityFields[i].name] = attributes[identityFields[i].name];
                            if (WIFITR['RX_AVR'] && WIFITR['TX_AVR'] && WIFITR['RX_TOTAL'] && WIFITR['TX_TOTAL']) {
                                template += ' <tr><td><b>Інтенсивність </b></td><td> прийом ' + WIFITR['RX_AVR'] + ' /  передача ' + WIFITR['TX_AVR'] + '</td></tr>';
                                template += ' <tr><td><b>Трафік </b></td><td> прийом ' + WIFITR['RX_TOTAL'] + ' /  передача ' + WIFITR['TX_TOTAL'] + '</td></tr>';
                            }
                        }
                    }
                    else if (identityFields[i].name == 'UPTIME') {
                        if (!attributes[identityFields[i].name] && attributes[identityFields[i].name] == '') {
                            template += '<tr><td><b>Стан: </b></td><td style="color:red;">Offline</td></tr>';
                            template += '<tr><td><b>Підключеня: </b></td><td>Підключеня відсутні</td></tr>';
                        }
                        else if (attributes[identityFields[i].name] && attributes[identityFields[i].name].trim() != '') {
                            template += '<tr><td><b>Стан: </b></td><td style="color:green;">Online</td></tr>';
                            template += '<tr><td><b>' + identityFields[i].description + '</b></td><td> ' + attributes[identityFields[i].name].trim() + '</td></tr>';
                        }
                    }
                    //site
                    else if ((identityFields[i].name == 'url' || identityFields[i].name == 'UNIVERSITY_SITE') && attributes[identityFields[i].name].trim() != "Null" && attributes[identityFields[i].name].trim() != "")
                        template += '<tr><td>' + identityFields[i].description + '</td><td><a href="' + attributes[identityFields[i].name] + '" target="_blank">' + attributes[identityFields[i].name] + '</a></td></tr>';
                    //education ---------------------------------
                    else if (identityFields[i].name == 'UNIVERSITY_DIRECTOR_FIO' || identityFields[i].name == 'UNIVERSITY_DIRECTOR_POST' && attributes[identityFields[i].name].trim() != "Null" && attributes[identityFields[i].name].trim() != "") {
                        director[identityFields[i].name] = attributes[identityFields[i].name];
                        if (director['UNIVERSITY_DIRECTOR_FIO'] && director['UNIVERSITY_DIRECTOR_POST'])
                            template += '<tr><td>' + (director['UNIVERSITY_DIRECTOR_POST'] != '' ? director['UNIVERSITY_DIRECTOR_POST'] : 'Керівник') + '</td><td>' + director['UNIVERSITY_DIRECTOR_FIO'] + '</td></tr>';
                    }


                    //adwert ---------------------------------
                    else if (identityFields[i].name == 'PermitDateValid' || identityFields[i].name == 'PermitNumber') {
                        if (identityFields[i].name == 'PermitDateValid' && attributes[identityFields[i].name].trim() != "Null" && attributes[identityFields[i].name].trim() != "" && attributes[identityFields[i].name].trim() != "01.01.0001")
                            template += '<tr><td>' + identityFields[i].description + '</td><td>' + attributes[identityFields[i].name] + '</td></tr>';
                    }
                    //webdocprof -----------------------------
                    else if (identityFields[i].name == 'CARD_NUMBER' ||
                        identityFields[i].name == 'CARTDATE' ||
                        identityFields[i].name == 'INDTEMA_VK' ||
                        identityFields[i].name == 'THEME_NAME' ||
                        identityFields[i].name == 'ADDITIONAL_THEMES_BY_STR' ||
                        identityFields[i].name == 'EXECUTOR_NAME' ||
                        identityFields[i].name == 'EXECUTOR_DEPARTMENT' ||
                        identityFields[i].name == 'EXECUTOR_PHONE' ||
                        identityFields[i].name == 'EXECUTOR_RANK' ||
                        identityFields[i].name == 'REGISTRATOR_PHONE') {
                        if (attributes[identityFields[i].name] && attributes[identityFields[i].name] != '') {

                            if (identityFields[i].name == 'THEME_NAME') {
                                card['THEME_NAME'] = attributes[identityFields[i].name];
                                if (attributes['ADDITIONAL_THEMES_BY_STR']) {
                                    var arr = attributes['ADDITIONAL_THEMES_BY_STR'].split('|');
                                    if (arr.length > 0) {
                                        for (var j = 0; j < arr.length; j++) {
                                            if (arr[j] != "") {
                                                var theme = arr[j].split('^'),
                                                    themeCode = theme[0],
                                                    themeName = theme[1];
                                                card['THEME_NAME'] += '<br/> (' + themeCode + ') ' + themeName;
                                            }
                                        }
                                    }
                                }
                            }

                            else if (identityFields[i].name == 'CARTDATE') {
                                var curDate = new Date(attributes[identityFields[i].name]);
                                var d = [curDate.getDate(), curDate.getMonth() + 1, +curDate.getFullYear().toString()];
                                d.forEach(function (v, i, a) {
                                    if (v < 10) return a[i] = '0' + v;
                                });
                                card[identityFields[i].name] = d.join('.');
                            }

                            else if (identityFields[i].name == 'EXECUTOR_NAME' ||
                                identityFields[i].name == 'EXECUTOR_DEPARTMENT' ||
                                identityFields[i].name == 'EXECUTOR_PHONE' ||
                                identityFields[i].name == 'EXECUTOR_RANK' ||
                                identityFields[i].name == 'REGISTRATOR_PHONE') {

                                if (attributes['EXECUTOR_NAME'] == 'На розгляді у керівництва')
                                    card[identityFields[i].name] = (identityFields[i].name == 'EXECUTOR_NAME') ? 'На розгляді у керівництва' : '_';
                                else
                                    card[identityFields[i].name] = attributes[identityFields[i].name];
                            }
                            else
                                card[identityFields[i].name] = attributes[identityFields[i].name];
                        }
                        else
                            card[identityFields[i].name] = '_';

                        //console.log('CARD_NUMBER = '+ card['CARD_NUMBER']);
                        //console.log('CARTDATE = '+ card['CARTDATE']);
                        //console.log('INDTEMA_VK = '+ card['INDTEMA_VK']);
                        //console.log('THEME_NAME = '+ card['THEME_NAME']);
                        //console.log('EXECUTOR_NAME = '+ card['EXECUTOR_NAME']);
                        //console.log('EXECUTOR_DEPARTMENT = '+ card['EXECUTOR_DEPARTMENT']);
                        //console.log('EXECUTOR_PHONE = '+ card['EXECUTOR_PHONE']);
                        //console.log('EXECUTOR_RANK = '+ card['EXECUTOR_RANK']);
                        //console.log('REGISTRATOR_PHONE = '+ card['REGISTRATOR_PHONE']);


                        if (card['CARD_NUMBER'] && card['CARTDATE'] && card['INDTEMA_VK'] && card['THEME_NAME'] && card['EXECUTOR_NAME'] && card['EXECUTOR_DEPARTMENT'] && card['EXECUTOR_PHONE'] && card['EXECUTOR_RANK'] && card['REGISTRATOR_PHONE']) {
                            template += ' <tr><td><b>Звернення </b></td><td> ' + card['CARD_NUMBER'] + ' від ' + card['CARTDATE'] + '</td></tr>';
                            template += ' <tr><td><b>Тематика </b></td><td> (' + card['INDTEMA_VK'] + ') ' + card['THEME_NAME'] + '</td></tr>';

                            if (card['EXECUTOR_NAME'] && card['EXECUTOR_NAME'] == 'На розгляді у керівництва')
                                template += ' <tr><td></td><td> ' + card['EXECUTOR_NAME'] + '</td></tr>';

                            if (card['EXECUTOR_NAME'] && card['EXECUTOR_NAME'] != 'На розгляді у керівництва' && card['EXECUTOR_DEPARTMENT'] && card['EXECUTOR_PHONE'] && card['EXECUTOR_RANK']) {
                                template += ' <tr><td><b>Відповідальний </b></td><td>' + card['EXECUTOR_NAME'] + ' (' + card['EXECUTOR_DEPARTMENT'] + ')</td></tr>';
                                if (card['EXECUTOR_PHONE'] || card['REGISTRATOR_PHONE'])
                                    template += ' <tr><td><b>Довідка за тел. </b></td><td> ' + (card['EXECUTOR_PHONE'] ? card['EXECUTOR_PHONE'] : card['REGISTRATOR_PHONE']) + '</td></tr>';
                            }
                        }
                    }
                    //zhil_fond----------------------
                    else if (identityFields[i].name == 'commnts' || (identityFields[i].name == 'balancer' && layerName != 'Приватний сектор')) {
                        if (identityFields[i].name == 'commnts' && attributes['commnts'] && attributes['commnts'] != 'Null') {
                            template += '<tr><td>Примітки</td><td>' + attributes['balancer'] + ' (ділянка №' + attributes['commnts'] + ')</td></tr>';
                        }
                    }
                    else if (layerName && layerName == "МАФ (земельна ділянка)" && (identityFields[i].name == 'OWNER_NAME' ||
                        identityFields[i].name == 'CUSTOMER_NAME' ||
                        identityFields[i].name == 'KVCPZ_CODE' ||
                        identityFields[i].name == 'AGREE_NUMBER' ||
                        identityFields[i].name == 'RESOLUTION_NUMBER' ||
                        identityFields[i].name == 'RESOLUTION_PUBLISHER_NAME')) {
                        if (identityFields[i].name == 'OWNER_NAME')
                            template += '<tr><td>' + identityFields[i].description +
                                '</td><td>' + attributes['OWNER_NAME'] +
                                ' (' + attributes['OWNER_EDRPOU'] + ')</td></tr>';
                        else if (identityFields[i].name == 'CUSTOMER_NAME')

                            template += '<tr><td>' + identityFields[i].description + '</td><td>' + attributes['CUSTOMER_NAME'] + ' (' + attributes['CUSTOMER_EDRPOU'] + ')</td></tr>';
                        else if (identityFields[i].name == 'KVCPZ_CODE')
                            template += '<tr><td>' + identityFields[i].description + '</td><td>' + attributes['KVCPZ_CODE'] + ' - ' + attributes['KVCPZ_NAME'] + '</td></tr>';
                        else if (identityFields[i].name == 'AGREE_NUMBER') {
                            if (attributes['AGREE_LINK'] && attributes['AGREE_LINK'] != 'Null' && attributes['AGREE_LINK'] != "")
                                template += '<tr><td>' + identityFields[i].description + '</td><td><a href="' + attributes['AGREE_LINK'] + '" target="_blank" title="Перейти до договору">№' + attributes['AGREE_NUMBER'] + ' від ' + attributes['AGREE_SIGN_DATE'] + '<span class="material-icons attr-link">link</span></a></td></tr>';
                            else
                                template += '<tr><td>' + identityFields[i].description + '</td><td>№' + attributes['AGREE_NUMBER'] + ' від ' + attributes['AGREE_SIGN_DATE'] + '</td></tr>';
                        }
                        else if (identityFields[i].name == 'RESOLUTION_NUMBER') {
                            if (attributes['RESOLUTION_LINK'] && attributes['RESOLUTION_LINK'] != 'Null' && attributes['RESOLUTION_LINK'] != "")
                                template += '<tr><td>' + identityFields[i].description + '</td><td><a href="' + attributes['RESOLUTION_LINK'] + '" target="_blank" title="Перейти до рішення">№' + attributes['RESOLUTION_NUMBER'] + ' від ' + attributes['RESOLUTION_DATE'] + '<span class="material-icons attr-link">link</span></a></td></tr>';
                            else
                                template += '<tr><td>' + identityFields[i].description + '</td><td>№' + attributes['RESOLUTION_NUMBER'] + ' від ' + attributes['RESOLUTION_DATE'] + '</td></tr>';

                        }
                        else if (identityFields[i].name == 'RESOLUTION_PUBLISHER_NAME')
                            template += '<tr><td>' + identityFields[i].description + '</td><td>' + attributes['RESOLUTION_PUBLISHER_NAME'] + ' (' + attributes['RESOLUTION_PUBLISHER_EDRPOU'] + ')</td></tr>';

                    }
                    //others-----------------
                    else if (identityFields[i].name == 'bindToServices') {
                        var btnsSTR = '';
                        identityFields[i].bindToServices.forEach(function (bsItem) {
                            //onclick="eventVue.$emit(\'showServieceObjectMap\', ' + JSON.stringify(bsItem) + ')"
                            var href = (window.location.pathname == '/' || window.location.pathname == '/opendataportal') ? window.location.origin + '/opendataportal/' : window.location.href;
                            var dtObject = JSON.stringify({
                                //url: (window.location.pathname == '/' ? window.location.origin + '/opendataportal/' : window.location.href) + bsItem.url + +attributes.AR_ID ,
                                url: (bsItem.type != 'bombshelters' ? href : '') + bsItem.url + +attributes.AR_ID + (bsItem.url_second_part ? bsItem.url_second_part : ''),
                                bindToServices: bsItem,
                                AR_ID: (attributes.AR_ID ? attributes.AR_ID : 0)
                            });
                            var btnClass = bsItem.type + '-btn';
                            //btnsSTR += `<button class='` + (bsItem.type == 'bombshelters' ? 'bombshelters-btn' : 'school-btn') + `' onclick='eventVue.$emit("getServiceObjectOnMap",` + dtObject + `)'>` + bsItem.name + `</button>`;

                            btnsSTR += `<button class='` + btnClass + `' onclick='eventVue.$emit("getServiceObjectOnMap",` + dtObject + `)'>` + bsItem.name + `<span class="material-icons">launch</span></button>`;
                        }.bind(this));
                        template += '<tr><td>' + identityFields[i].description + '</td><td class="areaBoxBtn">' + btnsSTR + '</td></tr>';
                    }
                    else if (identityFields[i].name == 'warmcon') {
                        var color = (attributes[identityFields[i].name] == 0 ? 'color:#0898c3;' : (attributes[identityFields[i].name] == 1 ? 'color:#ff2525;' : '')),
                            outSTR = (attributes[identityFields[i].name] == 0 ? '<span class="material-icons" style="transform: scale(0.9);">thermostat</span> очікуєсться' : (attributes[identityFields[i].name] == 1 ? '<span class="material-icons" style="transform: scale(0.9);">thermostat</span> підключено' : '')) + ' ' +
                                ((attributes[identityFields[i].name] == 0 && attributes['expdatewarmcon'] && attributes['expdatewarmcon'] != "Null") ? attributes['expdatewarmcon'] : ((attributes[identityFields[i].name] == 1 && attributes['datewarmcon'] && attributes['datewarmcon'] != "Null") ? attributes['datewarmcon'] : ''));
                        if (!isNaN(attributes[identityFields[i].name]))
                            template += '<tr><td>' + identityFields[i].description + '</td><td style="' + color + '; font-weight:400; display: flex; align-items: center;">' + outSTR + '</td></tr>';
                    }
                    else if (identityFields[i].name == 'BLOBS_ID' && attributes[identityFields[i].name] && attributes[identityFields[i].name].length > 0 && layerName == "Доступність інфраструктури") {
                        var arrL = attributes['BLOBS_ID'].split(','),
                            arrT = attributes['BLOBS_COMM'].split('#$#'),
                            links = [], titles = [];
                        arrL.forEach(function (item, index) {
                            links.push(("'https://acc.citynet.kharkov.ua/webaccesspoints/Home/blob?id=" + item + "&time=" + ((new Date()).getTime())).toString() + "'");
                            //var idI = item + "_",
                            //    title = arrT[index].substring(idI.length - 1).replace('_', "");
                            //titles.push(title ?  title :'');
                        }.bind(this));

                        template += '<tr><td></td><td><button class="photoBtn identify-btnDefault" onclick="showBlobs(null,[ ' + links + ' ],' + ("'" + attributes['BLOBS_COMM'].replace(/\r?\n/g, "") + "'") + ')"><span class="material-icons">photo_library</span>Фото</button></td></tr>';
                    }
                    else if (identityFields[i].name == 'FEATURE_TYPE' && layerName == "Доступність інфраструктури") {
                        var strs = ['', 'ДОСТУПНІ', 'ОБМЕЖЕНИЙ ДОСТУП', 'НЕДОСТУПНІ'],
                            colors = ['', '#4CAF50', '#eb8200', '#E53935'];
                        template += '<tr><td>' +
                            identityFields[i].description +
                            '</td><td><span style="font-weight: 600; color:' +
                            colors[attributes[identityFields[i].name]] +
                            '">' + strs[attributes[identityFields[i].name]] + '</span></td></tr>';
                    }
                    else if (identityFields[i].name == 'HASENTRANCE' && layerName == "Доступність інфраструктури") {
                        var str = (function () {
                            var out = '';
                            if (!isNaN(attributes['HASPARKING']) && attributes['HASPARKING'] > 0)
                                out += '<li>Парковка : <span class="markText">' + (attributes['HASPARKING'] == 1 ? 'Ні</span>' : 'Так</span>') + '</li>';
                            if (!isNaN(attributes['HASENTRANCE']) && attributes['HASENTRANCE'] > 0)
                                out += '<li>Вхід (пандус) : <span class="markText">' + (attributes['HASENTRANCE'] == 1 ? 'Ні</span>' : 'Так</span>') + '</li>';
                            if (!isNaN(attributes['HASTOILETS']) && attributes['HASTOILETS'] > 0)
                                out += '<li>Санвузол : <span class="markText">' + (attributes['HASTOILETS'] == 1 ? 'Ні</span>' : 'Так</span>') + '</li>';
                            if (!isNaN(attributes['HASINTERNAL']) && attributes['HASINTERNAL'] > 0)
                                out += '<li>Внутрішнє облаштування : <span class="markText">' + (attributes['HASINTERNAL'] == 1 ? 'Ні</span>' : 'Так</span>') + '</li>';
                            if (!isNaN(attributes['HASSURDO']) && attributes['HASSURDO'] > 0)
                                out += '<li>Сурдопереклад : <span class="markText">' + (attributes['HASSURDO'] == 1 ? 'Ні</span>' : 'Так</span>') + '</li>';
                            return out;
                        })();
                        if (str)
                            template += '<tr><td>' + identityFields[i].description + '</td><td><ul class="accessPoints-list">' + str + '</ul></td></tr>';
                    }

                    else if (identityFields[i].name == 'description' && layerName == 'asys.SDE.CyfraAccess') {
                        template += '<tr class="digitalInforow"><td>' + identityFields[i].description + '</td><td>' + attributes[identityFields[i].name] + '</td></tr>';
                    }

                    else if (attributes[identityFields[i].name] && attributes[identityFields[i].name] != 'Null' && attributes[identityFields[i].name] != "" && (typeof attributes[identityFields[i].name] == 'string' && attributes[identityFields[i].name].trim() != "")) {
                        //if (isNaN(attributes[identityFields[i].name]) && attributes[identityFields[i].name].trim() != "")
                        template += '<tr><td>' + identityFields[i].description + '</td><td>' + attributes[identityFields[i].name] + '</td></tr>';
                    }       
                }
                //showAreaBtn 
                if ((type.id == 3 && attributes.type == 2 && !isNaN(+attributes.institutionIdentifier_)) || (type.id == 15 && !isNaN(+attributes.inData_AID)) || (type.id == 2 && !isNaN(+attributes.OBJECTID))) {
                    var ID, type;
                    if (attributes.institutionIdentifier_) {
                        ID = attributes.institutionIdentifier_;
                        type = 'scool';
                    }
                    else if (attributes.AR_ID) {
                        ID = attributes.AR_ID;
                        type = 'bombshelter'
                    }
                    else if (attributes.OBJECTID) {
                        ID = attributes.OBJECTID;
                        type = 'medicine'
                    }
                    if (this.$store.getters.getAddressesObjectsList[ID])
                    template += `<tr>
                                    <td>Територія обслуговування</td>
                                    <td class="areaBoxBtn">
                                        <button class="showAreaBtn" onclick="eventVue.$emit('showAddressesObjectsOnMap', `+ID+`)">
                                            <i class="material-icons">apartment</i>
                                            Карта
                                        </button>
                                        <button onclick="eventVue.$emit('showAddressesObjectsList', {ID:`+ID+`, type:'`+type+`'})">
                                        Список
                                        </button>
                                    </td>
                                </tr>`;
                }


                if (layerName && layerName == "ОСББ, ЖК та ЖБК") {
                    osbbPhotosData = null;
                    var ARIDS = [117950, 114681];
                    //if (ARIDS.join('_').indexOf(attributes['AR_ID']) >= 0) {

                    //    template += `<tr>
                    //                <td></td>
                    //                <td class="areaBoxBtn">
                    //                    <button class="showAreaBtn" onclick="eventVue.$emit('showMoreForBuilds', `+ attributes['AR_ID']+`)">
                    //                        <i class="material-icons">account_balance</i>
                    //                        об'єднання
                    //                    </button>
                    //                </td>
                    //            </tr>`;
                    //}
                    //else
                    var imgs = [], outUrls = [], is_num = 0, AID = attributes['AR_ID'], isJpg = false, isPng = false, OID = attributes['OBJECTID'];

                    if (attributes['osbb_nom'] && attributes['osbb_nom'] >= 0) {
                        template += `<tr>
                                    
                                    <td class="photoBoxBtn zf_`+ attributes['OBJECTID'] +`">
                                        
                                    </td>

                                    <td class="areaBoxBtn">
                                        <button class="showAreaBtn" id="h_blob_`+ attributes['osbb_nom']+`" onclick="eventVue.$emit('showMoreForBuilds', `+ attributes['osbb_nom'] + `)" style="display:none;">
                                            <i class="material-icons">account_balance</i>
                                            об'єднання
                                        </button>
                                    </td>
                                </tr>`;
                        this.$store.dispatch(this.housesStore.methods.HouseByOSBB.name, { url: this.housesStore.methods.HouseByOSBB.url, osbb_nom: attributes['osbb_nom'] });
                        chackImages(attributes['AR_ID'], false);
                    }
                    else if (attributes['AR_ID'] && attributes['AR_ID'] >= 0 && !document.querySelector('.photoBoxBtn button')) {
                        template += `<tr>
                                    <td></td>
                                    <td class="photoBoxBtn zf_`+ attributes['OBJECTID']+`">
                                        
                                    </td>
                                </tr>`;
                                              

                       // var imgs = [], outUrls = [], is_num = 0, AID = attributes['AR_ID'], isJpg = false, isPng = false, OID = attributes['OBJECTID'];
                        chackImages(attributes['AR_ID'], false);


                    }
                        function chackImages(AID, is_) {
                            var img = new Image();
                            img.classList.add('zf_' + OID);
                            //если есть блоб то добавляем его в список
                            img.onload = function (e) {
                                imgs.push(e.target);
                                outUrls.push(e.target.src);
                                //isJpg = false; isPng = false;
                                if (is_) {
                                    chackImages(AID, true);
                                }
                                else {
                                    var boxId = e.target.getBoxId(e.target);
                                    var parent = document.querySelector('.photoBoxBtn .' + boxId),
                                        node = document.createElement('button');
                                    node.classList.add('photoBtn');
                                    node.innerHTML = '<i class="material-icons">photo_library</i >Фото';
                                    node.onclick = function () { showBlobs(null, outUrls[0]); };
                                    if (parent)
                                        parent.append(node);

                                    osbbPhotosData = { parent: parent, boxId: boxId, node: node, outUrls: outUrls };
                                    eventVue.$emit('updateInfoTamplateOSBB', osbbPhotosData);
                                    
                                    isJpg = false; isPng = false;
                                }
                            }
                            //если ошибка, то не грузим блоб
                            img.onerror = function (e) {
                                if (is_) {
                                    if (outUrls.length > 0) {
                                        var boxId = e.target.getBoxId(e.target);
                                        var parent = document.querySelector('.photoBoxBtn .' + boxId),
                                            node = document.createElement('button');
                                        node.innerHTML = '<i class="material-icons">photo_library</i >Фото';
                                        node.classList.add('photoBtn');
                                        node.onclick = function () { showBlobs(null, outUrls); };
                                        //node = document.createElement(`<button onclick="showBlobs(null, ` + outUrls[0] + `);" > <i class="material-icons">photo_library</i >Фото</button>`);
                                        if (parent)
                                            parent.append(node);
                                        osbbPhotosData = { parent: parent, boxId: boxId, node: node, outUrls: outUrls };
                                        eventVue.$emit('updateInfoTamplateOSBB',osbbPhotosData );
                                    }
                                    else if (!isPng){
                                        //isPng = true;
                                        chackImages(AID, true);
                                    }
                                }
                                else {                                    
                                    
                                    if (isJpg == isPng == true) {
                                        isJpg = false; isPng = false;
                                        chackImages(AID, true);
                                    }
                                    else {
                                        //isPng = true;
                                        chackImages(AID, false);
                                    }
                                }
                                  //  document.querySelector('.photoBoxBtn').append(`<button onclick="showBlobs(` + outUrls + `);" > <i class="material-icons">photo_library</i >Фото</button>`);
                            }.bind(this);

                            img.getBoxId = function (e) {
                                var res = 0, cls;
                                e.classList.forEach(function (cItem) {
                                    if (cItem.indexOf('zf_') >= 0)
                                        cls = cItem;
                                }.bind(this));
                                //res = cls.substring(3);
                                res = cls;
                                return res;
                            }.bind(this)
                            var tp = '';


                            if (!is_) {
                                if (!isJpg) {
                                    tp = '.jpg';
                                    isJpg = true;
                                }
                                else {
                                    tp = '.png';
                                    isPng = true;
                                }
                                img.src = (`https://smart.khmr.gov.ua/opendataportal/Images/builds/` + attributes['AR_ID'] + tp);
                            }
                            else {
                                if (outUrls.length == 0) {
                                    if (!isJpg) {
                                        tp = '.jpg';
                                        isJpg = true;
                                        is_num++;
                                    }
                                    else {
                                        tp = '.png';
                                        isPng = true;
                                        is_num = 1;
                                    }
                                }
                                else {
                                    if (isJpg && isPng) {
                                        tp = '.png';
                                        is_num++;
                                    }
                                    else {
                                        tp = '.jpg';
                                        is_num++;
                                    }
                                }
                                
                                img.src = (`https://smart.khmr.gov.ua/opendataportal/Images/builds/` + attributes['AR_ID'] + `_` + is_num + tp);

                            }
                        }
                }

                if (layerName && layerName == "Пам\'ятки архітектури" && attributes['BLOB_URL']) {
                        template += `<tr>                                    
                                    <td colspan="2" class="blobTD_`+ attributes['Id']+`">
                                       <!-- <img src="http://arch.kharkov.ua`+ attributes['BLOB_URL']+`">-->
                                    </td>
                                </tr>`;
                    function checkImage(url, Id) {
                        var img = new Image();
                        
                        //если есть блоб то добавляем его в список
                        img.onload = function (e) {
                            var parent = document.querySelector('.blobTD_' + Id),
                                node = document.createElement('img');
                            //node.style.width = '300px';
                            node.src = e.path[0].currentSrc;
                            node.onclick = function () { showBlobs(null, e.path[0].currentSrc); };
                            if (parent)
                                parent.append(node);
                            eventVue.$emit('repositionInfoWindow');
                        }

                        img.src = (`http://arch.kharkov.ua` + url);
                    }
                    checkImage.call(this, attributes['BLOB_URL'], attributes['Id']);
                }

                if (layerName && layerName == "МАФ") {
                    var mafBlobs = [], str = '/opendataportal/Content/maf/maf_17_1_';
                    for (var i = 0; i < 2; i++)
                        mafBlobs.push("'"+str+(i+1)+".jpg'");
                    template += '<tr><td></td><td><button onclick="showBlobs(null,[' + mafBlobs + '])"><i class="material-icons">photo_library</i >Фото</button></td></tr>';
                }
                
            }
          
            return template;
        },

        repositionInfoWindow: function (screenPt, mapPt) {
            //if (document.documentElement.clientWidth <= 768) {
                var popupLeft = document.getElementsByClassName('esriPopupWrapper')[0].offsetLeft,
                    popupVisibleLeft = document.getElementsByClassName('esriPopupVisible')[0].offsetLeft || 0,
                    popupTop = document.getElementsByClassName('esriPopupWrapper')[0].offsetTop,
                    popupVisibleTop = document.getElementsByClassName('esriPopupVisible')[0].offsetTop,
                    headerHeight = document.getElementsByClassName('navbar-header')[0].clientHeight,
                    headerWidth = document.getElementsByClassName('navbar-header')[0].clientWidth,
                    winH = document.documentElement.clientHeight,
                    winW = document.documentElement.clientWidth,
                    sPt = screenPt ? screenPt : this.currentClickEventData.screenPoint,
                    mPt = mapPt ? mapPt : this.currentClickEventData.mapPoint,
                    popupH = document.getElementsByClassName('esriPopupWrapper')[0].clientHeight,
                    popupW = document.getElementsByClassName('esriPopupWrapper')[0].clientWidth,
                    deltaX = 0, deltaY = 0, deltaExtentX, deltaExtentY, pt, newSPtX, newSptY
                    ;

                //if ((popupLeft + popupVisibleLeft < 0 || (popupLeft + popupVisibleLeft + popupW) > winW) && (sPt.x + popupW) > winW)
                //    deltaX = Math.abs(sPt.x + popupW - winW); 

            //очистка после проекта "Доступність інфраструктури"
            if ($('.esriPopupWrapper.accessPoints')) {
                $('.esriPopupWrapper.accessPoints').removeClass('accessPoints');
            }

            if (popupVisibleLeft < 0 || (popupLeft + popupVisibleLeft + popupW - 5) > winW || popupVisibleTop + popupTop + popupH > winH || (popupTop + popupVisibleTop - headerHeight) < 0) {

                if (popupVisibleLeft < 0)
                    deltaX = 20;
                else if ((popupLeft + popupVisibleLeft + popupW - 5) > winW)
                    deltaX = Math.abs(winW - (popupVisibleLeft + popupW) - 20);

                //if (popupVisibleLeft  < 0)
                //    deltaX = popupVisibleLeft - popupLeft + (2 * popupW);
                //else if ((popupLeft + popupVisibleLeft + popupW - 5) > winW)
                //    deltaX = Math.abs(winW - (popupVisibleLeft + popupW) - 20);
                //    //deltaX = Math.abs(popupVisibleLeft - clientWidth - popupW - 20);

                //if ((popupTop + popupVisibleTop) <  0 && (sPt.y - popupH - 60) < 0)
                //    deltaY = Math.abs(sPt.y - popupH - popupVisibleTop/2);

                //if (popupVisibleTop < 0)
                if (popupVisibleTop + popupTop + popupH > winH)
                    deltaY = 30;
                else if ((popupTop + popupVisibleTop - headerHeight) < 0)
                    deltaY = Math.abs(popupVisibleTop - headerHeight - popupH - 20);

                //if (popupVisibleTop < 0)
                ////if (popupVisibleTop + popupTop + popupH > winH)
                //    deltaY = popupVisibleTop  - popupTop + (2*popupH);
                //else if ((popupTop + popupVisibleTop - headerHeight) < 0)
                //    deltaY = Math.abs(popupVisibleTop - headerHeight - popupH - 20);


                var newSPtX = sPt.x < 0 ? deltaX : (sPt.x + (deltaX ? deltaX : 0)),
                    newSptY = (sPt.y + popupTop) > winH ? deltaY : sPt.y + (deltaY ? deltaY : 0);

                sPt.x = newSPtX;
                sPt.y = newSptY;

                pt = new this.widgets.screenUtils.toMapPoint(this.map.extent, this.map.width, this.map.height, sPt);

                if (popupVisibleLeft < 0)
                    deltaExtentX = mPt.x - pt.x;
                else
                    deltaExtentX = Math.abs(mPt.x - pt.x);

                //if (popupVisibleTop < 0)
                if (popupVisibleTop + popupTop + popupH > winH)
                    deltaExtentX = mPt.y - pt.y;
                else
                    deltaExtentY = Math.abs(mPt.y - pt.y);

                var Newextent = new esri.geometry.Extent({
                    "xmin": this.map.extent.xmin + deltaExtentX,
                    "ymin": this.map.extent.ymin + (deltaExtentY ? (deltaExtentY + ((popupVisibleTop + popupH > winH) ? -40 : 40)) : 0),
                    "xmax": this.map.extent.xmax + deltaExtentX,
                    "ymax": this.map.extent.ymax + (deltaExtentY ? (deltaExtentY + ((popupVisibleTop + popupH > winH) ? -40 : 40)) : 0),
                    "spatialReference": { "wkid": 28467 }
                });
                this.zoomToExtent(Newextent);
            }
            //}
          
        },
        clearSelectioHidePopup: function () {
            this.clearCraphicLayer();
            this.showedAddressObjects = false;
            this.hideInfowindow();
        },

        addSelectGeometry: function (e, infoTemplate) {
            this.clearCraphicLayer();
            this.showAddressesNotFound(false);
            var highlightSymbol,
                highlightGraphic,
                geometryType = e[0].geometryType || e[0].feature.geometry.type || e[0].feature.geometryType,
                layerId,
                feature = e[0].feature,
                layerName = e[0].layerName || e[0].feature.layerName || e[0].content.layerName || e[0].feature.getLayer()._attrs.name,
                layer = this.$store.getters.geLayerByVectorLayerName(layerName) || this.$store.getters.geLayerByLayerName(layerName),
                attributes = (feature.attributes ? feature.attributes : {}),
                identityProps = e[0].layerIdentityProp
                ;
            if (!geometryType) {
                if (layerName == "WEBADREG.%V_RECLAMA_FOR_SMARTCITY Events")
                    geometryType = 'esriGeometryPoint';
            }

          //  if ((layerName != "Будівлі і споруди" && layerName != "Вулиці міста")) {
                if (geometryType == 'esriGeometryPolygon' || geometryType == "polygon") {
                    highlightSymbol = new this.widgets.SimpleFillSymbol(this.widgets.SimpleFillSymbol.STYLE_SOLID,
                        new this.widgets.SimpleLineSymbol(this.widgets.SimpleLineSymbol.STYLE_SOLID, new this.widgets.Color([6, 201, 169, 1]), 3),
                        new this.widgets.Color([6, 201, 169, 0.0])
                    );

                    highlightGraphic = new this.widgets.Graphic(feature.geometry, highlightSymbol, (feature.attributes ? feature.attributes : {}), infoTemplate);
                }
                else if (geometryType == 'esriGeometryPolyline' || geometryType == 'polyline') {
                    highlightSymbol = new this.widgets.SimpleLineSymbol(this.widgets.SimpleLineSymbol.STYLE_SOLID, new this.widgets.Color([6, 201, 169, 1]), 3);
                    highlightGraphic = new this.widgets.Graphic(feature.geometry, highlightSymbol, (feature.attributes ? feature.attributes : {}), infoTemplate);
                }
                else if (geometryType == 'esriGeometryPoint' || geometryType == 'point') {
                    var height = 17, width = 17, yoffset = 0, xoffset = 0;
                    if (layer.selectIconSize) {
                        height = layer.selectIconSize.height;
                        width = layer.selectIconSize.width;
                    }
                    var pUrl = '/opendataportal/Images/' + (identityProps && identityProps.selectedMarkerFileName ? identityProps.selectedMarkerFileName : ('select_' + layer.id + '.svg'));
                    if (layerName == 'Доступність інфраструктури') {
                        pUrl = '/opendataportal/Images/select_16_' + attributes.FEATURE_CODE + '.png';
                        height = 26, width = 24;
                    }
                    if (layerName == "WIFI") {
                        pUrl = '/opendataportal/Images/select_4.svg';
                        height = 28, width = 18; yoffset = -3;
                    }
                    if (layerName == "Рекламні конструкції") {
                        pUrl = '/opendataportal/Images/select_1.svg';
                        height = 24, width = 24; 
                    }
                    if (layerName == 'Гідранти') {
                        var typeN;
                        switch (feature.attributes.TYPE_) {
                            case 'Г':
                                typeN = 2;
                                break;
                            case 'П':
                                typeN = 3;
                                break;
                            case 'ПB':
                                typeN = 4;
                                break;
                            case 'ПГ':
                                typeN = 5;
                                break;
                            default:
                                typeN = 1;
                        }
                        pUrl = '/opendataportal/Images/select_24_'+typeN+'.svg';
                        height = 15, width = 13, yoffset = 0;
                    }
                    if (layerName == 'Пункти обігріву' || layerName == 'Зупинки-укриття "Захист"') {
                        height = 34, width = 34, yoffset = 0;
                    }
                    if (layerName == 'Пункти харчування населення' || layerName == 'АЗС' || layerName == 'Непродовольчі магазини' || layerName == 'Ветеринарні клініки' || layerName == 'Укриття' || layerName == 'Пункти незламності') {
                        height = 31, width = 31, yoffset = 0;
                    }
                    if (layerName == 'Лікарні' || layerName == 'Поліклініки' || layerName == 'Аптеки' || layerName == 'Джерела водопостачання') {
                        height = 34, width = 34, yoffset = 0;
                    }
                    if (layerName == 'Ринки' || layerName == 'Зоомагазини' || layerName == 'Відділи поліції') {
                        height = 34, width = 34, yoffset = 0;
                    }
                    if (layerName == 'Продовольчі магазини') {
                        height = 31, width = 31, yoffset = 1.5, xoffset = -0.5;
                    }
                    //if () {
                    //    height = 34, width = 34, yoffset = 0;
                    //}
                    highlightSymbol = new this.widgets.PictureMarkerSymbol({
                        "angle": 0, "xoffset": xoffset, "yoffset": yoffset, "type": "esriPMS",
                        "url": pUrl,
                        "contentType": "image/svg", "width": width, "height": height
                    });
                    if (layerName == "WEBADREG.%V_RECLAMA_FOR_SMARTCITY Events" || layerName == "asys.SDE.bombshelters" || layerName == "asys.SDE.munic_education" || layerName == "asys.SDE.munic_medicine")
                        feature.geometry = new this.widgets.Point({ 'x': e[0].feature.geometry.x, 'y': e[0].feature.geometry.y, 'spatialReference': { 'wkid': 28467 } });

                    highlightGraphic = new this.widgets.Graphic(feature.geometry, highlightSymbol, attributes, infoTemplate);

                }
           // }
            //else
            //    highlightGraphic = feature;
            this.map.graphics.add(highlightGraphic);
            this.zoomToSelectedFeatures();
            return highlightGraphic;
        },

        showInfoWindow: function (data, prop) {
            var cFeatureTemplate, layerProperties;

            if (data && data.length > 0) {

                if (!this.cFFeature) {
                    this.cFFeature = [];
                    data.forEach(function (cFItem) {
                        //cFItem.feature.symbol = new this.widgets.PictureMarkerSymbol({
                        //    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                        //    "url": "/opendataportal/Images/select_" + prop.id + ".svg",
                        //    "contentType": "image/svg", "width": 16, "height": 16
                        //});

                        cFItem.feature.geometryType = 'esriGeometryPoint';
                        cFItem.feature.layerName = cFItem.layerName;
                        this.cFFeature.push(cFItem.feature);
                    }.bind(this));
                }
                for (var i = 0; i < data.length; i++) {
                    data[i].layerName = prop.name;
                    layerProperties = this.$store.getters.getLayerByTocName(data[i].layerName == 'ОСББ, ЖК та ЖБК' ? 'Житло' : data[i].layerName) || prop;
                    //для слоев с релейшн
                    if (layerProperties && (layerProperties.name == 'Жилкомсервіс' || layerProperties.name == 'Укриття для населення' || layerProperties.name == 'ОСББ, ЖК та ЖБК')) {
                        for (var j = 0; j < this.cFFeature.length; j++) {
                            //if (data[i].Id == this.cFFeature[j].attributes.OBJECTID || data[i].OBJECTID == this.cFFeature[j].attributes.OBJECTID) {
                            cFeatureTemplate = this.createInfoTemplate(this.cFFeature[j].attributes, layerProperties);
                            this.cFFeature[j].setInfoTemplate(cFeatureTemplate);
                        }
                    }
                    else {
                        if (layerProperties)
                        for (var j = 0; j < this.cFFeature.length; j++) {
                            if (data[i].Id == this.cFFeature[j].attributes.OBJECTID || data[i].OBJECTID == this.cFFeature[j].attributes.OBJECTID || (data[i].feature && this.cFFeature[j] && data[i].feature.attributes && this.cFFeature[j].attributes && data[i].feature.attributes.OBJECTID == this.cFFeature[j].attributes.OBJECTID)) {
                                cFeatureTemplate = this.createInfoTemplate(data[i], layerProperties);
                                this.cFFeature[j].setInfoTemplate(cFeatureTemplate);
                            }
                        }
                    }
                }
                if (cFeatureTemplate) {
                    this.cFFeature.forEach(function (cffItem) {
                        if (cffItem.layerName)
                            this.addSelectGeometry([{ feature: cffItem, geometryType: cffItem.geometryType, layerName: cffItem.layerName }], cffItem.infoTemplate);
                    }.bind(this));
                  //  this.zoomToSelectedFeatures();

                    this.map.infoWindow.setFeatures(this.cFFeature);
                }
            }
            else if (!data && prop && this.cFFeature && this.cFFeature.length > 0) {
                for (var j = 0; j < this.cFFeature.length; j++) {
                    this.cFFeature[j].attributes.layerName = prop.name;
                    layerProperties = this.$store.getters.getLayerByTocName(this.cFFeature[j].attributes.layerName);
                    cFeatureTemplate = this.createInfoTemplate(this.cFFeature[j].attributes, layerProperties);
                    this.cFFeature[j].setInfoTemplate(cFeatureTemplate);

                    //если выбран обьект слоя "Доступність", добавляем класс

                    if (prop.name == 'Доступність інфраструктури' && $('.esriPopupWrapper')) {
                        $('.esriPopupWrapper').addClass('accessPoints')
                    }

                }
               // this.zoomToSelectedFeatures();

                this.map.infoWindow.setFeatures(this.cFFeature);
                
            }
            else {
                data.layerName = prop[0].layerName;
                layerProperties = this.$store.getters.getLayerByTocName(data.layerName);
                cFeatureTemplate = this.createInfoTemplate(data, layerProperties);
                this.cFFeature.setInfoTemplate(cFeatureTemplate);
                this.addSelectGeometry(prop);                
                this.map.infoWindow.setFeatures([this.cFFeature]);
            }
            if (layerProperties) {
                if (!layerProperties.cluster)
                    this.zoomToSelectedFeatures();
                setTimeout(function () {
                    this.map.infoWindow.show(this.currentClickEventData.mapPoint, this.map.getInfoWindowAnchor(this.currentClickEventData.screenPoint));
                    if (layerProperties.cluster)
                        setTimeout(function () {
                            this.repositionInfoWindow();
                        }.bind(this), 200);

                }.bind(this), 500);
            }
            //this.map.infoWindow.show(this.currentClickEventData.mapPoint, this.map.infoWindow.ANCHOR_LOWERLEFT);

        },
        zoomToSelectedFeatures: function () {
            var extent = this.widgets.graphicsUtils.graphicsExtent(this.map._layers.map_graphics.graphics),
                delta = 100;
            if (extent) {
                extent.xmin = extent.xmin - delta;
                extent.xmax = extent.xmax + delta;
                extent.ymin = extent.ymin - delta;
                extent.ymax = extent.ymax + delta;

                this.map.setExtent(extent, true);
            }
        },
        updateInfoTamplate: function (osbb_nom) {
            if (this.map.infoWindow.features.length > 0) {
                var indx, tmplt;
                this.map.infoWindow.features.forEach(function (fItem, index) {
                    if (fItem.attributes.osbb_nom == osbb_nom) {
                        tmplt = fItem.infoTemplate.content.replace('style="display:none;"', 'style="display:block;"');
                        indx = index;
                    }
                }.bind(this));
                if (indx >= 0)
                    this.map.infoWindow.features[indx].infoTemplate.setContent(tmplt);

                //setTimeout(function () {
                //    this.updateInfoTamplateOSBB(osbbPhotosData);
                //}.bind(this), 1000);
            }
        },
        updateInfoTamplateOSBB: function (data) {
            var node = document.querySelector('button.photoBtn');
            if (node)
                node.remove();
                
            if (this.map.infoWindow.features && this.map.infoWindow.features.length > 0 && data) {
                var indx, tmplt, oid = data.boxId.replace('zf_', '');
                this.map.infoWindow.features.forEach(function (fItem, index) {
                    if (fItem.attributes.OBJECTID == oid) {
                        tmplt = fItem.infoTemplate.content.replace('class="photoBoxBtn ' + data.boxId + '">', 'class="photoBoxBtn ' + data.boxId + '">' + data.node.outerHTML.toString());
                        indx = index;
                    }
                }.bind(this));
                if (indx >= 0) {
                    //tmplt.replace('class="photoBoxBtn ' + data.boxId + '">', 'class="photoBoxBtn ' + data.boxId + '">' + data.node.outerHTML);
                    setTimeout(function () {
                       // this.map.infoWindow.features[indx].infoTemplate.setContent(tmplt);
                        var par = document.querySelector('.photoBoxBtn');
                           
                        if (par) {
                            var node = document.querySelector('button.photoBtn');
                            if (!node)
                               // node.remove();
                            par.append(data.node);
                        }
                    }.bind(this), 500);

                }
            }
        },
        updateInfoTamplateMonuments: function (data) {
            var node = document.querySelector('button.photoBtn');
            if (node)
                node.remove();

            if (this.map.infoWindow.features && this.map.infoWindow.features.length > 0 && data) {
                var indx, tmplt, oid = data.boxId.replace('zf_', '');
                this.map.infoWindow.features.forEach(function (fItem, index) {
                    if (fItem.attributes.OBJECTID == oid) {
                        tmplt = fItem.infoTemplate.content.replace('class="photoBoxBtn ' + data.boxId + '">', 'class="photoBoxBtn ' + data.boxId + '">' + data.node.outerHTML.toString());
                        indx = index;
                    }
                }.bind(this));
                if (indx >= 0) {
                    //tmplt.replace('class="photoBoxBtn ' + data.boxId + '">', 'class="photoBoxBtn ' + data.boxId + '">' + data.node.outerHTML);
                    setTimeout(function () {
                        // this.map.infoWindow.features[indx].infoTemplate.setContent(tmplt);
                        var par = document.querySelector('.photoBoxBtn');

                        if (par) {
                            var node = document.querySelector('button.photoBtn');
                            if (!node)
                                // node.remove();
                                par.append(data.node);
                        }
                    }.bind(this), 500);

                }
            }
        },
        removeInfoWindowBtn: function (type) {
            var el = document.querySelector('.'+type + '-btn');
                el.remove();
        },
        //addressesIdsList
        getAddressObjectsGeometriesByAddressObjectsList_old: function (data) {
            if (this.showAddressesObjectsList)
                this.showAddressesObjectsListPanel();

            if (data.response.length > 0) {
                var res = [], ids = [];
                //обнуляем
                this.QT.length = 0;

                //СИТУАЦИЯ КОГДА  БОЛЬШЕ 1000 НЕ ОБРАБОТАНО !!!!!!!!!!!!!!
                // if (data.response.length < 1000) {
                var q = new this.widgets.Query(), str = '';
                data.response.forEach(function (drItem) {
                    if (str.length > 0)
                        str += ',';
                    str += drItem;
                }.bind(this));
                q.outFields = ["*"];
                q.returnGeometry = true;
                q.orderByFields = ["ADDRESSID", "FULLADDRUA"];
                //q.where = "AR_ID IN (" + str + ")";
                q.where = "AR_ID IN (" + str + ") AND TypeOfBuild = 1";
                //q.geometryType = 'esriGeometryEnvelope';
                //q.spatialRel = 'esriSpatialRelIntersects';
                //q.units = 'esriSRUnit_Foot';
                //q.returnTrueCurves = false;
                //q.returnIdsOnly = false;
                //q.returnCountOnly = false;
                //q.returnZ = false;
                //q.returnM = false;
                //q.returnDistinctValues = false;
                //q.returnExtentOnly = false;
                //q.featureEncoding = 'esriDefault';
                //q.f = 'pjson';




                res.push(new this.widgets.QueryTask("https://smart.khmr.gov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/6")
                    .execute(q)
                );


               // this.$store.commit('set_isSearcherInit', false);
                promices = this.widgets.all(res);
                promices.then(e => {
                    if (e.length > 0) {
                        store.commit('setAddressObjectsList', e);
                        var o_ = {};
                        if (data.res.ajax.name == 'GetAddressesByBombShelter')
                            Vue.set(o_, data.res.bombGuid, e[0]);
                        if (data.res.ajax.name == 'GetAddressesByPrimarySchool')
                            Vue.set(o_, data.res.schoolGuid, e[0]);
                        if (data.res.ajax.name == 'GetAddressesByHospital')
                            Vue.set(o_, data.res.medGuid, e[0]);
                        store.commit('setServiceAddresses', o_);
                        this.handleIdentityResult(data.res.res);
                    }
                    this.$store.commit('set_isSearcherInit', true);
                }).catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('simpleMessage', thrown.message);
                });
            }
            else {
                data.res.res[0][0].addressesLoaded = true;
                this.handleIdentityResult(data.res.res);
            }
                //eventVue.$on('showSimpleMessage', this.$store.state.messagesStore.messagesTexts.hasNoData);
        },

        getAddressObjectsGeometriesByAddressObjectsList: function (data) {
            if (this.showAddressesObjectsList)
                this.showAddressesObjectsListPanel();

            if (data.response.length > 0) {
                var res = [], ids = [];
                //обнуляем
                this.QT.length = 0;

                //СИТУАЦИЯ КОГДА  БОЛЬШЕ 1000 НЕ ОБРАБОТАНО !!!!!!!!!!!!!!
                // if (data.response.length < 1000) {
                var q = new this.widgets.Query(), str = '';
                data.response.forEach(function (drItem) {
                    if (str.length > 0)
                        str += ',';
                    str += drItem;
                }.bind(this));
                q.outFields = ["*"];
                q.returnGeometry = true;
                q.orderByFields = ["ADDRESSID", "FULLADDRUA"];
                //q.where = "AR_ID IN (" + str + ")";
                q.where = "AR_ID IN (" + str + ") AND TypeOfBuild = 1";
                //q.geometryType = 'esriGeometryEnvelope';
                //q.spatialRel = 'esriSpatialRelIntersects';
                //q.units = 'esriSRUnit_Foot';
                //q.returnTrueCurves = false;
                //q.returnIdsOnly = false;
                //q.returnCountOnly = false;
                //q.returnZ = false;
                //q.returnM = false;
                //q.returnDistinctValues = false;
                //q.returnExtentOnly = false;
                //q.featureEncoding = 'esriDefault';
                //q.f = 'pjson';




                res.push(new this.widgets.QueryTask("https://smart.khmr.gov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/6")
                    .execute(q)
                );


               // this.$store.commit('set_isSearcherInit', false);
                promices = this.widgets.all(res);
                promices.then(e => {
                    if (e.length > 0) {
                        store.commit('setAddressObjectsList', e);
                        var o_ = {};
                        if (data.res.ajax.name == 'GetAddressesByBombShelter')
                            Vue.set(o_, data.res.bombGuid, e[0]);
                        if (data.res.ajax.name == 'GetAddressesByPrimarySchool')
                            Vue.set(o_, data.res.schoolGuid, e[0]);
                        if (data.res.ajax.name == 'GetAddressesByHospital')
                            Vue.set(o_, data.res.medGuid, e[0]);
                        store.commit('setServiceAddresses', o_);
                        //this.handleIdentityResult(data.res.res);
                        //Vue.set(data.res.identityData, 'fromServiceObject', true);
                        //this.showServiceObject(data.res.identityData);
                    }
                    this.$store.commit('set_isSearcherInit', true);
                }).catch(function (thrown) {
                    store.commit('set_isSearcherInit', true);
                    eventVue.$emit('simpleMessage', thrown.message);
                });
            }
            else {
                data.res.addressesLoaded = true;
                this.handleIdentityResult(data.res);
            }
                //eventVue.$on('showSimpleMessage', this.$store.state.messagesStore.messagesTexts.hasNoData);
        },

        showAddressesObjectsOnMap: function (ID) {

            this.removeAddressObjectsFromGraphicLayer();
            var list = this.$store.getters.getAddressesObjectsList;
            if (list[ID] && list[ID].features.length > 0) {


                list[ID].features.forEach(function (efItem) {
                            if (efItem.geometry)
                                this.map.graphics.add(new this.widgets.Graphic(efItem.geometry, this.polygonHighlightSymbol, efItem.attributes));
                        }.bind(this));



                this.showedAddressObjects = true;

                var extent = this.widgets.graphicsUtils.graphicsExtent(this.map._layers.map_graphics.graphics),
                    delta = 200;

                extent.xmin = extent.xmin - delta;
                extent.xmax = extent.xmax + delta;
                extent.ymin = extent.ymin - delta;
                extent.ymax = extent.ymax + delta;

                this.map.setExtent(extent, true);

                //if (window.innerWidth < 768) {
                //    setTimeout(function () {
                //        var sp = new this.widgets.screenUtils.toScreenPoint(this.map.extent, this.map.width, this.map.height, this.map.infoWindow.features[0].geometry);
                //        this.repositionInfoWindow(sp, this.map.infoWindow.features[0].geometry);
                //    }.bind(this), 500);
                //}
            }
        },

        showServiceObjectOnMap: function (data) {
            var res = [],
                layerOption = this.$store.getters.geLayerById(data.prop.bindToServices.layerId),
                addedData = false;

            data.response.forEach(function (drItem) {                
                if (drItem.GUID) {
                    var q = new this.widgets.Query();
                    q.outFields = ["*"];
                    q.returnGeometry = true;
                    q.where = data.prop.bindToServices.field + "=" + +drItem.GUID;
                    res.push(new this.widgets.QueryTask(layerOption.url + '/' + layerOption.layerIds[0])
                        .execute(q)
                    );
                }
                else if (drItem.features && Array.isArray(drItem.features) && drItem.features.length > 0) {
                    drItem.features.forEach(function (dItem) {
                        var q = new this.widgets.Query();
                        q.outFields = ["*"];
                        q.returnGeometry = true;
                        q.where = data.prop.bindToServices.field + "=" + +dItem.attributes[data.prop.bindToServices.field];
                        res.push(new this.widgets.QueryTask(layerOption.url + '/' + layerOption.layerIds[0])
                            .execute(q)
                        );
                    }.bind(this));
                }
                else if (drItem[0].feature && !drItem[0].feature.geometry.rings) {
                    var q = new this.widgets.Query();
                    q.outFields = ["*"];
                    q.returnGeometry = true;
                    q.where = data.identity.bindToAddressField + "=" + +drItem[0].feature.attributes[data.identity.bindToAddressField];
                    res.push(new this.widgets.QueryTask(layerOption.url + '/' + layerOption.layerIds[0])
                        .execute(q)
                    );
                }
            }.bind(this));
            this.$store.commit('set_isSearcherInit', false);

            promices = this.widgets.all(res);
            promices.then(e => {
                this.hideInfowindow();
                var currentClickEventData = this.$store.getters.getCurrentClickEventData;
                currentClickEventData.mapPoint = e[0].features[0].geometry;
                this.$store.commit('set_currentMapClick', currentClickEventData);
                var hrArr = [];
                if (e && Array.isArray(e) && e.length > 0) {
                    e.forEach(function (eItem) {
                        hrArr.push({
                            feature: eItem.features[0],
                            geometryType: eItem.geometryType,
                            layerName: layerOption.nameVectorLayer,
                            bindedObject: true
                        });
                        //this.handleIdentityResult([[{
                        //    feature: eItem.features[0],
                        //    geometryType: eItem.geometryType,
                        //    layerName: layerOption.nameVectorLayer,
                        //    bindedObject: true
                        //}]]);
                    }.bind(this));
                }

                if (hrArr.length > 0) {
                    this.cFFeature = null;
                    this.showInfoWindow(hrArr, layerOption);
                }

            if (window.innerWidth < 768)
                setTimeout(function () {
                    var sp = new this.widgets.screenUtils.toScreenPoint(this.map.extent, this.map.width, this.map.height, e[0].features[0].geometry);
                    this.repositionInfoWindow(sp, e[0].features[0].geometry);
                }.bind(this), 1000);

            this.$store.commit('set_isSearcherInit', true);

            }).catch(function (thrown) {
                store.commit('set_isSearcherInit', true);
                eventVue.$emit('simpleMessage', thrown.message);
            });
        },

        showAddressesObjectsListPanel: function (zoomToMainObject, ID, type) {

            this.removeAddressObjectsFromGraphicLayer();

            this.updateIT();

           //this.showAddressesObjectsList = !this.showAddressesObjectsList;

            if (!this.cFFeature || !this.cFFeature[0])
                this.cFFeature = [this.map.graphics.graphics[0]];

            this.addressesObjectsListType = (type ? type : '');
            
            var list = this.$store.getters.getAddressesObjectsList;
            //показываем список
            if (!this.showAddressesObjectsList && list[ID] && list[ID].features.length > 0 && !zoomToMainObject) {

                this.showAddressesObjectsList = true;

                var res = [];
                
                list[ID].features.forEach(function (aofItem, index, arr) {
                    var resArr = [aofItem];
                    arr.forEach(function (aItem) {
                        var isOk = false;
                        resArr.forEach(function (rItem) {
                            if (aItem.attributes['AR_ID'] == rItem.attributes['AR_ID'] && aItem.attributes['OBJECTID'] != rItem.attributes['OBJECTID'])
                                isOk = true;
                            else
                                isOk = false;
                        }.bind(this));
                        if (isOk)
                            resArr.push(aItem);
                    }.bind(this));
                            if ((res.join("_").toLowerCase()).indexOf(aofItem.attributes.FULLADDRUA.toLowerCase()) < 0){
                                res.push(aofItem.attributes.FULLADDRUA);
                                this.listOfObjects.push({ out: aofItem.attributes.FULLADDRUA, obj: aofItem, objArr: resArr});
                            }
                }.bind(this));
                if (res.length > 0) {
                    this.showedAddressObjects = false;
                    this.hideInfowindow();
                }
            }
            //возврат к школе
            else if (zoomToMainObject) {

                this.showAddressesObjectsList = false;

                this.listOfObjects = [];

                var currentClickEventData = this.$store.getters.getCurrentClickEventData,
                    delta = 100;

                if (Array.isArray(this.cFFeature) && this.cFFeature.length > 0)
                this.cFFeature.forEach(function (cffItem) {
                    var layerName;
                    if (cffItem.layerName)
                        layerName = cffItem.layerName;
                    else if (cffItem.attributes.institutionIdentifier_)
                        layerName = 'asys.SDE.munic_education';
                    else if (cffItem.attributes.AR_ID)
                        layerName = 'asys.SDE.bombshelters';
                    else if (cffItem.attributes.OBJECTID)
                        layerName = 'asys.SDE.munic_medicine';
                    this.addSelectGeometry([{ feature: cffItem, geometryType: cffItem.geometryType, layerName: layerName }], cffItem.infoTemplate);
                }.bind(this));
                //this.map.graphics.add(this.gFeature);
                var extent;
                if (this.cFFeature[0].geometry.type == 'point') {
                    var mapPoint = this.cFFeature[0].geometry.type == 'point' ? this.cFFeature[0].geometry :
                        currentClickEventData.mapPoint;

                        extent = new esri.geometry.Extent({
                            "xmin": mapPoint.x - delta,
                            "ymin": mapPoint.y - delta,
                            "xmax": mapPoint.x + delta,
                            "ymax": mapPoint.y + delta,
                            "spatialReference": { "wkid": 28467 }
                        });
                }
                else {
                    var fExtent = this.cFFeature[0].geometry.getExtent();
                    extent = new esri.geometry.Extent({
                        "xmin": fExtent.xmin - delta,
                        "ymin": fExtent.ymin - delta,
                        "xmax": fExtent.xmax + delta,
                        "ymax": fExtent.ymax + delta,
                        "spatialReference": { "wkid": 28467 }
                    });
                }
                this.map.setExtent(extent, true); 

                //setTimeout(function () {
                //    this.map.infoWindow.show(currentClickEventData.mapPoint, this.map.getInfoWindowAnchor(currentClickEventData.screenPoint));
                //    if (window.innerWidth < 768)
                //        setTimeout(function () {
                //            var sp = new this.widgets.screenUtils.toScreenPoint(this.map.extent, this.map.width, this.map.height, this.gFeature.geometry);
                //            this.repositionInfoWindow(sp , this.gFeature.geometry);
                //        }.bind(this), 200);

                //}.bind(this), 700);
                
            }
            //просто закрыли
            else {
                this.showAddressesObjectsList = false;
                this.listOfObjects = [];
                this.clearAddressObjectsList();
            }            
        },
        selectAddressesObject: function (ardObject) {
            if (!this.cFFeature)
                this.cFFeature = [this.map.graphics.graphics[0]];
            this.clearCraphicLayer();

            //if (ardObject.obj.geometry) {
            //    this.map.graphics.add(new this.widgets.Graphic(ardObject.obj.geometry, this.polygonHighlightSymbol, ardObject.obj.attributes));

            //    //var res = [];
            //    //this.$store.getters.getAddressObjectsList.forEach(function (aolItem, index) {
            //    //    if (Array.isArray(aolItem.features) && aolItem.features.length > 0) {
            //    //        aolItem.features.forEach(function (aofItem) {
            //    //            if (ardObject.out == aofItem.attributes.FULLADDRUA)
            //    //                this.map.graphics.add(new this.widgets.Graphic(aofItem.geometry, this.polygonHighlightSymbol, aofItem.attributes));
            //    //        }.bind(this));
            //      //  }
            //    //}.bind(this));
            //}


            if (ardObject.obj.geometry && ardObject.objArr && ardObject.objArr.length > 0) {
                ardObject.objArr.forEach(function (oItem) {
                    this.map.graphics.add(new this.widgets.Graphic(oItem.geometry, this.polygonHighlightSymbol, oItem.attributes));
                }.bind(this));
            }         

            this.zoomToSelectedFeatures();
            //var extent = this.widgets.graphicsUtils.graphicsExtent(this.map._layers.map_graphics.graphics),
            //    delta = 20;
            //extent.xmin = extent.xmin - delta;
            //extent.xmax = extent.xmax + delta;
            //extent.ymin = extent.ymin - delta;
            //extent.ymax = extent.ymax + delta;

            //this.map.setExtent(extent, true);
        },
        clearAddressObjectsList: function () {
            this.$store.commit('clearAddressObjectsList');
        },
        showServiceObject: function (data) {
            if (data.eventName)
                eventVue.$emit(data.eventName, data.GUID);
            else {
                if (data.fromServiceObject) {
                    this.identityFeatures.length = 0;
                    this.handleIdentityResult(data.infoData);
                    this.addSelectGeometry(data.highlightData);
                    //this.clearCraphicLayer();
                }
                else {
                    this.handleIdentityResult(data.infoData);
                    this.addSelectGeometry(data.highlightData);
                }
                //if (data.fromServiceObject)
                //    this.identityFeatures.length = 0;
                //var layer = this.$store.getters.geLayerById(data.infoData[0][0].layerId),
                //    list = this.$store.getters.getAddressesObjectsList,
                //    field = layer.identify[0].bindToAddressField;
                //if (layer.identify[0].bindToAddress && !list[data.infoData[0][0].feature.attributes[field]]) {
                //    var type = layer.identify[0].type,
                //        method, field;
                //    var prop = { identityData: data },
                //        method;
                //    if (data.infoData[0][0].feature.attributes[field] != 'Null') {
                //        if (type == "bombshelters") {
                //            method = this.$store.getters.getAjaxUrlByName('GetAddressesByBombShelter');
                //            Vue.set(prop, 'bombGuid', data.infoData[0][0].feature.attributes[field]);
                //        }
                //        else if (type == "scool") {
                //            method = this.$store.getters.getAjaxUrlByName('GetAddressesByPrimarySchool');
                //            Vue.set(prop, 'schoolGuid', data.infoData[0][0].feature.attributes[field]);
                //        }
                //        else if (type == "medicine") {
                //            method = this.$store.getters.getAjaxUrlByName('GetAddressesByHospital');
                //            Vue.set(prop, 'medGuid', data.infoData[0][0].feature.attributes[field]);
                //        }
                //        Vue.set(prop, 'ajax', method);
                //        this.$store.dispatch(method.name, JSON.stringify(prop));
                //    }
                //}
                //else {
                //    this.handleIdentityResult(data.infoData);
                //    this.addSelectGeometry(data.highlightData);
                //}
                
                
            }
        },
        //searchobjects--------------------------------------
        searchObjects: function (extent, where) {
            var promices, res = [];
            //добавляем екстент в каждый query QT
            for (var i = 0; i < this.QT.length; i++) {
                if (extent)
                    this.QT[i].query.geometry = extent;
                if (where)
                    //this.QT[i].query.where = this.QT[i].query.outFields[0] + " LIKE '%" + where +"%'";
                    this.QT[i].query.where = this.QT[i].query.outFields[0] + " = '" + where + "'";
                res.push(this.QT[i].task.execute(this.QT[i].query));
            }
            //this.QT[0].query.geometry = extent;
            //    if (where)
            //        //this.QT[i].query.where = this.QT[i].query.outFields[0] + " LIKE '%" + where +"%'";
            //        this.QT[0].query.where = this.QT[0].query.outFields[0] + " = '" + where + "'";
            //    res.push(this.QT[0].task.execute(this.QT[0].query));
            promices = this.widgets.all(res);
            promices.then(this.handleQueryResult);
        },
        handleQueryResult: function (e) {
            this.clearCraphicLayer();
            if (e.length > 0) {                
                var type = this.$store.getters.getСurrentSearchResult.type;
                let isOK = false;
                for (var i = 0; i < e.length; i++) {
                    for (var j = 0; j < e[i].features.length; j++) {
                        //-------------------------
                        if (e[i].features.length > 0 && e[i].features[j].geometry.type == 'polyline')
                            e[i].features[j].setSymbol(
                                new store.getters.getArcGisWidgets.SimpleLineSymbol(
                                store.getters.getArcGisWidgets.SimpleLineSymbol.STYLE_SOLID,
                                    new store.getters.getArcGisWidgets.Color([2, 250, 213]), 3));
                        //--------------------------------
                        if (e[i].features.length > 0 && e[i].features[j].geometry.type == 'polygon')
                            //e[i].features[j].setSymbol(new store.getters.getArcGisWidgets.SimpleFillSymbol(store.getters.getArcGisWidgets.SimpleFillSymbol.STYLE_SOLID,
                            //    new store.getters.getArcGisWidgets.SimpleLineSymbol(store.getters.getArcGisWidgets.SimpleLineSymbol.STYLE_SOLID,
                            //        new store.getters.getArcGisWidgets.Color([2, 250, 213]), 3), new store.getters.getArcGisWidgets.Color([255, 255, 0, 0])));
                        e[i].features[j].setSymbol(new this.widgets.SimpleFillSymbol(this.widgets.SimpleFillSymbol.STYLE_SOLID,
                            new this.widgets.SimpleLineSymbol(this.widgets.SimpleLineSymbol.STYLE_SOLID, new this.widgets.Color([6, 201, 169, 1]), 3),
                            new this.widgets.Color([6, 201, 169, 0.0])));

                       
                        //this.map.graphics.add(e[i].features[j]);
                        this.addGraphic(e[i].features[j]);
                        isOK = true;
                    }
                }
                //якщо геометрія додана то наблизуємось
                if (isOK) {
                    var extent = this.widgets.graphicsUtils.graphicsExtent(this.map._layers.map_graphics.graphics);

                    //для ліній віддаляємось
                    if (e[0].features.length > 0 && e[0].features[0].geometry.type == 'polyline') {
                        const delta = 50;
                        extent.xmin = extent.xmin - delta;
                        extent.xmax = extent.xmax + delta;
                        extent.ymin = extent.ymin - delta;
                        extent.ymax = extent.ymax + delta;
                    }
                    this.map.setExtent(extent, true);
                }
                //якщо геометрії немає, але є точка авреси в темпі
                else if (!isOK && this.temp_point_address_result) {
                    var delta = this.$store.getters.getExtentDelta,
                        extent = this.createExtent([
                            this.temp_point_address_result.local_X - delta,
                            this.temp_point_address_result.local_Y - delta,
                            this.temp_point_address_result.local_X + delta,
                            this.temp_point_address_result.local_Y + delta]);

                        this.zoomToExtent(extent);
                        this.addressOpacity = 1;
                        this.addressInterval = setInterval(function () {
                            this.addressOpacity -= 0.1;
                            var pt = new this.widgets.Point(this.temp_point_address_result.local_X, this.temp_point_address_result.local_Y);
                            var symbol = new this.widgets.SimpleMarkerSymbol(
                                this.widgets.SimpleMarkerSymbol.STYLE_CIRCLE,
                                70,
                                new this.widgets.SimpleLineSymbol(
                                    this.widgets.SimpleLineSymbol.STYLE_SOLID,
                                    new this.widgets.Color([232, 12, 12, this.addressOpacity]),
                                    3
                                ),
                                new this.widgets.Color([232, 12, 12, 0])
                            );
                            var graphic = new this.widgets.Graphic(pt, symbol);
                            this.clearCraphicLayer();
                            this.addGraphic(graphic);                                                       
                        }.bind(this), 300);
                        setTimeout(function () {
                            clearInterval(this.addressInterval);
                            this.clearCraphicLayer();
                        }.bind(this), 3000);
                }

            }
        },
        updateQT: function (type) {
            //обнуляем
            this.QT.length = 0;
            //если клик по мапе
            if (type == 'mapClick') {
                var layers = this.$store.getters.getVisibileLayers; 
                layers.forEach(function (item, index, layers) {
                    if (item.visibility && item.type == 'feature') {
                        var q = new this.widgets.Query(),
                            url;
                        q.outFields = ["*"];
                        q.returnGeometry = true;
                        this.QT.push({
                            task: new this.widgets.QueryTask(item.url + '/' + item.layerIds[0]),
                            query: q
                        });
                    }
                }.bind(this));
            }
            //если поиск адреса-улицы
            if (type == 'searcher') {
                var queryStreet = new this.widgets.Query(),
                    queryBuilds = new this.widgets.Query();
                queryStreet.returnGeometry = true;
                queryStreet.outFields = ["FULL_UA"];
                queryBuilds.returnGeometry = true;
                queryBuilds.outFields = ["AR_ID"];
                    //this.QT = [
                    //    {
                    //        task: new this.widgets.QueryTask("http://cdr.citynet.kharkov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/5"),
                    //        query: queryStreet
                    //    }, {
                    //        task: new this.widgets.QueryTask("http://cdr.citynet.kharkov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/6"),
                    //        query: queryBuilds
                    //}];

                if (this.$store.getters.getSearchType == 'street') {
                    this.QT = [
                        {
                            task: new this.widgets.QueryTask("https://smart.khmr.gov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/5"),
                            query: queryStreet
                        }];
                }
                else {
                    this.QT = [{
                        task: new this.widgets.QueryTask("https://smart.khmr.gov.ua/arcgis/rest/services/gis_ort_stat_general/MapServer/6"),
                        query: queryBuilds
                    }];
                }
            }
        },
        addGraphic: function (feature) {
            //this.clearCraphicLayer();
            this.map.graphics.add(feature);
        },
        //----------------------------------------------------
        startGeolocation: function () {
            if (navigator.geolocation) {
                this.clearSelectioHidePopup();
                if (!this.geoLayer) {
                    this.geoLayer = new this.widgets.GraphicsLayer();                    
                    this.geoLayer.attr('name', 'geoLayer');
                    this.geoLayer.attr('dataType', 'layer');
                    this.map.addLayer(this.geoLayer);
                }
                //navigator.geolocation.getCurrentPosition(this.zoomToLocation, this.locationError);
                this.watchId = navigator.geolocation.watchPosition(this.convertCoordinates, this.locationError);
            } else {                
                eventVue.$on('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.geolocationIsNotSupportingByBrowser)
                this.graphic = null;
                this.removeGeolocationGraphic();
            }
        },
        stopGeolocation: function () {
            navigator.geolocation.clearWatch(this.watchId);
            this.graphic = null;
            this.removeGeolocationGraphic();
            //this.$store.commit('set_geolocationButtonClick');
        },
        convertCoordinates: function (location) {
            if (navigator.geolocation && this.watchId) {
                var longitudes = location.coords.longitude,
                    latitudes = location.coords.latitude,
                    accuracy = location.coords.accuracy;

                this.$store.dispatch('convertCoordinates', JSON.stringify({
                    ajax: this.$store.getters.getAjaxUrlByName('convertCoordinates'),
                    longitudes: longitudes,
                    latitudes: latitudes,
                    accuracy: accuracy
                }));
            }
            else
                this.$store.commit('set_geolocationButtonClick');

        },
        showLocation: function (location) {
            //zoom to the users location and add a graphic
            if (this.watchId) {
                if (this.graphic)
                    this.removeGeolocationGraphic();
                this.addGraphic2(location, location.prop.accuracy);
            }            
        },
        locationError: function (error) {
            //error occurred so stop watchPosition
            if (navigator.geolocation)
                this.stopGeolocation();
                //navigator.geolocation.clearWatch(this.watchId);            
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.geolocationPermissionDenided);
                    break;
                case error.POSITION_UNAVAILABLE:
                    eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.geolocationPositionUnavailable);
                    break;
                case error.TIMEOUT:
                    eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.geolocationTimeout);
                    break;
                default:
                    eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.geolocationUnknowError);
                    break;
            }
            this.$store.commit('set_geolocationButtonClick');
        },
        addGraphic2: function (location, accuracy) {
            this.graphic = new this.widgets.Graphic({
                geometry: new this.widgets.Circle({//circle constructor
                    center: [location.newCoords.x, location.newCoords.y],//pass the pointer-down event X Y as a starting point
                    radius: location.prop.accuracy * 100000, /* !!!! умножаем на 100000, почему-то километровая сетка !!!!!!*/
                    
                })
            });
            var symbol = new this.widgets.SimpleFillSymbol(this.widgets.SimpleFillSymbol.STYLE_SOLID,
                new this.widgets.SimpleLineSymbol(this.widgets.SimpleLineSymbol.STYLE_DASHDOT,
                    new this.widgets.Color([255, 0, 0]), 2), new this.widgets.Color([255, 255, 0, 0.25])
            );
            this.graphic.setSymbol(symbol);
            this.geoLayer.add(this.graphic);  
            var delta;
            if (accuracy > 1000)
                delta = 1000;
            else if (accuracy > 100 && accuracy < 1000)
                delta = 500;
            else if (accuracy > 10 && accuracy < 100)
                delta = 100;
            else 
                delta = 20;
            var extent = new esri.geometry.Extent({
                "xmin": this.graphic._extent.xmin - delta,
                "ymin": this.graphic._extent.ymin - delta,
                "xmax": this.graphic._extent.xmax + delta,
                "ymax": this.graphic._extent.ymax + delta,
                "spatialReference": { "wkid": 28467 }
            });
            this.map.setExtent(extent, true); 
        },        
        zoomToLocation: function (location) {
            if (location.coords.longitude > 60 || location.coords.latitude > 60)
                this.addGraphic2(location, location.coords.accuracy);
        },
        removeGeolocationGraphic: function () {
            this.geoLayer.clear()
            //this.geoLayer.graphics.removeAll();
        },
        //--------------------------------------------------
        initLegend: function () {
                var layerInfo = [];
                var layersCount = (this.countLayerss + 1) * 10;


                for (var i = 0; i < this.map.layerIds.length; i++) {
                    if (this.map._layers[this.map.layerIds[i]] && this.map._layers[this.map.layerIds[i]]._attrs.dataType && this.map._layers[this.map.layerIds[i]]._attrs.dataType != "basic" || (this.map._layers[this.map.layerIds[i]]._attrs.dataType == "basic" && this.map._layers[this.map.layerIds[i]]._attrs.id == 0))
                        //this.map.removeLayer(this.map._layers[this.map.layerIds[i]]);
                        layerInfo.push({
                            layer: this.map._layers[this.map.layerIds[i]],
                            title: this.map._layers[this.map.layerIds[i]]._attrs.legendName ? this.map._layers[this.map.layerIds[i]]._attrs.legendName : this.map._layers[this.map.layerIds[i]]._attrs.name,
                            slider: true
                        });
                }

                for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                    if (this.map._layers[this.map.graphicsLayerIds[j]] && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType != "basic" || (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType == "basic" && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id == 0))
                        //this.map.removeLayer(this.map._layers[this.map.graphicsLayerIds[j]]);
                       
                            if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs["isCluster"] && !this.map._layers[this.map.graphicsLayerIds[j]]._attrs["isLoadData"]) {
                                var layer2;
                                layer2 = new this.widgets.FeatureLayer(this.map._layers[this.map.graphicsLayerIds[j]].url, { opacity: 1 });
                                layer2.attr('id', this.map._layers[this.map.graphicsLayerIds[j]]._attrs['id']);
                                layer2.attr('name', this.map._layers[this.map.graphicsLayerIds[j]]._attrs['name']);
                                layer2.setVisibility(true);
                                layerInfo.push({
                                    layer: layer2,
                                    title: this.map._layers[this.map.graphicsLayerIds[j]]._attrs['legendName'] ? this.map._layers[this.map.graphicsLayerIds[j]]._attrs['legendName'] : this.map._layers[this.map.graphicsLayerIds[j]]._attrs['name'],
                                    slider: true
                                });
                            }
                            else if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs["isCluster"] && this.map._layers[this.map.graphicsLayerIds[j]]._attrs["isLoadData"]) {
                                var layer2;
                                var renderer;

                                var defaultPointSymbol = new this.widgets.PictureMarkerSymbol({
                                    "angle": 0, "xoffset": 0, "yoffset": 0, "type": "esriPMS",
                                    "url": "/opendataportal/Images/default_" + this.map._layers[this.map.graphicsLayerIds[j]]._attrs["id"] + ".svg",
                                    "contentType": "image/svg", "width": 16, "height": 16
                                });

                                renderer = new this.widgets.SimpleRenderer({
                                    type: "simple",
                                    symbol: defaultPointSymbol
                                });
                                var featureCollection = {
                                    "layerDefinition": null,
                                    "featureSet": {
                                        "features": [],//properties.features,
                                        "geometryType": "esriGeometryPoint"
                                    }
                                };
                                featureCollection.layerDefinition = {
                                    "geometryType": "esriGeometryPoint",
                                    "objectIdField": "Id",
                                    "fields": []
                                };

                                layer2 = new this.widgets.FeatureLayer(featureCollection, {
                                    outFields: ["*"],
                                });
                                layer2.attr('id', this.map._layers[this.map.graphicsLayerIds[j]]._attrs['id']);
                                layer2.attr('name', this.map._layers[this.map.graphicsLayerIds[j]]._attrs['name']);

                                layer2.setRenderer(renderer);
                                layer2.setVisibility(true);
                                layerInfo.push({
                                    layer: layer2,
                                    title: this.map._layers[this.map.graphicsLayerIds[j]]._attrs['legendName'] ? this.map._layers[this.map.graphicsLayerIds[j]]._attrs['legendName'] : this.map._layers[this.map.graphicsLayerIds[j]]._attrs['name'],
                                    slider: true
                                });
                            }
                            else
                                layerInfo.push({
                                    layer: this.map._layers[this.map.graphicsLayerIds[j]],
                                    title: this.map._layers[this.map.graphicsLayerIds[j]]._attrs.legendName ? this.map._layers[this.map.graphicsLayerIds[j]]._attrs.legendName : this.map._layers[this.map.graphicsLayerIds[j]]._attrs.name
                                });
                       
                }

                if (this.legendDijit && layerInfo.length > 0) {
                    this.legendDijit.layerInfos = layerInfo;
                   // this.legendDijit.refresh();
                    setTimeout(function () {
                        this.legendDijit.refresh();
                    }.bind(this),1500);
                    
                }
                else {
                    if (layerInfo.length > 0) {
                        this.legendDijit = new this.widgets.Legend({
                            map: this.map,
                            layerInfos: layerInfo
                        }, "legendContent");
                        this.legendDijit.startup();
                    }
                }            
        },
        //------------------------------------------
        reInitEsriPrint: function() {
            setTimeout(function () {
                document.getElementsByClassName('esriPrintout')[0].remove();
                this.printer.startup();
            }.bind(this), 4000);
        },
        changeBasic: function (basicId) {
            var isOK = false, i = 0, layerCounters = 0;
            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType == 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.id != 0)
                    //
                    this.map._layers[this.map.layerIds[i]].setVisibility(false);

                if (this.map._layers[this.map.layerIds[i]]._attrs.dataType == 'basic' && this.map._layers[this.map.layerIds[i]]._attrs.id == basicId)
                    this.map._layers[this.map.layerIds[i]].setVisibility(true);
            }
            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType == 'basic' && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id != 0)
                    this.map._layers[this.map.graphicsLayerIds[j]].setVisibility(false);

                if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.dataType == 'basic' && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id == basicId)
                    this.map._layers[this.map.graphicsLayerIds[j]].setVisibility(true);
            }
            this.updateIT();
            this.initLegend();
        },

        //---------------
        getServices: function (data) {
            this.$store.dispatch('getServicesObjects', data);
        },
        setServicesObjects: function (data) {
            this.$refs.ic2.setServicesList(data);
        },
        showAddressesNotFound: function (show) {
            this.showingAddressesNotFound = show;
        },
        //----------------
        updateLayersDataWidthExpression: function () {
            this.getVisibileLayers.forEach(function (vlItem, index, arr) {
                if (vlItem.type === "feature" && vlItem.expression) {

                    var expression = this.getExpression(vlItem); 
                    
                    for (var i = 0; i < this.map.layerIds.length; i++) {
                        if (this.map._layers[this.map.layerIds[i]]._attrs.name === vlItem.name) {
                            this.map._layers[this.map.layerIds[i]].setDefinitionExpression(expression);
                            this.map._layers[this.map.layerIds[i]].refresh();
                        }
                    }
                    for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                        if (this.map._layers[this.map.graphicsLayerIds[j]]._attrs.name === vlItem.name) {
                            this.map._layers[this.map.graphicsLayerIds[j]].setDefinitionExpression(expression);
                            this.map._layers[this.map.graphicsLayerIds[j]].refresh();
                        }
                    }

               }
            }.bind(this));
        },

        setWhereToLayer: function (data) {       
            let isOk = false;

            for (var i = 0; i < this.map.layerIds.length; i++) {
                if (!isOk && this.map._layers[this.map.layerIds[i]]._attrs.id === data.layer.id) {
                    var layerDefinitions = [];
                    layerDefinitions[data.layer.layerIds[0]] = data.where;
                    this.map._layers[this.map.layerIds[i]].setLayerDefinitions(layerDefinitions);
                    this.map._layers[this.map.layerIds[i]].refresh();
                    isOk = true;
                }
            }

            for (var j = 0; j < this.map.graphicsLayerIds.length; j++) {
                if (!isOk && this.map._layers[this.map.graphicsLayerIds[j]]._attrs.id === data.layer.id) {
                    var layerDefinitions = [];
                    layerDefinitions[data.layer.layerIds[0]] = data.where;
                    this.map._layers[this.map.graphicsLayerIds[j]].setLayerDefinitions(layerDefinitions);
                    this.map._layers[this.map.graphicsLayerIds[j]].refresh();
                    isOk = true;
                }
            }               
        },

        handlingCoordinatesResult: function(oldValue, newValue) {
            if (newValue?.data?.x && newValue?.data?.y) {
               // var template = new this.widgets.InfoTemplate();
                let res = "'longitude: "+this.getCoordinatesResult.data.x+", latitude: "+this.getCoordinatesResult.data.y+"'";
                this.map.infoWindow.setTitle(`<b>Координати</b>`);
               // this.map.infoWindow.setContent(`<ul><li><b>lon: </b>${newValue.data.x}</li><li><b>lat: </b>${newValue.data.y}</li><ul>`);

                this.map.infoWindow.setContent(`<table class="digitalInfoTable">
                                                <tr><td><b>lon: </b></td><td>${newValue.data.x}</td></tr>
                                                <tr><td><b>lat: </b></td><td>${newValue.data.y}</td></tr></table>
                                                <a title="копіювати" class="coordinatesCopy" onclick="copyToClipboard(${res})"><i class="material-icons">content_copy</i></a>`);
                // this.map.infoWindow.setInfoTemplate(template);
                this.map.infoWindow.show(newValue.clickData.mapPoint);

            }
            else {
                this.map.infoWindow.hide();
                this.map.infoWindow.setTitle("");
                this.map.infoWindow.setContent(``);
            }
        }
    }    
};
//------------------------------------

//------------------------------------
//тулбар
const maptoolbarComponent = {
    template: `<div v-bind:class="{ hideBlock: !getHideBlock }" class="map-toolbar">
                    <div class="tollbar-first-item">
                        <span class="glyphicon glyphicon-menu-left" aria-hidden="true"
                                v-bind:class="{ selected: getHideBlock }" 
                                v-on:click="arrowClick">
                        </span>
                    </div>
                    <div class="toolbar-items">
                        <a id="toogleSearcher"
                                v-bind:class="{ selected: getToggleSearcherSelected }"
                                v-on:click="buttonClick(\'toggleSearcher\')">
                            <span class="glyphicon glyphicon-search" aria-hidden="true" title="Пошук"></span>
                        </a>
                        <a id="geolocation"
                                v-bind:class="{ selected: getGeolocationSelected }"
                                v-on:click="buttonClick(\'geolocation\')">
                            <span class="glyphicon" title="Визначити місцезнаходження">
                                <i class="material-icons">near_me</i>
                            </span>
                        </a>

                        <!-- <a id="pan" v-bind:class="{ selected: getPanSelected }" v-on:click="buttonClick(\'pan\')"><span aria-hidden="true" title="Перемістити карту" class="glyphicon"><i class="fa  fa-hand-paper-o "></i></span></a> -->

                        <a id="identify"
                                    v-bind:class="{ selected: getIdentifySelected }"
                                    v-on:click="buttonClick(\'identify\')">
                            <span class="glyphicon glyphicon-info-sign" aria-hidden="true" title="Інформація"></span>
                        </a>

                        <a id="zoomin"
                                        v-bind:class="{ selected: getZoominSelected }"
                                        v-on:click="buttonClick(\'zoomin\')">
                            <span class="glyphicon glyphicon-zoom-in" aria-hidden="true" title="Наблизити"></span>
                        </a>
                        <a id="zoomout"
                                    v-bind:class="{ selected: getZoomoutSelected }"
                                    v-on:click="buttonClick(\'zoomout\')">
                            <span class="glyphicon glyphicon-zoom-out" aria-hidden="true" title ="Віддалити" ></span>
                        </a>
                        <a id="zoomtofullextent"
                                    v-on:click="buttonClick(\'zoomtofullextent\')">
                            <span class="glyphicon glyphicon-fullscreen" aria-hidden="true" title="Початковий масштаб"></span>
                        </a>
                        <a id="refresh"
                                    v-on:click="buttonClick(\'refresh\')">
                            <span class="glyphicon glyphicon-refresh" aria-hidden="true" title="Оновити"></span>
                        </a>

                        <a id="feedback"
                                    v-on:click="buttonClick(\'feedback\')"
                                    data-toggle="modal"
                                    data-target="#feedbackWindow">
                            <span class="glyphicon" title="Зворотній зв\'язок">
                                <i class="material-icons">message</i></span>
                        </a>
                        <a id="mesurment"
                                    v-bind:class="{ selected: getMesurmentSelected }"
                                    v-on:click="buttonClick(\'mesurment\')">
                            <span class="glyphicon ruler" aria-hidden="true" title="Вімірювання">
                                <img class="ruler-grey" src="/opendataportal/Content/img/ruler.svg" />
                                <img class="ruler-white" src="/opendataportal/Images/ruler_white.svg" />
                            </span>
                        </a>
                       <!-- <a id="coordinates"
                                v-bind:class="{ selected: getCoordinatesSelected }"
                                v-on:click="buttonClick(\'coordinates\')">
                            <span class="glyphicon" title="Визначити координати">
                                <i class="material-icons">place</i>
                            </span>
                        </a>-->
                        <a id="statistic"
                            v-if="(getUser.roles.Admins)"
                            v-on:click="buttonClick(\'statistic\')">
                            <span class="glyphicon glyphicon-stats" aria-hidden="true"></span>
                        </a>
                        <a id="filterOpen"
                            v-if="(getUser.roles.DSNSLayers)"
                            v-on:click="buttonClick(\'dsnstables\')">                            
                            <span class="glyphicon glyphicon-filter" aria-hidden="true"></span>
                        </a>
                       <a id="filterCancel" 
                            v-if="(getUser.roles.DSNSLayers && getDSNSLayersWidthFilters.length > 0)"
                            v-on:click="buttonClick(\'dsnstablescancelfilters\')"
                        >
                            <span class="glyphicon glyphicon-filter" aria-hidden="true"></span>
                            <span class="glyphicon glyphicon-remove small-internIcon" aria-hidden="true"></span>
                        </a>

                    </div>
                    <div class="privacyLinkBlock">
                        <a href="http://www.infocity.kharkov.ua/" target="_blank" class="info-CP" title="КП  &quot;Міський інформаційний центр&quot;">
                            <img src="/opendataportal/Content/img/logo-infocity.png" alt="логотип КП Міський інформаційний центр"/>
                            КП «МІЦ»
                        </a>
                        <span class="linkDevider"> . </span>
                        <a href="../opendataportal/Home/Privacy" 
                                class="privacyLinkFixed" 
                                target="_blank" 
                                title="Політика конфіденційності">
                            Конфіденційність
                        </a>

                    </div>
            </div>`,
    computed: {
        getToggleSearcherSelected() {
            return this.$store.getters.getToggleSearcherSelected;
        },
        getPanSelected() {
            return this.$store.getters.getPanSelected;
        },
        getZoominSelected() {
            return this.$store.getters.getZoominSelected;
        },
        getZoomoutSelected() {
            return this.$store.getters.getZoomoutSelected;
        },
        getIdentifySelected() {
            return this.$store.getters.getIdentifySelected;
        },
        getMesurmentSelected() {
            return this.$store.getters.getMesurmentSelected;
        },
        getGeolocationSelected() {
            return this.$store.getters.getGeolocationSelected;
        },
        getCoordinatesSelected() {
            return this.$store.getters.getCoordinatesSelected;
        },
        getHideBlock() {
            return this.$store.getters.getHideBlock
        },
        getUser() {
            return this.$store.getters.getUser;
        },
        getDSNSLayersWidthFilters() {
            return this.$store.getters.getDSNSLayersWidthFilters;
        }
    },
    methods: {
        initMapTollBar: function () {
            this.$store.commit('set_isMapToolsInit', true);
        },
        buttonClick: function (type) {
            switch (type) {
                case 'toggleSearcher':
                    this.$store.commit('set_searchVisibility');
                    break;
                case 'geolocation':
                    this.$store.commit('set_geolocationButtonClick');
                    break;
                //case 'pan':
                case 'coordinates':
                case 'zoomin':
                case 'zoomout':
                case 'identify':
                case 'mesurment': {
                    this.$store.commit('set_maptoolbarButtonClick', type);
                    eventVue.$emit('maptoolbar_buttonClick', type);
                }
                    break;
                case 'zoomtofullextent':
                    eventVue.$emit('maptoolbar_buttonClick', type);
                    break;
                case 'refresh':
                    window.location = '/opendataportal';
                    break;
                case 'feedback':
                    eventVue.$emit('maptoolbar_feedbackBtnClick', type);
                    break;
                case 'statistic':
                    eventVue.$emit('maptoolbar_statisticBtnClick', type);
                    break;
                case 'dsnstables':
                    eventVue.$emit('maptoolbar_dsnstablesBtnClick', type);
                    break;
                case 'dsnstablescancelfilters':
                    eventVue.$emit('maptoolbar_dsnstablescancelfiltersBtnClick', type);
                    break;
            }
        },
        arrowClick: function () {
            this.$store.commit('set_toggleMaptoolVisibility');
        }
    }
};
//-------------------------------------------
//посиковик инпут
const searchInputComponent = {//v-on:keyup="autoComplete"
    template: `<div class="search-wrapper">
                   <input type="text" class="form-control zbz-input-clearable" name="roganMan" autocomplete="new-password" style="height: 0;padding: 0;border: 0;box- shadow: none;background: transparent;">
                    <input type="password"  class="form-control zbz-input-clearable" name="roganMan" autocomplete="new-password" style="height: 0;padding: 0;border: 0;box- shadow: none;background: transparent;">

                    <input type="text" id="searcherInput" name="field1"
                        class="form-control zbz-input-clearable"
                        v-bind:class="{ searcherDrop : data_results.length > 0 }" :placeholder="getSearchPlaceholder"
                        v-model="searchtext"
                        autocomplete="new-password"
                        @input="autoComplete"
                        @paste="autoComplete"
                        @cut="autoComplete" >
                    <div class="panel-footer" v-if="data_results.length" style="position:absolute; top:40px; padding:0; width: calc(85vw - 6px);">
                        <ul v-if="data_type.id === 0" class="list-group" style="margin-bottom:0;">
                            <li class="list-group-item" v-for="result in data_results" v-on:click="selectLi(result)">{{ result.FullNameUA }}</li>
                        </ul>
                        <ul v-else-if="data_type.id === 1"class="list-group" style="margin-bottom:0;">
                            <li class="list-group-item" v-for="result in data_results" v-on:click="selectLi(result)">{{result.name_ukr}} {{result.type_ukr}}</li>
                        </ul>
                        <ul v-else class="list-group" style="margin-bottom:0;">
                            <li class="list-group-item" v-for="result in data_results" v-on:click="selectLi(result)">{{ result.cadnum }}</li>
                        </ul>
                    </div>
                </div>`,
    //v-bind:class = "{ zbz-input-clearable__x : searchtext.length > 0 }"
    data: function () {
        return {
            searchtext: '',
            data_results: [],
            current_result: null, 
            data_type: {},
            minSearchStringLength: this.$store.getters.getMinSearchStringLength
        }
    },
    computed: {
        getSearchPlaceholder() {
            this.clearSearcher();
            return store.getters.getSearchPlaceholder;
        }
    },
    methods: {
        autoComplete: function () {
            //alert('autoComplete, searchtext.length = ' + this.searchtext.length + ', minSearchStringLength = ' + this.minSearchStringLength);
            if (this.searchtext.length > this.minSearchStringLength) {
                this.data_results = [];
                eventVue.$emit('searcherInputIsCleared');
                this.data_type.name = this.$store.getters.getSearchType,
                    nameMethod = '';
                if (this.data_type.name == 'address' || this.data_type.name == 'street') {
                    //если есть число хотя бы в одном слове, то это адрес, если нет улица
                    this.data_type.id = this.checkTextForNumber(this.searchtext) ? 0 : 1;
                    var type = this.checkTextForNumber(this.searchtext) ? 'address' : 'street';
                    this.data_type.name = type
                    this.$store.commit('set_searchType', type);
                    nameMethod = 'getAddressByText';
                    eventVue.$off('dataIsResponsed');
                    eventVue.$on('dataIsResponsed', (data) => {
                        setTimeout(function () {
                            if (data.length > 0) {
                                this.data_results = data;
                                eventVue.$emit('dataIsIserted', data);
                            }    
                        }.bind(this), 100);
                    });
                    //отсылаем
                    //alert('autoComplete before dispatch, nameMethod = ' + nameMethod);
                    this.$store.dispatch('getAddressByText', JSON.stringify({ ajax: this.$store.getters.getAjaxUrlByName('getAddressByText'), text: this.searchtext+' ' }));
                }
                //if (this.data_type.name == 'cad') {
                //    this.data_type.id = 2;
                //    nameMethod = 'getCadByText';
                //}
                //подписуемся на ответ
            }
            else {
                this.data_results = [];
                this.$store.commit('set_currentSearchResult', null);
                eventVue.$emit('searcherInputIsCleared');
                eventVue.$emit('data_resultsCleared');
            }
        },
        selectLi: function (data) {
            this.current_result = data;
            if (this.data_type.name == 'address' || this.data_type.name == 'street') {
                this.searchtext = (this.data_type.id == 0) ? data.FullNameUA : (data.name_ukr + ' ' + data.type_ukr);
            }
            if (this.data_type.name == 'cad') {
                this.searchtext = data.cadnum;
            }
           
            this.$store.commit('set_currentSearchResult', this.current_result);
            this.data_results = [];
            eventVue.$emit('data_resultsCleared');
        },
        clearSearcher: function () {
            this.searchtext= '';
            this.data_results = [];
            eventVue.$emit('data_resultsCleared');
            this.current_result = null;
            if (document.getElementById('searcherInput')) {
                this.$el.querySelector('#searcherInput').classList.remove('zbz-input-clearable__x');
                this.$store.commit('clearSearchResult');                
            }
        },
        checkTextForNumber: function (text) {
            var textOK = text.trim(),
                res = false;
            if (textOK.length > 0) {
                var arr = text.split(' '),
                    res = false;
                for (var i = 0; i < arr.length; i++)
                    if (arr[i].match(/\d+/g))
                        res = true;
            }
            return res;
        },
        blurComponent: function (el) {
            eventVue.$emit('scaleToOne');
        }
    },
    updated: function(e){
        if(this.searchtext.length > 0)
            this.$el.querySelector('input[type="text"]').classList.add('zbz-input-clearable__x');
    }
}

//поисковик
const _searchComponent = {
    template: '<div v-if="getSearcherVisibility" class="main-search-panel">\
                    <div class= "container">\
                        <div class="row">\
                            <div class="input-group">\
                                <div class="input-group-btn search-panel">\
                                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">\
                                        <span id="search_concept">Пошук</span><span class="caret"></span>\
                                    </button>\
                                    <ul class="dropdown-menu" role="menu">\
                                        <li><a @click="changeSearch(\'address\');">Адреса</a></li>\
                                        <li><a @click="changeSearch(\'cad\');">Кадастровий номер</a></li>\
                                    </ul>\
                                </div>\
                                <input type="hidden" name="search_param" value="all" id="search_param" autocomplete="new-password">\
                                <searchinput-comp ref="searchinput"></searchinput-comp>\
                                <span class="input-group-btn">\
                                    <button class="btn btn-default" v-bind:class="{searchButtonDrop : isSearchButtonDrop}" @click="searchStart();" type="button"><span class="glyphicon glyphicon-search"></span></button>\
                                </span>\
                            </div>\
                        </div>\
                    </div>\
                </div>',
    data: function () {
        return {
            isSearchButtonDrop: false
        }
    },
    computed: {
        getSearcherVisibility() {
            return store.getters.getSearcherVisibility;
        }
    },
    components: {
        'searchinput-comp': searchInputComponent
    },
    methods: {
        initSearcher: function () {
            eventVue.$on('dataIsIserted', (data) => {
                setTimeout(function () {
                    this.isSearchButtonDrop = (data.length > 0) ? true : false;
                }.bind(this), 100);
            });
            eventVue.$on('data_resultsCleared', () => {
                this.isSearchButtonDrop = false;
            });

            this.$store.commit('set_isSearcherInit', true);
        },

        changeSearch: function (type) {
            this.$store.commit('set_searchType', type);
        },
        searchStart: function () {
            eventVue.$emit('zoomToSearchObject', this.$store.getters.getСurrentSearchResult);
        },
        clearSearchInput: function () {
            this.$refs.searchinput.clearSearcher();
        }
    }
}
const searchComponent = {
    template: `<div v-if="getSearcherVisibility" class="main-search-panel">
                    <div class= "container">
                        <div class="row">
                            <div class="input-group searcherWithSelect-lg">
                                 <div class="input-group searcherWithSelect-inputLg" >
                                    <input type="text" 
                                        v-model="searchtext"
                                        class="zbz-input-clearable"  
                                        v-bind:class="{'zbz-input-clearable__x' : searchtext.length > 0}"
                                        placeholder="назва вулиці"
                                        :title="searchtext"
                                        autocomplete="new-password"
                                        @input="autoComplete"
                                        @paste="autoComplete"
                                        @cut="autoComplete"
                                    />
                                  <ul v-show="getFindedStreets.length > 0"
                                        class="searcherWithSelect-dropdown-menu">
                                        <li v-for="street in getFindedStreets" @click="selectStreet(street)">                                                                                      
                                            {{getStreetLabel(street)}}
                                        </li> 

                                  </ul>
                               
                                <input type="hidden" name="search_param" value="all" id="search_param" autocomplete="new-password">\
                                </div>
                                <div class="input-group searcherWithSelect-selectLg">
                                    <select v-model="selectedAddress"
                                            @change="selectAddress"
                                            :title="selectedAdressLabel"
                                            :disabled="!selectedStreet">
                                        <option value="null" disable>№</option>
                                        <option
                                            v-for="addr,index in getFindedAddresses"
                                            :value="JSON.stringify(addr)"
                                           
                                            :key="index">
                                            {{getAddressLabel(addr)}}
                                        </option>
                                    </select>
                                </div>

                                <span class="input-group-btn">
                                    <button class="btn btn-default searcherWithSelect-actionBtn"
                                        v-bind:class="{searchButtonDrop : isSearchButtonDrop}"
                                        @click="searchStart();" type="button" :disabled="!selectedStreet">
                                        <span class="glyphicon glyphicon-search"></span>
                                    </button>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>`,
    data: function () {
        return {
            isSearchButtonDrop: false,
            searchtext: "",
            selectedStreet: null,
            
            selectedAddress: null,
            selectedAdressLabel: "",
            findedAddresses:[],
        }
    },
    computed: {
        getSearcherVisibility() {
            return store.getters.getSearcherVisibility;
        },
        getMinSearchStringLength() {
            return store.getters.getMinSearchStringLength;
        },
        getFindedStreets() {
            //console.log(store.getters.getFindedStreets);
            return store.getters.getFindedStreets;
        },
        getFindedAddresses() {
            //console.log(store.getters.getFindedAddresses);
            return store.getters.getFindedAddresses;
        },
    },
    watch: {
        selectedStreet: function (newData , oldData) {
            if (newData) {
                this.getAddressesByStreet();
            }
        },
        //getFindedAddresses: function (newData, oldData) {
        //    this.findedAddresses = [...newData];
        //}
    },
    components: {
        'searchinput-comp': searchInputComponent
    },
    methods: {
        initSearcher: function () {
            eventVue.$on('dataIsIserted', (data) => {
                setTimeout(function () {
                    this.isSearchButtonDrop = (data.length > 0) ? true : false;
                }.bind(this), 100);
            });
            eventVue.$on('data_resultsCleared', () => {
                this.isSearchButtonDrop = false;
            });

            this.$store.commit('set_isSearcherInit', true);
        },
        changeSearch: function (type) {
            this.$store.commit('set_searchType', type);
        },
        searchStart: function () {
           // eventVue.$emit('zoomToSearchObject', this.$store.getters.getСurrentSearchResult);
            //let out_result = {
            //    currentResult:null,
            //    type:""
            //};
            //if (this.selectedStreet && !this.selectedAddress) {
            //    out_result.type = 'street';
            //    out_result.currentResult = this.selectedStreet.Street;
            //}
            //else if (this.selectedStreet && this.selectedAddress) {
            //    out_result.type = 'address';
            //    out_result.currentResult = this.selectedAddress;
            //}
            
            eventVue.$emit('zoomToSearchObject', this.$store.getters.getСurrentSearchResult);
        },
        clearSearchInput: function () {
            this.searchtext = "";
            this.selectedStreet =  null;
            this.selectedAddress =  null;
            this.findedAddresses =  [];
            this.$store.commit("set_findedStreets", []);
            this.$store.commit("set_findedAddresses", []);
            this.$store.commit("set_currentSearchResult", {
                currentResult: null,
                type: ""
            });
        },
        autoComplete: function () {
            if (this.searchtext.length > this.getMinSearchStringLength) {
                this.$store.commit("set_findedStreets", []);
                this.$store.commit("set_findedAddresses", []);
                this.$store.dispatch('findStreet', { ajax: this.$store.getters.getAjaxUrlByName('findStreet'), text: this.searchtext + ' ' });
            }
            else {
                this.$store.commit("set_findedStreets", []);
                this.$store.commit("set_findedAddresses", []);
            }
        },
        getStreetLabel: function (street) {
            let res = "";
            if (street) {
                res += street.Street.streetName + ' ' + street.Street.typeName;
                if (street.Befores.length > 0) {
                    res += " (стар. ";
                    street.Befores.forEach(function (bstreet, index) {
                        res += (index > 0 ? ", " : "") + bstreet.streetName + ' ' + bstreet.typeName;
                    }.bind(this));
                    res += ")";
                }
            }
            return res;
        },
        selectStreet: function (data) {
            this.selectedStreet = data;
            this.searchtext = this.getStreetLabel(data);
            this.$store.commit("set_currentSearchResult", {
                currentResult: data.Street,
                type: "street"
            });
            this.$store.commit("set_findedStreets", []);
            this.$store.commit("set_findedAddresses", []);
            eventVue.$emit('data_resultsCleared');
        },
        getAddressesByStreet: function () {
            if (this.selectedStreet) {
                this.$store.commit("set_findedAddresses", []);
                this.$store.dispatch('findAddress', { ajax: this.$store.getters.getAjaxUrlByName('findAddress'), streetId: this.selectedStreet.Street.id });
            }
            else {
                this.$store.commit("set_findedAddresses", []);
            }
        },
        getAddressLabel: function (address) {
            let res = "";
            if (address) {
                res += address.addressNumber;
                if (address.addressBlock) {
                    res += "корпус № " + address.addressBlock;
                }
            }
            return res;
        },
        selectAddress: function (data) {
           // console.log(data.currentTarget.value)
            if (data && data.currentTarget.value !== "null") {
                let out_data = data ? JSON.parse(data.currentTarget.value): null;
                this.selectedAddress = data.currentTarget.value;
                this.selectedAdressLabel = this.getAddressLabel(out_data);
                this.$store.commit("set_currentSearchResult", {
                    currentResult: out_data,
                    type: "address"
                });
                //this.$store.commit("set_findedAddresses", []);
                eventVue.$emit('data_resultsCleared');
            }
            else {
                this.$store.commit("set_currentSearchResult", {
                    currentResult: this.selectedStreet.Street,
                    type: "street"
                });
                eventVue.$emit('data_resultsCleared');
            }

        },
    }
}


//----------------------------------------
//спиннер
const spinnerComponent = {
    template: `<div v-if="getFullInit" class="spinerDiv">
                    <img src="/opendataportal/Content/img/VZvw.gif">
                </div>`,
    computed: {
        getFullInit() {
            return !store.getters.getFullInit;
        }
    },
    methods: {
        initSpinner: function () {
            this.$store.commit('set_isSpinnerInit', true);
        }
    }

};

//-----------------------------------------
//ток
const tocComponent = {//@start="drag=true" @end="drag=false"
    template: `<div v-if="getTocVisibility" class="TOC">
                <div class="visible-panel">
                    <div class="panel-name"  v-on:click="toggleTocClick">
                    <span class="glyphicon">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; line-height: 18px; " >
                            <path fill="#fff" d="M12 0L3 7L4.63 8.27L12 14L19.36 8.27L21 7L12 0M19.37 10.73L12 16.47L4.62 10.74L3 12L12 19L21 12L19.37 10.73M19.37 15.73L12 21.47L4.62 15.74L3 17L12 24L21 17L19.37 15.73Z" ></path></svg></span>
                            Активні шари даних
                        <span class="minimise-panel">-</span>
                    </div>
                    <div class="panel-option col-xs-12">
                        <button class="btn btn-sm col-xs-6" @click="openProjectWindow">
                            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>Додати шари
                        </button>
                        <button class="btn btn-sm col-xs-6" @click="removeAllLayers">
                            <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>Скинути
                            <span class="refresh-default">усе</span>
                        </button>
                    </div>
                    <div class="clearfix"></div>
                     <div class="layers-panel">
                        <!--<draggable v-if="getTocVisibleLayers.length > 0" v-model="getTocVisibleLayers" group="layers" >-->
                            <div><div v-for="element in getTocVisibleLayers" :key="element.id">
                                <div class= "input-group checkbox " style="margin:0" >
                                    <input :id="\'layer_\' + element.id" type="checkbox"
                                            :checked="element.map_visibility"
                                            v-on:click="changeLayerVisibility(element.id)">
                                    <label :for="\'layer_\' + element.id" :class="{layerOff: !element.map_visibility}">          
                                            <span v-if="[13,11,19,20,58,59].includes(element.id)" 
                                                        class="material-icons">
                                                <i class="fa fa-home" aria-hidden="true"></i>
                                            </span>
                                            <span v-if="element.id == 17 || element.id == 18" class="material-icons">
                                                storefront
                                            </span>
                                            <span v-if="element.id == 2 || element.id == 7" class="material-icons">
                                                local_hospital
                                            </span>
                                            <span v-if="element.id == 3 ||
                                                        element.id == 5 ||
                                                        element.id == 6"
                                                        class="material-icons">
                                                school
                                            </span>
                                            <span v-if="[45,28,29,30,31,32,33,34,35,36,37,39,41].includes(element.id)"
                                                        class="material-icons">
                                                groups
                                            </span>
                                            <span v-if="element.id == 51 ||
                                                        element.id == 52 ||
                                                        element.id == 53 ||                                                
                                                        element.id == 54 ||                                                
                                                        element.id == 55 ||                                                
                                                        element.id == 56 ||                                                
                                                        element.id == 57"
                                                        class="material-icons">
                                                contact_emergency
                                            </span>
                                            <span v-if="[42,43,9,21,4,16].includes(element.id)"
                                                        class="material-icons">
                                                wifi
                                            </span>
                                            <span v-if="element.id == 15 ||

                                                element.id == 8 ||
                                                element.id == 12 ||
                                                element.id == 26 ||
                                                element.id == 38" class="material-icons">
                                                security
                                            </span>
                                            {{ element.legendName  ? element.legendName  : element.name }}
                                    </label>
                                    <btn class="close" style="padding: 1px;border: none;"
                                                        @click="removeLayer(element.id)">
                                        <i class="fa fa-times fa-2" aria-hidden="true"></i>
                                    </btn>
                                </div>
                            </div></div>
                       <!-- </draggable> -->
                    </div>
               </div></div>
        <!-- ------------------------------------>\
        <div v-else class= "min-TOC" v-on:click="toggleTocClick" >
                <span class="glyphicon">
                <svg style="width:20px;height:20px" viewBox="0 0 24 24" >
                    <path fill="#fff" d="M12 0L3 7L4.63 8.27L12 14L19.36 8.27L21 7L12 0M19.37 10.73L12 16.47L4.62 10.74L3 12L12 19L21 12L19.37 10.73M19.37 15.73L12 21.47L4.62 15.74L3 17L12 24L21 17L19.37 15.73Z" />
                </svg >
                </span > Набір шарів
        </div>`,
    computed: {
        getTocVisibility() {
            //if (this.$store.getters.getTocVisibility) {
                //setTimeout(function () {
                //    $('.TOC').find('input[type="checkbox"]').off('click');
                //    $('.TOC').find('input[type="checkbox"]').on('click', function (e) {
                //        alert('hello');
                //    });
                //}, 100);
           // }
            return this.$store.getters.getTocVisibility;
        },
        getTocVisibleLayers: {
            get() {
                return this.$store.getters.getTocVisibleLayers
            },
            set(value) {
                this.$store.commit('set_mapListLayers', value);
                eventVue.$emit('set_mapListLayers', value);
            }
        }
    },
    methods: {
        initToc: function () {
            this.$store.commit('set_isTocInit', true);
        },
        toggleTocClick: function () {
            this.$store.commit('set_toggleToc');
        },
        changeLayerVisibility(layerId) {
            this.$store.commit('set_layerVisibility', layerId);     
            eventVue.$emit('set_layerVisibility', layerId);
            //eventVue.$emit('clearSelectioHidePopup');
        },
        openProjectWindow: function (e) {
            eventVue.$emit('openProjectWindow', e);
        },
        removeLayer: function (layerId) {
            this.$store.commit('set_onOffLayer', layerId);
            eventVue.$emit('selectLayer', layerId);
            eventVue.$emit('clearSelectioHidePopup');
        },
        removeAllLayers: function () {
            this.$store.commit('removeAllLayers');
            eventVue.$emit('clearSelectioHidePopup');
        }
    }
}

//компонент добавления слоев на карту <span aria-hidden="true">&times;</span>
const layersComponent = {
    template: `<modal v-model="show"
                        title="Шари даних"
                        class="TOC-form"
                        size="lg"
                        :footer="footer"
                        transition="50"
                        @show="showModal"
                        @hide="hiddenModal">
                    <div slot="header">
                                                                   <!--<button                                                                       
                                                                        type="button"
                                                                        class="close"
                                                                        data-dismiss="modal"
                                                                        aria-label="Close"
                                                                        @click="closeModal">
                                                                        <span aria-hidden="true">&times;</span>
                                                                    </button> -->
                            <div v-if="!getUser.roles.Admins" class="TOC-autorisationOffer">
                                Неавторизований користувач.
                                <a  v-on:click="loginClick"> Авторизуватись </a>
                            </div>
                            <h4 class="modal-title">
                        
                            <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                            <div class="firstRow">Оберіть</div>
                            <div class="secondRow">дані для відображення
                                <Btn size="lg"
                                    type="success"
                                    class="TOCmapBtn "
                                    @click="closeModal">
                                        <span>карта</span>
                                        <span class="material-icons">
                                            east
                                        </span>
                                </Btn>
                            </div>
                        </h4>
                    </div>

                    <div v-for="project in getAllProjectsFull()"
                                        class="item-group"
                                        v-bind:class="{ activeItem : project.isShowProjectData }"
                                        :data-project-id="project.id"
                                        @mouseover="mouseItemOver"
                                        @mouseout="mouseItemOut"
                                        @click.prev="onItemClick">
                        
                                
                          <div  style="display: flex; justify-content: flex-end; padding:5px 10px;">
                            <div class="my-switch " @click="toggleAll(project.id)" >
                              <div class="switch-track" :class="{ active: selectAllByProject(project.id) }">
                                <div class="switch-thumb" :class="{ active: selectAllByProject(project.id) }"></div>
                              </div>
                              <span class="switch-label">Вибрати всі</span>
                            </div>
                          </div>


                        <div class="project-item-collapse" role="button"
                                        style="font-size:20px;padding-bottom:10px;line-height: 20px;"
                                        :key="project.id"
                                        :href="\'#\'+project.id"
                                        :aria-expanded="project.isShowProjectData"
                                        @click="collapseClick"
                                        v-html="project.iconToc" >
                        </div>
                      
                     

                        <ul class="selected-project collapse"
                                        v-on:hide.bs.collapse="hideCollapse"
                                        :id="project.id" >
                            
                            <li v-for="layer in project.layers"
                                    class="project-layer checkbox"
                                    :data-attr="\'layer\'+layer.id"
                                    v-show="layer.type !='link' && ((layer.token && layer.token.need && getUser.roles.Admins) || !layer.token )">

                                <div v-if="layer.type !='link' && ((layer.token && layer.token.need && getUser.roles.Admins) || !layer.token )">
                                    <input v-if="((layer.token && layer.token.need && getUser.roles.Admins) || !layer.token ) && layer.type!='link'" type="checkbox"
                                            :id="\'layer\'+layer.id"
                                            :checked="layer.visibility"
                                            v-on:change="tooggleLayer(layer.id)">
                                    <label v-if="((layer.token && layer.token.need && getUser.roles.Admins ) || !layer.token) && layer.type!='link'" 
                                            :for="\'layer\'+layer.id"
                                            :class="{isInvincibility:layer.id == 41}"
                                            v-html="">
                                        {{layer.legendName ? layer.legendName : layer.name}}
                                    </label>
                                </div>                                
                            </li>

                          <!--  <li v-for="layer in project.layers"
                                    class="project-layer checkbox"
                                    v-show="layer.type=='link' && !layer.token" style:"">

                                <a
                                    v-if="layer.type=='link' && !layer.token"
                                    :id="\'layer\'+layer.id"
                                    :href="layer.url"
                                    @click.prevent="gotoAnotherSite"
                                    title="Перейти на сторінку ресурсу"
                                    class="linkLayer"
                                >
                                    <span class="linkLayer_title" >{{layer.name}}</span>
                                    <span class="material-icons">
                                        east
                                    </span>
                                </a>

                            </li>   -->                
                        </ul>
                       <ul class="selected-project collapse"
                            v-on:hide.bs.collapse="hideCollapse"
                            :id="project.id" >
                         <li v-for="layer in getProgectLinkLayers(project)"
                                    class="project-layer checkbox">
                                <a                                   
                                    :id="\'layer\'+layer.id"
                                    :href="layer.url"
                                    @click.prevent="gotoAnotherSite"
                                    title="Перейти на сторінку ресурсу"
                                    class="linkLayer"
                                >
                                    <span class="linkLayer_title" >{{layer.name}}</span>
                                    <span class="material-icons">
                                        east
                                    </span>
                                </a>

                            </li> 

                        </ul> 
                    </div>
                    <!--<div slot="footer" class="customFooter text-center">
                        <Btn size="lg"
                            type="success"
                            @click="closeModal">
                            Показати
                        </Btn>
                    </div>-->

            </modal>`,
    //v-bind:class= "{ in : project.isShowProjectData }"  :aria-expanded="project.isShowProjectData" data-toggle="collapse"
    data: function () {
        return {
            show: false,
            //btnCancelVisible: false,
            footer: false,
            linkStyle: {
                'display': 'inline-block',
                'width': '100%',
                'vertical-align': 'middle',
                'position': 'relative',
                'color': '#fff',
                'min-height': '17px',
                'padding-left': '10px',
                'margin-bottom': '0',
                'font-weight': 'normal',
                'cursor': 'pointer',
                'font-size': '1.3rem',
            }
            
        }
    },
    computed: {
        //getAllProjectsFull() {
        //    return this.$store.getters.getAllProjectsFull;
        //},
        getUser() {
            return this.$store.getters.getUser;
        },
        screenWidth() {
            return window.innerWidth;
        },

        selectAllByProject() {
            return function (projectId) {
                let res = false;
                this.$store.getters.getAllProjects.forEach(function (p) {
                    if (p.id === projectId) {
                        let map_notlink_layers_count = 0;
                        let map_visibility_layers_count = 0;
                        p.layers.forEach(function (l) {
                            if (l.type !== 'link') {
                                map_notlink_layers_count++;
                                if (l.map_visibility) {
                                    map_visibility_layers_count++
                                }
                            }

                        }.bind(this));
                        res = map_visibility_layers_count === map_notlink_layers_count;
                    }
                }.bind(this));
                return res;
            }.bind(this);
        },        
        getProgectLinkLayers() {
            return function (project) {
                let res = [];
                project.layers.forEach(function (l) {
                    if (l.type === 'link') {
                        res.push(l);
                    }

                }.bind(this));
                return res;
            }
        },
    },
    //watch: {
    //    getAllProjectsFull: function (oldData, newData) {
    //        var T = '';
    //    }
    //},
    methods: {
        toggleAll: function (projectId) {
            //поточний стан
            let currentVisibility = this.selectAllByProject(projectId);
            this.$store.getters.getAllProjects.forEach(function (p) {
                if (p.id === projectId) {                    
                    p.layers.forEach(function (l) {
                        //не лінк + наступний стан не повинен співпадати з поточним станом шару

                        if (l.type !== 'link' && !currentVisibility !== l.map_visibility &&
                            (!l.token ||
                            (l.token && l.token.role && this.getUser.roles[l.token.role]) ||
                            (l.token && l.token.need && !l.token.role)
                            )
                        ) {
                            this.$store.commit('set_onOffLayer', l.id);
                            eventVue.$emit('selectLayer', l.id);
                        }
                    }.bind(this));
                }
            }.bind(this));

        },
        stopTheEvent: function (event) {
            event.stopPropagation();
        },
        tooggleLayer: function (layerId, e) {
            this.$store.commit('set_onOffLayer', layerId);
            eventVue.$emit('selectLayer', layerId);
            eventVue.$emit('clearSelectioHidePopup');
            this.onItemClick(e);
        },
        closeModal: function (e) {
            this.show = false;
        },
        openModal: function (e) {
            this.show = true;
        },
        showModal: function (e) {
            var groups = this.$el.getElementsByClassName('activeItem');
            for (var i = 0; i < groups.length; i++) {
                var prItemCollapse = groups[i].getElementsByClassName('project-item-collapse'),
                    ulSelectProject = groups[i].getElementsByClassName('selected-project');
                prItemCollapse[0].setAttribute('aria-expanded', 'true');
                ulSelectProject[0].classList.add("in");
            }
        },
        hiddenModal: function (e) {
            var groups = this.$el.getElementsByClassName('item-group');
            for (var i = 0; i < groups.length; i++) {
                var prItemCollapse = groups[i].getElementsByClassName('project-item-collapse'),
                    ulSelectProject = groups[i].getElementsByClassName('selected-project');
                prItemCollapse[0].setAttribute('aria-expanded', 'false');
                ulSelectProject[0].classList.remove("in");
            }
        },
        collapseClick: function (e) {
            if (this.show)
                eventVue.$emit('centerModal', this);
        },
        //checkScreen: function () {
        //    window.innerWidth > 768 ?
        //        this.btnCancelVisible = false :
        //        this.btnCancelVisible = true;
        //},

        clickOnCheckbox: function (layerId) {
            this.$el.querySelector('#layer' + layerId).click();
        },
        getAllProjectsFull() {
            return this.$store.getters.getAllProjectsFull;
        },
        mouseItemOver: function (e) {
            var el;
            if (e.currentTarget.classList.contains('item-group'))
                el = e.currentTarget;
            else
                el = e.currentTarget.closest(".item-group");
            el.querySelectorAll('.selected-project').forEach(function (ell) {
                ell.classList.add('in');
            }.bind(this));
            el.querySelector('.my-switch').classList.add('in');
            //el.querySelector('ul').classList.add('in');
            //el.querySelector('.selected-project').classList.add('in');
        },
        mouseItemOut: function (e) {
            var projects = this.$store.getters.getAllProjectsFull,
                ul = e.currentTarget.querySelector('ul'),
                dv = e.currentTarget.querySelectorAll('.selected-project'),
                sw = e.currentTarget.querySelector('.my-switch'),
                projectId = +ul.id,
                remove = false;
            projects.forEach(function (item) {
                if (item.id == projectId)
                    remove = (item.isShowProjectData) ? false : true;
            }.bind(this));
            if (remove) {
                dv.forEach(function (ell) {
                    ell.classList.remove('in');
                }.bind(this));
                sw.classList.remove('in');
                //ul.classList.remove('in');
                //dv.classList.remove('in');
            }
                
        },
        onItemClick: function (e) {
            if (e && window.innerWidth < 768 && (e.target.localName == 'div' || e.target.localName == 'input' || e.target.localName == 'label'))
                this.mouseItemOver(e);
            //else if (window.innerWidth < 768 && (e.target.localName == 'div' && e.target.querySelector('ul.in')) || (e.target.localName == 'input' && e.target.closest(".item-group").querySelector('ul.in')))
            //    this.mouseItemOut(e);
        },
        hideCollapse: function (e) {
            varT = '';
        },
        gotoAnotherSite: function (e) {
            window.open(e.currentTarget.href, "_blank");
        },
        loginClick: function (e) {
            eventVue.$emit('loginLinkOnClick');
            eventVue.$emit('hideCollapse');
        },
    },
    beforeUpdate: function () {
        if (this.show) {
            eventVue.$emit('centerModal', this);
            //setTimeout(function () {  eventVue.$emit('centerModal', this);}.bind(this), 100);
           
        }


    }
};
const layersComponent_mobile = {
    template: `<modal v-model="show"
                        title="Шари даних"
                        class="TOC-form TOC-formMobile"
                        size="lg"
                        :footer="footer"
                        transition="50"
                        @show="showModal"
                        @hide="hiddenModal">
                    <div slot="header">
                                                                   <!--<button                                                                       
                                                                        type="button"
                                                                        class="close"
                                                                        data-dismiss="modal"
                                                                        aria-label="Close"
                                                                        @click="closeModal">
                                                                        <span aria-hidden="true">&times;</span>
                                                                    </button>-->
                                                                   
                            <div v-if="!getUser.roles.Admins" class="TOC-autorisationOffer">
                                Неавторизований користувач.
                                <a  v-on:click="loginClick"> Авторизуватись </a>
                            </div>
                            <h4 class="modal-title">
                            <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                            <div class="firstRow">Оберіть</div>
                            <div class="secondRow">дані для відображення
                                <Btn size="lg"
                                    type="success"
                                    class="TOCmapBtn "
                                    @click="closeModal">
                                        <span>карта</span>
                                        <span class="material-icons">
                                            east
                                        </span>
                                </Btn>
                            </div>
                        </h4>
                    </div>

                    <div v-for="project in getAllProjectsFull()"
                                        class="item-group"
                                        :data-project-id="project.id"
                                        @click.stop="onItemClick" >
                        <div class="project-item-collapse" role="button"
                                        :key="project.id"
                                        :href="\'#\'+project.id"
                                        :aria-expanded="project.isShowProjectData"
                                     
                                        v-html="project.iconToc" >
                                                                            <!--<span class="caret"></span>{{ project.name }} <i class="material-icons">school</i> -->
                        </div>



                        <ul class="selected-project collapse"
                                        v-on:hide.bs.collapse="hideCollapse"
                                        :id="project.id" >
                        <li class="project-layer checkbox">
                          
                                <div style="display: flex; justify-content: flex-end; padding:5px 10px;">
                                    <div class="my-switch" @click="toggleAll(project.id)" >
                                      <div class="switch-track" :class="{ active: selectAllByProject(project.id) }">
                                        <div class="switch-thumb" :class="{ active: selectAllByProject(project.id) }"></div>
                                      </div>
                                      <span class="switch-label">Вибрати всі</span>
                                    </div>
                                  </div>
                        </li>
                            <li v-for="layer in project.layers"
                                    class="project-layer checkbox"
                                    v-show="layer.type !='link' && ((layer.token && layer.token.need && getUser.roles.Admins) || !layer.token )">
                                <div v-if="layer.type !='link' && ((layer.token && layer.token.need && getUser.roles.Admins) || !layer.token )">
                                    <input v-if="((layer.token && layer.token.need && getUser.roles.Admins) || !layer.token ) && layer.type!='link'" type="checkbox"
                                            :id="\'layer\'+layer.id"
                                            :checked="layer.visibility"
                                            v-on:change="tooggleLayer(layer.id)">
                                    <label v-if="((layer.token && layer.token.need && getUser.roles.Admins ) || !layer.token) && layer.type!='link'" 
                                            :for="\'layer\'+layer.id"
                                            :class="{isInvincibility:layer.id == 41}"
                                            v-html="">
                                         {{layer.legendName ? layer.legendName : layer.name}}
                                                                                            <!--<i v-if="layer.id == 41" class="fa fa-bolt" aria-hidden="true"></i>
                                                                                                    <span v-if="layer.id == 41" class="material-icons">
                                                                                                        offline_bolt
                                                                                            </span>-->
                                    </label>
                                                                                            <!-- Додаткова класифікація пунктів незламності -->
                                                                                                <!--<div v-if="layer.id == 41">
                                                                                                        <ul style="text-decoration: none;
                                                                                                                    padding: 0 0 0 10px;
                                                                                                                    color: #fff;
                                                                                                                    font-size: 10px;
                                                    
                                                                                                                ">
                                                                                                            <li class="project-layer_innerListItem">
                                                                                                                <img src="/opendataportal/Images/default_41_в режимі очікування.svg" width="22" height="22"/>
                                                                                                                <span>В режимі очікування</span>
                                                                                                            </li>
                                                                                                            <li class="project-layer_innerListItem">
                                                                                                                <img src="/opendataportal/Images/default_41_цілодобово.svg" width="22" height="22"/>
                                                                                                                <span>Цілодобово</span>
                                                                                                            </li>
                                                                                                        </ul>
                                            
                                                                                                </div>-->   
                                </div>                                
                            </li>

                            <li v-for="layer in project.layers"
                                    class="project-layer checkbox"
                                    v-show="layer.type=='link' && !layer.token">

                                <a
                                    v-if="layer.type=='link' && !layer.token"
                                    :id="\'layer\'+layer.id"
                                    :href="layer.url"
                                    @click.prevent="gotoAnotherSite"
                                    title="Перейти на сторінку ресурсу"
                                    class="linkLayer"
                                >
                                                                                            <!--<i class="fa fa-mail-forward" aria-hidden="true" style="opacity: 0"></i>-->
                                    <span class="linkLayer_title" >{{layer.name}}</span>
                                    <span class="material-icons">
                                        east
                                    </span>
                                </a>

                            </li>

                        </ul>
                    </div>
                    <!--<div slot="footer" class="customFooter text-center">
                        <Btn size="lg"
                            type="success"
                            @click="closeModal">
                            Показати
                        </Btn>
                    </div>-->

            </modal>`,
    //v-bind:class= "{ in : project.isShowProjectData }"  :aria-expanded="project.isShowProjectData" data-toggle="collapse"
    data: function () {
        return {
            show: false,
            //btnCancelVisible: false,
            footer: false,
            linkStyle: {
                'display': 'inline-block',
                'width': '100%',
                'vertical-align': 'middle',
                'position': 'relative',
                'color': '#fff',
                'min-height': '17px',
                'padding-left': '10px',
                'margin-bottom': '0',
                'font-weight': 'normal',
                'cursor': 'pointer',
                'font-size': '1.3rem',
            }
            
        }
    },
    computed: {
        //getAllProjectsFull() {
        //    return this.$store.getters.getAllProjectsFull;
        //},
        getUser() {
            return this.$store.getters.getUser;
        },
        selectAllByProject() {
            return function (projectId) {
                let res = false;
                this.$store.getters.getAllProjects.forEach(function (p) {
                    if (p.id === projectId) {
                        let map_notlink_layers_count = 0;
                        let map_visibility_layers_count = 0;
                        p.layers.forEach(function (l) {
                            if (l.type !== 'link') {
                                map_notlink_layers_count++;
                                if (l.map_visibility) {
                                    map_visibility_layers_count++
                                }
                            }

                        }.bind(this));
                        res = map_visibility_layers_count === map_notlink_layers_count;
                    }
                }.bind(this));
                return res;
            }.bind(this);
        },    
    },
    watch: {
        getAllProjectsFull: function (oldData, newData) {
            var T = '';
        }
    },
    methods: {
        toggleAll: function (projectId) {
            //поточний стан
            let currentVisibility = this.selectAllByProject(projectId);
            this.$store.getters.getAllProjects.forEach(function (p) {
                if (p.id === projectId) {
                    p.layers.forEach(function (l) {
                        //не лінк + наступний стан не повинен співпадати з поточним станом шару

                        if (l.type !== 'link' && !currentVisibility !== l.map_visibility &&
                            (!l.token ||
                                (l.token && l.token.role && this.getUser.roles[l.token.role]) ||
                                (l.token && l.token.need && !l.token.role)
                            )
                        ) {
                            this.$store.commit('set_onOffLayer', l.id);
                            eventVue.$emit('selectLayer', l.id);
                        }
                    }.bind(this));
                }
            }.bind(this));

        },
        stopTheEvent: function (event) {
            event.stopPropagation();
        },
        tooggleLayer: function (layerId, e) {
            this.$store.commit('set_onOffLayer', layerId);
            eventVue.$emit('selectLayer', layerId);
            eventVue.$emit('clearSelectioHidePopup');
            //this.onItemClick(e);
        },
        closeModal: function (e) {
            this.show = false;
        },
        openModal: function (e) {
            this.show = true;
        },
        showModal: function (e) {
            var groups = this.$el.getElementsByClassName('activeItem');
            for (var i = 0; i < groups.length; i++) {
                var prItemCollapse = groups[i].getElementsByClassName('project-item-collapse'),
                    ulSelectProject = groups[i].getElementsByClassName('selected-project');
                prItemCollapse[0].setAttribute('aria-expanded', 'true');
                ulSelectProject[0].classList.add("in");
            }
        },
        hiddenModal: function (e) {
            var groups = this.$el.getElementsByClassName('item-group');
            for (var i = 0; i < groups.length; i++) {
                var prItemCollapse = groups[i].getElementsByClassName('project-item-collapse'),
                    ulSelectProject = groups[i].getElementsByClassName('selected-project');
                prItemCollapse[0].setAttribute('aria-expanded', 'false');
                ulSelectProject[0].classList.remove("in");
            }
        },
        collapseClick: function (e) {
            if (this.show)
                eventVue.$emit('centerModal', this);
        },
        //checkScreen: function () {
        //    window.innerWidth > 768 ?
        //        this.btnCancelVisible = false :
        //        this.btnCancelVisible = true;
        //},

        clickOnCheckbox: function (layerId) {
            this.$el.querySelector('#layer' + layerId).click();
        },
        getAllProjectsFull() {
            return this.$store.getters.getAllProjectsFull;
        },
        mouseItemOver: function (e) {
            var el, targetUlClasslist;
                if (e.currentTarget.classList.contains('item-group'))
                    el = e.currentTarget;
                else
                    el = e.currentTarget.closest(".item-group");
            el.querySelectorAll('.selected-project').forEach(function (ell) {
                //ell.classList.add('in');
                targetUlClasslist = el.querySelector('.selected-project').classList;
                targetUlClasslist.contains('in') ? targetUlClasslist.remove('in') : targetUlClasslist.add('in');
            }.bind(this));
            el.querySelector('.my-switch').classList.add('in');

            //targetUlClasslist = el.querySelector('.selected-project').classList;
            //targetUlClasslist.contains('in') ? targetUlClasslist.remove('in') : targetUlClasslist.add('in');
        },
        mouseItemOut: function (e) {
            var projects = this.$store.getters.getAllProjectsFull,
                ul = e.currentTarget.querySelector('ul'),
                dv = e.currentTarget.querySelectorAll('.selected-project'),
                sw = e.currentTarget.querySelector('.my-switch'),
                projectId = +ul.id,
                remove = false;
            projects.forEach(function (item) {
                if (item.id == projectId)
                    remove = (item.isShowProjectData) ? false : true;
            }.bind(this));
            if (remove) {
                dv.forEach(function (ell) {
                    ell.classList.remove('in');
                }.bind(this));
                sw.classList.remove('in');
                //ul.classList.remove('in');
                //dv.classList.remove('in');
            }

            //var projects = this.$store.getters.getAllProjectsFull,
            //    ul = e.currentTarget.querySelector('ul'),
            //    projectId = +ul.id,
            //    remove = false;
            //projects.forEach(function (item) {
            //    if (item.id == projectId)
            //        remove = (item.isShowProjectData) ? false : true;
            //}.bind(this));
            //if (remove)
            //    ul.classList.remove('in');
        },
        onItemClick: function (e) {
            if (e && e.target.classList.value.indexOf("switch") < 0 && (e.target.localName == 'div' || e.target.localName == 'span' || e.target.localName == 'i'))
                //if (e && (e.target.localName == 'div' || e.target.localName == 'input' || e.target.localName == 'label' || e.target.localName == 'span' || e.target.localName == 'i'))
                this.mouseItemOver(e);
            //else if (window.innerWidth < 768 && (e.target.localName == 'div' && e.target.querySelector('ul.in')) || (e.target.localName == 'input' && e.target.closest(".item-group").querySelector('ul.in')))
            //    this.mouseItemOut(e);
        },
        hideCollapse: function (e) {
            varT = '';
        },
        gotoAnotherSite: function (e) {
            window.open(e.currentTarget.href, "_blank");
        },
        loginClick: function (e) {
            eventVue.$emit('loginLinkOnClick');
            eventVue.$emit('hideCollapse');
        },
    },
    beforeUpdate: function () {
        if (this.show) {
            eventVue.$emit('centerModal', this);
            //setTimeout(function () {  eventVue.$emit('centerModal', this);}.bind(this), 100);
           
        }


    }
};

//legend--------------------------------------
const legendComponent = {
    template: '<div class="legend-group"><div class= "LEGEND" v-bind:class= "{ visibleLegend : getLegendVisibility }" >\
                <div class="visible-panel">\
                    <div class="panel-name">\
                        <i class="material-icons">category</i>\
                        Легенда\
                        <span class="minimise-panel" @click="toggleLegend">-</span>\
                        <button id="legendCloseButton" class="closeButton" @click="fullClose"></button>\
                    </div>\
                    <div class="clearfix"></div>\
                    <div id="legendContent"></div>\
               </div>\
            </div>\
            <div v-if="showMinLegend" class="min-legend" @click="toggleLegend" ><i class="material-icons">category</i>\<span>Легенда</span></div>\
        </div>', 
    data: function () {
        return {
            showMinLegend:false
        }
    },
    computed: {
        getLegendVisibility() {
            var visibility = this.$store.getters.getLegendVisibility;            
            return visibility;
        }
    },
    methods: {
        toggleLegend: function () {
            var currentMinLegendState = this.showMinLegend;
            this.showMinLegend = !currentMinLegendState;
            this.$store.commit('toggleLegend');
        },
        fullClose: function (e) {
            this.toggleLegend();
            this.showMinLegend = false;
        },
        //openModal: function (e) {
        //    this.show = true;
        //},
        //showModal: function (e) {
        //},
        //hiddenModal: function (e) {
        //},
        //collapseClick: function () {
        //    if (this.show)
        //        eventVue.$emit('centerModal', this);
        //}
    },
    mounted: function () {

        eventVue.$emit('initLegend');
    },
    updated: function () {
        setTimeout(function () {eventVue.$emit('initLegend'); }.bind(this), 300);
        
    }
};

//feedback------------------------------------------
const feedbackComponent = {
    template: `<modal v-model="showw"
                    id="feedbackForm"
                    class="entrance-form"
                    title="Зворотній з\'вязок"
                    size="lg"
                    @show="showModal"
                    @hide="hiddenModal">
               <div class="row">
                    <div class="form-group">
                        <!--<label for="feedback-name">Як Вас звати: </label>-->
                        <input type="text" class="form-control errorInput" id="feedback-name" placeholder="Як Вас звати?" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="name" :readonly="this.isAuth"/>
                    </div>
                </div>
                <div class="row">
                    <div class="alert alert-warning alert-dismissible" role="alert">
                      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                      <div><strong>Увага! </strong></div>
                        <p>З питань функціонування, облаштування та достпу до <strong>укриттів</strong> міста
                        <a href="https://1562.kharkivrada.gov.ua/" class="alert-link" target="_blanc" style="text-decoration: underline">звертатись</a>
                            до служби 1562.</p>
                    </div>
                </div>
                <!-- <div class="row">
                    <div class="form-group surname-group">
                        <input type="text" class="form-control " v-bind:class="{ errorInput: !hideEmail }" id="feedback-email" placeholder="Email або +380ХХХХХХХХХ" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="email" :readonly="this.isAuth"  v-bind:style="{ display: emailDisplay }"/>
                        <div class="tooltip" v-bind:style="{ display: emailDisplay }">&#42; Для обробки звернення необхідні дійсні дані!</div>
                     </div>
                </div> -->
                <div class="row">
                    <div class="form-group ">
                        <!--<label for="feedback-text">Текст звернення </label>-->
                        <textarea class="form-control errorInput" rows="7" id="feedback-text" placeholder="Текст звернення" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="textmail"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 captchaContainer">
                        <div class="form-group">
                            <div class="row">
                                <div class="col-xs-8 captchaInputContainer">
                                        <input id="captchaInput" type="text" class="form-control" v-bind:class="{ errorInput: !captchaCode }" placeholder="Введіть код" @input="inputEvents" @change="inputEvents" @copy="inputEvents" @paste="inputEvents" @cut="inputEvents" v-model="captchaCode">
                                </div>
                                <div class="col-xs-4 captchaImgContainer text-right"><img :src="captchaSorce" alt="captcha" rel="preload" /></div>
                            </div>
                        </div>
                    </div>
                </div>
            <div slot="footer">
                <btn type="button" class="btn btn-primary col-xs-12 enter-modal-footer-right disabeled-btn" id="forgotButton" :disabled="disabledEnterBtn" @click="buttonClick">НАДІСЛАТИ</btn >
                  </div>
                </modal>`,
    data: function () {
        return {
            showw: false,
            shown: false,
            disabledEnterBtn: true,
            name: '',
            email: '',
            textmail: '',
            isAuth: false,
            hideEmail: false,
            captchaCode:'',
            emailDisplay: 'block',
            captchaSorce: ''
        }
    },
    methods: {
        closeModal: function (e) {
            this.showw = false;
        },
        openModal: function (user) {
            
            if (user.Loginn != 'guest' && (user.roles.Informants || user.roles.Moderators || user.roles.Admins)) {
                this.updateCaptcha();
                this.name = user.Loginn;
                if (user.Email)
                    this.email = user.Email;
                else if (user.Phone)
                    this.email = '+' + user.Phone;
                else
                    this.email = '          ';
                this.isAuth = true;
                this.showw = true;
            }
            else
                this.$store.dispatch('showNeedAuthorizeMessage');
                //eventVue.$emit('showSimpleMessage', store.state.messagesStore.messagesTexts.UserNotFound);

        },
        showModal: function (e) {
            if (this.name != '') {
                this.validationElement(this.$el.querySelector('#feedback-name'));
                this.hideEmail = true;
                this.emailDisplay = this.hideEmail ? 'none' : 'block';
                //this.$el.querySelector('#feedback-email').classList.remove("errorInput");
                //this.$el.querySelector('#feedback-email').style.display = 'none';
                //this.validationElement(this.$el.querySelector('#feedback-email'));
            }
            this.shown = true;
        },
        hiddenModal: function (e) {
            eventVue.$emit('undoStartCloseModal', this);
            this.shown = false;
            this._clearForm();
        },
        inputEvents: function (e) {
            this.validationElement(e.currentTarget);
        },
        buttonClick: function (e) {
            this.$store.dispatch('Feedback',
                JSON.stringify({
                    ajax: this.$store.getters.getAjaxUrlByName('Feedback'),
                    //name: this.$el.querySelector('#feedback-name').value,
                    //email: this.$el.querySelector('#feedback-email').value,
                    //textmail: this.$el.querySelector('#feedback-text').value,
                    name: this.name,
                    email: this.email,
                    textmail: this.textmail,
                    captcha: this.captchaCode,
                }));
        },
        validationElement: function (e) {
            switch (e.id) {
                case 'feedback-email': {
                    if (this._checkEmail(e.value))
                        e.classList.remove('errorInput');
                    else if (this._checkPhone(e.value))
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
                case 'captchaInput':
                case 'feedback-text':
                case 'feedback-name': {
                    if (e.value.length > 2)
                        e.classList.remove('errorInput');
                    else
                        e.classList.add('errorInput');
                }
                    break;
            }
            this._enabilityButtonLoginForm();
        },
        updateCaptcha: function () {
            store.commit('set_isSearcherInit', false);
            this.captchaCode = '';
            this.captchaSorce = '';           
            let img = new Image();
            img.src = '/opendataportal/Home/Captcha?timestamp=' + new Date().getTime();
            img.onload = (e) => {
                store.commit('set_isSearcherInit', true);
                // this.captchaSorce = e.path[0].attributes.src.value;
                this.captchaSorce = e.currentTarget.src;
            }
        },
        _enabilityButtonLoginForm: function () {
            this.disabledEnterBtn = (this.$el.getElementsByClassName('errorInput').length > 0) ? true : false;
        },
        _checkEmail: function (data) {
            var re3 = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
            return re3.test(String(data).toLowerCase());
        },
        _checkPhone: function (data) {
            var re = /(\+380)[0-9]{9}/;
            if (data.length < 14)
                return re.test(String(data).toLowerCase()) ? true : false
            else
                return false;
        },
        _clearForm: function () {
            this.name = '';
            this.email = '';
            this.textmail = '';
            this.isAuth = false;
            this.hideEmail = false;
            this.emailDisplay = 'block';
            this.captchaCode = '';
            this.captchaSorce = '';    
            var inputs = this.$el.getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].value = '';
                this.validationElement(inputs[i]);
            }
            var textareas = this.$el.getElementsByTagName('textarea');
            for (var j = 0; j < textareas.length; j++) {
                textareas[j].value = '';
                this.validationElement(textareas[j]);
            }
            this._enabilityButtonLoginForm();
        }
    },
    beforeUpdate: function () {
        if (this.showw && !this.shown) {
            eventVue.$emit('centerModal', this);
            setTimeout(function () {
                eventVue.$emit('startCloseModal', this);
            }.bind(this), 300);
        }
    }
}

//links ---------------------------------------
const linksComponent = {
    template: '<modal v-model="showw" id="linksForm" title="Джерела відкритих даних" size="lg" :footer="false" @show="showModal" @hide="hiddenModal">\
                    <div class="row row-input">\
                        <div v-for="item in getLinks" class= "input-group enter-input-group col-xs-6">\
                            <a :href="item.href" target="_blank" @click="aclick" >\
                                <img :src="`/opendataportal/Images/b_${item.id}.jpg`" />\
                            </a >\
                        </div >\
                    </div>\
                </modal>',
    computed: {
        getLinks() {
            return this.$store.getters.getLinks;
        }
    },
    data: function () {
        return {
            showw: false,
            shown: false,
        }
    },
    methods: {
        closeModal: function (e) {
            this.showw = false;
        },
        openModal: function (e) {
            this.showw = true;
        },
        showModal: function (e) {
            this.shown = true;
        },
        hiddenModal: function (e) {
            eventVue.$emit('undoStartCloseModal', this);
            this.shown = false;
        },
        aclick: function () {
            this.closeModal();
        }
    },
    beforeUpdate: function (e) {
        if (this.showw && !this.shown) {
            eventVue.$emit('centerModal', this);
            setTimeout(function () {
                eventVue.$emit('startCloseModal', this);
            }.bind(this), 300);
        }
    }

}

//statistic ---------------------------------------
const statisticComponent = {
    template: '<modal v-model="showw" id="statisticForm" title="Загальна статистика" size="lg" :footer="false" @show="showModal" @hide="hiddenModal">\
                    <div class="row">\
                        <div class="col-xs-12 col-sm-12 filterContainer">\
                           <div class="form-group">\
                            <form class="form-inline">\
                                         <div class="input-group">\
                                            <select v-model="selected" @change.prevent="changeProject">\
                                                <option v-for="item in statProjects" :value="item.id"> {{item.name}}</option>\
                                            </select>\
                                        </div>\
                            </form>\
                              <form class="form-inline">\
                                       <div class="form-group">\
                                        <div class="calendar-group">\
                                            <div class="descr">З</div>\
                                            <input id="startDate" type="date" v-model="dateFrom" class="form-control mailing_history-input" min="2019-01-01" :disabled="!isFiltering"/>\
                                        </div>\
                                       </div>\
                              </form>\
                              <form class="form-inline">\
                                    <div class="form-group">\
                                       <div class="calendar-group">\
                                            <div class="descr">ПО</div>\
                                            <input class="form-control" type="date" v-model="dateTo" :disabled="!isFiltering">\
                                        </div>\
                                </div>\
                              </form>\
                              <button id="stat-show" class="btn btn-default col-xs-12 col-sm-3" @click="startFiltering" :disabled="!isFiltering">Показати</button>\
                            </div></div>\
                        </div>\
                        <!-- ------- -->\
                        <div class="row">\
                        <div class="col-xs-12 col-sm-12">\
                          <div v-for="item in chartData" class="small col-xs-12 col-sm-6">\
                            <div>\
                                <p v-if="item.filtering">{{item.title}} з {{dateOnFormFrom}} по {{dateOnFormTo}}</p>\
                                <p v-if="!item.filtering">{{item.title}}</p>\
                                <form v-if="item.type===3" class="form-inline">\
                                    <div class="input-group">\
                                        <select @change.prevent="changeDataByType" :data-statid="item.id">\
                                            <option v-for="itemm in item.types" :value="itemm.id"> {{itemm.name}}</option>\
                                        </select>\
                                    </div>\
                                </form>\
                            </div>\
                            <div v-if="item.type===2">\
                                <mixed-chart :mmixedChartData="item" :options="{responsive: false, maintainAspectRatio: false}"   :width="widthMixedContainer" :height="heightMixedContainer"></mixed-chart>\
                            </div>\
                            <div v-else-if="item.type === 0">\
                                <bar-chart :chartdata="item" :options="{responsive: true, maintainAspectRatio: false,  scales: {xAxes: [{  stacked: true, ticks: {autoSkip: false, beginAtZero: true}}]}}"   :width="widthBarContainer" :height="heightBarContainer"></bar-chart>\
                            </div>\
                            <div v-else-if="item.type === 1">\
                                <pie-chart :piechartdata="item" :options="pieOption"   :width="widthPieContainer" :height="heightPieContainer"></pie-chart>\
                            </div>\
                             <div v-else-if="item.type === 3">\
                                <mixedtypes-chart :mmixedTypesChartData="item" :options="{responsive: false, maintainAspectRatio: false}"   :width="widthMixedTypesContainer" :height="heightMixedTypesContainer"></mixedtypes-chart>\
                            </div>\
                            <div v-else-if="item.type === 4">\
                                <staked-chart :mmixedTypesChartData="item" :options="{responsive: true, maintainAspectRatio: false}"   :width="widthMixedTypesContainer" :height="heightMixedTypesContainer"></staked-chart>\
                            </div>\
                          <!-- </div></br> -->\
                        </div></div>\
                    </div>\
                </modal>',
    computed: {
        chartData() {
            var chartData = this.$store.getters.getChartData ? this.$store.getters.getChartData : []
            //if (chartData.length > 0 && chartData[0].datasets[0].data && chartData[0].datasets[0].data.length > 0)
            if (chartData.length > 0)
                return chartData;
        },

        statProjects() {
            return this.$store.getters.getStatProjects;
        },
        shortChartData() {
            return this.$store.getters.getBarData;
        },
        shortPieChartData() {
            return this.$store.getters.getPieData;
        },
        mixedChartData() {
            var mixedData = this.$store.getters.getMixedData ? this.$store.getters.getMixedData.data : []
            if (mixedData.length > 0 && mixedData[0].datasets[0].data && mixedData[0].datasets[0].data.length > 0)
                return (mixedData[0].datasets[0].data.length > 0) ? this.$store.getters.getMixedData.data : [];
        },
        isFiltering() {
            return this.$store.getters.getFiltering;
        },
        widthBarContainer() {
            return window.innerWidth < 768 ? 100 : 500;
        },
        heightBarContainer() {
            return window.innerWidth < 768 ? 250: 300;    
        },
        widthPieContainer() {
            return window.innerWidth < 768 ? 100 : 500 ;
        },
        heightPieContainer() {
            return window.innerWidth < 768 ? 250 : 350 ;
        },
        heightMixedContainer() {
            return window.innerWidth < 768 ? 350 : 300;
        },
        widthMixedContainer() {
            return window.innerWidth < 768 ? (window.innerWidth - 50) : (window.innerWidth > 1300 ? 500 : 450 );
        },
        heightMixedTypesContainer() {
            return window.innerWidth < 768 ? 250 : 300;
        },
        widthMixedTypesContainer() {
            return window.innerWidth < 768 ? (window.innerWidth - 50) : (window.innerWidth > 1300 ? 500 : 450);
        },
        pieOption() {
            return {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: true,
                    position: window.innerWidth < 768 ? 'top' : 'bottom',
                    fullWidth: false,
                    labels: {
                        boxWidth: 10,
                        fontSize: 12,
                    }
                }
            }
        }

    },
    data: function () {
        return {
            showw: false,
            shown: false,
            dateFrom: '',
            dateTo: '',
            dateOnFormFrom: '',
            dateOnFormTo: '',
            selected:'',
            selectedProject: null, 
            selectedProjectName: '',
            shortArr: [],
            longArr: [], 
            dateArr:[]
        }
    },
    methods: {
        closeModal: function () {
            if (this.selected)
                this.$store.commit('clear_currentStatisticProject', this.selected);
            //eventVue.$emit('startInterval');
            //eventVue.$emit('updateChart');
            //eventVue.$emit('updateMixedChart');
            //eventVue.$emit('updateMixedTypeChart');
            this.showw = false;
        },
        openModal: function () {
            this._selectFirst();
            this.showw = true;
            //if (this.$store.getters.getStatProjects.length > 0)
            //    this.showw = true;
            //else
            //    eventVue.$emit('showSimpleMessage', this.$store.getters.getMessagesStore.messagesTexts.noSelectedProjectWithStat);
        },
        showModal: function () {
            this.shown = true;

            //this._selectFirst();
            eventVue.$emit('startInterval');
            eventVue.$emit('updateChart');
            eventVue.$emit('updateMixedChart');
            eventVue.$emit('updateMixedTypeChart');
        },
        hiddenModal: function () { 
            if (this.selected)
                this.$store.commit('clear_currentStatisticProject', this.selected);
            eventVue.$emit('startInterval');
            eventVue.$emit('updateChart');
            eventVue.$emit('updateMixedChart');
            eventVue.$emit('updateMixedTypeChart');
            this.shown = false;

            this._createInitData(1);
            this.selected = '';
            this.selectedProject = null;
            this.selectedProjectName = '';
            this.shortArr = [];
            this.longArr = [];
            this.dateArr = [];
            eventVue.$emit('stopInterval');
        },
        aclick: function () {
            this.closeModal();
        },
        changeProject: function (e) {           
                //eventVue.$emit('stopInterval');
            this.selectedProject = +e.target.value;            
            var currentProject = this.$store.getters.getProjectById(+e.target.value);
            this.selectedProjectName= currentProject.name;
                console.log(e.target.value);
                //вычисляем и присваиваем даты
            this._createInitData(currentProject.statistic.defaultDays);
            this.$store.commit('set_currentStatisticProject', currentProject.id);     
            this.$store.dispatch('StartProjectStatistic', { projectId: currentProject.id, datefrom: this.dateOnFormFrom, dateto: this.dateOnFormTo});
        },
        startFiltering: function (e) {
            if (this.dateFrom <= this.dateTo) {
                var currentProject = this.$store.getters.getProjectById(+this.selectedProject),
                    dateFarr = this.dateFrom.split('-'),
                    dateTarr = this.dateTo.split('-');
                this.dateOnFormFrom = dateFarr[2] + '.' + dateFarr[1] + '.' + dateFarr[0];
                this.dateOnFormTo = dateTarr[2] + '.' + dateTarr[1] + '.' + dateTarr[0];
                
                currentProject.statistic.data.forEach(function (item, index) {
                    if (item.class && item.class == 'date') {
                        var dateFarr = this.dateFrom.split('-'),
                            dateTarr = this.dateTo.split('-');
                        this.dateOnFormFrom = dateFarr[2] + '.' + dateFarr[1] + '.' + dateFarr[0];
                        this.dateOnFormTo = dateTarr[2] + '.' + dateTarr[1] + '.' + dateTarr[0];
                        this.dateArr.push({
                            method: 'GetProjectDateStatistic',
                            ajax: JSON.stringify({
                                ajax: store.getters.getAjaxUrlByName(item.method),
                                layerId: null,
                                projectId: currentProject.id,
                                statId: item.id,
                                datefrom: this.dateOnFormFrom,
                                dateto: this.dateOnFormTo,
                                vuexMethod: item.vuexMethod
                            })
                        });
                    }

                }.bind(this));
                this._createStartLoadingData();
            }
            else
                eventVue.$emit('showSimpleMessage', this.$store.state.messagesStore.messagesTexts.dateFromLessDateTo);
        },
        _createStartLoadingData: function () {
            if (this.shortArr.length > 0) {
                this.$store.dispatch('GetProjectShortStatistic', this.shortArr);
                this.shortArr.length = 0;
            }
            if (this.longArr.length > 0) {
                this.$store.dispatch('GetProjectMixedStatistic', this.longArr);
                this.longArr.length = 0;
            }
            if (this.dateArr.length > 0) {
                this.$store.dispatch('GetProjectDateStatistic', this.dateArr);
                this.dateArr.length = 0;
            }
        },
        _createInitData: function (initAmountDays) {
            var dateFrom = new Date(Date.now() - 24 * initAmountDays * 60 * 60 * 1000),
                dateTo = new Date();
            this.dateFrom = this._formatDateYYYY_MM_DD(dateFrom);
            this.dateTo = this._formatDateYYYY_MM_DD(dateTo);    
            this.dateOnFormFrom = this._formatDateDDMMYYYY(dateFrom);
            this.dateOnFormTo = this._formatDateDDMMYYYY(dateTo);    
            //this.dateFrom = weekAgoDay;
            //this.dateTo = today;
        },
        _formatDateYYYY_MM_DD: function(date) {
            var d = [+date.getFullYear().toString(), date.getMonth() + 1, date.getDate()];
            d.forEach(function (v, i, a) {
                if (v < 10) return a[i] = '0' + v;
            });
            return d.join('-');
        },
        _formatDateDDMMYYYY: function (date) {
            var d = [ date.getDate(), date.getMonth() + 1,+date.getFullYear().toString()];
            d.forEach(function (v, i, a) {
                if (v < 10) return a[i] = '0' + v;
            });
            return d.join('.');
        },
        _selectFirst: function () {
            var projects = this.$store.getters.getStatProjects;
            if (projects.length > 0) {
                this.$store.commit('clear_currentStatisticProject', projects[0].id);
                this.selected = projects[0].id;
                this.selectedProjectName = projects[0].name;
                this.selectedProject = projects[0].id;
                this._createInitData(projects[0].statistic.defaultDays);
                //this.$store.commit('clear_currentStatisticProject', projects[0].id);
                this.$store.commit('set_currentStatisticProject', projects[0].id);
                this.$store.dispatch('StartProjectStatistic', { projectId: projects[0].id, datefrom: this.dateOnFormFrom, dateto: this.dateOnFormTo });
            }
            else
                this._createInitData(1);
        },
        chartUpdated: function () {
            eventVue.$emit('centerModal', this);
        },
        changeDataByType: function (e) {
            this.$store.commit('changeDataInMixedStatisticByType', { type: +e.target.value, projectId: this.selectedProject, statId: +e.target.attributes['data-statid'].value });  
        }
    },
    beforeUpdate: function () {
        if (this.showw && !this.shown) {
                eventVue.$emit('centerModal', this);          
        }
    },
}

var barChart = Vue.component('bar-chart', {
    extends: VueChartJs.Bar,
    mixins: [VueChartJs.mixins.reactiveProp/*, VueChartJs.mixins.reactiveData*/],
    props: ['chartdata', 'options'],
    data() {
        return {
            started: false
        }
    },
    watch: {
        chartdata: function (newData, oldData) {   
            setTimeout(function () {               
                this.renderChart(newData, this.getBarOption(this.options));
                this.chartUpdated();
            }.bind(this), 100);
        }
    },
    mounted() {     
        eventVue.$on('updateChart', () => {
            this.startChart();            
        });
        this.startChart();                
    },
    methods: {
        chartUpdated: function () {
            eventVue.$emit('centerModal', { $el: document.getElementsByClassName('modal fade in')[0] });
        },
        getBarOption: function (options) {
            var opt = options;
            opt.plugins = {
                    labels: {
                        render: 'value',
                        fontColor: 'black',
                        position: 'border',
                        outsidePadding: 4,
                        shadowColor: 'rgba(255,0,0,0.75)'
                    }
                }            
            return opt;
        },
        startChart: function () {
            this.renderChart(this.chartdata, this.getBarOption(this.options));
            this.chartUpdated();
        },
    }
});

var pieChart = Vue.component('pie-chart', {
    extends: VueChartJs.Pie,
    mixins: [/*VueChartJs.mixins.reactiveProp, */VueChartJs.mixins.reactiveData],
    props: ['piechartdata', 'options'],
    data() {
        return {
        }
    },
    watch: {
        piechartdata: function (newData, oldData) {
            if (newData && newData.labels.length > 0) {
                setTimeout(function () {                    
                    this.renderChart(newData, this.getPieOption(this.options));
                    this.chartUpdated();
                }.bind(this), 100);
            }
        }
    },
    mounted() {        
        eventVue.$on('updateChart', () => {
            this.startChart();
            //this.chartUpdated();
        });
        this.startChart();
    },
    methods: {
        chartUpdated: function () {
            eventVue.$emit('centerModal', { $el: document.getElementsByClassName('modal fade in')[0] });
        },
        startChart: function () {
            this.renderChart(this.piechartdata, this.getPieOption(this.options));
            this.chartUpdated();
        },
        getPieOption: function (options) {
            var opt = options;
            opt.responsive = true;
            opt.plugins = {
                datalabels: {
                    render: 'percentage',
                    fontColor: function (data) {
                        var rgb = data.dataset.backgroundColor[data.index].replace('rgba(', '').replace(')', '').split(',');
                        var threshold = 140;
                        var luminance =  (+rgb[0] * 0.299) + (+rgb[1] * 0.587) + (+rgb[2] *0.114);
                        return luminance > threshold ? 'black' : 'white';
                    },
                    textShadowColor: 'white',
                    textShadowBlur: 10,
                    precision: 2,
                    formatter: function (value, context) {
                        return value + '%';
                    }
                },
                tooltip: {
                    callbacks: {
                        label: (context) => {
                            let label =  '';
                                if (context.label && context.label.length > 0)
                                    label += context.label;
                            return label;
                        },
                    },
                }
            };
            return opt;
        }        
    }
});

var mixedChart = Vue.component('mixed-chart', {
    extends: VueChartJs.Bar,
    mixins: [VueChartJs.mixins.reactiveProp/*, VueChartJs.mixins.reactiveData*/],
    props: ['mmixedChartData', 'options'],
    data() {
        return {
        }
    },
    watch: {
        mmixedChartData: function (newData, oldData) {
            if (newData && newData.labels.length > 0) {
                setTimeout(function () {
                    this.renderChart(newData, this.getMixedOption(this.options, newData));
                    this.chartUpdated();
                }.bind(this), 100);
            }
        }
    },
    mounted() {
        //this.renderChart(this.piechartdata, this.options);
        eventVue.$on('updateMixedChart', () => {
            this.startChart();
            //this.chartUpdated();
        });
        this.startChart();
    },
    methods: {
        chartUpdated: function () {
            eventVue.$emit('centerModal', { $el: document.getElementsByClassName('modal fade in')[0] });
        },
        startChart: function () {
            if (this.mmixedChartData && this.mmixedChartData.datasets[0].data && this.mmixedChartData.datasets[0].data.length > 0) {
                this.renderChart(this.mmixedChartData, this.getMixedOption(this.options, this.mmixedChartData));
                this.chartUpdated();
            }
        },
        getMixedOption: function (options, data) {
            var opt = options;
            opt.responsive = true;
            opt.plugins = {
                labels: {
                    render: 'value',
                    fontColor: 'black',
                    fontColor: 'rgba(0,0,0, 0.001)',
                    position: 'outside',
                    outsidePadding: 2,
                    shadowColor: 'rgba(255,0,0,0.75)',
                    textMargin: 2,
                }
            };
           
            opt.tooltips = { mode: 'label' };
            opt.scales = {
                xAxes: [
                    {
                        stacked: true,
                        ticks: {
                            autoSkip: false,
                            beginAtZero: true,
                        }
                    }],
                yAxes: [{
                        id: 'A',
                        position: 'left',                        
                        ticks: {
                            min: 0,
                        },
                        gridLines: {
                            display: false
                        },
                    }, {
                        id: 'B',
                        type: 'linear',
                        position: 'right',
                        ticks: {                            
                            min: 0
                        },
                        gridLines: {
                            display: false
                        },
                    }]
            };    
            return opt;
        }
    }
});

var mixedTypesChart = Vue.component('mixedtypes-chart', {
    extends: VueChartJs.Bar,
    mixins: [VueChartJs.mixins.reactiveProp/*, VueChartJs.mixins.reactiveData*/],
    props: ['mmixedTypesChartData', 'options'],
    data() {
        return {
        }
    },
    watch: {
        mmixedTypesChartData: function (newData, oldData) {
            if (newData && newData.labels.length > 0) {
                setTimeout(function () {
                    this.renderChart(newData, this.getMixedOption(this.options, newData));
                    this.chartUpdated();
                }.bind(this), 100);
            }
        }
    },
    mounted() {
        //this.renderChart(this.piechartdata, this.options);
        eventVue.$on('updateMixedTypeChart', () => {
            this.startChart();
            //this.chartUpdated();
        });
        this.startChart();
    },
    methods: {
        chartUpdated: function () {
            setTimeout(function () {
                eventVue.$emit('centerModal', { $el: document.getElementsByClassName('modal fade in')[0] });
            }.bind(this), 100);
        },
        startChart: function () {
            if (this.mmixedTypesChartData && this.mmixedTypesChartData.datasets[0].data && this.mmixedTypesChartData.datasets[0].data.length > 0) {
                this.renderChart(this.mmixedTypesChartData, this.getMixedOption(this.options, this.mmixedTypesChartData));
                this.chartUpdated();
            }
        },
        getMixedOption: function (options, data) {
            var opt = options;
            opt.responsive = true;
            opt.plugins = {
                labels: {
                    render: 'value',
                    fontColor: 'rgba(0,0,0, 0.001)',
                    position: `outside`,
                    overlap: false,
                    outsidePadding: 10,
                    //shadowColor: 'rgba(255,0,0,0.75)',
                    textMargin: 4,

                }
            };

            opt.tooltips = { mode: 'label' };
            opt.scales = {
                xAxes: [
                    {
                        stacked: true,
                        ticks: {
                            autoSkip: false,
                            beginAtZero: true,
                        }
                    }],
                yAxes: [{
                    id: 'A',
                    position: 'left',
                    ticks: {
                        min: 0
                    },
                    gridLines: {
                        display: false
                    },
                }, {
                    id: 'B',
                    type: 'linear',
                    position: 'right',
                    ticks: {
                        min: 0
                    },
                    gridLines: {
                        display: false
                    },
                }]
            };
            return opt;
        }
    }
});

var stikedBarChart = Vue.component('staked-chart', {
    extends: VueChartJs.Bar,
    mixins: [VueChartJs.mixins.reactiveProp/*, VueChartJs.mixins.reactiveData*/],
    props: ['mmixedTypesChartData', 'options'],
    data() {
        return {
        }
    },
    watch: {
        mmixedTypesChartData: function (newData, oldData) {
            if (newData && newData.labels.length > 0) {
                setTimeout(function () {
                    this.renderChart(newData, this.getMixedOption(this.options, newData));
                    this.chartUpdated();
                }.bind(this), 100);
            }
        }
    },
    mounted() {
        //this.renderChart(this.piechartdata, this.options);
        eventVue.$on('updateChart', () => {
            this.startChart();
            //this.chartUpdated();
        });
        this.startChart();
    },
    methods: {
        chartUpdated: function () {
            setTimeout(function () {
                eventVue.$emit('centerModal', { $el: document.getElementsByClassName('modal fade in')[0] });
            }.bind(this), 100);
        },
        startChart: function () {
            if (this.mmixedTypesChartData && this.mmixedTypesChartData.datasets[0].data /*&& this.mmixedTypesChartData.datasets[0].data.length > 0*/) {
                this.renderChart(this.mmixedTypesChartData, this.getMixedOption(this.options, this.mmixedTypesChartData));
                this.chartUpdated();
            }
        },
        getMixedOption: function (options, data) {
            var opt = options;
            opt.responsive = true;
            opt.plugins = {
                ChartDataLabels: {
                    render: 'value',
                    color: 'rgba(0,0,0, 0.001)',
                    position: `outside`,
                    overlap: false,
                    outsidePadding: 10,
                    //textShadowColor: 'rgba(255,0,0,0.75)',
                    textMargin: 4,
                    textShadowColor: 'white',
                    textShadowBlur: 10,
                }
            };
            opt.tooltips = { mode: 'label' };
            opt.scales = {
                x: {
                    stacked: true,
                },
                y: {
                    stacked: true
                }
            };
            return opt;
        }
    }
});
//rasters-----------------------------
const basicComponent = {
    template: '<div class="basicList-container">\
                <div v-if="showBasicButton && showTHIS" class="basicListButton toolbar-items" @click="toggleBasicList" @mouseover="showRasterList"><a><span aria-hidden="true" title="Підоснови" class="glyphicon "><img src="/opendataportal/Images/layer_white_plus.png"/></span></a></div>\
                <div v-if= "showBasicsList && showTHIS" class= "basicList" v-bind:class="{ showingBasicsList : showBasicsList }" >\
                   <ul>\
                    <li v-for="item in basicList" :data-id="item.id" @click="clickOnBasicList" class="basicListItem">{{item.name}}</li>\
                   </ul>\
               </div>\
               </div>',
    data: function () {
        return {
            showBasicsList: false,
            currentBasicID: 0,
            showTHIS: false //убираем пока вообще
        }
    },
    computed: {
        showBasicButton() {
            var res = this.$store.getters.getUser.roles.InformantsPlus || this.$store.getters.getUser.roles.Moderators || this.$store.getters.getUser.roles.Admins;
            if (!res) {
                this.changeBasic(0);
                this.closeRasterList();
            }
            return res;
        },
        basicList() {
            return this.$store.getters.getBasics;
        },
        getUser() {
            return store.getters.getUser;
        }
    },
    methods: {
        toggleBasicList: function () {
            if (window.innerWidth < 768)
                this.showBasicsList = !this.showBasicsList;
        },
        clickOnBasicList: function (e) {
            var itemId = +e.currentTarget.attributes["data-id"].value;
            this.changeBasic(itemId);            
            this.closeRasterList();
        },
        mouseoutBasicList: function (e) {
            console.log('mouseoutBasicList');
            e.stopPropagation();
            this.toggleBasicList();
        },
        mousemoveBasicList: function (e) {
            console.log('mousemoveBasicList');
            e.stopPropagation();
        },
        closeRasterList: function () {
            this.showBasicsList = false;
        },
        showRasterList: function () {
            if (window.innerWidth > 768)
                this.showBasicsList = true;
        },
        rasterNameMouseOut: function () {
        },
        changeBasic: function (basicId) {
            this.currentBasicID = basicId;
            eventVue.$emit('changeBasic', basicId);
        },
        clearSelectBasicList: function () {
            var el = document.querySelector('.basicListItem');
            if (el)
                el.classList.remove('basicList-selected');
        },
        selectBasicListItem: function () {
            var el = document.querySelector('.basicListItem[data-id="' + this.currentBasicID + '"]');
            if (el) {
                this.clearSelectBasicList();
                el.classList.add('basicList-selected');
            }
        }
    },
    updated: function () {
        this.selectBasicListItem();
        //if (window.innerWidth < 768)
        //    this.$el.querySelector('.basicListButton').removeEventListener('mouseover', this.showRasterList);
    }
}
//Модули-------------------------------
//главный модуль
var ODP = new Vue({
    el: '#app',
    store, 
    template: `<div @keydown.ctrl.shift="handleCtrlShift">
                <spinner-comp ref="spinner"></spinner-comp>
                <search-comp ref="searcher"></search-comp>
                <maptoolbar-comp ref="maptoolbar"></maptoolbar-comp>
                <toc-comp ref="toc"></toc-comp>
                <layer-comp v-if="!mobile" ref="layers"></layer-comp>
                <layer-comp_mobile v-if="mobile" ref="layers"></layer-comp_mobile>
                <map-comp ref="mapp" @updateGoogleData="updateGoogleData"></map-comp>
                <login-comp ref="loginn"></login-comp>
                <register-comp ref="registerr"></register-comp>
                <forgotPassword-comp ref="forgott"></forgotPassword-comp>
                <feedback-comp ref="feedbackk"></feedback-comp>
                <sms-comp ref="smss"></sms-comp>
                <resetPassword-comp ref="respsww"></resetPassword-comp>
                <legend-comp ref="legendd"></legend-comp>
                <link-comp ref="linkss"></link-comp>
                <statistic-comp ref="statisticc"></statistic-comp>
                <basic-comp ref="basics"></basic-comp>
                <dsns-comp ref="dsnsC"
                    @showLayerDataInMap="showDSNSLayerDataInMap"
                ></dsns-comp>                

                            <!--<identityPanel-comp ref="iPanel"></identityPanel-comp>-->
                
                </div>`,
    computed: {
        getUser() {
            return store.getters.getUser;
        },
        getVisibileLayers() {
            return store.getters.getVisibileLayers;
        },
    },
    data: function () {
        return {
            mobile: false,
            bsInterval:null,
        }
    },
    components: {        
        'spinner-comp': spinnerComponent,
        'search-comp': searchComponent,
        'maptoolbar-comp': maptoolbarComponent,
        //'listAreaAddresses-comp': listAreaAddresses,
        'toc-comp': tocComponent,
        'layer-comp': layersComponent,
        'layer-comp_mobile': layersComponent_mobile,
        'login-comp': loginComponent,
        'register-comp': registerComponent,
        'forgotPassword-comp': forgotPasswordComponent,
        'feedback-comp': feedbackComponent,
        'sms-comp': smsComponent,
        'resetPassword-comp': resetPasswordComponent,
        'legend-comp': legendComponent,
        'link-comp': linksComponent,
        'statistic-comp': statisticComponent,
        'map-comp': mapComponent,
        'basic-comp': basicComponent,
        'dsns-comp':ODP_DSNS,
        //'identify_component': APP_IDENTIFY,
        //'identityPanel-comp': identityPanelComponent
    },
    methods: {
        clickApp: function () {
            eventVue.$emit('hideCollapse');
        },
        updateGoogleData: function (e) {
            this.getVisibileLayers.forEach(function (vlItem, index, arr){
                if (vlItem.checkUpdate)
                    this.$store.dispatch(vlItem.checkUpdate.method, { url: vlItem.checkUpdate.url});                
            }.bind(this));
        },
        showDSNSLayerDataInMap: function (data) {
            this.$store.commit("set_expression_toLayer", data);
            setTimeout(function () {
                let currentLayer = this.getVisibileLayers.find(l => l.id === data.layer.id);
                if (currentLayer) {
                    this.$refs.mapp.setWhereToLayer(data);
                    this.$refs.mapp.updateIT();
                }

                else {
                    this.$store.commit('set_onOffLayer', data.layer.id);
                    eventVue.$emit('selectLayer', data.layer.id);
                    eventVue.$emit('clearSelectioHidePopup');
                }
                    //this.$refs.mapp.createLayer(data.layer);
            }.bind(this), 500);

        },
        handleCtrlShift: function () {
            this.$store.commit('set_maptoolbarButtonClick', "'coordinates'");
            this.$emit('maptoolbar_buttonClick', 'coordinates');
        }
    },
    //beforeMount: function () {
    //    var dataKey = document.getElementsByTagName('body')[0].attributes["data-key"].value;
    //    if (this.getUser.FullName == "Вхід" && !sessionStorage.getItem('odp_user') && this.getUser.loginView && (window.location.href.toLowerCase()).indexOf('house') < 0 && (window.location.href.toLowerCase()).indexOf('account') < 0) {
    //        if (dataKey != '')
    //            sessionStorage.odp_data_key = dataKey;
    //        window.location = '/opendataportal/Account/Login';
    //    }
    //},
    mounted: function () {
        window.innerWidth < 768 ? this.mobile = true : this.mobile = false;
        //if (@ViewBag.VisibleProjectId)
        //    this.VisibleProjectId = @ViewBag.VisibleProjectId;
        if ((window.location.href.toLowerCase()).indexOf('house') < 0 && (window.location.href.toLowerCase()).indexOf('account') < 0) {
            require([
                "esri/map",
                "dojo/parser",
                "dojo/promise/all",
                "dojo/dom",
                "dojo/on",
                "esri/dijit/Measurement",
                "esri/dijit/Legend",
                "esri/dijit/Print",
                "esri/toolbars/navigation",
                "esri/dijit/BasemapLayer",
                "esri/layers/ArcGISTiledMapServiceLayer",
                "esri/layers/ArcGISDynamicMapServiceLayer",
                "esri/layers/FeatureLayer",
                "esri/layers/GraphicsLayer",
                "esri/layers/ImageParameters",
                "esri/dijit/PopupTemplate",
                "esri/layers/WMSLayer",
                "esri/layers/WMSLayerInfo",
                "esri/layers/ImageParameters",
                "esri/tasks/FeatureSet",
                "esri/tasks/GeometryService",
                "esri/geometry/Extent",
                "esri/geometry/Point",
                "esri/geometry/Circle",
                "esri/symbols/SimpleLineSymbol",
                "esri/symbols/SimpleFillSymbol",
                "esri/symbols/SimpleMarkerSymbol",
                "esri/symbols/PictureMarkerSymbol",
                "esri/symbols/TextSymbol",
                "esri/symbols/Font",
                "esri/renderers/SimpleRenderer",
                "esri/renderers/UniqueValueRenderer",
                "esri/renderers/ClassBreaksRenderer",
                "esri/layers/LabelLayer",
                "esri/layers/LabelClass",
                "esri/units",
                "esri/Color",
                "esri/graphic",
                "esri/graphicsUtils",
                "esri/geometry/screenUtils",
                "esri/tasks/query",
                "esri/tasks/QueryTask",
                "esri/tasks/IdentifyTask",
                "esri/tasks/IdentifyParameters",
                "esri/InfoTemplate",
                "esri/geometry/scaleUtils",
                "extras/clusterfeaturelayerr",
                // "extras/ClusterFeatureLayer",
                "extras/ClusterLayer",
               
                "esri/lang",
                "esri/request",
                "dojo/number",
                "dojo/dom-style",
                "dijit/TooltipDialog",
                "dijit/popup",
                "dojo/dom-construct",
                //"dojo/dom-class",
                //"dojo/_base/json",
                "dojo/_base/array",
                "esri/dijit/InfoWindow",
                "esri/config",
                "esri/tasks/FindTask",
                "esri/tasks/FindParameters",
                "dojo/domReady!"
            ], function (Map, parser, all, dom, on, Measurement, Legend, Print, Navigation, BasemapLayer, Tiled, ArcGISDynamicMapServiceLayer, FeatureLayer, GraphicsLayer, ImageParameters, PopupTemplate, WMSLayer, WMSLayerInfo, ImageParameters, FeatureSet, GeometryService, Extent, Point, Circle, SimpleLineSymbol, SimpleFillSymbol, SimpleMarkerSymbol, PictureMarkerSymbol, TextSymbol, Font, SimpleRenderer, UniqueValueRenderer, ClassBreaksRenderer,
                LabelLayer, LabelClass, Units, Color, Graphic, graphicsUtils, screenUtils, Query, QueryTask, IdentifyTask, IdentifyParameters, InfoTemplate, scaleUtils, ClusterLayer, ClusterLayer2, esriLang, esriRequest, number, domStyle, TooltipDialog, dijitPopup, /*domClass,
            dojoJson,*/  domConstruct, arrayUtils, InfoWindow, esriConfig, FindTask, FindParameters) {
                    //esriRequest,
                    parser.parse();
                    esriConfig.defaults.io.proxyUrl = "/proxy/";
                    esriConfig.defaults.io.alwaysUseProxy = false;
                    esriConfig.defaults.geometryService = new GeometryService('https://smart.khmr.gov.ua/arcgis/rest/services/Utilities/Geometry/GeometryServer');

                    //esri moduls--
                    var aw = {};
                    aw.Map = Map,
                        aw.dom = dom,
                        aw.UniqueValueRenderer = UniqueValueRenderer,
                        aw.SimpleRenderer = SimpleRenderer,
                        aw.SimpleFillSymbol = SimpleFillSymbol,
                        aw.SimpleLineSymbol = SimpleLineSymbol,
                        aw.Color = Color,
                        aw.ClassBreaksRenderer = ClassBreaksRenderer,
                        aw.Query = Query,
                        aw.Extent = Extent,
                        aw.Graphic = Graphic,
                        aw.esriLang = esriLang,
                        aw.LabelClass = LabelClass,
                        aw.FindTask = FindTask,
                        aw.FindParameters = FindParameters,
                        aw.SimpleMarkerSymbol = SimpleMarkerSymbol,
                        aw.PictureMarkerSymbol = PictureMarkerSymbol,
                        aw.ArcGISDynamicMapServiceLayer = ArcGISDynamicMapServiceLayer,
                        aw.FeatureLayer = FeatureLayer,
                        aw.GraphicsLayer = GraphicsLayer,
                        aw.ImageParameters = ImageParameters,
                        aw.PopupTemplate = PopupTemplate,
                        aw.ImageParameters = ImageParameters,
                        aw.FeatureSet = FeatureSet,
                        aw.BasemapLayer = BasemapLayer,
                        aw.Tiled = Tiled,
                        aw.Point = Point,
                        aw.Circle = Circle,
                        aw.Navigation = Navigation,
                        aw.on = on,
                        aw.Measurement = Measurement,
                        aw.Legend = Legend,
                        aw.Print = Print,
                        aw.GeometryService = GeometryService,
                        aw.Units = Units,
                        aw.esriConfig = esriConfig,
                        aw.parser = parser,
                        aw.dijitPopup = dijitPopup,
                        aw.domConstruct = domConstruct,
                        aw.QueryTask = QueryTask,
                        aw.all = all,
                        aw.arrayUtils = arrayUtils,
                        aw.graphicsUtils = graphicsUtils,
                        aw.screenUtils = screenUtils,
                        aw.IdentifyTask = IdentifyTask,
                        aw.IdentifyParameters = IdentifyParameters,
                        aw.InfoTemplate = InfoTemplate,
                        aw.scaleUtils = scaleUtils,
                        aw.ClusterLayer = ClusterLayer,
                        aw.ClusterLayer2 = ClusterLayer2,
                        aw.esriRequest = esriRequest,
                        aw.InfoWindow = InfoWindow,
                        aw.WMSLayer = WMSLayer,
                        aw.WMSLayerInfo = WMSLayerInfo,
                        aw.TextSymbol = TextSymbol,
                        aw.Font = Font

                        ;
                    //init components ==========================================
                    ODP.$refs.spinner.initSpinner();
                    ODP.$refs.searcher.initSearcher();
                    ODP.$refs.maptoolbar.initMapTollBar();
                    ODP.$refs.toc.initToc();
                    ODP.$refs.mapp.initMap(aw);
                    //ODP.$refs.loginn._gplInit();

                    //events====================================================
                    //maptoolbar
                    eventVue.$on('maptoolbar_buttonClick', (type) => {
                        ODP.$refs.mapp.setNavToolbarAction(type);
                    });

                    //idetify list
                    ODP.$on('showListArea', function () {
                        ODP.$refs.listArea.toggleVisibilityListArea();
                    });
                    //feedback
                    eventVue.$on('maptoolbar_feedbackBtnClick', () => {
                        ODP.$refs.feedbackk.openModal(ODP.$store.getters.getUser);
                    });

                    eventVue.$on('closefeedbackForm', (type) => {
                        ODP.$refs.feedbackk.closeModal();
                    });
                    eventVue.$on('updateCaptchaOnFeedbackForm', () => {
                        ODP.$refs.feedbackk.updateCaptcha();
                    });

                    //statistic
                    ODP.$store.commit('add_allProjectsToStat');
                    eventVue.$on('maptoolbar_statisticBtnClick', () => {
                        ODP.$refs.statisticc.openModal();
                    });


                    //address register
                    eventVue.$on('clearAutocomplette', () => {
                        ODP.$refs.searcher.clearSearchInput();
                         ODP.$refs.mapp.clearCraphicLayer();
                        //ODP.$store.commit('clearSearchResult');
                });

                    //statistic
                    eventVue.$on('maptoolbar_dsnstablesBtnClick', () => {
                        ODP.$refs.dsnsC.openModal();
                    });

                    eventVue.$on('maptoolbar_dsnstablescancelfiltersBtnClick', () => {
                        ODP.$refs.dsnsC.cancelFiltersInAllTables();
                    });

                    //map

                    eventVue.$on('selectProject', () => {
                        ODP.$refs.mapp.updateProject();
                    });
                    //eventVue.$on('selectProjectLayers', (projectId) => {
                    //    ODP.$refs.mapp.updateProjectLayers(projectId);
                    //});                    
                    eventVue.$on('selectLayer', (layerId) => {
                        ODP.$refs.mapp.updateLayerOnMap(layerId);
                    });
                    eventVue.$on('buildLayer', (properties) => {
                        ODP.$refs.mapp.buildLayer(properties);
                    });
                    eventVue.$on('searcherInputIsCleared', () => {
                        ODP.$refs.mapp.clearCraphicLayer();
                    });
                    eventVue.$on('mapOnClick', (e) => {
                        //ODP.$refs.searcher.clearSearchInput();
                        ODP.$refs.mapp.clickMapExecute(e);
                        ODP.$refs.basics.closeRasterList();
                    });
                    eventVue.$on('set_layerVisibility', (layerId) => {
                        ODP.$refs.mapp.setLayerVisibility(layerId);
                    });
                    eventVue.$on('set_mapListLayers', (value) => {
                        ODP.$refs.mapp.reorderLayers(value);
                    });
                    eventVue.$on('removeAllLayers', (value) => {
                        ODP.$refs.mapp.hideAllProjects();
                    });
                    eventVue.$on('clearSelectioHidePopup', (value) => {
                        ODP.$refs.mapp.clearSelectioHidePopup();
                    });
                    eventVue.$on('startGeolocation', () => {
                        ODP.$refs.mapp.startGeolocation();
                    });
                    eventVue.$on('stopGeolocation', () => {
                        ODP.$refs.mapp.stopGeolocation();
                    });
                    eventVue.$on('showLocation', (data) => {
                        ODP.$refs.mapp.showLocation(data);
                    });
                    eventVue.$on('showInfoWindow', (data) => {
                        //responce: response.data, prop: response.config.prop
                        ODP.$refs.mapp.showInfoWindow(data.responce, data.prop.prop);
                    });
                    eventVue.$on('changeBasic', (basicId) => {
                        if (basicId >= 0)
                            ODP.$refs.mapp.changeBasic(basicId);
                    });
                    eventVue.$on('updateRasters', () => {
                        ODP.$refs.mapp.updateRasters();
                    });
                eventVue.$on('getAddressesIdsListByCurrentObject', (data) => {
                    if (data.res.length > 0) {
                        var outArr = [];
                        data.res.forEach(function (drItem) {
                            if (drItem.length > 0) {
                                outArr.push(drItem);
                            }
                        }.bind(this));
                            //if (!isNaN(data.id) && data.res[0][0].feature && data.res[0][0].feature.attributes.institutionIdentifier_)
                            //    store.dispatch('GetAddressesByPrimarySchool', JSON.stringify({ ajax: store.getters.getAjaxUrlByName('GetAddressesByPrimarySchool'), schoolGuid: data.id, res: data.res }));
                            //else if (!isNaN(data.id) && data.res[0][0].feature && data.res[0][0].feature.attributes.inData_ADD)
                            //    store.dispatch('GetAddressesByBombShelter', JSON.stringify({ ajax: store.getters.getAjaxUrlByName('GetAddressesByBombShelter'), bombGuid: data.id, res: data.res, identity: data.identity }));
                        if (!isNaN(data.id) && outArr[0][0].feature && outArr[0][0].feature.attributes.institutionIdentifier_)
                            store.dispatch('GetAddressesByPrimarySchool', JSON.stringify({ ajax: store.getters.getAjaxUrlByName('GetAddressesByPrimarySchool'), schoolGuid: data.id, res: outArr }));
                        else if (!isNaN(data.id) && outArr[0][0].feature && outArr[0][0].feature.attributes.inData_ADD)
                            store.dispatch('GetAddressesByBombShelter', JSON.stringify({ ajax: store.getters.getAjaxUrlByName('GetAddressesByBombShelter'), bombGuid: data.id, res: outArr, identity: data.identity }));
                        else if (!isNaN(data.id) && outArr[0][0].feature && outArr[0][0].feature.attributes.OBJECTID)
                            store.dispatch('GetAddressesByHospital', JSON.stringify({ ajax: store.getters.getAjaxUrlByName('GetAddressesByHospital'), medGuid: data.id, res: outArr, identity: data.identity }));
                        }
                    });
                    eventVue.$on('getAddressObjectsGeometriesByAddressObjectsList', (data) => {
                        ODP.$refs.mapp.getAddressObjectsGeometriesByAddressObjectsList(data);
                    });
                    eventVue.$on('showAddressesObjectsOnMap', (ID) => {
                        ODP.$refs.mapp.showAddressesObjectsOnMap(ID);
                    });
                    eventVue.$on('showAddressesObjectsList', (data) => {
                        ODP.$refs.mapp.showAddressesObjectsListPanel(null , data.ID, data.type);
                    });
                eventVue.$on('getServiceObjectOnMap', (data) => {

                    //if (data.bindToServices && data.bindToServices.feature) {
                    //    ODP.$refs.mapp.showServiceObjectOnMap({
                    //        prop: { bindToServices: data.bindToServices },
                    //        response: [{ GUID: data.bindToServices.feature.attributes[data.bindToServices.field] }]                            
                    //    });
                    //    store.dispatch('GetServiceObjects', JSON.stringify(data));
                    //}
                    //else 
                    if (data.url)
                        store.dispatch('GetServiceObjects', JSON.stringify(data));
                });

                    eventVue.$on('showServiceObject', (data) => {
                        ODP.$refs.mapp.showServiceObjectOnMap(data);
                });
                eventVue.$on('addressesNotFound', () => {
                    ODP.$refs.mapp.showAddressesNotFound(true);
                });

                eventVue.$on('repositionInfoWindow', () => {
                    ODP.$refs.mapp.repositionInfoWindow();
                });
                    //projects form
                    eventVue.$on('openProjectWindow', (e) => {
                        ODP.$refs.layers.openModal();
                    });
                    eventVue.$on('toggleLayer', (e) => {
                        ODP.$refs.layers.clickOnCheckbox(e);
                    });

                    //center modals
                    eventVue.$on('centerModal', (e) => {
                        eventVue.centerModal(e);
                    });
                    eventVue.$on('startCloseModal', (e) => {
                        eventVue.startCloseModal(e);
                    });
                    eventVue.$on('undoStartCloseModal', (e) => {
                        eventVue.undoCloseModal(e);
                    });

                    //login form
                    eventVue.$on('loginLinkOnClick', (e) => {
                        ODP.$refs.loginn.openModal();
                    });
                    eventVue.$on('closeLoginForm', (e) => {
                        ODP.$refs.loginn.closeModal();
                    });
                    eventVue.$on('bakToLoginForm', (e) => {
                        ODP.$refs.loginn.email = e;
                        ODP.$refs.loginn.openModal();
                    });

                    //register form
                    eventVue.$on('openRegister', (e) => {
                        ODP.$refs.registerr.email = e;
                        ODP.$refs.registerr.openModal();
                    });
                    eventVue.$on('closeRegisterForm', (e) => {
                        ODP.$refs.registerr.closeModal();
                    });

                    //forgot password form
                    eventVue.$on('openForgotPassword', (e) => {
                        ODP.$refs.forgott.email = e;
                        ODP.$refs.forgott.openModal();
                    });
                    eventVue.$on('closeForgotPasswordForm', (e) => {
                        ODP.$refs.forgott.closeModal();
                    });

                    //sms form
                    eventVue.$on('openSmsForm', (data) => {
                        ODP.$refs.smss.openModal(data.phone, data.isForgot);
                    });
                    eventVue.$on('hideSmsForm', () => {
                        ODP.$refs.smss.closeModal();
                    });

                    //messenger
                    eventVue.$on('showSimpleMessage', (text) => {
                        eventVue.showSimpleMessage(text);
                    });

                    eventVue.$on('showErrorMessage', (errors) => {
                        eventVue.showErrorMessage(errors);
                    });

                    //reset password form
                    eventVue.$on('openResetPasswordForm', (data) => {
                        ODP.$refs.respsww.openModal(data.phone, data.code);
                    });
                    eventVue.$on('closeResetPasswordForm', () => {
                        ODP.$refs.respsww.closeModal();

                    });

                    //legend
                    eventVue.$on('initLegend', () => {
                        ODP.$refs.mapp.initLegend();
                    });


                    eventVue.$on('showLinks', () => {
                        ODP.$refs.linkss.openModal();
                    });
                    eventVue.$on('closeLinks', () => {
                        ODP.$refs.linkss.closeModal();
                    });

                    eventVue.$on('hideCollapse', () => {
                        eventVue.hideCollapseNavbar();
                    });

                    eventVue.$on('scaleToOne', () => {
                        eventVue.scaleToOne();
                    });

                    eventVue.initClearable();
                    //eventVue.showNotify();

                eventVue.$on('showMoreForBuilds', (AR_ID) => {
                    var ARIDS = [114681,117950],
                        key;
                    sessionStorage.setItem('smart_houses', +AR_ID);
 //                   sessionStorage.setItem('smart_houses', AR_ID);
                    window.open('/opendataportal/Houses', '_blank');
                    //ARIDS.forEach(function (aItem, index) {
                    //    if (aItem == AR_ID)
                    //        key = (index + 1);
                    //}.bind(this));

                    //if (key > 0)
                    //    window.open('/opendataportal/Houses/house' + key, '_blank');
                    });
                eventVue.$on('removeInfoWindowBtn', (type) => {
                    ODP.$refs.mapp.removeInfoWindowBtn(type);
                    });

                eventVue.$on('setHouseToView', (response) => {

                    if (response.data) {
                        //если у нас уже откріт попап и кнопка есть в доме
                        if (document.querySelector('#h_blob_' + response.data.OSBB_NOM))
                            document.querySelector('#h_blob_' + response.data.OSBB_NOM).style.display = 'block';
                        //обновляем темплейт
                        ODP.$refs.mapp.updateInfoTamplate(response.data.OSBB_NOM);
                    }
                });



                eventVue.$on('updateInfoTamplateOSBB', (data) => {

                    ODP.$refs.mapp.updateInfoTamplateOSBB(data);

                });
                eventVue.$on('updateInfoTamplateMonuments', (data) => {

                    ODP.$refs.mapp.updateInfoTamplateMonuments(data);

                });
                ;
               
                eventVue.$on('setServicesObjects', (data) => {
                    ODP.$refs.mapp.setServicesObjects(data);
                    //alert('setServicesObjects');
                });

                    setTimeout(function () {
                        var prjs = this.$store.getters.getAllProjects;
                        if (prjs && prjs.length > 0) {
                            var currentNumber = Math.floor(Math.random() * (prjs.length));
                            //console.log('currentNumber = ' + currentNumber);
                            if (prjs[currentNumber].notify)
                                eventVue.showNotify(prjs[currentNumber].notify.title, prjs[currentNumber].notify.content, 120000);
                        }
                    }.bind(ODP), 4000);

                    //START!!!!!!!!!!!!!!!===================================================
                var dataKey = document.getElementsByTagName('body')[0].attributes["data-key"].value;
                var dataStartbombsheltters = document.getElementsByTagName('body')[0].attributes["data-startbombsheltters"].value;
                var dataStartinvincibilitypoints = document.getElementsByTagName('body')[0].attributes["data-startinvincibilitypoints"].value;
                var startWaterDrinkPoints = document.getElementsByTagName('body')[0].attributes["data-startwaterdrinkpoints"].value;
                if (dataStartbombsheltters) {
                    this.bsInterval = setInterval(function () {
                        if (ODP.$refs.mapp.map.graphicsLayerIds.length > 0 || ODP.$refs.mapp.map.layerIds.length > 0) {
                            ODP.$store.commit('set_onOffLayer', 15);
                            eventVue.$emit('selectLayer', 15);
                            eventVue.$emit('clearSelectioHidePopup');
                            //2.clean history
                            var urri = window.location.toString();
                            if (urri.toLowerCase().indexOf("/home") > 0) {
                                var clean_uri = urri.substring(0, urri.indexOf("Home"));
                                window.history.replaceState({}, document.title, clean_uri);
                            }
                            //3.remove body parameter
                            document.getElementsByTagName('body')[0].setAttribute("data-startbombsheltters", "");
                            clearInterval(this.bsInterval);
                        }

                    }.bind(this), 100)
                    //1.add bombshelters to map

                }
                else if (dataStartinvincibilitypoints) {
                    this.bsInterval = setInterval(function () {
                        if (ODP.$refs.mapp.map.graphicsLayerIds.length > 0 || ODP.$refs.mapp.map.layerIds.length > 0) {
                            ODP.$store.commit('set_onOffLayer', 41);
                            eventVue.$emit('selectLayer', 41);
                            eventVue.$emit('clearSelectioHidePopup');
                            //2.clean history
                            var urri = window.location.toString();
                            if (urri.toLowerCase().indexOf("/home") > 0) {
                                var clean_uri = urri.substring(0, urri.indexOf("Home"));
                                window.history.replaceState({}, document.title, clean_uri);
                            }
                            //3.remove body parameter
                            document.getElementsByTagName('body')[0].setAttribute("data-startinvincibilitypoints", "");
                            clearInterval(this.bsInterval);
                        }
                    }.bind(this), 100)
                }
                else if (startWaterDrinkPoints) {
                    this.bsInterval = setInterval(function () {
                        if (ODP.$refs.mapp.map.graphicsLayerIds.length > 0 || ODP.$refs.mapp.map.layerIds.length > 0) {
                            ODP.$store.commit('set_onOffLayer', 45);
                            eventVue.$emit('selectLayer', 45);
                            eventVue.$emit('clearSelectioHidePopup');
                            //2.clean history
                            var urri = window.location.toString();
                            if (urri.toLowerCase().indexOf("/home") > 0) {
                                var clean_uri = urri.substring(0, urri.indexOf("Home"));
                                window.history.replaceState({}, document.title, clean_uri);
                            }
                            //3.remove body parameter
                            document.getElementsByTagName('body')[0].setAttribute("data-startwaterdrinkpoints", "");
                            clearInterval(this.bsInterval);
                        }
                    }.bind(this), 100)
                }
                else if (dataKey != "" && !ODP.getUser.loginView)
                    //open reset password form
                    ODP.$refs.respsww.openModal(null, dataKey);
                else
                    //open project form
                    ODP.$refs.layers.openModal();

                    //if (navigator.geolocation)
                    //    setTimeout(function () {
                    //        document.getElementById('geolocation').click();
                    //    }, 500);

                //if (ODP.getUser.loginView) {
                //    setTimeout(function () {
                //        ODP.$store.dispatch('getToken');
                //        ODP.$store.commit('startTokenTiks');
                //    }.bind(this), 500);

                //    }
                });
        }
    }    
});


