/*
 * WikiMapa
 * Copyright (C) 2007 Emilio Mariscal - Proyecto83.com
 * 
 * == BEGIN LICENSE ==
 * 
 * Licensed under the terms of any of the following licenses at your
 * choice:
 * 
 *  - GNU General Public License Version 2 or later (the "GPL")
 *    http://www.gnu.org/licenses/gpl.html
 * 
 *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
 *    http://www.gnu.org/licenses/lgpl.html
 * 
 * == END LICENSE ==
 * 
 * 	File Name  / description( nombre del archivo / descripción):
 *
 * 	lib.js
 *
 * 	Main file ( archivo principal )
 * 
 * File Authors ( autor del archivo ):
 * 		Emilio Mariscal ( emi420@gmail.com )
 */

	var map; // mapa
	var marker ; // marcador
	var allMarkers = [] ; // todos los marcadores
	var mgr ; // marker manager
	var q = '' ; // busqueda
	var activeMarker ; // marcador activo
	var activeMarkerHtml ; // html del marcador activo
	var iconBlue = new GIcon();  // icono azul 
	var searchIsActive = 0 ; // la busqueda esta activa
	var directions = '' ; // rutas
	
    iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(12, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);
	
    function load() {
      if (GBrowserIsCompatible()) {
	  
		// Inicializa el mapa
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(-38.561984, -58.7297), 4);
		mgr = new MarkerManager(map);
		map.setUIToDefault();
		var x= map.getMapTypes(); 
		map.setMapType(x[0]); 
		map.enableScrollWheelZoom();

		//loadMarkers("/stores/genXml/") ;
				
		GEvent.addListener(map, 'moveend', function() {
			loadMarkers("/stores/genXml/") ;
			var bounds = map.getBounds();
			if ( activeMarker ) {
				if ( bounds.contains( activeMarker.getPoint() ) == true )
					activeMarker.openInfoWindowHtml(activeMarkerHtml);
			}
		});
	
	  }
	}
		
	function loadMarkers(url) {

		var q = document.getElementById('location_searchField').value ;
		
		if ( q == '' || q == 'Barrio, ciudad o CP' )
			q = 'BarriociudadoCP' ;
		
		// Tipo de sucursal
		
		var store_type_array = document.getElementById('store_type').getElementsByTagName('input') ;
		var store_type = '' ;
		for ( var i = 0 ; i < store_type_array.length ; i++ ) {
			if( store_type_array[i].checked ) {
				store_type = store_type + store_type_array[i].value + ',' ;
			}			
		}
		store_type = store_type.substring(0,store_type.length - 1) ;
		
		// Filtro de servicios
		
		var store_criteria_array = document.getElementById('store_criteria').getElementsByTagName('input') ;
		var store_criteria = '' ;
        var store_criteria_string = '' ;
		for ( var i = 0 ; i < store_criteria_array.length ; i++ ) {
			if( store_criteria_array[i].checked ) {
				store_criteria = store_criteria + store_criteria_array[i].value + ',' ;
                var lbl =  document.getElementById('label-' + store_criteria_array[i].id) ;
                store_criteria_string = store_criteria_string + lbl.innerHTML + ',' ;
			}			
		}
		store_criteria = store_criteria.substring(0,store_criteria.length - 1) ;
        store_criteria_string = store_criteria_string.substring(0,store_criteria_string.length - 1) ;
		
		var bounds = map.getBounds();
		var latNE = map.getBounds().getNorthEast().lat();
		var longNE = map.getBounds().getNorthEast().lng();
		var latSW = map.getBounds().getSouthWest().lat();
		var longSW = map.getBounds().getSouthWest().lng(); 
			
		q = q.replace('.','') ;
		q = encodeURI(q) ;
		url += q.replace('%','.').replace('%','.') + '/' + latNE + '/' + longNE + '/' +  latSW + '/' + longSW + '/' + store_type + '/' + store_criteria ; 
		
		//alert(url) ;
		//document.location = url ;

		var boton = document.getElementById('submitStoreSearch') ;
		var markersCount = 0 ;
		
		boton.disabled = true ;

		allMarkers = [] ;
		mgr.clearMarkers();
		
		GDownloadUrl(url, function(data) {

			boton.disabled = false ;
			var xml = GXml.parse( data );		
			if (xml.documentElement != null ) {
				var markers = xml.documentElement.getElementsByTagName("marker");
				var cloud = document.getElementById("storelocator-tab1") ;
				var cloudList = cloud.getElementsByTagName('div') ;
				var balloonClass = 'balloon1' ;
				var markerId = ''
				
				while (cloud.hasChildNodes()) cloud.removeChild(cloud.firstChild);
				
				for (var i = 0; i < markers.length; i++) {
					switch( markers[i].getAttribute("store_type") ) {
						case 'Express': balloonClass = 'balloon1' ; break ;
						case 'Mini': balloonClass = 'balloon1' ; break ;
						case 'Super': balloonClass = 'balloon2' ; break ;
						case 'Hiper': balloonClass = 'balloon3' ; break ;
						default: balloonClass = 'balloon1' ; 
					}
											
					markerId = markers[i].getAttribute("id");
					var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
											parseFloat(markers[i].getAttribute("lng")));

					var html = '<div class="tooltip_content"><div class="resultat ' + balloonClass + '">' ;
					if(  markers[i].getAttribute("log") == '1' ) {
						if(  markers[i].getAttribute("mystore") == '' ) {
							html += '<a class="aggiungi add" href="/mi-carrefour/add/' + markers[i].getAttribute("id") + '">Agregar a MiCarrefour</a>' ;
						} else {
							html += '<a class="aggiungi remove" href="/mi-carrefour/del/' + markers[i].getAttribute("id") + '">Eliminar de MiCarrefour</a>' ;
						}
					}
					html += '<p class="balloon_legend">' + markers[i].getAttribute("store_type") + '</p>' ;
					html += '<div class="result_text"><a href="/sucursal/' + markers[i].getAttribute("id") + '">' +  markers[i].getAttribute("store_name") + '</a>' ; 
					html += '<p>' +  markers[i].getAttribute("store_address") +'<br />' +  markers[i].getAttribute("store_zone") ;
					html += ' (' +  markers[i].getAttribute("store_pc") +')<br />' +  markers[i].getAttribute("store_tel") +'</p></div>' ;
					html += '<ul>' ;
					html += '<li><a class="trovar" href="#buscarruta" onclick="showFindRoute(\'' + markers[i].getAttribute("store_address").replace("'","\\'") + ',' + markers[i].getAttribute("store_zone") + '\', \'' + point.lat() + '\', \'' + point.lng() + '\')"><span></span>Encuentra la ruta</a></li>' ;
					if( markers[i].getAttribute("id_region") != '' ) {
						html += '<li><a class="promozioni" href="/folletos/sucursal/' +  markers[i].getAttribute("id") +'"><span></span>Ver folleto</a></li>' ;
					}
					html += '</ul></div></div>' ;

					if (bounds.contains(point) == true)
					{
						allMarkers.push(createMarker(markerId, markersCount, point, html ));
						markersCount++ ;
					}
				}
				
				mgr.addMarkers(allMarkers, 0);
				mgr.refresh();

				if ( searchIsActive ) {
					activeMarker = '' ;
					activeMarkerHtml = '' ;
					map.closeInfoWindow();  
					if ( allMarkers[0] != null ) {
						map.setCenter(  allMarkers[0].getPoint() );
						map.setZoom(13) ;
					}
					searchIsActive = 0 ;
				}

				if( allMarkers.length < 1 ) {
					cloud.innerHTML = '<p>No se encontraron resultados para tu b&uacute;squeda.</p><ul><li>Barrio, ciudad o CP: <strong>' + decodeURI(q) + '</strong></li><li>Tipo de sucursal: <strong>' + store_type + '</strong></li><li>Servicios: <strong>' + store_criteria_string + '</strong></li></ul>';
				}
			}
	
        });
	}
	
	function removeChilds( eTargetElement ) 
	{
		for ( i = 0 ; i < eTargetElement.childNodes.length ; i++ )
		{
			if ( eTargetElement.childNodes[i].length )
				removeChilds( eTargetElement.childNodes[i] ) 
			else
				eTargetElement.removeChild( eTargetElement.childNodes[i] ) ;
		}
	}
	
	function createMarker(markerId, markerIndex, point, html) {
		var marker = new GMarker(point);
		var cloud = document.getElementById("storelocator-tab1") ;
		var div = document.createElement('div');

		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);
			GEvent.addListener( map.getInfoWindow(), 'closeclick',
				function () { activeMarker = '' } );
			activeMarker = marker ;
			activeMarkerHtml = html ;
		});

		div.innerHTML = html ;
		var a = div.getElementsByTagName('a')[0] ;
		if( a.className.substring(0,8) == 'aggiungi' )
			a = div.getElementsByTagName('a')[1] ;
 		a.onclick = function () { showMarker(markerId, markerIndex, point, html)  } ; 
		a.setAttribute('href','#showstore') ;
		cloud.appendChild(div);
	    
		return marker;
	}
		
	function findStores() {
		map.clearOverlays() ;
		if ( directions ) {
			directions.clear() ;
		}
		document.getElementById('getSearchDirections').style.display = 'none' ;
		document.getElementById('controltab2').parentNode.style.display = 'none' ;
	    document.getElementById('searchDirections').style.display = 'block' ; 
	    document.getElementById('storelocator-tab2').style.display = 'none' ; 
	    document.getElementById('storelocator-tab1').style.display = 'block' ; 
		document.getElementById('controltab2').parentNode.setAttribute('class','') ;
		document.getElementById('controltab1').parentNode.setAttribute('class','current') ;
		searchIsActive = 1 ;
        map.setCenter(new GLatLng(-38.561984, -58.7297), 3);
		loadMarkers("/stores/genXml/") ;
	}
	
	function showFindRoute(from, lat, lng) {
		map.clearOverlays() ;
		if ( directions ) {
			directions.clear() ;
		}
		document.getElementById('controltab2').parentNode.setAttribute('class','current') ;
		document.getElementById('controltab2').parentNode.style.display = 'block' ;
		document.getElementById('controltab1').parentNode.setAttribute('class','') ;
		document.getElementById('storelocator-tab1').style.display = 'none' ;
		document.getElementById('storelocator-tab2').style.display = 'block' ;
		document.getElementById('directions_to').value = from ;
		document.getElementById('waypoint_from').value = lat + ',' + lng ;
		document.getElementById('get_directions').style.display = 'block' ; 
	}
	
	function findRoute() {
		// load directions
		map.clearOverlays() ;
		map.closeInfoWindow();
		activeMarker = '' ;
		activeMarkerHtml = '' ;
		var wp = document.getElementById('waypoint_from').value.split(',') ;
		var directionsPanel = document.getElementById('storelocator-tab2') ;
		var msg = document.getElementById('msgsearchDirections') ;
		msg.innerHTML = 'Buscando...' ;
		msg.style.display = 'block' ;
	    document.getElementById('get_directions').style.display = 'none' ; 
		directions = new GDirections(map, directionsPanel);
		directions.load("from: " + document.getElementById('directions_from').value + " to: " + wp[0] + ',' + wp[1], { "locale": "es" }, {"getDistance" : true}); 		
	    GEvent.addListener(directions, "load", onDirectionsLoad ) ;
	    GEvent.addListener(directions, "error", onDirectionsError ) ;
	}

	function onDirectionsLoad() {
 	 mgr.clearMarkers();
	 document.getElementById('getSearchDirections').style.display = 'block' ;
	 document.getElementById('msgsearchDirections').style.display = 'none'  ;
	}

	function onDirectionsError() {
	 document.getElementById('msgsearchDirections').innerHTML = '<strong>No se encontraron resultados</strong>. Revisa tu b&uacute;squeda por favor.' ;
     document.getElementById('get_directions').style.display = 'block' ; 
	}

	function showMarker(markerId, markerIndex, point, html) {
		marker = allMarkers[markerIndex];
		marker.openInfoWindowHtml(html);
		GEvent.addListener( map.getInfoWindow(), 'closeclick',
				function () { activeMarker = '' } )
		activeMarker = marker ;
		activeMarkerHtml = html ;
	}
			
	/*
	  * checkEnter
	  * By Jennifer Madden
	  * http://jennifermadden.com/javascript/stringEnterKeyDetector.html
	 */ 
	function checkEnter(e, action)
	{
		var characterCode
	
		if( e && e.which )
		{
			e = e ;
			characterCode = e.which ;
		} else {
			e = event ;
			characterCode = e.keyCode ;
		}
	
		if(characterCode == 13) {
			switch ( action ) {
				case 'findRoute': findRoute() ; break ;
				default: findStores() ;
			}
			return false ;
		} else {
			return true ;
		}
	}
	
    