//FUNÇÃO DE MASCARA TIPO MOEDA
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
	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;
	key = String.fromCharCode(whichCode); // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false; // Chave inválida
	len = objTextBox.value.length;
	for(i = 0; i < len; i++)
	if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) objTextBox.value = '';
	if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
	if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += SeparadorMilesimo;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		objTextBox.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		objTextBox.value += aux2.charAt(i);
		objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
	}
	return false;
}

function maskmoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    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;    
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc    
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
    	return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
 
 
    if (strCheck.indexOf(key) == -1) 
    	return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) 
        	break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) 
        	aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) 
    	objTextBox.value = '';
    if (len == 1) 
    	objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) 
    	objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        	objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

//FUNÇÃO DE MASCARA DE DATA
function mascara_data(DATA){
	var mydata = '';
	mydata = mydata + DATA.value;
	if (mydata.length == 2){
		mydata = mydata + '/';
		DATA.value = mydata;
	}
	if (mydata.length == 5){
		mydata = mydata + '/';
		DATA.value = mydata;
	}

}


//FUNÇÃO PARA VALIDART DATA
function check_date(DATA) {
	if(DATA.value=='')return false;
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	var msgErro = 'Formato inválido de data.(DD/MM/AAAA)';
	var vdt = new Date();
	var vdia = vdt.getDay();
	var vmes = vdt.getMonth();
	var vano = vdt.getYear();
	if ((DATA.value.match(expReg)) && (DATA.value!='')){
		var dia = DATA.value.substring(0,2);
		var mes = DATA.value.substring(3,5);
		var ano = DATA.value.substring(6,10);
		if((mes==4 && dia > 30) || (mes==6 && dia > 30) ||
		(mes==9 && dia > 30) || (mes==11 && dia > 30)){
			alert("Dia incorreto !!! O mês especificado contém no máximo 30 dias.");
			DATA.focus();
			return false;
		} else{ //1
			if(ano%4!=0 && mes==2 && dia>28){
				alert("Data incorreta!! O mês especificado contém no máximo 28 dias.");
				DATA.value = '';
				DATA.focus();
				return false;
			} else{ //2
				if(ano%4==0 && mes==2 && dia>29){
					alert("Data incorreta!! O mês especificado contém no máximo 29 dias.");
					DATA.value = '';
					DATA.focus();
					return false;
				} else{ //3

					return true;

				} //3-else
			}//2-else
		}//1-else
	} else { //5
		alert(msgErro);
		//DATA.value = '';
		DATA.focus();
		return false;
	} //5-else
}



//função mascara dinheiro onKeyDown="FormataValor(this.id, 13, event)"
function FormataValor(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = document.getElementById(campo).value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;
	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 <= 2 ){
			document.frm_orcamento[campo].value = vr; }
			if ( (tam > 2) && (tam <= 5) ){
				document.frm_orcamento[campo].value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); }
				if ( (tam >= 6) && (tam <= 8) ){
					document.frm_orcamento[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
					if ( (tam >= 9) && (tam <= 11) ){
						document.frm_orcamento[campo].value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
						if ( (tam >= 12) && (tam <= 14) ){
							document.frm_orcamento[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 - 2, tam ); }
							if ( (tam >= 15) && (tam <= 17) ){
								document.frm_orcamento[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 );}
	}
}


//FUNÇÃO QUE ACEITA SOMENTE NÚMEROS TELEFÔNICOS
function SoNumeroTel(evtKeyPress, objeto) {
	var nTecla;
	nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode;

	mascara_telefone(objeto);
	
	if((nTecla > 47 && nTecla < 58) || nTecla == 9)
	return true;
	else
	{
		if (nTecla != 8)
		return false;
		else
		return true;
	}
}

//FUNÇÃO QUE ACEITA SOMENTE NÚMEROS
function SoNumero(evtKeyPress) {
	var nTecla;
	nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode;

	if((nTecla > 47 && nTecla < 58) || nTecla == 9)
	return true;
	else
	{
		if (nTecla != 8)
		return false;
		else
		return true;
	}
}


//FUNÇÃO COMPARA DATAS
function ComparaData()
{
	var data1 = document.getElementById("dtinicio").value;
	var data2 = document.getElementById("dtfim").value;

	if (data1 == '' || data2 == '')
	{
		if (data2 == '')
		{
			alert("Preencha a Data Final!");
			document.getElementById("dtfim").focus();
		}
		return false;
	}

	var nova_data1 = parseInt(data1.split("/")[2].toString() + data1.split("/")[1].toString() + data1.split("/")[0].toString());
	var nova_data2 = parseInt(data2.split("/")[2].toString() + data2.split("/")[1].toString() + data2.split("/")[0].toString());

	if (nova_data2 > nova_data1)
	{
		return true;
	}
	else if (nova_data1 == nova_data2)
	{
		return true;
	}
	else
	{
		alert("Data Inicial deve ser menor que Data Final.");
		document.getElementById("dtinicio").focus();
		return false;
	}
	return true;
}

function ContaTelefone()
{
	var telefone1 = document.getElementById("telresp").value;
	var telefone2 = document.getElementById("telefone").value;

	if(telefone2.length < 13)
	{
		alert("Preencha o telefone da seguinte forma: (xx)xxxx-xxxx.");
		document.getElementById("telefone").focus();
		return false;
	}
	if(telefone1.length < 13)
	{
		alert("Preencha o telefone do responsável da seguinte forma: (xx)xxxx-xxxx.");
		document.getElementById("telresp").focus();
		return false;
	}
	return true;
}

function validaForm(formulario)
{
	for(i=0;i<=formulario.length-1;i++)
	{
		if ((formulario[i].type=="textarea") || (formulario[i].type=="file") ||
		(formulario[i].type=="radio") || (formulario[i].type=="text") ||
		(formulario[i].type=="password") || (formulario[i].type=="checkbox") || 
		(formulario[i].type=="select-one"))
		{
			if ((formulario[i].title!="") && (formulario[i].title!=undefined))
			{
				if(formulario[i].value=="" || formulario[i].value==0)
				{
					alert(formulario[i].title);
					try
					{
						formulario[i].focus();
					}
					catch(e){}
					return false
				}
				else
				{
					if(formulario[i].title=="Preencha a Data de início")
					{
						if (!ComparaData())
						{
							return false;
						}
					}
					if(formulario[i].title=="Preencha o telefone da seguinte forma: (xx)xxxx-xxxx.")
					{
						if (!ContaTelefone())
						{
							return false;
						}
					}
				}
			}
		}
	}
	return true;
}

// JavaScript Document
function copiarfield(theField,msgsn) {
	//var tempval=eval("document."+theField)
	tempval = theField
	tempval.focus()
	tempval.select()
	therange=tempval.createTextRange()
	therange.execCommand("Copy")
	if(msgsn){alert("Copiado com sucesso agora é só colar")}
}
function Travaint(val)
{

	//Para travar basta colocar esse evento en um campo qualquer: onKeyPress="Travafloat(this)"
	testt = event.keyCode;

	//alert (n)
	//alert(testt);
	if (!(testt>=48 && testt<=57)) //in[48,49,50,51,52,53,54,55,56,57,46])
	{
		event.keyCode = 0;
	}

}

function abrirpop(url,nome,w,h,s){
	janela = window.open(url,nome,'width='+w+',height='+h+',top=1,left=1,scrollbars='+s+',toolbar=no,menubar=no,status=no,location=no,resizable=no');
	janela.focus();
}

function jczResetWindow(bmp)
{
	self.moveTo(2,2);
	self.resizeTo(bmp.width+50,bmp.height+130);
}

function formatar(src, mask, proxfoco)
{
	var i = src.value.length;
	var saida = mask.substring(0,1);
	var texto = mask.substring(i)
	if (texto.substring(0,1) != saida)
	{
		src.value += texto.substring(0,1);
	}
	if(i >= mask.length)
	proxfoco.focus();
}


//FUNÇÃO QUE MOSTRA UMA CAIXA DE CONFIRMAÇÃO, CASO VERDADEIRO VAI PRA PÁGINA PASSADA COMO PARÂMETRO
function confirma(texto,pagina){
	var resposta=confirm(texto);
	if (resposta==true) {
		if(pagina)
		window.location.href=pagina;
		return true;
	}
	return false;
}

//FUNÇÃO PARA VALIDAR E-MAILS
function checkMail(EMAIL){
	if(EMAIL.value=='') return false;
	var str = EMAIL.value;
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if(filter.test(str))
	valido = true;
	else{
		alert("Este endereço de e-mail não é válido!");
		EMAIL.value='';
		EMAIL.focus();
		valido = false;
	}
	return valido;
}


function mascara_telefone(objeto){
	
	
	if(objeto.value.length == 0)
	objeto.value = '(' + objeto.value;

	if(objeto.value.length == 3)
	objeto.value = objeto.value + ')';

	if(objeto.value.length == 8)
	objeto.value = objeto.value + '-';
}
//validação de CNPJ
function validaCNPJ(CNPJID) 
{
	if(CNPJID.value!='')
	{
		CNPJ = CNPJID.value;
		erro = new String;
		if (CNPJ.length < 18){ erro += "É necessario preencher corretamente o número do CNPJ! \n\n";}
		if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
		{
			if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";

		}
		//substituir os caracteres que não são números
		if(document.layers && parseInt(navigator.appVersion) == 4)
		{
			x = CNPJ.substring(0,2);
			x += CNPJ. substring (3,6);
			x += CNPJ. substring (7,10);
			x += CNPJ. substring (11,15);
			x += CNPJ. substring (16,18);
			CNPJ = x;
		} 
		else 
		{
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace ("-","");
			CNPJ = CNPJ. replace ("/","");
		}
		
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n";
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++)
		{
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		for (y=0; y<13; y++) {
			b += (a[y] * c[y]);
		}
		if ((x = b % 11) < 2) { a[13] = 0; } 
		else { a[13] = 11-x; }
		/*
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13]) || parseInt(CNPJID.value)==0)
		{
			erro +="CNPJ Inválido!";
		}
		*/
		if (erro.length > 0)
		{
			alert(erro);
			return false;
		}
		return true;
	}
	return false;
}

//mascara para cnpj
function FormataCNPJ(Campo, teclapres)
{

	if(window.event){
		var tecla = teclapres.keyCode;
	}else  tecla = teclapres.which;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1;


	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
		Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
		Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
		Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
		Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
	}
}


function mostrar(nomeCamada){
	document.getElementById(nomeCamada).style.visibility="visible";
}
function ocultar(nomeCamada){
	document.getElementById(nomeCamada).style.visibility="hidden";
}


function menu(nomeCamada){
	if(document.getElementById(nomeCamada).style.visibility=='visible'){
		ocultar(nomeCamada);
		document.getElementById(nomeCamada).style.position='absolute';
	}
	else{
		mostrar(nomeCamada);
		document.getElementById(nomeCamada).style.position='';
	}

}

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


function mostrar_ocultar(nomeCamada, tipodisplay, camada_retorno)
{
	if(document.getElementById(nomeCamada).style.display=='none')
	{
		document.getElementById(nomeCamada).style.display = tipodisplay;
		document.getElementById(camada_retorno).innerHTML = '[-]';
	}
	else
	{
		document.getElementById(nomeCamada).style.display = 'none';
		document.getElementById(camada_retorno).innerHTML = '[+]';
	}
}

