
/**
 * Define el manejador de mapas
 */
(function() {
	PorArriba.MapManager = function( _mapIFrameName, placeStart ) {

		if (!_mapIFrameName) {
			alert("Map Iframe Name not assigned.");
			return;
		}
		
		if (isUndefined(placeStart) || placeStart == null || placeStart == ''){
			placeStart = 'mdz';
		}

		this.doingZoom = false;

		//Componente que contiene el mapa
		this.mapIFrame = document.getElementById(_mapIFrameName);

		this.lat = getLatFor(placeStart);
		this.lng = getLngFor(placeStart);
		this.mapType = G_NORMAL_MAP;
		this.zoom = 15;
		this.map = null;
		this.drawingScopeBounds = null;
		this.markerComercio = null;
		
		this.sucursalesMapManager = new PorArriba.SucursalesMapManager( this.map );
		this.lugaresMapManager = new PorArriba.LugaresMapManager( this.map );
		this.callesMapManager = new PorArriba.CallesMapManager( this.map );
		this.callesMapManager.mapManager = this;
		this.lugaresMapManager.mapManager = this;
		
		//Los puntos dibujados para marcar origen y destino en un recorrido de micro
		this.pointsDrawed = new Array();
		this.clickEventListener = null;

		this.loadMap = function (lat, lng, zoom, mapType){
			if (this.map != null) return;
			
			if (lat) { this.lat = lat; }
			if (lng) { this.lng = lng; }
			if (zoom) {this.zoom = zoom;}
			if (mapType) {this.mapType = mapType;}
			
			//if (GBrowserIsCompatible()) {
				this.map = new GMap2(this.mapIFrame);
				
				var mt = this.map.getMapTypes();
				// Overwrite the getMinimumResolution() and getMaximumResolution() methods
				var i = mt.length;
				while (i--){
					mt[i].getMinimumResolution = function() {return 10;}
					mt[i].getMaximumResolution = function() {return 18;}
				}
				
				this.map.addControl(new ControlMap(this.map), new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(7,8)));
				
				//Drag zoom
				var boxStyleOpts = {
		          opacity: .2,
		          border: "2px solid red"
		        }
		
		        var otherOpts = {
		          buttonHTML: "<img src='files/pacontrol/buutonZoom43x38.png' />",
		          buttonZoomingHTML: "<img src='files/pacontrol/buttonZoomSelect43x38.png' />",
		          buttonStartingStyle: {padding: '0px', width: '0px', height: '0px'}
		        };
		       
				this.map.addControl(new DragZoomControl({}, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(7,172)));
				
				// Agrego el control de check de calles
				//this.map.addControl(new PorArriba.CheckCallesControl(), new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(7,7)));
				
				// Agrego los controles paras eleccionar tipo de mapa
				var typeMapControl = new GHierarchicalMapTypeControl();
				// Set up map type menu relationships
				typeMapControl.clearRelationships();
				typeMapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Calles", false);
				this.map.addControl(typeMapControl);
				
				this.map.setCenter(new GLatLng(this.lat, this.lng), this.zoom);
				this.map.setMapType(this.mapType);
				
				this.map.enableContinuousZoom();   // Habilita el zoom continuo
				this.map.enableScrollWheelZoom();
				
				this.updateDependencies();
				GEvent.addListener(this.map, "zoomend", onZoomMap);
				GEvent.addListener(this.map, "moveend", onMoveMap);
				A_SLIDERS[0].e_slider.style.visibility ="hidden";
				
				this.setDrawingScopeBounds();
		     //} else {
		     	//Abria que mostrar una pagina que de ayuda sobre este tema.
		     //	alert("Your browser is not campatible for this web, plese use Firefox or IExplorer.");
		     //}
		}
		
		this.updateDependencies = function () {
			this.sucursalesMapManager.map = this.map;
			this.callesMapManager.map = this.map;
			this.lugaresMapManager.map = this.map;
		}
		
		this.hideMap = function () {
			this.mapIFrame.style.visibility="hidden";
			layoutControl.getBGDegrade().style.zIndex = 1100;
			
			/*Debido a como esta implementado, el slider lo tengo que ocultar explicitamente*/
			A_SLIDERS[0].e_slider.style.visibility ="hidden";
		}
			
		this.showMap = function (){
			this.mapIFrame.style.visibility="visible";
			layoutControl.getBGDegrade().style.zIndex = 0;

			/*Debido a como esta implementado, el slider lo tengo que ocultar explicitamente*/
			A_SLIDERS[0].e_slider.style.visibility ="visible";
			
			this.callesMapManager.initCalles();
		}
		
		this.moveMap = function (x,y) {
			this.mapIFrame.style.left=x;
			this.mapIFrame.style.top=y;
			this.showAdvertising();
		}
		
		this.resizeMap = function (){
			var swf = layoutControl.getSWF();
			var bBar = layoutControl.getBottomBar();

			this.mapIFrame.style.height = swf.clientHeight - parseInt(bBar.style.height) - 10;
			this.mapIFrame.style.width = bBar.clientWidth - swf.clientWidth - 10;
			
			if(this.mapIFrame.style.visibility != "hidden"){
				this.map.checkResize();
				this.callesMapManager.initCalles();
			}
		}

		this.onZoom = function (oldLevel, newLevel) {
			A_SLIDERS[0].f_setValue(newLevel - 10);
			this.doingZoom = true;
		}

		this.onMove = function () {
			if (!this.doingZoom) {
				var bounds = this.map.getBounds();
				var southWest = bounds.getSouthWest();
				var northEast = bounds.getNorthEast();
				var swf = layoutControl.getSWF();
				swf.onMove(this.map.getZoom(), northEast.lat(), northEast.lng() , southWest.lat(), southWest.lng());
			} else {
				this.doingZoom = false;
			}
		}
		
		this.panTo = function (latitude, longitude){
      		var point = new GLatLng(latitude, longitude);
      		this.map.panTo(point);
        }
        
		/**
		 * Crea una nueva area de coordenadas donde se dibuja
		 */
		this.setDrawingScopeBounds = function(forceRefresh) {
			if (isUndefined(forceRefresh)) forceRefresh = false;
			
			var bounds = this.map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();

			var drawingScopePercent = this.callesMapManager.calleStyle.drawingScope;
			var deltaHeight = Math.abs((northEast.lat() - southWest.lat())) * drawingScopePercent;
			var deltaWidth = Math.abs((northEast.lng() - southWest.lng())) * drawingScopePercent;

			var newSouthWest = new GLatLng(southWest.lat() - deltaHeight, southWest.lng() - deltaWidth);
			var newNorthEast = new GLatLng(northEast.lat() + deltaHeight, northEast.lng() + deltaWidth);

			if (this.drawingScopeBounds == null){
				this.drawingScopeBounds = new GLatLngBounds(newSouthWest,  newNorthEast);
				this.callesMapManager.drawCalles(this.map.getZoom());
				this.lugaresMapManager.drawLugares(this.map.getZoom());
			} else {
				if (forceRefresh || this.mustRefresh()) {
					//var d = new Date().getTime();
					this.drawingScopeBounds = new GLatLngBounds(newSouthWest,  newNorthEast);
					this.lugaresMapManager.deleteLugares();
					this.lugaresMapManager.drawLugares(this.map.getZoom());
					this.callesMapManager.deleteCalles(true);

					this.callesMapManager.drawCalles(this.map.getZoom());
					
					if (this.callesMapManager.actualRecorrido != null) {
						this.callesMapManager.deleteActualRecorrido();
						this.callesMapManager.drawActualRecorrido();
					}
					//var d2 = new Date().getTime();
					//alert(d2-d);
					
				}
			}
		}
		
		/**
		 * Verifica si se debe refrescar el mapa
		 */
		this.mustRefresh = function (){
			var bounds = this.map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();

			var oldSouthWest = this.drawingScopeBounds.getSouthWest();
			var oldNorthEast = this.drawingScopeBounds.getNorthEast();

			var deltaScopeHeight = Math.abs((oldNorthEast.lat() - oldSouthWest.lat()) * this.callesMapManager.calleStyle.deltaScopeToReDraw);
			var deltaScopeWidth = Math.abs((oldNorthEast.lng() - oldSouthWest.lng()) * this.callesMapManager.calleStyle.deltaScopeToReDraw);

			return (southWest.lat() - deltaScopeHeight <= oldSouthWest.lat() ||
					southWest.lng() - deltaScopeWidth <= oldSouthWest.lng() ||
					northEast.lat() + deltaScopeHeight >= oldNorthEast.lat() ||
					northEast.lng() + deltaScopeWidth >= oldNorthEast.lng());
		}

		/**
		 * Verifica si un punto se encuentra dentro del area de dibujo.
		 */
		this.dentroDelAreaDeDibujo = function (pLat, pLong) {
			var southWest = this.drawingScopeBounds.getSouthWest();
			var northEast = this.drawingScopeBounds.getNorthEast();

			//puntoContenido(southWestLat, southWestLong, northEastLat, northEastLong, pLat, pLong)
			return puntoContenido(southWest.lat(), southWest.lng(), northEast.lat(), northEast.lng(), pLat, pLong);
		}

		/**
		 * Abre la pagina en ventana completa.
		 */
		this.openToPopUp = function() {
			var newWindow = window.open("index.php","ventana1","width="+ screen.width + ", height=" + screen.height +", top=0, height=0, scrollbars=no, menubar=no, location=no, resizable=yes") ;
			newWindow.focus();
		}
		
		this.newComercio = function (latitude, longitude, description) {
			this.removeNewComercio();
			var point = new GLatLng(latitude, longitude);
			var iconPath = "files/paMarker.png";;
			
			var marker = new GMarker(point, {draggable:true});
			
			marker.comDescription = description;
			GEvent.addListener(marker, 'dragend', 
				function() {
					var swf = layoutControl.getSWF();
					swf.onNewComercioMove(marker.getLatLng());
				}
			);
			
			this.markerComercio = marker;
			this.map.addOverlay(marker);
		}
		
		this.removeNewComercio = function(){
			if(this.markerComercio != null){
				this.map.removeOverlay(this.markerComercio);
				this.markerComercio = null;
			}
		}
		
		this.setSWFWidth = function(width){
			var swf = layoutControl.getSWF();
			swf.width = width;
		}

		this.enableDrawPoint = function(){
			this.clickEventListener = GEvent.bind(this.map, "click", this, function(marker,latlng) {
					this.drawNewPoint(latlng.lat(), latlng.lng());
					GEvent.removeListener(this.clickEventListener);
				}
			);
		}
		
		this.disableDrawPoint = function(){
			GEvent.removeListener(this.clickEventListener);
		}
		
		this.drawNewPoint = function (latitude, longitude) {
			var point = new GLatLng(latitude, longitude);
			
			var marker = new GMarker(point, {draggable:true});
			
			GEvent.addListener(marker, 'dragend', 
				function() {
					var swf = layoutControl.getSWF();
					swf.onNewPointMove(marker.getLatLng().lat(), marker.getLatLng().lng(), marker.pointId);
				}
			);
			
			this.map.addOverlay(marker);
			var pointId = this.pointsDrawed.length;
			this.pointsDrawed[pointId] = marker;
			marker.pointId = pointId;
			var swf = layoutControl.getSWF();
			swf.onNewPointDrawed(latitude, longitude, pointId);
		}
		
		this.deletNewPoint = function(pointId){
			if(this.pointsDrawed[pointId] != null){
				this.map.removeOverlay(this.pointsDrawed[pointId]);
				this.pointsDrawed[pointId] = null;
			}
		}

	}
})();


fileLoaded("MapManager.js");

