/*var gm_prefix = "";
var gm_encodedelement = "";
var gm_points = [];
var gm_marker = null;
var highlighted_gm_marker = null;
var point_gm_markers = [];
var gmzc_icons = [];*/

function gm_GetElement(id) {
	var obj = document.getElementById(gm_prefix+id);
	if (obj) {
		return obj;
	} else {
		objlist = document.getElementsByName(gm_prefix+id);
		if (objlist.length>0) {
			obj = objlist.item(0);
			return obj;
		}
	}
	return false;
}

function gm_GetValue(id) {
	if (obj = gm_GetElement(id)) {
		return obj.value;
	} else {
		return "";
	}
}
function gm_SetValue(id,newValue) {
	if (obj = gm_GetElement(id)) {
		obj.value = newValue;
		return true;
	} else {
		return false;
	}	
}

function prepare_gm_GoogleMap(map) {
	document.map = map;
	gmzc_edit_initbuttons();
}


function gmzc_BtnState(elemid,text,enabled) {
	if (obj = gm_GetElement(elemid)) {
		if (enabled!=null) obj.disabled = !enabled;
		if (text!=null) obj.value = text;
		return obj;
	} else return false;	
}

function gmzc_edit_startdraw() {
	var ffversion=0;
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		 var ffversion=new Number(RegExp.$1); // capture x.x portion and store as a number
		 if (ffversion<3) {
			 alert("Su versión de Firefox no permite modificar el trazado \n \n \nNecesita Firefox 3.0");
			 return false;
		 }
	} else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		 alert("Su navegador no permite modificar el trazado (IE "+ieversion+") \n \n \nNecesita Firefox 3.0");
		 return false;
	} else {
		 alert("Su navegador no permite modificar el trazado \n \n \nNecesita Firefox 3.0");
		 return false;
	}

	
	
	if (!document.gmzc_polyline) {
		document.gmzc_polyline = new google.maps.Polyline([]);
		document.gmzc_polyline.setMap(document.map);
		alert("El mapa aún no tiene ningún recorrido\n\nPara crear el punto de inicio, pulse el botón derecho del ratón\nCada vez que pulse el botón derecho en un lugar del mapa creará un nuevo punto\nSi quiere borrar un punto, pulse el botón derecho encima de él");
	}
	
	gmzc_changepolyline();
	
	var p = document.gmzc_polyline;
	p.runEdit(true);
	gmzc_BtnState("btn_gmap_draw","Dibujando...",false);
	gmzc_BtnState("btn_gmap_stopdraw","Finalizar edición",true);
	google.maps.event.addListener(p,"lineupdated",function() {
		gmzc_edit_savepolyline();
	});	
	if (document.gmzc_markerStart) {
		document.gmzc_markerStart.hide();
	}
	if (document.gmzc_markerEnd) {
		document.gmzc_markerEnd.hide();
	}	
}

function gmzc_changepolyline() {
	if (!document.gmzc_polyline) return false;
	var p = document.gmzc_polyline;
	encoded_points = google.maps.geometry.encoding.encodePath(p.getPath());
	encoded_points = prompt('Escriure polylinea codificada:',encoded_points);
	if (encoded_points!=null && encoded_points!="") {
		plcm = new google.maps.geometry.encoding.decodePath(encoded_points);
		np = new google.maps.Polyline({path: plcm});
		np.setMap(document.map);
		p.setMap(null);
		document.gmzc_polyline = np;
	}
}

function gmzc_edit_initbuttons() {
	gmzc_BtnState("btn_gmap_draw","Modificar",true);
	gmzc_BtnState("btn_gmap_stopdraw","Finalizar edición",false);
}

function gmzc_edit_enddraw() {
	if (!document.gmzc_polyline) return false;
	document.gmzc_polyline.stopEdit();
	gmzc_edit_initbuttons();
}

google.maps.Polyline.prototype.getBounds = function() {
	  var bounds = new google.maps.LatLngBounds();
	  this.getPath().forEach(function(e) {
	    bounds.extend(e);
	  });
	  return bounds;
	};

	google.maps.LatLng.prototype.mTo = function(a){
	    var e = Math, ra = e.PI/180;
	    var b = this.lat() * ra, c = a.lat() * ra, d = b - c;
	    var g = this.lng() * ra - a.lng() * ra;
	    var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos
	(c) * e.pow(e.sin(g/2), 2)));
	    return f * 6378137;
	  };

	  google.maps.Polyline.prototype.inM = function(n){
	    var a = this.getPath(n), len = a.getLength(), dist = 0;
	    for(var i=0; i<len-1; i++){
	      dist += a.getAt(i).mTo(a.getAt(i+1));
	    }
	    return dist;
	  }; 
	  
function gmzc_edit_savepolyline() {
	if (!document.gmzc_polyline) return false;
	var p = document.gmzc_polyline;
	//enc = google.maps.geometry.encoding.encodePath(p.getPath());
	enc = gmzc_encode_polyline(p);
	if (latlngbounds = p.getBounds()) { 
		gm_SetValue('lat_ne',latlngbounds.getNorthEast().lat());
		gm_SetValue('lng_ne',latlngbounds.getNorthEast().lng());
		gm_SetValue('lat_sw',latlngbounds.getSouthWest().lat());
		gm_SetValue('lng_sw',latlngbounds.getSouthWest().lng());
	}
	gm_SetValue(gm_encodedelement,enc);
	points = p.getPath().getLength();
	gm_SetValue("points",points+" puntos");
	if (points>0) {
	m = p.inM();
		gm_SetValue(gm_encodedelement+"_length",m);
		if (m>1000) {
			gm_SetValue('length',(m/1000).toFixed(2)+" Km");
		} else {
			gm_SetValue('length',m.toFixed(0)+" metros");
		}
	}
}

function gmzc_encode_polyline(poly) {
	encoded_points = google.maps.geometry.encoding.encodePath(poly.getPath());
	document.gmzc_encoded_polyline = encoded_points;
    return "<poly>"+encoded_points+"</poly><vertexscount>"+poly.getPath().getLength()+"</vertexscount>";	  
}


function gmzc_search_address(address) {
	if (!address) {
	  var address = gm_GetValue('txtAddress');
	}
	  if (address.length > 0) {
	    var geocoder = new google.maps.Geocoder();
	    geocoder.geocode( { 'address': address}, function(results, status) {
	        if (status == google.maps.GeocoderStatus.OK) {
	          document.map.setCenter(results[0].geometry.location);
	          document.map.setZoom(13);
	          gm_SetValue("lat",results[0].geometry.location.lat());
	          gm_SetValue("lng",results[0].geometry.location.lng());
	        } else {
	          alert('El lugar "' + address + '" no se ha encontrado en el mapa\n' + status);
	        }
	      });

	  }
}


