//Defino la ruta para las imágenes de los iconos

var customIcons = {
      znegocio: {
        icon: 'img/elem_graficos/icon_mapa_negocios.png'
      },
      panda: {
        icon: 'img/elem_graficos/icon_mapa_pandas.png'
      },
	  lugar: {
        icon: 'img/elem_graficos/icon_mapa_puntos.png'
      }
    };
	
	
//Creo el array para recoger después los marcadores y poder llamarlos desde javascript
var gmarkers = [];



//Defino la función que genera el mapa
 function initialize() {
	 
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(41.501978610157636, -5.000485181808472),
        zoom: 15,
        mapTypeControl: true,
		streetViewControl: true,
		mapTypeControlOptions: {
		  style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
		},
		navigationControl: true,
		navigationControlOptions: {
		  style: google.maps.NavigationControlStyle.SMALL
		},
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scaleControl: true
      });
      var infoWindow = new google.maps.InfoWindow;


      // Change this depending on the name of your PHP file
	  //Recojo el archivo donde se genera el xml desde la base de datos
	  //Creo los markers y las ventanas infowindow
      downloadUrl("markers_xml_home.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
		  var identificador = markers[i].getAttribute("id");
          var name = markers[i].getAttribute("nombre");
          var address = markers[i].getAttribute("info");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
		  
		  //Aquí distingo entre los tipos panda para ponerles un enlace a la página de dicha panda.
		  	if (type=="panda") {
				var html = "<b>" + address + "</b><br/> <a href='pandas.php?id_p=" + identificador + "'>Ir a p&aacute;gina de la pe&ntilde;a</a>";
			} else {
          		var html = "<b>" + address + "</b>";
			}
		   var icon = customIcons[type] || {};
		   
		   //Selecciono como visibles de principio solo las pandas y negocios, no los lugares
		   if (type == "lugar") {
			    var marker = new google.maps.Marker({
            map: map,
            position: point,
			 icon: icon.icon,
			 visible:false
          });
		   } else {
          var marker = new google.maps.Marker({
            map: map,
            position: point,
			 icon: icon.icon,
			 visible:true
          });
		  
		   }
		
		//Meto en el array gmarkers los datos que necesito de cada marker para llamarlos después
		marker.mycategory = type;
		marker.nombre = name;
      	gmarkers.push(marker);



		  
          bindInfoWindow(marker, map, infoWindow, html);
        }
		
		
		/*Funciones para mostrar u ocultar las rutas de los encierros*/
	
	//Defino las rutas.  Encierro normal y toro de la vega
	var ruta_encierro = [
    new google.maps.LatLng(41.47950996411165, -5.035858154296875),
    new google.maps.LatLng(41.481278292284024, -5.033454895019531),
	new google.maps.LatLng(41.479027684417694, -5.031008720397949),
    new google.maps.LatLng(41.48050666410621, -5.029120445251465),
	new google.maps.LatLng(41.482564318829745, -5.019850730895996),
    new google.maps.LatLng(41.485522083029565, -5.015988349914551),
	new google.maps.LatLng(41.48494340065747, -5.015130043029785),
    new google.maps.LatLng(41.485136295355765, -5.007748603820801),
	new google.maps.LatLng(41.49021564907758, -5.004315376281738),
    new google.maps.LatLng(41.496451779247224, -5.000367164611816),
	new google.maps.LatLng(41.49922034280597, -5.00126838684082),
    new google.maps.LatLng(41.499413194995995, -5.002598762512207),
	new google.maps.LatLng(41.50158274256205, -5.004422664642334),
    new google.maps.LatLng(41.50028102274435, -5.006074905395508),
	new google.maps.LatLng(41.50021673960624, -5.006611347198486)
	
	
  ];
	
	
	var ruta_toro_vega = [
    new google.maps.LatLng(41.50018379442419, -5.000302791595459),
    new google.maps.LatLng(41.49956908338083, -5.000292062759399),
	new google.maps.LatLng(41.499464622100625, -5.000334978103638),
    new google.maps.LatLng(41.499344089644865, -5.000479817390442),
	new google.maps.LatLng(41.499207485923854, -5.001348853111267),
    new google.maps.LatLng(41.49671535493184, -5.000485181808472),
	new google.maps.LatLng(41.495341213308365, -5.000978708267212),
    new google.maps.LatLng(41.49375595877824, -5.002405643463135),
	new google.maps.LatLng(41.491023593885295, -5.008714199066162),
    new google.maps.LatLng(41.48503127511094, -5.014400482177734)
	
	
  ];
	
	
	var ruta_faroles = [
    new google.maps.LatLng(41.5010395589061, -5.000458359718323),
    new google.maps.LatLng(41.50202387495947, -5.000581741333008),
	new google.maps.LatLng(41.5030885265002, -5.000324249267578),
    new google.maps.LatLng(41.50313673672175, -5.001182556152344),
	new google.maps.LatLng(41.50304031624278, -5.00127911567688),
    new google.maps.LatLng(41.50265061534416, -5.003258585929871),
	new google.maps.LatLng(41.502156455162094, -5.003103017807007),
    new google.maps.LatLng(41.50195155837092, -5.003290772438049),
	new google.maps.LatLng(41.50062681129789, -5.003172755241394),
    new google.maps.LatLng(41.500517262679715, -5.00352144241333),
    new google.maps.LatLng(41.499677562224214, -5.002958178520203),
    new google.maps.LatLng(41.49945658661056, -5.002593398094177),
	new google.maps.LatLng(41.499384267155065, -5.002073049545288),
    new google.maps.LatLng(41.499372213904614, -5.00177264213562),
	new google.maps.LatLng(41.499231592483774, -5.001482963562012),
    new google.maps.LatLng(41.49921953920494, -5.001305937767029),
	new google.maps.LatLng(41.499348107397005, -5.000485181808472),
    new google.maps.LatLng(41.49947265758972, -5.0003403425216675),
	new google.maps.LatLng(41.49959720754284, -5.00028669834137),
    new google.maps.LatLng(41.49951283502012, -4.999825358390808),
	new google.maps.LatLng(41.49967354449253, -4.999498128890991),
    new google.maps.LatLng(41.49979407633511, -4.9985164403915405),
	new google.maps.LatLng(41.50028423685053, -4.998596906661987),
    new google.maps.LatLng(41.50036459067944, -4.997920989990234),
	new google.maps.LatLng(41.50062172226198, -4.9965208768844604),
    new google.maps.LatLng(41.50058154551952, -4.996247291564941),
	new google.maps.LatLng(41.50045699745944, -4.995823502540588),
    new google.maps.LatLng(41.501224370407975, -4.995507001876831),
	new google.maps.LatLng(41.50250196592985, -4.995453357696533),
    new google.maps.LatLng(41.5020359277164, -4.996976852416992),
	new google.maps.LatLng(41.501509621908234, -4.998060464859009),
	new google.maps.LatLng(41.501059647138376, -4.9992835521698),
    new google.maps.LatLng(41.50097125886976, -4.999954104423523),
	new google.maps.LatLng(41.50094313530444, -5.000184774398804)
    
	
	
  ];

		
		//Defino el icono de inicio del encierro
		position1 = new google.maps.LatLng(41.47950996411165, -5.035858154296875);
		marker1 = new google.maps.Marker({
		position: position1,
		map: null,
		title: "Inicio de los Encierros",
		icon: 'img/elem_graficos/inicio.png'
		 });
		
		//Defino la ruta del encierro. Polyline
		encierro = new google.maps.Polyline({
		path: ruta_encierro,
		strokeColor: "#000",
		strokeOpacity: 1.0,
		strokeWeight: 2
		});
		//Tanto el icono como el polyline lo he definido como null para que no se muestre de inicio
		encierro.setMap(null);


		
		// Icono encierro toro vega
		position2 = new google.maps.LatLng(41.50018379442419, -5.000302791595459);
		marker2 = new google.maps.Marker({
		position: position2,
		map: null,
		title: "Inicio del Encierro del Toro de la Vega",
		icon: 'img/elem_graficos/inicio.png'
		 });
		
		// ruta encierro toro vega
		toro = new google.maps.Polyline({
		path: ruta_toro_vega,
		strokeColor: "#36408D",
		strokeOpacity: 1.0,
		strokeWeight: 2
		});
		
		toro.setMap(null);
		
		
		// Icono faroles
		position3 = new google.maps.LatLng(41.5010395589061, -5.000458359718323);
		marker3 = new google.maps.Marker({
		position: position3,
		map: null,
		title: "Inicio del Desfile de Faroles",
		icon: 'img/elem_graficos/inicio.png'
		 });
		
		// ruta faroles
		faroles = new google.maps.Polyline({
		path: ruta_faroles,
		strokeColor: "#769F3B",
		strokeOpacity: 1.0,
		strokeWeight: 2
		});
		
		faroles.setMap(null);

	
	//Recojo los dos campos checkbox con clase polyline y llamo a la función llamaPolylines enviando el campo y el id
	function preparaPolylines() {
		var polylines = document.getElementsByTagName("input");
			for (i=0;i<polylines.length;i++) {
					if (polylines[i].className == "polylines") {
						llamaPolylines(polylines[i], polylines[i].id);
					}
			}
	}
	
	//Recoge el campo checkbox y el id y les asigna a los campos una función que llama a click encierro
	function llamaPolylines(objeto, identificador) {
		var nuevo_objeto = document.getElementById(identificador);
		nuevo_objeto.onclick = function() {
			clickEncierro(nuevo_objeto, identificador);
		}
	}
	
	//Define si el id es encierro, faroles  o toro vega y recoge el estado del checkbox para mostrar una ruta u otra a través de muestra
	//u ocultaRuta.
	
	//Si recoge encierro, pasa en la funcion muestraruta a torovega y faroles para ocultarlos en el case 1, y mostrar el encierro, y así sucesivamente con los demás.
	function clickEncierro(box,category) {
		
		switch(category) {
			case "encierro":
			
				if (box.checked) {
					muestraRuta("torovega",1);
					muestraRuta("faroles",1);
				}
				
				if (!box.checked) {
					ocultaRuta(1);
				}
			
				break;
				
			case "torovega":
			
				if (box.checked) {
					muestraRuta("faroles",2);
					muestraRuta("encierro",2);
				}
				
				if (!box.checked) {
					ocultaRuta(2);
				}
			
				break;
				
			case "faroles":
			
				if (box.checked) {
					muestraRuta("encierro",3);
					muestraRuta("torovega",3);
				}
				
				if (!box.checked) {
					ocultaRuta(3);
				}
			
				break;
				
		}
			
	}
	
	
	//Hace visibles o invisibles los polylines que se han definido arriba.  
	//También centra en el mapa el polyline cuando se hace click en el checkbox, y desmarca el otro checkbox para que
	//sólo se vea un mapa a la vez.  También cierra la ventana infoWindow.
	function muestraRuta(idbox,number) {
		var checkbox;
			switch(number) {
			  	case 1:   
					checkbox = document.getElementById(idbox);
					checkbox.checked = false;
					encierro.setMap(map);
					toro.setMap(null);
					faroles.setMap(null);
					map.setCenter(new google.maps.LatLng(41.49931676897276,-5.001826286315918));
					marker1.setMap(map);
					marker2.setMap(null);
					marker3.setMap(null);
					infoWindow.close();
					break;
			 	case 2:   
					checkbox = document.getElementById(idbox);
					checkbox.checked = false;
					encierro.setMap(null);
					toro.setMap(map);
					faroles.setMap(null);
					map.setCenter(new google.maps.LatLng(41.49820785938658,-5.001010894775391));
					marker1.setMap(null);
					marker2.setMap(map);
					marker3.setMap(null);
					infoWindow.close();
					break;
			
				case 3:   
					checkbox = document.getElementById(idbox);
					checkbox.checked = false;
					encierro.setMap(null);
					toro.setMap(null);
					faroles.setMap(map);
					map.setCenter(new google.maps.LatLng(41.5010395589061, -5.000458359718323));
					marker1.setMap(null);
					marker2.setMap(null);
					marker3.setMap(map);
					infoWindow.close();
					break;

			}
	}
	
	
	//Oculta polylines.
	function ocultaRuta(number) {
		switch(number) {
		  	case 1:   
				encierro.setMap(null);
				marker1.setMap(null);
				break;
		  	case 2:   
				toro.setMap(null)
				marker2.setMap(null);
				break;
			case 3:   
				faroles.setMap(null)
				marker3.setMap(null);
				break;
		}
	}
	
	preparaPolylines();
		
		
		
		//Llamo a la funcion que hace que coloque los enlaces de las pandas y negocios al principio.
		//Es como makesidebar pero modificada.
		makeSidebarInicial();
		preparaCheckbox();
		


      });
    }
	
	
	//Creo funciones para mostrar u ocultar los iconos en el mapa dependiendo de si se pulsa checkbox o no
	function show(category) {
      for (var i=0; i<gmarkers.length; i++) {
        if (gmarkers[i].mycategory == category) {
          gmarkers[i].setVisible(true);
        }
      }
      document.getElementById(category).checked = true;
	  //Llamo a la función que crea los enlaces con nombres
	  makeSidebar();
    }

    function hide(category) {
      for (var i=0; i<gmarkers.length; i++) {
        if (gmarkers[i].mycategory == category) {
          gmarkers[i].setVisible(false);
		  
        }
      }
      document.getElementById(category).checked = false;
	  //Llamo a la función que crea los enlaces con nombres
	  makeSidebar();
    }
	
	
	//Función que lleva a cada icono cuando se pulsa el enlace de texto
	function myclick(i) {
        google.maps.event.trigger(gmarkers[i],"click");
      }
	  
	  
	  /*Esta funcion recoge todos los input checkbox con clase mapabox y recoge el id de cada uno para enviarlo junto con
	  el mismo checkbox a llamaCheckbox*/
	  function preparaCheckbox() {
		var encuentra = document.getElementsByTagName("input");
		var identifica = [];
			for (var i=0;i<encuentra.length;i++) {
				if (encuentra[i].type == "checkbox" && encuentra[i].className == "mapabox") {
					identifica[i] = encuentra[i].id;
					
					llamaCheckbox(encuentra[i], identifica[i]);
				}
			}
	  }
	  
	  
	  /*Ésta funcion recoge el checkbox y el id y los envía a boxclick para mostrar o esconder los markers*/
	  function llamaCheckbox(objeto, identificador) {
		var nuevo_objeto = document.getElementById(identificador);
		nuevo_objeto.onclick = function() {
			boxclick(nuevo_objeto, identificador);
		}

	  }
	  
	  //Funcion que recoge el click en checkbox y dependiendo de si está chequeado o no, muestra u oculta cada categoria
    function boxclick(box,category) {
		
      if (box.checked) {
        show(category);
      } 
	  if (!box.checked) {
        hide(category);
      }

    }
	  
	  
	  function prepareLinks() {
		var nombres_clase = [];
		var links = document.getElementsByTagName("a");
			for (var i=0; i<links.length; i++) {
				
				nombres_clase[i] = links[i].className;

					
				if (nombres_clase[i] == "makesidebar") {
					//llamo a llamaclick que va a llamar a myclick pasandole el identificador del enlace.
					llamaClick(links[i].id);
					
				}
			}
	  }
	  
	  function llamaClick(identificador) {
		var nuevo_id = document.getElementById(identificador);
		nuevo_id.onclick = function() {
			myclick(identificador);
			return false;
		}

	  }
	 

	 //Función que compone la barra de enlaces del mapa al inicio solo con las pandas
	function makeSidebarInicial() {
        var html = "<table>";
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory=="panda" || gmarkers[i].mycategory=="znegocio") {
			  //Asigno a cada enlace un id para recogerlo después y poder llamar a través de prepareLinks a la funcion
			  //que hará que el mapa vaya al icono deseado
            html += '<tr><td class=' + gmarkers[i].mycategory + '><a href="index.php" id="' + i + '" class="makesidebar">' + gmarkers[i].nombre + '<\/a></td></tr>';
          }
        }
		html +="</table>";
        document.getElementById("listas").innerHTML = html;
		
		
		//Llamo a preparelinks para que se asigne el id correspondiente a cada enlace y así poder llamar a myclick con ese identificador
		prepareLinks();
		
      }
	  
	  
	//Función que compone la barra de enlaces del mapa
	function makeSidebar() {
        var html = "<table>";
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].getVisible()) {
            //Asigno a cada enlace un id para recogerlo después y poder llamar a través de prepareLinks a la funcion
			  //que hará que el mapa vaya al icono deseado
            html += '<tr><td class=' + gmarkers[i].mycategory + '><a href="index.php" id="' + i + '" class="makesidebar">' + gmarkers[i].nombre + '<\/a></td></tr>';
          }
        }
		html +="</table>";
        document.getElementById("listas").innerHTML = html;
		
		//Llamo a preparelinks para que se asigne el id correspondiente a cada enlace y así poder llamar a myclick con ese identificador
		prepareLinks();
		
      }


			  


	
    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }
	
	

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }
	
	function doNothing() {}
