//============================================================================//
//========                  YANDEX MAPS                             ==========//
//============================================================================//

var map;
var user_city;
var marker_style, city_marker_style;
var pos_placemark;
var objManager;
var city_zoom_level, city_zoom, map_type;
var use_filter = false;

//============================================================================//

function mapFilterControl () {

    // Обработчик добавления элемента на карту
    this.onAddToMap = function (map, position) {
        this.container = $("#inmaps_map_filter");
        this.map = map;
        this.position = new YMaps.ControlPosition(YMaps.ControlPosition.TOP_RIGHT, new YMaps.Size(6, 36));

        // CSS-свойства, определяющие внешний вид элемента
        this.container.css({
            position: "absolute",
            right: '0px',
            zIndex: YMaps.ZIndex.CONTROL,
            background: '#fff',
            listStyle: 'none',
            padding: '15px',
            margin: 0,
            border: 'solid 1px gray',
            cursor: 'default'
        });

        // Располагает элемент управления в верхнем правом углу карты
        this.position.apply(this.container);

        // Добавляет элемент управления на карту
        this.container.appendTo(this.map.getContainer());

    }

    this.onRemoveFromMap = function () { return; };

}

//============================================================================//

function setMarkerStyles(){

    city_marker_style                   = new YMaps.Style();
    city_marker_style.iconStyle         = new YMaps.IconStyle();
    city_marker_style.iconStyle.href    = "/components/maps/images/markers/city.png";
    city_marker_style.iconStyle.size    = new YMaps.Point(27, 32);
    city_marker_style.iconStyle.offset  = new YMaps.Point(-13, -32);

    city_marker_style.iconStyle.shadow          = new YMaps.IconShadowStyle();
    city_marker_style.iconStyle.shadow.href     = "/components/maps/images/markers/marker-shadow-city.png";
    city_marker_style.iconStyle.shadow.size     = new YMaps.Point(22, 20);
    city_marker_style.iconStyle.shadow.offset   = new YMaps.Point(-4, -22);

}

//============================================================================//

function initGeoSystem(options) {

    city_zoom_level = options.city_zoom_level;
    city_zoom       = options.zoom_city;

    map         = new YMaps.Map(YMaps.jQuery("#citymap")[0]);
    user_city   = $('input[name=user_city]').val();

    if (options.map_type=='any') { map.addControl(new YMaps.TypeControl()); }
    map.addControl(new YMaps.Zoom());

    map.enableScrollZoom();

    var zoom;

    switch (options.mode){
        case 'city':    zoom = options.zoom_city;  break;
        case 'country': zoom = options.zoom_country;   break;
        default:        zoom = options.zoom_city;  break;
    }

    switch (options.map_type){
        case 'map': map_type = YMaps.MapType.MAP; break;
        case 'hybrid': map_type = YMaps.MapType.HYBRID;  break;
        case 'satellite': map_type = YMaps.MapType.SATELLITE;  break;
        default: map_type = null; break;
    }

    map.setMaxZoom(options.zoom_max);
    map.setMinZoom(options.zoom_min);

    if ($('#inmaps_map_filter:visible').length){
        map.addControl(new mapFilterControl());

        YMaps.Events.observe(map,map.Events.SmoothZoomEnd, function () {
            (map.getZoom() <= city_zoom_level ? $('#inmaps_map_filter').hide() : $('#inmaps_map_filter').show());
        });

        (zoom <= city_zoom_level ? $('#inmaps_map_filter').hide() : $('#inmaps_map_filter').show());

        use_filter = true;
    }

    if (options.center_lng && options.center_lat){
        options.center_lng = options.center_lng.replace(",", ".");
        options.center_lat = options.center_lat.replace(",", ".");
        map.setCenter(new YMaps.GeoPoint(options.center_lng, options.center_lat), zoom);
    } else {
        if (user_city) { centerAddress(user_city, zoom); }
    }

    setMarkerStyles();

    objManager = new YMaps.ObjectManager();
    map.addOverlay(objManager);

    if (map){ getMarkers(); }
    
}

function unloadGeoSystem(){
    map.destructor();
}

function redrawMap(){
    map.redraw();
}

//============================================================================//

function initPlaceMapXY(lng, lat, name, options){

    map = new YMaps.Map(YMaps.jQuery("#placemap")[0]);
    map.enableScrollZoom();

    map.addControl(new YMaps.Zoom({noTips: true}));

    var point = new YMaps.GeoPoint(lng, lat);

    if (typeof(options)=="undefined"){
        options = { zoom_max:15, zoom_min:5, zoom:15, map_type:'map' };
    } else {
        if (typeof(options.zoom_max)=="undefined"){ options.zoom_max = 15; }
        if (typeof(options.zoom_min)=="undefined"){ options.zoom_min = 5; }
        if (typeof(options.zoom)=="undefined"){ options.zoom = 15; }
        if (typeof(options.map_type)=="undefined"){ options.map_type = 'map'; }
    }

    map.setMaxZoom(options.zoom_max);
    map.setMinZoom(options.zoom_min);

    switch (options.map_type){
        case 'map': map_type = YMaps.MapType.MAP; break;
        case 'hybrid': map_type = YMaps.MapType.HYBRID;  break;
        case 'satellite': map_type = YMaps.MapType.SATELLITE;  break;
        default: map_type = null; break;
    }
    map.setCenter(point, options.zoom, map_type);

    pos_placemark = new YMaps.Placemark(point, {});
    pos_placemark.name = name;

    map.addOverlay(pos_placemark);
    
}

//============================================================================//

function initMarkerMapXY(lng, lat){

    zoom    = 13;
    map     = new YMaps.Map(YMaps.jQuery("#marker_map")[0]);

    map.enableScrollZoom();

    var point = new YMaps.GeoPoint(lng, lat);

    map.setCenter(point, 13, map_type);

    pos_placemark = new YMaps.Placemark(point, {draggable: true, hideIcon:false, style:"default#anchorIcon"});

    pos_placemark.name = "Маркер";
    pos_placemark.description = "Перетащите маркер чтобы<br/>задать позицию объекта";

    map.addOverlay(pos_placemark);

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

function centerMarkerMap(address){

    var geocoder = new YMaps.Geocoder(address);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            map.setCenter(this.get(0).getGeoPoint(), 13, map_type)
            pos_placemark.setGeoPoint(this.get(0).getGeoPoint());
        }
    })

}

function getMarkerMapPos(){

    var point = pos_placemark.getGeoPoint();

    return {x: point.getX(), y: point.getY()};

}

function destroyMarkerMap(){
    map.destructor();
}

//============================================================================//

function clearMap(){
    objManager.removeAll();
    map.addOverlay(objManager);
}

//============================================================================//

function detectLatLng(addr){

    var geocoder    = new YMaps.Geocoder(address);

    var address = addr.country + ', ' + addr.city + ', ' + addr.prefix + ' ' + addr.street + ' ' + addr.house;

    $('#detect_btn').attr('disabled', 'disabled').val('Подождите...');

    var geocoder = new YMaps.Geocoder(address);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            $('.addr_coord[rel='+addr.id+'] .addr_lat').val(this.get(0).getGeoPoint().getLat()).fadeOut('fast').fadeIn('fast');
            $('.addr_coord[rel='+addr.id+'] .addr_lng').val(this.get(0).getGeoPoint().getLng()).fadeOut('fast').fadeIn('fast');
        } else {
            alert('Не удалось определить координаты');
        }
        $('#detect_btn').attr('disabled', '').val('Найти координаты');
    });

    YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (error) {
        alert("Ошибка определения координат\nЯндекс ответил: " + error.message);
    });

}

function detectLatLngList(){

    var tr = $('tr.item_row').eq(0);

    var address = $(tr).find('td.addr').html();
    var item_id = $(tr).attr('rel');

    var geocoder = new YMaps.Geocoder(address);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            $('#'+item_id+'_lat').val(this.get(0).getGeoPoint().getLat()).attr('disabled', '');
            $('#'+item_id+'_lng').val(this.get(0).getGeoPoint().getLng()).attr('disabled', '');
        }
    });

    $(tr).removeClass('item_row');

    if ($('tr.item_row').length==0) {
        $('.start_detect').hide();
        $('.save_detect').show();
        return;
    }

    setTimeout('detectLatLngList()', 1000);

}

function centerAddress(address, zoom){

    if (!zoom){ zoom = 3; }

    var geocoder = new YMaps.Geocoder(address);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            map.setCenter(this.get(0).getGeoPoint(), zoom, map_type)
            if (use_filter){
                (zoom <= city_zoom_level ? $('#inmaps_map_filter').hide() : $('#inmaps_map_filter').show());
            }
        }
    })

}

//============================================================================//



function addMarkers(list){

    for(var p in list) {

        var place = list[p];

        if (!place.is_city){
            addMarkerXY(place.id, place.lng, place.lat, place.icon, place.zoom);
        } else {
            addCityMarker(place.city, place.country);
        }

        map.addOverlay(objManager);

    }

}

function addCityMarker(city, country) {

    var geocoder = new YMaps.Geocoder(country+', '+city);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {

            var placemark = new YMaps.Placemark(this.get(0).getGeoPoint(), {style: city_marker_style});
            YMaps.Events.observe(placemark, placemark.Events.Click, function (obj) { clickCityMarker(city, country, obj); });

            var zoom = (city == user_city ? city_zoom_level : 17);

            objManager.add(placemark, 0, zoom);

        }
    });

}

function addMarker(marker_id, address, icon, min_zoom) {

    if (!icon) { icon = 'default.png'; }
    if (min_zoom==0) { min_zoom = city_zoom_level + 1; }

    var geocoder = new YMaps.Geocoder(address);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {

            var marker_style                   = new YMaps.Style();
                marker_style.iconStyle         = new YMaps.IconStyle();
                marker_style.iconStyle.href    = icon ? "/components/maps/images/markers/"+icon : "default.png";
                marker_style.iconStyle.size    = new YMaps.Point(27, 26);
                marker_style.iconStyle.offset  = new YMaps.Point(-6, -26);

            var placemark = new YMaps.Placemark(this.get(0).getGeoPoint(), {style: marker_style});

            YMaps.Events.observe(placemark, placemark.Events.Click, function (obj) { clickMarker(marker_id, obj); });
            objManager.add(placemark, min_zoom, 17);

        }
    });

}

function addMarkerXY(marker_id, lng, lat, icon, min_zoom) {

    if (!icon) { icon = 'default.png'; }
    if (min_zoom==0) { min_zoom = city_zoom_level + 1; }

    var point = new YMaps.GeoPoint(lng, lat);

    var marker_style                   = new YMaps.Style();
        marker_style.iconStyle         = new YMaps.IconStyle();
        marker_style.iconStyle.href    = icon ? "/components/maps/images/markers/"+icon : "default.png";
        marker_style.iconStyle.size    = new YMaps.Point(27, 26);
        marker_style.iconStyle.offset  = new YMaps.Point(-6, -26);

    var placemark = new YMaps.Placemark(point, {style: marker_style});

    YMaps.Events.observe(placemark, placemark.Events.Click, function (obj) {
        clickMarker(marker_id, obj);
    });

    objManager.add(placemark, min_zoom, 17);

    map.addOverlay(objManager);

}

function clickMarker(marker_id, marker){

    marker.openBalloon('<div class="loading" style="display:block">Загрузка...</div>');

    $.ajax({
          type: 'POST',
          url: '/maps/ajax/get-info/'+marker_id,
          success: function(msg){
              marker.openBalloon(msg);
          }
    });
    
}

function clickCityMarker(city, country, marker){

    marker.openBalloon('<div class="loading" style="display:block">Загрузка...</div>');

    city    = encodeURIComponent(city);
    country = encodeURIComponent(country);

    $.ajax({
          type: 'POST',
          url: '/maps/ajax/get-city-info/'+country+'/'+city,
          success: function(msg){
              marker.openBalloon(msg);
          }
    });

}

function zoomToCity(city){

    $('input[name=user_city]').val(city);

    user_city = city;

    getMarkers();

    centerAddress(city, city_zoom);

}

//============================================================================//

