//<!--

var req;
var alvo;
var carregando = '';

function loadXMLDoc(url){
	req = null;

	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange1;
		req.open("GET", url, true);
		req.send('');
	} else if (window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP.4.0");
		} catch(e) {
			try {
				req = new ActiveXObject("Msxml2.XMLHTTP.3.0");
			} catch(e) {
				try {
					req = new ActiveXObject("Msxml2.XMLHTTP");
				} catch(e) {
					try {
						req = new ActiveXObject("Microsoft.XMLHTTP");
					} catch(e) {
						req = false;
					}
				}
			}
		}
		if (req) {
			req.onreadystatechange = processReqChange1;
			req.open("GET", url, true);
			req.send('');
		}
	}
}

function processReqChange1(){ 
	if (req.readyState == 4) {
		if (req.status == 200) {
			texto = req.responseText.replace(/\+/g," ");
			
			extraiScript(texto);

			document.getElementById(alvo).innerHTML = req.responseText;
		} else {
			alert("Houve um problema ao atualizar os dados:\n" + req.statusText);
		}
	} else {
		document.getElementById(alvo).innerHTML = carregando;
	}
}

function atualiza(url, target){
	alvo = target;
	
	loadXMLDoc(url);
}

function extraiScript(texto){
	/*
	 * Autor: SkyWalker.TO do imasters/forum 
	 * http://forum.imasters.com.br/index.php?showtopic=165277
	 * 
	 * Permite a esecução de um script/função como retorno do HttpRequest/Ajax
	 */
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            //eval(codigo);
            /**********************
            * Alterado por Micox - micoxjcg@yahoo.com.br
            * Alterei pois com o eval não executava funções.
            ***********************/
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}

function marcar(){
	d = document.formMailing;
	
	for (i = 0; i < d['sel[]'].length; i++){
		if (! d['sel[]'][i].checked) {
			d['sel[]'][i].checked = 'checked';
		} else {
			d['sel[]'][i].checked = '';
		}
	}
}

function segmento(check, rep, segid) {
	if(segid != '') {
		atualiza('reps.php?cod=10&rep=' + rep + '&segmento=' + segid, 'area');
	}
}

function validaForm(id){
	switch (id)	{
		case 1:
			er1 = /[A-Za-z]{3,}/;
			er2 = /[A-Za-z0-9_.-]+@([A-Za-z0-9_-]+)+\.[A-Za-z]{2,}/;
			
			d   = document.formCadastro;
			
			if (! er1.test(d.nome.value) || ! er2.test(d.email.value)){
				msgErro(1);
				
				d.nome.focus();
				
				return false;
			}
			
			d.submit();
			
			break;
			
		case 2:
			er1 = /[A-Za-z]{3,}/;
			er2 = /[A-Za-z0-9_.-]+@([A-Za-z0-9_-]+)+\.[A-Za-z]{2,}/;
			
			d   = document.formFolha;
			
			if (! er1.test(d.nome.value) || ! er2.test(d.email.value) || d.min.value == '' || d.max.value == '' || d.normal.value == '' || d.temp_minima.value == '' || d.temp_maxima.value == '' || d.pressao_media.value == '' || d.pressao_maxima.value == '' || d.tipo_emissao.value == '' || d.concentracao_minima.value == '' || d.concentracao_media.value == '' || d.insttipo.value == '' || d.forca.value == '' || d.agua.value == '' || d.tipo.value == '' || d.diametro.value == '' || d.altura_chamine.value == '' || d.resultado.value == ''){
				msgErro(1);
				
				d.nome.focus();
				
				return false;
			}
			
			d.submit();
			
			break;
			
		case 3:
			er1 = /[A-Za-z0-9_.-]+@([A-Za-z0-9_-]+)+\.[A-Za-z]{2,}/;	
			er2 = /[A-Za-z0-9]{3,}/;
			
			d   = document.formProj;
			
			if (! er1.test(d.login.value) || ! er2.test(d.senha.value)){
				msgErro(2);
				
				d.login.focus();
				
				return false;
			}
			
			return true;
			
			break;
			
		case 4:
			d = document.formIndicar;
			
			var teste  = d.emaildest.value;
			var testea = teste.split(';');
			
			var er = /[A-Za-z0-9_.-]+@([A-Za-z0-9_]+)+\.[A-Za-z]{2,4}/;
			
			for (var email in testea) {
				str = testea[email];

				if (! er.test(str) && str != '') {
					alert('O e-mail ' + str + ' parece inválido.');
				
					return false;
				}
			}
			
			if (! er.test(d.emailrem.value)) {
				alert('O e-mail do remetente parece inválido.');
				
				return false;
			}
			
			idn       = document.formIndicar.notid.value;
			emailDe   = document.formIndicar.emailrem.value;
			emailDest = document.formIndicar.emaildest.value;

			atualiza('noticias_indicar.php?idn=' + idn + '&emailDe=' + emailDe + '&emailDest=' + emailDest, 'divIndicar');

			break;
			
		case 5:
			d = document.formMailing;

			for (i = 0; i < d['sel[]'].length; i++){
				if (d['sel[]'][i].checked){
					return true;
				}
			}

			msgErro(3);

			return false;

			break;
	}
}

function msgErro(tipo){
	switch (tipo) {
		case 1:
			msg = "Verifique o preenchimento dos campos obrigatórios e tente novamente. Obrigado.";
					
			break;
			
		case 2:
			msg = "Informe corretamente seu usuário e senha para acessar a Área do Projetista. Obrigado.";
					
			break;
			
		case 3:
			msg = 'Selecione no mínimo 1 (um) destinatário. Obrigado.';
					
			break;
	}
	
	alert (msg);
}

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		countfield.value = maxlimit - field.value.length;
	}
}

function sair(){
	if (! confirm('Encerrar o sistema?')){
		return false;
	}
	
	window.open('logout.php', '_self');
}

function confirma(id, comp) {
	switch (id){
		case 1:
			if (!confirm('Confirma a exclusão deste usuario?')){
				return false;
			}
			
			window.open('usuarios.php?cod=5&id=' + comp, '_self');

			break;

		case 2:
			if (!confirm('Confirma a exclusão deste link?')){
				return false;
			}
			
			window.open('links.php?cod=5&id=' + comp, '_self');

			break;
			
		case 3:
			if (!confirm('Confirma a exclusão deste vídeo?')){
				return false;
			}
			
			window.open('videos.php?cod=5&id=' + comp, '_self');

			break;
		
		case 4:
			if (!confirm('Confirma a exclusão deste artigo?')){
				return false;
			}
			
			window.open('artigos.php?cod=5&id=' + comp, '_self');

			break;
		
		case 5:
			if (!confirm('Confirma a exclusão deste certificado?')){
				return false;
			}
			
			window.open('certificados.php?cod=5&id=' + comp, '_self');

			break;
			
		case 6:
			if (!confirm('Confirma a exclusão deste cliente?')){
				return false;
			}
			
			window.open('clientes.php?cod=5&id=' + comp, '_self');

			break;
			
		case 7:
			if (!confirm('Confirma a exclusão desta notícia?')){
				return false;
			}
			
			window.open('noticias.php?cod=5&id=' + comp, '_self');

			break;
			
		case 8:
			if (!confirm('Confirma a exclusão deste produto?')){
				return false;
			}
			
			window.open('produtos.php?cod=5&id=' + comp, '_self');

			break;
			
		case 9:
			if (!confirm('Confirma a exclusão deste cadastro?')){
				return false;
			}
			
			window.open('projetista.php?cod=12&id=' + comp, '_self');

			break;
			
		case 10:
			if (!confirm('Confirma a exclusão deste material?')){
				return false;
			}
			
			window.open('projetista.php?cod=5&id=' + comp, '_self');

			break;
			
		case 11:
			if (!confirm('Confirma a exclusão deste representante?')){
				return false;
			}
			
			window.open('reps.php?cod=5&id=' + comp, '_self');

			break;
			
		case 12:
			if (!confirm('Confirma a exclusão desta solução?')){
				return false;
			}
			
			window.open('solucoes.php?cod=5&id=' + comp, '_self');

			break;
			
		case 13:
			if (!confirm('Confirma a exclusão deste destinatário?')){
				return false;
			}
			
			window.open('mailing.php?cod=5&id=' + comp, '_self');

			break;
	}
}

// FORMATADOR

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all) { // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
		nTecla = evtKeyPress.which;
	} else {
		nTecla = evtKeyPress.which;
		if (nTecla == 8) {
			return true;
		}
	}

	sValue = objForm[strField].value;
	// Limpa todos os caracteres de formatação que
	// já estiverem no campo.
	sValue = sValue.toString().replace(/\-/g, "");
	sValue = sValue.toString().replace(/\./g, "");
	sValue = sValue.toString().replace(/\//g, "");
	sValue = sValue.toString().replace(/\(/g, "");
	sValue = sValue.toString().replace(/\)/g, "");
	sValue = sValue.toString().replace(/\s/g, "");
	fldLen = sValue.length;
	mskLen = sMask.length;

	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;

	while (i <= mskLen) {
	bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ":") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
	bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

	if (bolMask) {
		sCod += sMask.charAt(i);
		mskLen++;
	} else {
		sCod += sValue.charAt(nCount);
		nCount++;
	}
	i++;
	}

	objForm[strField].value = sCod;
	if (nTecla != 8) { // backspace
		if (sMask.charAt(i-1) == "9") { // apenas números...
			return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
		else { // qualquer caracter...
			return true;
		}
	} else {
		return true;
	}
}

//Fim da Função Máscaras Gerais

/***
* AUTO TAB - ao prencher o campo, automaticamente manda o foco para o próximo!
***/
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }

function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
        found = true;
    else
        index++;
        return found;
    }

function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
        if (input.form[i] == input)index = i;
        else i++;
        return index;
    }
    return true;
}

// FORMATADOR - fim

//

function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
aux = validos.indexOf(valor.substring(i, i+1));
if (aux>=0) {
result += aux;
}
}
return result;
}

//Formata número tipo moeda usando o evento onKeyDown

function Formata(campo,tammax,teclapres,decimal) {
var tecla = teclapres.keyCode;
vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal

if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

if (tecla == 8 )
{ tam = tam - 1 ; }

if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
{

if ( tam <= dec )
{ campo.value = vr ; }

if ( (tam > dec) && (tam <= 5) ){
campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
}
if ( (tam >= 9) && (tam <= 11) ){
campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
} 

}
	
//-->

