// Google


//Modos Clik 
var type; 
var lat;
var lng;
var tz;
var custommap;
var clickMode = 0;
//1.- Creando ruta

function google_Init(){
	getServiceStatus();
}

function google_processVars(URL){
	var arr=URL.split("?");
	arr=arr[1].split("&");
	var temp=arr[1].split("=");
	type=temp[1];
	temp=arr[2].split("=");
	lat=temp[1];
	temp=arr[3].split("=");
	lng=temp[1];
	temp=arr[4].split("=");
	tz=temp[1];
	//alert("LAT:"+lat+"LNG:"+lng+"TYPE:"+type+"TZ:"+tz);
}

function getNavigator(){
	var isIE6=false;	
	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
 		if (ieversion<7){
  			isIE6=true;
			ext="_ie6.html";	
		}else{
			ext="_nr.html";
		}
	}else{
		ext="_nr.html";
	}
	return isIE6;
}

function continue_init(){
		
		//Quitar en producción
		status =2;

		if (fromID==true){
			document.getElementById('init').style.background='url(http://admin.micodata.es/MicodataSIG/img/Idinit.png)';
		}
		
		if (fromIDadmin==true){
			
		}else{
			if (status==2){
				document.getElementById('init').style.background='url(http://admin.micodata.es/MicodataSIG/img/noprod.png)';
				if (getNavigator()==true){
					document.getElementById('init').style.behavior= 'url(fx-iepngfix.htc)';	
				}
			}
			
			V('b1');
			V('init');
		}
		
		
		
		species_getArray();
		users_getUserUniqueID(); 
		zoom_get(user);
		zoom_drag_initArray();
		google_load();
		
		if (fromIDadmin==true){
			if (type==0){
				LatLngToUTM();
			}else if(type==1){
				alert("No se puede convertir");
			}else{
				LatLng();
			}
		}
		
		if (fromID==true){
			V('coords');
			unids=3;
			google_SetCoords();
		}
		
		
}

function google_End(){
	users_chStatus("8","0");
	GUnload();
}




function google_load() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(42.17154633452751 ,  -4.691162109375), zoomMin);
		zoom=zoomMin;
		map.setMapType(G_HYBRID_MAP);
		map.continuousZoomEnabled();
		map.enableDoubleClickZoom();
		map.enableScrollWheelZoom();
		GEvent.addListener(map, "zoomend", function(){ google_isOnZoom();});
		GEvent.addListener(map, "click", function(layer,point){ google_clickDistpatcher(layer, point);});
	   }else{
	  	alert("Navegador no compatible, descarge Firefox");
	  }
    }
		
function google_clickDistpatcher(mylayer, mypoint){
	//alert("dispatcher" + clickMode );
	updatecoords(mylayer,mypoint);
	switch (clickMode) {
    	case 0:
       		//Modo normal no se hace nada
			map.getDragObject().setDraggableCursor("default");
       		break
    	case 1:
       		//Modo Ruta
			map.getDragObject().setDraggableCursor("crosshair"); 
			users_chStatus("2",mypoint.lat()+":"+mypoint.lng());
			google_drawRoute(mypoint);
       		break
		case 2:
			//Modo GetFeature
			get_info(mypoint);
		    break
    	default:
       		alert("¿?HOLHOHLHOHLHOHLHOHLHO");
			break
	} 
}

function google_set_cursor(){
	if (map != null){
		switch (clickMode) {
    		case 0:
       			//Modo normal no se hace nada
				map.getDragObject().setDraggableCursor("default");
       			break
    		case 1:
       			//Modo Ruta
				map.getDragObject().setDraggableCursor("crosshair"); 
       			break
			case 2:
				//Modo GetFeature
				map.getDragObject().setDraggableCursor("crosshair"); 
		    	break
    		default:
				break
			} 
		}
}

function info_changed(){
	if (document.getElementById("fi").checked == true){
		clickMode =2;
	}else{
		clickMode =0;
	}
		map.clearOverlays();
}

function get_info(latlng) {
	
	map.clearOverlays();
	var icono = new GIcon();
 	icono.image = icnPath + "comment.png";
 	icono.iconSize = new GSize(32, 32);
 	icono.iconAnchor = new GPoint(24, 30);
 	icono.infoWindowAnchor = new GPoint(24, 30);
    
	var marker = new GMarker(latlng, {draggable:false, icon:icono});
    //GEvent.addListener(marker, 'click', function() {V('featureInfo');});
	
	map.addOverlay(marker);
	
	var zm = map.getZoom(); 
	
	if(zm < 8) {
		zm=8;
	}
	
	V('featureInfo');
	O('featureInfoPos');
	O('featureInfoText');
	O('featureInfoProduction');
	V('featureInfoDrag')
	V('featureInfoWait');
	V('featureInfoClose');
	ajax=nuevoAjax();
	ajax.open("POST", "includes/includesPHP/sig_getFeatureInfo.php",true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			var text = ajax.responseText;
			//alert(text);
			V('featureInfoPos');
			O('featureInfoWait');
			V('featureInfoPos');
			CT('featureInfoPos','<b>Latitud: </b>'+ roundNumber(latlng.lat(),6)+' <b>Longitud: </b>'+ roundNumber(latlng.lng(),6));
			V('featureInfoText');
			
			var txt= text.split("|");
			CT('featureInfoText',txt[1]);
			//CT('featureInfoText',"Estamos realizando labores de mantenimiento, esta información estará proximamente diponible.");
			V('featureInfoProduction');
			CT('featureInfoProduction', txt[0]);
			//map.openInfoWindow(latlng, info);
		  }
		}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send('lat='+latlng.lat()+'&lng='+latlng.lng()+'&z='+zm+'&url='+esp_load.myBaseURL+'&QueryLayers='+ esp_load.myQueryLayers.replace("&","#"));
} 

function replace(texto,s1,s2){
	return texto.split(s1).join(s2);
}

function google_isOnZoom(){
	//document.getElementById("debug").value = " Zoom: " + map.getZoom() + " MINIMO " + zoomMin + " Maximo " + zoomMax;
	zoom= map.getZoom();
	
	if (zoom<=zoomMax && zoom>=zoomMin){
		zoom_drag_moveTo(zoomInterval - (zoomMax-map.getZoom()));
	}
	
	if (zoom<zoomMin){
		map.setZoom(zoomMin);
	}
	if (zoom>zoomMax){
		map.setZoom(zoomMax);
	}
}

function google_changeLayer(chk){
	
	var layers=new Array();
	
	var esp_ch= document.getElementById("esp").checked;
	var sat_ch= document.getElementById("sat").checked;
	var pla_ch= document.getElementById("pla").checked;
	var ter_ch= document.getElementById("terr").checked;
	
	if (chk==4 && esp_load==null){
		V('specie');	
	}else{
		if(sat_ch==false && ter_ch==false){
			document.getElementById("sat").checked=true;
			document.getElementById("pla").checked=true;
			document.getElementById("terr").checked=false;
			showMessage("Debe seleccionar una capa base", "Se requiere que la capa satélite o terreno esté cargada, ahora se cargarán las capas por defecto", 0);
			google_changeLayer(1);
		}else{
		
		if (ter_ch == true && chk ==3){
			document.getElementById("sat").checked=false;
			document.getElementById("pla").checked=false;
			sat_ch=false;
			pla_ch=false;
		}
		
		if (ter_ch == true && chk <=2){
			if (chk==1){
			document.getElementById("sat").checked=true;
			document.getElementById("terr").checked=false;
			sat_ch=true;
			ter_ch=false;
			}
			if (chk==2){
			document.getElementById("sat").checked=true;
			document.getElementById("pla").checked=true;
			document.getElementById("terr").checked=false;
			sat_ch=true;
			pla_ch=true;
			ter_ch=false;
			}
		}
		
		
		if (sat_ch==true){
			layers.push(G_HYBRID_MAP.getTileLayers()[0]);
		}
	
		if (ter_ch==true){
			document.getElementById("pla").checked=false;
			pla_ch=false;
			layers.push(G_PHYSICAL_MAP.getTileLayers()[0]);
		}
	
		if (pla_ch==true && sat_ch==true && ter_ch==false){
			layers.push(G_HYBRID_MAP.getTileLayers()[1]);
		}
	
		if (esp_ch==true){
			if (esp_load != null){
				layers.push(esp_load);
			}else{
				V('specie');
			}
		}
	
		if (layers!=null){
			if (custommap!=null){
				map.removeMapType(custommap);
			}
			custommap = new GMapType(layers, G_SATELLITE_MAP.getProjection(), "", G_SATELLITE_MAP);
			map.getMapTypes().length = 0;
			map.addMapType(custommap);
    		map.setMapType(custommap);
		}
	
		if (esp_ch == true){
			openLegend();
		}
		
		}
	}
}

/*
*
*
* Funciones para la representación de Rutas
*
*/

var markers=[];
var ids=0;
var draw=false;
var mySteps;
var index;
var tot=0;

function google_drawRoute(punto) {
	if (punto){
		google_createMarker(punto, "Hola", 0);
		google_redib();
	}		
}

function google_createMarker(point, txt, mode) {
	
	  var icono = new GIcon();
 	  icono.image = icnPath + "flag.png";
 	  icono.iconSize = new GSize(29, 32);
 	  icono.iconAnchor = new GPoint(14, 30);
 	  icono.infoWindowAnchor = new GPoint(16, 32);
      var marker = new GMarker(point, {draggable:true, icon:icono});
         GEvent.addListener(marker, 'click', function() {
          marker.openInfoWindowHtml(txt);
       });
		 
	  GEvent.addListener(marker, "dragend", function() {
			if (ids!=-1){
			  markers[ids]= marker;
		   	ids=-1;
		  	google_redib();
		    }		 
 		 });

		GEvent.addListener(marker, "dragstart", function() { 
		for (i=0; i< markers.length; i++){
			if (markers[i].getPoint()==marker.getPoint()){
				markers[i]=0;
				ids=i;
			}
		 }
 		 });
	  if (mode==0){
		  markers.push(marker);
	  }
	  map.addOverlay(marker);
}

function google_redib(){
	
var total=0.0;
var points= [];

if (draw==true){
	map.clearOverlays();
}

for (var i=0; i< markers.length; i++){
	var p = markers[i].getPoint();
		if (i==0){
			var texto='<div align="center" style="font-family:Arial, Helvetica, sans-serif; font-size:10px;><strong>Este es el primer punto marcado.</strong><br/><strong>Latitud: </strong>'+p.lat().toString().substr(0,10)+'<br/><strong>Longitud: </strong>'+p.lng().toString().substr(0,10)+"</div>";
			google_createMarker(p, texto, 1);
		}else if(i==1) {
			var p2 = markers[i-1].getPoint();
			var esp=google_calcDist(p2.lat(), p2.lng(), p.lat(), p.lng());
			total+=esp;
			google_createMarker(p,'<div align="center" style="font-family:Arial, Helvetica, sans-serif; font-size:10px;><strong>Latitud: </strong>'+p.lat().toString().substr(0,10)+'<br/><strong>Longitud: </strong>'+p.lng().toString().substr(0,10)+'<br/><strong>Distancia al ultimo:</strong>'+((esp*1609)/1000).toString().substr(0,6)+' Km<br/><strong>Distancia total hasta el punto:</strong>'+((esp*1609)/1000).toString().substr(0,6) +" Km"+"</div>", 1);
		}else if(i>=2) {	
			var p2 = markers[i-1].getPoint();
			var esp=google_calcDist(p2.lat(), p2.lng(), p.lat(), p.lng());
			total+=esp;
			google_createMarker(p,'<div align="center" style="font-family:Arial, Helvetica, sans-serif; font-size:10px;><strong>Latitud: </strong>'+p.lat().toString().substr(0,10)+'<br/><strong>Longitud: </strong>'+p.lng().toString().substr(0,10)+'<br/><strong>Distancia al ultimo:</strong>'+((esp*1609)/1000).toString().substr(0,6)+' Km<br/><strong>Distancia total hasta el punto:</strong>'+((total*1609)/1000).toString().substr(0,6) +" Km"+"</div>", 1);
		}
		points.push(p.lat() + "," + p.lng());
}

if (points.length>1){
		document.getElementById('test').innerHTML = "";
		var direction=new GDirections(map, document.getElementById("test"));
		GEvent.addListener(direction, "load", function(){onGDirectionsLoad(direction)});
        GEvent.addListener(direction, "error", function(){handleErrors(direction)});
		GEvent.addListener(direction,"addoverlay", function(){for(var i =0; i< direction.getNumGeocodes(); i++){map.removeOverlay(direction.getMarker(i));}}); 
		direction.loadFromWaypoints(points);
	}

}

function google_calcDist(lon1,lat1,lon2,lat2) {
	    var r = 3963.0;
	    //var multiplier = currentUnit == "miles" ? 1 : MILESASKM;
	    var multiplier = 1;
	    return multiplier * r * Math.acos(Math.sin(lat1/57.2958) * Math.sin(lat2/57.2958) +     Math.cos(lat1/57.2958) * Math.cos(lat2/57.2958) * Math.cos(lon2/57.2958 - lon1/57.2958));
}

function handleErrors(direction){
	
	   if (direction.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + direction.getStatus().code);
	   else if (direction.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + direction.getStatus().code);	   
	   else if (direction.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + direction.getStatus().code);
	   else if (direction.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + direction.getStatus().code);
	   else if (direction.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + direction.getStatus().code);
	   else alert("An unknown error occurred.");
	}

function onGDirectionsLoad(direction){ 
		window.map.addOverlay(direction.getPolyline());
		draw=true;
		document.getElementById('routeinfogen').innerHTML = "Latitud inicial: "+ markers[0].getPoint().lat().toString().substr(0,10) + " Longitud inicial: " +  markers[0].getPoint().lng().toString().substring(0,10) + "<br>" + "Latitud final: "+ markers[markers.length -1].getPoint().lat().toString().substring(0,10) + " Longitud final: " +markers[markers.length-1].getPoint().lng().toString().substring(0,10) + "<br>" + "Distancia: <b>"+ direction.getDistance().html + "</b> Duraci" +"&oacute;" + "n: <b>" + direction.getDuration().html + "</b> Pasos:<b>" + direction.getRoute(0).getNumSteps() + "</b>";
		 mySteps=null;
		 mySteps=new Array();
		 index=0;
		 tot=-1;
		 for (u=0; u< direction.getNumRoutes(); u++){
			for (var e=0; e < direction.getRoute(u).getNumSteps(); e++ ) {
				mySteps.push(direction.getRoute(u).getStep(e));
				tot+=1;
		 	}		 
		 }
		 
		 //alert(tot);
		 //Fijamos el numero de pasos
		  document.getElementById('routeinfosteps').innerHTML = "0/" + tot;
		
		 //Instrucciones del primer paso
		 if (mySteps){
			 if (mySteps.length>0){ 
		 		document.getElementById('routeinfospc').innerHTML = mySteps[0].getDescriptionHtml() + "<br> Distancia: <b>" +  mySteps[0].getDistance().html + "</b> Tiempo: <b>" + mySteps[0].getDuration().html + "</b>";
				index=0;
				google_mvRoute(0);
			 }
		 }
	//	}
	}

function google_mvRoute(movement){
	//alert(movement);
	if(mySteps){
	if (movement == -1){
		if (index > 1){
			index-=1;
			google_chRoute();
		}else{
			index=0;
			google_chRoute();
		}
	}else if (movement == 1){
		//alert(index);
		if (index < mySteps.length-1){
			index+=1;
			google_chRoute();
		}else{
			index=mySteps.length -1;
			google_chRoute();
		}
	}
	}
}

function google_removeOL(){
	map.clearOverlays();
	document.getElementById('routeinfogen').innerHTML = "";
	document.getElementById('test').innerHTML = "";
	document.getElementById('routeinfospc').innerHTML = "";
	document.getElementById('routeinfosteps').innerHTML = "";
	mySteps=new Array();
	index=0;
	tot=0;
	draw=false;
	points=new Array();
	direction=null;
	markers=new Array();
}

function google_chRoute(){
	//alert(index);
	//alert(mySteps[index].getDescriptionHtml().replace("<br>", " "));
	document.getElementById('routeinfospc').innerHTML = mySteps[index].getDescriptionHtml().replace("<br>", " ").replace('<div class="">', '').replace('</div>', '') + " (Distancia: <b>" +  mySteps[index].getDistance().html + "</b> Tiempo: <b>" + mySteps[index].getDuration().html + ")</b>";
	document.getElementById('routeinfosteps').innerHTML = (index) + "/" + tot;
}

function google_PrintRoute(){
	newwindow=window.open(MyPath + "/includes/includesHTML/route.html","","width=400,height=400,scrollbars=yes");
	if (window.focus) {newwindow.focus()}
}

function google_ExportRoute(){
var txt="";
if (mySteps){
	
	for (var i = 0; i < mySteps.length; i++) {
		txt= txt + '<wpt lat="' + mySteps[i].getLatLng().lat() + '" lon="' +  mySteps[i].getLatLng().lng() + '">\n\t<name>'+ mySteps[i].getDescriptionHtml().replace(/<\/?[^>]+(>|$)/g, "").replace("&nbsp;","") +'</name>\n\t<desc> Distancia:' +  mySteps[i].getDistance().html.replace(/<\/?[^>]+(>|$)/g, "").replace("&nbsp;","") + ' Tiempo:' + mySteps[i].getDuration().html.replace(/<\/?[^>]+(>|$)/g, "").replace("&nbsp;","") + '</desc>\n\t<sym>Dot</sym>\n\t<ele>' + i + '</ele>\n</wpt>' + '\n';
	}
	//alert(txt)
	ajax=nuevoAjax();
	ajax.open("POST", "includes/includesPHP/sig_genGPX.php",true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			var text = ajax.responseText
			//alert(text);
			openLinktoDownload(text);
			}
	 	}

	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("XMLdata="+txt);
}

}

function openLinktoDownload(text){
	if (text!=""){
		//users_chStatus("2",text);
		newwindow=window.open(MyPath + "includes/includesPHP/sig_downFILE.php?mode=2&file="+text);
		if (window.focus) {newwindow.focus()}
	}
}


/*
*
*
*Funciones de Busqueda de direcciones, pueblos, ciudades, POI's...
*
*/
 // ====== Array for decoding the failure codes ======
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Correcto";
      reasons[G_GEO_MISSING_ADDRESS]    = "Dirección perdida: La direccion no se ha encontrado.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Dirección desconocida: No se ha podido encontrar una correspondencia geografica para la dirección.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Dirección no disponible:  La direccion requerida no ha podido ser devuelta debido a razones contractuales o legales.";
      reasons[G_GEO_BAD_KEY]            = "Google API Key erronea: la llave no es válida o no coincide con el dominio";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Demasiadas peticiones: Se ha excedido el cupo de peticiones desde esta IP.";
      reasons[G_GEO_SERVER_ERROR]       = "Error del servidor: El servidor no ha podido procesar la petición de geolocalización.";
      

function google_showAddress() {
	    var search = document.getElementById("search_string").value;
	    users_chStatus("3",search);
		map.clearOverlays();
	    var geo = new GClientGeocoder(null,"ABQIAAAA0qSqzpGSHZnZ_8oTkNtmMRTTzhOfj89cSV2YTRRX1yTuQc6UaBRCJmfTr-1ZPu6URWsJysMtOr5hkg"); 
        
        // ====== Perform the Geocoding ======      
		geo.setBaseCountryCode("ES");
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
              //document.getElementById("debug").value = "Found " +result.Placemark.length +" results";
              // Loop through the results, placing markers
			  var center=false;
              
			  for (var i=0; i<result.Placemark.length; i++) {
				try{
					if (result.Placemark[i].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName.toString().indexOf("Castilla y Le",0) >= 0 || result.Placemark[i].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName.toString().indexOf("CL",0) >= 0){
                		center=true;
						var icono = new GIcon();
 	  					icono.image = icnPath + "home.png";
 	  					icono.iconSize = new GSize(16, 16);
 	  					icono.iconAnchor = new GPoint(8, 16);
 	  					icono.infoWindowAnchor = new GPoint(8, 16);
						var p = result.Placemark[i].Point.coordinates;
						var txt = "<b>" + result.Placemark[i].address.toString().replace("Spain", "Espa&ntilde;a") + "</b><br> <b>Lat: </b>" + p[1].toString() + " <br><b>Lng: </b>" + p[0].toString();
						var marker = new GMarker(new GLatLng(p[1],p[0]), {draggable:false, icon:icono});
         				GEvent.addListener(marker, 'click', function() {
          				marker.openInfoWindowHtml(txt);
       					});	
						map.addOverlay(marker);
					//
                	//var marker = new GMarker(new GLatLng(p[1],p[0]));
                	//document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
                	//map.addOverlay(marker);
					}
				}catch (error){}
              
			  if (center==true){
              	var p = result.Placemark[0].Point.coordinates;
              	map.setCenter(new GLatLng(p[1],p[0]),14);
			  }
			  
			  }
			  //draw_search_result(points);
              // centre the map on the first result
			  
            }
            // ====== Decode the error status ======
            else {
				 
				 
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
				showMessage('Aviso de la busqueda',reasons[result.Status.code] , 1);
              } 

            }
          }
        );
    }
	
	
/*
*
*
*Coordenadas
*
*
*/

//Variables

var UTMx=0;
var UTMy=0;
var DECx=0;
var DECy=0;
var SEXx=0;
var SEXy=0;
var hem;
var UTMScaleFactor = 0.9996;
var pi = 3.14159265358979;
var sm_a = 6378137.0;
var sm_b = 6356752.314;
var sm_EccSquared = 6.69437999013e-03;
var unids=2;
var marking=true;
//

function google_ChangeCoords(){
	if ( document.getElementById('rCDec').checked==true){
		unids=1;
	}else if(document.getElementById('rCSex').checked==true){
		unids=2;
	}else{
		unids=3;
	}
}

function google_SetCoords(){
	if (unids==1){
	document.getElementById('rCDec').checked=true;
	}else if(unids==2){
	document.getElementById('rCSex').checked=true;
	}else{
	document.getElementById('rCUtm').checked=true;
	}
}

function updatecoords(marker, point){	

if (point){

//Leemos las coordenadas y las dejamos como en google
if(marking){


Lpoint=point;

DECx=point.lat();

DECy=point.lng();

	if (unids==1){
		DEC();
	}

	if (unids==2){
		SEX();
	}

	if (unids==3){
		UTM();
	}

}
}

}

function formatear_angulo(ang, prec, sig_g, sig_m, sig_s) {

	var ang, g, m, s;

	prec = Math.pow(10, prec);

	ang = Math.abs(ang);

	g = Math.floor(ang);

	m = Math.floor(60*(ang-g));

	s = Math.floor(3600*prec*(ang - g - m/60))/prec;

	return g+sig_g + m+sig_m + s+sig_s;

}

function DEC(){

	var p1, p2;	

		var tstlat=DECx.toString();

		var tstlng=DECy.toString();

		p1=tstlat.split(".");

		p2=tstlng.split(".");
		
		document.getElementById("coordstxt").innerHTML= '<div style="font-family:Arial, Helvetica, sans-serif ; font-size:11px; color: #FFFFFF;"><b>Latitud:</b> ' + p1[0] + "." + p1[1].substring(0, 8) + " <br><b>Longitud:</b> " + p2[0]+ "." + p2[1].substring(0, 8);

	}

function SEX() {

	var lat, lng, labs, g, h, m, s, x, latitud, longitudg, longitudh;

	lat = Math.round(parseFloat(DECx)*1e6)/1e6;

	latitud = formatear_angulo(parseFloat(DECx), 2, "&deg; ", "' ", "\" &nbsp;");

	x = lat > 0 ? "N " : (lat==0?"":"S ");

	latitud = latitud + x;

    lng = Math.round(parseFloat(DECy)*1e6)/1e6;

    longitudg = formatear_angulo(parseFloat(DECy), 2, "&deg; ", "' ", "\" &nbsp;");

	x = lng < 0 ? "W" : (lng==0?"":"E");

	longitudg = longitudg + x;

	longitudh = formatear_angulo(parseFloat(DECy)/15, 3, "<sup>h</sup> ", "<sup>m</sup> ", "<sup>s</sup>");

	x = lng < 0 ? "-" : "+";

	longitudh = x + longitudh;

	SEXx=latitud;

	SEXy=longitudg;

	var p1, p2;

	document.getElementById("coordstxt").innerHTML= '<div style="font-family:Arial, Helvetica, sans-serif ; font-size:11px; color: #FFFFFF;"><b>Latitud:</b> ' + SEXx.toString() + " <br><b>Longitud:</b> " + SEXy.toString();

}

function UTM(){

	var zne;

	var xy = new Array(2);

	xy[0]=DECx;

	xy[1]=DECy;



	if (DECx < 0){hem="Sur";}else{hem="Norte";}

	zne = Math.floor ((DECy + 180.0) / 6) + 1

    zone = LatLonToUTMXY (DegToRad (DECx), DegToRad (DECy), zne, xy);

}

function UTMCentralMeridian (zone)

    {

        var cmeridian;



        cmeridian = DegToRad (-183.0 + (zone * 6.0));

    

        return cmeridian;

    }
	
function RadToDeg (rad)

    {

        return (rad / pi * 180.0)

    }

function DegToRad (deg)

    {

        return (deg / 180.0 * pi)

    }

function LatLonToUTMXY (lat, lon, zone, xy)

    {

        MapLatLonToXY (lat, lon, UTMCentralMeridian (zone), xy);



        /* Adjust easting and northing for UTM system. */

        xy[0] = xy[0] * UTMScaleFactor + 500000.0;

        xy[1] = xy[1] * UTMScaleFactor;

        if (xy[1] < 0.0)

            xy[1] = xy[1] + 10000000.0;

		var p1, p2;	

		var tstlat=xy[0].toString();

		var tstlng=xy[1].toString();

		p1=tstlat.split(".");

		p2=tstlng.split(".");

		var txt="<b>Zona:</b> "+ zone + " (" + hem +")";
		
		document.getElementById("coordstxt").innerHTML= '<div style="font-family:Arial, Helvetica, sans-serif ; font-size:11px; color: #FFFFFF;"><b>Latitud:</b> ' + p1[0]+"."+p1[1].substring(0, 2) + " <b>Longitud:</b> " + p2[0]+"."+p2[1].substring(0, 2) + "<br>" + txt + '</div>';

		return zone;

		

    }

function MapLatLonToXY (phi, lambda, lambda0, xy)

    {

        var N, nu2, ep2, t, t2, l;

        var l3coef, l4coef, l5coef, l6coef, l7coef, l8coef;

        var tmp;



        /* Precalculate ep2 */

        ep2 = (Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0)) / Math.pow (sm_b, 2.0);

    

        /* Precalculate nu2 */

        nu2 = ep2 * Math.pow (Math.cos (phi), 2.0);

    

        /* Precalculate N */

        N = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nu2));

    

        /* Precalculate t */

        t = Math.tan (phi);

        t2 = t * t;

        tmp = (t2 * t2 * t2) - Math.pow (t, 6.0);



        /* Precalculate l */

        l = lambda - lambda0;

    

        /* Precalculate coefficients for l**n in the equations below

           so a normal human being can read the expressions for easting

           and northing

           -- l**1 and l**2 have coefficients of 1.0 */

        l3coef = 1.0 - t2 + nu2;

    

        l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2 * nu2);

    

        l5coef = 5.0 - 18.0 * t2 + (t2 * t2) + 14.0 * nu2

            - 58.0 * t2 * nu2;

    

        l6coef = 61.0 - 58.0 * t2 + (t2 * t2) + 270.0 * nu2

            - 330.0 * t2 * nu2;

    

        l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2 * t2) - (t2 * t2 * t2);

    

        l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2 * t2) - (t2 * t2 * t2);

    

        /* Calculate easting (x) */

        xy[0] = N * Math.cos (phi) * l

            + (N / 6.0 * Math.pow (Math.cos (phi), 3.0) * l3coef * Math.pow (l, 3.0))

            + (N / 120.0 * Math.pow (Math.cos (phi), 5.0) * l5coef * Math.pow (l, 5.0))

            + (N / 5040.0 * Math.pow (Math.cos (phi), 7.0) * l7coef * Math.pow (l, 7.0));

    

        /* Calculate northing (y) */

        xy[1] = ArcLengthOfMeridian (phi)

            + (t / 2.0 * N * Math.pow (Math.cos (phi), 2.0) * Math.pow (l, 2.0))

            + (t / 24.0 * N * Math.pow (Math.cos (phi), 4.0) * l4coef * Math.pow (l, 4.0))

            + (t / 720.0 * N * Math.pow (Math.cos (phi), 6.0) * l6coef * Math.pow (l, 6.0))

            + (t / 40320.0 * N * Math.pow (Math.cos (phi), 8.0) * l8coef * Math.pow (l, 8.0));

    

        return;

    }

function ArcLengthOfMeridian (phi)

    {

        var alpha, beta, gamma, delta, epsilon, n;

        var result;



        /* Precalculate n */

        n = (sm_a - sm_b) / (sm_a + sm_b);



        /* Precalculate alpha */

        alpha = ((sm_a + sm_b) / 2.0)

           * (1.0 + (Math.pow (n, 2.0) / 4.0) + (Math.pow (n, 4.0) / 64.0));



        /* Precalculate beta */

        beta = (-3.0 * n / 2.0) + (9.0 * Math.pow (n, 3.0) / 16.0)

           + (-3.0 * Math.pow (n, 5.0) / 32.0);



        /* Precalculate gamma */

        gamma = (15.0 * Math.pow (n, 2.0) / 16.0)

            + (-15.0 * Math.pow (n, 4.0) / 32.0);

    

        /* Precalculate delta */

        delta = (-35.0 * Math.pow (n, 3.0) / 48.0)

            + (105.0 * Math.pow (n, 5.0) / 256.0);

    

        /* Precalculate epsilon */

        epsilon = (315.0 * Math.pow (n, 4.0) / 512.0);

    

    /* Now calculate the sum of the series and return */

    result = alpha

        * (phi + (beta * Math.sin (2.0 * phi))

            + (gamma * Math.sin (4.0 * phi))

            + (delta * Math.sin (6.0 * phi))

            + (epsilon * Math.sin (8.0 * phi)));



    return result;

    }

function UTMXYToLatLon (x, y, zone, southhemi, latlon)
{
 x -= 500000;  x /= UTMScaleFactor;
 if (southhemi) y -= 10000000;  y /= UTMScaleFactor; 

 MapXYToLatLon (x, y, UTMCentralMeridian(zone), latlon); 	
 return;
}

//-----------

function btnToUTM_OnClick ()
{var xy = new Array(2);
 
 if (isNaN (parseFloat (document.frmConverter.txtLongitude.value))) 
 { alert ("Please enter a valid longitude in the lon field.");
   return false;
 }
 lon = parseFloat (document.frmConverter.txtLongitude.value);
 if ((lon < -180) || (180 <= lon)) 
 { alert ("The longitude you entered is out of range.  " +
            "Please enter a number in the range [-180, 180).");
   return false;
 }
 if (isNaN (parseFloat (document.frmConverter.txtLatitude.value))) 
 { alert ("Please enter a valid latitude in the lat field.");
   return false;
 }
 lat = parseFloat (document.frmConverter.txtLatitude.value);
 if ((lat < -90) || (90 < lat)) 
 { alert ("The latitude you entered is out of range.  " +
          "Please enter a number in the range [-90, 90].");
   return false;
 }

 // Compute the UTM zone.
 zone = Math.floor ((lon + 180) / 6) + 1;
 zone = LatLonToUTMXY (DegToRad (lat), DegToRad (lon), zone, xy);
 /* Set the output controls.  */
 document.frmConverter.txtX.value = xy[0];
 document.frmConverter.txtY.value = xy[1];
 document.frmConverter.txtZone.value = zone;
 if (lat < 0)  // Set the S button.
   document.frmConverter.rbtnHemisphere[1].checked = true;
 else // Set the N button.
   document.frmConverter.rbtnHemisphere[0].checked = true;
 return true;
}

function LatLngToUTM (){
 
 latlon = new Array(2);
 var x, y, zone, southhemi;
 
 x = parseFloat (lat);
 y = parseFloat (lng);
 zone = parseFloat (tz);
 southhemi = false;
 
 UTMXYToLatLon (x, y, zone, southhemi, latlon);
 //alert(latlon[0]+"-"+latlon[1]);
 var gll=new GLatLng(RadToDeg(latlon[0]),RadToDeg(latlon[1]));
 map.addOverlay(new GMarker(gll));
 map.setCenter(gll, 13);

 
}

function LatLng (){
 var gll=new GLatLng(lat,lng);
 map.addOverlay(new GMarker(gll));
 map.setCenter(gll, 13);
}

function MapXYToLatLon (x, y, lambda0, philambda)
    {
        var phif, Nf, Nfpow, nuf2, ep2, tf, tf2, tf4, cf;
        var x1frac, x2frac, x3frac, x4frac, x5frac, x6frac, x7frac, x8frac;
        var x2poly, x3poly, x4poly, x5poly, x6poly, x7poly, x8poly;
        
        /* Get the value of phif, the footpoint latitude. */
        phif = FootpointLatitude (y);
        //("phif = " + phif);
                
        /* Precalculate ep2 */
        ep2 = (Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0))
              / Math.pow (sm_b, 2.0);
                
        /* Precalculate cos (phif) */
        cf = Math.cos (phif);
                
        /* Precalculate nuf2 */
        nuf2 = ep2 * Math.pow (cf, 2.0);
                
        /* Precalculate Nf and initialize Nfpow */
        Nf = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nuf2));
        Nfpow = Nf;
                
        /* Precalculate tf */
        tf = Math.tan (phif);
        tf2 = tf * tf;
        tf4 = tf2 * tf2;
        
        /* Precalculate fractional coefficients for x**n in the equations
           below to simplify the expressions for latitude and longitude. */
        x1frac = 1.0 / (Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**2) */
        x2frac = tf / (2.0 * Nfpow);
        
        Nfpow *= Nf;   /* now equals Nf**3) */
        x3frac = 1.0 / (6.0 * Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**4) */
        x4frac = tf / (24.0 * Nfpow);
        
        Nfpow *= Nf;   /* now equals Nf**5) */
        x5frac = 1.0 / (120.0 * Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**6) */
        x6frac = tf / (720.0 * Nfpow);
        
        Nfpow *= Nf;   /* now equals Nf**7) */
        x7frac = 1.0 / (5040.0 * Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**8) */
        x8frac = tf / (40320.0 * Nfpow);
        
        /* Precalculate polynomial coefficients for x**n.
           -- x**1 does not have a polynomial coefficient. */
        x2poly = -1.0 - nuf2;
        
        x3poly = -1.0 - 2 * tf2 - nuf2;
        
        x4poly = 5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2
                - 3.0 * (nuf2 *nuf2) - 9.0 * tf2 * (nuf2 * nuf2);
        
        x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2;
        
        x6poly = -61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2
                + 162.0 * tf2 * nuf2;
        
        x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2);
        
        x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2);
                
        /* Calculate latitude */
        philambda[0] = phif + x2frac * x2poly * (x * x)
                + x4frac * x4poly * Math.pow (x, 4.0)
                + x6frac * x6poly * Math.pow (x, 6.0)
                + x8frac * x8poly * Math.pow (x, 8.0);
                
        /* Calculate longitude */
        philambda[1] = lambda0 + x1frac * x
                + x3frac * x3poly * Math.pow (x, 3.0)
                + x5frac * x5poly * Math.pow (x, 5.0)
                + x7frac * x7poly * Math.pow (x, 7.0);
                
        return;
    }

 function FootpointLatitude (y)
    {
        var y_, alpha_, beta_, gamma_, delta_, epsilon_, n;
        var result;
        
        /* Precalculate n (Eq. 10.18) */
        n = (sm_a - sm_b) / (sm_a + sm_b);
                
        /* Precalculate alpha_ (Eq. 10.22) */
        /* (Same as alpha in Eq. 10.17) */
        alpha_ = ((sm_a + sm_b) / 2.0)
            * (1 + (Math.pow (n, 2.0) / 4) + (Math.pow (n, 4.0) / 64));
        
        /* Precalculate y_ (Eq. 10.23) */
        y_ = y / alpha_;
        
        /* Precalculate beta_ (Eq. 10.22) */
        beta_ = (3.0 * n / 2.0) + (-27.0 * Math.pow (n, 3.0) / 32.0)
            + (269.0 * Math.pow (n, 5.0) / 512.0);
        
        /* Precalculate gamma_ (Eq. 10.22) */
        gamma_ = (21.0 * Math.pow (n, 2.0) / 16.0)
            + (-55.0 * Math.pow (n, 4.0) / 32.0);
                
        /* Precalculate delta_ (Eq. 10.22) */
        delta_ = (151.0 * Math.pow (n, 3.0) / 96.0)
            + (-417.0 * Math.pow (n, 5.0) / 128.0);
                
        /* Precalculate epsilon_ (Eq. 10.22) */
        epsilon_ = (1097.0 * Math.pow (n, 4.0) / 512.0);
                
        /* Now calculate the sum of the series (Eq. 10.21) */
        result = y_ + (beta_ * Math.sin (2.0 * y_))
            + (gamma_ * Math.sin (4.0 * y_))
            + (delta_ * Math.sin (6.0 * y_))
            + (epsilon_ * Math.sin (8.0 * y_));
        
        return result;
    }
