//var centreLat=-15.37312905;
//var centreLon=-51.40196927999999;
var initialZoomLevel=4;
var n_buttonText="Mapa"; 
var s_buttonText="Satélite";
var h_buttonText="Híbrido";
var map; 
var opacity = 0.4;
var geocoder = null;
var conteudo_div_painel="";
var segunda_busca = false;
var fileXML = "/sys/xml/cobertura/3g.xml";
var fileXML_frequeencia = "/sys/xml/cobertura/geral.xml";

var pathIMG = "";
var	callCenter = (document.location.href.indexOf("cobertura_interna") == -1) ? false : true ;

function NovaJanela(pagina,nome,w,h,scroll)
{
	LeftPosition = (screen.width) ? (screen.width-w) / 2 : 0;
	TopPosition = ((screen.height) ? (screen.height-h) / 2 : 0) -100 ; //obtem a centralização da tela, porem retiramos 100px para melhor visualoização.
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable=No';
	win = window.open(pagina,nome,settings);
}

function exibirAjuda(){
	NovaJanela('info.htm', '', 800, 260, 'No');
}
	
function customGetTileURL(a,b) {
	
      //converte o tile x,y em uma string
      var UF = document.getElementById("cmbEstados").value;
		
      if (b>15 || vImagem.toUpperCase()=='NAO') { return pathIMG + UF.toUpperCase() +"/blank-tile.png"; };
			
      var c=Math.pow(2,b);
      var x=360/c*a.x-180;
      var y=180-360/c*a.y;
      var x2=x+360/c;
      var y2=y-360/c;
      var lon=x; 
      var lat=(2.0*Math.atan(Math.exp(y/180*Math.PI))-Math.PI/2.0)*180/Math.PI; //em graus
      var lon2=x2;
      var lat2=(2.0*Math.atan(Math.exp(y2/180*Math.PI))-Math.PI/2.0)*180/Math.PI; //em graus
      var tileBounds=new GLatLngBounds(new GLatLng(lat2,lon),new GLatLng(lat,lon2));

			//transparent
			
      if (!tileBounds.intersects(mapBounds)) { return pathIMG + UF.toUpperCase() +"/blank-tile.png"; };

				var d=a.x;
        var e=a.y;
        var f="t";
        for(var g=0;g<b;g++){
            c=c/2;
            if(e<c){
                if(d<c){f+="q"}
                else{f+="r";d-=c}
            }
            else{
                if(d<c){f+="t";e-=c}
                else{f+="s";d-=c;e-=c}
            }
        }
        return pathIMG + UF.toUpperCase() +"/"+f+".png"
    }
	
	function load() {
		
		//obtem os estados do brasil
		$.ajax({
			type: "GET",
				url: fileXML,
				dataType: "xml",
				
			success: function (data){
				var ufXml = data.getElementsByTagName('estado');
				var total = ufXml.length;					
				var select = $('#cmbEstados');
				for (var i = 0; i<total; i++){
					select.append("<option value='"+ufXml[i].getAttribute('uf')+"' nivel='"+ufXml[i].getAttribute('nivel')+"'>"+ufXml[i].getAttribute('uf')+"</option>");
				}
			},
			
			error: function(){
				alert('Erro na requisição');
			}
		});
		
		inicializaMapa();
	}
	
	function inicializaMapa()
	{	
		
		if (GBrowserIsCompatible()) {

	        var copyrightCollection = new GCopyrightCollection("");
	        copyrightCollection.addCopyright(
	          new GCopyright("",
	          new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)),0,"")
	        );

	 				//Geocode
	        geocoder = new GClientGeocoder();

	        //cria o layer G_NORMAL_MAP
	        var n_tileLayers = [ G_NORMAL_MAP.getTileLayers()[0], new GTileLayer(copyrightCollection , 0, 17)];
	        n_tileLayers[1].getTileUrl = customGetTileURL;
	        n_tileLayers[1].isPng = function() { return false; };
	        n_tileLayers[1].getOpacity = function() { return opacity; };
					
	        var n_customMap = new GMapType(n_tileLayers, new GMercatorProjection(n_tileLayers[0].maxResolution()+1), n_buttonText,
	            {maxResolution:12, minResolution:0, errorMessage:"Data not available"});
	        n_customMap.getMinimumResolution = function(){return 0}
	        n_customMap.getMaximumResolution = function(){return 15}

	        //cria o layer m G_SATELLITE_MAP
	        var s_tileLayers = [ G_SATELLITE_MAP.getTileLayers()[0], new GTileLayer(copyrightCollection , 0, 17)];
	        s_tileLayers[1].getTileUrl = customGetTileURL;
	        s_tileLayers[1].isPng = function() { return false; };
	        s_tileLayers[1].getOpacity = function() { return opacity; };
	        var s_customMap = new GMapType(s_tileLayers, new GMercatorProjection(s_tileLayers[0].maxResolution()+1), s_buttonText,
	            {maxResolution:12, minResolution:0, errorMessage:"Data not available"});
	        s_customMap.getMinimumResolution = function(){return 0}
	        s_customMap.getMaximumResolution = function(){return 15}
	            
	        //cria o layer G_HYBRID_MAP
	        var h_tileLayers = [ G_HYBRID_MAP.getTileLayers()[0], new GTileLayer(copyrightCollection , 0, 17),G_HYBRID_MAP.getTileLayers()[1]];
	        h_tileLayers[1].getTileUrl = customGetTileURL;
	        h_tileLayers[1].isPng = function() { return false; };
	        h_tileLayers[1].getOpacity = function() { return opacity; };
	        var h_customMap = new GMapType(h_tileLayers, new GMercatorProjection(h_tileLayers[0].maxResolution()+1), h_buttonText,
	            {maxResolution:12, minResolution:0, errorMessage:"Data not available"});
	        h_customMap.getMinimumResolution = function(){return 0}
	        h_customMap.getMaximumResolution = function(){return 15}

					map = new GMap2(document.getElementById("map"),{mapTypes:[n_customMap]});
			
					map.addControl(new GMapTypeControl());
			
					map.disableContinuousZoom();
	        map.disableDoubleClickZoom();
	        map.disableDragging();
			
        }
	}
	
	function limparAddress()
	{
		//Limpa o campo endereço
		$('#address').val('');
		$('#address').attr('completo', false);
	}

	function preencherMunicipios()
	{
		
		//Mostra o loading
		$('#spanLoading_Municipio').show();
		
		//Limpa o campo endereço
		limparAddress();
		
		$.ajax({
				type: "GET",
				url: fileXML,
				dataType: "xml",

				success: function(data){

					var ufXml = data.getElementsByTagName('estado');
					var total = ufXml.length;					
					var select = $('#cmbEstados');
					for (var i = 0; i<total; i++){

						if($('#cmbEstados').val()==ufXml[i].getAttribute('uf')){
								var municipioXml = ufXml[i].getElementsByTagName('cidade');
								var municipioTotal = municipioXml.length;	
								var select = $('#cmbMunicipios');
								select.empty();
								for (var m = 0; m<municipioTotal; m++){
									select.append("<option value='"+municipioXml[m].getAttribute('nome')+"' sinal='" + (municipioXml[m].getAttribute('imagem') == 'SIM' ? 0 : 1) +"'>"+municipioXml[m].getAttribute('nome')+"</option>");
								}
						}
					}

				$('#spanLoading_Municipio').hide();
			},
			
			error: function(){
				alert('Erro na requisição');
			}
		});
	}
 	 
	 function limparBarraSugestoes(){
		//Limpa o painel lateral
 	    document.getElementById("painel_lateral").innerHTML = "";
 	    conteudo_div_painel = "";
		
 	    //Recolhe o painel lateral
 	    document.getElementById("painel_lateral").style.width = "0px";
 	    document.getElementById("painel_lateral").style.width = "0px";
 	    document.getElementById("img_af_painel").src = "../sys/img/2010/06/cobertura/a_painel.png";
      document.getElementById("af_painel").style.left = "0px";
		
		fechaPainel();
	 }
	 
	 function controlarInatividade(){
		$('#button_busca').attr('disabled', 'disabled');
		$('#address').attr('disabled', 'disabled');
		setTimeout("$('#button_busca').attr('disabled', '')", 3000);
		setTimeout("$('#address').attr('disabled', '')", 3000);
	 }
	 
 	 // Geocodificação I (procura vinda do menu de busca)
 	 function showAddress1()
	 {
 		fnEscondeBalaoAparelhos();
 		
 		$('.mapContent').show();
		if($.trim($('#cmbEstados').val()) == '0'){
			abrePainel();
			$('#painel_lateral').css({'width':'650px','height':'60px', 'z-index':'100','overflow':'auto','border-bottom':'solid 1px #e4e4e4'});
			$('#painel_lateral').html('<div class="campo_msg">Escolha um <strong>Estado</strong> para consultar a cobertura.</div>');

			//$('#cmbEstado').addClass('onfocus');
			return;
			
		}else if($.trim($('#cmbMunicipios').val()) == '0'){
			abrePainel();
			$('#painel_lateral').css({'width':'650px','height':'60px', 'z-index':'100','overflow':'auto','border-bottom':'solid 1px #e4e4e4'});
			$('#painel_lateral').html('<div class="campo_msg">Escolha um <strong>Munic&iacute;pio</strong> para consultar a cobertura.</div>');
			//$('#cmbCidade').addClass('onfocus');
			
			return;
			
		}else if($.trim($('#address').val()) == ''){
			abrePainel();
			$('#painel_lateral').css({'width':'650px','height':'60px', 'z-index':'100','overflow':'auto','border-bottom':'solid 1px #e4e4e4'});
			$('#painel_lateral').html('<div class="campo_msg">Digite o <strong>Endere&ccedil;o, Bairro ou CEP</strong> para consultar a cobertura.</div>');

			//$('#cmbEstado').addClass('onfocus');
			return;
			
		}

			//Verificando se pode ser chamado o mapa
		 var vImagem = $('#cmbMunicipios').val().split('#')[1];
 		 var vFrequencia = $('#cmbMunicipios').val().split('#')[2];
		 
		if(vFrequencia == '' || vFrequencia == undefined){
			escondeMapa();
			
			if( ti_selecionada == '3g' ){
				
				html = "<div class='campo_msg'>O munic&iacute;pio de <strong>"+ $('#cmbMunicipios option:selected').html() +"</strong> ainda <strong>n&atilde;o possui cobertura 3G</strong>. Para consultar a cobertura GSM/EDGE altere o filtro \"Tecnologia\" logo acima do mapa</div>";
				
			} else {
				
				html = "<div class='campo_msg'>O munic&iacute;pio de <strong>"+ $('#cmbMunicipios option:selected').html() +"</strong> ainda <strong>n&atilde;o possui cobertura GSM/EDGE</strong>.";
				
			}
			
			abrePainel();
			$('#painel_lateral').css({'width':'650px','height':'70px', 'z-index':'100','overflow':'auto'});
			$('#painel_lateral').html(html);
			
			return;
		}else if(vImagem.toUpperCase() == 'NAO'){	
			escondeMapa();
			html  = "<div class='campo_msg'>";						
			
			
			if( ti_selecionada == '3g' ){
				
				html += "O município <strong>"+$('#cmbMunicipios option:selected').html()+"</strong> já <strong>tem cobertura 3G</strong> da Vivo e opera com a frequência de "+vFrequencia+"MHz. Porém, ainda não temos o detalhamento por endereço. Estamos trabalhando para oferecer esta informação.";
				
			} else {
				
				html += "O município <strong>"+$('#cmbMunicipios option:selected').html()+"</strong> já <strong>tem cobertura GSM/EDGE</strong> da Vivo e opera com a frequência de "+vFrequencia+"MHz. Porém, ainda não temos o detalhamento por endereço. Estamos trabalhando para oferecer esta informação.";
				
			}			
			
			html += "</div>";
			
			abrePainel();
			$('#painel_lateral').css({'width':'650px','height':'70px', 'z-index':'100','overflow':'auto'});
			$('#painel_lateral').html(html);
			
			return;
		}else{
			mostraMapa();
		}
		
		//Exibe o loading
		$('#spanLoading_Busca').show();
		
		$('#logoVivo').hide();
		$('#legendaCobertura').show();
		//$('#legendaCobertura').css('visibility','visible');
 	    
		inicializaMapa();
		controlarInatividade();
		
 	    ///////////////////////
		limparBarraSugestoes();
 	    
 	    // Busca o endereço no Google
 	    var address = null;
		
		address = $('#address').val() + " - " + $('#cmbMunicipios').val().split('#')[0] + " - " + $('#cmbEstados').val() + ', Brasil';
		
 	    geocoder.getLocations(address, addAddressToMap);
		$('#div_mapa').focus();

		//-- Mostra balao
		loadFrequencia(vFrequencia);
 	 }
	 
	 function loadFrequencia(freq){
		 $('.balaoConteudo .txtRoxo span').html(vFrequencia);
		 
		 var pTipo = $("#ddl_tipos").val();
		 
		 $.ajax({
		   type: "GET",
		   url: "/paravoce/cobertura/consulta.php?freq=" + freq +'&tipo='+ pTipo,
		   dataType: "text",
		   success: function(data)
		   {
			  $('.balaoConteudo .txtRoxo span').html(freq);
			  $('.balaoScroll div').html(data);
		   }
		});
	 }
	 
	 function fnMostraBalaoAparelhos(){
		$('.balaoAparelhos').show();		
		$('#balaoAparelhos').css({'margin-top:':'100px'});
		if(callCenter){//Verificando se a página é a Call Center
			$('.links').css({'margin-top':'285px'});
		}else{
			$('#btnfrequencia').hide();
			$('.imgModelo').css({'margin-top':'495px'});
			$('#info_3g').css({'width':'340px'});
			$('#info_3g').css({'margin-top':'10px'});
		}
	 }
	 
	 function fnEscondeBalaoAparelhos(){
		$('.balaoAparelhos').hide();
		if(callCenter){//Verificando se a página é a Call Center
			$('.links').css({'margin-top':'15px'});
		}else{
			$('#btnfrequencia').show();
			$('.imgModelo').css({'margin-top':'495px'});
			$('#info_3g').css({'width':'100%'});			
		}
	 }

	//cria o marker no mapa de acordo com o endereço encontrado pelo google
 	 function addAddressToMap(response){
		
		//Preenche o valor do Path de imagem com base na tecnologia.
		pathIMG = 'http://www.vivo.com.br/_cobertura/common/img/png_' + ti_selecionada + '/';
		
		//Define o nível de zoom de acordo com a UF escolhida.
 	    zoom();
		
		//Exibe o loading
		$('#spanLoading_Busca').hide();
		
 	    map.clearOverlays();
		var place = null;
		
 	    if ((!response) || (response.Status.code != 200))
		{
			abrePainel();
			$('#painel_lateral').css({'width':'650px','height':'70px', 'z-index':'100','overflow':'auto'});
			$('#painel_lateral').html("<div class='campo_msg'>Endere&ccedil;o n&atilde;o localizado. <span style='color: #000080; font-size: 10pt; font-family: Arial; cursor:hand; text-decoration: underline;' onclick='exibirAjuda();'>Clique aqui</span> e veja algumas dicas para encontrar o endere&ccedil;o.</div>");

 	    }else{
 	        var painel = document.getElementById("painel_lateral");
 	        var str_cand = "";
			
 	        if (response.Placemark.length == 1 || segunda_busca == true){   /* Caso exista apenas um candidato */
 	            
 	            place = response.Placemark[0];
 	            point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
				
				gotoPoint(place.Point.coordinates[0], place.Point.coordinates[1], place.address, false);

 	        }else{  /* Caso exista mais de um candidato */
 	            // Abre o menu lateral
				abrePainel();
				$('#painel_lateral').css({'width':'650px','height':'150px', 'z-index':'100','overflow':'auto','background':'#fff'});
				
 	            document.getElementById("img_af_painel").src = "../sys/img/2010/06/cobertura/f_painel.png";
              document.getElementById("af_painel").style.left = "300px";
            	
				str_cand = '<p style="color:#000000; font-size:12px;"><strong>Voc&ecirc; quis dizer:</strong></p>';
 	            // Carrega os candidatos no painel lateral
				for (var p=0; p<response.Placemark.length; p++)
				{
					x = response.Placemark[p].Point.coordinates[0];
					y = response.Placemark[p].Point.coordinates[1];
					add = response.Placemark[p].address;
					
					str_cand = str_cand + "<p><span id='sug_end" + p + "' onclick='gotoPoint("+ x+ "," + y + ", \"" + add + "\", true)'>" + add + "</span></p>";
				}

                painel.innerHTML = str_cand;
 	        }
        }
 	 }
	 
	 function LatLongToPoint(y,x)
	 {
		return new GLatLng(y,x);
	 }
	 
	 function gotoPoint(x, y, address, gravaLog)
	 {
		mostraMapa();
		point = new GLatLng(y,x);
		marker = new GMarker(point);
		
		map.addOverlay(marker);
		
		map.setCenter(point, 20);
		
		var html = "";
		
//		if(vFrequencia == '' || vFrequencia == undefined){
//			html = "<div class='campo_msg'>O munic&iacute;pio de <strong>"+ $('#cmbMunicipios option:selected').html() +"</strong> ainda n&atilde;o possui cobertura 3G. Para consultar a cobertura GSM/EDGE altere o filtro \"Tecnologia\" logo acima do mapa</div>";
//			abrePainel();
//			$('#painel_lateral').css({'width':'650px','height':'70px', 'z-index':'100','overflow':'auto'});
//			$('#painel_lateral').html(html);
//			
//		}else if(vImagem.toUpperCase() == 'NAO'){
//			escondeMapa();
//			html  = "<div class='campo_msg'>";
//			html += "<p>O munic&iacute;pio <strong>"+ $('#cmbMunicipios option:selected').html() +" tem cobertura 3G da VIVO</strong>, por&eacute;m ainda n&atilde;o temos o detalhamento por endere&ccedil;o. Estamos trabalhando para oferecer esta informa&ccedil;&atilde;o.</p>";
//			html += "</div>";
//			
//			abrePainel();
//			$('#painel_lateral').css({'width':'650px','height':'120px', 'z-index':'100','overflow':'auto'});
//			$('#painel_lateral').html(html);
//			
//		}else{

			if(callCenter){//Verificando se a página é a Call Center
				vCl = "";
			}else{
				vCl=(ie6 && $.browser.version=='6.0')?' class=\'png_bg info-window\'':'';
			}

			//-- ALTERADO EM REVITALIZAÇÃO 24/06/2010 (MARCUS)
			//html = "<b><div style='font-size:16px;font-family: Arial; width:300px; color:#000000;'>Este &eacute; o endere&ccedil;o que voc&ecirc; est&aacute; procurando? <span style='color:#363636; font-size: 10pt; font-family: Arial; font-weight:normal;'>Se n&atilde;o</span> <span style='color: #000000; font-size: 10pt; font-family: Arial; cursor:hand; text-decoration: underline; font-weight:normal;' onclick='abreDuvidasMapa();'>clique aqui.</span></div></b><div style='margin-top:10px; width:300px;font-size: 14px;font-family: Arial'>" + address + "</div><br /><div class='divFrequencia' onclick='window.location.href=\"/portal/cobertura_frequencia.php\";'>Frequ&ecirc;ncia "+ vFrequencia +" MHz</div>";
			//html = "<div"+vCl+"><div><b style='font-size:16px;font-family: Arial; width:300px; color:#000000;'>Este &eacute; o endere&ccedil;o que voc&ecirc; est&aacute; procurando? <span style='color:#363636; font-size: 10pt; font-family: Arial; font-weight:normal;'>Se n&atilde;o</span> <span style='color: #000000; font-size: 10pt; font-family: Arial; cursor:hand; text-decoration: underline; font-weight:normal;' onclick='abreDuvidasMapa();'>clique aqui.</span></b></div><div style='margin-top:10px; width:300px;font-size: 14px;font-family: Arial'>" + address + "</div><br /><div class='divFrequencia' onclick='fnLightBox(\"lb_frequencia\",\"615\",\"290\",1,\"lightbox_frequencia\");'>Frequ&ecirc;ncia "+ vFrequencia +" MHz</div></div>";
			html = "<div"+vCl+"><p><b style='font-size:16px;font-family: Arial; width:300px; color:#000000;'>Este &eacute; o endere&ccedil;o que voc&ecirc; est&aacute; procurando? <span style='color:#363636; font-size: 10pt; font-family: Arial; font-weight:normal;'>Se n&atilde;o</span> <span style='color: #000000; font-size: 10pt; font-family: Arial; cursor:hand; text-decoration: underline; font-weight:normal;' onclick='abreDuvidasMapa();'>clique aqui.</span></b></p><p style='margin-top:10px; width:300px;font-size: 14px;font-family: Arial'>" + address + "</p><p class='divFrequencia' onclick='fnLightBox(\"lb_frequencia\",\"615\",\"290\",1,\"lightbox_frequencia\");'>Frequ&ecirc;ncia "+ vFrequencia +" MHz</p></div>";

			marker.openInfoWindowHtml(html,{maxWidth:300});
			//Clicar no marker abre a janela.
			GEvent.addListener(marker, "click", function(){
				marker.openInfoWindowHtml(html,{maxWidth:300});
			});
			
			///////////////////////
			limparBarraSugestoes();
			
			// mostra balão de aparelhos
			fnMostraBalaoAparelhos();
		//}
	 }
	 
	 //Define o nível de zoom de acordo com a UF escolhida.
	 function zoom()
	 {
        var maxzoom;
        maxzoom = $('#cmbEstados option:selected').attr('nivel');
		
        var mt = map.getMapTypes();
        for(var i=0; i<mt.length; i++){
            mt[i].getMinimumResolution = function() {return 0;}
            mt[i].getMaximumResolution = function() {return maxzoom;}
        }
	 }
	 
    
    // Abre a janela de Sugestões e Erros
    function contato(){
        window.open('http://pergamo/Cobertura3G_/contato.aspx', '_blank', "height=380; width=340; dialogTop: px; dialogleft: px; center: Yes; help: no; resizable: No; status: No")
    }


function fnOnchange(){
	loadFrequencia(vFrequencia);
}
