function initialize() {
  var myLatlng = new google.maps.LatLng(-32.05, -59.3);
  var myOptions = {
	  zoom: 8,
	  center: myLatlng,
	  mapTypeId: google.maps.MapTypeId.SATELLITE,
      mapTypeControl: true,
	  mapTypeControlOptions: {
		  style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
		  position: google.maps.ControlPosition.TOP_RIGHT
		},
      panControl: true,
      panControlOptions: {
          position: google.maps.ControlPosition.LEFT_TOP
      },
	  navigationControl: true,
	  navigationControlOptions: {
		  style: google.maps.NavigationControlStyle.ANDROID,
		  position: google.maps.ControlPosition.BOTTOM
		},
//      zoomControl: true,
//      zoomControlOptions: {
//          style: google.maps.ZoomControlStyle.LARGE,
//          position: google.maps.ControlPosition.LEFT_CENTER
//      },
	  scaleControl: true,
	  scaleControlOptions: {
		  position: google.maps.ControlPosition.BOTTOM_LEFT
		},
      streetViewControl: false,
      streetViewControlOptions: {
          position: google.maps.ControlPosition.LEFT_TOP
      }
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  var layer = new google.maps.KmlLayer('http://www.bolsacer.org.ar/img/estaciones/divisionER.kmz', {preserveViewport: true , suppressInfoWindows: true});
  layer.setMap(map);

  var logoControlDiv = document.createElement('DIV'); 
  var logoControl = new DivControl(logoControlDiv, 'Bolsa de Cereales de Entre Ríos', '<img src="img/logogm.png">'); 
  logoControlDiv.index = 1; 
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv); 

  var botonVistaInicialDiv = document.createElement('DIV'); 
  var botonVistaInicial = new Boton(botonVistaInicialDiv, map, 'Vista Inicial', 'Mostrar la vista inicial', function() {vistaInicial();}); 
  botonVistaInicialDiv.index = 1; 
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(botonVistaInicialDiv); 

  var botonActualizarDiv = document.createElement('DIV'); 
  var botonVistaInicial = new Boton(botonActualizarDiv, map, 'Actualizar Datos', 'Busca actualizaciones de datos en el servidor', function() {actualizarXmlCentrales();});
  DivControl(botonActualizarDiv, '', '<img id="cargando" src="img/sinImagen.png">');
  botonActualizarDiv.index = 1; 
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(botonActualizarDiv); 

  var actualizacionlDiv = document.createElement('DIV'); 
  var actualizacionControl = new Leyenda(actualizacionlDiv, '', '<div id="actualizacion" align="center">&nbsp;</div>');
  actualizacionlDiv.index = 1; 
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(actualizacionlDiv); 
  
  var leyendaControlDiv = document.createElement('DIV'); 
  var leyendaControl = new DivControl(leyendaControlDiv, 'Estación funcionando correctamente', '<div align="left" class="Texto" style="color:#FFFFFF"><img src="img/puntoVerde.png">Operativa</div>');
  DivControl(leyendaControlDiv, 'Estación momentaneamente fuera de servicio', '<div align="left" class="Texto" style="color:#FFFFFF"><img src="img/puntoRojo.png">No operativa</div>');
  leyendaControlDiv.index = 1; 
  map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(leyendaControlDiv); 

  google.maps.event.addListener(map, 'click', function(){closeInfoWindow();});
  infoWindow = new google.maps.InfoWindow();

  geocoder = new google.maps.Geocoder(); 

  vistaInicial();
  obtenerXmlCentrales();
  timer = setTimeout('actualizarXmlCentrales();', intervalo);
}

function vistaInicial() {
  var southWest = new google.maps.LatLng(-33.54,-60.7);
  var northEast = new google.maps.LatLng(-30.54,-57.9);
  var bounds = new google.maps.LatLngBounds(southWest,northEast);
  map.fitBounds(bounds);
  if (marcador != null) {marcador.setMap(null);}
}

function DivControl(controlDiv, titulo, contenido) { 
  controlDiv.style.padding = '5px'; 
  var controlUI = document.createElement('DIV'); 
  controlUI.style.textAlign = 'center'; 
  controlUI.title = titulo; 
  controlDiv.appendChild(controlUI); 
  var controlText = document.createElement('DIV'); 
  controlText.innerHTML = contenido; 
  controlUI.appendChild(controlText); 
} 

function Leyenda(controlDiv, titulo, contenido) { 
  controlDiv.style.padding = '5px'; 
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = '#CCCCCC'; 
  controlUI.style.borderColor = '#CCCCCC'; 
  controlUI.style.borderStyle = 'solid'; 
  controlUI.style.borderWidth = '1px'; 
  controlUI.style.textAlign = 'center'; 
  controlUI.title = titulo; 
  controlDiv.appendChild(controlUI); 
  var controlText = document.createElement('DIV'); 
  controlText.style.fontFamily = 'Arial,sans-serif'; 
  controlText.style.fontSize = '12px'; 
  controlText.style.color = '#666666'; 
  controlText.style.paddingTop = '2px'; 
  controlText.style.paddingBottom = '1px'; 
  controlText.style.paddingLeft = '6px'; 
  controlText.style.paddingRight = '6px'; 
  controlText.innerHTML = contenido; 
  controlUI.appendChild(controlText); 
}

function Boton(controlDiv, map, nombre, descripcion, funcion) { 
 
  // Set CSS styles for the DIV containing the control 
  // Setting padding to 5 px will offset the control 
  // from the edge of the map 
  controlDiv.style.padding = '5px'; 
 
  // Set CSS for the control border 
  var controlUI = document.createElement('DIV'); 
  controlUI.style.backgroundColor = 'white'; 
  controlUI.style.borderColor = '#717B87'
  controlUI.style.borderStyle = 'solid'; 
  controlUI.style.borderWidth = '1px'; 
  controlUI.style.cursor = 'pointer'; 
  controlUI.style.textAlign = 'center'; 
  controlUI.title = descripcion; 
  controlDiv.appendChild(controlUI); 
 
  // Set CSS for the control interior 
  var controlText = document.createElement('DIV'); 
  controlText.style.fontFamily = 'Arial,sans-serif'; 
  controlText.style.fontSize = '12px'; 
  controlText.style.paddingTop = '2px'; 
  controlText.style.paddingBottom = '1px'; 
  controlText.style.paddingLeft = '6px'; 
  controlText.style.paddingRight = '6px'; 
  controlText.style.color='#333333';
  controlText.innerHTML = nombre; 
  controlUI.appendChild(controlText); 
 
  // Setup the click event listeners: simply set the map to 
  google.maps.event.addDomListener(controlUI, 'click', funcion);
  google.maps.event.addDomListener(controlUI, 'mouseover', function(){controlText.style.color='#000000';});
  google.maps.event.addDomListener(controlUI, 'mouseout', function(){controlText.style.color='#333333';});
}

// Funciones para AJAX (Prototype)
function obtenerXmlCentrales() { 
	var url = 'xmlDatosEstaciones.php';
	var myAjax = new Ajax.Request( url, { method: 'get', onComplete: resultadoObtenerXMLCentrales});
} 

function resultadoObtenerXMLCentrales(XMLCentrales){
	var xml = XMLCentrales.responseXML.documentElement;
	var image;
	var shadow = 'img/puntoSombra.png';
	var listado = document.getElementById('listaEstaciones');
	delete idEstaciones;
	for (i = 0; i < xml.getElementsByTagName('Estacion').length; i++){
		// Accedemos al objeto XML Estacion
		var item = xml.getElementsByTagName('Estacion')[i];
		// Recojemos los datos de las Estaciones
		var numero = item.getElementsByTagName('numero')[0].firstChild.data;
		var nombre = item.getElementsByTagName('nombre')[0].firstChild.data;
		var latitud = item.getElementsByTagName('latitud')[0].firstChild.data;
		var longitud = item.getElementsByTagName('longitud')[0].firstChild.data;
		var altura = item.getElementsByTagName('altura')[0].firstChild.data;
		var localidad = item.getElementsByTagName('localidad')[0].firstChild.data;
		var provincia = item.getElementsByTagName('provincia')[0].firstChild.data;
		var fechaInstalacion = item.getElementsByTagName('fechaInstalacion')[0].firstChild.data;
		var fechaMuestra = item.getElementsByTagName('fechaMuestra')[0].firstChild.data;
		var temperatura = item.getElementsByTagName('temperatura')[0].firstChild.data;
		var humedad = item.getElementsByTagName('humedad')[0].firstChild.data;
		var precipitacionDia = item.getElementsByTagName('precipitacionDia')[0].firstChild.data;
		var precipitacionSemana = item.getElementsByTagName('precipitacionSemana')[0].firstChild.data;
		var operativa = item.getElementsByTagName('operativa')[0].firstChild.data;

		var titulo = nombre + ' | ' + temperatura + ' ºC | ' + humedad + ' % | ' + precipitacionDia + ' mm | ' + fechaMuestra;

		var myLatLng = new google.maps.LatLng(parseFloat(latitud), parseFloat(longitud));

		idEstaciones[i] = numero;
		
		if (operativa == '1') {
			image =  'img/puntoVerde.png';
		}
		else {
			image =  'img/puntoRojo.png';
			titulo = titulo + ' | MOMENTANEAMENTE FUERA DE SERVICIO';
		}
		
		marcadores[numero] = new google.maps.Marker({position: myLatLng, map: map, icon: image, shadow: shadow, title: titulo, animation: google.maps.Animation.DROP});

		var contentString = '<table width="250" border="0" align="center" cellpadding="5"><tr><td align="center"><span class="Titulo">Estacion '+ nombre +'<br>('+ localidad +')</span></td></tr> <tr><td align="center"><span class="EncabezadoPie"><strong>Ultima actualizaci&oacute;n:<br> '+ fechaMuestra +' Hs.</strong></span></td></tr> <tr><td align="center">&nbsp;</td></tr> <tr><td align="center"><p><span class="Texto">Temperatura: '+ temperatura +' ºC</span></p></td></tr> <tr><td align="center"><span class="Texto">Humedad relativa: '+ humedad +' %</span></td></tr> <tr><td align="center"><p><span class="Texto">Precipitacion del día: '+ precipitacionDia +' mm</span></p></td></tr> <tr><td align="center"><span class="Texto">Precipitaci&oacute;n &uacute;ltimos 7 d&iacute;as: '+ precipitacionSemana +' mm</span></td></tr> <tr><td align="center">&nbsp;</td></tr> <tr><td align="center" class="EncabezadoPie">Instalada el '+ fechaInstalacion +'</td></tr></table>';

		crearBaloon(marcadores[numero], contentString, numero);
		listado.options.add(new Option(nombre, numero));
	} 
	actualizarHora();
}

function actualizarXmlCentrales() { 
	document.getElementById('cargando').src= 'img/cargando.gif';
	var url = 'xmlDatosEstaciones.php';
	var myAjax = new Ajax.Request( url, { method: 'get', onComplete: resultadoActualizarXMLCentrales});
} 

function resultadoActualizarXMLCentrales(XMLCentrales){
	var xml = XMLCentrales.responseXML.documentElement;
	for (i = 0; i < xml.getElementsByTagName('Estacion').length; i++){
		// Accedemos al objeto XML Estacion
		var item = xml.getElementsByTagName('Estacion')[i];
		// Recojemos los datos de las Estaciones
		var numero = item.getElementsByTagName('numero')[0].firstChild.data;
		var nombre = item.getElementsByTagName('nombre')[0].firstChild.data;
		var latitud = item.getElementsByTagName('latitud')[0].firstChild.data;
		var longitud = item.getElementsByTagName('longitud')[0].firstChild.data;
		var altura = item.getElementsByTagName('altura')[0].firstChild.data;
		var localidad = item.getElementsByTagName('localidad')[0].firstChild.data;
		var provincia = item.getElementsByTagName('provincia')[0].firstChild.data;
		var fechaInstalacion = item.getElementsByTagName('fechaInstalacion')[0].firstChild.data;
		var fechaMuestra = item.getElementsByTagName('fechaMuestra')[0].firstChild.data;
		var temperatura = item.getElementsByTagName('temperatura')[0].firstChild.data;
		var humedad = item.getElementsByTagName('humedad')[0].firstChild.data;
		var precipitacionDia = item.getElementsByTagName('precipitacionDia')[0].firstChild.data;
		var precipitacionSemana = item.getElementsByTagName('precipitacionSemana')[0].firstChild.data;

		var titulo = nombre + ' | ' + temperatura + ' ºC | ' + humedad + ' % | ' + precipitacionDia + ' mm | ' + fechaMuestra;
		var contentString = '<table width="250" border="0" align="center" cellpadding="5"><tr><td align="center"><span class="Titulo">Estacion '+ nombre +'<br>('+ localidad +')</span></td></tr> <tr><td align="center"><span class="EncabezadoPie"><strong>Ultima actualizaci&oacute;n:<br> '+ fechaMuestra +' Hs.</strong></span></td></tr> <tr><td align="center">&nbsp;</td></tr> <tr><td align="center"><p><span class="Texto">Temperatura: '+ temperatura +' ºC</span></p></td></tr> <tr><td align="center"><span class="Texto">Humedad relativa: '+ humedad +' %</span></td></tr> <tr><td align="center"><p><span class="Texto">Precipitacion del día: '+ precipitacionDia +' mm</span></p></td></tr> <tr><td align="center"><span class="Texto">Precipitaci&oacute;n &uacute;ltimos 7 d&iacute;as: '+ precipitacionSemana +' mm</span></td></tr> <tr><td align="center">&nbsp;</td></tr> <tr><td align="center" class="EncabezadoPie">Instalada el '+ fechaInstalacion +'</td></tr></table>';
		
		marcadores[numero].setTitle(titulo);
		modificarBaloon(marcadores[numero], contentString, numero);
	} 
	actualizarHora();
	clearTimeout(timer);
	timer = setTimeout('actualizarXmlCentrales();', intervalo);
}

function actualizarHora(){
	var fecha = new Date();
//	var dia = fecha.getDate();
//	var mes = fecha.getMonth() + 1;
//	var anio = fecha.getFullYear();
	var hora = fecha.getHours();
	var minuto = fecha.getMinutes();
	var segundo = fecha.getSeconds();
	
//	if (dia < 10) {dia = '0' + dia;}
//	if (mes < 10) {mes = '0' + mes;}
	if (hora < 10) {hora = '0' + hora;}
	if (minuto < 10) {minuto = '0' + minuto;}
	if (segundo < 10) {segundo = '0' + segundo;}
	
	document.getElementById('actualizacion').innerHTML = 'Actualizado ' + hora + ':' + minuto + ':' +  segundo;
	document.getElementById('cargando').src= 'img/sinImagen.png';
}

//function crearBaloon(marker, message, numero, descripcion) {
//	var infowindow = new google.maps.InfoWindow({ content: message, disableAutoPan: false, size: new google.maps.Size(50,50)});
//	google.maps.event.addListener(marker, 'click', function() {infowindow.open(map,marker);});
//	google.maps.event.addListener(marker, 'click', function() {document.getElementById('descripcion').innerHTML = descripcion;});
//	google.maps.event.addListener(marker, 'click', function() {document.getElementById('imagen').src = "http://www.bolsacer.org.ar/img/estaciones/" + numero + ".jpg";});
//	google.maps.event.addListener(marker, 'click', function() {if (marcadores[numero].getAnimation() != null) {marcadores[numero].setAnimation(null);} else {quitarAnimaciones(); marcadores[numero].setAnimation(google.maps.Animation.BOUNCE);}});
//}

function crearBaloon(marker, message, numero) {
	eventosMarcadores[numero] = google.maps.event.addListener(marker, 'click', function() {openInfoWindow(marker, message);});
	google.maps.event.addListener(marker, 'click', function() {document.getElementById('descripcion').innerHTML = nombreEstacion(numero);});
	google.maps.event.addListener(marker, 'click', function() {document.getElementById('imagen').style.backgroundImage = fotoEstacion(numero)});
	google.maps.event.addListener(marker, 'click', function() {if (marcadores[numero].getAnimation() != null) {marcadores[numero].setAnimation(null);} else {quitarAnimaciones(); marcadores[numero].setAnimation(google.maps.Animation.BOUNCE);}});
}

function modificarBaloon(marker, message, numero) {
	google.maps.event.removeListener(eventosMarcadores[numero]);
	eventosMarcadores[numero] = google.maps.event.addListener(marker, 'click', function() {openInfoWindow(marker, message);});
}

function closeInfoWindow() { 
	infoWindow.close();
}
  
function openInfoWindow(marker, content) { 
	var markerLatLng = marker.getPosition(); 
	infoWindow.setContent([content].join('')); 
	infoWindow.open(map, marker);
}
 
function quitarAnimaciones(){
	for (i = 0; i < idEstaciones.length; i++){
		marcadores[idEstaciones[i]].setAnimation(null);
	}
}

function soloUno() {
	i=0;
	while (document.getElementById('listaEstaciones').length > i) {
 		if (document.getElementById('listaEstaciones').options[i].selected == true) {
			i++;
			for (i;i < document.getElementById('listaEstaciones').length; i++){
				document.getElementById('listaEstaciones').options[i].selected = false ;						 
			}
		}
		i++;
	}
}

function ubicarVistaSeleccion(){
	var id = idEstaciones[document.getElementById('listaEstaciones').selectedIndex];
	if (document.getElementById('listaEstaciones').selectedIndex >= 0) {
		map.setCenter(marcadores[id].getPosition());
		map.setZoom(8);
		closeInfoWindow();
		quitarAnimaciones();
		marcadores[id].setAnimation(google.maps.Animation.BOUNCE);
		document.getElementById('descripcion').innerHTML = nombreEstacion(id);
		document.getElementById('imagen').style.backgroundImage = fotoEstacion(id);
	}
	else {
		alert('Debe seleccionar una estación del listado para poder ir a la misma.');
	}
	document.getElementById('listaEstaciones').focus();
}

function codeAddress() { 
	var address = toCapitalCase(document.getElementById("address").value) + ' Entre Rios Argentina'; 
	if (geocoder) { 
	  geocoder.geocode( { 'address': address}, function(results, status) { 
		if (status == google.maps.GeocoderStatus.OK) { 
		  map.setCenter(results[0].geometry.location); 
		  if (marcador != null) {marcador.setMap(null);}
		  marcador = new google.maps.Marker({ 
			  map: map,  
			  position: results[0].geometry.location,
			  icon: 'http://maps.google.com/mapfiles/kml/shapes/cross-hairs.png',
			  title: address
		  }); 
		} else { 
		  alert("No tuvo exito la búsqueda por: " + status); 
		} 
	  }); 
	} 
}

function toCapitalCase(s) {
	var re = /\s/;
	var words = s.split(re);
	if (s.length > 0) {
		re = /(\S)(\S+)/;
		for (i = words.length - 1; i >= 0; i--) {
			re.exec(words[i]);
			words[i] = RegExp.$1.toUpperCase() + RegExp.$2.toLowerCase();
		}
		return words.join(' ');
	}
	else {return '';}
}

function nombreEstacion(id){
	var descripcion = marcadores[id].getTitle();
	return 'Estacion ' + descripcion.substring(0, descripcion.indexOf(' | '));
}

function fotoEstacion(id){
	return "url(http://www.bolsacer.org.ar/img/estaciones/" + id + ".jpg)";
}
