google.load("earth", "1");
google.load("maps", "2.111");  // 2 perque funcionen les lineas, 2.99 For JS geocoder

// GMaps / GEarth
// 11 = 22400
// 12 = 11200
// 13 = 5600
// 14 = 2800
// 15 = 1400
// 16 = 700
// 17 = 350
// 18 = 175

// Constants
var ZOOM_BASE_CONVERSIO = 16;
var METRES_BASE_CONVERSIO = 1400;

var map = null; // 2D
var ge = null; // 3D

// 2D
var mrkOrigen = null;
var mrkDesti = null;

// 3D
var mrkOrigen3D = null;
var mrkDesti3D = null;

var styleMap = null;
//var lineStringStyle = null;

var pntOrigen = null;
var xyOrigen = new Array(2);
var pntDesti = null;
var xyDesti = new Array(2);
var mrk = null;
var mrk3D = null;
var desX = 93.74636705;
var desY = 204.2073194;

var resultat = null;
var polylineRecorregut = null;
var lineStringPlacemarkRecorregut = null;
var polyline = null;
var lineStringPlacemark = null;

// Guarda les posicions X,Y de la ruta
var arRutaX = null;
var arRutaY = null;

var SUFIX_LOCALITZACIO_GMAPS = ", Catalunya, Espanya";
//var SUFIX_LOCALITZACIO_GMAPS = ", Madrid, Espaï¿½a";
var ZONA_UTM = 31;
//var ZONA_UTM = 30;

//Array descripcio resultats
var arrRes;
var arrResDes;
var arrResTer;

function fPutMarker(x,y,nomPunt){
	// <JMIRO: Sembla no funcionar amb la ultima versio de GMaps API>
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	var OrigenIcon = new GIcon(baseIcon);
	//OrigenIcon.image = "../img/red_Marker.png";
	var DestinoIcon = new GIcon(baseIcon);
	//DestinoIcon.image = "../img/green_Marker.png";
	// </JMIRO>
	// 2D
	var latlon = new Array(2);
	
	var letteredIcon = new GIcon(baseIcon);
  	//letteredIcon.image = "http://localhost:8080/DemoRouting/img/blue_Marker.png";
  	letteredIcon.image = "../img/blue_Marker.png";

    UTMXYToLatLon(x-desX, y-desY, ZONA_UTM, false, latlon);
    var punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
    //mrk = new GMarker(punt, {icon:letteredIcon,draggable:false, title:nomPunt}); 
    mrk = new GMarker(punt, {icon:DestinoIcon,draggable:false, title:nomPunt});

	//alert("fPutMarker map:" + map + ",mrk: " + mrk);
    map.addOverlay(mrk);
    //alert("fPutMarker fi");
    
    // 3D
    
    if(ge != null) {
    	//alert("ge OK");
	    mrk3D = ge.createPlacemark('');
	    mrk3D.setName(nomPunt);
		ge.getFeatures().appendChild(mrk3D);
		mrk3D.setStyleSelector(styleMap);
		var point = ge.createPoint('');
		point.setLatitude(RadToDeg(latlon[0]));
		point.setLongitude(RadToDeg(latlon[1]));
		mrk3D.setGeometry(point);
    }else{
    	//alert("ge KO");
    }
}

 function fPutLine(UTMsX,UTMsY){

	var punt;
	
    // 2D
 	var latlon = new Array(2);
 	if(polyline != null) {	map.removeOverlay(polyline); }
	var bounds = new GLatLngBounds();
	if(UTMsX.length>=1){
		UTMXYToLatLon(UTMsX[0]-desX, UTMsY[0]-desY, ZONA_UTM, false, latlon);
		polyline = new GPolyline([new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true)], "#FFFF00", 8,0.7);
		punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
		map.addOverlay(polyline);	 
		bounds.extend(punt);		
	}		
		
 	for (i=1; i<UTMsX.length; i++){
 		 UTMXYToLatLon(UTMsX[i]-desX, UTMsY[i]-desY, ZONA_UTM, false, latlon);
		 punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
		 polyline.insertVertex(i,punt);
		 bounds.extend(punt);
	}
 	polyline.deleteVertex(UTMsX.length);
	 
	// UTMXYToLatLon(UTMsX[0]-desX, UTMsY[0]-desY, ZONA_UTM, false, latlon);
	//var punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
	 
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());  
	// map.setCenter(punt, 14);

	// 3D
	if(ge != null) {
		if(lineStringPlacemark != null) { ge.getFeatures().removeChild(lineStringPlacemark); }
		lineStringPlacemark = ge.createPlacemark('');
		var lineString = ge.createLineString('');
		lineStringPlacemark.setGeometry(lineString);
		lineString.setTessellate(true);
		for(i=0; i<UTMsX.length; i++) {
			UTMXYToLatLon(UTMsX[i]-desX, UTMsY[i]-desY, ZONA_UTM, false, latlon);
			punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
			lineString.getCoordinates().pushLatLngAlt(punt.lat(), punt.lng(), 0);
		}
		ge.getFeatures().appendChild(lineStringPlacemark);
		lineStringPlacemark.setStyleSelector(ge.createStyle(''));
		var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
		lineStyle.setWidth(8);
		lineStyle.getColor().set("FF00FFFF");  // aabbggrr format
				
		var iDiferenciaZoom = ZOOM_BASE_CONVERSIO - map.getZoom();
		var iAmpleMetres = METRES_BASE_CONVERSIO * Math.pow(2,iDiferenciaZoom);
		var la = ge.createLookAt('');
	    	la.set(bounds.getCenter().y, bounds.getCenter().x, 100, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, iAmpleMetres);
    	ge.getView().setAbstractView(la);
	}
    	
}

 function fPutLineSencera(UTMsX,UTMsY) {

		var punt;
		
		arRutaX = UTMsX;
		arRutaY = UTMsY;
		
		// Interficie
		document.getElementById("botoNavegar").style.visibility = "visible";
		
	    // 2D
	 	var latlon = new Array(2);
	 	if(polylineRecorregut != null) {	map.removeOverlay(polylineRecorregut); }
		var bounds = new GLatLngBounds();
		if(UTMsX.length>=1){
			UTMXYToLatLon(UTMsX[0]-desX, UTMsY[0]-desY, ZONA_UTM, false, latlon);
		 	polylineRecorregut = new GPolyline([new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true)], "#0031a2", 8,0.7);
			punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
		 	map.addOverlay(polylineRecorregut);	
			bounds.extend(punt); 		
		}
	 	
	 	for (i=1; i<UTMsX.length; i++){
	 		 UTMXYToLatLon(UTMsX[i]-desX, UTMsY[i]-desY, ZONA_UTM, false, latlon);
			 punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
			 polylineRecorregut.insertVertex(i,punt);
			 bounds.extend(punt);
		}
	 	polylineRecorregut.deleteVertex(UTMsX.length);
		 
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());  

		// 3D
		if(ge != null) {
			if(lineStringPlacemarkRecorregut != null) { ge.getFeatures().removeChild(lineStringPlacemarkRecorregut); }
			lineStringPlacemarkRecorregut = ge.createPlacemark('');
			var lineString = ge.createLineString('');
			lineStringPlacemarkRecorregut.setGeometry(lineString);
			lineString.setTessellate(true);
			for(i=0; i<UTMsX.length; i++) {
				UTMXYToLatLon(UTMsX[i]-desX, UTMsY[i]-desY, ZONA_UTM, false, latlon);
				punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
				lineString.getCoordinates().pushLatLngAlt(punt.lat(), punt.lng(), 0);
			}
			ge.getFeatures().appendChild(lineStringPlacemarkRecorregut);
			lineStringPlacemarkRecorregut.setStyleSelector(ge.createStyle(''));
			var lineStyle = lineStringPlacemarkRecorregut.getStyleSelector().getLineStyle();
			lineStyle.setWidth(8);
			lineStyle.getColor().set("B2A23100");  // aabbggrr format
					
			var iDiferenciaZoom = ZOOM_BASE_CONVERSIO - map.getZoom();
			var iAmpleMetres = METRES_BASE_CONVERSIO * Math.pow(2,iDiferenciaZoom);
			var la = ge.createLookAt('');
		    	la.set(bounds.getCenter().y, bounds.getCenter().x, 100, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, iAmpleMetres);
		    	ge.getView().setAbstractView(la);
		}
	}
 
function load() {
    if (GBrowserIsCompatible()) {
          
        // 2D
    map = new GMap2(document.getElementById("map"));
    
    map.setCenter(new GLatLng(41.4, 2.2), 11);
    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
 	try {
    	putAll(1);
	} catch (e) {
		// TODO: handle exception
	}    
    	
    // 3D
    google.earth.createInstance("map3d", initCB, failureCB);
  }
}

// 3D
function initCB(object) {
	//alert("Google Earth succeded");
    ge = object;
    ge.getWindow().setVisibility(true);

    // Inicialitzar bbox
    var la = ge.createLookAt('');
	la.set(41.4, 2.2, 100, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 22400);
	ge.getView().setAbstractView(la);

	// Inicialitzaciï¿½ estils
	var normal = ge.createIcon('');
	normal.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
	//normal.setHref('http://localhost:8080/DemoRouting/img/red_Marker.png'); // OJO, HARDCODED
	var iconNormal = ge.createStyle('');
	iconNormal.getIconStyle().setIcon(normal);
	var highlight = ge.createIcon('');
	highlight.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
	//highlight.setHref('http://localhost:8080/DemoRouting/img/red_Marker.png'); // OJO, HARDCODED
	var iconHighlight = ge.createStyle('');
	iconHighlight.getIconStyle().setIcon(highlight);
	styleMap = ge.createStyleMap('');
	styleMap.setNormalStyle(iconNormal);
	styleMap.setHighlightStyle(iconHighlight);

	//lineStringStyle = ge.createStyle('');
	//lineStringStyle.setWidth(8);
	//lineStringStyle.getColor().set("B20031A2");  // aabbggrr format
	
        	
}

// 3D
function failureCB(object) {
	ge = null;
}

function anarA(x, y) {

	var latlon = new Array(2);
	var desvLon= 0.002538;
	var desvLat = 0.002217;
    //alert("UTMXYToLatLon:"+UTMXYToLatLon);
    UTMXYToLatLon(x-desX, y-desY, ZONA_UTM, false, latlon);
    //alert("Lat:"+RadToDeg(latlon[0])+", Lon:"+RadToDeg(latlon[1]));
    var punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
    
	// 2D
	map.setCenter(punt, 16);

    // 3D
	if(ge != null) {
	    var la = ge.createLookAt('');
		la.set(punt.y, punt.x, 100, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 700);
		ge.getView().setAbstractView(la);
	}
}

function changeImage(identi) {
	if(identi=='2D'&&document.getElementById("map3d").style.width != "0px") {
		document.getElementById("2D").style.backgroundImage= "url(../img/btn2D.png)";
	}else if(identi=='3D'&&document.getElementById("map3d").style.width == "0px"){
		document.getElementById("3D").style.backgroundImage= "url(../img/btn3D.png)";
	}
}

function OnSwapViewers(identi) {
	//alert("OnSwapViewers");
	
	
    if(identi=='2D'&&document.getElementById("map3d").style.width != "0px") {
    	document.getElementById("map").style.visibility = "visible";
        // // 2D // //
         
    	// 3D no visible
    	document.getElementById("map3d").style.width = "0px";
    	document.getElementById("map3d").style.height = "0px";

    	// Passar bbox de 2D a 3D
    	if(ge != null) {
    		
	    	var iZoom;
	    	var la;
	    	var coeficient;
	
	    	la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
	
	    	//alert("Metres " + la.getRange());
	    	
	    	coeficient = (la.getRange() / METRES_BASE_CONVERSIO);
	    	iZoom = Math.round(ZOOM_BASE_CONVERSIO - Math.log(coeficient)/Math.LN2); // Logaritme base 2 de coeficient
	
	    	//alert("Zoom " + iZoom);
	    	
	    	if(iZoom>18) {iZoom=17;}
	    	map.setCenter(new GLatLng(la.getLatitude(), la.getLongitude()), iZoom);
    	}    	

    	document.getElementById("3D").style.backgroundImage= "url(../img/btn3D.png)";
    	document.getElementById("2D").style.backgroundImage= "url(../img/btn2DHover.png)";
    	
    	// Ajuda3D
    	document.getElementById("divHelp3D").style.visibility = "hidden";

   	
    } else if(identi=='3D'&&document.getElementById("map3d").style.width == "0px"){
    	
    	// // 3D // //
		
		// 3D visible
    	document.getElementById("map3d").style.top = "" + document.getElementById("map").offsetTop + "px";
    	document.getElementById("map3d").style.left = "" + document.getElementById("map").offsetLeft + "px";
    	var myWidth = 0;
    	if (typeof (window.innerWidth) == 'number') {
    		// Non-IE
    		myWidth = window.innerWidth;
    	} else if (document.documentElement
    			&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
    		// IE 6+ in 'standards compliant mode'
    		myWidth = document.documentElement.clientWidth;
    	} else if (document.body
    			&& (document.body.clientWidth || document.body.clientHeight)) {
    		// IE 4 compatible
    		myWidth = document.body.clientWidth;
    	}
    	myWidth = (((myWidth*75)/100) - 10);
    	myWidth = String(myWidth);
    	myWidth = myWidth.split(".")[0];
    	document.getElementById("map3d").style.width = myWidth + "px";
    	document.getElementById("map3d").style.height =""+ document.getElementById("map").style.height;
    	
        // Passar bbox de 2D a 3D
        
    	if(ge != null) {
    		
	        var iDiferenciaZoom;
	    	var iAmpleMetres;
	    	var punt;
	    	
	    	iDiferenciaZoom = ZOOM_BASE_CONVERSIO - map.getZoom();
	    	iAmpleMetres = METRES_BASE_CONVERSIO * Math.pow(2,iDiferenciaZoom);
	    	punt = map.getCenter();
		    	
	    	var la = ge.createLookAt('');
	    	la.set(punt.y, punt.x, 100, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, iAmpleMetres);
	    	ge.getView().setAbstractView(la);
    	}

	// 3D
	   	
    	 // Ajuda3D
    	document.getElementById("divHelp3D").style.visibility = "visible";
    	
    	document.getElementById("map").style.visibility = "hidden";
    	document.getElementById("3D").style.backgroundImage= "url(../img/btn3DHover.png)";
    	document.getElementById("2D").style.backgroundImage= "url(../img/btn2D.png)";    	
    }
}

var NUM_STEP;
var iNavegarStep;
var iNavegarPunt;
var idIntervalNavegacio;
var idIntervalNavegacio3D;
var bNavegant = false;

function fNavegarRuta() {

	  if(bNavegant) {
		 if(idIntervalNavegacio > 0) { clearInterval(idIntervalNavegacio); }
		 if(idIntervalNavegacio3D > 0) { clearInterval(idIntervalNavegacio3D); }
		 bNavegant = false;
		 
		// Interficie
		document.getElementById("botoNavegarText").innerHTML = strSimulPlay;
			
	 } else {
		 if(document.getElementById("map3d").style.width != "0px") {
			 // 3D
			 if(ge != null) {
				 iNavegarPunt = 0;
				 idIntervalNavegacio3D = setInterval("fNavegarStep3D()", 2500);
			 }
		 } else {
			 // 2D
			 iNavegarStep = 0;
			 iNavegarPunt = 0;
			 NUM_STEP = 20;
			 idIntervalNavegacio = setInterval("fNavegarStep()", 50);
		 }
		 bNavegant = true;
		 
		// Interficie
		document.getElementById("botoNavegarText").innerHTML = strSimulStop;
	 }
	 
	 //setTimeout("alert('hello')",100);
}
 
function fNavegarStep3D() {
	var punt;
	var puntDesti;
	
	if(ge != null) {
		if(arRutaX == null) {
			 clearInterval(idIntervalNavegacio3D);
			 bNavegant = false;
			// Interficie
			document.getElementById("botoNavegarText").innerHTML = strSimulPlay;
		} else if(iNavegarPunt == arRutaX.length) {
			clearInterval(idIntervalNavegacio3D);
			bNavegant = false;
			// Interficie
			document.getElementById("botoNavegarText").innerHTML = strSimulPlay;
		} else {
			//anarA(arRutaX[iNavegarPunt],arRutaY[iNavegarPunt]);
			
			var latlon = new Array(2);
			var desvLon= 0.002538;
			var desvLat = 0.002217;
			var angle;
			
		    if(iNavegarPunt == arRutaX.length-1) {
		    	// Calcul d'angle del segment anterior
		    	UTMXYToLatLon(arRutaX[iNavegarPunt-1]-desX, arRutaY[iNavegarPunt-1]-desY, ZONA_UTM, false, latlon);
			    punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
			    
			    UTMXYToLatLon(arRutaX[iNavegarPunt]-desX, arRutaY[iNavegarPunt]-desY, ZONA_UTM, false, latlon);
		    	puntDesti = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
		    	
		    	angle = obtenirAngle(punt, puntDesti);
				
		    	UTMXYToLatLon(arRutaX[iNavegarPunt]-desX, arRutaY[iNavegarPunt]-desY, ZONA_UTM, false, latlon);
		    	punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
		    	
		    } else {
		    	// Calcul d'angle normal
		    	UTMXYToLatLon(arRutaX[iNavegarPunt]-desX, arRutaY[iNavegarPunt]-desY, ZONA_UTM, false, latlon);
			    punt = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
			    
			    UTMXYToLatLon(arRutaX[iNavegarPunt+1]-desX, arRutaY[iNavegarPunt+1]-desY, ZONA_UTM, false, latlon);
		    	puntDesti = new GLatLng(RadToDeg(latlon[0]), RadToDeg(latlon[1]) , true);
		    	
		    	angle = obtenirAngle(punt, puntDesti);
				
		    }
		    
		    var la = ge.createLookAt('');
			la.set(punt.y, punt.x, 25, ge.ALTITUDE_RELATIVE_TO_GROUND, angle, 60, 700);
			ge.getView().setAbstractView(la);
			
			iNavegarPunt++;
		}
	}
}

function obtenirAngle(inici, fi) {

	var degreesPerRadian = 180.0 / Math.PI;
	var radiansPerDegree = Math.PI / 180.0;

	// Returns the bearing in degrees between two points.
	// North = 0, East = 90, South = 180, West = 270.
	var lat1 = inici.latRadians();
	var lon1 = inici.lngRadians();
	var lat2 = fi.latRadians();
	var lon2 = fi.lngRadians();

	// Compute the angle.
	var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
	if ( angle < 0.0 ) {
		angle += Math.PI * 2.0;
	}

	// And convert result to degrees.
	angle = angle * degreesPerRadian;
	//angle = angle.toFixed(1);

	return angle;
}
	
function fNavegarStep() {
	 var x;
	 var y;
	 
	 //alert("fNavegarStep");
	 
	 if(arRutaX == null) {
		 //alert("1");
		 clearInterval(idIntervalNavegacio);
		 bNavegant = false;
		// Interficie
		document.getElementById("botoNavegarText").innerHTML = strSimulPlay;
	 } else if((iNavegarStep == NUM_STEP) && (iNavegarPunt == arRutaX.length-2)) {
		 //alert("2");
		 clearInterval(idIntervalNavegacio);
		 bNavegant = false;
		// Interficie
		document.getElementById("botoNavegarText").innerHTML = strSimulPlay;
	 } else if(iNavegarStep < NUM_STEP) {
		 //alert("3");
		 x = (arRutaX[iNavegarPunt]*(1-(iNavegarStep/NUM_STEP))) + (arRutaX[iNavegarPunt+1]*(iNavegarStep/NUM_STEP));
		 y = (arRutaY[iNavegarPunt]*(1-(iNavegarStep/NUM_STEP))) + (arRutaY[iNavegarPunt+1]*(iNavegarStep/NUM_STEP));;
		 //alert("anar("+x+","+y+")");
		 anarA(x,y);
		 iNavegarStep++;
	 } else {
		 
		 //alert("4");
		 //alert("iNavegarPunt " + iNavegarPunt + ", arRutaX.length " + arRutaX.length);
		 /*
		 alert("NUM_STEP " + NUM_STEP);
		 alert("(iNavegarStep/NUM_STEP) " + (iNavegarStep/NUM_STEP));
		 alert("1-(iNavegarStep/NUM_STEP) " + 1-(iNavegarStep/NUM_STEP));
		 alert("arRutaX[iNavegarPunt] " + arRutaX[iNavegarPunt]);
		 alert("arRutaX[iNavegarPunt+1] " + arRutaX[iNavegarPunt+1]);
		 */
		 x = arRutaX[iNavegarPunt+1];
		 y = arRutaY[iNavegarPunt+1];
		 //alert("anar("+x+","+y+")");
		 anarA(x,y);
		 iNavegarPunt++;
		 iNavegarStep = 0;
	 }
	 //alert("Fi");
	 
}
/* Funciones de control de pestaï¿½as */

function Mostrar(TabName)
{
    for (i = 0; i < _TabsArray.length; i++)
    {
        if (_TabsArray[i] != TabName)
            document.getElementById(_TabsArray[i]).style.display = "none";
    }
    document.getElementById(TabName).style.display = "";
}

function Pestana_select(PesName)
{
	for (i = 0; i < _PestsArray.length; i++)
    {
        if (_PestsArray[i] != PesName)
            document.getElementById(_PestsArray[i]).className = "";
    }
    document.getElementById(PesName).className = "pestanaseleccionada";
}

/* Funciones de control de respostes */
function changeresposta(id){
	document.getElementById("Tab1").innerHTML = arrResDes[id];
	//document.getElementById("Tab2").innerHTML = arrResTer[id];
	putAll(id);
}
