/************************************************************************
  							FUNCOES GLOBAIS
************************************************************************/

function getHTTPObject()
{
	var xmlhttp;
	// Internet Explorer
	try
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(oc)
		{
			xmlhttp = null;
		}
	}
	// Mozilla/Safari
	if (!xmlhttp && typeof xmlhttp != "undefined")
	{
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

/*
* Faz uma chamada ajax
* @param	url - url da chamada
* @param metodo - default(GET) / POST / HEADER
* @param parametro - Parametros a serem enviados (não é necessário "?" ou "&" no começo da string)
* @param tipo de resposta - true, false, alerta, texto
* @param	funcao função para ser executada na conclusão do request
*/
var __ajaxReturn;
function callAjax(url, metodo, parametros, resposta, destino, funcao)
{
	var retorno = null;
	//verifica se existe url para request definida
	if(typeof(url)=='undefined')
	{
		alert("Url de request não definido!");
		return false;
	}
	else
	{
		var obj = getHTTPObject(); //instancia obj xmlHttpRequest
	}
	
	//Verifica o método passado
	if(typeof(metodo)=='undefined' || metodo.length < 3){
		metodo = "GET";
	}
	
	if(metodo=='POST') //Verifica método e parametros
	{
		if(typeof(parametros)=='undefined' || parametros.length < 3)
		{
			alert('Falta parâmetros para o método de request!')	
			return false;
		}
	}
	else if (metodo=='GET')
	{
		
		if(typeof(parametros) != 'undefined'){
			if(url.search('[?]') < 0 )
			{
				url += '?'+parametros;
			}
			else
			{
				url += '&'+parametros;
			}
		}
	}
	//Verifica se existe destino e mostra mensagem de 
	if(typeof(destino)!='undefined' && typeof(resposta)!='undefined' && resposta == true)
	{
		var receptor = typeof(document.getElementById(destino)) == 'undefined' ? document.getElementsByName(destino)[0] : document.getElementById(destino) ;
		receptor.innerHTML =  '<table border="0" width="100%" height="100%" style="text-align:center;"><tr><td><img src="images/carregando.gif" /> <br /> Carregando...</td></tr></table>';
		//alert(receptor.id);
	}
	
	//Abre objeto http
	obj.open(metodo,url,true);
	
	//Verifica mudança de estado do request
	obj.onreadystatechange = function()
	{
		if(obj.readyState==4)
		{ 
			switch(resposta)
			{
				//Retorna a resposta da requisição em um objeto
				case true:
					receptor.innerHTML = obj.responseText;
				break;
				//Apenas retorna true ou false
				case false:
					if(obj.status == 200)
					{
						return true;
					}
					else
					{
						return false;
					}
				break;
				//retorna a resposta da requisição em um alert
				case 'alerta':
					alert(obj.responseText);
				break;
				
				//retorna a resposta do request em uma string
				case 'texto':
					if(obj.status == 200)
					{
						__ajaxReturn = obj.responseText;
					}
					else
					{
						return false;
					}
				break;
			}
			
			if(typeof(funcao)!='undefined')
			{
				setTimeout(funcao,50);
			}
			else
			{
				correctPNG();
			}
			setTimeout(function(){correctPNG();},500);
		}
	}
	
	//Verifica os parametros da requisição de acordo com o método passado
	if(metodo == 'POST'){
		obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //Seta header para post form 
		obj.send(parametros);
	}
	else
	{
		obj.send("");
	}
}

/************************************************************************
					PEGA VALOR DAS VARIÁVEIS
************************************************************************/

function pegaValor(idElemento){
	var valor = typeof(document.getElementById(idElemento).value)=='undefined' ? document.getElementsByName(idElemento)[0].value : document.getElementById(idElemento).value;
	return valor;
}

/************************************************************************
					VALIDAR UMA STRING DO EMAIL
************************************************************************/

function validarEmail(valorEmail)
{
	regEmail = /^\w+([\.\-]\w+)*@\w+\.\w+(\.\w+)*$/;
	
	if(regEmail.test(valorEmail))
	{
		return true;
	}
	else
	{
		return false;
	}
}

/************************************************************************
		FAZ A VALIDACAO DA DATA (dateString FORMATO = ANO,MES,DIA) 
************************************************************************/

function isDate(dateString, separador) 
{
    dateArray = dateString.split(separador); 			// separada data pelo separador
    
	if (dateArray.length < 3) 
	{
		return false;   
	}
	else 
	{
		if (isNaN(dateArray[0]) || dateArray[0] < 1900 || dateArray[0] > 9999)
		{			
			return false;
		}      
		else 
		{
			if (isNaN(dateArray[1]) || dateArray[1] < 1 || dateArray[1] > 12)
			{				
				return false;
			}
			else 
			{
				if (isNaN(dateArray[2]) || dateArray[2] < 1 || dateArray[2] > daysInMonth(dateArray[1], dateArray[0]))
				{					
					return false;
				}
				else
				{
					return true;
				}
			}
		}
	}
}

/************************************************************************
		RETORNA O NUMERO DE DIAS DE UM MÊS DE ACORDO COM O ANO
************************************************************************/
   
function daysInMonth(month, year) 
{
	// meses com 31 dias
	if (month=='1' || month=='01' || month=='3' || month=='03' || month=='5' || month=='05' || month=='7' || month =='07' || month =='8' || month =='08' ||month =='10'|| month =='12' )
	{
		return 31;
	}
	else 
	{	// meses com 30 dias
		if (month =='4' || month =='04' || month =='6' || month =='06' || month =='9' || month =='09' || month =='11')
		{
			return 30;
		}
		else  
		{	// mes de 28 ou 29 dias (fevereiro)
			if(year % 4 == 0)
			{
				return 29;
			}
			else 
			{
				return 28;
			}
		} // fim else
	}  // fim else
}

/************************************************************************
				DE ACORDO COM OS PARAMETROS GERA A DATA 
************************************************************************/

function gerarData(dia, mes, ano) 
{	
	var data = ano + '-' + mes + '-' + dia;
	
	return data
} // fim isDate

/************************************************************************
	  			LIMPA O VALOR DE DETERMINADOS CAMPOS
************************************************************************/

function limparCamposClonagem(vetorCampos)
{			
	for (var i=0;i<vetorCampos.length;i++)
	{
		vetorCampos[i].value = '';
	}
}

/************************************************************************
	  		PEGA UM VETOR E TRANSFORMA SEUS VALORES EM UMA STRING
************************************************************************/

function vetorToString(vetor,separador)
{						 
	var retorno = '';
		
	for (var i=0;i<vetor.length;i++)
	{
		retorno += i == 0 ? vetor[i].value :  ' || '+vetor[i].value
	}

	return retorno;  
} // fim vetorToString


function getLanguage()
{
	callAjax('index.php','GET','acao=getLanguage',true,'idiomaAtivo','alert("teste de abrir funcao no fim do request")');
} // fim verificaPermissoes

/**********************************************************************
  	VERIFICA SE EXISTE CAMPO COM PREENCHIMENTO INVALIDO
**********************************************************************/

function verificaPreenchimento(vetorValores, vetorIdiomas, tamMinCampos, mensagemErro, mensagemComplemento, divDestino)
{
	var validacao = true;	
	
	for (var i=0;i<vetorValores.length;i++)
	{				
		if (vetorValores[i].value.length < tamMinCampos)
		{									
			if (vetorIdiomas[i].selectedIndex != 0)
			{							
				alert(mensagemErro + " para o idioma " + vetorIdiomas[i].options[vetorIdiomas[i].selectedIndex].text + "! " + mensagemComplemento);
				document.getElementById('validacao').innerHTML = '';
				document.getElementById(divDestino).style.display = 'block';				
				vetorValores[i].focus();
				validacao = false;
				break;
			}
			else
			{
				alert(mensagemErro + "!" + mensagemComplemento);
				document.getElementById('validacao').innerHTML = '';
				document.getElementById(divDestino).style.display = 'block';				
				vetorValores[i].focus();
				validacao = false;
				break;
			}
		}  // fim if
	}  // fim for
	
	return validacao;
} // fim verificaPermissoes

/*****************************************************************************************
  	ADICIONA OS OPTIONS SELECIONADOS NO SELECT DE DESTINO E REMOVE NO SELECT DE ORIGEM
*****************************************************************************************/

function swapOption(selectOrigemId, selectDestinoId)
{
	var origem = document.getElementById(selectOrigemId);
	var destino = document.getElementById(selectDestinoId);	
	var i = 0;
	
	while (i<origem.options.length)
	{		
		if (origem.options[i].selected == true)
		{
			var novoOption = document.createElement('option');	
			
			//Pega os valores
			novoOption.text = origem.options[origem.selectedIndex].text;
			novoOption.value = origem.options[origem.selectedIndex].value;	
		
			// adicionar option no destino
			try 
			{				
				destino.add(novoOption, null);		// outros
			}
			catch(ex) 
			{
				destino.add(novoOption);       		// Somente para o IE		
			}
			
			// Remover option da origem
			origem.remove(origem.selectedIndex);									
		}
		else
		{
			i++;
		}
	}	
	
} // fim swapOption

/************************************************************************
  			VERIFICA QUAL RADIO BUTTON QUE ESTA MARCADO
************************************************************************/

function pegaRadioChecked(vetorRadio)
{
	for (var i=0;i<vetorRadio.length;i++)
	{
		if (vetorRadio[i].checked == true)
		{
			return vetorRadio[i].value;
		}
	}
}

/************************************************************************
  					MOSTRA O ERRO DE VALIDACAO
************************************************************************/

function erroValidacao(campo, msg, div)
{		
	alert(msg);
	document.getElementById('validacao').innerHTML = '';
	document.getElementById(div).style.display = 'block';
	document.getElementById(campo).focus();	  
}

/************************************************************************
				VERIFICA SE O IDIOMA JÁ FOI SELECIONADO
************************************************************************/

function verificaIdiomaSelecionado(vetorIdiomas)
{
	var validacao = true;
	for (var i=0;i<vetorIdiomas.length;i++)
	{
		if (vetorIdiomas[i].selectedIndex != 0)
		{
			var j = i+1;
			
			while (j<vetorIdiomas.length)
			{
				if (vetorIdiomas[i].selectedIndex == vetorIdiomas[j].selectedIndex)
				{
					alert("O idioma " + vetorIdiomas[i].options[vetorIdiomas[i].selectedIndex].text + " foi selecionado mais de uma vez!");
					vetorIdiomas[j].selectedIndex = '0';
					vetorIdiomas[j].focus();
					validacao = false;
				}
				j++;
			}  // fim for
		} 
	}  // fim for
	return validacao;
} // fim verificaPermissoes

/************************************************************************
					VERIFICA SE O CPF E VALIDO OU NAO
************************************************************************/

function validarCPF(cpf)
{
	s = cpf;
	
	if (isNaN(s)) 
	{
		return false;
	}
	
	var i;
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	
	for (i = 0; i < 9; i++) 
	{
		d1 += c.charAt(i)*(10-i);
	}
	
	if (d1 == 0)
	{
		return false;
	}  
	
	d1 = 11 - (d1 % 11);
	
	if (d1 > 9) 
	{
		d1 = 0;        
	}
	
	if (dv.charAt(0) != d1) 
	{
		return false;        
	}
	
	d1 *= 2;
	
	for (i = 0; i < 9; i++) 
	{
		d1 += c.charAt(i)*(11-i);
	}
	
	d1 = 11 - (d1 % 11);
	
	if (d1 > 9)
	{
		d1 = 0;
	}
	
	if (dv.charAt(1) != d1) 
	{
		return false;
	}
	
	return true;
}

/************************************************************************
					VERIFICA SE O CNPJ E VALIDO OU NAO
************************************************************************/

function validarCNPJ(cnpj)
{
	s = cnpj;
	
	if (isNaN(s)) 
	{
		return false;
	}
	
	var i;
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	
	for (i = 0; i <12; i++)
	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
	
	if (d1 == 0)
	{
		return false;
	}
	
	d1 = 11 - (d1 % 11);
	
	if (d1 > 9) 
	{
		d1 = 0;
	}
	
	if (dv.charAt(0) != d1)
	{
		return false;
	}
	
	d1 *= 2;
	
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	
	d1 = 11 - (d1 % 11);
	
	if (d1 > 9)
	{
		d1 = 0;
	}
	
	if (dv.charAt(1) != d1)
	{
		return false;
	}
	
	return true;
}

/************************************************************************
						Funções de cookie
Exemplos de uso
var cookie_expire_date = new Date(today.getTime() + (8 * 7 * 86400000));
function defineConteudoId() {
   if (pegaCookie('conteudoId')) 
   {
       var conteudoId = pegaCookie('conteudoId');
   }
   else
   {
       defineCookie('conteudoId',Math.random(),cookie_expire_date);
   }
}
************************************************************************/

function pegaCookie(nomeCookie) 
{
   var start = document.cookie.indexOf(nomeCookie+"=");
   var len = start+nomeCookie.length+1;
   if ((!start) && (nomeCookie != document.cookie.substring(0,nomeCookie.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}

function defineCookie(name,value,expires,path,domain,secure) 
{
    var cookieString = name + "=" +escape(value) +
       ( (expires) ? ";expires=" + expires.toGMTString() : "") +
       ( (path) ? ";path=" + path : "") +
       ( (domain) ? ";domain=" + domain : "") +
       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
}

function removeCookie(name,path,domain) 
{
   if (pegaCookie(name)) document.cookie = name + "=" +
      ( (path) ? ";path=" + path : "") +
      ( (domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

/*
	Função para correção de arquivos PNG necessária apenas para o internet explorer
*/
function correctPNG()
{
	for(var i=0; i<document.images.length; i++)
	{
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
		{
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:pointer;" + imgStyle
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
			img.outerHTML = strNewHTML
			i = i-1
		}
	}
}

if(document.all)
{
	window.attachEvent('onload',correctPNG);
}