/**
 *  scripts
 *  Desenvolvedor: Raymundo Brasil
 *  Data: 24 de dezembro de 2009
 *  Atualização: 
 */

function setFocus(){
	var existe = typeof document.forms['form2'] != 'undefined';
	if (existe) { 
		var fForm = document.forms['form2'].NOME;
	} else {
		var fForm = document.forms['form1'].LOGIN;
	}
	fForm.focus();
//	document.forms['form2'].NOME.focus();
}

function setaFoco(){
	document.forms['form1'].LOGIN.focus();
}

function validaData(campo,valor) {
	var date=valor;
	var ardt=new Array;
	var ExpReg=new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
	ardt=date.split("/");
	erro=false;
	if ( date.search(ExpReg)==-1){
		erro = true;
		}
	else if (((ardt[1]==4)||(ardt[1]==6)||(ardt[1]==9)||(ardt[1]==11))&&(ardt[0]>30))
		erro = true;
	else if ( ardt[1]==2) {
		if ((ardt[0]>28)&&((ardt[2]%4)!=0))
			erro = true;
		if ((ardt[0]>29)&&((ardt[2]%4)==0))
			erro = true;
	}
	if (erro) {
		campo.focus();
		return false;
	}
	return true;
}



function checaTamanho() {
	var tam = document.form2.DADO.value.length; var cor = document.form2.DADO.style;

	if ( (tam=0)&&(cor = 'background-color:#FF0000') ) {
    	alert('Senha deve ter no m\xEDnimo 8 caracteres.');
        document.form2.DADO.focus();
	} else
	if ( ( tam > 0 )&&( tam < 8 ) ) {
    	alert('Senha deve ter no m\xEDnimo 8 caracteres.');
        document.form2.DADO.focus();
    } else 
	if ( tam > 15 ) {
    	alert('Senha deve ter no m\xe1ximo 15 caracteres.');
        document.form2.DADO.focus();
    } 
		
		
}



function getValor(form) {
	var url = "";
	elementosForm = form.getElementsByTagName("input");
	for(i=0; i<elementosForm.length; i++)	{
		//if ( (trim(elementosForm[i].name)!='guardaGet') || (trim(elementosForm[i].name)!='volta') ) {
		if (trim(elementosForm[i].name)!='guardaGet') {
			url = url + elementosForm[i].name + "=" + elementosForm[i].value + "&";
		}
	}
	
	elementosFormSelect = form.getElementsByTagName("select");
	for(i=0; i<elementosFormSelect.length; i++)	{
		url = url + elementosFormSelect[i].name + "=" + elementosFormSelect[i].value + "&";
	}
//	alert(url);
//     document.location = url;
	document.form2.guardaGet.value = url.substring(0,url.length-1);
}

function alimentaInput(texto) {
	var temp, novo = "";
	temp = texto.split("|");
	for (i in temp) {
		novo = novo+ String.fromCharCode(temp[i]);
	}
	document.form2.guardaGet.value = novo;
}

function convertInput(texto) {
	var novo = "";
	for(i=0; i<texto.length; i++)	{
		novo = novo+texto.substr(i,1).charCodeAt(0)+'|';
	}
	return novo;
}

function primeiroNome() {
	var texto = document.form2.NOME.value;
	var novo = "";
	var i=0;
	while (trim(texto.substr(i,1))!='') {
		novo = novo+texto.substr(i++,1);
	}
	document.form2.APELIDO.value = novo;
}

function inclui_MM_jumpMenu(targ,selObj,restore){ //v3.0
	/*var guardaG, guardaG1, guardaG2;
 	guardaG = document.form2.guardaGet.value;
	guardaG1 = guardaG.replace(/&/gi, "|");
	guardaG2 = guardaG1.replace(/=/gi, String.fromCharCode(045));
	var gGet = "guardaGet=" + guardaG2;
	*/
	var gGet = "guardaGet=" + convertInput(document.form2.guardaGet.value);

	//eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"&"+document.form2.guardaGet.value+"'"); 
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"&"+gGet+"'"); 
	//alert(targ+".location='"+selObj.options[selObj.selectedIndex].value+"&"+gGet+"'"); 
  	if (restore) selObj.selectedIndex=0;
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  	if (restore) selObj.selectedIndex=0;
}

function confirmar(delUrl, msg, op) {
	var existe = typeof document.forms['form2'] != 'undefined';
	if (existe) { 
		var fForm = document.forms['form2'];
	} else {
		var fForm = document.forms['form1'];
	}
	if (op==1) {
		if (confirm(msg)) {
			alert(deUrl);
			if (deUrl=='') {
				fForm.submit(); 
			} else {
				document.location = delUrl;
			}
		}
	} else {
		document.location = delUrl;
	}
}

function confirmar_estado(msg, op) {
	// incrementar para inclusão ou alteração
	var fForm = document.forms['form1'];
	if (confirm(msg)) {
		fForm.submit(); 
	}
}

function muda() {
	var existe = typeof document.forms['form2'] != 'undefined';
	if (existe) { 
		var fForm = document.forms['form2'];
	} else {
		var fForm = document.forms['form1'];
	}
	if (fForm.ativo.checked) {
		fForm.ativo.value = 1;
	} else {
		fForm.ativo.value = 0;
	}
/*
	if (document.form1.ativo.checked) {
		document.form1.ativo.value = 1;
	} else {
		document.form1.ativo.value = 0;
	}
*/	
}


function limpaCampo(){ 
	document.forms['search'].searchText.value = '';
	
} 

function reenvia(url,set,gru,op) {
	location.href = url+'?codSetor='+set+'&codGrupo='+gru+'&pag=1&op='+op+'&mapa=0';
}

function filtraTipo(url) {
	for(i = 0; i < document.form1.tipo.length; i++){
    	if (document.form1.tipo[i].checked) {
			valor=document.form1.tipo[i].value;
	    	break;
    	}
	}
	location.href = url+'&tipo='+valor;
	
}

function chamaUrl(op,url) {
	if (op==0) {
		var fForm = document.forms['form2'];
		location.href = url+'&top='+document.form2.fim.value+'&bottom='+document.form2.inicio.value+'&ecivil='+fForm.elements['codEstCivil'].value;
	} else 
		if (op==10){
		location.href = url+'&filtro='+document.form1.DESCRICAO.value;
	} else {
		location.href = url+'&top='+document.form2.maior.value+'&bottom='+document.form2.menor.value+'&batizado='+document.form2.batizado.value;
	}
}

function chamaFilhos(url) {
	var existe = typeof document.forms['form2'].codConjuge != 'undefined';
	if (existe) { 
		open(url+'&codConjuge='+document.form2.codConjuge.value, 'new','width=950,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
	} else {
		open(url+'&codConjuge=', 'new','width=950,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
	}
	
	open(url+'&codConjuge='+document.form2.codConjuge.value, 'new','width=950,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
//	open(url+'&codConjuge='+document.form2.codConjuge.value, 'new','width=950,height=600,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
}

function trim(s) {
	var l=0; var r=s.length -1;
	while(l < s.length && s[l] == ' ') 	{	
		l++; 
	}
	while(r > l && s[r] == ' ')	{	
		r-=1;	
	}
	return s.substring(l, r+1);
}

function aresTexto() {
	var at = document.getElementById('send_string_array');
	var rows = at.rows;
	alert(at.rows.value);
}

function confirme(velho, msg, url, codigo, campo){ 
	var para = '', novo = '', novoComplemento='', sair = false;
	var existe = typeof document.forms['form2'] != 'undefined';
	if (existe) { 
		var fForm = document.forms['form2'];
	} else {
		var fForm = document.forms['form1'];
	}

	if (velho!='fechar') {
		if (document.getElementById("DESCRICAO") == null) {
			if (document.getElementById("NOME") != null) {
				valor = document.getElementById("NOME").value;
			}
		} else {
			valor = document.getElementById("DESCRICAO").value;
		}
		if (codigo!='0') {
			if ("DESCRICAO"!=campo) {
				if( fForm.elements[campo].type == "select-one" ) {
					novoComplemento = ' - '+fForm.elements[campo].options[fForm.elements[campo].selectedIndex].text;     
				} else
				if ( document.getElementById(campo) ) {
					novoComplemento = ' - '+document.getElementById(campo).value;
				}
			}
			if (document.getElementById("ATUALIZA") == null) {
				if (fForm.op[0].checked==true) {
					velho = trim(velho);
					if (velho.length <= 1) {
						alert("Voc\xEA n\xE3o pode alterar um campo que n\xE3o existe:\r"+valor);
						sair = true;
					} else {
						msg = 'Confirma a altera\xe7\xE3o d'+msg+' ';
						novo = valor+novoComplemento;
						para = 'Para: ';
					}
				} else
				if (fForm.op[1].checked==true) {
					msg = 'Confirma a inclus\xE3o d'+msg;
					novo = valor+novoComplemento;
					para = '';
					velho = '';
				}
			} else {
					apelido = novoComplemento.split("-");
					novo = trim(apelido[1]);
					para = '';
					velho = '';
			}
		}
	} else {
		velho = '';
		novo = codigo; // passo em código o usuário
	}
	if (!sair) {
		proxLinha = '\r\n';
		if (velho='') {
			conteudo = msg+proxLinha+velho+proxLinha+para+proxLinha+novo+' ?';
		} else {
			conteudo = msg+' '+novo+'?';
			//conteudo = novo+', '+msg.toLowerCase()+'?';
		}
		if (confirm(conteudo)){ 
			if (url=='') {
				fForm.submit(); 
			} else {
				location.href = url;
			}
		} 
	}
} 

function decision(message, url){
	if(confirm(message)) 
		location.href = url;
}

function passaProprietario(url, cod){
	location.href = url;
}

function esqueceu(url){
	var email = document.getElementById('LOGIN').value;
	
	if(email=='') {
		alert('Preencha o campo [ E-mail ] e tente novamente!');
	} else {
		location.href = url+email;
	}
	// document.location 
}

function informar(msg) { 
	alert(msg);
	location.href = 'www.fazendodiscipulos.net';
}

// maps

var map;
var geocoder;
var index=0, j=0;

function initialize(enderecos) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(-12.9792, -38.4461), 12);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		function createMarker(latlng, num) {
			var iconOptions = {}; 
			iconOptions.width = 10; 
			iconOptions.height = 10; 
			iconOptions.primaryColor = "#FF0000"; 
			iconOptions.label = i; 
			iconOptions.labelSize = 0; 
			iconOptions.labelColor = "#000000"; 
			iconOptions.shape = "circle"; 


			var newIcon = MapIconMaker.createFlatIcon(iconOptions);
		
			//var newIcon = MapIconMaker.createFlatIcon({width: 10, height: 10, primaryColor: "#00ff00"});
			var marker = new GMarker(latlng, {icon: newIcon});
			return marker;
		}
		var pontos;
		address = enderecos.split("|");
		for (i in address) {
			addressX = address[i].split(",");
		    var latlng = new GLatLng(Number(addressX[0]), Number(addressX[1]));
			map.addOverlay(createMarker(latlng, i));
			pontos = i;
		};
		document.getElementById("numPontos").value = ' '+pontos+' pontos encontrados!';
	}
}


function addAddressToMap(response) {
	//map.clearOverlays();
	var erros = '';
	var volta = '';
	var point=null;
	
	if (!response || response.Status.code != 200) {
		erros = 'erro no endere\xe7o';
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		//map.addOverlay(createMarker(point));
	}
	volta = point+'|';
	document.getElementById("send_string_array").value += volta;
	//document.getElementById("php_code").innerHTML="<?php echo("+document.getElementById('send_string_array').value+"); ?>";
	return point;
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation(enderecos) {
	geocoder = new GClientGeocoder();
	var address;
	address = enderecos.split("|");
	for (i in address) {
		addressX = address[i].split("!");
		codigo = addressX[0]+'\n';
		//cod = codigo+'\n';
		document.getElementById("codigo").value += codigo;
		geocoder.getLocations(addressX[1], addAddressToMap);
	}
	//stringVolta = volta.join("|");
	//incluiPoint(volta);
}

function sLocation(address) {
	geocoder = new GClientGeocoder();
	geocoder.getLocations(address, addAddressToMap);
}

function createMarkerXX(latlng) {
	var iconOptions = {}; 
	iconOptions.width = 10; 
	iconOptions.height = 10; 
	iconOptions.primaryColor = "#FF0000"; 
	iconOptions.label = "."; 
	iconOptions.labelSize = 0; 
	iconOptions.labelColor = "#000000"; 
	iconOptions.shape = "circle"; 
	var newIcon = MapIconMaker.createFlatIcon(iconOptions);

	//var newIcon = MapIconMaker.createFlatIcon({width: 10, height: 10, primaryColor: "#00ff00"});
    var marker = new GMarker(latlng, {icon: newIcon});
	return marker;
}

function fazAgora(enderecos) {
	//map1 = new GMap2(document.getElementById("map_canvas"));
	var address, latlng;
	address = enderecos.split("|");
	for (i in address) {
		latlng = address[i];
		map.addOverlay(createMarker(latlng));
	}
}

function createMarker1(enderecos) {
	var iconOptions = {}; 
	var address;
	address = enderecos.split("|");
	iconOptions.width = 10; 
	iconOptions.height = 10; 
	iconOptions.primaryColor = "#FF0000"; 
	iconOptions.label = "."; 
	iconOptions.labelSize = 0; 
	iconOptions.labelColor = "#000000"; 
	iconOptions.shape = "circle"; 
	for (i in address) {
		latlng = address[i];
		var newIcon = MapIconMaker.createFlatIcon(iconOptions);
	
		//var newIcon = MapIconMaker.createFlatIcon({width: 10, height: 10, primaryColor: "#00ff00"});
		var marker = new GMarker(latlng, {icon: newIcon});
		map.addOverlay(marker);

	}

	return marker;
}



function showCidade(enderecos) {
	geocoder = new GClientGeocoder();
	geocoder.getLocations(enderecos, entregaPoint);

}

function entregaPoint(response) {
	var point=null;
	var erros = '';
	index++;
	if (!response || response.Status.code != 200) {
		erros = 'erro no endere\xe7o';
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		map.panTo(point);
	}
	return point;
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
  showLocation(address);
}


/* fim de novos testes*/

function incluiPoint(volta){
	//alert(cPessoa+' : '+point);
	document.location = 'mapeamento.php?volta='+volta;
	//document.location = 'incluiPonto.php?pessoa='+pessoa+'&point='+point;
	//array_produtos.join("|");

	//document.location = '../funcoes/funcoes.php?codPessoa='+cPessoa+'&point='+point;
	//document.getElementById("php_code").innerHTML="<?php $zz = incluiPonto("+cPessoa+", "+point+"); //maybe a function ?>";
}


/* funções para capturar POINT e colocar na tag input POINT */

// passa o endereço digitado pelo usuário para a função
// que converte para coodenadas
function pegaCoordenadas() {
	//var geocoder;
	var existe = typeof document.forms['form2'] != 'undefined';
	if (existe) { 
		var fForm = document.forms['form2'];
	} else {
		var fForm = document.forms['form1'];
	}
	endereco = trim(document.getElementById("ENDERECO").value) + ', ' +	fForm.elements['codBairro'].options[fForm.elements['codBairro'].selectedIndex].text + ', ' + fForm.elements['codCidade'].options[fForm.elements['codCidade'].selectedIndex].text + ', ' +	fForm.elements['codEstado'].options[fForm.elements['codEstado'].selectedIndex].text;
	geocoder = new GClientGeocoder();
	geocoder.getLocations(endereco, converteEndereco);
}

function converteEndereco(response) {
	//map.clearOverlays();
	var point=null;
	var erros = '';
	var volta = '';
	if (!response || response.Status.code != 200) {
		erros = 'erro no endere\xe7o';
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	}
	// coloca coordenada na tag POINT
	if (trim(document.getElementById("POINT").value)=='') {
		document.getElementById("POINT").value = point;
	}
	//return point;
}

/* fim funções para capturar POINT e colocar na tag input POINT*/


