function SomenteNumero(e)
{ 
	var key;

	if (window.event) 
	{
		key = event.keyCode;
	}
	else
	{ 
		key = e.which;
	}

	if(key > 47 && key < 58 || key == 8 || key == 0)
	{
		return; 
	}
	else
	{
		if(window.event)
		{
			window.event.returnValue = null; 
		}
		else 
		{
			e.preventDefault();
		}
	}
} 
function Mascara(src, mask) 
{
	 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);
	 }
}

/*
 * '[======================================================================================
 * '[= Nome : fgSplitString '[= Descrição : Divide a string por um separador
 * dado, retornando um array com os valores. '[= Entrada : psString - String a
 * ser dividida '[= psDivider - Divisor '[= Saida : Array com os items '[=
 * Exemplo : aryRetorno = fgSplitString(text16.value, "/"); '[= OBS :
 * '[======================================================================================
 */
function fgSplitString(psString, psDivider)
{
	/*
	 * * Conta o número de ocorrências do separador para saber quantos elementos
	 * terá o Array.
	 */
	var liOccurs = 0;
	
	for (var liCount = 0; liCount < (psString.length - psDivider.length); liCount++)	
		if (psString.substr(liCount, psDivider.length) == psDivider)
			liOccurs++;
			
	/*
	 * * Cria o array
	 */
	var laRet = new Array(liOccurs);
	var lsAux = '';
	
	liCount  = 0;
	liOccurs = 0;
	do
	{
		if (psString.substr(liCount, psDivider.length) == psDivider)
		{
			liCount += psDivider.length;
			laRet[liOccurs++] = lsAux;
			lsAux = '';
		}
		
		lsAux += psString.charAt(liCount++);
	}
	while (liCount < psString.length);
	
	laRet[liOccurs++] = lsAux;
	
	return (laRet);
}

/*
'[======================================================================================
'[= Nome		: fgIsDate
'[= Descrição	: Verifica se uma string é uma data válida
'[= Entrada		: psData - String de data no formato DD/MM/YYYY
'[= Saida		: True  - se a string for uma data
'[=				  False - caso contrário
'[= Exemplo		: if(fgIsDate(text13.value))
'[= OBS			: Para utilizar esta função é necessário a inclusão do genericoFuncoes.js
'[======================================================================================
*/
function fgIsDate(psData)
{
	
	var laDiasMes = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var laData    = fgSplitString(psData, '/');

	/*
	 * * Se não houver três partes a data é considerada inválida
	 */
	if (laData.length != 3)
		return false;
	
	/*
	 * * A string é dividida em três partes : * * laData[0] - Dia * laData[1] -
	 * Mês * laData[2] - Ano
	 */

	/*
	 * * Verifica se o mes está no intervalo [1,12]
	 */
	if (!(laData[1] >= 1 && laData[1] <= 12))
		return false;

	/*
	 * * Se o ano não tiver 4 digitos, é invalida
	 */
	if (laData[2].length != 4) 
		return false;

	/*
	 * * Se for ano bissexto, o Limite p/ o mes de Fevereiro é 29 dias
	 */
	if (Math.floor(laData[2] / 4) * 4 == laData[2]) 
		laDiasMes[1] = 29;
	
	
	/*
	 * * Se o dia estiver fora do limite para o mes dado, é invalida
	 */
	if (!((laData[0] >= 1) && (laData[0] <= laDiasMes[laData[1] - 1])))
		return (false);

	/*
	 * * Finalmente, se chegou até aqui, é uma data válida
	 */
	return (true);
}

/*
 * '[================================================================================================
 * '[= Nome : fgFormataValidaData '[= Descrição : Formata a data no formato
 * DD/MM/YYYY ou MM/YYYY '[= Entrada : obj '[= Saida : data formatada '[=
 * Exemplo : <INPUT id=text9 name=text9 onblur="fgFormataValidaData(this)"> '[=
 * '[= OBS : Para utilizar esta função é necessário a inclusão do
 * genericoFuncoes.js
 * '[================================================================================================
 */
function fgFormataValidaData(obj)
{
	
	var lsData = obj.value;
	var lsAux  = '';
	
	/*
	 * * Deixa só os números
	 */
	for (var liPos = 0; liPos < lsData.length; liPos++)
		if (!isNaN(lsData.charAt(liPos)))
			lsAux += lsData.charAt(liPos);

	/*
	 * * Se não tiver sido digitado nada, retorna
	 */
	if (lsAux.length == 0)
		return;

	/*
	 * * Verifica se tem todos os digitos necessários
	 */
	if ((lsAux.length != 8) && (lsAux.length != 6) && (lsAux.length != 4))
	{
		alert('Data Incorreta.');
		obj.value = '';
		obj.focus();
		return (false);
	}
	
	/*
	 * * Divide os números nos componentes de data
	 */
	switch (lsAux.length)
	{
		case 8 : // DD/MM/YYYY
		{
			var lsDia = lsAux.substr(0, 2);
			var lsMes = lsAux.substr(2, 2);
			var lsAno = lsAux.substr(4, 4);
	
			lsAux = lsDia + '/' + lsMes + '/' + lsAno;
	
			/*
			 * * Verifica se é uma data válida
			 */
			if (!fgIsDate(lsAux))
			{
				alert('Data Incorreta.');
				obj.value = '';
				obj.focus();
				return (false);
			}

			break;
		}
		
		case 6 : // MM/YYYY
		{
		    var lsMes = lsAux.substr(0, 2);
		    var lsAno = lsAux.substr(2, 4);
	
		    lsAux = lsMes + '/' + lsAno;
	
		    /*
			 * * Verifica se é o mês é válido
			 */
		    if (lsMes < '01' || lsMes > '12')
		    {
			    alert('Data Incorreta.');
			    obj.value = '';
			    obj.focus();
			    return (false);
		    }
			
			break;
		}
		
		case 4 : // YYYY
		{
			/*
			 * * Verifica se é o ano é válido
			 */
			if (lsAux < '1900')
			{
				alert('Data Incorreta.');
				obj.value = '';
				obj.focus();
				return (false);
			}
		}
	}
	
	/*
	 * * Retorna a Data formatada
	 */
	obj.value = lsAux;
	return (true);

}

function GetXmlHttpObject()
{ 
	var objXMLHttp=null
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{		
		try 
		{
			objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
		catch (e) 
		{
            try 
            {
            	objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {}
        }

	}
	return objXMLHttp
}

var xmlHttp;
function PreencheComboCidade(uf,path,pathPage,num)
{ 
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Este browser não suporta HTTP Request");	
		return false;
	
	}
	
	var url=pathPage;
	url=url+"?uf="+uf
	url=url+"&path="+path
	url=url+"&sid="+Math.random()
	if(num == 1)
	{
		xmlHttp.onreadystatechange=stateChangedCidade
	}
	else if(num == 2)
	{
		xmlHttp.onreadystatechange=stateChangedCidadeBoxe
	}
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}
function stateChangedCidade() 
{ 	
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		document.getElementById("comboCidade").innerHTML=xmlHttp.responseText 
	} 
}

function stateChangedCidadeBoxe() 
{ 	
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		document.getElementById("comboCidadeBoxe").innerHTML=xmlHttp.responseText 
	} 
}

var homeBuscaEvento = false;

function digitadoBuscaEvento(){
	homeBuscaEvento=true;
}

function validaBuscaHomeEvento(){
	if(homeBuscaEvento){
		return true
	}else{
		alert('Favor digitar algum valor para busca.')
		return false
	}
}

var homeBusca = false;

function digitadoBusca(){
	homeBusca=true;
}


function validaBuscaHome(){
	if(homeBusca){
		return true
	}else{
		alert('Favor digitar algum valor para busca.')
		return false
	}
}

function valida(form){
	
	for (i=0;i<form.length;i++)
	{
		var obg = form[i].obrigatorio;
		if (obg==1)
		{
			if (form[i].value == "" && form[i].disabled == "")
			{
				var nome = form[i].descricao
				alert("O campo " + nome + " é obrigatório.")
				form[i].focus();
				return false
			}
			else if(form[i].value == "0" && form[i].disabled == "")
			{
				var nome = form[i].descricao
				alert("O campo " + nome + " é obrigatório.")
				form[i].focus();
				return false
			}
		}
	}
	return true
}

function imprimirDiv(urlBase,divName)
{
	var WinPrint = window.open('','newwin','toolbar=no,status=no,scrollbars=yes,width=700,height=800');
	var allDivTags = document.getElementsByTagName("div");
	var divTagContent;
	var stylesPath = urlBase+'/system/modules/br.gov.turismo.eventos/resources/css/';
	
	for(var i=0; i < allDivTags.length; i++){
		if(  allDivTags[i].className == divName){
			divTagContent = allDivTags[i];
			 break;
			}
	}

	with (WinPrint.document) {
	write('<html>');
	write('<head>' + 
		'<link rel="stylesheet" type="text/css" href="'+stylesPath+'mtur_print.css" />'+
		'<link rel="stylesheet" type="text/css" href="'+stylesPath+'mtur_geral.css" />'+
		'<link rel="stylesheet" type="text/css" href="'+stylesPath+'mtur_interna.css" />'+
		'<link rel="stylesheet" type="text/css" href="'+stylesPath+'mtur_eventos.css" />'+
		'</head>');
	write('<body style="background:#FFF;" onload="print();">');
	write('<div class="printArea">');
	
	var divConteudo = divTagContent.innerHTML;
	var obj = document.getElementById("idIcones").innerHTML;
	divConteudo = divConteudo.replace(obj, "");	
	
	write(divConteudo);
	write('</div>');
	write('</body>');
	write('</html>');
	close();
	focus();
	}
}

function maxLength(textAreaField, limit) {
	if (textAreaField.value.length > limit) {
		alert("Numero de caracteres excedeu o limite em "+(textAreaField.value.length-limit)+" caracter(es)");
		textAreaField.focus();
	}
}
function abrePopupLupa(){
	document.getElementById('siteSombraLupa').style.height= document.body.clientHeight+'px';
	document.getElementById('siteSombraLupa').style.display = 'block';
	document.getElementById('sitePopupLupa').style.display = 'block';
}

function fechaPopupLupa(botao){

	document.getElementById('siteSombraLupa').style.display = '';
	document.getElementById('sitePopupLupa').style.display = '';
}

function abrePopup(){
	document.getElementById('siteSombra').style.height= document.body.clientHeight+'px';
	document.getElementById('siteSombra').style.display = 'block';
	document.getElementById('sitePopup').style.display = 'block';
}

function fechaPopup(botao){

	document.getElementById('siteSombra').style.display = '';
	document.getElementById('sitePopup').style.display = '';
}

function validaEnviaAmigo(form){
	
	for (i=0;i<form.length;i++)
	{
		
		var obg = form[i].obrigatorio;
		if (obg==1)
		{
			if(form[i].value == "seu nome*")
			{				
				var nome = form[i].descricao
				alert("O campo " + nome + " é obrigatório.")
				form[i].focus();
				return false
			}
			else if(form[i].value == "seu e-mail*")
			{				
				var nome = form[i].descricao
				alert("O campo " + nome + " é obrigatório.")
				form[i].focus();
				return false
			}
			else if(form[i].value == "nome do destinatário*")
			{				
				var nome = form[i].descricao
				alert("O campo " + nome + " é obrigatório.")
				form[i].focus();
				return false
			}
			else if(form[i].value == "e-mail do destinatário*")
			{				
				var nome = form[i].descricao
				alert("O campo " + nome + " é obrigatório.")
				form[i].focus();
				return false
			}
			
		}
	}
	return true
}

function limpaCampoSimples(campo){	
	if(campo.value == campo.title)
		campo.value = '';
	campo.className = 'text valido';
}

function tiraString(campo,string){
	string = ' '+string;
	if (campo.indexOf(string)>0){
		campo = campo.substring(0, campo.indexOf(string));
	}
	return campo;
}

function checaCampo(campo){	
	while(campo.value.indexOf(' ') == 0){
		campo.value = campo.value.substring(1, campo.value.length);
	}
	if((campo.value == '') || (campo.value.toLowerCase() == campo.title.toLowerCase())){
		campo.value = campo.title;
		campo.className = tiraString(campo.className,'valido');
	}
}

//envento onkeyup
function mascaraCPF(e, CPF) {
    var evt = e || window.event;
    kcode=evt.keyCode;
    if (kcode == 8) return;
    if (CPF.value.length == 3) { CPF.value = CPF.value + '.'; }
    if (CPF.value.length == 7) { CPF.value = CPF.value + '.'; }
    if (CPF.value.length == 11) { CPF.value = CPF.value + '-'; }
}

//valida o CPF digitado
function validarCPF(Objcpf){
	var valor = Objcpf.value;
	if (valor != ""){
	    var cpf = Objcpf.value;
	    exp = /\.|\-/g
	    cpf = cpf.toString().replace( exp, "" ); 
	    var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
	    var soma1=0, soma2=0;
	    var vlr =11;
	    
	    for(i=0;i<9;i++){
	        soma1+=eval(cpf.charAt(i)*(vlr-1));
	        soma2+=eval(cpf.charAt(i)*vlr);
	        vlr--;
	    }    
	    soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));
	    soma2=(((soma2+(2*soma1))*10)%11);
	    
	    var digitoGerado=(soma1*10)+soma2;
	    if(digitoGerado!=digitoDigitado){    
	        alert('CPF Invalido!'); 
	    	Objcpf.focus();
	    }
	}
}

//function para contar os caracteres inseridos no campo depoimento
var max=1024;
function contador_tecla(obj)
{
	var contador = document.getElementById("contador");
	var restante = max-obj.value.length;
	if(restante < 0){
		restante = 0;
	}
	contador.innerHTML = "Restam "+restante+" caracteres";
}

function validaForm(form){
	for ( var i = 0; i < form.elements.length; i++) {
		var els = form.elements[i];
		var title = els.title;
		var descricao = "";
		var semErro = true;
		var value = els.value;
		if(value == "" || value == "0"){
			for ( var j = 0; j < els.attributes.length; j++) {	
				var atributo = els.attributes[j];
				var nome = atributo.nodeName;
				var valor = atributo.nodeValue;
				//Pega a descrição
				if (nome == 'descricao'){
					descricao = valor;
				}
				//Pega o valor obrigatório
				else if(nome == 'obrigatorio' && valor == '1'){
					semErro = false;
				}
				if (descricao != "" && !semErro){
					break;
				}
			}
		}
		if (descricao != "" && !semErro){
			break;
		}
	} // for
	if(!semErro){
		alert('O campo ' + descricao + ' é obrigatório.');
		els.focus();
	}
	return semErro;
}

function validaTextArea(obj) {
	var maxlength = "";
	var els = "";
	for ( var i = 0; i < obj.elements.length; i++) {
		els = obj.elements[i];
		maxlength = "";
		var descricao = "";
		var foundMaxlength = false;
		switch (els.type) {
		case "textarea":
			loop:
			for ( var j = 0; j < els.attributes.length; j++) {	
				var atributo = els.attributes[j];
				var nome = atributo.nodeName;
				var valor = atributo.nodeValue;
				//Pega a descrição
				if (nome == 'descricao'){
					descricao = valor;
				}
				if (nome == 'maxlength'){
					maxlength = valor;
					foundMaxlength = true;
				}
			}

			if (els.value.length > maxlength && foundMaxlength ) {
				alert("Número de caracteres excedeu o limite em "+(els.value.length-maxlength)+" caracter(es) no campo \""+descricao+"\"");
				return false;
			}
			break;
		} // switch
	} // for
	return true;
}

function validaEmail(form){
	for ( var i = 0; i < form.elements.length; i++) {
		var els = form.elements[i];
		var title = els.title;
		var descricao = "";
		var semErro = true;
		var value = els.value;
		var desabilitado =  form[i].disabled;
		if(!desabilitado){
			for ( var j = 0; j < els.attributes.length; j++) {	
				var atributo = els.attributes[j];
				var nome = atributo.nodeName;
				var valor = atributo.nodeValue;
				if(nome == 'tipoemail' && valor == '1'){
					if (value.indexOf("@") == -1 || value.indexOf(".") == -1 || value == ""
						|| !validaArroba(els) || !validaTamanhoEmail(els)) {
							alert("Insira um e-mail valido!");
							els.focus();
							return false;
					}
				}	
			}
		}
	}
		return true;

}

function validaIntervaloDatas(inicio, fim)
{
	var dataMinima = fgSplitString(inicio.value, '/');
	var dataMaxima = fgSplitString(fim.value, '/');
	
	var dataMin = new Date();
	var dataMax = new Date();
	
	var mesMin = dataMinima[1] -1;
	var mesMax = dataMaxima[1] -1;
	
	dataMin.setFullYear(dataMinima[2],mesMin,dataMinima[0]);
	dataMax.setFullYear(dataMaxima[2],mesMax,dataMaxima[0]);
	
	if(dataMin > dataMax)
	{
		alert('ATENCAO: Data minima maior que data maxima!')
		return(false);
	}	
	  return(true);	
}