// pop-up //
// USO <a href="pagina.htm" onclick="return popUp(this.href, 'N', 800, 600, 'resizabel=yes');"> //
function popUp(strURL, strType, strWidth, strHeight, resizable)
{
	var strOptions = "height=" + strHeight + ", width = " + strWidth + ", status, "+resizable;
	if(strType == "RS")
		strOptions += ", resizable, scrollbars";
	if(strType == "R")
		strOptions += ", resizable";
	if(strType == "S")
		strOptions += ", scrollbars";
	newWin = window.open(strURL, "newWin", strOptions);
	newWin.focus();
	return false;
}

// NoSpan //
// USO <a href="javascript: noSpam('contato', 'dominio.com.br')">email para contato</a> //
function noSpam(user, domain)
{
	lString = "mailto: " + user + "@" + domain;
	window.location = lString;
}

// toggle visibility
function toggle(targetId)
{
	if(document.getElementById)
	{
		target = getObj(targetId);
		if(target.style.display == "none" || target.style.display == "")
			target.style.display = "block";
		else
			target.style.display = "none";
	}
}

// Foco //
function focusme(obj)
{
	if(obj)
		obj.focus();
	else
		window.focus();
}

// retorna objeto do html pelo nome //
function getObj(nome)
{
	if(document.getElementById)
		return document.getElementById(nome);
	else if(document.all)
		return document.all[nome];
	else if(document.layers)
		return document.layers[nome];
	else return false;
}

// apresenta objeto html escondido //
function mostra(obj)
{
	obj.style.display = '';
}

// esconde objeto html //
function esconde(obj)
{
	obj.style.display = 'none';
}

// controla a apresenta��o de objeto html //
function controla(obj)
{
	var dx = getObj(obj);
	if(dx.style.display != 'none')
		esconde(dx);
	else
		mostra(dx);
}

// maximiza a janela //
function fullScreen()
{
	window.moveTo(0, 0);
	if(document.all)
		window.resizeTo(screen.availWidth, screen.availHeight);
	else if(document.layers || document.getElementById)
	{
		if(window.outerHeight < screen.availHeight || window.outerWidth < screen.availWidth)
		{
			window.outerHeight = screen.availHeight;
			window.outerWidth = screen.availWidth;
		}
	}
}

// trim //
function trim(str)
{
	return str.replace(/^(\s)+|(\s)+$/g, '');
}

// cria data a partir de uma string (dd/mm/aaaa) //
function toDate(data)
{
	if(isDate(data))
	{
		dia = parseInt(data.substr(0, 2), 10);
		mes = parseInt(data.substr(3, 2), 10);
		ano = parseInt(data.substr(6, 4), 10);
		return new Date(ano, mes - 1, dia);
	}
	else
		return new Date();
}

// completa com zeros � esquerda //
function Zeros(texto, tamanho)
{
	while(texto.length < tamanho)
		texto = '0' + texto;
	return texto;
}

// convert data para string (dd/mm/aaaa) //
function toDateStr(data)
{
	dia = Zeros(data.getDate().toString(10), 2);
	mes = Zeros((data.getMonth() + 1).toString(10), 2);
	ano = data.getFullYear();
	return dia + '/' + mes + '/' + ano;
}

// retorna tamanho do mes //
function monthLen(mes, ano)
{
	switch(mes)
	{
		// meses com 30 dias //
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
			break;
		// fevereiro //
		case 2:
			// se ano n�o for bisexto //
			if(ano % 4)
				return 28;
			else
				return 29;
			break;
		// meses com 31 dias //
		default:
			return 31;
	}
}

// adiciona em uma parte da data um n�mero //
function dateAdd(parte, numero, data)
{
	dia = data.getDate();
	mes = data.getMonth() + 1;
	ano = data.getFullYear();
	switch(parte)
	{
		// acrescenta dias na data //
		case 'd':
			dia += numero;
			while(dia > monthLen(mes, ano))
			{
				dia -= monthLen(mes, ano);
				mes += 1;
				if(mes > 12)
				{
					mes = 1;
					ano += 1;
				}
			}
			break;
		// acrescenta meses na data //
		case 'm':
			mes += numero;
			while(mes > 12)
			{
				mes -= 12;
				ano += 1;
			}
			if(dia > monthLen(mes, ano))
				dia = monthLen(mes, ano);
			break;
		// acrescenta anos na data //
		case 'y':
			ano += numero;
			if(mes == 2 && dia == 29 && ano % 4)
				dia = 28;
			break;
		default:
			// erro de par�metro (retorna a mesma data) //
	}
	return new Date(ano, mes - 1, dia)
}

// compara duas datas //
function compareDate(data1, data2)
{
	if(data1 < data2)
		return -1;
	else if(data1 > data2)
		return 1;
	else
		return 0;
}

// compara duas datas como string (dd/mm/aaaa) //
function compareDateStr(data1, data2)
{
	d1 = toDate(data1);
	d2 = toDate(data2);
	return compareDate(d1, d2);
}

// compara duas strings //
function compareStr(str1, str2, msg)
{
	if(str1 != str2)
	{
		alert(msg);
		return false;
	}
	return true;
}

// converte texto para valor numerico
function toNumber(valor) {
	return parseFloat(valor.replace(',', '.').replace('.', ''));
}

// aceita a digita��o somente de n�meros com ou sem m�scara (keypress) //
function Numeric(ev, campo, mask)
{
	if(ev.keyCode) {
		if((ev.keyCode < 48 || ev.keyCode > 57) && ev.keyCode != 13) {
			ev.returnValue = false;
			return false;
		}
	}
	else if((ev.charCode < 48 || ev.charCode > 57) && ev.charCode != 13) {
		ev.preventDefault(false);
		ev.stopPropagation();
		return false;
	}
	if(campo && mask)
	{
		i = campo.value.length;
		if(i < mask.length && i < campo.maxLength)
		{
			c = mask.charAt(i);
			if(c != '9')
				campo.value += c;
		}
	}
}

// coloca mascara em campo data (dd/mm/aaaa) [keypress] //
function MascareDate(ev, campo)
{
	return Numeric(ev, campo, '99/99/9999 99:99:99');
}

// verifica se um campo de um formul�rio est� vazio ou s� com espa�os //
function Empty(campo, msg)
{
	if(campo.value.length)
		if(trim(campo.value) != '')
			return false;
	if(msg != '')
	{
		alert(msg);
		if(tp = campo.getAttribute('type'))
		{
			if(tp.toLowerCase() != 'hidden')
				campo.focus();
		}
		else
			campo.focus();
	}
	return true;
}

// verifica se um campo tipo checkbox ou radio de um formul�rio foi marcado //
function Check(campo, msg)
{
	if(campo.length)
		for(i = 0; i < campo.length; i++)
			if(campo[i].checked)
				return true;
	else if(campo.checked)
		return true;
	if(msg != '')
		alert(msg);
	return false;
}

// verifica se uma string � uma data (dd/mm/aaaa) //
function isDate(data)
{
	if(data.length == 10)
	{
		dia = parseInt(data.substr(0, 2), 10);
		mes = parseInt(data.substr(3, 2), 10);
		ano = parseInt(data.substr(6, 4), 10);
		if(dia > 0 && dia < 32 && mes > 0 && mes < 13 && ano > 999 && ano < 10000)
		{
			if(mes == 2 && dia > 28)
			{
				if(ano % 4)
					return false;
				else if(dia > 29)
					return false;
			}
			switch(mes)
			{
				case 4:
				case 6:
				case 9:
				case 11:
					if(dia > 30)
						return false;
					break;
			}
		}
		else
			return false;
	}
	else if(data.length)
		return false;
	return true;
}

// valida o e-mail //
function isEmail(email)
{
	if(email.length)
		return(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
	return true;
}

function unformatNumber(number){
	
	//funcao que retira caracteres de formatacao de strings numericas fornecidas
	
	return String(number).replace(/\D/g, "");
	
}

// valida CPF //
function isCPF(CPF)
{
	var i, j, soma;
	CPF = unformatNumber(CPF);
	
	if(CPF.length != 11)
		return false;
	j = true;
	for(i = 0; i < 9; i++)
	{
		if(parseInt(CPF.charAt(i), 10) != parseInt(CPF.charAt(i + 1), 10))
		{
			j = false;
			break;
		}
	}
	if(j) return false;
	for(j = 0; j < 2; j++)
	{
		soma = 0;
		for(i = 0; i < 9 + j; i++)
			soma += parseInt(CPF.charAt(i), 10) * (10 + j - i);
		soma = 11 - (soma % 11);
		if(soma > 9) soma = 0;
		if(soma != parseInt(CPF.charAt(9 + j), 10))
			return false;
	}
	return true;
}

// valida CNPJ //
function isCNPJ(CNPJ)
{
	var i, j, k, soma;
	CNPJ = unformatNumber(CNPJ);
	
	if(CNPJ.length != 14)
		return false;
	for(k = 0; k < 2; k++)
	{
		soma = 0;
		j = 5 + k;
		for(i = 0; i < 12 + k; i++)
		{
			soma += parseInt(CNPJ.charAt(i), 10) * j;
			if(j > 2) j--;
			else j = 9;
		}
		soma = 11 - soma % 11;
		if(soma > 9) soma = 0;
		if(soma != parseInt(CNPJ.charAt(12 + k)))
			return false;
	}
	return true;
}

// limita o tamanho do textarea na digita��o //
function textCounter(ev, field, limit, diplay)
{
	if(field.value.length >= limit)
	{
		if(ev.keyCode)
			ev.returnValue = false;
		else
		{
			ev.preventDefault(false);
			ev.stopPropagation();
		}
		return false;
	}
	getObj(diplay).innerHTML = field.value.length + 1;
}

// limita e mostra o tamanho do textarea //
function textLimit(field, limit, diplay)
{
	field.value = field.value.substr(0, limit);
	getObj(diplay).innerHTML = field.value.length;
}

// marca altera��o //
var alterou = false;
function altera(campo)
{
	alterou = campo;
}

// confirma altera��o //
function confirma(campo)
{
	if(alterou && alterou != campo)
		return confirm('voc� n�o salvou as altera��es. \n deseja continuar ?');
	return true;
}

// calcula m�dulo //
function modulo(numero, mod, x)
{
	total = 0;
	for(i = 0; i < numero.length; i++)
		total += parseInt(numero.substr(numero.length - (i + 1), 1)) * ((i % 8) + 2);
	digito = mod - (total % mod);
	return (digito > 9) ? x : digito;
}

// substitui todas as ocorr�ncias de um char //
function substitui(chr, rpl, str)
{
	while(str.search(chr) >= 0)
		str = str.replace(chr, rpl);
	return str;
}

// acessa url de forma s�ncrona //
function getUrl(url, method, enctype, post, xml)
{
	var obj = false;
	if(window.XMLHttpRequest)
		obj = new XMLHttpRequest();
	else if(window.ActiveXObject)
		obj = new ActiveXObject('Microsoft.XMLHTTP');
	if(obj)
	{
		obj.open(method, url, false);
		obj.setRequestHeader('Content-type', enctype);
		obj.send(post);
		if(xml) return obj.responseXML;
		return obj.responseText;
	}
	else
		alert('Error: Not suport for XMLHttpRequest!');
}

// retorna todas as ocorr�ncias de uma tag xml //
function getTags(docx, tag)
{
	node = docx.getElementsByTagName(tag);
	if(node.length)
		return node;
	return false;
}

// retorna valor de tag xml //
function getValue(node, i)
{
	if(node.length) {
		if(child = node[i])
			return unescape(child.firstChild.nodeValue);
		return null;
	}
	return null;
}

// seleciona um formul�rio //
function getForm(file, name, onload)
{
	if(div = getObj(name))
	{
		div.innerHTML = getUrl(file, 'get', 'text/plain', '', false);
		if(onload) eval(onload);
	}
	else
		alert('Elemento inv�lido!');
	return false;
}

// posta um formul�rio //
function postForm(frm, name, onload)
{
	flds = '';
	if(frm.length)
	{
		for(i = 0; i < frm.length; i++)
		{
			elm = frm.elements[i];
			if(elm.name != '')
			{
				if(!Validate(elm))
					return false;
				if(tp = elm.getAttribute('type'))
				{
					switch(tp.toLowerCase())
					{
						case 'checkbox':
						case 'radio':
							if(elm.checked)
								flds += elm.name + '=' + escape(elm.value) + '&';
							break;
						default:
							flds += elm.name + '=' + escape(elm.value) + '&';
					}
				}
				else
					flds += elm.name + '=' + escape(elm.value) + '&';
			}
		}
		if(div = getObj(name)) {
			div.innerHTML = getUrl(frm.action, frm.method, frm.enctype, flds, false);
			if(onload) eval(onload);
		}
		else
			alert("Elemento inv�lido!");
	}
	else
		alert("Formul�rio inv�lido!");
	return false;
}

// valida um formul�rio //
function validForm(frm)
{
	if(frm.length)
	{
		for(i = 0; i < frm.length; i++)
		{
			elm = frm.elements[i];
			if(elm.name != '')
				if(!Validate(elm))
					return false;
		}
		return true;
	}
	else
		alert("Formul�rio inv�lido!");
	return false;
}

// valida um elemento de um formul�rio //
function Validate(elm)
{
	if(elm.getAttribute('required'))
	{
		if(tp = elm.getAttribute('type'))
		{
			switch(tp.toLowerCase())
			{
				case 'checkbox':
					if(!elm.checked){
						alert(elm.getAttribute('validationmsg'));
						return false;
					}
				case 'radio':
					break;
				default:
					if(Empty(elm, elm.getAttribute('validationmsg')))
						return false;
			}
		}
		else if(Empty(elm, elm.getAttribute('validationmsg')))
			return false;
	}
	switch(elm.getAttribute('param'))
	{
		case 'date':
			if(!isDate(elm.value))
			{
				alert('Data Inválida!');
				elm.focus();
				return false;
			}
			break;
		case 'email':
			if(!isEmail(elm.value))
			{
				alert('E-mail Inválido!');
				elm.focus();
				return false;
			}
			break;
		case 'cpf':
			if(!isCPF(elm.value))
			{
				alert('CPF Inválido!');
				elm.focus();
				return false;
			}
			break;
		case 'cnpj':
			if(!isCNPJ(elm.value))
			{
				alert('CNPJ Inválido!');
				elm.focus();
				return false;
			}
			break;
		case 'cpfcnpj':
			if(!isCPF(elm.value) && !isCNPJ(elm.value))
			{
				alert('CPF / CNPJ Inválido!');
				elm.focus();
				return false;
			}
			break;
	}
	return true;
}

// mensagem de erro //
function erro()
{
	if(obj = getObj('erro'))
	{
		if(obj.innerHTML != '')
		{
			alert(obj.innerHTML);
		 	return true;
		}
	}
	return false;
}

//Altera o link da p�gina
function novaURL(url)
{
	window.location = url;
}

// ajax //
var ajax;

// inicia ajax //
function iniciaAjax(name)
{
	ajax = getObj(name);
}

// carrega ajax //
function carregaAjax(doc)
{
	if(ajax)
		ajax.innerHTML = doc.body.innerHTML;
	ajax = false;
}

// copia itens de um select para outro //
function copySel(origem, destino) {

	tam = origem.options.length;

	for(i = 0; i < tam; i++) {

		if(origem.options[i].selected) {

			var Opt = new Option();

			Opt.text = origem.options[i].text;

			Opt.value = origem.options[i].value;

			for(j = 0; j < destino.options.length; j++)

				if(Opt.text < destino.options[j].text)

					break;

			if(j < destino.options.length)

				destino.options.add(Opt, j);

			else

				destino.options.add(Opt);

			origem.remove(i);

			tam--;

			i--;

		}

	}

}

//combo de idiomas -> cadastro

function comboIdioma(idioma, id_evento){
	
	if(idioma.value != "seleciona"){

		window.location = "evento_idioma.php?idioma="+idioma.value+"&sq_evento="+id_evento;
	
	}

}

//fun��o para esconder o combo do setor//
	function desabilita(o){
	
			var div = getObj('setor');
			if(o.value == 'G'){
			div.style.display = 'none';
		
			}  else {
				div.style.display = 'block';
		
			}
		}


	function esqueciSenha(){
	
		window.open("esqueci_senha.php", "_blank", "width=600px, height=300px, toolbars=no, menubar=no, scrollbars=no, statusbar=yes");
	
	}

	
	function selecionarTodos(){
	
		var qtde = $("#qtde_enviados").val();
		
		for(i = 0; i<qtde; i++){
		
			str_chk = 'chk_sq_evento_'+i;
			
			document.forms[0][str_chk].checked=true;
		
		}
	
	}
	
	function limparTodos(){
	
		var qtde = $("#qtde_enviados").val();
		
		for(i = 0; i<qtde; i++){
		
			str_chk = 'chk_sq_evento_'+i;
			
			document.forms[0][str_chk].checked=false;
		
		}
	
	}
	
	function validaForm(){
	
		var campos = $(".required");
		campo_marcado = campos.checked;
		alert(campo_marcado);
	
	}
	
	function selecionaListagem(codigo, funcao_retorno){
	
		eval(funcao_retorno+'('+codigo+')');
		return;
	
	}
	
	function mascaraInscricaoEstadual(estado, campo_destino){
		
		//cria a mascara do campo de IE conforme o estado
		
		switch (estado){
			
			case 'AC':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99.999.999/999-99')");
			
			break;
			
			case 'AL':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999999')");
			
			break;
			
			case 'AP':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999999')");
			
			break;
			
			case 'AM':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99.999.999-9')");
			
			break;
			
			case 'BA':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999-99')");
			
			break;
			
			case 'CE':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99999999-9')");
			
			break;
			
			case 'DF':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99.999999/999-99')");
			
			break;
			
			case 'ES':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999999')");
			
			break;
			
			case 'GO':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99.999.999-99')");
			
			break;
			
			case 'MA':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999999')");
			
			break;
			
			case 'MS':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999999')");
			
			break;
			
			case 'MT':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '9999999999-9')");
			
			break;
			
			case 'MG':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999.999.999/9999')");
			
			break;
			
			case 'PA':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99-999999-9')");
			
			break;
			
			case 'PB':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99999999-9')");
			
			break;
			
			case 'PR':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99999999-99')");
			
			break;
			
			case 'PE':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99.9.999.9999999-9')");
			
			break;
			
			case 'PI':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999999')");
			
			break;
			
			case 'RJ':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99.999.99-9')");
			
			break;
			
			case 'RN':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99.999.999-9')");
			
			break;
			
			case 'RS':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999/9999999')");
			
			break;
			
			case 'RO':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999.99999-9')");
			
			break;
			
			case 'RR':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99999999-9')");
			
			break;
			
			case 'SC':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999.999.999')");
			
			break;
			
			case 'SP':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999.999.999.999')");
			
			break;
			
			case 'SE':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '999999999-9')");
			
			break;
			
			case 'TO':
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99999999999')");
			
			break;
			
			default:
			
				$("#"+campo_destino).attr("onkeypress", "Numeric(event, this, '99999999999')");
			
			break;
			
		}
		
	}
	
	function validaInsc(campo, uf_sg){
			
		var cpo = campo.value;
		cpo = unformatNumber(cpo);
		
		if(uf_sg != 0){
			
			if(CheckIE(cpo, uf_sg)){
				
				return true;
				
			}else{
				
				alert("Inscrição inválida")
				campo.focus();
				
			}
			
		}else{
			
			return true;
			
		}
		
	}
	
	//funcao que verifica, via ajax, a unicidade de determinados campos do formulario
	
	function verificaUnico(campo, tp_campo, cpo_hidden, metodo_ajax, botao_submit){
		
		//recebe o valor do campo hidden, que indica se eh uma atualizacao ou uma insercao
		hidden = $("#"+cpo_hidden).val();
		
		$.post(metodo_ajax+'/'+campo.value+'/'+tp_campo+'/'+hidden, {valor_validacao:campo.value}, function (xml){
			
			var retorno = [
			
				$("retorno", xml).text()
			
			];
			
			if(retorno == "true"){
				
				//o dado passado não é unico
				//desabilita o botão de gravar
				$("#"+botao_submit).attr("disabled", "true");
				$(".msg_validacao").html("<span style='color:red;'>Valor precisa ser único</span>");
				campo.focus();
				return;
				
			}else{
				
				$("#"+botao_submit).removeAttr("disabled");
				$("#msg_validacao").html('');
				return;
				
			}
			
		});
		
	}
	
//Funções para carregamento de ano e mes na página giraturma do admin

function objXMLHttp(){

  if(window.XMLHttpRequest){
      var objetoXMLHttp = new XMLHttpRequest();
   return objetoXMLHttp;
  
  } else if(window.ActiveXObject){
      
	   var versoes = [ "MSXML2.XMLHttp.6.0", " MSXML2.XMLHttp.5.0" , "MSXML2.XMLHttp.4.0" , "MSXML2.XMLHttp.3.0" , "MSXML2.XMLHttp" , "Microsoft.XMLHttp" ];
	   
	   for (var i = 0; i < versoes.length; i++){
		 
		   try{
			   var objetoXMLHttp = new ActiveXObject(versoes[i]);
			   return objetoXMLHttp;
		   }catch (ex){
			  // nada aqui
		   }
	   
	   }
  
  
  }

    
}
//Envia dados para o php
function ajaxSend(dados,arquivo,resposta){

		var ajaxObj = objXMLHttp();

		ajaxObj.open("POST",arquivo,true);
		ajaxObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
		ajaxObj.setRequestHeader("encoding", "iso-8859-1");

		ajaxObj.onreadystatechange=function(){
		   if(ajaxObj.readyState == 1){
		   	//carregando
		   }
		
		   if(ajaxObj.readyState == 4){
				if(ajaxObj.status == 200){
						document.getElementById(resposta).innerHTML = ajaxObj.responseText;
				} else {
					alert('Ocorreu um erro');
			  
				} 
		   }
		};
		ajaxObj.send(dados);
		return false;
}
//Carrega meses
function change_ano(anoVar, base_url){
	var dados = "ano="+anoVar;
	link = base_url+'admin/giraturma/ajax/'+anoVar;
	//alert(link);
	$('#form_mes').load(link);
	//document.location.href = '../giraturma/ajax/'+anoVar;
	//ajaxSend(dados,'..,'form_mes');
}