
function confirma(mensagem){
	if (mensagem == null) mensagem = "Confirma os dados?";
	return confirm(unescape(mensagem.replace(/\+/g," ")));
}

function confirmaExcluir(){
	mensagem = "Deseja realmente excluir esse registro?";
	return confirm(unescape(mensagem.replace(/\+/g," ")));
}

function validaCnpj(obj){
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	cnpj = TiraTudo(obj.value);
	digitos_iguais = 1;

	if (cnpj.length < 14 && cnpj.length < 15)
		return false;
	for (i = 0; i < cnpj.length - 1; i++)
		if (cnpj.charAt(i) != cnpj.charAt(i + 1))
			  {
			  digitos_iguais = 0;
			  break;
			  }
	if (!digitos_iguais)
		{
		tamanho = cnpj.length - 2
		numeros = cnpj.substring(0,tamanho);
		digitos = cnpj.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
			  {
			  soma += numeros.charAt(tamanho - i) * pos--;
			  if (pos < 2)
					pos = 9;
			  }
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0))
			  return false;
		tamanho = tamanho + 1;
		numeros = cnpj.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
			  {
			  soma += numeros.charAt(tamanho - i) * pos--;
			  if (pos < 2)
					pos = 9;
			  }
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1))
			  return false;
		return true;
		}
	else
		return false;
} 

function validaCpf(obj){
	var numeros, digitos, soma, i, resultado, digitos_iguais;
	
	cpf = TiraTudo(obj.value);
	digitos_iguais = 1;
	
	if (cpf.length < 11)
		return false;
	for (i = 0; i < cpf.length - 1; i++)
		if (cpf.charAt(i) != cpf.charAt(i + 1)){
			digitos_iguais = 0;
			break;
		}
		
	if (!digitos_iguais){
		
		numeros = cpf.substring(0,9);
		digitos = cpf.substring(9);
		soma = 0;
		for (i = 10; i > 1; i--)
			  soma += numeros.charAt(10 - i) * i;
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0))
			  return false;
		numeros = cpf.substring(0,10);
		soma = 0;
		for (i = 11; i > 1; i--)
			  soma += numeros.charAt(11 - i) * i;
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1))
			  return false;
		return true;
	}else
		return false;
}

function validaEmail(objEmail){

      var emailStr = objEmail.value;


        //remove espaços antes da verificação
        var emailStr = Trim(emailStr);
        /* Critica de e-mail */
        var emailPat=/^(.+)@(.+)$/
        var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
        var validChars="\[^\\s" + specialChars + "\]"
        var quotedUser="(\"[^\"]*\")"
        var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
        var atom=validChars + '+'
        var word="(" + atom + "|" + quotedUser + ")"
        var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
        var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


        var matchArray=emailStr.match(emailPat)
        if (matchArray==null) {
			//alert("O endere\u00E7o de e-mail est\u00E1 incorreto (verifique @ e .'s)");
			alertaMensagem("O endere\u00E7o de e-mail est\u00E1 incorreto (verifique @ e .'s)",'erro');
			objEmail.focus();
			//objEmail.value="";
			return false;
        }
        var user=matchArray[1]
        var domain=matchArray[2]

        if (user.match(userPat)==null) {
			alertaMensagem("O endere\u00E7o de e-mail est\u00E1 inv\u00E1lido.",'erro');
			objEmail.focus();
			//objEmail.value="";
			return false;
        }

        var IPArray=domain.match(ipDomainPat)
        if (IPArray!=null) {
                  for (var i=1;i<=4;i++) {
                    if (IPArray[i]>255) {
						alertaMensagem("O endere\u00E7o de e-mail est\u00E1 inv\u00E1lido.",'erro');
						objEmail.focus();
						//objEmail.value="";
						return false;
                    }
            }
            return true
        }

        var domainArray=domain.match(domainPat)
        if (domainArray==null) {
			alertaMensagem("O endere\u00E7o de e-mail est\u00E1 inv\u00E1lido.",'erro');
			objEmail.focus();
			//objEmail.value="";
			return false;
        }

        var atomPat=new RegExp(atom,"g")
        var domArr=domain.match(atomPat)
        var len=domArr.length
        if (domArr[domArr.length-1].length<2 ||
			domArr[domArr.length-1].length>3) {
			alertaMensagem("O endere\u00E7o de e-mail est\u00E1 inv\u00E1lido.",'erro');
			objEmail.focus();
			//objEmail.value="";
			return false;
        }

        if (len<2) {
			var errStr="O endere\u00E7o de e-mail est\u00E1 inv\u00E1lido.";
			alertaMensagem(errStr,'erro');
			objEmail.focus();
			//objEmail.value="";
			return false;
        }

        return true;
}

function Trim(str){
	return LTrim(RTrim(str));
}
function LTrim(str){
	return str.replace(/^\s*/, "");
}
function RTrim(str){
	return str.replace(/\s*$/, "");
}
 



function abreConsulta(url, nome_janela){
	var largura = 800, altura = 600;
	if (nome_janela==null) nome_janela="";
	var janela = window.open(url,nome_janela,"width=" + largura + ",height=" + altura);
	janela.moveBy(0,0);
}

function abrePopUp(url, largura, altura, barraRolagem){    
	if (barraRolagem == true)
        barraRolagem = "yes"
    else
        barraRolagem = "no"
    window.open(url,"","toolbar=no,location=no,status=no,menubar=no,scrollbars=" + barraRolagem + ",resizable=no,directories=no,width=" + largura + ",height=" + altura+",left=200,top=100");
}

function arredonda( valor , casas ){
   var novo = Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );
   return( novo );
}

function ajustaCasasDecimais(strNumero){
	var LocVirgula = strNumero.indexOf(',');
	var myNum = strNumero;
	var myDec = "";

	if (LocVirgula > -1){
		myNum = strNumero.substring(0,LocVirgula);
		myDec = strNumero.substring(LocVirgula);
		//alert (myNum + " - " + myDec + " - " + myDec.length);
		if (myDec.length==1)
			myDec += "00";
		else if (myDec.length==2)
			myDec += "0";
		//alert (myNum + " - " + myDec + " - " + myDec.length);
	}else{
		myNum = strNumero;
		myDec = ",00";
	}
	return myNum + myDec;
}

function formataNumero(num){
	var retorno = "";
	num = Arredonda(num,2);
	var n = Math.floor(num);
	var myNum = num + "";
	var myDec = ""
 	
	if (myNum.indexOf('.',0) > -1){
		myDec = myNum.substring(myNum.indexOf('.'));
		myDec = TrocaPic(myDec, ".", ",");
	}
	var arr=new Array('0'), i=0; 
	while (n>0){
		arr[i]=''+n%1000; 
		n=Math.floor(n/1000); 
		i++;
	}
 	arr=arr.reverse();
 	for (var i in arr){ 
		if (i>0){ //padding zeros
  	 		while (arr[i].length<3){ 
				arr[i]='0'+arr[i];
			}
		}
	}
	//alert (arr.join('.'));
	retorno = AjustaCasasDecimais(arr.join('.') + myDec);
 	return retorno;
}

function TiraPic(Valor, ValorTirar){
	return Valor.replace(ValorTirar,"");
}

function TrocaPic(Valor, ValorTrocar, ValorPor){
	return Valor.replace(ValorTrocar, ValorPor);
}

function cNumero(Valor){
	var retorno=Trim(Valor);
	retorno = TiraPic(retorno,".");
	retorno = TrocaPic(retorno, ",", ".");
	if (!ENumero(retorno))
		retorno="0";
	return retorno;
}




function eEmail(str){
	if (str.indexOf('@', 0) == -1) 
		return false;
	return true;
}


// Verifica se a Data digitada é válida
function EDataValida(vfield, vfieldName){
	var diaStr, mesStr, anoStr
	var diaInt, mesInt, anoInt
	var tam, sep1, sep2, verAno
	
	tam = vfield.value.length;

	sep1 = parseInt(vfield.value.indexOf("/", 0));

	if (sep1<0)	{
		alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
		return false;
	}

	sep2 = parseInt(vfield.value.indexOf("/", sep1+1));

	if (sep2<5){
		alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
		return false;
	}

	verAno = tam-sep2;

	if(verAno < 5 )	{
		alert("As datas devem ser preenchidas utilizando 4 dígitos para informar o Ano (ex.: DD/MM/AAAA)!");
		return false;
	}

	diaStr = vfield.value.substring(0, sep1);

	if(diaStr.substring(0, 1) == "0")
	diaStr = diaStr.substring(1, 2);

	if (isValidNumberValue(diaStr, vfieldName))	{
		mesStr = vfield.value.substring(sep1+1, sep2); 

		if(mesStr.substring(0, 1) == "0")
		mesStr = mesStr.substring(1, 2);

		if (isValidNumberValue(mesStr, vfieldName))	{
			anoStr = vfield.value.substring(sep2+1, tam);
		
			if (isValidNumberValue(anoStr, vfieldName)){
				diaInt = parseInt(diaStr);
				mesInt = parseInt(mesStr);
				anoInt = parseInt(anoStr);
	
				if ((diaInt <= 0) || (diaInt > 31))	{
					alert("O dia informado não é válido!");
					return false;
				}
	
				if ((mesInt <= 0) || (mesInt > 12)){
					alert("O mês informado não é válido!");
					return false;
				}

				if ((mesInt == 4) || (mesInt == 6) || (mesInt == 9) || (mesInt == 11)){
					if( diaInt > 30){
						alert("O mês informado não possui mais de 30 dias!");
						return false;
					}
				}

				if (mesInt == 2){
					if ((anoInt % 4 == 0) && ( (anoInt % 100 != 0) || (anoInt % 400 == 0))){
						if (diaInt > 29){
							alert("O mês informado não possui mais de 29 dias!");
							return false;
						}
					}else{
						if(diaInt > 28){
							alert("O mês informado não possui mais de 28 dias!");
							return false;
						}
					}
					return true;
				} 
				return true;
			}else return false;
		}else return false;
	}else return false;
}

 
function eInteiro(Valor)
{   var i=0;
    if (EVazio(Valor)) 
       if (EInteiro.arguments.length == 1) return (false);
       else return (EInteiro.arguments[1] == true);
    
    for (i = 0; i < Valor.length; i++)
    {   
        var c = Valor.charAt(i);
        if( i != 0 ) {
            if (!EDigito(c)) return (false);
        } else { 
            if (!EDigito(c) && (c != "-") || (c == "+")) return (false);
        }
    }
    return (true);
}
function eDigito(c){
	return ((c >= "0") && (c <= "9"));
}

function eVazio(Valor) {
	if (Valor=="" || Valor==null){
		return (true);
	}
	return (false);
}

function validaCampo(Campo, NomeCampo, classe) {
	if (!eVazio(Campo.value) && Campo.value != NomeCampo){
		Campo.className = "";
		return true;
	}
	if (Campo.tagName.toLowerCase() == "select")
		if (!Campo.value == "0")
			return true;
	
	document.getElementById("alerta").className = "display-ativado";
	Campo.className = classe;
	Campo.focus();
	return false;
		
}

function ajustaImagem(objetoImagem) {
	maiorLargura = 300;
	maiorAltura = 200;
	
	larguraReal = objetoImagem.width;
	alturaReal = objetoImagem.height;
		
	novaLargura = maiorLargura;
	novaAltura = (maiorLargura * alturaReal) / larguraReal;
	
	if (novaAltura > alturaReal) {
		novaAltura = alturaReal;
		novaLargura = (larguraReal * alturaReal) / alturaReal;
	}
	//alert(larguraReal + "x" + alturaReal)
	//objetoImagem.width = novaLargura;
	//objetoImagem.height = novaAltura;
}


function redirect(caminho,valor){
	window.location=caminho+valor;	
}

function formatarCampo(src,mask,e,limite) {
	var i = src.value.length;
    var strCheck = '0123456789';
	var saida = mask.substring(0,1);
	var texto = mask.substring(i)
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	switch(e.keyCode){
		case 9:
				switch(mask){
					case '###.###.###-##'		: if(validaCpf(src))	return true; else{alert("CPF inválido!");	src.value="";	return false;}
					//case '##.###.###/####-##'	: if(validaCnpj(src))	return true; else{alert("CNPJ inválido!");	src.value="";	return false;}
				}
				return true;
	}
	
	switch(whichCode){
		case 0:return true;
		case 8:return true;
		case 9:return true;
		case 13:return true;
	}
    
	
	key = String.fromCharCode(whichCode);

	if (strCheck.indexOf(key) == -1){
        return false;  //NÃO E VALIDO
    }

	if(i>=limite){
        return false;    //impede de digitar
    }
	
	if (texto.substring(0,1) != saida){
		src.value += texto.substring(0,1);
	}
	
}


function verificaValidacao(elemento){
	switch(elemento){
		case 'cpf':	
				if(!validaCpf(document.getElementById(elemento))){
					alert("CPF inválido!");
					document.getElementById(elemento).value="";
					src.value="";
				}
				break;
		case 'cnpj': 
				if(!validaCnpj(document.getElementById(elemento))){
					alert("CNPJ inválido!");	
					document.getElementById(elemento).value="";
					src.value="";	
				}
				break;
	}
}

function displaySelect(dado,lista){
	
	var longstring	= lista;
	var dadoslista	= longstring.split(";");
	
	for (var i=0; i<dadoslista.length; i++)
		document.getElementById(dadoslista[i]).style.display = "none";
		
	if (document.getElementById(dado).style.display == "none")
		document.getElementById(dado).style.display = "";
	else
		document.getElementById(dado).style.display = "none";
	
}

function FormataReais(fld, e) {
	
	var milSep = ".";
	var decSep = ",";

	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;
	
	switch(whichCode){
		case 8:return true;
		case 9:return true;
		case 13:return true;
	}
	
	
		key = String.fromCharCode(whichCode);// Valor para o código da Chave
	
	if (strCheck.indexOf(key) == -1) return false; // Chave inválida
	
		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);
	
	}
	
	return false;

} 

function formatarArea(src,e,limite) {
	
	var i = src.value.length;
	var whichCode = (window.Event)?e.which:e.keyCode;
	//alert(whichCode);
	
	switch(whichCode){
		case 8:return true;
		case 9:return true;
		case 13:return true;
		case 46:return true;
		case 44:return true;
	}
	
    if(i>=limite)
        return false;    //impede de digitar
    
	if (whichCode > 47 && whichCode < 58)
		return true;
	else
		return false;
    
	
}

function viewDivCheck(nome,div){
	elemento = document.getElementById(div);
	if(nome == "1"){
		if(elemento.className == "display-ativado"){
			elemento.className = "display-desativado";
		}else{
			elemento.className = "display-ativado";
		}
	}else {
		elemento.className = "display-ativado";
	}
}

function viewDiv(selecao, opcao, div){
	elemento = document.getElementById(div);
	if(opcao == selecao){
		elemento.className = "display-ativado";	
	}else {
		elemento.className = "display-desativado";
	}
}

function viewDivClick(div, hidden){
		
		if(hidden){
			elemento = document.getElementById(hidden);
			elemento.value = 1;
		}
		elemento = document.getElementById(div);
			elemento.className = "display-ativado";	
}

var HTTP = {

    init : false,
    GetVars: new Array(),

    __construct : function() {

        var uri = window.location.href;

        if(uri.indexOf('?') == -1)
            return false;

        var parts = uri.split('?');
        var xv = parts[1].split('&');

        for(var i=0; i < xv.length; i++) {
            var get = xv[i].split('=');
            HTTP.GetVars[get[0]] = get[1];
        }

        this.init = true;
    },

    GET : function(v) {

        if(this.init == false)
            this.__construct();

        if(!this.GetVars[v])
            return false;

        return this.GetVars[v];
    }
}

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

var Utf8 = {

    // public method for url encoding
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
