function camposObrigatorios(which) 
{
	if (document.images) 
	{
		for (i=0;i<which.length;i++) 
		{
			var objeto=which.elements[i];
			if (objeto.getAttribute('obrigatorio')!=null) 
			{
				if (((objeto.type=="text" || objeto.type=="textarea" || objeto.type=="password" || objeto.type=="file") && objeto.value=='') || (objeto.type.toString().charAt(0)=="s" && objeto.selectedIndex==0)) 
				{
					alert("O campo '"+objeto.getAttribute('obrigatorio')+"' deve ser preenchido.");
					objeto.focus();
					return false;
				}
			}
		}
	}
	return true;
}

function validaCPF(cpf)
{
	var numeros, digitos, soma, i, resultado, filtro = cpf.value;

	filtro = filtro.replace(/\./g,"");
	filtro = filtro.replace(/\-/g,"");

	if ((filtro.length > 0 && filtro.length < 11) || filtro == "00000000000" || filtro == "11111111111" || filtro == "22222222222" || filtro == "33333333333" || filtro == "44444444444" || filtro == "55555555555" || filtro == "66666666666" || filtro == "77777777777" || filtro == "88888888888" || filtro == "99999999999")
	{
		alert("CPF inválido. Tente novamente.");
		cpf.value="";
		cpf.focus();
		return false;
	}
	
	numeros = filtro.substring(0,9);
	digitos = filtro.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))
	{
		alert("CPF inválido. Tente novamente.");
		cpf.value="";
		cpf.focus();
		return false;
	}
	numeros = filtro.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))
	{
		alert("CPF inválido. Tente novamente.");
		cpf.value="";
		cpf.focus();
		return false;
	}
	
	return true;
}

function validaCNPJ(cnpj)
{
	var numeros, digitos, soma, i, resultado, pos, tamanho, filtro = cnpj.value;

	filtro = filtro.replace(/\./g,"");
	filtro = filtro.replace(/\//g,"");
	filtro = filtro.replace(/\-/g,"");

	if (filtro.length != 14 || filtro == "00000000000000" || filtro == "11111111111111" || filtro == "22222222222222" || filtro == "33333333333333" || filtro == "44444444444444" || filtro == "55555555555555" || filtro == "66666666666666" || filtro == "77777777777777" || filtro == "88888888888888" || filtro == "99999999999999") 
	{
		alert("CNPJ inválido. Tente novamente.");
		cnpj.value="";
		cnpj.focus();
		return false;
	}

	tamanho = filtro.length - 2
	numeros = filtro.substring(0,tamanho);
	digitos = filtro.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))
	{
		alert("CNPJ inválido. Tente novamente.");
		cnpj.value="";
		cnpj.focus();
		return false;
	}
	tamanho = tamanho + 1;
	numeros = filtro.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))
	{
		alert("CNPJ inválido. Tente novamente.");
		cnpj.focus();
		return false;
	}
	return true;
} 

function validaCEP(cep)
{
	if(cep.value.length>0 && cep.value!='__.___-___')
	{
		exp = /\d{2}\.\d{3}\-\d{3}/;
		if(!exp.test(cep.value))
		{
			alert('CEP Invalido. Tente novamente!');
			cep.focus();
			return false;
		}
	}
	return true;
}

function validaFone(fone)
{
	if(fone.value.length>0)
	{
		exp =  /\(?\d{2}\) ?\d{4}-\d{4}/;
		if(!exp.test(fone.value))
		{
			alert('Telefone Invalido. Tente novamente!');
			fone.focus();
			return false;
		}
	}
	return true;
}

function validaCelular(celular)
{
	if(celular.value.length>0)
	{
		exp =  /\(?\d{2}\) ?\d{4}-\d{4}/;
		if(!exp.test(celular.value))
		{
			alert('Celular Invalido. Tente novamente!');
			celular.focus();
			return false;
		}
	}
	return true;
}

function validaData(data)
{
	if(data.value.length>0)
	{
		exp = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
		if(!exp.test(data.value))
		{
			alert('Data Invalida. Tente novamente!');
			data.focus();
			return false;
		}
	}
	return true;
}

function validaHora(hora)
{
	if(hora.value.length>0)
	{
		exp = /^([0-1]\d|2[0-3]):[0-5]\d$/;
		if(!exp.test(hora.value))
		{
			alert('Hora Invalida. Tente novamente!');
			hora.focus();
			return false;
		}
	}
	return true;
}

function validaDataHora(dataHora)
{
    exp = /^([0-1]\d|2[0-3]):[0-5]\d$/;
    if(!exp.test(dataHora.value))
	{
        alert('Data Hora Invalida. Tente novamente!');
		dataHora.focus();
		return false;
	}
	return true;
}

function validaEmail(email)
{
	if(email.value.length>0)
	{
		exp = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if(!exp.test(email.value))
		{
			alert('E-mail Invalido. Tente novamente!');
			email.focus();
			return false;
		}
	}
	return true;
}

function mascaraCampo(tipo, campo, event) 
{
	if (window.event)
        tecla = event.keyCode;
	else 
        tecla = event.which;

	var s = new String(campo.value);
    // Remove todos os caracteres a seguir: ( ) / - . e espaço, para tratar a string denovo.
    s = s.replace(/(\.|\(|\)|\/|\-| )+/g,'');
    s = s.replace(",",'');

    tam = s.length + 1;

	if ( (tecla < 48 || tecla > 57) &&  tecla != 9 && tecla != 8 && tecla != 0 )
		return false;

    if ( tecla != 9 && tecla != 8 && tecla != 0 ) 
	{
        switch (tipo)
        {
			case 'CPF' :
				if (tam > 3 && tam < 7)
					campo.value = s.substr(0,3) + '.' + s.substr(3, tam);
				if (tam >= 7 && tam < 10)
					campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,tam-6);
				if (tam >= 10 && tam < 12)
					campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9);
				if (tam > 11)                
					campo.value = campo.value.substr(0,campo.value.length-1);                            
			break;
	
			case 'CNPJ' :
	
				if (tam > 2 && tam < 6)
					campo.value = s.substr(0,2) + '.' + s.substr(2, tam);
				if (tam >= 6 && tam < 9)
					campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,tam-5);
				if (tam >= 9 && tam < 13)
					campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,tam-8);
				if (tam >= 13 && tam < 15)
					campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,4)+ '-' + s.substr(12,tam-12);
				if (tam > 14)                
					campo.value = campo.value.substr(0,campo.value.length-1);            
			break;
	
			case 'FONE' :
				if (tam > 2 && tam < 4)
					campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,tam);
				if (tam >= 7 && tam < 11)
					campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,4) + '-' + s.substr(6,tam-6);
				if (tam > 10)                
					campo.value = campo.value.substr(0,campo.value.length-1);            
			break;
	
			case 'DATA' :
				if (tam > 2 && tam < 4)
					campo.value = s.substr(0,2) + '/' + s.substr(2, tam);
				if (tam > 4 && tam < 11)
					campo.value = s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4);
				if (tam > 8)                
					campo.value = campo.value.substr(0,campo.value.length-1); 
			break;
			
			case 'HORA' :
				if (tam > 2 && tam < 4)
					campo.value = s.substr(0,2) + ':' + s.substr(3, 3);
				if (tam > 5)                
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;
	
			case 'CEP' :
				if (tam > 2 && tam < 4)
					campo.value = s.substr(0,2) + '.' + s.substr(3, 3);
				if (tam > 5 && tam < 7)
					campo.value = s.substr(0,2) + '.' + s.substr(2, 3) + '-' + s.substr(5, tam);
				if (tam > 8)                
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;

			case 'VALOR' :		
				if ( (tam > 2) && (tam <= 5) )
					campo.value = s.substr( 0, tam - 2 ) + "," + s.substr( tam - 2, tam ) ; 
				if ( (tam >= 6) && (tam <= 8) )
					campo.value = s.substr( 0, tam - 5 ) + "." + s.substr( tam - 5, 3 ) + "," + s.substr( tam - 2, tam ) ; 
				if ( (tam == 9))
					campo.value = s.substr( 0, tam - 8 ) + "." + s.substr( tam - 8, 3 ) + "." + s.substr( tam - 5, 3 ) + "," + s.substr( tam - 2, tam ) ; 
				if (tam > 9)
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;

			case 'VALORPORCENTAGEM' :
				if ( (tam > 2) && (tam <= 5) )
					campo.value = s.substr( 0, tam - 2 ) + "," + s.substr( tam - 2, tam ) ; 
				if(tam > 5)
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;

			case 'VALORPORCENTAGEM2' :
				if (tam == 2)
					campo.value = s.substr( 0, 1 ) + "," + s.substr( 1 , 1 ) ; 
				if (tam == 3)
					campo.value = s.substr( 0, 2) + "," + s.substr( 2 , 1 ) ; 
				if (tam == 4)
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;

			case 'VALORPORCENTAGEM3' :
				if ( (tam > 2) && (tam <= 4) )
					campo.value = s.substr( 0, tam - 2 ) + "," + s.substr( tam - 2, tam ) ; 
				if(tam > 4)
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;

			case 'VALORPORCENTAGEM4' :
				if (tam == 2)
					campo.value = s.substr( 0, 1 ) + "," + s.substr( 1 , 1 ) ; 
				if (tam == 3)
					campo.value = s.substr( 0, 1 ) + "," + s.substr( 1 , 2 ) ; 
				if (tam == 4)
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;

			case 'VALORPORCENTAGEM5' :
				if ( (tam > 2) && (tam <= 5) )
					campo.value = s.substr( 0, tam - 2 ) + "," + s.substr( tam - 2, tam ) ; 
				if ( (tam > 5) && (tam <= 7) )
					campo.value = s.substr( 0, tam - 5 ) + "." + s.substr( tam - 5, 3 ) + "," + s.substr( tam - 2, tam ) ; 
				if(tam > 7)
					campo.value = campo.value.substr(0,campo.value.length-1);
			break;
		}
    }
	return ( ( ( tecla > 47 ) && ( tecla < 58 ) ) || ( tecla == 8 ) || ( tecla == 13 ) || ( tecla == 0 ) );
}

function somenteNumeros(event)
{
    if (window.event)
		key = event.keyCode;
    else 
	{
		if ( event.which ) 
        	key = event.which;
	}

	if ( key != 8 || key != 13 || key < 48 || key > 57 )
        return ( ( ( key > 47 ) && ( key < 58 ) ) || ( key == 8 ) || ( key == 13 ) );
    
	return true;
}

function redireciona(tempo, url, id)
{
	document.getElementById(id).innerHTML = tempo;
	tempo--;
	if(tempo == -1)
  		location.href = url;
	var nr = 'setTimeout("redireciona('+tempo+',\''+url+'\',\''+id+'\')",1000)';
	eval(nr);
}

function avisoConfirmacao(mensagem) 
{
	if(mensagem==undefined)
		mensagem='Confirma exclusão?';
	if(confirm(mensagem)){
		this.href;
		return true;
	}else{
		return false;
	}
}

function uploadArquivo(form, url_action, id_elemento_retorno, html_exibe_carregando, html_erro_http)
{
	//testando se passou o ID ou o objeto mesmo
	form = typeof(form)=="string"?document.getElementById(form):form;

	var erro="";
	if(form==null || typeof(form)=="undefined")
	{ 
		erro += "O form passado no 1o parâmetro não existe na página.\n";
	}
	else if(form.nodeName!="FORM")
	{ 
		erro += "O form passado no 1o parâmetro da função não é um form.\n";
	}
	if(document.getElementById(id_elemento_retorno)==null)
	{ 
		erro += "O elemento passado no 3o parâmetro não existe na página.\n";
	}
	if(erro.length>0) 
	{
		alert("Erro ao chamar a função Upload:\n" + erro);
		return;
	}

	//criando o iframe
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","upload-temp");
	iframe.setAttribute("name","upload-temp");
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","0");
	iframe.setAttribute("style","width: 0; height: 0; border: none;");
	
	//adicionando ao documento
	form.parentNode.appendChild(iframe);
	window.frames['upload-temp'].name="upload-temp"; //ie sucks

	//adicionando o evento ao carregar
	var carregou = function() 
	{ 
		if ( document.getElementById('upload-temp').detachEvent ) 
			document.getElementById('upload-temp').detachEvent( 'onload', carregou );
		else 
			document.getElementById('upload-temp').removeEventListener( 'load', carregou, false ); 
		
		var cross = "javascript: ";
		cross += "window.parent.document.getElementById('" + id_elemento_retorno + "').innerHTML = document.body.innerHTML; void(0); ";

		document.getElementById(id_elemento_retorno).innerHTML = html_erro_http;
		document.getElementById('upload-temp').src = cross;
		//deleta o iframe
		setTimeout(function(){ document.getElementById('upload-temp').parentNode.removeChild(document.getElementById('upload-temp'))}, 250);
	}

	if (document.getElementById('upload-temp').addEventListener)
        document.getElementById('upload-temp').addEventListener("load", carregou, true)
    if (document.getElementById('upload-temp').attachEvent)
        document.getElementById('upload-temp').attachEvent("onload", carregou)

	//setando propriedades do form
	form.setAttribute("target","upload-temp");
	form.setAttribute("action",url_action);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	//submetendo
	form.submit();
	
	//se for pra exibir alguma imagem ou texto enquanto carrega
	if(html_exibe_carregando.length > 0)
	{
		document.getElementById(id_elemento_retorno ).innerHTML = html_exibe_carregando;
	}
	form.reset();
}

function umCheckboxSelecionado(campo, mensagem)
{
	var checkbox = getElementsByname(campo);
	
	for (i=0; i<checkbox.length; i++)    
	{ 
    	if (checkbox[i].checked) 
			return true;
	}
    alert(mensagem);
    return false;
}

function umCheckboxSelecionado2(mensagem)
{
	if(($(":checkbox:checked").length)==0)
	{
		alert(mensagem);
		return false;
	}
}

function ocultar(id) 
{
	document.getElementById(id).style.display = "none";
}

function mostrar(id) 
{
	document.getElementById(id).style.display = "";
}

function limitaTextArea(campo, contador, numero) 
{
	if (campo.value.length>numero)
		campo.value = campo.value.substring(0, numero);
	else 
		contador.value=numero-campo.value.length;
}

function calculaPorcentagem(valor, porcentagem)
{
	porcentagem = porcentagem.replace(",",".");

	if(valor>0 && porcentagem>0)
		return Math.round(valor*porcentagem/100);
	else
		return 0;
}

function float2moeda(num) 
{
	x = 0;

	if(num<0) 
	{
		num = Math.abs(num);
		x = 1;
	} 
	if(isNaN(num)) 
		num = "0";
	cents = Math.floor((num*100+0.5)%100);

	num = Math.floor((num*100+0.5)/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)); 
	ret = num + ',' + cents; 
	if (x == 1) 
		ret = ' - ' + ret;
	return ret;

}

// Função para iniciar o Ajax no browser do cliente.
function openAjax() {
	var ajax;

	try {
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	} 
	catch(e) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(ex) {
			try {
				ajax = new XMLHttpRequest();
			}
			catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				ajax = null;
			}
		}
	}
	return ajax;
}
