//
//		Funções genéricas.
//

// passar somente nome do formulario.
// pega todos texts e verifica se são vazios - APENAS TEXTS
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
//var endereco = 'hawaii:81/reddiamond/';
var endereco = 'www.sangatiberga.com.br/';

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 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 validamailboolean (texto) {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(texto))) {
			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;
}

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 verificapreinscricao () {
	var nome = 		document.getElementById('nome');
	var email =  	document.getElementById('email');
	var endereco = 	document.getElementById('endereco');
	var bairro = 	document.getElementById('bairro');
	var cidade = 	document.getElementById('cidade');
	var estado = 	document.getElementById('estado');
	var ddd = 		document.getElementById('ddd');
	var telefone = 	document.getElementById('telefone');
	var telefone_ = document.getElementById('telefone_');
	var tipo = 		document.getElementById('tipo');
	var sexo = 		document.getElementById('sexo');
	var curso = 	document.getElementById('curso');
	var observacoes = document.getElementById('observacoes');
	var formulario = document.getElementById('form1');
	var div = document.getElementById('salvando');
	if (verificatextsvazios(formulario) == false) { return false; }
	else {
		if (validamail(email) == false) return false;
		else if (estado.value == 0) { alert('Por favor selecione um estado para continuar.'); return false; }
		else if (curso.value == 0) { alert('Por favor selecione um curso para continuar'); return false; }
		else if (checanumero(ddd) == false) return false;
		else if (checanumero(telefone) == false) return false;
		else if (checanumero(telefone_) == false) return false;
	}
	div.style.visibility = 'visible';
	nome.disabled = true;
	email.disabled = true;
	endereco.disabled = true;
	estado.disabled = true;
	bairro.disabled = true;
	cidade.disabled = true;
	ddd.disabled = true;
	telefone.disabled = true;
	telefone_.disabled = true;
	tipo.disabled = true;
	sexo.disabled = true;
	curso.disabled = true;
	observacoes.disabled = true;
	document.getElementById('botao1').disabled = true;
	document.getElementById('botao2').disabled = true;
	setTimeout("xhSend('inscrever.php','form1',inclui)",2000);
}

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 (verificavazio(document.getElementById('login')) == false || verificavazio(document.getElementById('senha')) == false || verificainject(document.getElementById('login')) == false || verificainject(document.getElementById('senha')) == false) 
	{
		return false; 
	}
	else 
	{
		document.getElementById('senha').value = hex_md5(senha.value);
		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 redirecionar(id,pag) {
   document.getElementById('id').value = id;
   document.getElementById('frm').action = pag;
   document.frm.submit();
}

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;	
	}
}


//funções para galeria

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 abrirImagem(caminho,altura,largura)
{
	//pegando altura do body - ie6
	var pageSize = getPageSize();
	document.getElementById('mascara').style.height = (pageSize.pageHeight + 'px');
	
	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>';
	
	document.getElementById('caixa').style.width 	= largura+'px';
	
	n_altura = parseInt(altura) + 20;
	
	document.getElementById('caixa').style.height 	= n_altura +'px';
	
	document.getElementById('caixa').style.margin = "-"+ altura/2 + "px 0 0 -" + largura/2 + "px";
	
	document.getElementById('mascara').style.display 	= '';
	
	document.getElementById('caixa').style.display 	= '';
}

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

/* parseUri 1.2; MIT License By Steven Levithan <http://stevenlevithan.com> */
var parseUri = function (source) { var o = parseUri.options, value = o.parser[o.strictMode ? "strict" : "loose"].exec(source); for (var i = 0, uri = {}; i < 14; i++) { uri[o.key[i]] = value[i] || ""; } uri[o.q.name] = {}; uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { if ($1) uri[o.q.name][$1] = $2; }); return uri; }; parseUri.options = { strictMode: false, key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], q: { name: "queryKey", parser: /(?=.)&?([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } };

parseUri.options.strictMode = true;


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 addList(texto,valor,destino) {
	var dest 	= 	document.getElementById(destino);
	dest.options[dest.length] = new Option(texto,valor);
}


function adicionaListagem(obj,dest,acao)
{
	var destino = document.getElementById(obj);	
	var i = 0;
	// vai percorrendo os objetos e deletando, por isso que i sempre tira um quando encontra um marcado
	while (destino.selectedIndex >= 0 && i < destino.options.length)
	{
		if (destino.options[i].selected == true)
		{
			if (acao == 'add')
				addList(destino.options[i].text,destino.options[i].value,dest);
			destino.options[i] = null;
			i>0?i--:'';
		}
		else
			i++;
	}
		
}
function selecionarTodos(obj)
{
	var destino = document.getElementById(obj);	
	for(i = 0; i < destino.length; i++)
	{
		destino.options[i].selected = true;
	}
}


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 numberFormat(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;
}
