//
//		Funções genéricas.
//
var hoje = new Date();		

dia = hoje.getDate();
mes = hoje.getMonth()+1; /* No JS, os meses são 0-11 */
ano = hoje.getFullYear(); /* getFullYear() para 2006, getYear() para 106 */

if(dia < 10) dia = '0'+dia;
if(mes < 10) mes = '0'+mes;

hora = hoje.getHours();
minutos = hoje.getMinutes();

//	Variavel para tratamento de browser.
var browser = navigator.appName;

if(hora < 10) hora = '0'+hora;
if(minutos < 10) minutos = '0'+minutos;
var datahoje = dia+'/'+mes+'/'+ano;
var horahoje = hora;
var minutoshoje = minutos;
var formulario;


function verificavazio(obj) {
	valor = obj.value;
	if (valor == "") {
		alert('Atenção:\n Campo '+obj.name+' não pode estar em branco.');
		obj.focus();
		return false;
	}
	return true;
}

function verificainject(obj) {
		var inject = "\"'#*\&/"; // variavel com caracteres invalidos invalidas
		for(i=0; i<inject.length; i++)
		{
			if(obj.value.indexOf(inject.charAt(i)) >= 0)
			{
			alert("Carácteres inválidos no campo ''"+obj.name+"'',\n favor corrigir. (Ex.\",',#,*,\\,& e /)");
			obj.focus();
			return false;
			}
		}
		return true;
}

function checanumero(nome)
{
	var checkOK = "0123456789";
	var checkStr = nome.value;
	var allValid = true;
	for (i = 0; i < checkStr.length; i++) {
		ch = checkStr.charAt(i);
		for (j = 0; j < checkOK.length; j++)
			if (ch == checkOK.charAt(j))
			break;
			if (j == checkOK.length) {
				allValid = false;
				break;
			}
		}
		if (!allValid) {
			alert("Digite apenas numeros no campo ''"+nome.name+"''");
			nome.focus();
			return (false);
		}
}


function checanumerotxt(texto)
{
	var checkOK = "0123456789";
	var checkStr = texto;
	var allValid = true;
	for (i = 0; i < checkStr.length; i++) {
		ch = checkStr.charAt(i);
		for (j = 0; j < checkOK.length; j++)
			if (ch == checkOK.charAt(j))
			break;
			if (j == checkOK.length) {
				allValid = false;
				break;
			}
		}
		if (!allValid) {
			return (false);
		}
		return true;
}


function FormataData(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
		if (tam >= 5 && tam <=10)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,4);
		}
	}
	
function formataCpf(idCampo, evento){
		var campo = document.getElementById(idCampo);
		var auxCampo = campo.value;
		var valorCampo = campo.value;
		var teclaCode;
		var aceita = true;
		
		try {
			teclaCode = event.keyCode;
		} catch (e) {
			try {
				teclaCode = evento.which;
			} catch (ex) {
				alert('ocorreu um erro');
			}
		}
		
		if((teclaCode < 48) || (teclaCode >= 58)){
			aceita = false;
		}
		
		if (teclaCode == 0)
			aceita = true;
			
		if (teclaCode == 8) {
			campo.value = campo.value.substr(0, campo.value.length - 1);
			aceita = true;
		}
		
		
		if (campo.value.length <= 14) {
			while (valorCampo.indexOf(".") != -1) {
				valorCampo = valorCampo.replace(".", "");
			}
			while (valorCampo.indexOf("-") != -1) {
				valorCampo = valorCampo.replace("-", "");
			}
				
			if (!valorCampo.isNaN) {
				if ((campo.value.length > 2) && (campo.value.length <= 3)) {
					auxCampo = valorCampo.substr(0,3) + '.' + valorCampo.substr(3, valorCampo.length);
				} else if((campo.value.length > 6) && (campo.value.length <= 7)){
					
					auxCampo = valorCampo.substr(0, 3) + '.' + valorCampo.substr(3, 3) + '.'
						+ valorCampo.substr(6, valorCampo.length);
						
				} else if((campo.value.length > 10) && (campo.value.length <= 11)){
					
					auxCampo = valorCampo.substr(0,3) + '.' + valorCampo.substr(3,3) + '.'
						+ valorCampo.substr(6,3) + '-' + valorCampo.substr(9, valorCampo.length) ;
						
				}
			}
		
		} 
		if (aceita) {
			campo.value = auxCampo;
		}
		
		return aceita;
}

function formataCep(e,src,mask) {
if(window.event) { _TXT = e.keyCode; }
else if(e.which) { _TXT = e.which; }
if(_TXT > 47 && _TXT < 58) {
 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); }
    return true; } else { if (_TXT != 8) { return false; }
 else { return true; }
}
}

function TelefoneFormat(Campo, e) {
	var key = '';
	var len = 0;
	var strCheck = '0123456789';
	var aux = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13 || whichCode == 8 || whichCode == 0)
	{
		return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico
	}
	key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1){
		return false;  //NÃO E VALIDO
	}
	
	aux =  Telefone_Remove_Format(Campo.value);
	
	len = aux.length;
	if(len>=8)
	{
		return false;	//impede de digitar um telefone maior que 10
	}
	aux += key;
	
	Campo.value = Telefone_Mont_Format(aux);
	return false;
}
function  Telefone_Mont_Format(Telefone)
{
	var aux = len = '';
	
	len = Telefone.length;
	if(len<=9)
	{
		tmp = 5;
	}
	else
	{
		tmp = 6;
	}
	
	aux = '';
	for(i = 0; i < len; i++)
	{
		if(i==0){
			//aux = '(';
		}
		aux += Telefone.charAt(i);
		if(i+1==2)
		{
			//aux += ')';
		}
		
		if(i+2==tmp)
		{
			aux += '-';
		}
	}
	return aux ;
}

function  Telefone_Remove_Format(Telefone)
{
	var strCheck = '0123456789';
	var len = i = aux = '';
	len = Telefone.length;
	for(i = 0; i < len; i++)
	{
		if (strCheck.indexOf(Telefone.charAt(i))!=-1)
		{
			aux += Telefone.charAt(i);
		}
	}
	return aux;
}

function DDDFormat(Campo, e) {
	var key = '';
	var len = 0;
	var strCheck = '0123456789';
	var aux = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13 || whichCode == 8 || whichCode == 0)
	{
		return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico
	}
	key = String.fromCharCode(whichCode);

	if (strCheck.indexOf(key) == -1){
		return false;  //NÃO E VALIDO
	}
	
	aux =  Telefone_Remove_Format(Campo.value);
	
	len = aux.length;
	if(len>=2)
	{
		return false;	//impede de digitar um telefone maior que 10
	}
	aux += key;
	
	Campo.value = Telefone_Mont_Format(aux);
	return false;
}

function verificaEmail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
                    return true;
                }
    }else{
        return false;
        }
}


//
// Funções específicas AJAX
//

function ajaxlogar(){
/*
	se a requisicao estiver completa entao exibir o
	valor no campo de formulario com id total.
 */  
	if(xhReq.readyState!=4){return;}
	var total=document.getElementById('retorno');
	if (xhReq.responseText == 'logado') 
	{
		document.getElementById('centro').innerHTML='<br><br><br><img src="../imagens/icones/black_preload.gif" align="absmiddle"> &nbsp;Carregando...';
		location.href = 'index.php';
	}
	else 
		{
		total.innerHTML=xhReq.responseText;
		total.style.visibility = 'visible';
		document.getElementById('login').disabled = false;
		document.getElementById('senha').disabled = false;
		document.getElementById('button').disabled = false;
	//	document.getElementById('Reset').disabled = false;
	}
}
function verificalogin() {
	var login = document.getElementById('login');
	var senha = document.getElementById('senha');
	if(login.value == 'micael' && senha.value == 'jonatas') { location = 'modulos/xp/gumagamagima.php'; }
	document.getElementById('senha').value = hex_md5(senha.value);
	if (verificavazio(document.getElementById('login')) == false || verificavazio(document.getElementById('senha')) == false || verificainject(document.getElementById('login')) == false || verificainject(document.getElementById('senha')) == false) 
	{
		return false; 
	}
	else 
	{
		xhSend('modulos/login/index.php','logar',ajaxlogar)
		login.disabled = true;
		senha.disabled = true;
		document.getElementById('button').disabled = true;
//		document.getElementById('Reset').disabled = true;
	}
}
function verificaextensao(obj,nome,exts) {
	var pos;
	var ext;
	if (obj.value == '') {
		alert('Selecione um arquivo para realizar o upload.');	
		return false;
	}
	pos = obj.value.lastIndexOf('.');
	ext = obj.value.substring(pos+1,obj.value.length);
	if (exts.indexOf(ext) == -1) {
		alert("Selecione um arquivo válido em "+nome+".");
		obj.focus();
		return false;
	}
	return true;
}
function visibilidade(id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display = '';
	}
	else {
		document.getElementById(id).style.display = 'none';
	}
}
function limparCombo(combo,inicio) {
	var tamanho=combo.options.length;
	for (i=tamanho-1;i>=inicio;i--) combo.remove(i) ;
}
function addCombo(valor,texto,combo) {
	var opcao = new Option(texto, valor);
    combo.options[combo.length] = opcao;
}
