﻿/* modificaciones del nucleo */
//Array.prototype.indexOf = function(s) {
//	for (var x=0;x<this.length;x++) if(this[x] == s) return x;
//	return false;
//}


/* funciones cross-browser */
function agregarItemACombo(nCombo, nItem)
{
	try
	{
		nCombo.add(nItem, null); // standards compliant
	}
	catch(ex)
	{
		nCombo.add(nItem); // IE only
	}
}

 
/**
 * Clase PuntoDeVenta
 */	
function PuntoDeVenta(sNombre, sDireccion, sCiudad, sEstadoProvincia, sCp, sTelefono, decLatitud, decLongitud)
{
	this._sNombre = sNombre;
	this._sDireccion = sDireccion;
	this._sCiudad= sCiudad;
	this._sEstadoProvincia= sEstadoProvincia;
	this._sCp= sCp;
	this._sTelefono= sTelefono;
	this._decLatitud= decLatitud;
	this._decLongitud= decLongitud;
	//la marca en el mapa
	this._marca;
	this._coordenadas;
	
	this.getCoordenadas=	function()
							{
								if(this._coordenadas== null)
									this._coordenadas= new GLatLng(this._decLatitud, this._decLongitud);
									
								return this._coordenadas;
							};
									
	this.getMarca=	function()
					{
						if(this._marca== null)
						{
							this._marca= new GMarker(this.getCoordenadas());
							//vinculamos la marca con el pdv
							this._marca.padre= this;
							//agregamos un listener para el click
							GEvent.addListener(this._marca, 
								"click", 
								// "mouseover", 
								function(overlay, point) { this.padre.mostrarGlobo();}
							);	
						}
							
						return this._marca;
					};						
						
	this.getContenidoGlobo= function()
							{
								return '<div class="container_datos" width="400px">'
									+ '<img src="../images/gmaps/logo-levis-google-maps.jpg" width="70px" height="70px" />'
									+ '<div class="titulo-globo">'
									+ this._sNombre 
									+ ',</div><p class="parrafo-globo"><br />'
									+ (jQuery.trim(this._sDireccion)!= ""? 'Calle: '+  this._sDireccion+ '<br />': "")
									+ (jQuery.trim(this._sCiudad)!= ""? 'Ciudad: '+  this._sCiudad+ '<br />': "")
									+ (jQuery.trim(this._sEstadoProvincia)!= ""? 'Estado/Provincia: '+  this._sEstadoProvincia+ '<br />': "")
									+ (jQuery.trim(this._sCp)!= ""? 'CP: '+ this._sCp+ '<br />': "")
									+ (jQuery.trim(this._sTelefono)!= ""? 'Tel: '+ this._sTelefono: "")
									+ '</p></div>';
							}

	this.mostrarGlobo= 	function()
						{
							this.getMarca().openInfoWindowHtml(this.getContenidoGlobo());
						}
} 
 
/**
* Clase WebarMap
* Es una clase wrapper para manipular el mapa
*/	
function WebarMap(sIdContenedor, decLatitud, decLongitud, iZoomLevel)
{
	/** 
	 * propiedades
	 */
	//el id del div contenedor
	this._sIdContenedor= sIdContenedor;
	//la latitud inicial
	this._decLatitud= decLatitud;
	//la longitud inicial
	this._decLongitud= decLongitud;
	//el nuvel de zoom
	this._iZoomLevel= iZoomLevel;
	
	//la instancia del mapa
	this._mapa;
	//los puntos de venta
	this._arrPuntosDeVenta= new Array();
	//el nodo contenedor
	this._nodoContenedor= document.getElementById(this._sIdContenedor);

	/** 
	 * eventos
	 */
	//listener para el evento click de la lista
	this._onMapaClickCallBack;
	
	/** 
	 * metodos
	 */
	
	//dibuja el mapa
	this.dibujar= 	function()
					{
						this._mapa= new GMap2(this._nodoContenedor);
						this._mapa.addControl( new GLargeMapControl());
						this._mapa.addControl( new GMapTypeControl());
						this._mapa.setCenter( new GLatLng( this._decLatitud, this._decLongitud), this._iZoomLevel);
						this._mapa.setMapType(G_NORMAL_MAP);
						this._mapa.padre= this;
					}
	
	//genera marcas en el mapa para cada punto de venta
	this.marcarPuntosDeVenta= 	function(pdvACentrar)
								{
									/* for (var i= 0; i < this._arrPuntosDeVenta.length; i++)
									{
										//centramos el mapa en el primero
										// var coordenadas= new GLatLng(this._arrPuntosDeVenta[i]._decLatitud, 
											// this._arrPuntosDeVenta[i]._decLongitud);
											
										if(pdvACentrar && i== pdvACentrar)
											this._mapa.setCenter(this._arrPuntosDeVenta[i].getCoordenadas(), this._iZoomLevel);
											
										// this._arrPuntosDeVenta[i]._marca= new GMarker(coordenadas);
										this._mapa.addOverlay(this._arrPuntosDeVenta[i].getMarca());
									} */
									for (var item in this._arrPuntosDeVenta)
									{
										// if(pdvACentrar && i== pdvACentrar)
											// this._mapa.setCenter(this._arrPuntosDeVenta[i].getCoordenadas(), this._iZoomLevel);
											
										this._mapa.addOverlay(this._arrPuntosDeVenta[item].getMarca());
									}
								}
								
	//muestra un globo con los datos del punto de venta indicado
	this.mostrarGlobo= 	function(iIndice)
						{
							if(this._arrPuntosDeVenta && this._arrPuntosDeVenta.length> iIndice)
								this._arrPuntosDeVenta[iIndice].mostrarGlobo();
						}
				
	//muestra un globo con los datos del punto de venta indicado
	this.centrar= 		function(iIndice)
						{
							if(this._arrPuntosDeVenta && this._arrPuntosDeVenta.length> iIndice)
								this._mapa.setCenter(this._arrPuntosDeVenta[iIndice].getCoordenadas(), this._iZoomLevel);
						}						
	//muestra un globo con los datos del punto de venta indicado
	this.limpiarMarcas= 	function(iIndice)
							{
								this._mapa.clearOverlays();
							}	
	//permite al usuario seleccionar un punto en el mapa, recibe un callback para enviar las coordenadas
	this.habilitarSeleccion= 	function(onMapaClickCallBack)
								{
									this._onMapaClickCallBack= onMapaClickCallBack;
									GEvent.addListener(	this._mapa, "click",	function (overlay, point)
																				{
																					if(point) //esto evita el evento cuando se hace click en una marca
																						this.padre._onMapaClickCallBack(point.lat(), point.lng());
																				}
														);
								}
}

/**
* Clase WebarMapBuscador
* Es una clase wrapper para realizar busquedas por medio del servicio geocoder de google
*/	
function WebarMapBuscador(sIdTextBox, sIdBoton, sIdListaResultados, onListaResultadosClickCallBack)
{
	/** 
	 * propiedades
	 */
	//el id de la caja de texto de busqueda
	this._sIdTextBox= sIdTextBox;
	//el nodo caja de texto de busqueda
	this._nTextBox= document.getElementById(sIdTextBox);
	//el id del nodo boton "buscar"
	this._sIdBoton= sIdBoton;
	//el nodo boton "buscar"
	this._nBoton= document.getElementById(sIdBoton);
	//el id de la lista de resultados
	this._sIdListaResultados= sIdListaResultados;
	//el nodo lista de resultados
	this._nListaResultados= document.getElementById(sIdListaResultados);
	//la instancia de GClientGeocoder
	this._clienteGeoCoder= new GClientGeocoder();
	//un array para guardar los lugares obtenidos en una busqueda, este array se bindea con la lista de resultados
	this._aLugares;

	/** 
	 * eventos
	 */
	//listener para el evento click de la lista
	this._onListaResultadosClickCallBack= onListaResultadosClickCallBack;

	
	
	
	/** 
	 * metodos
	 */
	 
	//limpia la lista de resultados
	this.limpiarResultados= 	function()
								{
									/* for(var i= this._nListaResultados.length; i>= 0; i--)
										this._nListaResultados.remove(i); */
									for(var item in  this._nListaResultados)
										this._nListaResultados.remove(item); 
								}
								
	//agrega un lugar a la lista de resultados
	this.agregarItemALista= 	function(/* Placemark */ unLugar, iIndice)
								{
									var nItem= document.createElement('option');
									nItem.text= unLugar.address;
									nItem.value= iIndice;
									agregarItemACombo(this._nListaResultados, nItem);
								}			
	//codigo ejecutado al hacer un click en la lista
	this.onListaResultadosClick= 	function(lista)
									{
										if(lista.length> 0)
										{
											var indice= $("#"+ this._sIdListaResultados+ " :selected").val();
											var longitud= instancia._aLugares[indice].Point.coordinates[0];
											var latitud= instancia._aLugares[indice].Point.coordinates[1];
											this._onListaResultadosClickCallBack(latitud, longitud);
										}
									}	
	//agregamos el listener al click del item
	instancia= this;
	$("#"+this._sIdListaResultados).change(function () { 
		instancia.onListaResultadosClick(this);
    });

	//recarga los lugares en la lista de resultados
	this.recargarLista= 	function()
							{
								this.limpiarResultados();
								// for(var i= this._aLugares.length; i>= 0; i--)
									// this.agregarItemALista(this._aLugares[i], i);
								for(var item in this._aLugares)
									this.agregarItemALista(this._aLugares[item], item);
							}	
	
	//callback para de la funcion getLocations del GClientGeocoder
	this.mostrarResultados= 	function(response)
								{
									if (!response|| response.Status.code!= 200) 
										alert("error inesperado");
									else
									{
										instancia._aLugares= response.Placemark;
										instancia.recargarLista();
									}
								}
	
	//callback para de la funcion getLatLng del GClientGeocoder
	this.procesarCoordenadas= 	function(coordenadas)
								{
									if (!coordenadas)
										alert("No se obtuvieron resultados, intenta nuevamente");
									else
										instancia._clienteGeoCoder.getLocations(coordenadas, instancia.mostrarResultados);
								}
	
	//busca direcciones segun el texto ingresado
	this.buscar= 	function()
					{
						if(jQuery.trim(instancia._nTextBox.value)== "")
							alert("Debes ingresar alguna dirección a buscar");
						else
						{
							instancia._clienteGeoCoder.getLocations(instancia._nTextBox.value, instancia.mostrarResultados);
						}
					}
					
	//agregamos el listener al click del bonton y al enter de la caja de texto
	$("#"+ this._nBoton.id).bind("click", instancia.buscar);
	
	$("#"+this._sIdTextBox).keypress(	function (e) 
										{
											if (e.which == 13) 
											{
												e.stopPropagation();
												instancia.buscar();
											} 
										}
									);
									
	$("body").keydown(	function (e) 
										{
											if (e.which == 13) 
											{
												return false;
											} 
										}
									);
	
	// $("#"+this._sIdTextBox).bind("onkeypress", function(){
		// if (event.keyCode == 13)
        // {
		    // instancia.buscar();
		// }
    // });
}