function XML_HTTP(Pagina, obj) { 
	var oAjax = new ajax;
	var resposta = oAjax.enviar(Pagina, "POST", false);
	//alert("Pronto");
	obj.innerHTML = resposta; 
	//alert("Fim");
}

// Inicializador Ajax
function ajax() {
    
};
// Método iniciar
ajax.prototype.iniciar = function() {
// instanciando o objeto em cada navegador
    try {
        this.xmlhttp = new XMLHttpRequest();
    }
    catch(ee) {
        try {
            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e) {
            try {
                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(E) {
                this.xmlhttp = false;
            }
        }
    }
    return true;
}
// Metodo Ocupado
ajax.prototype.ocupado = function() {
    estadoAtual = this.xmlhttp.readyState;
    return (estadoAtual && (estadoAtual < 4));
}
// Metodo Processa
ajax.prototype.processa = function() {
    if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
        return true;
    }
}
// Metodo que faz as requisições web
ajax.prototype.enviar = function(url, metodo, modo) {
    // se nao estiver iniciado vai iniciar dae...
    if(!this.xmlhttp) {
        this.iniciar();
    }
    // se nao estiver ocupado
    if(!this.ocupado()) {
        //alert("não ocupado...")
        // se for metodo GET
        if(metodo == "GET") {
            this.xmlhttp.open("GET", url, modo);
            this.xmlhttp.setRequestHeader("encoding","ISO-8859-1");
            this.xmlhttp.send(null);
        }
        else {
			//alert("POST")
            // se for post
            this.xmlhttp.open("POST", url, modo);
            //alert("abriu")
            this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
            //alert("Header content")
            this.xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            //alert("Header 1")
            this.xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
            //alert("Header 2")
            this.xmlhttp.setRequestHeader("Pragma", "no-cache");
            //alert("Header 3")
            this.xmlhttp.setRequestHeader("encoding","ISO-8859-1");
            var parametros = new String(url);
            this.xmlhttp.send(parametros.substring(parametros.indexOf("?",1)+1,parametros.length));
            //alert("enviou")
        }
        if(this.processa) {
            // recebe o resultado da pagina... asp
            return unescape(this.xmlhttp.responseText.replace(/\+/g," "));
        }
    }
    else {
		alert("ocupado...")
    }
    return false;
}

// url_encode version 1.0  
function url_encode(str) {  
    var hex_chars = "0123456789ABCDEF";  
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
    var n, strCode, hex1, hex2, strEncode = "";  
	
    for(n = 0; n < str.length; n++) {  
        if (noEncode.test(str.charAt(n))) {  
            strEncode += str.charAt(n);  
        } else {  
            strCode = str.charCodeAt(n);  
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
            hex2 = hex_chars.charAt(strCode % 16);  
            strEncode += "%" + (hex1 + hex2);  
        }  
    }  
    return strEncode;  
}  

// url_decode version 1.0  
function url_decode(str) {  
    var n, strCode, strDecode = "";  

    for (n = 0; n < str.length; n++) {  
        if (str.charAt(n) == "%") {  
            strCode = str.charAt(n + 1) + str.charAt(n + 2);  
            strDecode += String.fromCharCode(parseInt(strCode, 16));  
            n += 2;  
        } else {  
            strDecode += str.charAt(n);  
        }  
    }  
    return strDecode;  
}  

//ValidaData(frm.txt.value)
function ValidaData(data) {
	var dia, mes, ano;
	var dataAtual = new Date();
	var anoAtual;
	
	anoAtual = dataAtual.getYear();
		
	var barra = "/"
	var datas = new Array()
	datas = data.split(barra)
	dia = datas[0]
	mes = datas[1]
	ano = datas[2]

	if(dia == undefined){dia = 0;}
	if(mes == undefined){mes = 0;}
	if(ano == undefined){ano = 0;}

	//dia = parseInt(data.substring(0,2), 10);
	//mes = parseInt(data.substring(3,5), 10);
	//ano = parseInt(data.substring(6,10), 10);

	if ((dia > 31) ||( dia < 1)||( mes > 12 )||( mes < 1 )||( ano < 1900 )) { //||( ano > anoAtual)
		return false; 
	} 
	
	/*se ano é bissexto*/
	if((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)){
		if ((mes == 2) && (dia > 29)) { 
			return false; 
		}
	} else { 
		if ((mes == 2) && (dia > 28)){ 
			return false; 
		}
	}
	
	/* Validando o mês */ 
	if ((dia > 30) && ((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11))){ 
		return false; 
	} 

	/*Se passou por todos a Data é valida (true)*/
	return true;
}

//javascript:FormataCampo(this,event,'##/##/####')
function FormataCampo(Campo,teclapres,mascara){ 
    //pegando o tamanho do texto da caixa de texto com delay de -1 no event 
    //ou seja o caractere que foi digitado não será contado. 
    strtext = Campo.value 
    tamtext = strtext.length 
    //pegando o tamanho da mascara 
    tammask = mascara.length 
    //criando um array para guardar cada caractere da máscara 
    arrmask = new Array(tammask)     
    //jogando os caracteres para o vetor 
    for (var i = 0 ; i < tammask; i++){ 
        arrmask[i] = mascara.slice(i,i+1) 
    } 
    //alert (teclapres.keyCode) 
    //começando o trabalho sujo 
    if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){ 
        if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)){ 
            Organiza_Casa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)         
        } 
        else{ 
            Detona_Event(Campo,strtext) 
        } 
    } 
    else{//Aqui funcionaria a mascara para números mas eu ainda não implementei 
        if ((arrmask[tamtext] == "A"))    { 
            charupper = event.valueOf() 
            //charupper = charupper.toUpperCase() 
            Detona_Event(Campo,strtext) 
            masktext = strtext + charupper 
            Campo.value = masktext
        } 
    } 
} 

function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){ 
    if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "(") || (arrpos == ")") || (arrpos == "-")) && !(teclapres_key == 8)){ 
        separador = arrpos 
        masktext = strtext + separador 
        Campo.value = masktext 
    } 
} 
function Detona_Event(Campo,strtext){ 
    event.returnValue = false 
    if (strtext != "") { 
        Campo.value = strtext 
    } 
} 

function ValidaEmail(email){
	
	if (email.length>0) {
		var goodEmail = email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
		if(goodEmail != null)
			return true;
		else {
			goodEmail = email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org))$)\b/gi);
			if(goodEmail != null)
			return true;
		else 
			return false;
		}
	}
	else
		return true;
}

function telefone(tel){
	if (isNaN(tel.value)){
		return
	}
	if (tel.value.length == 10){
		var listArray = tel.value.split("");
		if ( listArray.length >= 9){
			listArray[0] = "(" + listArray[0];
			listArray[2] = ") " + listArray[2];
		}
		if (tel.value.length == 9){
			listArray[5] = "-" + listArray[5];
		}else if(tel.value.length ==  10){
			listArray[6] = "-" + listArray[6];
		}
		if (listArray.length == 7){
			listArray[3] = "-" + listArray[3];
		}
		if (listArray.length == 8){
			listArray[4] = "-" + listArray[4];
		}
		tel.value = "";
		for ( var i = 0; i <= listArray.length - 1; i++){
			tel.value += listArray[i];
		}
	}
	else {
		if (tel.value != "")
			alert('Telefone incompleto. Informe DDD e número.');
		tel.value = "";
	}
}

function cnpj_raiz(cnpj){
	if (isNaN(cnpj.value)){
		return
	}
	if (cnpj.value.length == 8){
		var listArray = cnpj.value.split("");
		
		listArray[2] = "." + listArray[2];
		listArray[5] = "." + listArray[5];
		
		cnpj.value = "";
		for ( var i = 0; i <= listArray.length - 1; i++){
			cnpj.value += listArray[i];
		}
	}
}

function cnpj_completo(cnpj){
	if (isNaN(cnpj.value)){
		return
	}
	if (cnpj.value.length == 14){
		var listArray = cnpj.value.split("");
		
		listArray[2] = "." + listArray[2];
		listArray[5] = "." + listArray[5];
		listArray[8] = "/" + listArray[8];
		listArray[12] = "-" + listArray[12];
		
		cnpj.value = "";
		for ( var i = 0; i <= listArray.length - 1; i++){
			cnpj.value += listArray[i];
		}
	}
}

function cpf_completo(cpf){
	if (isNaN(cpf.value)){
		return
	}
	if (cpf.value.length == 11){
		var listArray = cpf.value.split("");
		
		listArray[3] = "." + listArray[3];
		listArray[6] = "." + listArray[6];
		listArray[9] = "-" + listArray[9];
		
		cpf.value = "";
		for ( var i = 0; i <= listArray.length - 1; i++){
			cpf.value += listArray[i];
		}
	}
}

function UpperCase(inputString){
	 return inputString.value = inputString.value.toUpperCase();
}

//FORMATA MOEDA
//onKeyPress="return(currencyFormat(this,'.',',',event))"
function currencyFormat(fld, milSep, decSep, e) {
	if (fld.value.length > 12){
		return false
	}
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  // Enter
	if (whichCode == 8) return true;  //  BackSpace
	if (whichCode == 9) return true;  //  Tab
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
	if (j == 3) {
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	fld.select();
	}
	return false;
}

//CTYPE = CPF OU CNPJ
function Verify(CNUMB,CTYPE) {
	if (CNUMB == "") {
		return(true);
	}

	CNUMB=ParseNumb(CNUMB)
	if(CNUMB == 0) {
		return(false);
	}
	else {
		g=CNUMB.length-2;
		if(TestDigit(CNUMB,CTYPE,g)) {
			g=CNUMB.length-1;
			if(TestDigit(CNUMB,CTYPE,g)) {	
				return(true);
			}
			else {
				return(false);
			}
		}
		else {
			return(false);
		}
	}
}

function ClearStr(str, Char) {
	while((cx=str.indexOf(Char))!=-1) {
		str = str.substring(0,cx)+str.substring(cx+1);
	}
	return(str);
}

function ParseNumb(c) {
	c=ClearStr(c,'-');
	c=ClearStr(c,'/');
	c=ClearStr(c,',');
	c=ClearStr(c,'.');
	c=ClearStr(c,'(');
	c=ClearStr(c,')');
	c=ClearStr(c,' ');
	if((parseFloat(c) / c != 1)) {
		if(parseFloat(c) * c == 0) {
			return(c);
		}
		else {
			return(0);
		}
	} 
	else {
		return(c);
	}
}

function TestDigit(CNUMB,CTYPE,g) {
	var dig=0;
	var ind=2;
	for(f=g;f>0;f--) {
		dig+=parseInt(CNUMB.charAt(f-1))*ind;
		if (CTYPE=='CNPJ') { 
			if(ind>8) {
				ind=2
			} 
			else {
				ind++
			}
		}
		else { 
			ind++ 
		}
	}
	dig%=11;
	if(dig<2) {
		dig=0;
	} 
	else {
		dig=11-dig;
	}
	if(dig!=parseInt(CNUMB.charAt(g))) {
		return(false);
	}
	else {
		return(true);
	}
}

//só aceita números
// onkeypress="javascript:Codigo(event);"
function Codigo(teclapres){
	if ((teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9)||(teclapres.keyCode == 44)||(teclapres.keyCode == 0)){ 
		return true
	}else{
		event.returnValue = false
	}
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + ',' + cents);
}

//Função que valida o Formulário
function validaFormulario(form) {
	var i = 0;
	var nome;

	for (i=0;i<form.length;i++) {
		nome = new String(form[i].name);
		obrigatorio = form[i].obrigatorio;
		if ((obrigatorio == 'true')||(obrigatorio == 'True')) {
			if (form[i].type == "select-one") {
				if (form[i][form[i].selectedIndex].value == "0") {
					nome = new String(form[i].name)
					alert("Selecione o campo " + nome.substring(3,nome.length).replace("_"," ").replace("_"," "));
					form[i].focus();
					return false
				}
			}
			if (form[i].type == "hidden") {
				if (form[i].value == "") {
					nome = new String(form[i].name)
					alert("Selecione o campo " + nome.substring(3,nome.length).replace("_"," ").replace("_"," "));
					return false
				}
			}
			if (form[i].type == "text") {
				nome = new String(form[i].name)
				if (nome.substring(0,3) == "dta") {
					if (form[i].value == 0) {					
						alert("Preencha o campo " + nome.substring(3,nome.length).replace("_"," ").replace("_"," "));
						form[i].focus();
						return false
					} else {
						if (!ValidaData(form[i].value)) {
							alert("A data é inválida");
							form[i].focus();
							return false
						}
					}
				}
				else if (nome.substring(0,6) == "txtCPF") {
					if (!Verify(form[i].value, "CPF")) {
						alert("O CPF é inválido");
						form[i].focus();
						form[i].select();
						return false
					}
				}
				else {
					if (form[i].value == "") {					
						alert("Preencha o campo " + nome.substring(3,nome.length).replace("_"," ").replace("_"," "));
						form[i].focus();
						return false
					}
				}
			}
			if (form[i].type == "password") {
				if (form[i].value == "") {
					nome = new String(form[i].name)
					alert("Preencha o campo " + nome.substring(3,nome.length).replace("_"," ").replace("_"," "));
					form[i].focus();
					return false
				}
			}
			if (form[i].type == "textarea") {
				if (form[i].value == "") {
					nome = new String(form[i].name)
					alert("Preencha o campo " + nome.substring(3,nome.length).replace("_"," ").replace("_"," "));
					form[i].focus();
					return false
				} 
				else {
					var conteudo = new String(form[i].value);
					if (conteudo.length > form[i].maximo) {
						alert("O campo " + nome.substring(3,nome.length).replace("_"," ").replace("_"," ") + " deve possuir até " + form[i].maximo + " caracteres.");
						form[i].focus();
						return false
					}
				}
			}
		}
		else if (nome.substring(0,6) == "txtCPF") {
			if (form[i].value !== "") {
				if (!Verify(form[i].value, "CPF")) {
					alert("O CPF é inválido");
					form[i].focus();
					form[i].select();
					return false
				}
			}
		}
	}
	return true
}

function escondeCombo(form) {
	for(var i=0;i<form.length;i++) {
		if (form[i].type == "select-one")
			form[i].style.visibility = "hidden";
	}
}

function mostraCombo(form) {
	for(var i=0;i<form.length;i++) {
		if (form[i].type == "select-one")
			form[i].style.visibility = "visible";
	}
}

function flash(src, width, heigth, script) {
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" name="interferencia" width="' + width + '" height="' + heigth + '" align="middle" id="interferencia" ' + script + '>');
	document.write('<param name="allowScriptAccess" value="always" />');
	document.write('<param name="movie" value="' + src + '" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="bgcolor" value="#FFFFFF" />');
	document.write('<param name="wmode" value="transparent" />');
	document.write('<embed src="' + src + '" quality="high" bgcolor="#FFFFFF" width="' + width + '" height="' + heigth + '" name="interferencia" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	document.write('</object>');
}

function muda_menu(mnu, over) {
	if (over) {
		//eval("mnu_" + mnu + "a.className = 'aba_esq2';")
		eval("mnu_" + mnu + "b.className = 'aba2';")
		//eval("mnu_" + mnu + "c.className = 'aba_dir2';")
	}
	else {
		//eval("mnu_" + mnu + "a.className = 'aba_esq';")
		eval("mnu_" + mnu + "b.className = 'aba';")
		//eval("mnu_" + mnu + "c.className = 'aba_dir';")
	}	    
}
