//
//		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;
// endereço do site para exibição de imagens

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 validaData(data)
{
	var reDate = /^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)?\d{4}$/;
	if (reDate.test(data)) {
		return true;
	} 
	if (data != null && data != "") {
		return false;
	}
}

// passar somente nome do formulario.
// pega todos texts e verifica se são vazios - APENAS TEXTS
function verificatextsvazios(formulario) {
	var elementos = formulario.elements.length;
	for (i = 0;i<elementos;i++) 
		{
			if (formulario.elements[i].value == '' && formulario.elements[i].type == 'text') 
			{
				alert('Por gentileza preencha o campo ' + formulario.elements[i].title + ' para continuar');
				formulario.elements[i].focus();
				return false;
			}
		}	
}
// passar como document.getElement. Valida email.
function validamail (email) {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))) {
			alert("Email invalido, digite novamente por favor.");
			email.focus();
			return false;
		}
		return true;
}
function validaEmailBO (email) {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))) {
			return false;
		}
		return true;
}
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;
}

// verifica se o arquivo tem a extensao solicitada
// passar vazio 1 se quiser que verifique se esta vazio tambem
function verificaExtensao(obj,exts,vazio) {
	var pos;
	var ext;
	if (!obj.value && vazio) {
		return false;
	}
	pos = obj.value.lastIndexOf('.'); 	
	ext = obj.value.substring(pos+1,obj.value.length);
	if (exts.indexOf(ext) == -1) {
		return false;
	}
	else {
		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;
}

//
// 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 mudapara(atual,para,chars) {
	var irPara = document.getElementById(para);
	if (atual.value.length >= chars) {
		irPara.focus();
	}
} 
function mudaCampos(formulario,acao)
{
	var action
	if (acao == '0') { action = true; }
	else { action = false; }
	for (i = 0; i < formulario.length; i++)
	{
		formulario.elements[i].disabled = action;	
	}
}

function moveList(origem,destino,limite) {
	dest 	= 	document.getElementById(destino);
	orig	=	document.getElementById(origem);
	if (document.getElementById(origem).value == '') {
		return false;
	}
	else {
		if (limite == '' || dest.length < limite) {
			txt 	=	document.getElementById(origem).options[document.getElementById(origem).selectedIndex].text;
			valor 	= 	document.getElementById(origem).value;
			orig.options[orig.selectedIndex] = null;
			dest.options[dest.length] = new Option(txt,valor);
		}
		else {
			alert('Este campo permite no máximo '+limite+' ítens');
		}
	}
}

function addList(origem,destino,limite) {
	dest 	= 	document.getElementById(destino);
	orig	=	document.getElementById(origem);
	if (orig.value == '') {
		alert('Por favor preencha o campo "'+orig.title+'" para adicionar a lista.');
		return false;
	}
	else {
		if (limite == '' || dest.length < limite) {
			txt 	=	orig.value;
			valor 	= 	orig.value;
			dest.options[dest.length] = new Option(txt,valor);
			orig.value = '';
		}
		else {
			alert('Este campo permite no máximo '+limite+' ítens');
		}
	}
}

function remList(origem) {
	orig	=	document.getElementById(origem);
	orig.options[orig.selectedIndex] = null;
}

function limpaList(list,limite)
{
	listbox = document.getElementById(list);
	for (i = listbox.length;i >= limite; i--) {
		listbox.options[i] = null;;
	}
}

function addListValor(texto,value,destino) {
	dest 	= 	document.getElementById(destino);
	txt 	=	texto;
	valor 	= 	value;
	dest.options[dest.length] = new Option(txt,valor);
}

function validaNoXml(no,valor)
{
	if (no.firstChild == null) return valor; 
	else 
	{
		if (no.childNodes.length > 1)
		{
			var texto = '';
			for (c = 0; c < no.childNodes.length; c++)
            {
                texto += no.childNodes[c].data;
            }
			return texto;
		}
		else
			return no.firstChild.nodeValue;
	}
}

function limparCombo(combo,inicio)
{
	var tamanho=combo.options.length;
	for (i=tamanho-1;i>=inicio;i--)
		combo.remove(i) ;
}
function validaEmailBO (email) {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))) {
			return false;
		}
		return true;
}
function validaHora(horario)
{
	if (!(/^([0-1]\d|2[0-3]):[0-5]\d$/.test(horario))) {
		return false;
	}
	return true;
}

// Funcao que exibe a mascara
function exibirBgBody() {
	// Seleciona a tag body. item(0) por que só existe uma tag body
	var tagBody = document.getElementsByTagName('body').item(0);
	// Pega os tamanhos atuais da página, como largura, altura, ...
	var sizesPage = getPageSize();
	// Vamos criar uma tag div
	var bgBody = document.createElement('div');
	// Setar o atributo ID a div criada
	bgBody.setAttribute('id','bgBody');
	// Essa div terá o tamanho exato da página
	bgBody.style.height = arrayPageSize[1] + 'px';
	// Essa div terá a largura exata da página
	bgBody.style.width = arrayPageSize[0] + 'px';
	// Evita criar a div novamente
	if (!document.getElementById('bgBody')) {
		tagBody.insertBefore(bgBody, tagBody.firstChild);
	}	
}

function ampliaFoto(foto,legenda,largura,altura) {
	exibirBgBody();
	var quadro = document.getElementById('fotoAmpliada');
	quadro.style.display = '';
	quadro.style.height	 = (altura+30)+"px";
	quadro.style.width	 = largura+"px";
	quadro.style.padding = '5px 5px 5px 5px';
	
	var img = document.createElement('img');
	img.setAttribute('src',foto);
	var br1 = document.createElement('br');
	var br2 = document.createElement('br');
	var txt = document.createTextNode(legenda);
	var small1 = document.createElement('small');
	var txt3 = document.createTextNode('Clique na imagem para fechar');
	small1.appendChild(txt3);
	
	quadro.appendChild(img);
	quadro.appendChild(br1);
	quadro.appendChild(txt);
	quadro.appendChild(br2);
	quadro.appendChild(small1);
	
	var sizesPage = getPageSize();
	var wPage = arrayPageSize[0]; // Largura total da página
	var hPage = arrayPageSize[1]; // tamanho total da página
	/*quadro.style.width = (wPage / 2) + 'px'; // metade da largura da página*/
	//quadro.style.height = (wPage / 2) + 'px'; // metade da altura da página
	quadro.style.marginTop = -(wPage / 4) + 'px'; // 1 quarto da largura
	//quadro.style.marginLeft = -(wPage / 4) + 'px'; // 1 quarto da altura
}

function fechaFoto() {
	var quadro = document.getElementById('fotoAmpliada');
	var bgBody = document.getElementById('bgBody');
	removeNodes(quadro);
	quadro.style.display = 'none';
	bgBody.parentNode.removeChild(bgBody);
}

function removeNodes(obj) {
	try {
		if(obj.hasChildNodes() && obj.childNodes) {
			while(obj.firstChild) {
				obj.removeChild(obj.firstChild);
			}
		}
	} catch(e) {
		// nao faz nada ou, se preferir, descomente a linha abaixo para exibir alerta de erro
		alert(e.message);
	}
}

function abrirImagem(caminho,altura,largura,legenda)
{
	//pegando altura do body - ie6
	var pageSize = getPageSize();
	document.getElementById('mascara').style.height = (pageSize.pageHeight + 'px');
	
	if(!legenda)
	{
		document.getElementById('caixa').innerHTML 		= '<img src="'+caminho+'" height="'+altura+'" width="'+largura+'" alt="Clique na imagem para fechar"><div id="caixa_legenda">Clique na imagem para fechar</div>';
	}
	else
	{
		document.getElementById('caixa').innerHTML 		= '<img src="'+caminho+'" height="'+altura+'" width="'+largura+'" alt="Clique na imagem para fechar"><div id="caixa_legenda">'+legenda+'</div>';
	}
	
	document.getElementById('caixa').style.width 	= largura+'px';
	
	n_altura = parseInt(altura) + 20;

	document.getElementById('caixa').style.height 	= n_altura +'px';
	

	if (typeof document.body.style.maxHeight != "undefined")
	{
		document.getElementById('caixa').style.margin = "-"+ altura/2 + "px 0 0 -" + largura/2 + "px";	
	}
	else
	{
		var alturaScroll = document.documentElement.scrollTop;
		diferencaIE = alturaScroll - altura/2;
		document.getElementById('caixa').style.marginLeft = -largura/2 + "px";
		document.getElementById('caixa').style.marginTop = diferencaIE + "px";
	}

	
	document.getElementById('mascara').style.display 	= 'block';
	
	document.getElementById('caixa').style.display 	= 'block';
}

function fechar()
{
	document.getElementById('caixa').innerHTML 		= '';
	document.getElementById('mascara').style.display 	= 'none';
	document.getElementById('caixa').style.display 	= 'none';
}

function fecharLoad()
{
	document.getElementById('mascara').style.display 	= 'none';
	document.getElementById('caixa').style.display 	= 'none';
}

//funcao para diminuir o tamanho do flsh em caso de foto unica

function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY){
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	if(yScroll < windowHeight) pageHeight = windowHeight;
	else pageHeight = yScroll;
	if(xScroll < windowWidth) pageWidth = windowWidth;
	else pageWidth = xScroll;
	arrayPageSize = {pageWidth:pageWidth,pageHeight:pageHeight,windowWidth:windowWidth,windowHeight:windowHeight}
	return arrayPageSize;
}

function gE(valor) { return document.getElementById(valor); }