var map = null;
var markers = [];
var markerClusterer = null;
var GBounds = null;
var grid_size = 60;
var grid_zoom = 10;
var isZoomed = false;

$(document).ready(function(){
  initialize();
});

function initialize() {
  if(GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById('map'));
    map.setCenter(new GLatLng(40.44694705960048, 8.61328125), 5);
    map.addControl(new GSmallZoomControl());
    map.enableScrollWheelZoom();
    isZoomed = false;
  }
}

function initializeZoomed() {
  if(GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById('map'));
    map.setCenter(new GLatLng(40.44694705960048, 8.61328125), 7);
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    
    refreshMap(grid_size, grid_zoom);
    isZoomed = true;
  }
}

function zoomMap()
{
  setTimeout(function(){
    DPopup.Create('gmap-zoomed', {
      width: 990, 
      closeCallBack: hideZoomedMap
    });
    DPopup.Text('gmap-zoomed', $('.popup-template').html());
    $('#gmap-zoomed .text').append($('.map-canvas'));
    $('#map').css({width: '930px', height: '500px'});
    DPopup.Open('gmap-zoomed');
    initializeZoomed();
  }, 100);
}

function hideZoomedMap()
{
  $('.top-map-container').prepend($('.map-canvas'));
  $('#map').css({width: '414px', height: '230px'});
  initialize();
  refreshMap(grid_size, grid_zoom);
}

function resetClusterMarkers()
{
  map.clearOverlays();
  markers = [];
  GBounds = null;
}

function refreshMap(size, zoom) {
  if (markerClusterer != null) {
    markerClusterer.clearMarkers();
  }
  
  markerClusterer = new MarkerClusterer(map, markers, {maxZoom: zoom, gridSize: size, styles: "-1"});
  
  zoom = map.getBoundsZoomLevel(GBounds);
  if(markers.length == 1)
  {
    zoom = 15;
  }
  else if(zoom <= 2)
  {
    zoom = 2;
//    map.setCenter(new GLatLng(22.917922936146045, -28.828125), 2);
  }
  var clat = (GBounds.getNorthEast().lat() + GBounds.getSouthWest().lat()) /2;
  var clng = (GBounds.getNorthEast().lng() + GBounds.getSouthWest().lng()) /2;
  map.setCenter(new GLatLng(clat,clng), zoom);
} 

function updateMapData()
{
  $.post('/realestate/map/get-data/', {},
    function(data){
      var map_container = $('#map').get(0);
      hideAjaxLoader(map_container);
      switch(data.type)
      {
        case 'country':
          updateCountryMarkers(data);
          break;
        case 'city':
          updateCityMarkers(data);
          break;
        case 'object':
          updateObjectMarkers(data);
          break;
      }
    },
    "json"
  );
}

function updateCountryMarkers(data)
{
  resetClusterMarkers();
  GBounds = new GLatLngBounds();	
  var icon = new GIcon(G_DEFAULT_ICON);
  icon.iconSize = new GSize(40, 55);
  icon.iconAnchor = new GPoint(7, 55);
  icon.imageMap = [0,0,40,0,40,20,10,20,7,55,0,20];
  
  for (var i in data.markers) {
    icon.image = data.defaultIcon;
    var point = new GLatLng(data.markers[i].lat, data.markers[i].lng);
    point.dataId = data.markers[i].id;
    var marker = new LabeledMarker(point, {icon: icon, labelText: data.markers[i].label,labelOffset: new GSize(-3, -53), labelClass: 'country-marker'});
    GEvent.addListener(marker, "click", onClickCountryMarker);
    GBounds.extend(point);
    markers.push(marker);
  }
  grid_size = 60;grid_zoom = 10;
  refreshMap(grid_size, grid_zoom);
  $('#map-breadcramb').html('');
}

function updateCityMarkers(data)
{
  resetClusterMarkers();
  GBounds = new GLatLngBounds();	
  var icon = new GIcon(G_DEFAULT_ICON);
  icon.iconSize = new GSize(30, 37);
  icon.iconAnchor = new GPoint(15, 37);
  icon.imageMap = [0,0,30,0,30,20,20,20,15,37,7,20,0,20];
  
  for (var i in data.markers) {
    icon.image = data.defaultIcon;
    var point = new GLatLng(data.markers[i].lng, data.markers[i].lat);
    point.dataId = data.markers[i].id;
    var marker = new LabeledMarker(point, {icon: icon, labelText: data.markers[i].label, labelOffset: new GSize(-12, -34), labelClass: 'city-marker'});
    GEvent.addListener(marker, "click", onClickCityMarker);
    GBounds.extend(point);
    markers.push(marker);
  }
  grid_size = 60;grid_zoom = 12;
  refreshMap(grid_size, grid_zoom);
  $('#map-breadcramb').html(
    '<a onclick="onClickMapBreadCramb(\'country\');" href="javascript:void(0);">Весь мир</a>'+
    '<span>' + data.breadCrumbLabel + '</span>'
  );
}

function updateObjectMarkers(data)
{
  resetClusterMarkers();
  GBounds = new GLatLngBounds();	
  for (var i in data.markers) {
    var point = new GLatLng(data.markers[i].lat, data.markers[i].lng);
    point.dataId = data.markers[i].point_id;
    point.dataType = data.markers[i].type;
    
    switch(data.markers[i].type)
    {
      case 'one':
        icon = new GIcon(G_DEFAULT_ICON);
        icon.iconSize = new GSize(25, 34);
        icon.iconAnchor = new GPoint(12, 34);
        icon.imageMap = [0,0,34,0,34,20,20,20,15,34,7,20,0,20];
        icon.image = data.Icons[data.markers[i].icon];
        labelText = 1;
        labelOffset = new GSize(0, 0);
        labelClass = 'hide-object-label';
        break;
      case 'group':
        icon = new GIcon(G_DEFAULT_ICON);
        icon.iconSize = new GSize(25, 34);
        icon.iconAnchor = new GPoint(12, 34);
        icon.imageMap = [0,0,34,0,34,20,20,20,15,34,7,20,0,20];
        icon.image = data.groupIcon;
        labelText = data.markers[i].label;
        labelOffset = new GSize(-11, -30);
        labelClass = 'object-marker';
        point.dataLabel = data.markers[i].label;
        break;
      case 'city_group':
        icon = new GIcon(G_DEFAULT_ICON);
        icon.iconSize = new GSize(30, 37);
        icon.iconAnchor = new GPoint(15, 37);
        icon.imageMap = [0,0,30,0,30,20,20,20,15,37,7,20,0,20];
        icon.image = data.cityIcon;
        labelText = data.markers[i].label;
        labelOffset = new GSize(-12, -34);
        labelClass = 'city-marker';
        point.dataLabel = data.markers[i].label;
        break;
    }
    
    var marker = new LabeledMarker(point, {icon: icon, labelText: labelText, labelOffset: labelOffset, labelClass: labelClass});
    GEvent.addListener(marker, "click", onClickObjectMarker);
    GBounds.extend(point);
    markers.push(marker);
  }
  grid_size = 60;grid_zoom = 16;
  refreshMap(grid_size, grid_zoom);
  $('#map-breadcramb').html(
    '<a onclick="onClickMapBreadCramb(\'country\');" href="javascript:void(0);">Весь мир</a>'+
    '<a onclick="onClickMapBreadCramb(\'city\');" href="javascript:void(0);">' + data.breadCrumbLabel.country + '</a>'+
    '<span>' + data.breadCrumbLabel.city + '</span>'
  );
}

function onClickCountryMarker(marker)
{
  id = marker.dataId;
  $('#filter-country').val(id).change();
  if($('#change-filter-url').attr('rel') != 'map_submit')
  {
    $('.search-form form').submit();
  }
}

function onClickCityMarker(marker)
{
  id = marker.dataId;
  $('#filter-city').val(id).change();
  if($('#change-filter-url').attr('rel') != 'map_submit')
  {
    $('.search-form form').submit();
  }
}

function onClickObjectMarker(marker)
{
  type = marker.dataType;
  map.setCenter(marker);
   
  switch(type)
  {
    case 'one':
      map.openInfoWindow(map.getCenter(), '<div class="object-info" style="width: 240px; height: 100px;"><img style="position: relative; left: 102px; top: 47px; " src="/images/small-loader.gif"/></div>');
      if(marker.dataId > 0)
      {
        $.post('/realestate/map/show/'+marker.dataId+'/', {}, function(html){
          $('.object-info').html(html);
        });
      }
      break;
    case 'group':
      map.openInfoWindow(map.getCenter(), 
        '<div class="object-info">'+
          '<div style="white-space: nowrap;">'+
            'По данному адресу расположено<br/> объектов: <span style="color: #CA2F33; font-weight: bold;">'+ marker.dataLabel +'</span>'+
          '</div> <br/><br/>'+
          '<a href="#" onclick="showGroupObjects(\''+marker.dataId+'\')">Посмотреть объекты</a>'+
        '</div>'
      );
      break;
    case 'city_group':
      map.openInfoWindow(map.getCenter(), 
        '<div class="object-info">'+
          '<div style="white-space: nowrap;">'+
            'В данном городе расположено<br/> <span style="color: #CA2F33; font-weight: bold;">'+marker.dataLabel+'</span> объектов без адресса'+
          '</div> <br/><br/>'+
          '<a href="#" onclick="showGroupObjects(\''+marker.dataId+'\')">Посмотреть объекты</a>'+
        '</div>'
      );
      break;
  } 
}

function showGroupObjects(point_id)
{
  if($('#change-filter-url').attr('rel') != 'map_submit')
  { 
    var map_container = $('#map').get(0);
    showAjaxLoader(map_container);
    var container = $('.ajax-container').get(0);
    showAjaxLoader(container);
    $.post('/search.html', {point_id: point_id}, function(html){
      hideAjaxLoader(map_container);
      $('.ajax-container').html(html);
      map.disableInfoWindow();
      map.enableInfoWindow();
      if(isZoomed)
      {
        DPopup.Close('gmap-zoomed', hideZoomedMap);
      }
    });
  }
  else
  {
    $('.search-form form').append('<input id="map-point" type="hidden" name="point_id" value="'+point_id+'"/>').submit();
  }
}

function onClickMapBreadCramb(type)
{
  switch(type)
  {
    case 'country':
      $('#filter-country').val(0).change();
      break;
    case 'city':
      $('#filter-city').val(0).change();
      break;
  }
}
