/* <<<< ФУНКЦИИ РАБОТЫ С КАРТОЙ */
// <script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;&v=2&key=ABQIAAAAF0-INiYtLHBl5e6vNa0sCxQyb4aYtKvJm6jiRDYmjL1P8Z5sCBRPrMmKkhU5yPaZh9M6IrkQ238Kcg"></script>
// ключ можно получить на http://code.google.com/intl/ru/apis/maps/signup.html
var map;
var markers = [];
var mapErrors = [];
var baseIcon;
var scale = 4;
var bon;
var descriptions = new Array();

function get_scale(address) {
	if (address == undefined || address == '') scale = 4;
	else if (address.indexOf(',') != -1) {
		var	sep = address.split(',');
		switch (sep.length) {
			case 1: scale = 12; break;
			case 3: scale = 16; break;
			default: scale = 14;
		}
	} else scale = 10;
return scale;
}

function loadMap() {
 if (GBrowserIsCompatible()) {
    map = new GMap2($("google_map"));
    bon = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0), 1);

//  MINI
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
//  FULL
//	map.addControl(new GLargeMapControl());
//	map.addControl(new GMapTypeControl());

	map.hideControls();
	GEvent.addListener(map, "mouseover", function(){map.showControls();});
	GEvent.addListener(map, "mouseout", function(){map.hideControls();});

   geocoder = new GClientGeocoder();

   baseIcon = new GIcon();
   baseIcon.shadow = "/img/ico/shadow.png";
   baseIcon.iconSize = new GSize(35, 35);
   baseIcon.shadowSize = new GSize(35, 35);
   baseIcon.iconAnchor = new GPoint(35, 35);
   baseIcon.infoWindowAnchor = new GPoint(17, 10);

   window.onunload = GUnload;
  }

}



function createMarkerAt(latlng, address, ind) {
  //var index = 0;
  //var letter = String.fromCharCode("A".charCodeAt(0) + index);
  var letteredIcon = new GIcon(baseIcon);
  letteredIcon.image = "/img/ico/marker.png";

  markerOptions = { icon:letteredIcon }; //, draggable:true
  var marker = new GMarker(latlng, markerOptions);
  //var text = (descriptions[ind]) ? descriptions[ind] : "<b style=font-size:14px>Адрес:<br></b> " + address;
  var text = (descriptions[ind]) ? "<div class=\"gmap\">"+descriptions[ind]+"</div>" : "<b style=font-size:14px>Адрес:<br></b> " + address;
  GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(text); });

  if (markers.length<100) map.addOverlay(marker);
  markers.push(marker);

}



function clearMarkers() {
  for (var i = 0; i < markers.length; i++) {
    //alert(markers[i]['ja'].lat() + " = " +markers[i]['ja'].lng());
    map.removeOverlay(markers[i]);
  }
  markers = []; mapErrors = [];
}


//	   		 showAddress(points[i], false, i, last);
function showAddress(address, pan, ind, last) {
  if (pan == undefined && pan == null) last = 0;
  if (pan == undefined && pan == null) { pan = true; ind = 0; }
  
  if (pan) scale = get_scale(address);

  geocoder.getLatLng(
    address,
    function(latlng) {
      if (!latlng) {
		if (pan) {
      		if ($('map_content')) $('map_content').style.visibility = 'hidden';
			//close_message('info', "Адрес: \"" + address + "\" не найден");
		}
		mapErrors.push(address);
      } else {
		//close_message('info', latlng);
        if (pan) { if ($('map_content')) { $('map_content').style.visibility = 'visible'; } map.setCenter(latlng, scale);  }
        if (last == 1) { window.setTimeout(function() { map.setCenter(latlng, 16); },150); }
        createMarkerAt(latlng, address, ind);
	}
    }
  );


  if (last>1) {
  	var sep = address.split(',');
	  geocoder.getLatLng(
	    sep[0],
	    function(latlng) {
    		if (latlng) map.setCenter(latlng, 10);
	    }
	  );
  }
}



function scaleMarkers(){
  var lat, lng, minLat = 0, minLng = 0, maxLat = 0, maxLng = 0;
  var len = markers.length;
  scale = 16;
  var key_lat = 'la';

if (len>0) {

  if (!markers[0][key_lat]) for (var i in markers[0]) if (markers[0][i].lat) { key_lat = i; break; }

  for (var i = 0; i < len; i++) if (markers[i][key_lat].lat&&markers[i][key_lat].lng) {
    lat = parseFloat(markers[i][key_lat].lat);
	lng = parseFloat(markers[i][key_lat].lng);
	alert("MARKERS: ("+markers[i][key_lat]+"), LAT: ("+lat+"), LNG: ("+lng+")");
    //map.addOverlay(markers[i]);
    //pause(20);
    if (lat<minLat || minLat == 0) minLat = lat;
    if (lat>maxLat || maxLat == 0) maxLat = lat;
    if (lng<minLng || minLng == 0) minLng = lng;
    if (lng>maxLng || maxLng == 0) maxLng = lng;
  }

  alert("MIN: ("+minLat+", "+minLng+") MAX: ("+maxLat+", "+maxLng+")");
  var centerLat = (len>1) ? (maxLat-(-minLat))/2 : maxLat;
  var centerLng = (len>1) ? (maxLng-(-minLng))/2 : maxLng;
  var centerLatlng = new GLatLng(centerLat, centerLng);

   if (len>1) {
	  var lat1 = new GLatLng(minLat,minLng);
	  var lat2 = new GLatLng(maxLat,maxLng);
	  var dis = parseFloat(lat1.distanceFrom(lat2)/1000);
            // нужно найти как определить масштаб с помощью google функций
            if (dis < 0.5) scale = 16;
            else if (dis < 2) scale = 15;
            else if (dis < 2.5) scale = 14;
            else if (dis < 6) scale = 13;
            else if (dis < 12) scale = 12;
            else if (dis < 26) scale = 11;
            else if (dis < 64) scale = 10;
            else if (dis < 96) scale = 9;
            else if (dis < 128) scale = 8;
            else if (dis < 256) scale = 7;
            else if (dis < 512) scale = 6;
            else if (dis < 1024) scale = 5;
            else if (dis < 2048) scale = 4;
            else if (dis < 4096) scale = 3;
            else if (dis < 8192) scale = 2;
            else scale = 1;

	  			//alert(dis)
	        //var polyline = new GPolyline([lat1, lat2], "#ee5555", 5, 0.5);
             // map.addOverlay(polyline);
       	      //alert(polyline.getLength());
   }
   if (scale>0) map.setCenter(centerLatlng, scale);
   else map.setCenter(centerLatlng);

   window.setTimeout(function() { map.panTo(centerLatlng); }, 1000);
   window.setTimeout(function() { showErrors(); }, 2000);

} else {
	map.setCenter(new GLatLng(0,0), 1);
	setTimeout("if (len<1) close_message('info', 'Невозможно отобразить');",400);
	}


}



/// ПОКАЗАТЬ ОШИБКИ
function showErrors(){
   var text = ''; var j = 0;
   if (mapErrors.length>1) {
      for (var i=0; i<mapErrors.length; i++) if (mapErrors[i]) {
      	text += ' &nbsp; &nbsp; &nbsp; '+(++j)+'. '+mapErrors[i]+'<br>';
        if (j >= 20) { text += ' &nbsp; &nbsp; &nbsp; ....<br> &nbsp; &nbsp; &nbsp; Всего не найдено адресов: '+mapErrors.length+''; break; }
      } else if (mapErrors.length == 1) text = mapErrors[0];

   	  if (mapErrors.length == markers.length && mapErrors.length>0 && markers.length==0) text = 'Ни один пункт Мигом не был найден на карте';
   	  else if (mapErrors.length < markers.length) text = 'Некоторые адреса не были найдены на карте:<br> &nbsp; &nbsp; &nbsp; (возможно адресов нет на карте, либо сервис перегружен)<br>'+text;
   	  else if (mapErrors.length == 1) text = "Адрес: \"" + text + "\" не найден";
	  else if (text) text = 'Некоторые адреса не были найдены на карте:<br> &nbsp; &nbsp; &nbsp; (возможно адресов нет на карте, либо сервис перегружен)<br>'+text;
   	  if (text) close_message('info', text);

   } else close_message();

}


function pause(ms){
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < ms);
}

function AddPoints(points){
	clearMarkers();
	if (points == undefined) {
		address = $("addressTEXT").value;
		showAddress(address);
	} else {
	   var len = points.length;
	   /*var ci = get_scale(points);
		//alert(points);
		geocoder.getLatLng(
		points,
	    function(latlng) {
	      if (!latlng) {
	      	mapErrors.push(points);
	      	close_message();
	      } else {
			map.setCenter(latlng, ci); //new GLatLng(0,0)
		  }
		}
	  	);*/
	   var last = 0;
	  
	   if (len>0) for (var i=0; i<len; i++) if (points[i]) {
	   	     //if (i%20==0 && i>0) pause(150);
	   	     if (len>1) last = (i==0)? 2: 0;
	   	     else if (i == (len-1)) last = len;
	   		 showAddress(points[i], false, i, last);
	   		 //close_message('info', points[i]);
	   }

	   //delay(1500); //scaleMarkers();
	   //var del = len*40;
	   //del = ((del<1000) ? 1000 : ((del>1800) ? del : 1800));
	   //del = ((del<1000) ? 1000 : ((del>1800) ? ((del>5000) ? 5000 : del) : 1800));
	   //window.setTimeout(function() {scaleMarkers();}, del);
	}
}

/* ФУНКЦИИ РАБОТЫ С КАРТОЙ >>>> */