/******************************************************************
/* Função utilizada para identificar a versão do browser
/* Author: http://www.quirksmode.org/js/detect.html
/* Browser name: BrowserDetect.browser
/* Browser version: BrowserDetect.version
/* OS name: BrowserDetect.OS
/******************************************************************/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Internet Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

$(document).ready(function(){ 
    $().ajaxStart(function() {
		$('#loading').show();
		$('#loadingMin').show();
	});
    $().ajaxStop(function() { 
		$('#loading').hide(); 
		$('#loadingMin').hide(); 
	});    
    
	if (((BrowserDetect.browser == "Internet Explorer") && (BrowserDetect.version == "6")) 
        ||(BrowserDetect.browser == "Firefox") && (BrowserDetect.version == "2.0")
        ||(BrowserDetect.browser == "Firefox") && (BrowserDetect.version == "1.0")
        )
	{
	$('body').prepend("<div id=\"asn-warning\" style=\"position:absolute; display:none; left: 0px; border-bottom: solid 1px #DFDDCB; top:0px; margin: 0px; padding: 5px 0px; width: 100%; color: #4F4D3B; background: #FFFCDF; font: normal 8pt/14px 'Trebuchet MS', Arial, Helvetica; text-align: center;\">Voc&ecirc; est&aacute; usando <strong>"+BrowserDetect.browser+" "+BrowserDetect.version+"</strong>, um navegador antigo e com falhas de seguran&ccedil;a. Por favor <a href=\"http://www.updateyourbrowser.net/\" style=\"color: #4F4D3B; text-decoration: underline; font: normal 8pt/14px 'Trebuchet MS', Arial, Helvetica;\" target=\"_blank\">atualize seu navegador</a>. <a href=\"javascript://\" id=\"asn-close\" style=\"color: #4F4D3B; text-decoration: underline; font: normal 8pt/14px 'Trebuchet MS', Arial, Helvetica;\">[x]</a></div>");
	$('#asn-warning').fadeIn(1000);
	$('#asn-close').click(function(){ $('#asn-warning').fadeOut(400); });
	}      
});
  
/*
   Autor: Najib El Alam - 11/11/2009
   Resumo: Atualiza div genérico usando jquery
 */
 function atualizarDiv(nomeDiv, url){
        
     $("#"+nomeDiv).load(url);

} 

/*
   Autor: Najib El Alam - 30/12/2009
   Resumo: Realiza a execução de uma página php usando jquery e devolve o resultado
 */
function getResultadoSincrono(pUrl, pData){
   
    return $.ajax({
            type: "POST",
            url: pUrl,
            data:  pData,
            async: false
        }).responseText;
    
}

/*
   Autor: Najib El Alam - 17/12/2009
   Resumo: Retorna uma lista HTML contendo a mensagem de erro/informação
 */
function trataMensagemErro(varErrorMessage, message){

	//Se a mensagem está vazia então inicia lista.
	if (varErrorMessage.length == 0)
			varErrorMessage = "<ul>";
		
	
    //Se não veio mensagem então fecha tag de lista.
	if (message.length == 0)
		varErrorMessage += "</ul>";
		else
			varErrorMessage += "<li>"+message+"</li>";
	
	return varErrorMessage;
}

/*
   Autor: Najib El Alam - 17/12/2009
   Resumo: Mostra div de erro/informação 
*/
function mostrarMensagemValidacao(varErrorMessage, divId){
	ShowContent(divId, 1);
	$('#'+divId+'Inner').html(varErrorMessage);
}

function getNewCaptcha(divId){
	$('#'+divId).html('<img src=includes/getNewCaptcha.php?'+ Math.random()+' />');   
}

function onClickMostrarLogErro(){
    $("#divLogErro").load("controle.php?module=usuario&acao=getFrmLogErro");
    ShowContent('divLogErro',1); 	
}

function abrirJanela (pUrl, pNome, pWidth, pHeight, pOpcoes, pNewWidth, pNewHeight) { 
    // OPCOES !!
    //channelmode=yes|no|1|0 Whether or not to display the window in theater mode. Default is no 
    //directories=yes|no|1|0 Whether or not to add directory buttons. Default is yes 
    //fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode 
    //height=pixels The height of the window. Min. value is 100 
    //left=pixels The left position of the window 
    //location=yes|no|1|0 Whether or not to display the address field. Default is yes 
    //menubar=yes|no|1|0 Whether or not to display the menu bar. Default is yes 
    //resizable=yes|no|1|0 Whether or not the window is resizable. Default is yes 
    //scrollbars=yes|no|1|0 Whether or not to display scroll bars. Default is yes 
    //status=yes|no|1|0 Whether or not to add a status bar. Default is yes 
    //titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box. Default is yes 
    //toolbar=yes|no|1|0 Whether or not to display the browser toolbar. Default is yes 
    //top=pixels The top position of the window 
    //width=pixels The width of the window. Min. value is 100 

	try {	
	    tWindow = window.open("", pNome);
	    
	    if(tWindow == null) {
	    	throw "Erro ao abrir a página solicitada! \n\n(dica: desabilite o Bloqueador de Pop-ups)";
	    }

	    if(tWindow.document.forms.length > 0){
			tWindow.focus();
	
	    }else{
			tWindow.close();
			
			tLargura = screen.width;
			tAltura = screen.height;
			
			tTop = (tAltura - pHeight) / 2;
			tLeft = (tLargura - pWidth) / 2;
			
			if((tTop - 40) > 0)
			    tTop = tTop - 40;
			
			if (pOpcoes != "")
			    tWindow = window.open(pUrl, pNome, "top="+tTop+", left="+tLeft+", width="+pWidth+", height="+pHeight+", "+pOpcoes); 
			else
			    tWindow = window.open(pUrl, pNome, "top="+tTop+", left="+tLeft+", width="+pWidth+", height="+pHeight);

            if ((pNewWidth > 0) && (pNewHeight > 0))
                tWindow.resizeTo(pNewWidth,pNewHeight);
                
			tWindow.focus();
	    }
	    
	}
	catch(e) {
		//alert(e);
	}	    
	
} 

function trim(sString) {
    while (sString.substring(0,1) == ' ')
		sString = sString.substring(1, sString.length);

    while (sString.substring(sString.length-1, sString.length) == ' ')
		sString = sString.substring(0,sString.length-1);

    return sString;
}

function arrayLength(pArray) {
	for(ix=0; ix<pArray.length; ix++)
		if(pArray[ix] == undefined)
			return ix;
	return ix;
}

function cancelarSubmit(e) {
	if (e && e.preventDefault)
		e.preventDefault();
	return false;
}

function addEvent(obj, evType, fn) {
	if (obj.addEventListener)
	{
   		obj.addEventListener(evType, fn, false);
   		return true;
	}
	else if (obj.attachEvent)
	{
   		var r = obj.attachEvent("on"+evType, fn);
   		return r;
 	}
 	else
 	{
   		return false;
 	}
}

/******************************************************************
/*Fecha todas as janelas do sistema e efetua logout do usuario
******************************************************************/
function sair(pMens, pAcao) {
	if(confirm(pMens)) {
		document.formPrincipal.acao.value = pAcao;
		document.formPrincipal.submit();
	}
}

/******************************************************************
/*Fecha a janela e chama o foco em quem a abriu
******************************************************************/
function fechar(pMens) {
	if(confirm(pMens)) {
		opener.focus();
		window.close();
	}
}


/******************************************************************
/*Recupera as informações do Grupo para edição
******************************************************************/
function editarGrupo(pCodigoGrupo) {
    tFrm = document.formGrupos

    tFrm.acao.value = 'editarGrupo';
    tFrm.idLista.value = pCodigoGrupo;

    tFrm.submit();
}


/******************************************************************
/*Valida se o e-mail está dentro do formato padrão, utilizando
/*expressões regulares.
/******************************************************************/
function validarEmail(eMail)
{
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

    //Verifica se o e-mail informado é String ou um objeto 
    if(typeof(eMail) == "string")
    {
        //Se o email estiver correto
        if(er.test(eMail))
           return true; 
         else 
          {
            return false;
          }
    }else 
      if(typeof(eMail) == "object")
      {
          //Se o email estiver correto
          if(er.test(eMail.value))
          { 
           return true; 
          }
      }
       else
       {
         return false;
       }
}

/******************************************************************
/*Valida se a senha está dentro do formato espeficado
/* deverá conter: letras e números com no mínimo 6 caracteres
/******************************************************************/
function validarSenha(tSenha) {
	//verifica tamanho
	if(tSenha.length < 6)
		return false;
	
	//verifica se tem caracteres
	tExiste = false;
    for(aux=0; aux<tSenha.length; aux++) {
    	if(tAlfabetico.indexOf(tSenha.charAt(aux)) >= 0) {
    		tExiste = true;
    		break;
    	}
    }
	if(!tExiste)
		return false;
	
	//verifica se tem numeros			
	tExiste = false;
    for(aux=0; aux<tSenha.length; aux++) {
    	if(tNumerico.indexOf(tSenha.charAt(aux)) >= 0) {
    		tExiste = true;
    		break;
    	}
    }
	return tExiste;
}


/******************************************************************
/*Mascara para campo alfanumerico
/*expressões regulares.
/******************************************************************/
tAlfanumerico = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@-._ ÃÁÀÂÇÉÊÍÓÕÚÜãáàâçéêíóõúü";
tAlfabetico = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ÃÁÀÂÇÉÊÍÓÕÚÜãáàâçéêíóõúü";
tNumerico = "0123456789";
tData = "0123456789/";
tReal = "0123456789,";

function mascara(tInput, tTipo, tTamanho1, tTamanho2) {

	if(tTipo == "numerico") {
		//limita o tamanho
		tInput.value = tInput.value.substring(0, tTamanho1);
	
		//aplica a mascara
		permitirNumerico(tInput);

	} else if (tTipo == "alfanumerico") {
		//limita o tamanho
		tInput.value = tInput.value.substring(0, tTamanho1);
		
		//aplica a mascara
		permitirAlfanumerico(tInput);
	
	} else if (tTipo == "alfabetico") {
		//limita o tamanho
		tInput.value = tInput.value.substring(0, tTamanho1);
	
		//aplica a mascara
		permitirAlfabetico(tInput);

	} else if (tTipo == "real") {
		//aplica a mascara
		permitirReal(tInput, tTamanho1, tTamanho2);
	
	} else if (tTipo == "data") {
		//limita o tamanho
		tInput.value = tInput.value.substring(0, tTamanho1);

		//aplica a mascara
		permitirData(tInput);
	
	} else {
		//nao faz nada
	}

}

function permitirAlfanumerico(tInput) {
	tValorAtual = tInput.value;
	tNovoValor = "";
    for(aux=0; aux<tValorAtual.length; aux++) {
    	if(tAlfanumerico.indexOf(tValorAtual.charAt(aux)) >= 0){
    	   
    		tNovoValor += tValorAtual.charAt(aux);
        }
    }
    if(tInput.value != tNovoValor)
    	tInput.value = tNovoValor;
}

function permitirNumerico(tInput) {
	tValorAtual = tInput.value;
	tNovoValor = "";
    for(aux=0; aux<tValorAtual.length; aux++) {
    	if(tNumerico.indexOf(tValorAtual.charAt(aux)) >= 0)
    		tNovoValor += tValorAtual.charAt(aux);
    }
    if(tInput.value != tNovoValor)
    	tInput.value = tNovoValor;
}

function permitirAlfabetico(tInput) {
	tValorAtual = tInput.value;
	tNovoValor = "";
    for(aux=0; aux<tValorAtual.length; aux++) {
    	if(tAlfabetico.indexOf(tValorAtual.charAt(aux)) >= 0)
    		tNovoValor += tValorAtual.charAt(aux);
    }
    if(tInput.value != tNovoValor)
    	tInput.value = tNovoValor;
}

function permitirReal(tInput, tInt, tDec) {
	tValorAtual = tInput.value;
	tNovoValor = "";
    for(aux=0; aux<tValorAtual.length; aux++) {
    	if(tReal.indexOf(tValorAtual.charAt(aux)) >= 0)	{
    		if(tValorAtual.charAt(aux) == ",") {
    			if(tNovoValor.indexOf(",") < 0 && tNovoValor.length > 0) {
		    		tNovoValor += tValorAtual.charAt(aux);
		    	}
		   	} else {
	    		tNovoValor += tValorAtual.charAt(aux);
		   	} 
    	}
    }
    if(tNovoValor.indexOf(",") >= 0) {
		tValorTmp = tNovoValor;
    	tDecimal = tValorTmp.substring(tNovoValor.indexOf(","));
    	tInteiro = tValorTmp.substring(0, tNovoValor.indexOf(","));
    	tInteiro = tInteiro.substring(0, tInt);
	    tDecimal = tDecimal.substring(0, tDec);
	    tNovoValor = tInteiro + tDecimal;

    } else {
    	tNovoValor = tNovoValor.substring(0, tInt);
    }
    
    
    if(tInput.value != tNovoValor)
    	tInput.value = tNovoValor;
}

function permitirData(tInput) {
	tValorAtual = tInput.value;
	tNovoValor = "";
	tUtlimoCaracter = "";
	tCountParte = 1;
	tCountDigito = 0;
    for(aux=0; aux<tValorAtual.length; aux++) {
    	if(tData.indexOf(tValorAtual.charAt(aux)) >= 0) {
    		if(tNumerico.indexOf(tValorAtual.charAt(aux)) >= 0) {
    			if(tCountParte == 1 || tCountParte == 2) {
    				if(tCountDigito < 2) {
			    		tNovoValor += tValorAtual.charAt(aux);
			    		tCountDigito++;
    				}
    			} else {
    				if(tCountDigito < 4) {
			    		tNovoValor += tValorAtual.charAt(aux);
			    		tCountDigito++;
    				}
    			}
    		} else {
    			if(aux > 1) {
	    			if(tValorAtual.charAt(aux - 1) != "/") {
		    			if(tCountParte == 1 || tCountParte == 2) {
		    				if(tCountDigito == 2) {
					    		tNovoValor += tValorAtual.charAt(aux);
					    		tCountParte++;
					    		tCountDigito = 0;
		    				}
		    			} else {
		    				if(tCountDigito == 4) {
					    		tNovoValor += tValorAtual.charAt(aux);
					    		tCountParte++;
					    		tCountDigito = 0;
		    				}
		    			}
		    		}
		    	}
    		}
    	}
    }
    if(tInput.value != tNovoValor)
    	tInput.value = tNovoValor;
}


/******************************************************************
/*Funções utilizadas para mostrar dicas nas telas do sistema
/******************************************************************/
var wmtt

function showWMTT(id) 
{
   wmtt = document.getElementById(id);
   wmtt.style.display = "block"
}

document.onmousemove = updateWMTT;

function updateWMTT(e) 
{
	x = (document.all) ? window.event.x + document.body.scrollLeft : e.pageX;
	y = (document.all) ? window.event.y + document.body.scrollTop  : e.pageY;
	if (wmtt != null) 
      {
	   wmtt.style.left = (x + 20) + "px";
	   wmtt.style.top  = (y + 20) + "px";
	}
}
function hideWMTT() 
{
  wmtt.style.display = "none";
}

/******************************************************************
/*Funções utilizadas para trocar imagem dos botões em tela
/******************************************************************/
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}

}


function formata_data(tCampo,tecla){ 
    // Por Tiago Araujo Silva (tiago@tiagoaraujo.com)
    
    separador="/"; // Você pode definir o separador. Ex: "/" ou "-" ou "."
    
    tecla=tecla.keyCode; // Identifica a tecla, caso seja backspace
    
    valor=tCampo.value.split(''); // Pega o valor do campo e transforma cada caractere em uma string
    formatado=""; // Variável para carregar formatação temporariamente
    
    i=0; // variável de controle
    
    while(i<valor.length){ // Loop para cada caractere do campo
        caractere=valor[i]; // Seleciona um caractere para ser formatado
        numeros=/^\d+$/; // Variavel contendo números positivos
            // Verifica se é número ou "barra"
        if(numeros.test(caractere) || caractere==separador){ 
		formatado+=String(caractere);
		}
            // Verifica se precisa de barra, se a tecla for backspace, então a barra não é adicionada
            // Se for para adicionar barra, aumenta ++ variável de controle "i" para pular a barra adicionada
        if((formatado.length==2 || formatado.length==5) && tecla!=8){formatado+=separador; i++;}
            
        i++; // Se houver, passa para o próximo caractere
    }
    
    tCampo.value=formatado; // Atribui o valor formatado ao campo
	
	if (formatado.length == 10){
		if(!formatado.match(/^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/)){
			//$.prompt('Data Inválida! - ' + tCampo.value);
			tCampo.value = '';
			tCampo.focus;
		}
   }		
}


function validaData(str) { 
	var dia, mes, ano
	if(str != null && str != ""){
		dia = parseInt(str.substring(0,2),10); 
		mes = parseInt(str.substring(3,5),10); 
		ano = parseInt(str.substring(6,10),10); 
	
		cons = true; 
		
		// verifica se foram digitados números
		if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
/*			alert("Preencha a data somente com números.");  
			str.value="";
			str.focus(); */
			return false;
		}
		
		// verifica o dia valido para cada mes 
		if ((dia < 1)|| (dia < 1 || dia > 30) && (mes == 4 || mes == 6 || mes == 9 || mes == 11 ) || (dia > 31)) { 
			cons = false; 
		} 
	
		// verifica se o mes e valido 
		if( mes == null || mes == "" || mes < 1 || mes > 12 ) { 
			cons = false; 
		}
		
		// verifica se o ano e valido 
		if( ano == null || ano == "" || ano < 1753 || ano > 9999 ) { 
			cons = false;
		}
		// verifica se e ano bissexto 
		if (mes == 2 && ( dia < 1 || dia > 29 || ( dia > 28 && (ano / 4 != parseInt(ano / 4))))) { 
			cons = false; 
		} 
		
		if (cons == false) { 
/*			alert('A data "'+ str.value + '" não é válida.');
			str.value = '';		
			str.focus();*/
			return false;
		} 
	}
	return true;
}

function getAbsPos(o,p){
    var i=0;while(o!=null){
        i+=o["offset"+p];
        o=o.offsetParent;
    }
    return i;
} 
function hideTooltip() {
     tooltip=MM_findObj('div_dicas_tooltip');
     if(tooltip)
     document.body.removeChild(tooltip);
}     
function showTooltip(component, msg) {
    showTooltip(component, msg, '10', '80');
}

function showTooltip(component, msg, altura) {
    showTooltip(component, msg, altura, '80');
}

function showTooltip(component, msg, altura, largura) {
     hideTooltip();
     var html = "<div class=\"tooltip\"><div class=\"bicoesquerdo\">&nbsp;</div><div class=\"tooltipconteudo\" style=\"height:" + altura + "px; width:" + largura + "px; \">"+msg+"</div></div>";
     element = document.createElement("DIV");
     element.style.position="absolute";
     element.id="div_dicas_tooltip";
     element.style.top=(getAbsPos(component, "Top")-10)+"px";
     element.style.left=(getAbsPos(component,"Left")+component.offsetWidth +15)+"px";
     element.innerHTML=html;
     document.body.appendChild(element);
}
