/**
 * Implements planos API stuff
 * Veja mais detalhes em http://linuxas.pgnet.cl:8180/api/examples/example1.html
 * e em http://linuxas.pgnet.cl:8180/api/services/js/ApiRequestService?v=2.0&key=uuu
 */
 
var flickr_zIndexOn = 900000;

var CPlanos2Map = function(parent, eventHandler) {
    var _map = new cl.publiguias.planos.Map(parent.id);
    var _this = this;
	
	var templates = new JSCache();
	var layersCache = new JSCache();
	var flickrCache = new JSCache();

    _map.getZoomEvent().subscribe(function(o, args) {
		logInfo('/zoom');				
        eventHandler.focusChanged(_this.getCenter(), args[0], _this.getSouthWest(), _this.getNorthEast());
    });

    _map.getNewCenterEvent().subscribe(function(e, args) {
    	var currentPoint = _map.findPosition(new cl.publiguias.planos.GeoPoint(args[0]._latitude, args[0]._longitude));
		var oldPoint = _map.findPosition(new cl.publiguias.planos.GeoPoint(currentLatitude, currentLongitude));
		var displacement = ( ( Math.abs(currentPoint._left - oldPoint._left) + Math.abs(currentPoint._top - oldPoint._top ) ) / 2 );
		
		if ( displacement >= 250 ){
			logInfo('/desplazamiento');
		}
		
		currentLatitude = args[0]._latitude;
		currentLongitude = args[0]._longitude;
		
		var zoomLevel = _map.getZoomLevel();
		eventHandler.focusChanged(_this.getCenter(), zoomLevel , _this.getSouthWest(), _this.getNorthEast());
    });
	
    this.setFocus = function(center, zoomLevel) {
    	_map.setFocus(new cl.publiguias.planos.GeoPoint(center.getLatitude(), center.getLongitude()), zoomLevel);
    	
    }
	
    this.createMarker = function(options, point, icon, type) {
		return new CPlanos2Marker(options, point, icon, _map, type);
	}
	
    this.initFocus = function(center, zoomLevel) {
        _map.draw(new cl.publiguias.planos.GeoPoint(center.getLatitude(), center.getLongitude()), zoomLevel);
        eventHandler.focusChanged(_this.getCenter(), _map.getZoomLevel(), _this.getSouthWest(), _this.getNorthEast());
    }
    
     this.setFocusByBoundary = function(center, sw, ne, zoomMax) {
     	var zl = _map.getZoomLevel();
    	
    	if ((sw.getLatitude() != ne.getLatitude()) && (sw.getLongitude() != ne.getLongitude())) {
    		zl = _getPlanos2Zoom(sw.getLatitude(), sw.getLongitude(), ne.getLatitude(), ne.getLongitude());
    	}
     
     	this.setFocus(center, zl);
    }
    
    var _getPlanos2Zoom = function(minLat, minLon, maxLat, maxLon){             
       var deltaLat = maxLat - minLat;
       var deltaLon = maxLon - minLon;
       var zoomLat = 0;
       var zoomLon = 0;
      
       var lats = new Array(0.002354716436087756, 0.0047094332287400675, 0.009418866486058164,
       						0.018837738848638708, 0.03767550211772175, 0.07535110923186039,
       						0.1507026969636982, 0.30140633021368757, 0.6028259322601457,
       						1.2057117486581461, 2.411901767229267, 4.827970238241285,
       						9.686934813351769, 19.586445053641135, 40.32528367759949,
       						83.44200181390545, 168.35910573481115, 336.79682502555625);
       
	   var lons = new Array(0.004689769269361932, 0.009379539248897117, 0.018759078554694497,
	   						0.03751816881336367, 0.07503638626369025, 0.15007298164340455,
	   						0.3001469162909558, 0.6002956973358096, 1.2006178265076812,
	   						2.401354923206398, 4.803662392335539, 9.615623396215412,
	   						19.2929766589008, 39.00932897936981, 80.31382177121905,
	   						166.18720195738797, 335.3122899185969, 670.7811504684274);
      							
      for (var i=0; i<lats.length; i++) {
      	if(lats[i]>deltaLat){
      		zoomLat = i;
      		break; 
      	}      
      }	
      
      for (var j=0; j<lons.length; j++) {
      	if(lons[j]>deltaLon){
      		zoomLon = j;
      		break;
      	}      
      }         
      
      if(zoomLat >= zoomLon){
      	  return zoomLat;
      }else{
      	  return zoomLon;
      } 
           
    }    
	
	this.getCenter = function() {
        return new cl.publiguias.planos.GeoPoint(_map.getCenter().getLatitude(),_map.getCenter().getLongitude());
    }
    
    this.setCenter = function(center) {
    	_map.moveTo(new cl.publiguias.planos.GeoPoint(center.getLatitude(), center.getLongitude()));
    }
	
	this.getSouthWest = function() {
        var p = _map._findBoundary().getSouthWest();
        return new CPoint(formatNumber(p.getLongitude()), formatNumber(p.getLatitude()));
    }

    this.getNorthEast = function() {
        var p = _map._findBoundary().getNorthEast();
        return new CPoint(formatNumber(p.getLongitude()), formatNumber(p.getLatitude()));
    }
	
	this.plotOpen = function(id, advId, acts) {
		var elId = $D.get('infoWindowPlot' + id);
		var eventType;
		var elWidth, elHeight;
		
		//console.log([id, advId, acts]);

		if(acts != 'flickr') {
			$D.addClass(elId.parentNode, 'openZindex');
		}
		
		if (elId){
			if (elId.className == 'plotAddress' || elId.className == 'plotRoute'){
				eventType = '/infoCalle';
			} else {
				eventType = '/infoEmpresa';
			}
			
			//logInfo(eventType);
					
			if ($D.hasClass(elId,'plotBusinessAdTop') || $D.hasClass(elId,'box2')) {
				MegaBlasterOpen(advId, acts, id)				
				elId.className = 'box2';
				elWidth = 350;
				elHeight = 320;//260
			} else if ((elId.className == 'plot') && (acts == 'bullet')) {
				showBulletDetail($D.get('bulletContent' + id),advId);
				elId.className = 'box3';
				elWidth = 290;
				elHeight = 200;
			} else if ($D.hasClass(elId,'plotPanoramico')) {
				showPanoramicoDetail($D.get('iconContent' + id),advId);
				elId.className = 'box4';
				elWidth = 582;
				elHeight = 264;
		  
		  	} else if ($D.hasClass(elId,'plotFlickr')) {// flickr
			
				flickrId = 'Flickr' + id;			
				flickrCache.add(flickrId, flickrId); // utilizado posteriormente no flickrHideAll
			
			  	if(__monitor == undefined || __monitor == null){
	        		__monitor = new ActivityMonitor();
	        	}
	        
		  		__monitor.on();

				var thumb = $D.getElementsByClassName('flickrPhoto', 'img', elId)[0];
				var balloonContainer = $D.get("balloonFlickr"+id);
				var photo_src = thumb.src.replace('_s.jpg','_m.jpg');
												
				var text = balloonContainer.innerHTML;
				var infoChildsTagA = balloonContainer.getElementsByTagName("a");
				//var infoTitle = textChilds[1].getElementsByTagName("*");
				
				var photo =	[];
				var htmlballoon = [];
				var linkPhoto =  $D.get("linkFlickr"+id);
				//console.log([linkPhoto]);
				var elLatLng = elId.getAttribute('rel');//coordenadas do box para atualizar posição do mapa no resample;
				
				photo.push('<a href="' + linkPhoto.href + '" target="_blank" title="'+linkPhoto.title+'"/>');
				photo.push('<img id="flickrIMG'+id+'" class="flickrMPhoto" src="'+photo_src+'" ');
				if(!IE6) photo.push('onload="map.resample(this, \''+id+'\', \''+elLatLng+'\')"');
				photo.push(' />');
				photo.push('</a>');
						
				//balloon tag
				/*
				
				htmlballoon.push(   '<div class="flickrBalloon" 			id="flickrballoon'+id+'" style="position:absolute">');
			    htmlballoon.push(   '<div class="bgFlickr fkr_top_right"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_top" 			id="flckr_t'+id+'"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_top_left">');
			    htmlballoon.push(	'<a href="javascript://" class="infoClose" onclick="map.flickrHide(\''+flickrId+'\');return false"><!--//--></a>');
			    htmlballoon.push(	'</div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_right" 		id="flckr_r'+id+'" ><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_content" 		id="flickrContent'+id+'" style="height:auto; position: relative;">');
			    htmlballoon.push(	photo.join('')	);
			    htmlballoon.push(	text	);
			    htmlballoon.push(   '</div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_left" 			id="flckr_l'+id+'"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_bottom_right"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_bottom" 		id="flckr_b'+id+'"><div class="bgFlickr fkr_ie6Bottom"><!--//--></div></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_bottom_left"><!--//--></div>');
			  	htmlballoon.push(   '</div>');
			  	*/
			  	
			  	htmlballoon.push(   '<div class="flickrBalloon" 			id="flickrballoon'+id+'" style="position:absolute">');
			    htmlballoon.push(   '<div class="bgFlickr fkr_top_right" style="position: absolute; top: 0px; left: 0px;"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_top" 			id="flckr_t'+id+'" style="position: absolute; top: 0px; left: 17px;"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_top_left" style="position: absolute; top: 0px; right: 0px;">');
			    htmlballoon.push(	'<a href="javascript://" class="infoClose" onclick="map.flickrHide(\''+flickrId+'\');return false"><!--//--></a>');
			    htmlballoon.push(	'</div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_right" 		id="flckr_r'+id+'" style="position: absolute; top: 17px; left: 0px;"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_content" 		id="flickrContent'+id+'" style="height:auto; position: relative; top: 17px; left: 17px;">');
			    htmlballoon.push(	photo.join('')	);
			    //htmlballoon.push(	text	);
			    htmlballoon.push(	'<div id="infoFlickrA'+id+'" style="position: absolute; left: 0px;"><strong>'+linkPhoto.title+'</strong></div>'	);
			    htmlballoon.push(	'<div id="infoFlickrB'+id+'" style="position: absolute; left: 0px;"><a href="'+infoChildsTagA[1].href+'" target="_blank">'+infoChildsTagA[1].innerHTML+'</a></div>'	);
			    htmlballoon.push(	'<div id="infoFlickrC'+id+'" style="position: absolute; right: 0px;"><a href="'+infoChildsTagA[2].href+'" target="_blank" border="0">'+infoChildsTagA[2].innerHTML+'</a></div>'	);
			    htmlballoon.push(   '</div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_left" 			id="flckr_l'+id+'" style="position: absolute; top: 17px; right: 0px;"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_bottom_right" id="flckr_br'+id+'" style="position: absolute; left: 0px;"><!--//--></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_bottom" 		id="flckr_b'+id+'" style="position: absolute; left: 17px;"><div class="bgFlickr fkr_ie6Bottom"><!--//--></div></div>');
			    htmlballoon.push(   '<div class="bgFlickr fkr_bottom_left"  id="flckr_bl'+id+'" style="position: absolute; right: 0px;"><!--//--></div>');
			  	htmlballoon.push(   '</div>');
			  	
			  	if(!$D.hasClass(balloonContainer, "called")){			
					balloonContainer.innerHTML = htmlballoon.join("");
				}	
				
				$D.addClass(balloonContainer, "called");
				
				if(IE6){	
					var ie6load = new ie6_onloadImg("map.resample",balloonContainer, id, elLatLng);
					ie6load.execute(ie6load);
				}
				
				infoWindow  = null; thumb = null; photo = null;
				
			} else {
				elId.className = 'box1';
				elWidth = 290;
				elHeight = $D.getElementsByClassName('boxContainer','div',elId)[0].clientHeight;
			}
			
			elId.parentNode.style.zIndex = ++window_zIndexOn;
			$E.addListener(elId.parentNode, 'click', levelUp);
				
			this.centerBox(elWidth, elHeight, elId.getAttribute('rel'));//função criada para centralizar o box;
		}
	}
	
	this.flickrHide = function(id){//ativo apenas no flickr	
		flickrCache.remove(id);
		
		$D.get("balloon"+id).style.display = "none";
		$D.get("thumb"+id).style.display = "block";
		$D.get("thumb"+id).onclick = function(){
			map.flickrShow(id);
		}
		$D.get("balloon"+id).parentNode.parentNode.style.zIndex = 1;		
	}
	
	this.flickHideAll = function() {
		var ids = flickrCache.getAll();
		for (var i = 0; i < ids.length; i++) {
			_this.flickrHide(ids[i]);
			__monitor.off();
		}
	}
	
	this.flickrShow = function(id){
		flickrCache.add(id, id); // utilizado posteriormente no flickrHideAll
		
		$D.get("thumb"+id).style.display = "none";
		$D.get("balloon"+id).style.display = "block";
		//$D.get("balloon"+id).parentNode.parentNode.style.zIndex = ++flickr_zIndexOn;
		$D.get("balloon"+id).parentNode.parentNode.style.zIndex = ++window_zIndexOn;
		
		if($D.get("infoFlickrC"+id) != null) $D.get("infoFlickrC"+id).style.zIndex = ++window_zIndexOn;
		
		var _id = id.replace("Flickr",""); 
		
		var coords = $D.get('infoWindowPlot'+_id).getAttribute('rel');
		var balloon = $D.get('flickrballoon'+_id);//largura + 17 + 17
		
		var centerHeight = balloon.offsetHeight + 50;
		var centerWidth = balloon.offsetWidth + 50;

		this.centerBox(centerWidth, centerHeight, coords);
	}
	
	// Flickr
	this.plotExpand = function(id) {		
		var divOverlay = $D.getElementsByClassName("flickrOverlayMini", "div", ("infoWindowPlot" + id))[0];
		$D.replaceClass(divOverlay, "flickrOverlayMini", "flickrOverlay");
		var photo = $D.getElementsByClassName("flickrPhoto", "img", ("infoWindowPlot" + id))[0];
		photo.height = photo.width = 75;
		$D.setStyle(photo,'position','absolute');
		$D.setStyle(photo,'left','-30px');
		$D.setStyle(photo,'top','-30px');
	}
	
	// Flickr	
	this.plotShrink = function(id) {
		var divOverlay = $D.getElementsByClassName("flickrOverlay", "div", ("infoWindowPlot" + id))[0];
		$D.replaceClass(divOverlay, "flickrOverlay", "flickrOverlayMini");
		var photo = $D.getElementsByClassName("flickrPhoto", "img", ("infoWindowPlot" + id))[0];
		photo.height = photo.width = 20;
		$D.setStyle(photo,'position','absolute');
		$D.setStyle(photo,'left','-1px');
		$D.setStyle(photo,'top','-1px');
	}
	
    this.plot = function(name, description, point, ord, type, advIcon, advId, acts, flickr, typeNumber) {
    	var geoPoint = new cl.publiguias.planos.GeoPoint(point.getLatitude(), point.getLongitude());
		//alert([acts]);
		var icone = new CIcon(point, ord, name, description, type, geoPoint, advId, advIcon, flickr, acts);
		var planosIcon = new CPlanosIcon(icone.getHtml());
		icone = null;
                
        var layer = null;
        // se for um IPoint ou similar, cria um layer com essa finalidade        
        if ((type == 'Icon') || (type == 'Bullet') || (type == 'Panoramico') || (type == 'Flickr')) {
        	
        	layer = layersCache.get(typeNumber);
        	if (!layer) {
        		layer = new cl.publiguias.planos.MapLayer(_map);  
        		layersCache.add(typeNumber, layer);
        	}
        } else {
        	// ou usa o layer padrão do mapa
        	layer = _map;
        }
        
		return layer.addDecoration(planosIcon, geoPoint);
	}
	//exibe o balão após loading da imagem, usado para contornar a falta do evento onload em imagens no ie6
	this.resample = function(img, id, coords) {
				
		if (!isMapFeatureEnabled('flickr')) return;
		
		var _thumb = $D.get('thumbFlickr'+id);
		var _balloon = $D.get('balloonFlickr'+id);
		var balloon = $D.get('flickrballoon'+id);//largura + 17 + 17
		
		var balloon_Content = $D.get('flickrContent'+id);//largura + altura
		
		_thumb.style.display = "none";
		_balloon.style.display = "block";
		_balloon.parentNode.parentNode.style.zIndex = ++window_zIndexOn;
		var posLeft = -(img.width/2) - 5;
				
		balloon.style.width = Math.ceil(img.width) + 34 + "px";
		
		$D.get('flckr_t'+id).style.width = img.width + "px";//balloonTop/Bottom
		$D.get('flckr_b'+id).style.width = img.width + "px";//balloonTop/Bottom
		
		$D.get('flickrContent'+id).style.width = img.width + "px";//balloonContent
		$D.get('flickrContent'+id).style.height = parseInt(50) + img.height + "px";//balloonContent
				
		balloon.style.display="block";
		_balloon.style.visibility = "visible";
		
		var elHeight = balloon.offsetHeight;
		var elWidth = balloon.offsetWidth;
		
		balloon.style.left 	= "-"+ ((elWidth / 2) - 10) + "px";
		balloon.style.top 	= "-"+ (elHeight - 12) + "px";
		
		$D.get('flckr_l'+id).style.height = $D.get('flickrContent'+id).offsetHeight + "px";//balloonLeft/Right
		$D.get('flckr_r'+id).style.height = $D.get('flickrContent'+id).offsetHeight + "px";//balloonLeft/Right
		
		$D.get('flckr_br'+id).style.top = $D.get('flickrContent'+id).offsetHeight + parseInt(17) + "px";
		$D.get('flckr_b'+id).style.top = $D.get('flickrContent'+id).offsetHeight + parseInt(17) + "px";
		$D.get('flckr_bl'+id).style.top = $D.get('flickrContent'+id).offsetHeight + parseInt(17) + "px";
		
		$D.get('infoFlickrA'+id).style.top = parseInt(5) + img.height + "px";
		$D.get('infoFlickrB'+id).style.top = parseInt(25) + img.height + "px";
		$D.get('infoFlickrC'+id).style.top = parseInt(35) + img.height + "px";
		$D.get('infoFlickrC'+id).style.left = parseInt(-38) + img.width + "px";
		
		var centerHeight = elHeight + 70;
		var centerWidth = elWidth + 210;

		this.centerBox(centerWidth, centerHeight, coords);
		
		__monitor.off();
	}
	
	
	this.centerBox = function (elWidth, elHeight, coords){
		//mover o mapa qdo a photo não ficar visivel;
		var moveToX, moveToY;
		var elLatLng = coords.split(',');
		var elPos = map.latLngToPixel(new CPoint(elLatLng[1],elLatLng[0]));
		var moveToLat = map.getCenter()._latitude;
		var moveToLng = map.getCenter()._longitude;
		
		var elBottom = elPos._top;
		var elCenter = elPos._left;
		var elTop = elBottom - elHeight;
		var elLeft = elCenter - (elWidth / 2);
		var elRight = elCenter + (elWidth / 2);
		
		var mapTop = 0;
		var mapLeft = 0;
		var mapBottom = map.latLngToPixel(new CPoint(map.getSouthWest().getY(),map.getNorthEast().getX()))._top;
		var mapRight = map.latLngToPixel(new CPoint(map.getSouthWest().getY(),map.getNorthEast().getX()))._left;
		var mapCenter = map.latLngToPixel(new CPoint(map.getCenter()._latitude,map.getCenter()._longitude));
		
		var rightAd = 0;
		
		if ($D.get('rightAd')) {
			rightAd = $D.get('rightAd').clientHeight;
		}
		
		var posTop = (elTop) - (mapTop) + 6;
		var posBottom = (mapBottom - rightAd) - (elBottom);
		var posLeft = (elLeft) - (mapLeft);
		var posRight = (mapRight) - (elRight);

		var moveX = false;
		var moveY = false;

		if (posTop < 10) {
			moveX = (elTop - 10);
		} if (posBottom < 10) {
			moveX = (- posBottom + 10);	
		} if (posLeft < 10) {
		} if (posRight < 10) {
			moveY = (- posRight + 10);
		} if ( posBottom < 135 && posRight < 170 && (!$D.hasClass('mapMini','off')) ) {
			if ( posBottom > 65 ) { // MINIMAP TOP
				moveX = (- posBottom + 6 + 130);
				
			} else { // MINIMAP LEFT
				moveY = (- posRight + 170);
				
				
			}
		}  else if ( posBottom < 40 && posRight < 40 ) { // CLOSED MINIMAP
			moveX = (- posBottom + 35);
			
		}  if ( posTop < 45 && posRight < 95 ) { // CONTROLS
			moveX = (elTop - 45);
			
		} if ( posTop < 220 && posLeft < 40 ) { // ZOOM
			moveY = (elLeft - 40);
			
		} if ( posBottom < 60 && posLeft < 130 ) { // LOGO PUBLIGUIAS
			moveX = (- posBottom + 50);
			
		}
		
		if (moveX || moveY) {
			if (moveX) {
				moveToX = mapCenter._top + moveX;
				moveToLat = map.pixelToLatLng(new CPoint(0, moveToX)).getLatitude();
			}			
			if (moveY) {
				moveToY = mapCenter._left + moveY;
				moveToLng = map.pixelToLatLng(new CPoint(moveToY, 0)).getLongitude();
			}
			map.setCenter(new CPoint(moveToLng,moveToLat));
		}
	
	}
	
	
	
	this.hideLayer = function(type) {
		var layer = layersCache.get(type);
		if (layer) layer.hide();
	}
	
	this.showLayer = function(type) {
		var layer = layersCache.get(type);
		if (layer) layer.show();
	}
	
	this.clearLayers = function() {
		var layers = layersCache.getAll(); 
		for (var i = 0; i < layers.length; i++) {
			var layer = $D.get(layers[i]._idDiv);
			layer.parentNode.removeChild(layer);			
		}
		layersCache.clear();
	}	

    this.clear = function() {
		_map.clear();
    }

    this.zoomIn = function() {
		_map.zoomIn();
    }

    this.zoomOut = function() {
		_map.zoomOut();
	}

    this.getZoom = function() {
         return _map.getZoomLevel();
    }

	this.setZoom = function(zoom) {
		_map.zoomTo(zoom);
	}
	
	this.move = function(e,o) {

		var _o = o || {};
		var movement = 100;
		var pixelX = map.latLngToPixel(new CPoint(map.getCenter()._latitude,map.getCenter()._longitude))._top;
		var pixelY = map.latLngToPixel(new CPoint(map.getCenter()._latitude,map.getCenter()._longitude))._left;

		if (o[1].type == 'keydown') {
			
			if (o[1].ctrlKey == true) movement *= 2; //CTRL
			if (o[1].shiftKey == true) movement /= 2; //SHIFT
			if (o[0] == 38) pixelX -= movement; //UP
			if (o[0] == 40) pixelX += movement; //BOTTOM
			if (o[0] == 37) pixelY -= movement; //LEFT
			if (o[0] == 39) pixelY += movement; //RIGHT
			
			var latLng = map.pixelToLatLng(new CPoint(pixelY,pixelX));
			map.setCenter(new CPoint(latLng.getLongitude(),latLng.getLatitude()));
			
			keyMove.disable();
			keyMoveCtrl.disable();
			keyMoveShift.disable();
			keyMoveUp.enable()
			keyMoveCtrlUp.enable();
			keyMoveShiftUp.enable();
		} else {
			keyMove.enable()
			keyMoveCtrl.enable();
			keyMoveShift.enable();
			keyMoveUp.disable();
			keyMoveCtrlUp.disable();
			keyMoveShiftUp.disable();
		}
	}
	
	this.print = function() {
		_map.print();
	}

	this.mailForm = function() {
		_map.showMailForm(true);
	}

	
	this.wheelDisable = function() {
		_map.disableScrollWheelZoom(); // Deshabilita el scroll del mouse
	}
	
	this.wheelEnable = function() {
		_map.enableScrollWheelZoom(); // Habilita el scroll del mouse
	}
	
	this.wheelZoom = function() {
		_map.scrollWheelZoomEnabled(); // return boolean, para consultar el estado del feature
	}

	this.pixelToLatLng = function(point) {
		var geoPoint = _map.findGeoPoint(new cl.publiguias.planos.Position(point.getX(), point.getY()));
		return new CPoint(geoPoint.getLongitude(), geoPoint.getLatitude());
	}
	
	this.latLngToPixel = function(geopoint) {
		var point = _map.findPosition(new cl.publiguias.planos.GeoPoint(geopoint.getLongitude(), geopoint.getLatitude()));
		return point;
	}
	
	this.updateSize = function() {
		_map.refresh();
	}	
	
	this.clearRoutes = function() {
		var canvases = _map.getCanvases();
		for (var i = 0; i < canvases.length; i++) canvases[i].clear();
	}
	
	this.plotRoute = function(waypoints) {
		
		var geoPoints = [];
				
		var maxLat = waypoints[0].y;
		var minLat = waypoints[0].y;
		var maxLng = waypoints[0].x;
		var minLng = waypoints[0].x;
		
		for (var i = 0; i < waypoints.length; i++) {
			lat = waypoints[i].y;
			lng = waypoints[i].x;
			
			geoPoints.push(new cl.publiguias.planos.GeoPoint(lat, lng));
			
			// faz calculo do boundary da rota
			maxLat = lat > maxLat ? lat : maxLat;
			maxLng = lng > maxLng ? lng : maxLng;			
			minLat = lat < minLat ? lat : minLat;
			minLng = lng < minLng ? lng : minLng;
		}
		
		// centraliza o mapa
		var	zl = _getPlanos2Zoom(minLat, minLng, maxLat, maxLng);
		var latCenter = ((minLat - maxLat) / 2) + maxLat;
		var lngCenter = ((minLng - maxLng) / 2) + maxLng;    	
     	this.setFocus(new CPoint(lngCenter, latCenter), zl);
     	
     	// desenha a rota
     	var canvas = _map.createCanvas(); 
		//canvas.drawLine(geoPoints, "#FF0000", 4); //ANTIGO SEM OPACIDADE
		canvas.drawLine(geoPoints, "rgba(255, 0, 0, 0.5)", 4);	     	
	}
		
	this.getProportion = function() {
		// largura em pixels
		var widthPx = _map.getSize().getWidth();
		// altura em pixels
		var heightPx = _map.getSize().getHeight();				
				
		// largura em graus
		var widthLng = Math.abs(_this.getNorthEast().getLongitude() - _this.getSouthWest().getLongitude());
		// altura em graus
		var heightLat = Math.abs(_this.getNorthEast().getLatitude() - _this.getSouthWest().getLatitude());
		
		var pX = widthLng / widthPx;
		var pY = heightLat / heightPx;
		
		return [pX, pY]; 		
	}
	
    // antiga gambetaToNumber
    var formatNumber = function(n) {
        if (typeof(n) != 'number') {
            var ns = n.split('.');
            if (ns.length == 1 || ns.length == 2) {
                return n;
            } else {
                var result = parseFloat(ns[0] + '.' + ns[1]);
                return result;
            }
        } else {
            return n;
        }
    }
    
	/*
	 * Planos2 implementation of CMarker Interface
	 */
	var CPlanos2Marker = function(options, point, icon, map, type) {
		var me = this;
		var _options = options;
		var _point = point;
		var _map = map;
		var _divId;
		
		this.hide = function() {
			/*var layers = layersCache.get(map.getZoomLevel())
			if (layers) {
				var layer = layers.get(options.type.number);
				if (layer && layer.isVisible()) layer.hide();
			}*/						
			$D.setStyle(_divId, "display", "none");
		}
		 
		this.show = function() {
			/*var layers = layersCache.get(map.getZoomLevel())
			if (layers) {
				var layer = layers.get(options.type.number);
				if (layer && !layer.isVisible()) layer.show();
			}*/			
			if ($D.get(_divId)) $D.setStyle(_divId, "display", "");
			else me.plot();
		}
		
		this.plot = function() {
			_divId = _this.plot(options.name, options.description, point, icon, type, null, options.id, null, options.content, options.type.number);
		}
		
		this.getId = function() {
			return _options.id;	
		}
		
		this.getName = function() {
			return _options.name;
		}
		
		this.getType = function() {
			return _options.type;	
		}
		
		this.getDescription = function() {
			return _options.description;
		}
		
		this.getPoint = function() {
			return _point;
		}	
		
	}

}

var CPlanosIcon = function(html) {
	this.getSize = function() {
		return new cl.publiguias.planos.Size(0, 0);
	};

	this.getDrawingOffset = function() {
		return new cl.publiguias.planos.Size(0, 0);
	};

	this.getHTML = function() {
        return html;
	}
}

CPlanos2Map.prototype = new CMap();
//CPlanos2Marker.prototype = new CMarker();
