var dealers    = new Array();
var placemarks = new Array();
var placemarkp = new Array();
var loader     = $("#loader");
var ajax_url   = "/ru/ajax/sales/";
var dealers_url = '/ru/ajax/dealers/';
var debug      = false;
var zoomcorrect = -2;

// loadDealers();

var map, geoResult;
var minZoom;

$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
   return results ? results[1] : 0;
}

$id = $.urlParam('id') ? $.urlParam('id') : 0;


if ($("#cities option:selected").metadata().hasSubway == 'Yes') {
    minZoom = $("#cities option:selected").metadata().zoom;
  } else {
  $("#cities option").each(function(i){
    if ( $(this).metadata().hasSubway == 'Yes') minZoom = $(this).metadata().zoom;
     return false;
  });
}

var map = new YMaps.Map(document.getElementById("mapCanvas"));
map.addControl(new YMaps.TypeControl());
map.addControl(new YMaps.Zoom());
map.addControl(new YMaps.ScaleLine());

getDealers($("#cities option:selected").metadata().citiId);
// togglePartnersBlock($("#cities").val());
showRegionalBlock($("#cities option:selected").metadata().citiId);

initMap();
loadMetro($("#cities option:selected").metadata().citiId);
getPoints($id);


$("#cities").change(function () {
 // togglePartnersBlock($("#cities").val());
  showRegionalBlock($("#cities option:selected").metadata().citiId);
  getDealers($("#cities option:selected").metadata().citiId);
  initMap();
  loadMetro($("#cities option:selected").metadata().citiId);
});


$("#subways").change(function () {
  map.setCenter(new YMaps.GeoPoint($("#subways").val().split(",")[0],$("#subways").val().split(",")[1]), minZoom);
});



$('#s_htc, #s_mod, #s_note, #s_egg, #s_router, #s_zyxel').click(function () {
  getPoints(0);
});

//$('#device_selection input').click(function () {
//	getPoints(0);
//});


map.listenMouseEvent(map.Events.MouseUp, true);

event_mapUpdate = YMaps.Events.observe(map, map.Events.Update, function () {
  getPoints($id);
});


var flag_user_move = false;
YMaps.Events.observe(map, map.Events.MoveEnd, function () {
   if (flag_user_move) {
       getPoints($id);
       flag_user_move = false;
   }
})

var event_mapMouseUp = YMaps.Events.observe(map, map.Events.MouseUp, function () {
   flag_user_move = true;
})



// Point styles

var terminals = new YMaps.Style();
terminals.iconStyle = new YMaps.IconStyle("yota#terminalsPointIcon");
terminals.iconStyle.offset = new YMaps.Point(-11, -28);
terminals.iconStyle.href = "/images/map/marker-blue.png";
terminals.iconStyle.size = new YMaps.Point(22, 28);
terminals.iconStyle.shadow = new YMaps.IconShadowStyle();
terminals.iconStyle.shadow.offset = new YMaps.Point(-15, -35);
terminals.iconStyle.shadow.href = "/images/map/point-shadow.png";
terminals.iconStyle.shadow.size = new YMaps.Point(36, 34);
YMaps.Styles.add("yota#terminalsPoint", terminals);

var t = new YMaps.Template();
t.text = "<div><img alt='' style='height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];' src='$[style.iconStyle.href]'\/><div class='CustomPointName'>$[name| ]</div></div>";
YMaps.Templates.add("yota#terminalsPointIcon", t);


var atm = new YMaps.Style();
atm.iconStyle = new YMaps.IconStyle("yota#atmPointIcon");
atm.iconStyle.offset = new YMaps.Point(-11, -28);
atm.iconStyle.href = "/images/map/marker-green.png";
atm.iconStyle.size = new YMaps.Point(22, 28);
atm.iconStyle.shadow = new YMaps.IconShadowStyle();
atm.iconStyle.shadow.offset = new YMaps.Point(-15, -35);
atm.iconStyle.shadow.href = "/images/map/point-shadow.png";
atm.iconStyle.shadow.size = new YMaps.Point(36, 34);
YMaps.Styles.add("yota#atmPoint", atm);

var t1 = new YMaps.Template();
t1.text = "<div><img alt='' style='height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];' src='$[style.iconStyle.href]'\/><div class='CustomPointName'>$[name| ]</div></div>";
YMaps.Templates.add("yota#atmPointIcon", t1);

var counters = new YMaps.Style();
counters.iconStyle = new YMaps.IconStyle("yota#countersPointIcon");
counters.iconStyle.offset = new YMaps.Point(-11, -28);
counters.iconStyle.href = "/images/map/marker-yellow.png";
counters.iconStyle.size = new YMaps.Point(22, 28);
counters.iconStyle.shadow = new YMaps.IconShadowStyle();
counters.iconStyle.shadow.offset = new YMaps.Point(-15, -35);
counters.iconStyle.shadow.href = "/images/map/point-shadow.png";
counters.iconStyle.shadow.size = new YMaps.Point(36, 34);
YMaps.Styles.add("yota#countersPoint", counters);

var t2 = new YMaps.Template();
t2.text = "<div><img alt='' style='height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];' src='$[style.iconStyle.href]'\/><div class='CustomPointName'>$[name| ]</div></div>";
YMaps.Templates.add("yota#countersPointIcon", t2);



function showAddress (value) {
map.removeOverlay(geoResult);
var geocoder = new YMaps.Geocoder(value, {results: 1, boundedBy: map.getBounds()});

YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
    if (this.length()) {
        geoResult = this.get(0);
        geoResult.setBalloonContent(geoResult.text);
        geoResult.setStyle("default#greenPoint");
        map.addOverlay(geoResult);
        map.setBounds(geoResult.getBounds());
    }
//    else {
//        alert("Ничего не найдено!");
//        }
    });
};


function getPoints($id) {

$lb = map.getBounds().getLeftBottom().toString().split(",");
$rt = map.getBounds().getRightTop().toString().split(",");
//$type = $("#payments_type").val();
var $type = new Array();
// TODO Rewrite this to universal
if ($('#s_htc').get(0).checked) {
  $type.push('htcmax');
}
if ($('#s_mod').get(0).checked) {
  $type.push('modem');
}
if ($('#s_note').get(0).checked) {
  $type.push('note');
}

if ($('#s_egg').get(0).checked) {
  $type.push('egg');
}

if ($('#s_router').get(0).checked) {
  $type.push('router');
}

/*
if ($('#s_zyxel').get(0).checked) {
  $type.push('zyxel');
}
*/

zoom = map.getZoom();

loader.show();

map.removeOverlay(placemarks);
placemarks = [];
placemarkp = [];
data = [];

if (zoom < minZoom + zoomcorrect) {
  debugMap();
  $('#salesList').html("<p>Выберите район или интересующее вас метро</p>");
  loader.hide();
  return;
}

//$data = ({long1 : $lb[0], lat1: $lb[1], long2: $rt[0], lat2: $rt[1], 'type[]': $type});

if ($id != 0) {
  $data = ({type: 'spoint', id: $id});
} else {
  $data = ({long1 : $lb[0], lat1: $lb[1], long2: $rt[0], lat2: $rt[1], 'type[]': $type});
}

$.ajax({
   type: "GET",
    url: ajax_url,
   dataType: "json",
   data: $data,
   success: function(data){
  var ind = 1;

    for (var i in data) {
      var point = new YMaps.GeoPoint(data[i].longitude, data[i].latitude);

      placemark = new YMaps.Placemark(point);

      placemarkp[ind] = placemark;
      placemark.name = ind;

      baloonContent = '<h4>' + data[i].owner_name + '</h4>';
      baloonContent += '<div>';

      baloonContent +=  '<div>';
      baloonContent +=  '<p>' + data[i].address + '</p>';
      if (data[i].time) {
        baloonContent += '<p>Время работы: ' + data[i].time + '</p>';
      }
     // baloonContent += '<p>' + data[i].type + '</p>';
     // baloonContent += '<p>' +  data[i].longitude + ', ' +  data[i].latitude + '</p>';
      baloonContent +=  '</div>';
      if (data[i].owner_logo) {
        baloonContent += '<img src="' + data[i].owner_logo + '" alt="' + data[i].owner_name + '" class="baloon-dealer-logo"  />';
      }
      baloonContent +=  '</div>';
      placemark.setBalloonContent(baloonContent);
      placemark.setStyle("yota#"+ 'terminals' + "Point");

      YMaps.Events.observe(placemark, placemark.Events.BalloonOpen, function () {
         flag_user_move = false;
      });

      placemarks.push(placemark);
      ind++;
      }
    map.addOverlay(placemarks);

    if($id != 0 && placemarks.length == 1) {
    //	console.log(placemarks[0].getGeoPoint());

      map.setCenter(placemarks[0].getGeoPoint(), minZoom + 2);
      event_mapUpdate.cleanup();
      event_mapMouseUp.cleanup();
    }

    pointsList(data);
    loader.hide();
    debugMap();
     }
   });
 }


function showBalloon(ind) {
   YMaps.Events.observe(placemarkp[ind], placemarkp[ind].Events.BalloonOpen, function () {
   });
   flag_user_move = false;
  placemarkp[ind].openBalloon();
}


function pointsList(points) {
  var ind = 1;
  var html = '';
  if (points.nopoints) {
    html ='';
  } else {
  for (var id in points) {
    if (points[id]!= null) {
    //	$tt = eval(points[id].type);
      $tt = terminals;
      $icon = $tt.iconStyle.href;
      if(typeof document.body.style.maxHeight === "undefined") {
        $icon = $tt.iconStyle.href.replace(/png/,'gif');
      }
      // $icon = $.support.opacity ? $tt.iconStyle.href : $tt.iconStyle.href.replace(/png/,'gif');
      // TODO IE6 icon fix
      html += '<dl pointID="' + id + '"><dt><span><a href="#point' + ind + '" onclick="showBalloon(' + ind + ');return false;" style="color:#fff/*background-image: url(' + $icon + ')*/">' + (ind) + '</a></span>' +
      '<a href="#point' + ind + '" onclick="showBalloon(' + ind + ');return false;">' + points[id].owner_name + '</a></dt>' +
      '<dd>'+points[id].address+ '</dd></dl>';
      ind++;
    }
  }
  }
  if (html.length == 0) {
    html = "<p>В указанной области точек продаж не найдено.</p>";
  }
  $('#salesList').html(html);
  html = '';

  $('#salesList').jScrollPane({
    scrollbarWidth: 14,
    showArrows: true,
    arrowSize: 17,
    dragMinHeight: 15
  });

}

function initMap() {
  metadata = $('#cities option:selected').metadata();
  $('#salesList').empty();
  map.setCenter(new YMaps.GeoPoint(metadata.long, metadata.lat), metadata.zoom + zoomcorrect, YMaps.MapType.MAP);
  debugMap();
}

function debugMap() {
  if (debug) {
  geores = typeof(geoResult)!="undefined" ? geoResult.text + '.  Координаты: ' + geoResult.getGeoPoint().toString() : '';
  $("#result").html(geores +
      '<br/>LeftBottom: ' + map.getBounds().getLeftBottom().toString() +
      ' RightTop: ' + map.getBounds().getRightTop().toString() +
      ' Zoom:' + map.getZoom()
        );
  }
}


function loadMetro(cityId){
  if ($("#cities option:selected").metadata().hasSubway == 'Yes') {
    $('#subways').empty().append( $('<option>').val('').text(LANG.loadingSubwaysStations));
    $.ajax({
       type: "GET",
       url: ajax_url,
       data: {cityId: cityId},
       dataType: "json",
       success: function(subways){
        // add options to metro select
        $('#subways').empty().append( $('<option>').val('').text(LANG.selectSubwayStation) );
        for (var subwayID in subways) {
          var opt = $('<option>').val(subways[subwayID].longitude + ',' + subways[subwayID].latitude).text(subways[subwayID].name);
          $('#subways').append(opt);
          }
        $('#subways_div').show();
        }
    });
  } else {
    $('#subways_div').hide();
  }
}


function getDealers(cityId) {
  var dealers_output = '';
  $.ajax({
     type: "GET",
     url: dealers_url,
     data: {cityId: cityId},
     dataType: "json",
     success: function(dealers){
        for (var dealerID in dealers) {
          dealers_class = '';

          dealer_title = '<span>' + dealers[dealerID].name + '</span>';
          dealer_site = '';
          if (dealers[dealerID].picture) {
            dealer_picture = '<img src="' + dealers[dealerID].picture + '" alt="' + dealers[dealerID].name + '" />';
          } else {
            dealer_picture = '';
          }

          if (dealers[dealerID].url) {
            //www = dealers[dealerID].url.replace(/http:\/\//,'').replace(/\/$/,''); // removes http:// and trim final slash
            www = dealers[dealerID].url.replace(/http:\/\//,'');
            www_domain = www.split(/\/+/g)[0]; // only domain name, to avoid long urls

            if (dealer_picture) {
              dealer_picture = '<a href="http://' + www + '">' + dealer_picture + '</a>';
            }
            dealer_title = '<span><a href="http://' + www + '">' +  dealers[dealerID].name + '</a></span>';
            dealer_site = '<br/><a href="http://' + www + '">' + www_domain + '</a>';
          }

          dealers_output += '<div class="shops' + dealers_class + '"><div>';
          dealers_output += dealer_picture;
          dealers_output += dealer_title;
          if (dealers[dealerID].phone) {// phone
            dealers_output += '<br/>' + dealers[dealerID].phone + '';
          }
          dealers_output += dealer_site;
          dealers_output += '</div></div>';
        }
        $(".dealers_outer").html(dealers_output);
     }
  });
}
/**
 * Показывает блок только для Уфы
 * @param city_name
 * @return
 */
function togglePartnersBlock(city_name) {
  if (city_name == "Уфа") {
    $("#partners").show();
  } else {
    $("#partners").hide();
  }
}

/**
 * Показывает блок для определенного региона
 * @param cityId
 * @return
 */
function showRegionalBlock(cityId) {
	$('#partners').html('<img height="21" width="113" id="loader" style="display:block; margin:auto;" alt="Загрузка..." src="/bitrix/templates/yota/i/loading_animation.gif"/>');
  $("#partners").load("/ru/ajax/wheretobuy-block/?city_id="+cityId);
  }
