var mapa;
var pontos = new Array();
var marcas = new Array();	
var arrayResposta = new Array();
var radarTemporario = '';
var texto = '';
var imagem = '';	
var indiceTemp = '';
var marcaTemp = '';
var marca;
var mantemAzimute = false;
var dadosEdicao = new Array();
var dadosEdicao1 = new Array();
var arraySrc = new Array();

function Encripta(dados){
	var mensx="";
	var l;
	var i;
	var j=0;
	var ch;
	ch = "assbdFbdpdPdpfPdAAdpeoseslsQQEcDDldiVVkadiedkdkLLnm";	
	for (i=0;i<dados.length; i++){
		j++;
		l=(Asc(dados.substr(i,1))+(Asc(ch.substr(j,1))));
		if (j==50){
			j=1;
		}
		if (l>255){
			l-=256;
		}
		mensx+=(Chr(l));
	}
	document.getElementById("1").value=mensx;
}

function Descripta(dados){
	var mensx="";
	var l;
	var i;
	var j=0;
	var ch;
	ch = "assbdFbdpdPdpfPdAAdpeoseslsQQEcDDldiVVkadiedkdkLLnm";	
	for (i=0; i<dados.length;i++){			
		l=( Asc(dados.substr(i,1)) - 3);
		if (j==50){
			j=0;
		}
		j++;
		if (l<0){
			l+=256;
		}
		mensx+=(Chr(l));
	}	
	return mensx;
}

function Asc(String){
	return String.charCodeAt(0);
}

function Chr(AsciiNum){
	return String.fromCharCode(AsciiNum)
}

function buscaEndereco(objeto,evento){
	if (objeto.value != ''){	
		var geocoder = new GClientGeocoder(); 	
		geocoder.setBaseCountryCode('pt_BR');	
		geocoder.getLocations(objeto.value, function (ponto){						
			if (ponto.Placemark){	
				document.getElementById('enderecos').innerHTML = '<a href="#" class="close"><img src="images/balao_close.png" width="24" height="24" border="0" onclick="$(\'#mask\').hide(); $(\'.window\').hide();" /></a>';		
				div = document.getElementById('enderecos'); 	
				if (ponto.Placemark.length > 1){	
					for (i=0;i<ponto.Placemark.length;i++){	
						//alert(ponto.Placemark[i].address);	
						div.innerHTML += '<label style="cursor:pointer;" id="lblSetaCentro'+i+'" onclick="setaCentro('+i+'); $(\'#mask\').hide(); $(\'.window\').hide();">'+ponto.Placemark[i].address+'</label><br/>';	
						pontos[i] = ponto.Placemark[i];	
					}
					document.getElementById('enderecos').style.display = 'block';					
					chamaLightBoxBusca(evento,'endereco');
				} else if (ponto.Placemark.length == 1) {	
					mapa.setCenter(new GLatLng(ponto.Placemark[0].Point.coordinates[1],ponto.Placemark[0].Point.coordinates[0]), 16);	
				}	
			} else {	
				alert('Não foi encontrado nenhum endereço');	
			}										
		});	
	} else {
		alert('Digite algo para buscar');	
	}	
	return false;
}

function chamaLightBoxBusca(e,tipo){
	//evento.preventDefault();		
	if (tipo == 'endereco'){
		var id = '#enderecos';	
	} else if (tipo == 'inclusao') {
		var id = $('a[name=aInclusao]').attr('href');
	} else {
		return false;
	}
	
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();
	$('#mask').css({'width':maskWidth,'height':maskHeight});
	$('#mask').fadeIn(1000);	
	$('#mask').fadeTo("slow",0.8);	
	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();		  
	$(id).css('top',  winH/2-$(id).height()/2);
	$(id).css('left', winW/2-$(id).width()/2);
	$(id).fadeIn(2000);
} 

function setaCentro(indice){			
	mapa.setCenter(new GLatLng(pontos[indice].Point.coordinates[1],pontos[indice].Point.coordinates[0]), 16); 
	document.getElementById('enderecos').setAttribute('style','display:none');			
}

function verificaAzimute(){
	if (document.getElementById('azimute').value === ''){
		alert('Defina a direção do radar clicando no aro da rosa dos ventos de acordo com a rua.');
		return false;
	}
	return true;
}

function criaMarca(ponto, url, caminhoImagem, arrastavel, clicavel, largura, altura, idRadar, indice){	
	if (caminhoImagem == ''){
		var icone = '';
		var marca = new GMarker(ponto , {draggable:arrastavel, clickable:clicavel});
	} else {
		var icone = new GIcon(G_DEFAULT_ICON);
		icone.image = caminhoImagem;
		var marca = new GMarker(ponto, {icon:icone, draggable:arrastavel, clickable:clicavel});
		icone.iconSize = new GSize(largura, altura);
		if (altura == 80){
			icone.iconAnchor = new GPoint(39,39);
			icone.infoWindowAnchor = new GPoint(38,34);
			icone.imageMap = new Array(29,29,50,29,50,50,29,50);
		} else {
			icone.iconAnchor = new GPoint(29,34);
			icone.imageMap = new Array(15,0,38,0,38,34,15,34);
			icone.infoWindowAnchor = new GPoint(29,17);
		}						
	}
	icone.shadow = '';
	marca.enableDragging();
	
	GEvent.addListener(marca, "dragstart", function() {
	  document.getElementById('latitude').value = '';
	  document.getElementById('longitude').value = '';	
	  zeraEndereco();												
	  mapa.closeExtInfoWindow();
	});	
	
	GEvent.addListener(marca, 'click', function(ponto) {														
		mapa.setCenter(new GLatLng(ponto.lat(),ponto.lng()));
		mapa.setZoom(18);
		buscaAtributos(marca, idRadar, indice);
		atualizaEndereco(ponto);										
	});
	
	radarTemporario = marca;	
	
	if (dadosEdicao1.length == 0){
		zeraAtributos();	
	}	
	
	return marca;
} 

function buscaAtributos(marca, idRadar, indice){
	ajax('buscaAtributos.php','?ir='+idRadar+'&i='+indice,'post',exibeAtributos,marca);
}

function exibeAtributos(marca){
	resposta = xmlhttp.responseText;		
	if (resposta != ''){							
		valores = resposta.split(';');	
		indice = valores[0];
		velocidade = valores[1];
		tipo = valores[2];
		usuarioRadar = valores[3];
		azimute = valores[4];
		idRadar = valores[5];
		latitude = valores[6];
		longitude = valores[7];
		logradouro = valores[8];
		referencia = valores[9];
		status = valores[10];
		sentido  = valores[11];
		dataInclusao = valores[12];
		dataAuditoria = valores[13];
		votosPositivos = valores[14];
		if (votosPositivos == ''){
			votosPositivos = 0;
		}
		votosNegativos = valores[15];
		if (votosNegativos == ''){
			votosNegativos = 0;
		}
		incluidoPor = valores[16];
		idRdu = valores[17];
		idTipo = valores[22];
		
		if (idRdu != ''){
			velocidade = valores[18];
			tipo = valores[19];
			azimute = valores[20];
			sentido = valores[21];
			idTipo = valores[23];
			status = 'aguardando liberação';
		}
		
		idStatus = valores[24];
		
		// tratar caracteres especiais no IE
		if (document.getElementById('navegador').value == 'Internet Explorer'){
			logradouro = trataCaracteresEspeciais(logradouro);
			referencia = trataCaracteresEspeciais(referencia);
			status = trataCaracteresEspeciais(status);
		}
		
		url = 'exibicao.php?v='+velocidade+'&t='+tipo+'&vp='+votosPositivos+'&vn='+votosNegativos+'&di='+dataInclusao+'&da='+dataAuditoria+'&l='+logradouro+'&r='+referencia+'&s='+status+'&ir='+idRadar+'&i='+indice+'&sd='+sentido+'&a='+azimute+'&ur='+usuarioRadar+'&lt='+latitude+'&lg='+longitude+'&ip='+incluidoPor+'&it='+idTipo+'&n='+document.getElementById('navegador').value+'&is='+idStatus;
		
		marca.openExtInfoWindow(
			mapa,
			"balao_window",
			"<p>Carregando...</p><br><p><img src='images/ajax-loader.gif' width='16' height='16' /></p>",
			{beakOffset: 1, ajaxUrl: url, ajaxCallback: respostaJanela}
		);		  
	}	
}

function zeraAtributos(){
	document.getElementById('hiddenSentidoDuplo').value = 0;
	document.getElementById('velocidade').value = '';
	document.getElementById('tipo').value = '';
	document.getElementById('hiddenComentario').value = '';
	document.getElementById('azimute').value = '';
	document.getElementById('hiddenIdRadar').value = '';
	document.getElementById('hiddenIndice').value = '';
	document.getElementById('logradouro').value = '';
}

function cadastrarMarca(){				
	if (document.getElementById('tipo').value == ''){
		alert('Escolha o tipo do radar.');
		return false;	
	}
	velocidade = document.getElementById('velocidade').value
	if ( (document.getElementById('tipo').value != '2') && (velocidade == '') ){
		alert('Velocidade obrigatória.');
		return false;
	}	
	if ( (document.getElementById('tipo').value != '2') && (velocidade < 30) || (velocidade > 120) || (velocidade % 10 != 0)){
		alert('Velocidade inválida');
		return false;
	}
	//document.getElementById('endereco').value = document.getElementById('enderecoAux').value;	
	
	document.getElementById('frm').action = 'cadastrarRadar.php';
	setaZoom();
	document.getElementById('frm').submit();
}

function cancelarMarca(){	
	document.getElementById('zoom').value = mapa.getZoom();
	mapa.closeExtInfoWindow();
	mapa.removeOverlay(marca);
}

function zeraEndereco(){		
	document.getElementById('estado').value = '';
	document.getElementById('cidade').value = '';
	document.getElementById('logradouro').value = '';
	document.getElementById('bairro').value = '';
	document.getElementById('cep').value = '';
}

function verificaValorAzimute(valor){	
	if (document.getElementById('sentidoDuplo').checked == true){
		if (valor > 180){
			valor = 5;
		} else if (valor < 0){
			valor = 165;
		}
	} else {
		if (valor > 360){
				valor = 5;
		} else if (valor < 0){
			valor = 345;
		}
	}
	
	return valor;
}

function retornaNos(){
	//percorre os nós da div mapa para manipulação das imagens
	div1 = document.getElementById('mapa').childNodes[0];
	div2 = div1.childNodes[0];		

	// esconde sombra da marca
	/*div = div2.childNodes[4];		
	nosDiv = div.childNodes;		
		 	
	imagem = nosDiv[indice];		
	imagem.style.display = 'none';*/

	// esconde a marca
	div = div2.childNodes[6];		
	nosDiv = div.childNodes;
	
	return nosDiv;
	
}

function calculaIndice(indice){
	nosDiv = retornaNos();
	if (indice === ''){
		if (navigator.appName.indexOf('Internet Explorer') > 0){
			indice = nosDiv.length - 2;
		} else {
			indice = nosDiv.length - 1;
		}						
	} else {
		if (navigator.appName.indexOf('Internet Explorer') > 0){
			indice = indice * 2;
		} 
	}
	return indice;
}

function setaImagem(valor, indice, sentidoDuplo){	
	if (valor == ''){
		valor = 0;
	}		
	
	indice = calculaIndice(indice);
	
	imagem = retornaNos()[indice];				
	
	if (sentidoDuplo){
		while (valor >= 180){
			valor = valor - 180;
		}
	} else {
		while (valor >= 360){
			valor = valor - 360;
		}
	}
	
	document.getElementById('azimute').value = valor;
	
	//imagem.style.display = 'none';
	resto = valor % 5;
	if (resto != 0){
		if (resto < 3){
			valor = valor - resto;			
		} else {
			valor = (1+Math.floor(valor/5))*5;
			if (sentidoDuplo){
				if (valor == 180){
					valor = 0;
				}
			} else {
				if (valor == 360){
					valor = 0;
				}
			}							
		}
	} else {
		valor = parseFloat(valor).toFixed(0);
	}	
	
	// seta a figura azimute na marca		
	if (sentidoDuplo){		
		src = 'images/bussola/duplo_'+valor+'.png';	
		document.getElementById('hiddenSentidoDuplo').value = 1;
	} else {
		src = 'images/bussola/simples_'+valor+'.png';
		document.getElementById('hiddenSentidoDuplo').value = 0;
	}		
	
	if (document.getElementById('imgAzimute')){
		document.getElementById('imgAzimute').src = src;
	}
	
	if (document.getElementById('flagExibicao')){		
		src = src;
	} else {
		imagem.src = src;
	}
	
	return src; 
}	 

function setaInverso(){
	azimute = parseFloat(document.getElementById('azimute').value);
	if (azimute < 180){
		azimute += 180;
	} else {
		azimute -= 180;
	}	
	setaImagem(azimute,'',document.getElementById('sentidoDuplo').checked);
}

function exibeInverso(sentidoDuplo){
	if (sentidoDuplo){
		document.getElementById('pSentidoInverso').innerHTML = '&nbsp;';		
	} else {
		document.getElementById('pSentidoInverso').innerHTML = '<input type="checkbox" name="sentidoInverso" id="sentidoInverso" onclick="setaInverso();" value="1" /><span class="titulo7">&nbsp;Sentido Inverso</span>';
	}
}

function atualizaEndereco(latlng){
	geocoder = new GClientGeocoder();	
	if (latlng != null) {
		address = latlng;
		geocoder.getLocations(latlng, mostraEndereco);
	}	
}

function getEndereco(ponto) {		
	if (mapa.getZoom() < 17){
		return false;
	}
	geocoder = new GClientGeocoder();	
	if (ponto != null) {
		latlng = mapa.fromContainerPixelToLatLng(ponto);	
		address = latlng;
		geocoder.getLocations(latlng, mostraEndereco);
	}			
}

function mostraEndereco(response) {			  
	if (!response || response.Status.code != 200) {
		alert("Erro ao buscar endereço. Marque novamente o radar");
		cancelarMarca();
	} else {		
		zeraEndereco();
		place = response.Placemark[0];					
		document.getElementById('enderecoCompleto').value = place.address;			
		if (document.getElementById('lblEnderecoCompleto')){
			document.getElementById('lblEnderecoCompleto').innerHTML = place.address;
		}		
		try{				
			document.getElementById('estado').value = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
		} catch (e){
			document.getElementById('estado').value = '';
		}
		try{				
			document.getElementById('cidade').value =  place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
		} catch (e){
			document.getElementById('cidade').value = '';
		}			
		try{				
			document.getElementById('bairro').value =  place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName;
			try{				
				document.getElementById('logradouro').value =  place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
			} catch (e){
				document.getElementById('logradouro').value = '';
			}									
			try{				
				document.getElementById('cep').value =  place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber;
			} catch (e){
				document.getElementById('cep').value = '';
			}
		} catch (e){
			document.getElementById('bairro').value = '';
			try{				
				document.getElementById('logradouro').value =  place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
			} catch (e){
				document.getElementById('logradouro').value = '';
			}
			try{				
				document.getElementById('cep').value =  place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
			} catch (e){
				document.getElementById('cep').value = '';
			}
		}
		logradouro = document.getElementById('logradouro');
		if (logradouro.value.indexOf(',') != -1){
			logradouro.value = logradouro.value.substr(0,logradouro.value.indexOf(','));
		}
	}
}

function validaLogin(){
	if (document.getElementById('emailLogin').value == ''){
		alert('Preencha o campo e-mail');
		return false;
	}
	if (document.getElementById('senhaLogin').value == ''){
		alert('Preencha o campo senha');
		return false;
	}
	setaZoom();
	document.getElementById('centroLogar').value = mapa.getCenter();
	return true;
}

function buscaRadar(exibeLightbox){		
	if (exibeLightbox){
		if (document.getElementById('emitirMensagem').value == 'Sim'){
			chamaLightbox('','mensagemConfirmacao');
		}	
	}	
	coordenadas = mapa.getCenter();	
	latitude = coordenadas.lat();
	longitude = coordenadas.lng();		
	ajax('buscaRadar.php','?latitudeCentro='+latitude+'&longitudeCentro='+longitude,'post',exibeMarcas,'');		
}

function exibeMarcas(){	
	resposta = xmlhttp.responseText;		
	if (resposta != ''){
		arrayResposta = new Array();
		mapa.clearOverlays();				
		//resposta = resposta.replace(/^\s+|\s+$/g,"");
		arrayResposta = resposta.split('#');
		marcas = new Array();		
		for (i=0;i<arrayResposta.length-1;i++){
			//pega os valores retornados do banco - pagina buscaRadar.php
			valores = arrayResposta[i].split(';');			
			idRadar = valores[0]; //$linha['idRadar']
			velocidade = valores[1]; //$linha['velocidade']									
			latitude = valores[2]; //$linha['latitude']
			longitude = valores[3]; //$linha['longitude']			
			idTipo = valores[4];
			idStatus = valores[5];			
			idRdu = valores[6];	
			
			if (idRdu != ''){				
				velocidade = valores[7];				
				idTipo = valores[8];
				inexistente = valores[9];							
				latitude = valores[10];
				longitude = valores[11];
				
				if (inexistente == 1){
					if (idTipo != '2' && idTipo != '3'){
						icone = 'images/iconesexcluidos/radarexcluido.png';					
					} else {
						icone = 'images/iconesexcluidos/semaforoexcluido.png';
					}					
				} else {					
					switch(idTipo){
						case '2':
							icone = 'images/iconesincluidos/semaforoincl.png';
							break;
						case '3':
							icone = 'images/iconesincluidos/semaforoincl'+velocidade+'.png';
							break;
						case '10':
							icone = 'images/iconesincluidos/policia.png';
							break;
						case '6':
							icone = 'images/iconesincluidos/pistaseletiva.png';
							break;
						default:
							icone = 'images/iconesincluidos/radarincl'+velocidade+'.png';
							break;
					}
				}			
			} else {
				switch(idStatus){
					case '1':								
						switch(idTipo){
							case '2':
								icone = 'images/iconesincluidos/semaforoincl.png';
								break;
							case '3':
								icone = 'images/iconesincluidos/semaforoincl'+velocidade+'.png';
								break;
							case '10':
								icone = 'images/iconesincluidos/policia.png';
								break;
							case '6':
								icone = 'images/iconesincluidos/pistaseletiva.png';
								break;
							default:
								icone = 'images/iconesincluidos/radarincl'+velocidade+'.png';
								break;
						}
						break;
					case '2':														
						switch(idTipo){
							case '2':
								icone = 'images/iconesverificados/semaforoverif.png';
								break;
							case '3':
								icone = 'images/iconesverificados/semaforoverif'+velocidade+'.png';
								break;
							case '10':
								icone = 'images/iconesverificados/policia.png';
								break;
							case '6':
								icone = 'images/iconesverificados/pistaseletiva.png';
								break;
							default:
								icone = 'images/iconesverificados/radarverif'+velocidade+'.png';
								break;
						}
						break;
					case '4':										
						switch(idTipo){
							case '2':
								icone = 'images/iconesauditados/semaforoaud.png';
								break;
							case '3':
								icone = 'images/iconesauditados/semaforoaud'+velocidade+'.png';
								break;
							case '10':
								icone = 'images/iconesauditados/policia.png';
								break;
							case '6':
								icone = 'images/iconesauditados/pistaseletiva.png';
								break;
							default:
								icone = 'images/iconesauditados/radaraud'+velocidade+'.png';
								break;
						}
						
						break;
				}	
			}		
			
			arraySrc[i] = icone;
			
			var point = new GPoint (longitude, latitude);									
				
			marca = criaMarca(point, '', icone, false, true, 58, 34, idRadar, i);			
			marcas[i] = marca;	
			mapa.addOverlay(marcas[i]);					
			
		}				
		radarTemporario = '';
		document.getElementById('latitudeCentro').value = mapa.getCenter().lat();
		document.getElementById('longitudeCentro').value = mapa.getCenter().lng();	
		
		chamaEdicao();			
	}
}

function chamaEdicao(){		
	if (document.getElementById('dadosEdicao').value != ''){
		dadosEdicao1 = document.getElementById('dadosEdicao').value;
		dadosEdicao1 = dadosEdicao1.split(';');			
		indice = retornaIndice(dadosEdicao1[0]);					
		
		indiceTemp = indice;
		
		valores = arrayResposta[indiceTemp].split(';');		
		
		indice = calculaIndice(indice);	
		imagem = retornaNos()[indice];					
		
		document.getElementById('velocidade').value = dadosEdicao1[1];
		document.getElementById('tipo').value = dadosEdicao1[2];
		document.getElementById('azimute').value = dadosEdicao1[3];		
		document.getElementById('hiddenSentidoDuplo').value = dadosEdicao1[4];
		
		usuarioRadar = dadosEdicao1[7];				
		votosPositivos = dadosEdicao1[8];		
		votosNegativos = dadosEdicao1[9];
		
		if ( (usuarioRadar == document.getElementById('idUsuarioLogado').value) && (votosPositivos == 0) && (votosNegativos == 0) && (usuarioRadar != '') ){			
			document.getElementById('hiddenIdRadar').value = dadosEdicao1[0];	
			document.getElementById('hiddenIndice').value = indiceTemp;			
			document.getElementById('latitude').value = dadosEdicao1[5];
			document.getElementById('longitude').value = dadosEdicao1[6];			
			marcas[indiceTemp].openExtInfoWindow(mapa, 'balao_window', "<p>Carregando...</p><br><p><img src='images/ajax-loader.gif' width='16' height='16' /></p>",{beakOffset: 1, ajaxUrl: 'cadradar1.php?i='+indiceTemp+'&ir='+dadosEdicao1[0], ajaxCallback: respostaJanela});
		} else {
			marcas[indiceTemp].openExtInfoWindow(mapa, 'balao_window', "<p>Carregando...</p><br><p><img src='images/ajax-loader.gif' width='16' height='16' /></p>",{beakOffset: 1, ajaxUrl: 'editaradar1.php?i='+indiceTemp+'&ir='+dadosEdicao1[0], ajaxCallback: respostaJanela});	
		}		
	}
}

function verificaBuscaRadar(){
	if (mapa.getZoom() < 14){
		return false;
	}	
	latitudeCentro = document.getElementById('latitudeCentro').value;
	longitudeCentro = document.getElementById('longitudeCentro').value;
	
	//Codigo usado para buscar as coordenadas dos extremos do mapa
	/*retangulo = mapa.getBounds();
	coordenadas = retangulo.getSouthWest();
	latitudeOesteRetangulo = coordenadas.lat();
	longitudeSulRetangulo = coordenadas.lng();
	coordenadas = retangulo.getNorthEast();
	latitudeLesteRetangulo = coordenadas.lat();
	longitudeNorteRetangulo = coordenadas.lng();
	difLatitude = latitudeLesteRetangulo - latitudeOesteRetangulo;
	difLongitude = longitudeNorteRetangulo - longitudeSulRetangulo;
	*/
	//Diferença entre os extremos do mapa no monitor com maior resolução
	difLatitude = 0.04720920564661668;
	difLongitude = 0.16333580017089844;		
	
	if ( (parseFloat(mapa.getCenter().lat()) < (parseFloat(latitudeCentro) - parseFloat(difLatitude))) || (parseFloat(mapa.getCenter().lat()) > (parseFloat(latitudeCentro) + parseFloat(difLatitude))) || (parseFloat(mapa.getCenter().lng()) < (parseFloat(longitudeCentro) - parseFloat(difLongitude))) || (parseFloat(mapa.getCenter().lng()) > (parseFloat(longitudeCentro) + parseFloat(difLongitude)))  ){		
		buscaRadar(false);		
	}
}

function confirmaRadar(){
	document.getElementById('frm').action = 'votar.php';
	document.getElementById('latitude').value = '';
	document.getElementById('longitude').value = '';
	document.getElementById('tipo').value = '';
	document.getElementById('velocidade').value = '';
	document.getElementById('azimute').value = '';
	document.getElementById('hiddenSentidoDuplo').value = '';
	document.getElementById('hiddenComentario').value = '';
	setaZoom();
	document.getElementById('frm').submit();
}


function respostaJanela(){
	if (document.getElementById('lblEnderecoCompleto')){
		document.getElementById('lblEnderecoCompleto').innerHTML = document.getElementById('enderecoCompleto').value;
	}	
	azimute = document.getElementById('azimute').value;
	if (azimute != ''){		
		if (document.getElementById('imgAzimute')){
			if (document.getElementById('indice')){
				indice = document.getElementById('indice').value;
			} else {
				indice = '';
			}			
			
			if (document.getElementById('hiddenSentidoDuplo').value == 1){
				sentido = true;
			} else {
				sentido = false;
			}					
			setaImagem(azimute,indice,sentido);
		}
	}	
	if (document.getElementById('imgTopo')){
		velocidade = document.getElementById('velocidade').value;
		if (velocidade != '' && velocidade != 0){
			setaImagemVelocidade(velocidade);	
		}
		tipo = document.getElementById('tipo').value;
		if (tipo != ''){
			setaImagemTipo(tipo);	
		}	
	}
	comentario = document.getElementById('hiddenComentario').value;
	if (document.getElementById('comentario')){
		if (comentario != ''){
			document.getElementById('comentario').value = comentario;	
		}
	}
	
	if (document.getElementById('flagExibicao')){		
		//mapa.setZoom(18);
		indice = document.getElementById('indice').value;	
		indiceTemp = indice;					
		if (document.getElementById('hiddenSentido').value == 1){
			sentido = true;				
		} else {
			sentido = false;
		}	
		if (radarTemporario != ''){
			mapa.removeOverlay(radarTemporario);
		}
		marcaTemp = criaMarca(marcas[indice].getLatLng(), '', setaImagem(document.getElementById('hiddenAzimute').value,indice,sentido), false, false, 80, 80, '','');
		marcas[indice].hide(); 
		mapa.addOverlay(marcaTemp);				
		dadosEdicao = new Array();
		document.getElementById('hiddenSentidoDuplo').value = document.getElementById('hiddenSentido').value;
		dadosEdicao['sentidoDuplo'] = document.getElementById('hiddenSentido').value;			
		document.getElementById('velocidade').value = document.getElementById('hiddenVelocidade').value;
		dadosEdicao['velocidade'] = document.getElementById('hiddenVelocidade').value;
		document.getElementById('tipo').value = document.getElementById('hiddenTipo').value;
		dadosEdicao['tipo'] = document.getElementById('hiddenTipo').value;
		document.getElementById('hiddenComentario').value = document.getElementById('hiddenReferencia').value;		
		document.getElementById('azimute').value = document.getElementById('hiddenAzimute').value;		
		dadosEdicao['azimute'] = document.getElementById('hiddenAzimute').value;	
		document.getElementById('logradouro').value = document.getElementById('hiddenLogradouro').value;		
	}	
	
	if (document.getElementById('flagVoto')){
		if (document.getElementById('pSentidoInverso')){
			if (document.getElementById('hiddenSentidoDuplo').value == 1){		
				exibeInverso(true);
				document.getElementById('pSentidoInverso').innerHTML = '&nbsp';							
				document.getElementById('sentidoDuplo').style.display = 'block';
				document.getElementById('spanSentidoDuplo').style.display = 'block';
				document.getElementById('sentidoDuplo').checked = true;				
			} else {				
				exibeInverso(false);
				document.getElementById('sentidoSimples').checked = true;
			}
		}
	}
	if (document.getElementById('lblOperacao')){
		if (document.getElementById('hiddenIdRadar').value != ''){
			document.getElementById('lblOperacao').innerHTML = 'EDITAR';
		}	
	}
	
	if (dadosEdicao1.length != 0){	
		if (document.getElementById('indice')){
			indice = document.getElementById('indice').value;	
			indiceTemp = indice;	
		}		
		
		if (radarTemporario != ''){
			mapa.removeOverlay(radarTemporario);
		}				
		
		if (document.getElementById('hiddenSentidoDuplo').value == 1){
			sentido = true;
		} else {
			sentido = false;
		}
		
		marcaTemp = criaMarca(marcas[indiceTemp].getLatLng(), '', setaImagem(document.getElementById('azimute').value,indice,sentido), false, false, 80, 80, '', '');
		
		marcas[indiceTemp].hide(); 
		
		mapa.addOverlay(marcaTemp);		
	}
	
	dadosEdicao1 = new Array();		
} 

function chamaPasso(passo, indice){
	texto = '';
	parametros = '';
	azimute = document.getElementById('azimute').value;
	sentidoDuplo = document.getElementById('hiddenSentidoDuplo').value;
	tipo = document.getElementById('tipo').value;
	velocidade = document.getElementById('velocidade').value;
	comentario = document.getElementById('hiddenComentario').value;
	if (document.getElementById('idRadar')){
		idRadar = document.getElementById('idRadar').value;
	}
	
	if (azimute != ''){
		if (parametros == ''){
			parametros = '?azimute='+azimute;
		}
	}
	if (sentidoDuplo == '1'){
		if (parametros == ''){
			parametros = '?sentidoDuplo=1';
		} else {
			parametros += '&sentidoDuplo=1';
		}
	}
	if (tipo != ''){
		if (parametros == ''){
			parametros = '?tipo='+tipo;
		} else {
			parametros += '&tipo='+tipo;
		}
	}
	if (velocidade != ''){
		if (parametros == ''){
			parametros = '?velocidade='+velocidade;
		} else {
			parametros += '&velocidade='+velocidade;
		}
	}
	if (comentario != ''){
		if (parametros == ''){
			parametros = '?comentario='+comentario;
		} else {
			parametros += '&comentario='+comentario;
		}
	}
	mantemAzimute = false;
	switch(passo){	
		case 1:						
			url = 'cadradar1.php'+parametros;
			if (document.getElementById('hiddenIdRadar').value != ''){
				indice = document.getElementById('hiddenIndice').value;
			}
			mantemAzimute = true;
			break;
		case 2:
			url = 'cadradar2.html'+parametros;
			if (document.getElementById('hiddenIdRadar').value != ''){
				indice = document.getElementById('hiddenIndice').value;
			}
			mantemAzimute = true;
			break;
		case 3:
			url = 'cadradar3.html'+parametros;
			if (document.getElementById('hiddenIdRadar').value != ''){
				indice = document.getElementById('hiddenIndice').value;
			}
			mantemAzimute = true;
			break;
		case 4:
			url = 'editaradar1.php?i='+indice+'&ir='+idRadar;
			mantemAzimute = true;
			break;
		case 5:
			url = 'editaradar2.php?i='+indice+'&ir='+idRadar;
			mantemAzimute = true;
			break;
	}
	
	if (indice !== ''){
		marcas[indice].openExtInfoWindow(mapa, 'balao_window', "<p>Carregando...</p><br><p><img src='images/ajax-loader.gif' width='16' height='16' /></p>",{beakOffset: 1, ajaxUrl: url, ajaxCallback: respostaJanela});			
	} else {
		marca.openExtInfoWindow(mapa, 'balao_window', "<p>Carregando...</p><br><p><img src='images/ajax-loader.gif' width='16' height='16' /></p>",{beakOffset: 1, ajaxUrl: url, ajaxCallback: respostaJanela});
	}	
	
}

function setaImagemVelocidade(velocidade){
	for (i=3; i<=12; i++){		
		document.getElementById('cadvel'+i*10).src = 'images/cadvel'+i*10+'_up.jpg';			
	}
	if (document.getElementById('tipo').value == '2'){
		setaImagemTipo('3');
	}
	document.getElementById('velocidade').value = velocidade;
	document.getElementById('cadvel'+velocidade).src = 'images/cadvel'+velocidade+'_down.jpg';
} 

function setaImagemTipo(tipo){
	switch(tipo){
		case '0':
			zeraTipos();
			document.getElementById('fixo').src = 'images/cadtipofixo_down.jpg';	
			break;
		case '4':
			zeraTipos();
			document.getElementById('tunel').src = 'images/cadtipotunel_down.jpg';
			break;
		case '1':
			zeraTipos();	
			document.getElementById('movel').src = 'images/cadtipomovel_down.jpg';	
			break;
		case '2':
			zeraTipos();
			for (i=3; i<=12; i++){		
				document.getElementById('cadvel'+i*10).src = 'images/cadvel'+i*10+'_up.jpg';			
			}
			document.getElementById('semaforo').src = 'images/cadtiposemaforo_down.jpg';
			document.getElementById('velocidade').value = '';
			break;
		case '3':
			zeraTipos();			
			document.getElementById('semafvel').src = 'images/cadtiposemafvel_down.jpg';	
			break;		
		case '5':
			zeraTipos();			
			document.getElementById('outros').src = 'images/cadtipooutros_down.jpg';
			break;		
	}	
	document.getElementById('tipo').value = tipo;
} 

function zeraTipos(){
	document.getElementById('fixo').src = 'images/cadtipofixo_up.jpg';
	document.getElementById('tunel').src = 'images/cadtipotunel_up.jpg';
	document.getElementById('movel').src = 'images/cadtipomovel_up.jpg';
	document.getElementById('semaforo').src = 'images/cadtiposemaforo_up.jpg';
	document.getElementById('semafvel').src = 'images/cadtiposemafvel_up.jpg';
	document.getElementById('outros').src = 'images/cadtipooutros_up.jpg';
}

function setaCometario(valor){
	document.getElementById('hiddenComentario').value = valor;
}

function verificaHabilitacao(usuarioRadar,usuarioVotou){		
	usuarioLogado = document.getElementById('idUsuarioLogado').value;
	if (usuarioLogado == ''){
		return 'disabled';
	}
	if (usuarioRadar == usuarioLogado){
		return 'disabled';
	}
	if (usuarioVotou == usuarioLogado){
		return 'disabled';
	}
	return '';						
}

function confereLogin(){
	usuarioLogado = document.getElementById('idUsuarioLogado').value;
	if (usuarioLogado == ''){
		alert('Para votar o usuário deve estar logado');
		chamaLightbox('','login');
		cancelarMarca();
		return false;
	}			
	return true;
} 

function confereVoto(){	
	if ( (document.getElementById('velocidade').value == dadosEdicao['velocidade']) && (document.getElementById('azimute').value == dadosEdicao['azimute']) && (document.getElementById('tipo').value == dadosEdicao['tipo']) && (document.getElementById('hiddenSentidoDuplo').value == dadosEdicao['sentidoDuplo']) ){
		alert('Nenhum campo modificado. Para votar e necessario alterar pelo menos um campo.');
	} else {	
		votaMarca();			
	}
}

function votaMarca(){
	if (document.getElementById('tipo').value == 'semafvel'){
		document.getElementById('tipo').value = 'semaforo';
	}
	document.getElementById('frm').action = 'votar.php';	
	setaZoom();
	document.getElementById('frm').submit();
}

function setaZoom(){
	document.getElementById('zoom').value = mapa.getZoom();
	document.getElementById('zoomLogar').value = mapa.getZoom();
	document.getElementById('zoomBox').value = mapa.getZoom();
}

function zeraAzimute(indice){
	valor = document.getElementById('azimute').value;		
	setaImagem(valor,indice);
}

function gravaCentro(centro){
	if (document.getElementById('tipoMapa')){
		var tipoMapa = document.getElementById('tipoMapa').value;		
	} else {
		var tipoMapa = '';
	}
	switch(tipoMapa){
		case 'Mapa':
			tm = 0;
			break;
		case 'Satélite':
			tm = 1;
			break;
		case 'Híbrido':
			tm = 2;
			break;
		default:
			tm = 0;
			break;
	}	
	ajax("gravaCentro.php",'?centro='+centro+'&tm='+tm,'post','','');	
}


function confereInclusao(velocidade , azimute, tipo, logradouro, usuarioVotou, usuarioRadar){		
	if (logradouro == document.getElementById('logradouro').value){		
		if ( (document.getElementById('azimute').value > parseFloat(azimute)+15) || (document.getElementById('azimute').value < parseFloat(azimute)-15)){
			cadastrarMarca();	
		} else {
			if ( (usuarioVotou == document.getElementById('idUsuarioLogado').value) || (usuarioRadar == document.getElementById('idUsuarioLogado').value)  ){
				alert('Voto já cadastrado');
				mapa.closeExtInfoWindow();
				mapa.removeOverlay(radarTemporario);
			} else {
				votaMarca();
			}
		}				
	} else {
		cadastrarMarca();
	}
}

function carregaMapa() {	
	document.getElementById('navegador').value = navigator.appName;
	if (GBrowserIsCompatible()) {		
		mapa = new GMap2(document.getElementById("mapa"));			
		var zoom = document.getElementById('zoom').value;	
		if (zoom == ''){
			zoom = 14;
		}
		if (document.getElementById('centro').value == ''){
			mapa.setCenter(new GLatLng(-23.5489433, -46.6388182), parseInt(zoom));							
		} else {
			var centro = document.getElementById('centro').value;						
			posicao = centro.indexOf(',');
			if (isNaN(centro.substr(0,posicao - 1)) == false && isNaN(centro.substr(posicao+1,centro.length - posicao + 1)) == false){
				mapa.setCenter(new GLatLng(centro.substr(0,posicao - 1), centro.substr(posicao+1,centro.length - posicao + 1)), parseInt(zoom));
			} else {
				mapa.setCenter(new GLatLng(-23.5489433, -46.6388182), parseInt(zoom));
			}							
		}		
		if (zoom >= 14){
			buscaRadar(true);
		}
		mapa.addControl(new GMapTypeControl());
		mapa.addControl(new GScaleControl());
		mapa.addControl(new GOverviewMapControl()); 
		mapa.addControl(new GLargeMapControl()); 
		
		var tipoMapa = document.getElementById('tipoMapa').value;
	
		switch(tipoMapa){
			case 'Mapa':
				mapa.setMapType(G_NORMAL_MAP);
				break;
			case 'Satélite':
				mapa.setMapType(G_SATELLITE_MAP);
				break;
			case 'Híbrido':
				mapa.setMapType(G_HYBRID_MAP );
				break;
			default:
				mapa.setMapType(G_NORMAL_MAP);
				break;
			
		}
		
		mapa.enableScrollWheelZoom();	
		
		setaTipoMapa();
		
		GEvent.addListener(mapa, "singlerightclick", getEndereco);							

		GEvent.addListener(mapa, "singlerightclick", function (ponto, src, overlay){						
			if (overlay){
				return false;
			}
			if (ponto){																					
				if (document.getElementById('logado').value == 'Sim'){	
					posicaoPonto = mapa.fromContainerPixelToLatLng(ponto);
					if (mapa.getZoom() < 17){
						mapa.setCenter(new GLatLng(posicaoPonto.lat(),posicaoPonto.lng()), 17);	
						return false;
					} else {
						mapa.setCenter(new GLatLng(posicaoPonto.lat(),posicaoPonto.lng()));
					}																									
					
					menorDistancia = 51;
					indiceDistancia = '';
					for (i=0;i<marcas.length;i++){														
						posicaoMarca = new GLatLng(marcas[i].getLatLng().lat(),marcas[i].getLatLng().lng());							
						if ( (posicaoPonto.distanceFrom(posicaoMarca) <= 50) && (posicaoPonto.distanceFrom(posicaoMarca) < menorDistancia) ){								
							menorDistancia = posicaoPonto.distanceFrom(posicaoMarca);
							indiceDistancia = i;								
						}											
					}					
					if (radarTemporario != ''){
						mapa.removeOverlay(radarTemporario);
					}
					document.getElementById('latitude').value = posicaoPonto.lat();
					document.getElementById('longitude').value = posicaoPonto.lng();
					if (indiceDistancia !== ''){																					
						marca = criaMarca(posicaoPonto, 'cadradar1.php', 'images/bussola/simples_0.png', true, true, 80, 80, '', '');	
						mapa.addOverlay(marca);						
						dados = arrayResposta[indiceDistancia].split(';');
						preencheRadarProximo(dados[0]);											
					} else {
						marca = criaMarca(posicaoPonto, 'cadradar1.php', 'images/bussola/simples_0.png', true, true, 80, 80, '', '');
						mapa.addOverlay(marca); 							
						chamaPasso(1,'');
					}							
				} else {
					alert('Para cadastrar um radar você deve estar logado..');
					chamaLightbox('','login');
				}				
			}
		});				
	}
	
	GEvent.addListener(mapa, "extinfowindowopen", function (){		
		mantemAzimute = false;		
	});
	
	GEvent.addListener(mapa, "extinfowindowclose", function (){				
		if (marcaTemp != ''){			
			if (mantemAzimute != true){				
				mapa.removeOverlay(marcaTemp);								
				marcas[indiceTemp].show();
				indice = calculaIndice(indiceTemp);
				imagem = retornaNos()[indice];				
				imagem.src = arraySrc[indiceTemp];					
				marcaTemp = '';
				indiceTemp = '';				
				imagem = '';
			}	
		} else {	
			if (mantemAzimute != true){				
				mapa.removeOverlay(marca);								
			}			
		}		
	});

	GEvent.addListener(mapa, "zoomend", function (antigoZoom, novoZoom){
		//setaLinkDados();
		setaZoom();
		if(antigoZoom < 14 && novoZoom >= 14){
			buscaRadar(false);
		} else if (antigoZoom >= 14 && novoZoom < 14){				
			mapa.clearOverlays();
		}
	});
	
	GEvent.addListener(mapa, "maptypechanged", setaTipoMapa); 

	GEvent.addListener(mapa, "moveend", verificaBuscaRadar);		
	
	GEvent.addDomListener(mapa, 'extinfowindowupdate',function(){
		if (document.getElementById("flagExibicao")){
			var windowContent = document.getElementById("balao_window_contents");
			var tabs = new Array(document.getElementById("tab0"),document.getElementById("tab1"));
			if( tabs.length > 0 ){
				var tabContentsArray = new Array(tabs.length);
				for( i=0; i < tabs.length; i++){
					tabContentsArray[i] = document.getElementById("tab"+i+"_content");
					if( i > 0){
						hide(tabContentsArray[i]);
					}
					tabs[i].setAttribute("name", i.toString());
			
					GEvent.addDomListener(tabs[i],"click",function(){
						var tabIndex = this.getAttribute("name");
			
						for(tabContentIndex=0; tabContentIndex < tabs.length; tabContentIndex++){
							if( tabContentIndex == tabIndex ){
								show(tabContentsArray[tabContentIndex]);
							}else{
								hide(tabContentsArray[tabContentIndex]);
							}
						}
						mapa.getExtInfoWindow().resize();
			
					});
				}
			}	
		}		
	});
	
}

function preencheRadarProximo(idRadar){
	ajax('buscaAtributos.php','?ir='+idRadar,'post',exibeRadarProximo,'');
}

function exibeRadarProximo(){
	resposta = xmlhttp.responseText;
	if (resposta != ''){
		valores = resposta.split(';');
		velocidade = valores[1];								
		azimute = valores[4];								
		referencia = '';								
		sentido  = valores[11];								
		idRdu = valores[17];
		tipo = valores[22];
		
		if (idRdu != ''){
			velocidade = valores[18];									
			azimute = valores[20];
			sentido = valores[21];
			tipo = valores[23];
		}
		
		document.getElementById('velocidade').value = velocidade;						
		document.getElementById('tipo').value = tipo;
		document.getElementById('azimute').value = azimute;
		
		if (sentido == 1){							
			document.getElementById('hiddenSentidoDuplo').value = 1;
		} else {
			document.getElementById('hiddenSentidoDuplo').value = 0;
		}						
		
		document.getElementById('hiddenComentario').value = referencia;																		 							
		chamaPasso(1,'');								
	}
}


function hide(element){
	element.style.display = "none";
	element.style.position = "absolute";
}

function show(element){
	element.style.display = "block";
	element.style.position = "relative";
}

function setaInexistente(){	
	document.getElementById('tipo').value = '';
	document.getElementById('velocidade').value = '';
	document.getElementById('azimute').value = '';
	document.getElementById('hiddenComentario').value = '';
	document.getElementById('hiddenSentidoDuplo').value = '';
	document.getElementById('inexistente').value = 1;
	document.getElementById('frm').action = 'votar.php';
	document.getElementById('latitude').value = '';
	document.getElementById('longitude').value = '';
	document.getElementById('frm').submit();
}

function calculaAzimute(evento){	
	posicaoImagem = mostraPosicaoElemento('imgAzimute');	
	
	posicaoX = evento.clientX - posicaoImagem.left;
	posicaoY = evento.clientY - posicaoImagem.top;	
	
	//equação da reta
	theta = Math.atan((posicaoY - 70) / (posicaoX - 70));
	/*tranformado para graus:*/
	theta = theta*180/Math.PI;
	/*segundo quadrante*/
	if(70 - posicaoX<= 0 && 70 - posicaoY>= 0){
		theta = 180 +theta ;
	}		
	/*terceiro quadrante*/
	if(70- posicaoX<= 0 && 70 - posicaoY<= 0){
		theta = 180 +theta ;
	}	
	/*quarto quadrante */
	if(70 - posicaoX>= 0 && 70 - posicaoY<= 70){
		theta =  360 + theta ;
	}
	theta = (theta  + 270)%360;
	
	return theta;	
}

function mostraPosicaoElemento(idElemento){
	var offsetTrail = document.getElementById(idElemento);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft, top:offsetTop};
}

function carregaestado(latitude, longitude){
	document.getElementById('frmIndex').action = "radares.php";
	document.getElementById('centro').value = latitude+','+longitude;
	document.getElementById('frmIndex').submit();			
}

function chamaLightbox(e,parametro){	
	if (e != ''){
		e.preventDefault();	
	}		
	
	if (parametro == 'mensagemConfirmacao'){
		var id = $('a[id=opiniaook]').attr('href');				
	} else if (parametro == 'login'){
		var id = $('a[id=janelaLogin]').attr('href');
	} else if (parametro == 'loading'){
		var id = $('a[id=janelaLoading]').attr('href');
	} else if (parametro == 'newsletter'){
		var id = $('a[id=newsletter]').attr('href');
	} else {
		var id = $('a[name=modal]').attr('href');	
	}				
	
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();
	
	$('#mask').css({'width':maskWidth,'height':maskHeight});
	
	$('#mask').fadeIn(1000);	
	$('#mask').fadeTo("slow",0.6);	
	
	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();
		  
	$(id).css('top',  winH/2-$(id).height()/2);
	$(id).css('left', winW/2-$(id).width()/2);
	
	$(id).fadeIn(1000); 
	
}

function excluiRadar(){
	setaZoom();
	document.getElementById('frm').action = 'excluiRadar.php';
	document.getElementById('frm').submit();
}

function limitaTextArea(objeto,evento){	
	var tecla=(window.event)?event.keyCode:evento.which;
	if (teclaEspeciais(tecla)){
		return true;
	}
	if (objeto.value.length > 100){
		alert('Limite de caracteres atingido.');
		return false;
	}
	return true;
}

function editaRadar(){
	document.getElementById('hiddenIdRadar').value = document.getElementById('idRadar').value;	
	document.getElementById('hiddenIndice').value = document.getElementById('indice').value;
	document.getElementById('latitude').value = document.getElementById('hiddenLatitude').value;
	document.getElementById('longitude').value = document.getElementById('hiddenLongitude').value;
	chamaPasso(1, document.getElementById('indice').value);
} 

function gerarSenha(objeto){
	document.getElementById('btEnviarSenha').setAttribute('onclick',''); 
	ajax('gerarSenha.php','?email='+objeto.value,'post',respostaGeraSenha,'');	
	//document.getElementById('emailRecSenha').setAttribute('onclick',"gerarSenha(document.getElementById('emailRecSenha').value)");
}

function respostaGeraSenha(){
	resposta = xmlhttp.responseText;	
	alert(resposta);
	document.getElementById('btEnviarSenha').setAttribute('onclick',"gerarSenha(document.getElementById('emailRecSenha'));"); 
	//$('#mask').hide();
	//$('.window').hide();document.getElementById('')
}

function setaTipoMapa(){
	document.getElementById('tipoMapa').value = mapa.getCurrentMapType().getName();
	document.getElementById('tipoMapaLogar').value = mapa.getCurrentMapType().getName();
	document.getElementById('tipoMapaBox').value = mapa.getCurrentMapType().getName();	
}

function buscaCoordenadaUsuario(cidade, estado){
	var geocoder = new GClientGeocoder(); 	
	geocoder.setBaseCountryCode('pt_BR');		
	geocoder.getLocations(cidade + ' cidade' + estado, function (ponto){						
		if (ponto.Placemark){	
			if (ponto.Placemark.length == 1) {	
				document.getElementById('latitudeUsuario').value = ponto.Placemark[0].Point.coordinates[1];
				document.getElementById('longitudeUsuario').value = ponto.Placemark[0].Point.coordinates[0];
			} else {
				document.getElementById('latitudeUsuario').value = '';
				document.getElementById('longitudeUsuario').value = '';
			}	
		} else {
			document.getElementById('latitudeUsuario').value = '';
			document.getElementById('longitudeUsuario').value = '';
		}										
	});	
}

function retornaIndice(idRadar){
	tamanho = arrayResposta.length;			
	for (i=0;i<tamanho;i++){
		valores = arrayResposta[i].split(';');
		if (idRadar == valores[0]){			
			return i;
		}
	}
}

function setaSessao(latitude, longitude){
	window.location = 'setaSessao.php?latitude='+latitude+'&longitude='+longitude;
}

function marcaChecks(nomeCheck, marca){
	if (marca){
		elementos = document.getElementById('frm').elements;
		for (i=0; i<elementos.length; i++){
			if (elementos[i].name == nomeCheck){
				elementos[i].checked = true;
			}
		}
	} else {
		for (i=0; i<elementos.length; i++){
			if (elementos[i].name == nomeCheck){
				elementos[i].checked = false;
			}
		}
	}
}

function validaExcluiRdu(){				
	elementos = document.getElementById('frm').elements;
	for (i=0; i<elementos.length; i++){
		if (elementos[i].name == 'checkPerfil[]'){
			if (elementos[i].checked == true){	
				return true;
			}
			
		}
	}
	alert('Escolha uma opção para exclusão');
	return false;
} 

function excluiRdu(){
	if (confirm('Deseja excluir os RDU\'s selecionados?')){
		document.getElementById('frm').action = 'excluiRdu.php';
		document.getElementById('frm').submit();
	}
}

function pagina(numero){
	document.getElementById('numPagina').value = numero;
	document.getElementById('frm').submit();
}

function ordenar(campo){				
	if ( document.getElementById('campoOrdem').value == campo){
		if (document.getElementById('formaOrdem').value == 'ASC'){
			document.getElementById('formaOrdem').value = 'DESC';
		} else {
			document.getElementById('formaOrdem').value = 'ASC';
		}
	} else {
		document.getElementById('formaOrdem').value = 'ASC';
	}
	document.getElementById('campoOrdem').value = campo;
	document.getElementById('frm').submit();
}


