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

var map;
var user_city;
var marker_style, city_marker_style;
var pos_placemark;
var objManager;
var city_zoom_level;
var companies;
//============================================================================//

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 () {};
}

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

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);//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(mode, cfg_city_zoom_level) {

    city_zoom_level = cfg_city_zoom_level;

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

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

    map.disableScrollZoom();

    switch (mode){
        case 'city':    var zoom = 11;  break;
        case 'country': var zoom = 3;   break;
        default:        var zoom = 11;  break;
    }

    if ($('#inmaps_map_filter').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());
    }

        YMaps.Events.observe(map,map.Events.BeforeMouseUp, function () {
            map.enableScrollZoom();
        });
        

    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 initPlaceMap(address){

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

    map.addControl(new YMaps.Zoom());

    centerAddress(address, 15);

    var geocoder = new YMaps.Geocoder(address);

    map.addOverlay(geocoder);

}

function initPlaceMapXY(lng, lat, name){

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

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

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

    map.setCenter(point, 15);

    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]);

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

    map.setCenter(point, 13)

    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)
            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(){

    var geocoder    = new YMaps.Geocoder(address);

    var country     = $('input[name=addr_country]').val();
    var city        = $('input[name=addr_city]').val();
    var prefix      = $('select[name=addr_prefix]').val();
    var street      = $('input[name=addr_street]').val();
    var house       = $('input[name=addr_house]').val();

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

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

    var geocoder = new YMaps.Geocoder(address);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            $('input[name=addr_lat]').val(this.get(0).getGeoPoint().getLat()).fadeOut('fast').fadeIn('fast');
            $('input[name=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)
            if ($('#inmaps_map_filter').length){
                (zoom <= city_zoom_level ? $('#inmaps_map_filter').hide() : $('#inmaps_map_filter').show());
            }
        }
    })

}

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

function addMarkers(list){

    for(place_id in list) if (list.hasOwnProperty(place_id)) {

        if (typeof(list[place_id].lng) != 'undefined'){
            addMarkerXY(place_id, list[place_id].lng, list[place_id].lat, list[place_id].icon, list[place_id].zoom);
        } else {
            addCityMarker(list[place_id].city, list[place_id].country);
        }

        map.addOverlay(objManager);

    }

    $('.marker_loading').hide();

}

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(place_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(place_id, obj); });
            objManager.add(placemark, min_zoom, 17);

        }
    });

}

function addMarkerXY(place_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(65, 42);//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(place_id, obj);
    });

    objManager.add(placemark, min_zoom, 17);

    map.addOverlay(objManager);

}

function clickMarker(place_id, marker){
    
    marker.openBalloon('<div class="loading" style="display:block">Загрузка...</div>');
    var url = '';
    if(companies){
        url = '/companies/ajax/get-info/'+place_id;
    }else{
        url =   '/maps/ajax/get-info/'+place_id;
    }
    $.ajax({
          type: 'POST',
          url:  url,
          success: function(msg){
              marker.openBalloon(msg);
          }
    });
    
}

function clickCityMarker(city, country, marker){

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

    $.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, 11);

}

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

//============================================================================//
var x, y, N, _y, _x, _timer_i;
_actionT = 'off';// состояние таймера - on off scroll
var _timer = null;

// проверяем текущее положение курсора и тех, что были за преведущими
function chekTimer(){
    //var x, y;
    _timer_i +=1;
        if(_actionT!='on'){
         clearInterval(_timer);
         return;
        }

    $('#citymap').mousemove(function(e){
        x= e.pageX;
        y= e.pageY;
    });
  //  console.log(x+'-'+ _x+" "+_actionT );
    if(x- _x< N && y-_y  < N){
        if(_timer_i > 2){
            addScroll();
        }

    }else{
        deleteTimer();
    }
    _x = x;
    _y = y;
}

function deleteTimer(){
  //  console.log("clear");
    _timer_i =0;
}
function addScroll(){
//   console.log("!!!!!!!!!!");
  if(!map){
     return;
  }
  map.enableScrollZoom();
 //console.log("!!!!!!!!!!");
   // map.set('scrollwheel', true)
    clearInterval(_timer);
    _timer = null;
    _actionT = 'scroll';
     _timer_i =0;
}

N = 50;


$(document).ready( function(){

    $('.component').mousemove(function(e) {
        if( (_actionT!='off')  &&(  $('#citymap').offset().top >  e.pageY ||   $('#citymap').offset().left >  e.pageX ||
             $('#citymap').offset().top + $('#citymap').height() <  e.pageY ||   $('#citymap').offset().left  + $('#citymap').width() <  e.pageX
            )){
                     map.disableScrollZoom();
           // map.set('scrollwheel', false);
         //   console.log("Out delete timer"  );
            _timer = null;
            _actionT = 'off';
        }    //
    });


    $('#citymap').mousemove(function(e) {
        if(_actionT == 'scroll'){
            return;
        }
        // если новые значения больше или меньше на N чем передущие координаты, то будем считать что мышка не сдвинулась
        // если таймер невключён- включаем, и записываем в переменные _x _y координаты для сравнения
        if(_actionT != 'on' && !_timer){

          //  console.log("Timer ON:");
            _actionT='on';
            _x= e.pageX;
            _y= e.pageY;
            _timer = window.setInterval("chekTimer();",700);

        }
        x= e.pageX;
        y= e.pageY;

    })
});

function maps_goto( lat, lng){
   // var latlng = new google.maps.LatLng( lat, lng);
  
//var geocoder = new YMaps.Geocoder(new YMaps.GeoPoint(37.588395, 55.762718), {results: 1});
//console.log(lat, lng);
  var geocoder = new YMaps.Geocoder(new YMaps.GeoPoint( lng , lat) );

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

}; 
