var map = null;
var geocoder = null;
//var unique_bank_list = [];
//var unique_bank_list_colors = [];
// Создает базовый стиль для значка банка
var baseStyle = new YMaps.Style();
baseStyle.iconStyle = new YMaps.IconStyle();
baseStyle.iconStyle.offset = new YMaps.Point(-12, -28);
baseStyle.iconStyle.size = new YMaps.Point(27, 32);


var EXCHANGES = false;
// Задает опции метки для Обменных пунктов.
var EXHANGE_POINT_OPTIONS = {
    draggable: false,
    hasBalloon: true,
    hintOptions: {
        maxWidth: 100,
        offset: new YMaps.Point(5, 5)
    },
    style: 'default#bankIcon'
};

function initialize(cityId) {
    map = new YMaps.Map(document.getElementById("map_canvas"));
    setProgress(10);
    if (cityId == 2 || cityId == 10) // Astana
        map.setCenter(new YMaps.GeoPoint(71.480124, 51.151817), 17);   // Площадь республики 76.944333,43.238168
    else // Almata
        map.setCenter(new YMaps.GeoPoint(76.9235137291253, 43.2404977392819), 11);   // Площадь республики 76.944333,43.238168

    map.addControl(new YMaps.ScaleLine());
    map.addControl(new YMaps.TypeControl());
    map.addControl(new YMaps.Zoom());
    map.addControl(new YMaps.MiniMap());

    //map.enableScrollZoom();
    map.enableRightButtonMagnifier();

    setProgress(20);
    window.onunload = function() {
        map.destructor();
    };
}

function xload() {
    if (!EXCHANGES) {
        addStyles();
        fillOnMapLabels();
    }
    //    var start = (new Date()).getTime();
    addPoints();
    //    alert(" time: " + ((new Date()).getTime() - start))
    finishLoading();
}

function addStyles() {
    var length = unique_bank_list_ids.length;
    for (var i = 0; i < length; i++) {
        var bank_id = unique_bank_list_ids[i];
        if (bank_id !== undefined) {
            var markerStyle = "bank#" + bank_id;
            // Стиль значка конкретного банка наследует признаки базового стиля
            var styleBank = new YMaps.Style(baseStyle);
            styleBank.iconStyle = new YMaps.IconStyle();
            styleBank.iconStyle.href = unique_bank_list_icons[i];
            // Добавляет стиль в хранилище
            YMaps.Styles.add(markerStyle, styleBank);
        }
    }
}

function addPoints() {
    var progress = 50;
    var bounds = new YMaps.GeoCollectionBounds();
    var createBalloonFunction = createBalloon;
    var setProgressFunction = setProgress;
    var createStyledMarkerFunction = createStyledMarker;
    var createExchangeMarkerFunction = createExchangeMarker;
    var createMarkerFunction = createMarker;
    //    var mapAddOverlayFunction = map.addOverlay;
    //    var boundsAddFunction = bounds.add;
    var ml = markers.length;
    for (var i = 0; i < ml; i++) {
        var point = markers[i];
        if (point !== undefined) {
            var type = point[0];  // 1 = branch, 2 = bankomat, 3 = exchange, 4 = ibranch
            var lat = parseFloat(point[1]);
            var lng = parseFloat(point[2]);
            if (lat > 0 && lng > 0) {
                var marker;
                if (type == 1 || type == 2) {
                    marker = createStyledMarkerFunction(lat, lng, "bank#" + point[4]); // var bank_id = point[4];
                } else if (type == 3) {
                    marker = createExchangeMarkerFunction(lat, lng);
                } else {
                    marker = createMarkerFunction(lat, lng, 'red');
                }
                // добавляем на карту
                map.addOverlay(marker);
                bounds.add(marker.getGeoPoint());
                // Создаем балун
                createBalloonFunction(point, marker);

                if (i % 100 == 0 && progress < 90) {
                    progress += 5;
                    setProgressFunction(progress);
                }
            }
        }
    }
    map.setBounds(bounds);
}

function fillOnMapLabels() {
    var onMapHtml = "";
    var l = unique_bank_list.length;
    for (var c = 0; c < l; c++) {
        if (unique_bank_list_colors[c] !== undefined) {
            onMapHtml += '<li style="color: ' + unique_bank_list_colors[c] + ';">' + unique_bank_list[c] + '</li>';
        }
    }
    $('#onMap').html(onMapHtml);
}

function finishLoading() {
    hideProgressBar();
    //    $('#map_canvas').show();
}

function createBalloon(point, marker) {
    // branch 11 elements = [type, lat, lng, id, bank_id, name, bank_name, street, dom, xphone, xfiziki]
    // atm 11 elements = [type, lat, lng, id, bank_id, name, bank_name, street, dom, timeofwork, functions]
    // ibranch 11 elements = [type, lat, lng, id, bank_id, name, bank_name, street, dom, xphone, xfiziki]
    var type = point[0];  // 1 = branch, 2 = bankomat, 3 = exchange, 4 = ibranch
    var lat = parseFloat(point[1]);
    var lng = parseFloat(point[2]);
    var id = point[3];
    var bank_id = point[4];
    var name = point[5];
    var bank_name = point[6];
    var street = point[7];
    var dom = point[8];


    if (lat > 0 && lng > 0) {
        var html = "", title = "";
        if (type == 1) { // branch
            var xphone = point[9];
            var xfiziki = point[10];
            html += street + ", " + dom;
            if (xphone != "")
                html += "<br>Телефон: " + xphone;
            if (xfiziki != "")
                html += "<br>Режим работы:<br> " + xfiziki;

            title = bank_name + ", <a href='/cat/branch/" + id + "'>" + name + '</a>';

        } else if (type == 2) { // atm
            var timeofwork = point[9];
            var functions = point[10];
            html += street + ", " + dom;
            if (functions != "")
                html += "<br>Функции банкомата:: " + functions;
            if (timeofwork != "")
                html += "<br>Режим работы: " + timeofwork;

            html += "<br>Банк: <a href='/cat/bank/" + bank_id + "'>" + bank_name + "</a>";
            title = "Банкомат: <a href='/cat/bankomat/" + id + "'>" + name + "</a> банка " + bank_name;
        } else if (type == 3) { // exchange

            var rate = point[10];
            var time = point[9];
            html += street + ", " + dom;
            if (time != "")
                html += "<br><br><b>Режим работы:</b><br> <i>" + time + " </i>";

            if (rate != "" && rate.length > 0) {
                rate = rate.replace(/\[/g, '<').replace(/\]/g, '>');
                html += "<br><br>Курсы валют:<br> " + rate;
            }

            title = "<a href='/obmennyj/?id=" + id + "'>" + name + "</a>";
        } else if (type == 4) { // ibranch
            var xphone = point[9];
            var xfiziki = point[10];
            html += street + ", " + dom;
            if (xphone != "")
                html += "<br>Телефон: " + xphone;
            if (xfiziki != "")
                html += "<br>Режим работы:<br> " + xfiziki;

            title = bank_name + ", <a href='/cat/ibranch/" + id + "'>" + name + '</a>';
        }

        marker.name = title;
        html = "<div id=\"balloon_content\">" + html + "</div>";
        html += reportBugLink;
        marker.description = html;
    }
}

function createMarker(lat, lng, color) {
    var point = new YMaps.GeoPoint(lng, lat);

    // Задает опции метки и отображает метку на карте.
    var options = {
        draggable: false,
        hasBalloon: true,
        hintOptions: {
            maxWidth: 100,
            offset: new YMaps.Point(5, 5)
        },
        style: 'default#' + color + 'SmallPoint'
    };
    return new YMaps.Placemark(point, options);
}

function createExchangeMarker(lat, lng) {
    var point = new YMaps.GeoPoint(lng, lat);
    return new YMaps.Placemark(point, EXHANGE_POINT_OPTIONS);
}

function createStyledMarker(lat, lng, markerStyle) {
    var point = new YMaps.GeoPoint(lng, lat);

    // Задает опции метки и отображает метку на карте.
    var options = {
        draggable: false,
        hasBalloon: true,
        hintOptions: {
            maxWidth: 100,
            offset: new YMaps.Point(5, 5)
        },
        style: markerStyle
    };

    return new YMaps.Placemark(point, options);
}

var progresbarcontrol;
function setUpProgressBar() {
    progresbarcontrol = document.getElementById("progresbarcontrol");
    setProgress(5);
}
function hideProgressBar() {
    progresbarcontrol.style.display = 'none';
}
function setProgress(percent) {
  //  progresbarcontrol.innerHTML = "Идет загрузка " + percent + "%";
}

// ======================================================================
function installMapInner(cityId) {
    $(document).ready(function() {

     //   $('#map_canvas').show();
        setUpProgressBar();
        initialize(cityId);
        xload();
        var map_visible = $.cookie("map_visible3");
//        alert(map_visible);
        if (map_visible == '1') {
            showMap();
        } //else {showMap();}

    });
}
function installMap(cityId) {
    if (cityId == 1 || cityId == 2) {
        installMapInner(cityId);
    }
}

function installMapForExchange(cityId) {
    if (cityId == 9 || cityId == 10) {
        EXCHANGES = true;
        installMapInner(cityId);
    }
}

function hideMap() {
    $('#map_canvas').hide();
    $('#legend-map').hide();
    $('#progresbarcontrol').hide();

    $('#hideMap').html('<a href="javascript:void(0);" onclick="showMap();" class="close">Показать карту</a>');
    $.cookie("map_visible3", null, {expires: -1, path: '/'});
}

function showMap() {
    $('#map_canvas').show();
    $('#legend-map').show();
    $('#progresbarcontrol').show();
    $('#hideMap').html('<a href="javascript:void(0);" onclick="hideMap();" class="close">Скрыть карту</a>');
    $.cookie("map_visible3", "1", {expires: 30, path: '/'});
}
