    var map, newMarker, currentMarker, timer;
    var marcadoresJs = new Array();
    var friendMarkerList = new Array();
    var toolTipMarcadores;
    var chosen = [];   
    var lastMarkerArray;
    var pe; // Periodical Executer
    var minfo_content, media_content, comments_content,associations_content;
    var tempinfo = "<p>Loading...</p><script>setTimeout('map.getInfoWindow().maximize()',500);</script>";
    
    //	Hidrotonico i9 Config
    var hidrotonicoi9 = null;
    var hidrotonicoi9_idApp = 309;
    
    var podeCarregarEventos = true;
    var qtdMoveMap = 0;
    var typeMarkers = "";
    
    var filtroAplicado = 'ALL';
    var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase());
    var is_safari = (/webkit/.test(navigator.userAgent.toLowerCase()) && !/chrome/.test(navigator.userAgent.toLowerCase()));
	var is_opera = /opera/.test(navigator.userAgent.toLowerCase());
	var is_msie = (/msie/.test(navigator.userAgent.toLowerCase()) && !/opera/.test(navigator.userAgent.toLowerCase()));
	var is_mozilla = (/mozilla/.test(navigator.userAgent.toLowerCase()) && !/(compatible|webkit)/.test(navigator.userAgent.toLowerCase()));
   
    function WikiMappsMarker(){
    	this.id = null;
    	this.obj = null;
    	this.numTypeAssociations = null;
    	this.title = null;
    }   
    
  
    function  imageSrc(id, marker_id,eventExpired){
      marker_id = typeof(marker_id) != 'undefined' ? marker_id : 0;
      var base_location = "http://wikimapps.com/images/";
      var grayScale = "_gray";
      if(eventExpired == 'T')
    	  return id!=0?base_location+"mm_"+id+grayScale+".png":base_location+"icons/mm_"+marker_id+grayScale+".png";    	  
      else
    	  return id!=0?base_location+"mm_"+id+".png":base_location+"icons/mm_"+marker_id+".png";      
    }    
    
    var circle = null;
    function plotCircle(lt,lg,raioT){
    	circle = new CircleOverlay(new GLatLng(lt,lg), raioT?raioT:300, '#336699', 1, 1, '#336699', 0.25);
//    	map.setZoom(15);
//    	map.setCenter(new GLatLng(lt,lg));
    	map.addOverlay(circle);
    }   
    
    function getMarkersCircle(){
    	mostrarCarregando('imgCarregando','bt_send_message_by_area');
    	var b = circle.getBounds();
    	for (k in markersArray){
    		if(markersArray[k].obj instanceof GMarker){
	    		if(b.contains(markersArray[k].obj.getPoint())){
	    			if(document.getElementById('events_in_the_circle').value == ''){
	    				document.getElementById('events_in_the_circle').value = markersArray[k].id;
	    			}else{	
	    				document.getElementById('events_in_the_circle').value += ';'+markersArray[k].id;
	    			}
	    		}
    		}else{
    			for (var j=0 ; j < markersArray[k].obj.getVertexCount();j++){    				
    				
		    		if(b.contains(markersArray[k].obj.getVertex(j))){
		    			if(document.getElementById('events_in_the_circle').value == ''){
		    				document.getElementById('events_in_the_circle').value = markersArray[k].id;
		    			}else{	
		    				document.getElementById('events_in_the_circle').value += ';'+markersArray[k].id;
		    			}
		    			break;
		    		}
    			}	
    		}	
    	}
    	document.getElementById('btSubmitSendMessage').click();    		
    }
    
    function updateRadius(raio){
    	if(raio>1000){
    		raio = 1000;
    		document.getElementById('raio').value = raio;    		
    	}
    	circle.setRadius(raio);
    	circle.redraw();
    }
    
    function tinyImage(opt_color, opt_preload, marker_id,eventExpired){
      var color = opt_color||"0";
      var src_ = imageSrc(opt_color, marker_id,eventExpired);
      if(opt_preload){
        var preImage = new Image();
        preImage.src = src_;
      }
      return  src_;
    }
    
    var idRouteInsert = null;
    function habilitaEdicaoRota(){    	
    	gdir.getPolyline().enableEditing({onEvent: "mouseover"});
        gdir.getPolyline().disableEditing({onEvent: "mouseout"});
        GEvent.bind(gdir.getPolyline(), "lineupdated", '', function() {
        	if(idRouteInsert){
        		insertRouteGoogle(gdir.getPolyline(),idRouteInsert,idEventRoute);
        	}	
        });
        insertRouteGoogle(gdir.getPolyline(),'new',idEventRoute);
    }
    var gdir = null;
    var idEventRoute = null
    function plotGoogleRoute(origem,destino,eventId){
    	gdir = new GDirections(map, null);
    	idEventRoute = eventId;
    	gdir.load("from: " + origem  + " to: " + destino,
                  { "locale":"pt_BR","preserveViewport":true });
    	   	
    	setTimeout('habilitaEdicaoRota()',4000);
    }
    function editProfile(id){    	
    	var url=homepage+"/apps/editProfileUser?ondeVem=friendPanel&url="+wikimaps +"&uid="+id;
    	var req = GXmlHttp.create();
    	req.open("GET", url, false);
        req.send(null);
        fillMsg(req.responseText,660,440,'22%',80,true);
    	
    	
    }
    function addFriend(friendId, appsId){    	
    	document.getElementById("imgCarregandoProfile").style.visibility = "visible";
    	var url=homepage+"/users/addFriend?op=1&id="+friendId+"&app="+appsId;
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);
        document.getElementById('friendPanel').innerHTML=req.responseText;
    }
    
    function loadScrapPage(users_id){    	
    	var url=homepage+"/users/loadScrapPage?users_id=" + users_id +"&url="+wikimaps;
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);        
        fillMsg(req.responseText,660,440,'22%',80,true);
    }
    
    function addScrap(message,friend_id){    	
    	var url=homepage+"/users/addScrap?msg=" + message+"&friend_id="+friend_id+"&url="+wikimaps;
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);        
        fillMsg(req.responseText,660,440,'22%',80,true);
    }   
    
    function deleteScrap(messages_id,friend_id){    	
    	var url=homepage+"/users/deleteScrap?messages_id=" + messages_id+"&friend_id="+friend_id;
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);        
        fillMsg(req.responseText,660,440,'22%',80,true);
    }
    
    function tinyIcon(opt_color, marker_id, width, height,eventExpired){
      width = (typeof(width) != 'undefined')&&(marker_id!=0) ? width : 12;
      height = (typeof(height) != 'undefined')&&(marker_id!=0) ? height : 20;
      var tiny = new GIcon();
      tiny.image = tinyImage(opt_color,false,marker_id,eventExpired);      
      tiny.iconSize = new GSize(width, height);//new GSize(25, 39);//
      tiny.iconAnchor = new GPoint(parseInt(width/2), height);//12,39);//
      tiny.infoWindowAnchor = new GPoint(parseInt(width/2),parseInt(height/2));
      //tiny.shadow = "http://wikimapps.com/images/shadow_gma.png";
      /*tiny.shadowSize = new GSize(54,39); (22, 20);*/
      tiny.transparent = "http://maps.google.com/mapfiles/transparent.png"; 
      return tiny;
    }    
    
    function treatTxtRoutes(txt){
    	var txtRoutes =  txt.split('|');
    	if(txt!=''){
    	
	    	for(var i = 0 ; i < txtRoutes.length; i++){
	    		var routeProperties = txtRoutes[i].split('?');
	    		var id = routeProperties[0];
	    		var lts = routeProperties[1];
	    		var lgs = routeProperties[2];
	    		var route = new WikiMappsMarker();
	    		route.id = id;
	    		
	    		var latitudes = lts.split(';');
	        	var longitudes = lgs.split(';');
	        	var arrayPontosLatLngPolyLine = new Array();
	        	
	        	for (var z = 0; z < latitudes.length; z++){        		
	        		arrayPontosLatLngPolyLine[z] = new GLatLng(parseFloat(latitudes[z]), parseFloat(longitudes[z]));
	        	}
	        	
	        	route.obj = new GPolyline(arrayPontosLatLngPolyLine,'#4169E1',4,1.6);
	    		map.addOverlay(route.obj);    		
	    		return route;
	    		arrayRotasGoogle[id] = route;
	    	}
    	}	
    }
    
    var arrayRotasGoogle = {};    
    
    function selectRoutesByUser(){
    	var url=homepage+"/a/"+wikimaps+"/selectRoutes";
    	
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);
        return treatTxtRoutes(req.responseText);
    }
    
    function selectRoutesByEvent(events_id){
    	var url=homepage+"/a/"+wikimaps+"/selectRoutes?events_id="+events_id;
    	
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);
        return treatTxtRoutes(req.responseText);
    }
    
    function insertRouteGoogle(polyline,rota,idEvento){
    	var latitudes = '';
    	var longitudes = '';
    	
	    for(var i=0 ; i<polyline.getVertexCount();i++){
  	  		if(i==polyline.getVertexCount()-1){
				latitudes+= polyline.getVertex(i).lat().toPrecision(6);
				longitudes+= polyline.getVertex(i).lng().toPrecision(6);
			}
			else{
				latitudes+= polyline.getVertex(i).lat().toPrecision(6)+';';
				longitudes+= polyline.getVertex(i).lng().toPrecision(6)+';';
			}
					
		  }
    	var url=homepage+"/a/"+wikimaps+"/saveGoogleRoute";
    	var parans = "events_id="+idEvento+"&lts="+latitudes+"&lgs="+longitudes+"&routes_id="+rota;
        var req = GXmlHttp.create();
        req.open("POST", url, true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.setRequestHeader("Content-length", parans.length);
        req.send(parans);
       
        var idNewRoute = req.responseText;
        idRouteInsert = idNewRoute;
        var route = new WikiMappsMarker();
        route.id = idNewRoute;
        route.obj = polyline;
        if(!arrayRotasGoogle[route.id])
        	arrayRotasGoogle[route.id] = route;
    }    
  
    //Preload loop
    //Electronics freaks  know the numbering scheme  
    function preLoadImages(){
      for (var i=0;i<=12;i++){
        tinyImage(i, true);
      }
    }
    
    function clearMarkersArray()
    {
    	markersArray = {};
    }
    
    function chooseMarker(value){    	
    	document.getElementById("id_marcador_selecionado").value = value;
    	document.getElementById("id_event_edicao").value="-1";
    	document.getElementById("form_new_event").click();	
    }
    
    function registrarEventoMapa(){
    	document.getElementById("div_sobre_mapa").innerHTML = '<div align="center" style="width:100%; height:100%;text-align:center;vertical-align:middle"><br/><br/><br/><br/><br/><br/><img align="center" style="vertical-align:middle;" id="imgCarregando" src="/images/carregando.gif" /> </div>';
    	document.getElementById("div_sobre_mapa").style.display = "block";
    	document.getElementById("map").style.display = "none";
    	//document.getElementById("div_sobre_mapa").innerHTML = newEvent();
    }
    
    function cancelarEventoMapa(){
    	document.getElementById("div_sobre_mapa").style.display = "none";
    	document.getElementById("map").style.display = "block";
    }
    
    function confirmaEndereco(){
    	podeCarregarEventos = false;
    	newMarker=arrayTiposMarcadores[idMarkerRegistro];    	
    	document.getElementById("div_sobre_mapa").style.display = "none";
    	document.getElementById("map").style.display = "block";
    	var html = addMarker(newMarker.getLatLng().lat(),newMarker.getLatLng().lng(),idMarkerRegistro,paisRegistro,cidadeRegistro);    	
        var tabs = [];
        tabs.push(new GInfoWindowTab(mData,html));
        if(layoutApp != "newviewer" && layoutApp != "wikicrianca")
        	tabs.push(new GInfoWindowTab(mMediaFotos,"<div id='media_list'><p>" + msgTrMedia + "</p></div>"));        
        map.setCenter(mapRegistro.getCenter());
        map.setZoom(mapRegistro.getZoom());
        map.addOverlay(newMarker);
        newMarker.openInfoWindowTabs(tabs);
        limpaCidadePaisRegistro();
    }
    
    var corLinhaPoligono = null;
    function desenharLinha(){
    	podeCarregarEventos = false;
    	document.getElementById("div_sobre_mapa").style.display = "none";
    	document.getElementById("map").style.display = "block";
    	map.setCenter(mapRegistro.getCenter());
        map.setZoom(mapRegistro.getZoom());
        iniciarDesenhoLinha();
        
    }
    
    function desenharPoligono(){
    	podeCarregarEventos = false;
    	document.getElementById("div_sobre_mapa").style.display = "none";
    	document.getElementById("map").style.display = "block";
    	map.setCenter(mapRegistro.getCenter());
        map.setZoom(mapRegistro.getZoom());
        iniciarDesenhoPoligono();
        
    }
    
    function pararDesenho(poly){
    	escondeAjudaDesenhoPoly();
    	poly.disableEditing();
    	map.removeOverlay(poly);
  	    GEvent.removeListener(eventoBotaoDireitoDesenhoLinha);
  	    eventoBotaoDireitoDesenhoLinha = null;
  	    GEvent.removeListener(mapClickRegisterPoly);
  	    mapClickRegisterPoly = null;
  	    polyRegister = null;
    }
    
    var mouseMoveRegisterPoly = null;
    var divAjuda = null;
    var mensagemAjudaDesenhoPoly = "";
    function mostraAjudaDesenhoPoligono(){
    	divAjuda = document.createElement('div');
    	mouseMoveRegisterPoly = GEvent.addListener(map, 'mousemove', function(cursorPoint){           			
              
              	var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    			var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(cursorPoint,map.getZoom());
    			
    			var height = divAjuda.clientHeight;
    			var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - 30, offset.y - point.y -20 -height));
    			if(polyRegister instanceof GPolyline)
    				divAjuda.innerHTML = "<div style='width: 192px;padding: 2px;font: normal normal normal 8pt Arial;text-align: justify;border: solid 1px black;background-color: #FFF;'>"+mensagemAjudaDesenhoPoly+" ("+(Math.round(polyRegister.getLength() / 10) / 100)+" km)</div>";
    			else
    				divAjuda.innerHTML = "<div style='width: 192px;padding: 2px;font: normal normal normal 8pt Arial;text-align: justify;border: solid 1px black;background-color: #FFF;'>"+mensagemAjudaDesenhoPoly+" ("+(Math.round(polyRegister.getArea() / 10) / 100)+" km2)</div>";
    			
    			// Plota toolTip no mapa
    		  	pos.apply(divAjuda);
    		  	map.getPane(G_MAP_FLOAT_PANE).appendChild(divAjuda);
        	  					      	  	
    		  	divAjuda.style.visibility="visible";
           
          });    	 	
    }
    
    var mapClickRegisterPoly = null; 
    function addActionMapClick(){
    	mapClickRegisterPoly = GEvent.addListener(map, 'click', function(){
	    	 if(polyRegister){ 	
				if(polyRegister.getVertexCount()==0){
					  mensagemAjudaDesenhoPoly=mDesenhoPoligono2;
				}
				if(polyRegister.getVertexCount()>0){
					  mensagemAjudaDesenhoPoly=mDesenhoPoligono3;
				}
				
	    	 }
    	});	 
    }
    
    function escondeAjudaDesenhoPoly(){
    	GEvent.removeListener(mouseMoveRegisterPoly);
    	divAjuda.style.visibility = "hidden";
    	GEvent.removeListener(mapClickRegisterPoly);
    }
    
    var idMarkerLinePolygon = null;
    var eventoBotaoDireitoDesenhoLinha = null;
    function iniciarDesenho(poly, name, onUpdate, color) {
    	  addActionMapClick();
    	  mensagemAjudaDesenhoPoly=mDesenhoPoligono1;
    	  map.addOverlay(poly);
    	  poly.enableDrawing({});
    	  poly.enableEditing({onEvent: "mouseover"});
    	  poly.disableEditing({onEvent: "mouseout"});    	  
    	  mostraAjudaDesenhoPoligono();    	  
    	  eventoBotaoDireitoDesenhoLinha = GEvent.addListener(map, "singlerightclick", function(point)
	      {   		  
	    	  pararDesenho(poly);
	    	  podeCarregarEventos = true;
	      }); 
    	  GEvent.addListener(poly, "endline", function() {
    		  poly.disableEditing();
    		  escondeAjudaDesenhoPoly();
    		  var latitudes='';
		      var longitudes='';
		      for(var i=0 ; i<poly.getVertexCount();i++){
	    	  	if(i==poly.getVertexCount()-1){
					latitudes+= poly.getVertex(i).lat();
					longitudes+= poly.getVertex(i).lng();
				}
				else{
					latitudes+= poly.getVertex(i).lat()+';';
					longitudes+= poly.getVertex(i).lng()+';';
				}
						
			  }
    		  var html = addMarker(latitudes,longitudes,idMarkerLinePolygon,paisRegistro,cidadeRegistro);    	
    	      var tabs = [];
    	      tabs.push(new GInfoWindowTab(mData,html));
    	      tabs.push(new GInfoWindowTab(mMediaFotos,"<div id='media_list'><p>Save this marker before adding a media</p></div>"));  
    	      map.openInfoWindowTabs(poly.getVertex(0),tabs);
    	      //poly.openInfoWindowTabs(tabs);
    		  limpaCidadePaisRegistro(); 
    		  GEvent.removeListener(eventoBotaoDireitoDesenhoLinha);
    		//alert('fim');  
    	    //var cells = addFeatureEntry(name, color);
    	    GEvent.bind(poly, "lineupdated", '', onUpdate);
    	    GEvent.addListener(poly, "click", function(latlng, index) {
    	    	
    	    });
      });
    }
    var polyRegister = null;
    function iniciarDesenhoLinha(){
      var color = corLinhaPoligono;
      corLinhaPoligono = null;
	  var line = new GPolyline([], color);
	  polyRegister = line;
	  iniciarDesenho(line, "Line ", function() {
		  
	  }, color);
    }
    
    function iniciarDesenhoPoligono(){
        var color = corLinhaPoligono;
        corLinhaPoligono = null;
	  	var poly = new GPolygon([], color, 2, 0.7, color, 0.2);
	  	polyRegister = poly;
	  	iniciarDesenho(poly, "Poly ", function(){
	  	  
	  	}, color);
      }
    
    function chooseTypeMarker(idMarker){    	
		if(idMarker!=''){
			document.getElementById("div_acoes_registro").style.display = "block";
			document.getElementById("bt_cancelar_inicio").style.display = "none";
			document.getElementById("txt_endereco").style.display = "block";
			document.getElementById("div_endereco").style.visibility = "visible";
			if(document.getElementById("div_mapa"))
				document.getElementById("div_mapa").style.visibility = "visible";
			
			if(idMarkerRegistro!='' && idMarkerRegistro!=null){				
				mapRegistro.removeOverlay(arrayTiposMarcadores[idMarkerRegistro]);
			}
			
			arrayTiposMarcadores[idMarker].setLatLng(mapRegistro.getCenter());
			mapRegistro.addOverlay(arrayTiposMarcadores[idMarker]);
//			var html = '<div style="width:180px; height:48px"> '+messageTempRegister+' </div>';
//		    arrayTiposMarcadores[idMarker].openInfoWindowHtml(html);
			
		}else{
			document.getElementById("div_acoes_registro").style.display = "none";
			document.getElementById("bt_cancelar_inicio").style.display = "block";
			document.getElementById("txt_endereco").style.display = "none";
			document.getElementById("div_endereco").style.visibility = "hidden";
			if(document.getElementById("div_mapa"))
				document.getElementById("div_mapa").style.visibility = "hidden";
			if(idMarker!='')
				mapRegistro.removeOverlay(arrayTiposMarcadores[idMarkerRegistro]);
		}
		idMarkerRegistro = idMarker;
	}
    
    var geocoder = null;
    var mapRegistro = null;
    var arrayTiposMarcadores = {};
    var customIcon = null;
    var idMarkerRegistro = null;
    function loadMapRegister(lt,lg){
    	
    	mapRegistro = new GMap2(document.getElementById("mapa_registro"),new GLatLng(-3.7183943,-38.5433948),13);
    	if(lt && lg)
    		mapRegistro.setCenter(new GLatLng(lt,lg),map.getZoom());
    	else
    		mapRegistro.setCenter(map.getCenter(),map.getZoom());    	
    	mapRegistro.setUIToDefault();
    	geocoder = new GClientGeocoder(); 	    
    }
    
    function limpaCidadePaisRegistro(){
    	cidadeRegistro = '';
        paisRegistro = '';
    }
    
//Reverser geocoder
    var cidadeRegistro = '';
    var paisRegistro = '';
    var idEventoEdicao = '';
    var ltLgRegistro = null;
    var typeDesignRegistro = null;
    function getCidadePais(latlng, eventId, typeDesign) {
    	typeDesignRegistro = typeDesign;
    	if(eventId){
    		idEventoEdicao = eventId;
    	}	
        if (latlng) {
        	ltLgRegistro = latlng; 
            geocoder.getLocations(latlng, function(response) {
              if(response.Status.code != 200) {
            	  //alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
              }
              else {

	              var place = response.Placemark[0];	             
	              var camposEndereco = place.address.split(',');
	              paisRegistro = camposEndereco[camposEndereco.length-1];
	              if(camposEndereco.length == 2){
	              		var estado = camposEndereco[0].split('-');
	                	if(estado.length == 2)
	                		cidadeRegistro = estado[0];                	
	              }
	              
	              if(camposEndereco.length == 4 || camposEndereco.length == 3){
	              		var estado = camposEndereco[camposEndereco.length-2].split('-');
	                	if(estado.length == 2){
	                		try{
	                			cidadeRegistro = estado[0];
	                			if(IsNumeric(estado[0])){
			            			estado = camposEndereco[camposEndereco.length-3].split('-');
			            			cidadeRegistro = estado[0];
			            		}	
	                		}catch(e){}
	                		
	                	}		                	
	              }
	              
	              if(camposEndereco.length == 5){
	              		var estado = camposEndereco[2].split('-');
	                	if(estado.length == 2)
	                		cidadeRegistro = estado[0];
	              }
	              
	              if(typeDesignRegistro == '1'){
	            	  desenharLinha();
	            	  
	              }
	              else if(typeDesignRegistro == '2'){
	            	  desenharPoligono();
	              }	  
	              else if(idEventoEdicao == '')
	            	  confirmaEndereco();
	              else{
	            	  atualizarEnderecoMarcador(idEventoEdicao,paisRegistro,cidadeRegistro,ltLgRegistro);
	            	  ltLgRegistro = null;
	            	  idEventoEdicao = '';	            	  
	              }	  
	            	  
              }
            });
        }
    }
    
    function atualizarEnderecoMarcador(idEventoEdicao,paisRegistro,cidadeRegistro,ltLgRegistro){
    	var url=homepage+"/a/"+wikimaps+"/atualizarEnderecoEvento?event_id="+idEventoEdicao+"&pais="+paisRegistro+"&cidade="+cidadeRegistro+"&lt="+ltLgRegistro.lat()+"&lg="+ltLgRegistro.lng();
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);
        if(req.responseText == 'ok'){        	
        	getMarkerData(idEventoEdicao);
        	limpaCidadePaisRegistro();
        	if(document.getElementById("div_sobre_mapa"))
        		document.getElementById("div_sobre_mapa").style.display = "none";
        	document.getElementById("map").style.display = "block";
        }else{
        	alert('error');
        }	
    }
    
    function IsNumeric(sText){
 	   var ValidChars = "0123456789.";
 	   var IsNumber=true;
 	   var Char; 
 	   for (i = 0; i < sText.length && IsNumber == true; i++) { 
 		  Char = sText.charAt(i); 
 		  if (ValidChars.indexOf(Char) == -1){
 		     IsNumber = false;
 		  }
 	   }
 	   return IsNumber;
 	   
 	}
    
    function plotaMarcadorRegistroComGeoLocation(overlay, locationAndress, event){
    		var endereco = "";
    		if(!locationAndress)
    	 		endereco =  document.getElementById('pais').value+","+ document.getElementById('cidade').value +"-"+document.getElementById('estado').value+","+document.getElementById('endereco').value + ","+document.getElementById('bairro').value + ","+document.getElementById('numero').value ;   
    		else
    			endereco = locationAndress;
    		
    		if(event == 'focus' && !locationAndress && endereco==',-,,,')
    			return false;
    			
    		
    	    geocoder.getLocations(endereco, function(response) {
    	         if (!response || response.Status.code != 200) {
    	             document.getElementById('mens_erro_endereco_registro').innerHTML = mEnderecoNaoEncontrado;    	            
    	        }
    	        else {
    	        	document.getElementById('mens_erro_endereco_registro').innerHTML = '';
    	            place = response.Placemark[0];
    	            point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
    	            switch(place.AddressDetails.Accuracy)
    	            {
    	                    case 0:
    	                        zoom=4;
    	                          break;   
    	                    case 1:
    	                        zoom=4;
    	                      break;
    	                     case 2:
    	                        zoom=6;
    	                      break;
    	                    case 3:
    	                        zoom=12;
    	                      break;
    	                    case 4:
    	                        zoom=13;
    	                      break;
    	                    case 5:
    	                        zoom=14;
    	                      break;
    	                    case 6:
    	                        zoom=16;
    	                      break;
    	                    case 7:
    	                        zoom=17;
    	                      break;
    	                    case 8:
    	                        zoom=17;
    	                      break;
    	                    default:
    	                        zoom=17;       
    	            }
    	            mapRegistro.setCenter(point, zoom);
    	            arrayTiposMarcadores[idMarkerRegistro].setLatLng(point);
    	            var html = '<div style="width:180px; height:48px"> '+messageTempRegister+' </div>';
    			    arrayTiposMarcadores[idMarkerRegistro].openInfoWindowHtml(html);
    	          }
    	         
    	     });
    	    
    }
       
    function replaceAll(string, token, newtoken) {
    	while (string.indexOf(token) != -1) {
     		string = string.replace(token, newtoken);
    	}
    	return string;
    }
    
    function updateCheckFilter(){    	
    	var vetorMarcadores = typeMarkers.split(',');
    	for(var i=0; i < vetorMarcadores.length; i++){
    		if(vetorMarcadores[i] != ''){    					
    			document.getElementById('tick'+vetorMarcadores[i]).checked = false;
    		}
    	}
    }
    
    function showhide(id) {
    	
        var checkbox = document.getElementById('tick'+id);
        if (checkbox.checked == true) {
        	typeMarkers = replaceAll(typeMarkers,','+id,'');
        	typeMarkers = replaceAll(typeMarkers,id+',','');
        	typeMarkers = replaceAll(typeMarkers,id,'');
        	searchMarkers('ALL');
        } else {
        	if(typeMarkers=='') {
        		typeMarkers+=id;
        	} else {
        		typeMarkers+=','+id;
        	}
        	clearMarkersArray();
        	map.clearOverlays();  
        	searchMarkers('ALL');        	
        }       
       
    	/*
        var checkbox = document.getElementById('tick'+id);
        var spacer = document.getElementById('sp'+id);

        if (checkbox.checked=='none') {
        	typeMarkers = replaceAll(typeMarkers,','+id,'');
        	typeMarkers = replaceAll(typeMarkers,id,'');
        	searchMarkers('ALL');
        	
        } else {
        	if(typeMarkers=='') {
        		typeMarkers+=id;
        	} else {
        		typeMarkers+=','+id;
        	}
        	
        	searchMarkers('ALL');
        }	

        checkbox.style.display=checkbox.style.display=='inline'?'none':'inline';               
        spacer.style.width=checkbox.style.display=='inline'?'0px':'16px';
        */
    }
    
    function markerCanceled(){
        newMarker.closeInfoWindow();
    }

    function newMarkerSaved(id,icon){
	    //markersArray[id]=newMarker;	    
	    newMarker.setId(id);
	    //newMarker.setIcon(icon);
	    GEvent.addListener(newMarker, 'click', function() {
	        markerClick(newMarker);
	        /*
	        var html = getMarkerInfo(newMarker.getId());	
	        lastMarkerArray=newMarker;
	        
            newMarker.openInfoWindow(html);
            */
        });
        //$("media_list").innerHTML=getMarkerMedias(id);
	    
	    
	    
	    /*
	     *	Adiciona o marcador no vetor do kernelMap e no vetor de marcadores.
	     */
	    //markersArray[id]=newMarker; 
    }
   
    function getMarkers(){
      var url=homepage+"/a/"+wikimaps+"/mkr/list";
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);
      return req.responseText;
    }
    
    function addMarker(lat,lng,marker_id,country,city,event_id){     
      var url=homepage+"a/"+wikimaps+"/newmarker?lt="+lat+"&lg="+lng+"&mk="+marker_id+"&country="+country+"&city="+city;
      if(event_id)
    	  url+="&ev="+event_id;
//      return '<iframe src ="'+url+'" width="370" height="200" frameborder="0"><p>Your browser does not support iframes.</p></iframe>';
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);
      
      return req.responseText;
    }
    
    function getMarkerData(id){
    	GDownloadUrl(homepage+"/a/"+wikimaps+"/getMarker?id="+id, 
	        function(data, responseCode) {
	          var xml = GXml.parse(data);
	          var markers = xml.documentElement.getElementsByTagName("m");
	          podeCarregarEventos = false;
	          map.setCenter(new GLatLng(markers[0].getAttribute("lt"), markers[0].getAttribute("lg")), 15);  
	          podeCarregarEventos = true;
	          plotMarkers(markers);	          
	          markerClick(markersArray[markers[0].getAttribute("id")]);
	        }
    	);
    }

    function getMarkerInfo(id){          
      var url;
      id==0?url=homepage+"a/"+wikimaps+"/newmarker":url=homepage+"a/"+wikimaps+"/markerinfo/id/"+id;     
//      return "<iframe src='"+url+"' id='infowindow' width='350' height='200' frameborder='0'></iframe>"
      /*
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      return req.responseText;
      */
      GDownloadUrl(url, 
               function(data, responseCode) {
	            minfo_content.innerHTML=data;	          
	    }); 
     /* GEvent.addListener(marker.obj, 'mouseout', function() {
	    	markerMouseOut(marker);
      });*/
    }
    
    function getMarkerMedias(id){
        //var url="http://wikimapps.com/dev.php/"+"a/"+wikimaps+"/medias/id/"+id;
        var url=homepage+"a/"+wikimaps+"/medias/id/"+id;   
        /*
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);      
        return req.responseText;
        */
        media_content.innerHTML='<iframe src="'+url+'" width="425px" height="220px" frameborder="0" />';	          
  	  
      }
    
    function getMarkerMedia(id){
      var url=homepage+"a/"+wikimaps+"/media/id/"+id;      
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      return req.responseText;
    }
    
    function getMarkerComments(id){
     
      var url=homepage+"a/"+wikimaps+"/comments/id/"+id;
      
      GDownloadUrl(url, 
               function(data, responseCode) {
	            comments_content.innerHTML=data;	          
	    });
    }
    //retorna div com texto das associacoes
    function getMarkerAssociations(id){
        
        var url=homepage+"a/"+wikimaps+"/mkr/getTypeAssociations?id="+id;
        
        GDownloadUrl(url, 
                 function(data, responseCode) {
  	            associations_content.innerHTML=data;	          
  	    });
      }
    function markerClick(localMarker){
	    	if((layoutApp != "newviewer" && layoutApp != "wikicrianca") || (qtdEventsVP==1 && default_search.indexOf('NBSP',0) != -1)){	
    			if(layoutApp == "newviewer" || layoutApp == "wikicrianca"){
    				//alert(layoutApp);
    				podeCarregarEventos = true;
    				return;
    			}	
	    		podeCarregarEventos = false;
	    		//map.savePosition();
		        //sidebarEntry.focus();
	    		// Posiciona o Marker nmo centro do mapa
	            //map.panTo(localMarker.getLatLng());
	            //map.panBy(new GSize(0,1));                        
	            //alert('MarkerClick');
	    		if(layoutApp=="viewer"){ 	
	    			if(gadgetsComprados[5]!=undefined){
		    			executaRequisicaoRecuperarUsuariosPorEvento(localMarker.id);
		    		}
	    		}	
	    		
	    		currentMarker=localMarker;
	            minfo_content.innerHTML='Loading...';
	            media_content.innerHTML='Loading...';
	            getMarkerInfo(localMarker.id);
		        getMarkerMedias(localMarker.id);	       
		        getMarkerComments(localMarker.id);
		        getMarkerAssociations(localMarker.id);
		        	
	            
	            var tabs = [];            
	            tabs.push(new GInfoWindowTab(mData,minfo_content));
	           
	            if(layoutApp != "viewer" && layoutApp != "semWidgets" && layoutApp != "semWidgets2")
	            	tabs.push(new GInfoWindowTab(mComments,comments_content))
	            if(localMarker.numTypeAssociations != 0){
	            	tabs.push(new GInfoWindowTab(mAssociations,associations_content))
	            }
	            if(localMarker.obj instanceof GMarker)
	            	localMarker.obj.openInfoWindowTabs(tabs);
	            else
	            	map.openInfoWindowTabs(localMarker.obj.getVertex(0),tabs);
	                      	
	            if(layoutApp=="viewer" || layoutApp=="semWidgets" || layoutApp == "semWidgets2")
	            	$j('#vmenu').accordion('activate',2);
	           
	            //var iw = map.getInfoWindow();            
	            //GEvent.addListener(iw, "restoreend", function() {
	            //   setTimeout(map.closeInfoWindow(),500);
	            //});
	            selectRoutesByEvent(localMarker.id);
	            if(layoutApp == "semWidgets")
			    	getWidgetPeloNome(localMarker.title);
	    	}else{
	    		var er = /^[0-9]+$/;
	    		if(er.test(localMarker.id)){
	    		    window.location=homepage+"a/"+wikimaps+"/verEvento/id/"+localMarker.id;
	    		}else{
	    			window.location=homepage+"a/"+wikimaps+"/verEvento/token/"+localMarker.id;
	    		}
	    	}	
	    		
    }
    
    var pointedMarkerId;
    
    //	Evento "mouseover" do marcador [INICIO]
    function markerMouseOver(marcador)
    {   
    	pointedMarkerId = marcador.id;
    	setTimeout(function(){
    		if(pointedMarkerId === marcador.id){
	    		
		    	var url=homepage+"apps/infoEventMouseOver?t=" + marcador.id;  
		        var req = GXmlHttp.create();
		        req.open("GET", url, false);
		        req.send(null);
		
		        //	Controle para tooltip
		    	toolTipMarcadores = tooltipCreater('toolTip'+marcador.id, marcador.obj.getLatLng(), req.responseText);
    		}
    	}, 500);
    }
    //	Evento "mouseover" do marcador [FIM]
    
    
    
    //	Evento "mouseout" do marcador [INICIO]
    function markerMouseOut(marcador)
    {
    	pointedMarkerId = null;
    	setTimeout(function(){
        	if(toolTipMarcadores)
        	{
        		if($j('#toolTip' + marcador.id)){
        			$j('#toolTip' + marcador.id).remove();
        			toolTipMarcadores = null;
        		}	
        	}
    	},800);
    	
    }
    //	Evento "mouseout" do marcador [FIM]
   
    
    
    //	Cria tooltip [INICIO]
    var ttMarkerMouseOver = null
    function tooltipCreater(id, latLngObj, html)
    {
    	//	info tooltip
    	if(!ttMarkerMouseOver)	
    		ttMarkerMouseOver = document.createElement('div');
    	ttMarkerMouseOver.id = id;
    	ttMarkerMouseOver.innerHTML = html;
    	
    	//	CSS tooltip
    	ttMarkerMouseOver.style.visibility = "visible";
    	ttMarkerMouseOver.style.maxWidth = "250px";
    	ttMarkerMouseOver.style.maxHeight = "180px";
    	ttMarkerMouseOver.style.backgroundColor = "white";
    	ttMarkerMouseOver.style.cursor = "pointer";
    	//ttMarkerMouseOver.style.border = "1px Solid #0099CC";
    	ttMarkerMouseOver.style.padding = "5px";

    	//	Conf posicionamento
    	var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    	var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(latLngObj, map.getZoom());
    	var height = ttMarkerMouseOver.clientHeight;
    	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x + 16, offset.y - point.y -25 -height));
    	
    	// Plota toolTip no mapa
	  	pos.apply(ttMarkerMouseOver);
	  	map.getPane(G_MAP_FLOAT_PANE).appendChild(ttMarkerMouseOver);
	  	
	  	return ttMarkerMouseOver;
    }
    //	Cria tooltip [FIM]
    
    
    
    
    
    //	Create Marker [INICIO]
    function createMarker(info, container) {
        var id = info.getAttribute("id");
        
        var markerid = info.getAttribute("mid");
        var icon = info.getAttribute("i");
        var icon_width = info.getAttribute("iw");
        var icon_height = info.getAttribute("ih");        
        var title = info.getAttribute("t");
        var description = info.getAttribute("d");
        var color = info.getAttribute("cl");
        var typeDesign = info.getAttribute("td");
        var ownerEvent = info.getAttribute("uId");
        var checkUserFriend = info.getAttribute("cf");
        var eventExpired = info.getAttribute("e");
        var numTypeAssociations = info.getAttribute("as");
        
        //var w = info.getAttribute("width");
        //var h = info.getAttribute("height");
        //if(icon_width != '' && icon_height != '')
        	var point = new GLatLng(parseFloat(info.getAttribute("lt")),parseFloat(info.getAttribute("lg")));
        if(layoutApp=="viewer" || layoutApp=="capella" || layoutApp == "semWidgets" || layoutApp == "semWidgets2"){        
	        // SideBar
	        var sidebarEntry = document.createElement('p');
	        sidebarEntry.id='_sb'+id;
	        sidebarEntry.style.display='block';
	        sidebarEntry.style.height='40px';        
	        sidebarEntry.style.borderBottom='1px dashed #ccc';
	        sidebarEntry.style.verticalAlign='middle';
	        sidebarEntry.title = title;
	        var text = document.createElement('span');
	        if( title.length > 16 ){
	        	title = title.substring(0,16)+'...';
	        }
	        title = title.toUpperCase();
	        text.innerHTML = '' + title + '';
	        var img = null;
	        if(typeDesign == '0'){
		        img = document.createElement('img');
		        img.src = imageSrc(icon,markerid,eventExpired);
		        img.align='left';
		        img.style.marginRight='3px';
		        img.style.width = "25px";
		        img.style.height = "25px";
		        sidebarEntry.appendChild(img);
	        }else
	        if(typeDesign == '1'){
	        	var divLine =  '<div style="float:left; width:20px; height:20px;margin-left:2px;margin-bottom:2px;background-color:#ffffff;"> <div style="float:right; margin-top:8px; margin-right:2px; width:4px; height:4px;border-top:2px solid '+color+'"> </div> <div style="border-bottom:2px solid '+color+'; border-right:2px solid '+color+'; width:10px; height:4px; margin-top:8px; margin-left:2px" > </div> </div>'
	        	sidebarEntry.innerHTML = divLine;
	        }else{
	        	var divPoly =  '<div style="float:left; width:20px; height:20px;margin-left:2px;margin-bottom:2px;background-color:#ffffff;"> <div style="float:right; margin:2px; width:12px; height:12px;border:2px solid '+color+'"> </div> </div>';
	        	sidebarEntry.innerHTML = divPoly;
	        }       
	        
	        sidebarEntry.appendChild(text);
	        sidebarEntry.style.cursor = 'pointer';
	        sidebarEntry.style.marginBottom = '2px';        
		    GEvent.addDomListener(sidebarEntry, 'mouseover', function() {
		        sidebarEntry.style.backgroundColor = '#eee';
		    });
		    GEvent.addDomListener(sidebarEntry, 'mouseout', function() {
		        sidebarEntry.style.backgroundColor = '#fff';
		    });        
	        container.appendChild(sidebarEntry);
        }            
        //Marker
        var marker = new WikiMappsMarker();
        marker.id = id;
        marker.title = title;
        marker.numTypeAssociations=numTypeAssociations;
        if(typeDesign == '0'){
	        var customIcon = tinyIcon(icon,markerid,icon_width,icon_height,eventExpired);
	        if(eventExpired == 'T'){
	        	title+=' '+ msgExpiredEvent;
	        }	
	        
	        
	        marker.obj = new GMarker(point, { icon:customIcon }); //	title:title 
		    
		    GEvent.addListener(marker.obj, 'click', function() {
		    	map.addOverlay(marker.obj);
		        markerClick(marker);
	        });	    
		    
        } else
        if(typeDesign == '1'){
        	var latitudes = info.getAttribute("lt").split(';');
        	var longitudes = info.getAttribute("lg").split(';');
        	var arrayPontosLatLngPolyLine = new Array();
        	
        	for (var z = 0; z < latitudes.length; z++){        		
        		arrayPontosLatLngPolyLine[z] = new GLatLng(parseFloat(latitudes[z]), parseFloat(longitudes[z]));
        	}
        	
        	marker.obj = new GPolyline(arrayPontosLatLngPolyLine, color,4,1.0);
        	
        	GEvent.addListener(marker.obj, "mouseover", function(latlng, index) {
		     	document.getElementById("map").style.cursor="pointer";
		    });
		    GEvent.addListener(marker.obj, "mouseout", function(latlng, index) {
		    	document.getElementById("map").style.cursor="default";
		    });
        	
        	GEvent.addListener(marker.obj, 'click', function() {        		
		    	map.addOverlay(marker.obj);
		    	document.getElementById("map").style.cursor="default";
		    	markerClick(marker);
	        });	
        	
        	//marker.setId(id);
        	
        }else{
        	var latitudes = info.getAttribute("lt").split(';');
        	var longitudes = info.getAttribute("lg").split(';');
        	var arrayPontosLatLngPolygon = new Array();
        	
        	for (var z = 0; z < latitudes.length; z++){        		
        		arrayPontosLatLngPolygon[z] = new GLatLng(parseFloat(latitudes[z]), parseFloat(longitudes[z]));
        	}
        	marker.obj = new GPolygon(arrayPontosLatLngPolygon, color, 2, 0.7, color, 0.2);
        	
        	GEvent.addListener(marker.obj, "mouseover", function(latlng, index) {
		     	document.getElementById("map").style.cursor="pointer";
		    });
		    GEvent.addListener(marker.obj, "mouseout", function(latlng, index) {
		    	document.getElementById("map").style.cursor="default";
		    });
        	
        	GEvent.addListener(marker.obj, 'click', function() {        		
		    	map.addOverlay(marker.obj);
		    	document.getElementById("map").style.cursor="default";
		    	markerClick(marker);
	        });
        	
        }	
	    //marker.setIcon(icon);
                
	    
        if(layoutApp=="viewer" || layoutApp == "capella" || layoutApp == "semWidgets" || layoutApp == "semWidgets2"){        
        	GEvent.addDomListener(sidebarEntry, 'click', function(){ GEvent.trigger(marker.obj, 'click');});
        }	
//        sidebarEntry.onfocus = function(){GEvent.trigger(point.marker,'click'); return false};
                
        // Adiciona no array de marcadores
        //alert('j'+markerid+'.push(marker);');
        eval('j'+markerid+'.push(marker);');        	
	    return marker;
    }
    //	Create Marker [FIM]
    
    
    //Variáveis de controle das estatisticas da area visivel
    var qtdEventsVP;
    var tiposMarcadores = {};
    
    function plotMarkers(markers){
    	tiposMarcadores = {};
    	qtdEventsVP=0;
    	var sidebar = null;
    	if(layoutApp=="viewer" || layoutApp=="capella" || layoutApp == "semWidgets" || layoutApp == "semWidgets2"){      
	        if(layoutApp!="capella")	
    			$j('#vmenu').accordion('activate',1);
	        sidebar = $('search_results');
	        sidebar.innerHTML = '';
    	}
    	    
        //	Limpa registro do mapa e vetor de marcadores.           
        var bounds = new GLatLngBounds();
	    var marker;
	    var l = 0;
	    for (var i = 0; i < markers.length; i++) {
	    	var point = null;
	    	if(markers[i].getAttribute("td")=='0')
	    		point = new GLatLng(parseFloat(markers[i].getAttribute("lt")),parseFloat(markers[i].getAttribute("lg")));
	    	
		    marker = createMarker(markers[i], sidebar);
		    
		    if(point == null){
		    	point = marker.obj.getVertex(0);
		    }
		    
		    //if(!markersArray[marker.id]){
		    	markersArray[marker.id]=marker;
		    	if(l<=300){
		    		map.addOverlay(marker.obj);
		    	}	
		    //}
		    
		    if(markers[i].getAttribute("td")=='0'){
		    	if(filtroAplicado!='ALL'){
		    		bounds.extend(point);
		    	}	
		    }else{
		    	if(filtroAplicado!='ALL'){
		    		
		    		for (var j=0 ; j < marker.obj.getVertexCount();j++){
		    				
		    			bounds.extend(marker.obj.getVertex(j));
		    		}	
		    	}
		    }	
		    
		    var tipoMarcador = markers[i].getAttribute("mid");
		    if(!tiposMarcadores[tipoMarcador] ){
		    	tiposMarcadores[tipoMarcador] = 1;
		    }else{
		    	tiposMarcadores[tipoMarcador]++;
		    }	
		    	
		    qtdEventsVP++;
		    l++;
	    }
	    
	    if(filtroAplicado!='ALL')
	    	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));	 
	    
	    //Remove os eventos que estão fora do view port
	    var mapBounds = map.getBounds();
	    for (k in markersArray) {
    		if(markersArray[k].obj instanceof GMarker) {
				if (!mapBounds.contains(markersArray[k].obj.getPoint())){					
					//	Exclui marcador do mapa e do vetor de marcadores
					map.removeOverlay(markersArray[k].obj);
					delete markersArray[k];
				}
	    	} else {
	    		//Não é marcador... é poligono
	    		for (var j=0 ; j< markersArray[k].obj.getVertexCount();j++){
	    			var removerPoly = true;
	    			if (mapBounds.contains(markersArray[k].obj.getVertex(j))){
	    				removerPoly = false;
	    			}		    			
	    		}
	    		if(removerPoly){
    				map.removeOverlay(markersArray[k].obj);
    				delete markersArray[k];
	    		}
	    	}
		}
	    
	    for(k in gadgetsComprados){
	    	if (gadgetsComprados[k]==1){
	    		atualizaEstatisticasAV();  		
	    		break;
	    	}
	    }	  
	    
	    // Abre popup caso o resultado seja somente 1
	    if(markers.length==1 && default_search.indexOf('NBSP',0) != -1){
	    	podeCarregarEventos = false;	    	
	    	if(marker.obj instanceof GMarker) {
	    		map.setCenter(marker.obj.getPoint(),15);
	    	} else {
	    		//e um poligono
	    		map.setCenter(marker.obj.getVertex(0),15);
	    	}
	    	
	    	GEvent.trigger(marker.obj, 'click');
	    	filtroAplicado = 'ALL';
	    	default_search = 'ALL';
	    }
	    
    }
    
    function editMarkers(marker,marker_id, event_id, pais, cidade){
    	
    	var latitudes='';
	    var longitudes='';
	    var ePoly = false;
	    try{
	    	latitudes = marker.getLatLng().lat();
	    	longitudes = marker.getLatLng().lng();
	    }catch(e){
	    	//e poligono
	    	ePoly = true;
	    	for(var i=0 ; i<marker.getVertexCount();i++){
			  	if(i==marker.getVertexCount()-1){
					latitudes+= marker.getVertex(i).lat();
					longitudes+= marker.getVertex(i).lng();
				}
				else{
					latitudes+= marker.getVertex(i).lat()+';';
					longitudes+= marker.getVertex(i).lng()+';';
				}					
			}
	    }	
	    
    	var html = addMarker(latitudes,longitudes,marker_id,pais,cidade,event_id);    	
    	var tabs = [];    	
        tabs.push(new GInfoWindowTab('Data',html));
        tabs.push(new GInfoWindowTab('Media',"<div id='media_list'><p>Save this marker before adding a media</p></div>"));        
        
        if(!ePoly)
        	marker.openInfoWindowTabs(tabs);
        else
        	map.openInfoWindowTabs(marker.getVertex(0),tabs);
        
        podeCarregarEventos = false;
    }
    
    function deleteMarker(id){
      var url=homepage+"a/"+wikimaps+"/deletemarker?id="+id;
      var req = GXmlHttp.create();
      // community check
      req.open("GET", url, false);
      req.send(null);      
      var result=req.responseText;
      var force=true;        
      if(parseInt(result)>0){
         force=confirm(comunidade);
      }    
      if(force){
          req.open("POST", url, false);
          req.send(null);      
          result=req.responseText;
          if(result=="OK"){
        	window.location=homepage+"a/"+wikimaps;
            map.closeInfoWindow();
            map.removeOverlay(markersArray[id].obj);
    	    
            var sidebar = $('search_results');
            var entry = $('_sb'+id);
            if(entry){
                sidebar.removeChild(entry);
            }
            //TODO Remove from markersArray
          }else{
             alert('Oops! '+result);
          }
      }
    }
    
    function getDadosSemWidgets(latLng, concept){
        if (latLng) {
        	if(!geocoder)
        		geocoder = new GClientGeocoder();
        	geocoder.getLocations(latLng, function(response) {
              if(response.Status.code != 200) {
            	  //alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
              }
              else {
            	  var place = response.Placemark[0];
            	  var pais = "";
            	  var estado = "";
            	  var cidade = "";
            	  if(place.AddressDetails.Accuracy >= 1)
            		  pais = place.AddressDetails.Country.CountryNameCode;
            	  if(place.AddressDetails.Accuracy >= 2)
            		  estado = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
            	  try{
            	  if(place.AddressDetails.Accuracy >= 4)
            		  cidade = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
            	  }catch(e){}
            	  if(pais && pais != "");
            	  var idConcept = "";
            	  for(i=0;i<concept.length;i++){
            		  if(i==0)
            			  idConcept += concept[i];
            		  else
            			  idConcept += ','+concept[i];
            	  }
            	  getWidget(pais, estado, cidade, idConcept);
              }    
            });
        }   	
    	
    }
    
    function searchMarkers(params){
        //Handle XML
    	filtroAplicado = params; 
        if (params==null||params=="") {
            $('qinput').focus();
            alert(pesquisaMarcador);
            return false;
        }
        if(params != 'ALL'){
        	clearMarkersArray();
        	map.clearOverlays();  
        }
        
	    GDownloadUrl(homepage+"/a/"+wikimaps+"/markers?q="+params+"&n="+map.getBounds().getNorthEast().lat()+"&s="+map.getBounds().getSouthWest().lat()+"&l="+map.getBounds().getNorthEast().lng()+"&o="+map.getBounds().getSouthWest().lng()+"&tm="+typeMarkers,
          function(data, responseCode) {
          	var xml = GXml.parse(data);
          	var markers = xml.documentElement.getElementsByTagName("m");
          	var concept = new Array();
          	for(i=0;i<markers.length;i++){
          		if(concept.indexOf(markers.item(i).getAttribute("idcon")) == -1)
          			concept[i] = markers.item(i).getAttribute("idcon");
          	}
          	plotMarkers(markers);
          	if(podeCarregarEventos && layoutApp == "semWidgets")
          		getDadosSemWidgets(map.getCenter(), concept);
    	  });
	    
    }
    
    function showTagCloud(){
      var url=homepage+"a/"+wikimaps+"/tagcloud";
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      $('tagcloud').innerHTML=req.responseText;      
    }        
    
    function showNotifications(){
        $j('#vmenu').accordion('activate',3);
    }
    
    var htmlMarkOnTheMap = '';
    function showMarkOnTheMap(){
      var url=homepage+"a/"+wikimaps+"/markonthemap";
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      htmlMarkOnTheMap = req.responseText;  
    }
    
    var htmlFilter = '';
    function showMarkersFilter(){
      var url=homepage+"a/"+wikimaps+"/showmarkers";
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      htmlFilter = req.responseText;              
    }
    
    function getHtmlFilter(){
    	htmlFilter = document.getElementById('info_modal_panel_content').innerHTML;
    }
    
    function checkNotifications(){      
      var url=homepage+"a/"+wikimaps+"/notifications";           
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);
      
      //Aqui são montadas as notificações para o layout Marina ou Mobilizace ou Capella /* Alterado por Izequiel */
      if (layoutApp=="microcredito" || layoutApp=="marina" || layoutApp=="mobilizace" || layoutApp=="capella") 
		  htmlNotifications = req.responseText;
      
      //Aqui são montadas as notificações para o layout viewer
      if(layoutApp=="viewer" || layoutApp == "semWidgets" || layoutApp == "semWidgets2") {
    	  $('notification_list').innerHTML=req.responseText;
      }	  
      else
      {
    	  if(document.getElementById('notification_list'))
    		  $('notification_list').innerHTML=req.responseText;
      }
    }
    
    function checkNewAlerts(){      
        var url=homepage+"a/"+wikimaps+"/newAlerts";           
        var req = GXmlHttp.create();
        req.open("GET", url, false);
        req.send(null);            
        if(layoutApp != 'mobilizace' && layoutApp != 'newviewer' && layoutApp != 'wikicrianca') { //Modificação para o Mobilizace /* Alterado por Izequiel */
        	$('notification_header').innerHTML=req.responseText; 
        }	
      }
    
    function cron(){
    	checkNewAlerts();
        checkNotifications();
        
        //Alteração para o layout Mobiliza CE /* Alterado por Izequiel */
        if (layoutApp != 'mobilizace' && layoutApp != 'newviewer' && layoutApp != 'wikicrianca') {
        	showTagCloud();
        }	
    }
    function showAddressComZoom(address,zoom) {
    	if (address==null||address=="") {
            $('qinput').focus();
            alert(pesquisaMarcador);
            return false;
        }
     var geocoder = new GClientGeocoder();
     geocoder.getLocations(address, function(response) {
         if (!response || response.Status.code != 200) {
             alert(mEnderecoNaoEncontrado);
        }
        else {
            place = response.Placemark[0];
            point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
            var msg=place.address  + ' <br/> ' + '<b>Codigo Pais:</b> ' + place.AddressDetails.Country.CountryNameCode;           
            filtroAplicado = "ALL";
            map.setCenter(point, zoom);
            //podeCarregarEventos = false;
            //map.openInfoWindowHtml(point,msg);
            
          }
         
     });
    }
    function showAddress(address) {
    	if (address==null||address=="") {
            $('qinput').focus();
            alert(pesquisaMarcador);
            return false;
        }
     var geocoder = new GClientGeocoder();
     geocoder.getLocations(address, function(response) {
         if (!response || response.Status.code != 200) {
             alert(mEnderecoNaoEncontrado);
        }
        else {
            place = response.Placemark[0];
            point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
            var msg=place.address  + ' <br/> ' + '<b>Codigo Pais:</b> ' + place.AddressDetails.Country.CountryNameCode;  
            switch(place.AddressDetails.Accuracy)
            {
                    case 0:
                        zoom=4;
                          break;   
                    case 1:
                        zoom=4;
                      break;
                     case 2:
                        zoom=8;
                      break;
                    case 3:
                        zoom=10;
                      break;
                    case 4:
                        zoom=11;
                      break;
                    case 5:
                        zoom=12;
                      break;
                    case 6:
                        zoom=14;
                      break;
                    case 7:
                        zoom=16;
                      break;
                    case 8:
                        zoom=17;
                      break;
                    default:
                        zoom=17;       
            }
            filtroAplicado = "ALL";
            map.setCenter(point, zoom);
            //podeCarregarEventos = false;
            //map.openInfoWindowHtml(point,msg);
            
          }
         
     });
    }
    var infoPC = null;
    var mouseMovePC=null;
    var mapRightClickPC = null;
    var mapClickPC = null;
    var ltLg = null;
    function prepararPedirCarona(){
    	mostraMenuRC = false;
    	infoPC = document.createElement('div');
    	mouseMovePC = GEvent.addListener(map, 'mousemove', function(cursorPoint){           			
    		    ltLg = cursorPoint;
              	var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    			var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(cursorPoint,map.getZoom());
    			
    			var height = infoPC.clientHeight;
    			var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - 30, offset.y - point.y + 20));
    			infoPC.innerHTML = "<div style='color:white;width: 192px;padding: 2px;font: normal normal normal 8pt Arial;text-align: justify;border: solid 1px white;background-color: #000;'>Clique no local onde deseja pedir carona</div>";
    			// Plota toolTip no mapa
    		  	pos.apply(infoPC);
    		  	map.getPane(G_MAP_FLOAT_PANE).appendChild(infoPC);
        	  					      	  	
    		  	infoPC.style.visibility="visible";
           
        }); 
    	mapRightClickPC = GEvent.addListener(map, "singlerightclick", function(point)
	    {        
	    		GEvent.removeListener(mapClickPC);
		        GEvent.removeListener(mapRightClickPC);
		        GEvent.removeListener(mouseMovePC);
		        
		      
		   	    infoPC.style.visibility="hidden";
		   	    mostraMenuRC = true;
	    }); 
	    mapClickPC = GEvent.addListener(map, 'click', function(){
		    	 
	        	
		        GEvent.removeListener(mapClickPC);
		        GEvent.removeListener(mapRightClickPC);
		        GEvent.removeListener(mouseMovePC);
		        
		      
		   	    infoPC.style.visibility="hidden";
		   	    plotCircleLeftClick(ltLg);
		   	    mostraMenuRC = true;
			   
		  });  
    }
    var raioPadrao = 800;
    function plotCircleLeftClick(point){
		
		plotCircle(point.lat(),point.lng(),raioPadrao);		
		//hiddeContextMenuRightClick();
		podeCarregarEventos = false;
		var html = getUsersWichRouteInTheCircle(raioPadrao, point.lat(), point.lng());
		map.openInfoWindowHtml(point,html);
	}

    /*
     *	Cria um controle para o pedir carona no GMAP
     *	[INICIO]
     */
    function caronaControl () {
    }
    
    caronaControl.prototype = new GControl();
    
    caronaControl.prototype.initialize = function(map) {
  	  // Declarando variáveis de controle
      this.posCaronaControl = new GSize(48,4);
      var div = document.createElement("div");
  	  div.style.cssText = vetorConfigCaronaControl.style;
  	  
  	  // ToolTip
  	  var tooltip = document.createElement("div");
  	  var posToolTip = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize((this.posCaronaControl.width + 46), (this.posCaronaControl.height + 6)));
  	  tooltip.style.cssText = vetorConfigCaronaControl.tooltipConfig;
  	  tooltip.innerHTML = vetorConfigCaronaControl.tooltipText;
  	  posToolTip.apply(tooltip);
  	  tooltip.style.visibility = "hidden";
  	  
  	  
  	  GEvent.addDomListener(div, "click", function() {
  		prepararPedirCarona();
  	  });
  	  
  	  GEvent.addDomListener(div, "mouseover", function() {
  		  tooltip.style.visibility="visible";
	  });
  	  
  	  GEvent.addDomListener(div, "mouseout", function() {
  		  tooltip.style.visibility = "hidden";
	  });

  	  map.getContainer().appendChild(div);
  	  map.getContainer().appendChild(tooltip);
  	  return div;
    }
    
    caronaControl.prototype.getDefaultPosition = function() {
  	  return new GControlPosition(G_ANCHOR_TOP_LEFT, this.posCaronaControl);
    }
    
    
    /*
     *	Cria um controle para o embedded no GMAP
     *	[FIM]
     */
    
    
    
    /*
     *	Cria um controle para o embedded no GMAP
     *	[INICIO]
     */
    function embedded () {
    }
    
    embedded.prototype = new GControl();
    
    embedded.prototype.initialize = function(map) {
  	  // Declarando variáveis de controle
      this.posEmb = new GSize(4,105);
      var div = document.createElement("div");
  	  div.style.cssText = vetorConfigEmbedded.style;
  	  
  	  // ToolTip
  	  var tooltip = document.createElement("div");
  	  var posToolTip = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize((this.posEmb.width + 46), (this.posEmb.height + 6)));
  	  tooltip.style.cssText = vetorConfigEmbedded.tooltipConfig;
  	  tooltip.innerHTML = vetorConfigEmbedded.tooltipText;
  	  posToolTip.apply(tooltip);
  	  tooltip.style.visibility = "hidden";
  	  
  	  
  	  GEvent.addDomListener(div, "click", function() {
  		  // Redireciona dados para página do embedded.
      	  var urlNewPage = homepage + 'embconf?idApp=' + vetorConfigEmbedded.idApp + '&titleApp=' + wikimaps_title + '&lat=' + map.getBounds().getCenter().lat() + '&lng=' + map.getBounds().getCenter().lng() + '&zoom=' + map.getZoom() + '&filtraMarcadores=' + typeMarkers + '&IFW=200&IFH=200';
      	  var embeddedWebPage = window.open(urlNewPage,'','left=200, top=130, width=1000, height=500, menubar=no, resizable=no, status=no, titlebar=no, toolbar=no, scrollbars=yes');
  		  embeddedWebPage.focus();
  	  });
  	  
  	  GEvent.addDomListener(div, "mouseover", function() {
  		  tooltip.style.visibility="visible";
	  });
  	  
  	  GEvent.addDomListener(div, "mouseout", function() {
  		  tooltip.style.visibility = "hidden";
	  });

  	  map.getContainer().appendChild(div);
  	  map.getContainer().appendChild(tooltip);
  	  return div;
    }
    
    embedded.prototype.getDefaultPosition = function() {
  	  return new GControlPosition(G_ANCHOR_TOP_LEFT, this.posEmb);
    }
    
    
    /*
     *	Cria um controle para o embedded no GMAP
     *	[FIM]
     */
    
    
    
    
    /*
     *	Cria um controle para o Mapa de Kernel
     *	[INICIO]
     */
    
    //	Variáveis para controle de interface.
    var kernelHabilitado = false;
    var clicouBotaoKernel = true;
    
    function kernelMap() {
    }
    
    kernelMap.prototype = new GControl();
    
    kernelMap.prototype.initialize = function(map) {
    	//	Declarando variáveis.
    	this.posKernel = new GSize(4,140);
    	var div = document.createElement("div");
    	div.style.cssText = vetorConfigKernelMap.style;
    	
    	
    	// ToolTip
		var tooltip = document.createElement("div");
		var posToolTip = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize((this.posKernel.width + 46), (this.posKernel.height + 6)));
		tooltip.style.cssText = vetorConfigKernelMap.tooltipConfig;
		tooltip.innerHTML = vetorConfigKernelMap.tooltipText;
		posToolTip.apply(tooltip);
		tooltip.style.visibility = "hidden";
    	

    	//	GEvents.
    	GEvent.addDomListener(div, "click", function() {
    		//	Tratamento para travar o duplo clique enquanto o kernel está sendo carregado.
    		if(clicouBotaoKernel) {
    			clicouBotaoKernel = false;
    			
	    		if (!kernelHabilitado) {
	    			podeCarregarEventos = false;	    			
	    			mapaDeKernelWikiMapps();
	    			kernelMapEscondeMarkers();
	    		}	
	    		else {	    			
	    			map.removeTPhoto(photo);
	    			//kernelMapMostraMarkers();
	    			kernelMapEscondeMarkers();
	    			podeCarregarEventos = true;
	    			searchMarkers(filtroAplicado);
	    		}
	    		//	Tratamento para ativar ou desativar o kernelMap.
	    		kernelHabilitado = !kernelHabilitado;
    		}	
    	});
    	
    	GEvent.addDomListener(div, "mouseover", function() {
    		  tooltip.style.visibility="visible";
  	  	});
    	  
    	  GEvent.addDomListener(div, "mouseout", function() {
    		  tooltip.style.visibility="hidden";
    	});

    	map.getContainer().appendChild(div);
    	map.getContainer().appendChild(tooltip);
    	return div;
    }
    
    kernelMap.prototype.getDefaultPosition = function() {
    	return new GControlPosition(G_ANCHOR_TOP_LEFT, this.posKernel);
	}

	function kernelMapMostraMarkers() {		// Reestrutura a lógica (atraves do filtroMarcadores)
		for(i in marcadoresKernel)
		{
			marcadoresKernel[i].obj.show();
		}
	}
	
	function kernelMapEscondeMarkers() {	// Reestrutura a lógica (atraves do filtroMarcadores)
		for(i in markersArray)
		{
			markersArray[i].obj.hide();
		}
	}
    /*
     *	Cria um controle para o Mapa de Kernel
     *	[FIM]
     */
  
	var clickedPixel;
	var contextmenu;
	var latLngRightClick;
	var mostraMenuRC = true;
	function contextMenuRightClick(){
       
	      contextmenu = document.createElement("div");
	      contextmenu.style.visibility="hidden";
	      contextmenu.style.background="#ffffff";
	      contextmenu.style.border="1px solid #8888FF";
	
	      contextmenu.innerHTML = '<a style="font-family:Arial, sans-serif; text-decoration:none; color:#4444ff; font-size:small; " href="javascript:plotCircleRightClick()"><div class="context">&nbsp;&nbsp;'+mQuemPassaPorAqui+'&nbsp;&nbsp;<\/div><\/a>'
	                            + '<a style="font-family:Arial, sans-serif; text-decoration:none; color:#4444ff; font-size:small; " href="javascript:hiddeContextMenuRightClick()"><div class="context">&nbsp;&nbsp;'+mCancel+'&nbsp;&nbsp;<\/div><\/a>';
	      map.getContainer().appendChild(contextmenu);
	      
	   
	      GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
	    	  if(mostraMenuRC){	
		    	  	if(circle){
				      map.removeOverlay(circle);
				    }	  
			    	  // store the "pixel" info in case we need it later
			        // adjust the context menu location if near an egde
			        // create a GControlPosition
			        // apply it to the context menu, and make the context menu visible
			    	var b = map.getBounds();
			    	
			    	pixelAux = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getNorthEast(), map.getZoom());
			    	var pointLatLng = new GPoint(pixelAux.x - map.getSize().width  + pixel.x, pixel.y + pixelAux.y);
			    	latLngRightClick = map.getCurrentMapType().getProjection().fromPixelToLatLng(pointLatLng, map.getZoom());
			    	clickedPixel = pixel;
			        var x=pixel.x;
			        var y=pixel.y;
			        if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
			        if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
			        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
			        pos.apply(contextmenu);
			        contextmenu.style.visibility = "visible";
	    	  }     
	      });
         
	}
	
	function plotCircleRightClick(){
		
		plotCircle(latLngRightClick.lat(),latLngRightClick.lng(),raioPadrao);		
		hiddeContextMenuRightClick();
		podeCarregarEventos = false;
		var html = getUsersWichRouteInTheCircle(raioPadrao, latLngRightClick.lat(), latLngRightClick.lng());
		map.openInfoWindowHtml(latLngRightClick,html);
	}
	
	function getUsersWichRouteInTheCircle(raio,lt,lg){
		var url=homepage+"a/"+wikimaps+"/getUsersWichRouteInTheCircle?raio="+raio+"&lt="+lt+"&lg="+lg;
		var req = GXmlHttp.create();
	    req.open("GET", url, false);
	    req.send(null);      
	    return req.responseText;
	}
	

	function getWidget(pais, estado, cidade, idConcept){
		var url=homepage+"a/"+wikimaps+"/getWidgetSemWidgets?type=2&pais="+pais+"&estado="+estado+"&cidade="+cidade+"&idConcept="+idConcept+"&lang=pt";
		var req = GXmlHttp.create();
	    req.open("GET", url, false);
	    req.send(null);
	    document.getElementById("div_codigo_sem_widgets").innerHTML = req.responseText;
	}
	
	function getWidgetPeloNome(nome){
		var url=homepage+"a/"+wikimaps+"/getWidgetSemWidgets?nome="+nome;
		var req = GXmlHttp.create();
	    req.open("GET", url, false);
	    req.send(null);
	    document.getElementById("div_codigo_sem_widgets").innerHTML = req.responseText;
	}
	
	function hiddeContextMenuRightClick(){
		contextmenu.style.visibility = "hidden";
	}
    
    // Construindo o mapa
    function load() {
    	//<div id="minfo_content" style="width: 370px; height: 150px;"></div>
		//<div id="media_content" style="width: 370px; height: 150px;"></div>      
      minfo_content = document.createElement('div');
      minfo_content.setAttribute('id', 'minfo_content');
      minfo_content.style.width = '420px';     
      minfo_content.style.height = '280px';
      
      generateqrcode_content = document.createElement('div');
      generateqrcode_content.setAttribute('id', 'generateqrcode_content');
      generateqrcode_content.style.width = '370px';     
      generateqrcode_content.style.height = '220px';
      
      media_content = document.createElement('div');
      media_content.setAttribute('id', 'media_content');
      media_content.style.width = '420px';     
      media_content.style.height = '250px';
      associations_content = document.createElement('div');
      associations_content.setAttribute('id', 'associations_content');
      associations_content.style.width = '420px';     
      associations_content.style.height = '250px';
      if(layoutApp=="viewer" || layoutApp == "semWidgets" || layoutApp == "semWidgets2"){ 
    	  comments_content = $('comments');
      }else{
    	  comments_content = document.createElement('div');
      } 
      
      if (GBrowserIsCompatible()) {
        //showLayerAdHoc('date_range', 400,7);      
        map = new GMap2($("map"),new GLatLng(-3.7183943,-38.5433948),13);
	    map.addControl(new GSmallMapControl());
	    map.addControl(new GMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(4,26)));
	    // Add the self created control
        //map.addControl(new ViewControl());
        //map.addControl(new AddControl());
	    
	    
	    //	Controle para o hidrotonicoi9 [INICIO]
//	    if(idWikiMappCurrent)
//	    {
//	    	if(idWikiMappCurrent == hidrotonicoi9_idApp)
//	    		hidrotonicoi9 = criaTPhoto(map, '/images/hidrotonicoi9/i9_1.png');
//	    }
	    //	Controle para o hidrotonicoi9 [FIM]
	    
	   
        if(usuarioLogado) 
        	contextMenuRightClick();
	    GEvent.addListener(map,"infowindowclose", 
	      function(overlay,latlng){
	    	if(circle){
	    		map.removeOverlay(circle);
	    		circle = null;
	    	}	
	    	if(polyRegister){
	    		map.removeOverlay(polyRegister);
	    		polyRegister = null;
	    		if(eventoBotaoDireitoDesenhoLinha)
	    			GEvent.removeListener(eventoBotaoDireitoDesenhoLinha);
	    	}	
	    	if(gadgetsComprados[5]!=undefined){
	    		mostrarFavoritos(false);
	    	}	
	    	podeCarregarEventos = true;
	        //map.returnToSavedPosition();          	
           	if(layoutApp=="viewer" || layoutApp == "semWidgets" || layoutApp == "semWidgets2"){
           		comments_content.innerHTML = "Select a marker";
           		$j('#vmenu').accordion('activate',1);
           	}	
	        if(newMarker){	            
	           	map.removeOverlay(newMarker);
	        }
	    });
	    
		preLoadImages();		
	    showMarkOnTheMap();	    
	    showMarkersFilter();
	    
	    if(layoutApp != "microcredito" && layoutApp != 'marina' && layoutApp != 'capella'){
	    	cron();        
			pe = new PeriodicalExecuter(cron,30);
	    }

	    //Inicia as Notificações no mapa da Marina ou MobilizaCE ou Capella /* Alterado por Izequiel */
	    if(layoutApp == "microcredito" || layoutApp == 'marina' || layoutApp == 'mobilizace')
	    {
	    	checkNotifications();
	    }
	    
	    //Adiciona controle de busca no mapa - Botões: Pesquisa Lugar e Pesquisa Marcador /* Alterado por Izequiel */
		if(layoutApp=='viewer' || layoutApp == 'mobilizace' || layoutApp == 'semWidgets' || layoutApp == 'semWidgets2' || layoutApp == 'newviewer' || layoutApp == 'wikicrianca'){
			map.addControl(new ComandoMapaPesquisa());
        }    
	    
	    // Adiciona controles personalizados ao mapa.
	    map.addControl(new embedded());
	    map.addControl(new kernelMap());
	    
//	    if(idWikiMappCurrent == "450" && usuarioLogado)
//	    	map.addControl(new caronaControl());
	    
	    
	    GEvent.addListener(map, "moveend", function() {
	    	if(filtroAplicado=='ALL'){
	      	  qtdMoveMap++;
	      	  if(podeCarregarEventos){	      		
			    	searchMarkers(filtroAplicado);		    	
		      }
	      	  else 
	      		  if (kernelHabilitado) {
	      			  podeCarregarEventos=false;
	      			  setTimeout(function(){
	      				  mapaDeKernelWikiMapps();
	      				  kernelMapEscondeMarkers();
	      				  map.removeTPhoto(photo);
	      			
	      			  },1000);    			
	      	  	}	
	    	}
	    });
	   
	    for(k in gadgetsComprados){
	      if (gadgetsComprados[k]==1){
	    	  setTimeout("addEstatisticasAV()",1000);    		 
	    	  break;
	      }    	  
	    }
	   
	    if(default_search=='ALL'){
	    	if(default_location != 'nulo'){
	    		if(raio!=''){
	    			map.setCenter(new GLatLng(latitude,longitude),15);
	    			
	    			setTimeout("plotCircle(latitude,longitude,raio)",1000);
	    		}
	    		else if(layoutApp == 'capella'){
	    			showAddressComZoom(default_location,6);	    			
	    		}
	    		else{	
	    			showAddress(default_location);	
	    			mostraIntroducaoApp();
	    		}	
	    	}	
	    	else{
	    		if(raio!=''){
	    			map.setCenter(new GLatLng(latitude,longitude),15);
	    			
	    			setTimeout("plotCircle(latitude,longitude,raio)",1000);
	    		}else{
		    		if(cookieCidade != null && cookieCidade != undefined && cookieCidade != ''){		    		
		    			showAddress(cookieCidade);
		    			$('qinput').value = cookieCidade;
		    		}	
			    	else{
			    		showAddress('Brasil-Fortaleza');
			    		$('qinput').value = 'Brasil-Fortaleza';
			    		if(!usuarioLogado){	
			    			mostraIntroducaoAppComEstados();			    	
			    		}
			    	}
	    		}	
	    	}
	    	
	    }	
	    else
	    	searchMarkers(default_search);
	   
	   
	    if(idUserParameter!='none'){
	    	showProfileUser(idUserParameter);
	    }	
	    
	    if(default_location != 'nulo')
	    	$('qinput').value = default_location;
	   
	   
      }
      
     
    }
  //Janela Modal para a aplicação notificações no Mapa da Marina  
  function showNotificationsModal(){ 
	  fillMsg(htmlNotifications,300,220,'38%','34%',true);
  }
  
   var mapClick = null; 
   var mouseMove = null;
   var mapRightClick = null;
   var infoMT = document.createElement("div");
  function follow(marker_id, color, w, h){
	  podeCarregarEventos = false;
	  removeMarkerRegisterEvent();
	  var dog = true;
      var noMore = false;
      var mapRightClick;
      mouseMove = GEvent.addListener(map, 'mousemove', function(cursorPoint){
        if(!noMore){      
          var customIcon = tinyIcon(color,marker_id,w,h);
          markerOptions = { icon:customIcon, draggable:false, autoPan:false };
          newMarker = new MyMarker(cursorPoint, markerOptions);
          map.addOverlay(newMarker);
          noMore = true;	
        }
        
        if(dog){
        	newMarker.setLatLng(cursorPoint);
          
          	var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
			var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(newMarker.getPoint(),map.getZoom());
			var anchor = newMarker.getIcon().iconAnchor;
			var width = newMarker.getIcon().iconSize.width;
			var height = infoMT.clientHeight;
			var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height));
	
		  	infoMT.innerHTML = "<div style='width: 150px;heidth: 100px;padding: 5px;font: normal normal normal 8pt Arial;text-align: justify;border: solid 1px black;background-color: #F0F8FF;'>"+messageTempRegister+"</div>";
	
			// Plota toolTip no mapa
		  	pos.apply(infoMT);
		  	map.getPane(G_MAP_FLOAT_PANE).appendChild(infoMT);
    	  					      	  	
  	  		infoMT.style.visibility="visible";
        }
      });
      mapRightClick = GEvent.addListener(map, "singlerightclick", function(point)
      {        
    	  removeMarkerRegisterEvent();
    	  podeCarregarEventos = true;
      }); 
      mapClick = GEvent.addListener(map, 'click', function(){
	    	 
        	//map.savePosition();      
	        dog = false;        
	        // 'mousemove' event listener is deleted to save resources
	        GEvent.removeListener(mapClick);
	        GEvent.removeListener(mapRightClick);
	        GEvent.removeListener(mouseMove);
	        // Posiciona o Marker nmo centro do mapa
	        //map.panTo(newMarker.getLatLng());
	        getCidadePais(newMarker.getLatLng());
	        var html = addMarker(newMarker.getLatLng().lat(),newMarker.getLatLng().lng(),marker_id,paisRegistro,cidadeRegistro);
	        limpaCidadePaisRegistro();
	        var tabs = [];
	        tabs.push(new GInfoWindowTab('Data',html));
	        tabs.push(new GInfoWindowTab('Media',"<div id='media_list'><p>Save this marker before adding a media</p></div>"));        
	   	    newMarker.openInfoWindowTabs(tabs);
	   	    infoMT.style.visibility="hidden";
		    //newMarker.openInfoWindow(tempinfo,{maxContent: html,   maxTitle: wikimaps_title});  	    	    
		    eval('lastMarkerArray=j'+marker_id+';');
		    
	    });
   }
  
function removeMarkerRegisterEvent(){
	if (newMarker) {	         
		// perform marker specific right-click processing
		GEvent.removeListener(mapClick);        
        GEvent.removeListener(mouseMove);
		map.removeOverlay(newMarker);
		infoMT.style.visibility="hidden";
		noMore=true;           
	} else {
		// possibly consider other types of overlays, e.g. info window
	}
}

function commentFocus(){
	if(layoutApp == 'viewer' || layoutApp == 'semWidgets' || layoutApp == "semWidgets2")
		$j('#vmenu').accordion('activate',2);
	else
		map.getInfoWindow().selectTab(1);
	//document.getElementById('txt_area_comment').style.height = 140;
	document.getElementById('txt_area_comment').focus();
}

function showAssociation(idTyp,idEvent,oper){
	var url=homepage+"/a/"+wikimaps+"/mkr/editAssociation?idTyp="+idTyp+"&idEvent="+idEvent+"&op="+oper;      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);
    
    
    fillMsg(req.responseText,480,370,'22%',80,true);
}

function showDataAssociation(idTyp,idEvent,oper){	
	var url=homepage+"/a/"+wikimaps+"/mkr/dataAssociation?idTyp="+idTyp+"&idEvent="+idEvent+"&op="+oper;      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);
    
    
    fillMsg(req.responseText,400,210,'30%',180,true);
}

function showProfileUser(id){
	var url=homepage+"/users/friendship?id="+id+"&apps_id="+idWikiMappCurrent;      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);      
    fillMsg(req.responseText,680,470,'30%',50,true);
}

function showRouteView(id){
	var url=homepage+"/a/"+wikimaps+"/routeview?events_id="+id;      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);
    fillMsg(req.responseText,320,200,'38%','30%',true);
}

   
/* start View button */

function showLayerAdHoc(div_name, x_pos, y_pos) {

 var layerbox = $(div_name); 
 var mapdiv = $("map"); 
 // Left size of more control plus mapdiv.style.left 
 var offsetX = x_pos + mapdiv.offsetLeft;
 // Top size of more control plus mapdiv.style.top plus more button height
 var offsetY = y_pos + mapdiv.offsetTop;
 var lpos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offsetX, offsetY));
 lpos.apply(layerbox);
 if(window.timer) clearTimeout(timer);
 layerbox.style.display = "block";
}

function showViewBox(){
  showLayerBox('box', 160);
}

function showAddBox(){
  showLayerBox('add', 50);
}

function showLayerBox(div_name, x_pos) {

 var layerbox = $(div_name); 
 var mapdiv = $("map"); 
 // Left size of more control plus mapdiv.style.left 
 var offsetX = x_pos + mapdiv.offsetLeft;
 // Top size of more control plus mapdiv.style.top plus more button height
 var offsetY = 7 + mapdiv.offsetTop + 18;

 var lpos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offsetX, offsetY));
 lpos.apply(layerbox);
 if(window.timer) clearTimeout(timer);
 layerbox.style.display = "block";
}

function setCloseView(e){
    setCloseBox(e, "box");
}

function setCloseAdd(e){
    setCloseBox(e, "add");
}

function setCloseBox(e, div_name) {

 if(!e) e = window.event;
 var layerbox = document.getElementById(div_name);

 if(checkMouseLeave(layerbox, e))
  timer = setTimeout(function() {
   layerbox.style.display = "none"; }, 400);
}

function checkMouseLeave(element, evt) {

 /* Avoid firing a mouseout event
 *  when the mouse moves over a child element.
 *  Borrowed from:
 *  http://www.faqts.com/knowledge_base/view.phtml/aid/1606/fid/145
 */
 if(element.contains && evt.toElement) {
   return !element.contains(evt.toElement);
 }
 else if(evt.relatedTarget) {
   return !containsDOM(element, evt.relatedTarget);
 }
}


function containsDOM(container, containee) {

 var isParent = false;
 do {
  if((isParent = container == containee))
   break;
   containee = containee.parentNode;
 }
 while(containee != null);
 return isParent;
}

function ViewControl(){};
ViewControl.prototype = new GControl();
ViewControl.prototype.initialize = function(map) {

 var control = document.createElement("div");
 control.style.border = "1px solid black";
 control.title = "Show/Hide Markers";
 var inner = document.createElement("div");
 inner.id = "more_inner";
 inner.appendChild(document.createTextNode("Filter Markers"));
 control.appendChild(inner);
 //control.onmouseover = showViewBox;
 control.onclick = showViewBox;
 control.onmouseout = setCloseView;
 map.getContainer().appendChild(control);
 return control;
}

ViewControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(160, 7));
}

function AddControl(){};
AddControl.prototype = new GControl();
AddControl.prototype.initialize = function(map) {

 var control = document.createElement("div");
 control.style.border = "1px solid black";
 control.title = "Add Marker";
 var inner = document.createElement("div");
 inner.id = "more_inner";
 inner.appendChild(document.createTextNode("Add Marker"));
 control.appendChild(inner);
 //control.onmouseover = showAddBox;
 control.onclick = showAddBox;
 control.onmouseout = setCloseAdd;
 map.getContainer().appendChild(control);
 return control;
}

AddControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50, 7));
}

function switchStar(){
    var star = document.getElementById("mini_icon");
    star.className=star.className=='enstar'?'disstar':'enstar';    
}

   /* end more button */
 
function myToggle(){
        $j("#map").toggle();
        $j("#msg").toggle();
}  

function toggleMsg(map){
//    if(map){
//        $j("#map").show();
//        
//        $j("#msg").hide();
//    }else{
//        $j("#map").hide();
//        $j("#msg").show();
//        
//    }    
}

function validaFormConvidarAmigos(){
	if(($('email1').value==null || $('email1').value== "" ) && ($('email2').value==null || $('email2').value== "" ) && ($('email3').value==null || $('email3').value== "" ) && ($('email4').value==null || $('email4').value== "") && ($('email5').value==null || $('email5').value== "" ) && ($('email6').value==null || $('email6').value== "" )){
		$('div_error_invite_friends').innerHTML = mValidacaoConvite;
		$('email1').focus();
	}else{
		$('div_error_invite_friends').innerHTML = "";
		$('bt_enviar_convite').disabled=true;
		$('form_invite_friends').click();
	}	
}

function prepararConvidarAmigos(){
	var url=homepage+"a/"+wikimaps+"/invitefriends";      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);      
    fillMsg(req.responseText,580,400,'30%',120,true);
}

function fecharModal(){
	//	Oculta mensagem de descrição do wikimap [INICIO]
	if($('fillmsgCheck') && $('fillmsgCheck').checked)
	{
		var url=homepage+"apps/ocultaJanelaInicialApp?aId=" + idWikiMappCurrent;      
	    var req = GXmlHttp.create();
	    req.open("GET", url, false);
	    req.send(null);
	}
	//	Oculta mensagem de descrição do wikimap [FIM]
	
	$('fundo_bloqueado').style.visibility='hidden';
	$('info_modal_panel').style.visibility = 'hidden';
}

function fillMsg(html,largura,altura,left,top,semBotaoFechar){
	
    $("info_modal_panel_content").innerHTML=html;
    
    
    if(!$("fillmsgCheck") || ($("fillmsgCheck") && showDescricaoInicial == 'T'))
    {
    	$("fundo_bloqueado").style.visibility = "visible";
    	$('info_modal_panel').style.visibility = "visible";
    } else {
    	$('fundo_bloqueado').style.visibility='hidden';
    	$('info_modal_panel').style.visibility = 'hidden';
    }

    
    if (altura && largura && left && top){
    	$("info_modal_panel").style.width = largura;
    	$("info_modal_panel").style.height = altura + 46;
    	$("info_modal_panel_content").style.height = (parseInt(altura)-52);
    	$("info_modal_panel").style.left = left;
    	$("info_modal_panel").style.top = top;
    }
    //codigo que inclui botao para fechar modal
    if(!semBotaoFechar)
    {
    	$("info_modal_panel_content").innerHTML+="<br /><center><input type=button class='buttongray' value=" + mClose + " onclick='fecharModal();' ></input></center>";
    }
    
    //	inclui opção para que não apareça a tela inicial de descrição do wikimapp
    //	$("info_modal_panel_content").innerHTML+="<br /><input id='fillmsgCheck' type='checkbox'/>" + telaDescInicial_check;
    
}

function static_link(title){
    wiki(title);
}

function static_link_map(title){
    wiki(title);
    //toggleMsg(false);
}

function wiki(title){
	var url=homepage+"s/"+wikimaps+"/"+title;      
	if (arguments.length == 2){
	   url=url+"?path="+arguments[1];   
	}  
	var myAjax = new Ajax.Request(url,{method: 'get', 				
		onComplete: function (req){	
		fillMsg(req.responseText,580,380,'30%',200);            
    }
	});		   
}

function showAboutUs(edit){
      var url=edit?homepage+"a/"+wikimaps+"/aboutus?edit=y":homepage+"a/"+wikimaps+"/aboutus";      
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      fillMsg(req.responseText,580,180,'30%',200);
      //toggleMsg(false);
}

function showContactUs(edit){
      var url=edit?homepage+"a/"+wikimaps+"/contactus?edit=y":homepage+"a/"+wikimaps+"/contactus";      
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      fillMsg(req.responseText,580,180,'30%',200);
      //toggleMsg(false);
}

function showTermsOfUse(edit){
      var url=edit?homepage+"a/"+wikimaps+"/tou?edit=y":homepage+"a/"+wikimaps+"/tou";      
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      fillMsg(req.responseText,580,300,'30%',200);
      //toggleMsg(false);
}

function showHowToUse(edit){
    var url=edit?homepage+"a/"+wikimaps+"/htu?edit=y":homepage+"a/"+wikimaps+"/htu";      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);      
    fillMsg(req.responseText,580,300,'30%',200);
    //toggleMsg(false);
}

function showPropHelp(pid,edit){
      var url=edit?homepage+"a/"+wikimaps+"/prophelp?pid="+pid+"&edit=y":homepage+"a/"+wikimaps+"/prophelp?pid="+pid;      
      var req = GXmlHttp.create();
      req.open("GET", url, false);
      req.send(null);      
      fillMsg(req.responseText,580,300,'30%',200);
      //toggleMsg(false);

}

function showAddMedia(idEvent){
	 var url=homepage+"a/"+wikimaps+"/medias/id/" + idEvent;
	 var req = GXmlHttp.create();
     req.open("GET", url, false);
     req.send(null);      
     fillMsg(req.responseText,350,250,'30%',200);
}




function showResponderTopico(id){
	 var url=homepage+"/apps/responderTopico?url="+wikimaps+"&tid="+id;
	 var req = GXmlHttp.create();
	  	req.open("GET", url, false);
	  	req.send(null);
	  	 fillMsg(req.responseText,550,380,'30%',150,true);
}
function validaTexto(obj) {
	obj.value = obj.value.replace(/\d/g,"");
}



function chooseFileType(idTypeFile){
	if(idTypeFile==0){
		document.getElementById('video').style.display="";
		 document.getElementById('video').style.visibility="visible";
		 document.getElementById('photo').style.visibility="hidden";
		 document.getElementById('photo').style.display="none";
		 
		 
	}	
	else if(idTypeFile==2){
		document.getElementById('video').style.visibility="hidden";
		document.getElementById('video').style.display="none";
		 document.getElementById('photo').style.visibility="visible";
		 document.getElementById('photo').style.display="";
		
	}
	else {
		document.getElementById('video').style.display="none";
		 document.getElementById('photo').style.display="none";
    }
}

    
function showMedia(id){      
/*
        var template='<div id="media"><h2>LABEL</h2><object width="320" height="265"><param name="movie" value="URL&hl=pt-br&fs=1&color1=0x2b405b&color2=0x6b8ab6"></param>        <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="URL&hl=pt-br&fs=1&color1=0x2b405b&color2=0x6b8ab6" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="320" height="265"></embed></object></div><a href="javascript:hideMedia()">Back to Map</a>';		
		var t = template.replace(/LABEL/g,label);
        mediaDiv.innerHTML=t.replace(/URL/g,url);
        */
        fillMsg(getMarkerMedia(id));
        //toggleMsg(false);
        map.closeInfoWindow();
}

function hideMedia(){
    fillMsg('');
    $('info_modal_panel').style.visibility = 'hidden';
    //toggleMsg(true);
}

function searchDate(title, when){
    $('when').innerHTML=title;
    searchMarkers(when);
}


function validate_required(field,alerttxt){
    with (field)
    {
      if (value==null||value=="")
      {
      alert(alerttxt);return false;
      }
      else
      {
      return true;
      }
    }
}

//	Remove propriedades não cadastradas no banco na tela de edição de marcadores da aplicação
function removePropriedadesMarcador(divRoot, elemento) {
	var root = document.getElementById(divRoot);
	var elem = document.getElementById(elemento);
	root.removeChild(elem);
}

//	Controle para termos de uso na página: cadastroUserApp.php
function checkTermAction(checkStatus) {
	var botao = document.getElementById("bAvancar").disabled;
	
	if (botao) {
		document.getElementById("bAvancar").disabled = false;
	} else {
		document.getElementById("bAvancar").disabled = true;
	}
}

function getHtmlPesquisaGenerica(){
	var url=homepage+"a/"+wikimaps+"/formPesquisa";      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);      
    return req.responseText;
}

var divPesquisaMapa;

function ComandoMapaPesquisa() {
}
ComandoMapaPesquisa.prototype = new GControl();

ComandoMapaPesquisa.prototype.initialize = function(map) {
  var container = document.createElement("div");

  divPesquisaMapa = document.createElement("div");
  this.setButtonStyle_(divPesquisaMapa);
  container.appendChild(divPesquisaMapa);
  divPesquisaMapa.innerHTML = getHtmlPesquisaGenerica();
 
  map.getContainer().appendChild(container);
  return container;
}


ComandoMapaPesquisa.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(4,4));
}


ComandoMapaPesquisa.prototype.setButtonStyle_ = function(gadget) {				
 
    //gadget.style.backgroundColor = corApp;
	//gadget.style.border = "solid 1px #ccc";
//	gadget.style.opacity= ".85";
//	gadget.style.mozOpacity = "0.85";
//	gadget.style.filter= "alpha(opacity=85)";
  //button.style.cursor = "pointer";
  //button.style.backgroundImage = "url('./images/logoWikicrimesEmbedded.PNG')";
}

function mostrarCarregando(elemento,button){
	document.getElementById(elemento).style.visibility = "visible";
	document.getElementById(button).disabled = true;
	
}

function escondeCarregando(elemento,button){
	document.getElementById(elemento).style.visibility = "hidden";
	document.getElementById(button).disabled = false;    	
}

function validaFormRegistrarEvento(texto){    
	mostrarCarregando('imgCarregando','btSubmitSaveMarker');
	var campoDefault = document.getElementById("def_properties_id").value;
	if(campoDefault == "" || campoDefault == null){
		var textTags = document.getElementById("raw_tags").value;
		if(textTags == "" || textTags == null){			
			mostrarValidacao(texto);
			escondeCarregando('imgCarregando','btSubmitSaveMarker');
			document.getElementById("raw_tags").focus();
			return false;
		}
	}else{		
		var propDefaut = document.getElementById('p_'+campoDefault).value;		
		if(propDefaut == "" || propDefaut == null){
			mostrarValidacao(texto);
			escondeCarregando('imgCarregando','btSubmitSaveMarker');
			document.getElementById('p_'+campoDefault).focus();
			return false;
		}
	}
	
	document.getElementById("btSubmitSaveMarkerHidde").click();
	return false;	
}

function mostrarValidacao(texto){
	var html = '<ul>';
	html += '<font color="red"><li>'+texto+'</li></font>';
	html += '</ul>';
	document.getElementById("div_validacoes").innerHTML = html;
}
// funcao que verifica se o usuario está logado
function checaUsuarioLogado() {
	if (usuarioLogado)
		return true;
	else {
		
		return false;
	}
}
// alert indicativo de necessidade de login com permalink para marker
function alertaUsuario(marcador){
	
	fillMsg("<center><font color=red>"+ informativoLogin +"</font><br/><br/> <a href=/a/"+ wikimaps + "/secureshow/mid/NBSP" + marcador + ">" + informativoClickLogin + "</a></center><br/><br/>",250,150,'40%',200);
	
}
//mostra splash screen da aplicacao
function mostraIntroducaoApp(){
	 var url=homepage+"a/"+wikimaps+"/introapp";
	 
//     return '<iframe src ="'+url+'" width="370" height="200" frameborder="0"><p>Your browser does not support iframes.</p></iframe>';
     var req = GXmlHttp.create();
     req.open("GET", url, false);
     req.send(null);
     fillMsg(req.responseText,550,300,'30%',130)
     
	
}
function salvaCookie(cidade){
	var url=homepage+"/a/"+wikimaps+"/salvarCookie?cidade="+cidade;
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);
    if(req.responseText == 'ok'){        	
    	
    }else{
    	alert('error');
    }	
}

function mostrarCidadeMapa(cidade){
	default_location = cidade;
	showAddress(default_location);
	$('qinput').value = default_location;	
	fecharModal();
	salvaCookie(cidade);
}

function mostraIntroducaoAppComEstados() {
	 var url=homepage+"a/"+wikimaps+"/introapp";
   
//    return '<iframe src ="'+url+'" width="370" height="200" frameborder="0"><p>Your browser does not support iframes.</p></iframe>';
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);
    fillMsg(req.responseText+getHtmlComEstados(),450,350,'30%',180,true);	
}

function getHtmlComEstados(){
	var html = '';
	html += '	<table width="100%">';
	html += '	<tr>';
	html += '	<td style="text-align:center">';
	html += '	'+mSelecioneEstadoBrasileiro+':';
	html += '	</td>';
	html += '	</tr>';
	html += '	<tr>';
	html += '	<td style="text-align:center">';
	html += '	<select onchange="mostrarCidadeMapa(this.value)" id="endereco_combo" name="endereco_combo">';
	html += '	<option value=""> '+mSelecione+' </option>';
	html += '	<option value="Brasil-Acre"> Ácre </option>';
	html += '	<option value="Brasil-Alagoas"> Alagoas </option>';	
	html += '	<option value="Brasil-Amapá"> Amapá </option>';
	html += '	<option value="Brasil-Amazonas"> Amazônas </option>';
	html += '	<option value="Brasil-Bahia"> Bahia </option>';
	html += '	<option value="Brasil-Boa-Vista"> Boa Vista </option>';
	html += '	<option value="Brasil-Ceará"> Ceará </option>';
	html += '	<option value="Brasil-DF"> Distrito Federal </option>';
	html += '	<option value="Brasil-Espírito-Santo"> Espírito Santo </option>';
	html += '	<option value="Brasil-Goias"> Goias </option>';
	html += '	<option value="Brasil-Pará"> Pará </option>';
	html += '	<option value="Brasil-Paraíba"> Paraíba </option>';
	html += '	<option value="Brasil-Paraná"> Paraná </option>';
	html += '	<option value="Brasil-Pernambuco"> Pernambuco </option>';
	html += '	<option value="Brasil-Piauí"> Piauí </option>';
	html += '	<option value="Brasil-Mato-Grosso-do-Sul"> Mato Grosso do Sul </option>';
	html += '	<option value="Brasil-Mato-Grosso"> Mato Grosso </option>';
	html += '	<option value="Brasil-Maranhão"> Maranhão </option>';
	html += '	<option value="Brasil-Minas-Gerais"> Minas Gerais </option>';
	html += '	<option value="Brasil-Rio-de-Janeiro"> Rio de Janeiro </option>';
	html += '	<option value="Brasil-Rio-Grande-do-Norte"> Rio Grande do Norte </option>';
	html += '	<option value="Brasil-Rio-Grande-do-Sul"> Rio Grande do Sul </option>';	
	html += '	<option value="Brasil-Rondônia"> Rondônia </option>';
	html += '	<option value="Brasil-São-Paulo"> São Paulo </option>';
	html += '	<option value="Brasil-Santa-Catarina"> Santa Catarina </option>';
	html += '	<option value="Brasil-Sergipe"> Sergipe </option>';
	html += '	<option value="Brasil-Tocantins"> Tocantins </option>';	
	html += '	</select>';
	html += '	</td>';
	html += '	</tr>';
	html += '	</table>';
	return html;
}
//marca msg nova como lida
function marcaMsgLida(param){
	var url=homepage+"a/"+wikimaps+"/markAsRead?notif="+param;
	var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);
	
}
function removeAplicacao(name){
	document.forms[name].submit();
}

function generateQRCode(marker){
	var url = homepage+"a/"+wikimaps+"/generateQRCode/id/"+marker.id+"/lat/"+marker.obj.getLatLng().lat()+"/lng/"+marker.obj.getLatLng().lng();

	var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);
    
    generateqrcode_content.innerHtml = req.responseText;
	
    //Por algum motivo eh necessario passar o valor do innerHtml para a nova variavel
    var stringHtml = generateqrcode_content.innerHtml;
    
	var tabs = [];
	tabs.push(new GInfoWindowTab('Generate QRCode', stringHtml));
	marker.obj.openInfoWindowTabs(tabs);
	podeCarregarEventos = false;
}

/*
 *	Wikimapps Modal
 *		Para utilização é necessario criar um vetor que deverá conter os seguintes campos:
 *			wmTamanhoModal 			- [p|m|g]
 *			wmTituloModal  			- ['Titulo do seu modal']
 *			wmCorTituloModal 		- ['Black'|'#FFFF']
 *			wmCorFundoTituloModal	- ['Black'|'#FFFF']
 *			wmConteudoModal			- [STRING|HTML]
 *			wmCorConteudoModal		- ['Black'|'#FFFF']
 *			wmCorFundoConteudoModal		- ['Black'|'#FFFF']
 *		Exemplo de um vetor para o criação do modal:
 *		
		var vInfoModal = {
			wmTamanhoModal : 'm',
			wmTituloModal : 'Meu titulo',
			wmCorTituloModal : 'Black',
			wmCorFundoTituloModal : '#FFFFFF',
			wmConteudoModal : '<div>Hello World</div>',
			wmCorConteudoModal : 'Black',
			wmCorFundoConteudoModal : 'White'
		}
 *		
 *		Bom uso! 
 */

//	Wikimapps Modal Config [INICIO]
function wmModalShow(modalConfig)
{
	//	Monta estrutura do modal
	var mBase = document.createElement("div");
	var mTitulo = document.createElement("div");
	var mTituloText = document.createElement("p");
	var mConteudo = document.createElement("div");
	var mRodape = document.createElement("div");
	var bFechar = document.createElement("div");
	
	
	
	//	Configurando Base
	mBase.id = "wmModalBaseDiv";
	mBase.className = "wmModalBase";
	
	//	Configurando título
	mTitulo.id = "wmModalTituloDiv";
	mTituloText.innerHTML = modalConfig.wmTituloModal;
	mTitulo.className = "wmModalTitulo";
	
	//	Configurando conteudo
	mConteudo.innerHTML = modalConfig.wmConteudoModal;
	mConteudo.className = "wmModalConteudo";
	
	//	Configurando rodapé
	mRodape.id = "wmModalRodapeDiv";
	mRodape.className = "wmModalRodape";
	
	//	Configurando botão de fechar
	bFechar.className = "wmModalFecharDiv";
	bFechar.innerHTML = "X";
	bFechar.onclick = function () {
		wmModalClose();
	};
	
	
	
	//	Configura style do modal [INICIO]
	//	Altera tamanho se necessário
	if(modalConfig.wmTamanhoModal)
	{
		if(modalConfig.wmTamanhoModal == 'm' || modalConfig.wmTamanhoModal == 'M')
		{
			document.getElementById("wmModal").style.width = '70%';
			document.getElementById("wmModal").style.height = '70%';
			document.getElementById("wmModal").style.top = '12%';
			document.getElementById("wmModal").style.left = '15%';
			mTitulo.style.height = '8%';
			mConteudo.style.height = '87%';
			bFechar.style.left = '96%';
		}
		
		if(modalConfig.wmTamanhoModal == 'g' || modalConfig.wmTamanhoModal == 'G')
		{
			document.getElementById("wmModal").style.width = '90%';
			document.getElementById("wmModal").style.height = '90%';
			document.getElementById("wmModal").style.top = '2.5%';
			document.getElementById("wmModal").style.left = '5%';
			mTitulo.style.height = '7%';
			mConteudo.style.height = '88%';
			bFechar.style.left = '96.5%';
			bFechar.style.top = '22%';
		}
	}
	
	//	Altera a cor do fundo e das letras do modal
	if(modalConfig.wmCorTituloModal)
	{
		bFechar.style.color = modalConfig.wmCorTituloModal;
		bFechar.style.borderColor = modalConfig.wmCorTituloModal;
		mTitulo.style.color = modalConfig.wmCorTituloModal;
	}
	
	if(modalConfig.wmCorConteudoModal)
	{
		mConteudo.style.color = modalConfig.wmCorConteudoModal;
		mRodape.style.color = modalConfig.wmCorConteudoModal;
	}
	
	if(modalConfig.wmCorFundoTituloModal)
		mTitulo.style.backgroundColor = modalConfig.wmCorFundoTituloModal;
	
	if(modalConfig.wmCorFundoConteudoModal)
	{
		mConteudo.style.backgroundColor = modalConfig.wmCorFundoConteudoModal;
		mRodape.style.backgroundColor = modalConfig.wmCorFundoConteudoModal;
	}
	//	Configura style do modal [FIM]
	
	
	
	//	Anexando conteúdos
	mTitulo.appendChild(mTituloText);
	mTitulo.appendChild(bFechar);
	mBase.appendChild(mTitulo);
	mBase.appendChild(mConteudo);
	mBase.appendChild(mRodape);
	$j("#wmModal").append(mBase);
	
	//	Arrendonda bordas do modal
	$j("#wmModalTituloDiv").corner("top");
	$j("#wmModalRodapeDiv").corner("bottom");
	
	//	Mostrando modal
	window.scroll(0,0);
	document.body.style.overflow = 'hidden';
	$j("#wmModalBack").show();
	$j("#wmModal").show();
}


function wmModalClose()
{
	$j("#wmModalBaseDiv").remove();
	window.scroll(0,0);
	document.body.style.overflow = 'auto';
	$j("#wmModalBack").hide();
	$j("#wmModal").hide();
}
function showMarkerHelp(mid){
    var url=homepage+"a/"+wikimaps+"/markerhelp?mid="+mid;      
    var req = GXmlHttp.create();
    req.open("GET", url, false);
    req.send(null);      
    fillMsg(req.responseText,580,300,'28%',200);
    //toggleMsg(false);

}
//	Wikimapps Modal Config [FIM]



//	Verifica caracteres inválidos [INICIO]
function checaCharInvalidos(idObj)
{
	var objText = document.getElementById(idObj).value;
	var ocorrencias = objText.split('|');
	var newText = '';
	
	for(var i=0; i < ocorrencias.length; i++)
		newText += ocorrencias[i];

	document.getElementById(idObj).value = newText;
	
	if(ocorrencias.length > 1)
		alert(msgCharInvalido);
}
//	Verifica caracteres inválidos [FIM]


//	Controle do radiobutton do page template [INICIO]
function checaTemplateRadio(id,valor)
{
	if(valor == 'padrao')
		document.getElementById('TPTextArea').style.display="none";
	else
		document.getElementById('TPTextArea').style.display="block";
}
//	Controle do radiobutton do page template [FIM]

//linkperfil
function linkperfil(token){
	window.open("http://wikimapps.com/index.php/a/"+wikimaps+"/show/uid/"+token);
}
//fim 
