var count = 0;
var map;
var points = new Array();
var markers = new Array();
var newmark = [];
var ad = '';

var code = '';

var poly;	//для приватки 
var polyArr = [];	
var boundZ;	//прямоугольник чтобы увидеть все объекты

var tooltip;
var lineColor = "#004184";
var fillColor = "#9DAFC8";
var lineWeight = 1;
var lineOpacity = .9;
var fillOpacity = .5;
var geocoder = null;

var mode = 1;
var showMe = 0;

function load(c) {
		mode = c;
		if(document.getElementById("map")){
	      if (GBrowserIsCompatible()) {
	        map = new GMap2(document.getElementById("map"));
             map.addControl(new GLargeMapControl()); // Zoom control
              map.addMapType(G_PHYSICAL_MAP);
			 // Create a hierarchical map type control
			 var hierarchy = new GHierarchicalMapTypeControl();
			 // make Hybrid the Satellite default
			 hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", true);
			 // add the control to the map
			 map.addControl(hierarchy);

			 map.addControl(new GScaleControl()); // Scale bar
		 //	 map.disableDoubleClickZoom();
			 geocoder = new GClientGeocoder(); 

			map.setCenter(new GLatLng(59.939039, 30.315785), 13);
			if(mode==0)
			 GEvent.addListener(map, "click", leftClick);
	          // Add a div element for toolips
			 tooltip = document.createElement("div");
			 tooltip.className="tooltip";
			 map.getPane(G_MAP_MARKER_PANE).appendChild(tooltip);
			 map.disableScrollWheelZoom();
			 
			 
			if(document.getElementById("coords") && document.getElementById("coords").value!="")
				showPoly(document.getElementById("coords").value);
			if(typeof(info)!="undefined" && info.items.length>0){
				boundZ = new GLatLngBounds();
				getProjects();
			}					
	      }
	  }
    }
function showPoly(coords,index){
    var points = decodeLine(coords.substr(coords.indexOf("%%")+2));
    decodeLevels(coords.substring(0,coords.indexOf("%%")));	
	
	if(mode==0)
		for(var i=0; i<points.length; i++){
			leftClick(null,new GPoint(points[i][1],points[i][0]));		
		}
	else{
		var newPoints = []
		for(var i=0; i<points.length; i++){
			newPoints.push(new GPoint(points[i][1],points[i][0]));					
		}
		drawOverlay(newPoints,index);	
	}
	
}
function getProjects(){	
	for(var i=0; i<info.items.length; i++){
		showPoly(info.items[i].coords,i);		
	}	
		map.setCenter(boundZ.getCenter(), map.getBoundsZoomLevel(boundZ));
		
}

function decodeLine (encoded) {
  var len = encoded.length;
  var index = 0;
  var array = [];
  var lat = 0;
  var lng = 0;

  while (index < len) {
    var b;
    var shift = 0;
    var result = 0;
    do {
      b = encoded.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
    lat += dlat;

    shift = 0;
    result = 0;
    do {
      b = encoded.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
    lng += dlng;

    array.push([lat * 1e-5, lng * 1e-5]);
  }

  return array;
}

// Decode an encoded levels string into a list of levels.
function decodeLevels(encoded) {
  var levels = [];

  for (var pointIndex = 0; pointIndex < encoded.length; ++pointIndex) {
    var pointLevel = encoded.charCodeAt(pointIndex) - 63;
    levels.push(pointLevel);
  }

  return levels;
}
function showAddress(address) {  
	var z = 0;
	var x;   
	
	for (var i=0; i<markers.length; i++){  
		if(markers[i].name.search(RegExp(address,"i"))!=-1){
  			markers[i].show();
			if(typeof(markers[i].l)!='undefined')
			markers[i].l.show();
			tooltip.style.display = "none";
			z++; 
			x = i;    
  		}   
		else{
			markers[i].hide();	
			if(typeof(markers[i].l)!='undefined')
			markers[i].l.hide();				
		}                 
	}       
	if(z==1){          
		var tx;
		for(var i=0; i<objects[x].length; i++){
			tx += " "+ objects[x][i];
		}
	  //s	alert(objects[x][objects[x].length-1])
		//var point = new GLatLng(objects[x]['x'], objects[x]['y'])
		var point = new GLatLng(objects[x][objects[x].length-2], objects[x][objects[x].length-1])
	   	map.setCenter(point, 15);
		showTooltip(markers[x]) 
	}
	else if(z>1){
		map.setCenter(new GLatLng(59.939039, 30.315785), 13);
	}


   if (geocoder && z==0) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " пїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅ");
            } else {
              map.setCenter(point, 13);
             // var marker = new GMarker(point, {draggable:false, bouncy:false, dragCrossMove:false});
             // GEvent.addListener(marker, "click", function() {alert(point)  });
             // map.addOverlay(marker);
             // marker.openInfoWindowHtml(address);
			  leftClick(null,point,address)
            }
          }
        );
      }   
    }

function addIcon(icon) { // Add icon attributes
//if(mode==1){
 icon.iconSize = new GSize(24, 32);
 	icon.iconAnchor = new GPoint(0, 32);
 icon.infoWindowAnchor = new GPoint(0, 32);
/* }
 else{
  	icon.iconSize = new GSize(24, 32);
	icon.iconAnchor = new GPoint(12, 32);
 	icon.infoWindowAnchor = new GPoint(12, 32);
 }*/
}

function drawOverlay(newPoints,index){		
	if(mode==0 && poly) 	//в приватке остаться должен только адин
		map.removeOverlay(poly);
	
	points.length = 0;

	if(mode==0){
		for(i = 0; i < markers.length; i++) {
			points.push(markers[i].getLatLng());  
		}  
		points.push(markers[0].getLatLng());
	}
	else{
		points = newPoints;
		points.push(points[0]);
	}


	if(mode==0){	
		poly = new GPolygon(points, lineColor, lineWeight, lineOpacity, "#9DAFC8", fillOpacity);
		
		////////////////////////////определение центра координат
		 var mlat = 0;
		 var mlng = 0;	 

		for(i = 0; i < poly.getVertexCount(); i++) {
			mlat += poly.getVertex(i).lat();
			mlng += poly.getVertex(i).lng();
		}
		
		mlat = mlat/poly.getVertexCount();
		mlng = mlng/poly.getVertexCount();
		/////////////////////////////////////
		
		if(showMe==0){				///типа центрировать только при первом показе
			map.setCenter(new GLatLng(mlat, mlng),13);
			showMe++
		}
		map.addOverlay(poly);
		
		createEncodings();
	}
	else
		createPoly(index);	
}


function createPoly(index){
	var poly = new GPolygon(points, lineColor, lineWeight, lineOpacity, "#9DAFC8", fillOpacity);
	polyArr.push(poly);	
	map.addOverlay(poly);
	
	var icon = new GIcon();
	icon.image = "/private/templates/images/0flag.gif";    
	addIcon(icon);
	var marker = new GMarker(poly.getVertex(0), {icon:icon, draggable:false, bouncy:false, dragCrossMove:true});
	map.addOverlay(marker);


	
	poly.name = info.items[index].name;
	poly.service_id = info.items[index].service_id;
	
	if(pro_id && info.items[index].id==pro_id){
		for(i = 0; i < poly.getVertexCount(); i++) {
			boundZ.extend(poly.getVertex(i));	
		}	
		var icon = new GIcon();
		icon.image = "/private/templates/images/0flag.gif";    
		addIcon(icon);
		var marker = new GMarker(poly.getVertex(0), {icon:icon, draggable:false, bouncy:false, dragCrossMove:true});
		map.addOverlay(marker);
	}
	else if(!pro_id || pro_id==0)
		boundZ.extend(poly.getVertex(0));	

	
	
	GEvent.addListener(poly, "click", function() {
	location.href = info.items[index].link;
	});
	GEvent.addListener(marker, "click", function() {
	location.href = info.items[index].link;
	});
	GEvent.addListener(marker, "mouseover", function() {
	showTooltip(poly);
	}); 
	GEvent.addListener(marker, "mouseout", function() {
	tooltip.style.display = "none";
	});
	GEvent.addListener(poly, "mouseover", function() {
	showTooltip(poly);
	}); 
	GEvent.addListener(poly, "mouseout", function() {
	tooltip.style.display = "none";
	});
}

function flashPoly(val){
	for (var i=0; i<polyArr.length; i++){
		if(polyArr[i].service_id.search(val)!=-1){
		   //	coloring(polyArr[i],"#9CD9D0")
			
			
		var icon = new GIcon();
		icon.image = "/private/templates/images/0flag.gif";
		addIcon(icon);
		var marker = new GMarker(polyArr[i].getVertex(0), {icon:icon, draggable:false, bouncy:false, dragCrossMove:true});
		map.addOverlay(marker);
			
			
			
			}
		else{
	   //	coloring(polyArr[i],"#9DAFC8" )	
		var icon = new GIcon();
		icon.image = "/private/templates/images/1flag.gif";
		addIcon(icon);
		var marker = new GMarker(polyArr[i].getVertex(0), {icon:icon, draggable:false, bouncy:false, dragCrossMove:true});
		map.addOverlay(marker);
		}
		  
	}
}

function coloring(poly,col){
	poly.color = col;
	poly.redraw(true);
}

function leftClick(overlay, point) {   //   document.getElementById("point").innerHTML = point;
 if(point) {
 // points.push(point);
  count++;
  // Light blue marker icons
  var icon = new GIcon();
  icon.image = "/private/templates/images/0flag.gif";//mark.png";
  addIcon(icon);
  // Make markers draggable

  var marker = new GMarker(point, {icon:icon, draggable:true, bouncy:false, dragCrossMove:true});
  map.addOverlay(marker);
  marker.content = count;
  markers.push(marker);

  marker.tooltip = "Point "+ count;
  // Drag listener
 GEvent.addListener(marker, "drag", function() {
   //tooltip.style.display= "none";
    createEncodings();
	drawOverlay();
  });
   GEvent.addListener(marker, "mouseout", function() {
     createEncodings();
  });

  // Second click listener
 GEvent.addListener(marker, "click", function() {
   tooltip.style.display = "none";

  // Find out which marker to remove
  for(var n = 0; n < markers.length; n++) {
   if(markers[n] == marker) {
    map.removeOverlay(markers[n]);
    break;
   }
  }
  // Shorten array of markers and adjust counter
  markers.splice(n, 1);
  if(markers.length == 0) {
    count = 0;
  }
   else {
    count = markers[markers.length-1].content;
    drawOverlay();
  }
  }); 
 drawOverlay();
 
 }
}

function createEncodings() {
  var i = 0;

  var plat = 0;
  var plng = 0;

  var encoded_points = "";
  var encoded_levels = "";
  
  for(i = 0; i < points.length-1; i++) {
    var point = points[i];
    var lat = point.lat();
    var lng = point.lng();
    var level = 3;
	
    var late5 = Math.floor(lat * 1e5);
    var lnge5 = Math.floor(lng * 1e5);

    dlat = late5 - plat;
    dlng = lnge5 - plng;

    plat = late5;
    plng = lnge5;

    encoded_points += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
    encoded_levels += encodeNumber(level);
  }

 
  code = encoded_levels+"%%"+encoded_points
    document.getElementById("coords").value = code;
}

function encodeSignedNumber(num) {
  var sgn_num = num << 1;

  if (num < 0) {
    sgn_num = ~(sgn_num);
  }

  return(encodeNumber(sgn_num));
}

function encodeNumber(num) {
  var encodeString = "";

  while (num >= 0x20) {
    encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
    num >>= 5;
  }

  encodeString += (String.fromCharCode(num + 63));
  return encodeString;
}

function showTooltip(poly) { // Display tooltips

	// tooltip.innerHTML = poly.name;
	 tooltip.style.display = "block";

	 // Tooltip transparency specially for IE
   /*	 if(typeof(tooltip.style.filter) == "string") {
		tooltip.style.filter = "alpha(opacity:50)";
	 }    */

	 
	 var mlat = 0;
	 var mlng = 0;	 

	for(i = 0; i < poly.getVertexCount(); i++) {
		mlat += poly.getVertex(i).lat();
		mlng += poly.getVertex(i).lng();
	}	
	mlat = mlat/poly.getVertexCount();
	mlng = mlng/poly.getVertexCount(); 
	
	var currtype = map.getCurrentMapType().getProjection();
	var point= currtype.fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	 

	 
//	 var offset= currtype.fromLatLngToPixel(poly.point,map.getZoom());
	
	var offset= currtype.fromLatLngToPixel(new GLatLng(mlat,mlng),map.getZoom());
		 
	 
	//map.openInfoWindow(new GLatLng(mlat,mlng),document.createTextNode("пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ, пїЅпїЅпїЅ!")); 
	
	var ics=[];
	
	tooltip.innerHTML = "<p style='border:1px solid #004184; width:242px; font-size:12px; color: #004184; padding:5px; background-color:#eee;'>"+poly.name+"</p>";
	
	 
	 var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x, offset.y- point.y));
	 pos.apply(tooltip);
}

function updatecoords(){
       	newmark[0].setLatLng(markers[0].getLatLng())
			document.getElementById("coords").value = newmark[0].getLatLng()
		
			
	   	geocoder.getLocations(newmark[0].getLatLng(), showAddress2); 
		
}

function showall() { 
     count = 0;
	 points.length = 0;
	 markers.length = 0;
     map.clearOverlays();
       for(var i=0; i<newmark.length; i++){
        	leftClick(null,newmark[i].getLatLng(),1)
          }   

}

function showAddress2(response) {                                        
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
  //  marker = new GMarker(point);
 //   map.addOverlay(marker);
  //  marker.openInfoWindowHtml(place.address);
  //	leftClick(null,point) 
  			markers[0].openInfoWindowHtml(place.address);  
  }
}
function resize(){ 
  if(typeof(map)!="undefined" && navigator.appName.search("Microsoft")!=-1){
   map.checkResize();	
   map.setCenter(new GLatLng(59.939039, 30.315785), 13);
   draw()
   }
}
