//
// Atualizado em: 11/10/2008 - ROGERIO
//
// Comparei com a versao tw4 (v1_1) em funcionamento, e incorporei aqui as funcoes 
//          que tinham lá e aqui nao.
//
//***************************************************************************************

// FORÇA LINKS A ABRIREM EM UMA NOVA JANELA
//******************************************************************************
// A W3C não aceita mais o atributo "target" em links (tag <a>) em doctypes XHTML 1.0 Strict
// A função abaixo faz com que todos os links que possuem rel="externo" no link, abram em outra janela conforme no exemplo abaixo:
// EXEMPLO:
//******************************************************************************
//<a href="index.php" title="Link de Exemplo" rel="externo">

/* Para chamar a função, insira no body  == <script type="text/javascript">createExternalLinks();</script>  */
function createExternalLinks() {
    if(document.getElementsByTagName) {
        var anchors = document.getElementsByTagName('a');
        for(var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            if(anchor.getAttribute("href") && anchor.getAttribute('rel')=='externo') { // <-- É necessário inserir rel="externo" no link
                anchor.target = '_blank';
                var title = anchor.title + ' (Este link abre uma nova janela)'; // <-- Insere este texto no final do Title do link
                anchor.title = title;
            }
        }
    }
}


/*
* PROTOTYPES - ROGERIO
*
 * Variaveis globais
 **/

String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

String.prototype.pad = function(size, pad, side) {
  var str = this, append = "", size = (size - str.length);
  var pad = ((pad != null) ? pad : " ");
  if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
    throw new Error("Wrong parameters for String.pad() method.");
  }
  if (side == String.PAD_BOTH) {
    str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
    return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
  }
  while ((size -= pad.length) > 0) {
    append += pad;
  }
  append += pad.substr(0, (size + pad.length));
  return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}


Number.prototype.format = function(d_len, d_pt, t_pt) {
  var d_len = d_len || 0;
  var d_pt = d_pt || ".";
  var t_pt = t_pt || ",";
  if ((typeof d_len != "number")
    || (typeof d_pt != "string")
    || (typeof t_pt != "string")) {
    throw new Error("wrong parameters for method 'String.pad()'.");
  }
  var integer = "", decimal = "";
  var n = new String(this).split(/\./), i_len = n[0].length, i = 0;
  if (d_len > 0) {
    n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
    decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
  }
  while (i_len > 0) {
    if ((++i % 3 == 1) && (i_len != n[0].length)) {
      integer = t_pt.concat(integer);
    }
    integer = n[0].substr(--i_len, 1).concat(integer);
  }
  return (integer + decimal);
}      


//
//Fonte:http://www.nerdcore.com.br/blog/?p=11
//      http://www.somacon.com/p355.php
//
// example of using trim, ltrim, and rtrim
//
//var myString = " hello my name is ";
//alert("*"+myString.trim()+"*");
//alert("*"+myString.ltrim()+"*");
//alert("*"+myString.rtrim()+"*");
//
//alert(variable.trim());
//
//String.prototype.empty = (this.trim().length == 0 ? true : false);
//
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
    }

String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
    }

String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
    }
/*
* FIM - PROTOTYPES - ROGERIO
*
  **/












/*
 * Variaveis globais
 **/
//CARACTERES DIVERSOS
var letrasmai = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var letrasmin = "abcdefghijklmnopqrstuvwxyz";
var numeros   = "0123456789";
var emails    = letrasmin+"_."+numeros;
var telefones = "()-x "+numeros;
//CARACTERES UNICOS
var emailsc   = "@";
var moeda     = ",";
//MASCARAS
var datas     = "  /  /    ";
var horas     = "  :  ";

/*
 * Tipo do navegador
 **/
var agt = navigator.userAgent.toLowerCase();
var is_ie	    = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_opera  = (agt.indexOf("opera") != -1);
var is_mac    = (agt.indexOf("mac") != -1);
var is_mac_ie = (is_ie && is_mac);
var is_win_ie = (is_ie && !is_mac);
var is_gecko  = (navigator.product == "Gecko");



function abre_PopUp(larg,altura,link)
{
  var vl_alt  = parseInt(altura);
  var vl_lar  = parseInt(larg);
  var desktop = window.open(link, "_blank", "width="+vl_lar+",height="+vl_alt+",toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,top=120,left=120" );
}

function js_PopUp(pPagina,pJanela,pLargura,pAltura,pScroll,pResize,autoClose) {

  var posX = (window.screen.width - pLargura - 16) / 2;
  var posY = (window.screen.height - pAltura) / 2;
  var win = window.open(pPagina,pJanela,"width=" + pLargura + ",height=" + pAltura + ",top=" + posY + ",left=" + posX + ",scrollbars=" + pScroll + (pResize ? ",resizable=yes" : ""));
  if(win){
    win.focus();
    if (autoClose){
      if (is_ie) {
        attachEvent("onunload", function(){closePop(win)});
      } else {
        addEventListener("unload", function(){closePop(win)}, true);
      }
    }
  }
  return win;
}
/*
 * Abre uma janela pop-up no centro da tela
    **/
function abrePop(pPagina,pLargura,pAltura,pScroll,pResize,autoClose) {
  var name = pPagina.substr(pPagina.lastIndexOf("/")+1,pPagina.lastIndexOf(".")-pPagina.lastIndexOf("/")-1);
  var posX = (window.screen.width - pLargura - 16) / 2;
  var posY = (window.screen.height - pAltura) / 2;
  var win = window.open(pPagina,name,"width=" + pLargura + ",height=" + pAltura + ",top=" + posY + ",left=" + posX + ",scrollbars=" + pScroll + (pResize ? ",resizable=yes" : ""));
  if(win){
    win.focus();
    if (autoClose){
      if (is_ie) {
        attachEvent("onunload", function(){closePop(win)});
      } else {
        addEventListener("unload", function(){closePop(win)}, true);
      }
    }
  }
  return win;
}

/*
 * Testa se a popup existe e fecha a mesma
 **/
function closePop(obj){
  if(!isNull(obj))
    if(!obj.closed)
      obj.close();
  return true;
}

/*
 * Executa o metodo submit do formulario
 **/
function doSubmit(tform){
  if (tform && !tform.action) tform = document.getElementById(tform);
  if (tform) {
    if (!tform.onsubmit || tform.onsubmit()){
      tform.submit();
      return true;
    }
    return false;
  }
  alert("Formulario nao encontrado!");
  return false;
}

/*
 * Redireciona a pagina para a url informada
 **/
function redirect(url){
  document.location.href=url;
}

/*
 * Verifica se a tecla pressionada pode ser incluida no campo
 **/
function testaMascara(obj,str,strone,mask,mykey){
  //SE O CAMPO EH READONLY CAI FORA
  if (obj.readOnly) return false;

  if (document.selection){
      document.selection.createRange().text = "";
  }else if (obj.selectionStart || obj.selectionStart == "0"){
    var selectionStart = obj.selectionStart;
    var selectionEnd = obj.selectionEnd;
    obj.value = obj.value.substring(0, selectionStart) + obj.value.substring(selectionEnd);
    obj.setSelectionRange(selectionStart, selectionStart);
  }

  //VERIFICA TECLA EH IGUAL A MASCARA OU VALIDA EM "str" E "strone"
  if (mykey == mask.charAt(obj.value.length) && mykey != " " && mykey != "%") return true;
  if ((str+strone)!="" && (str+strone).indexOf(mykey) ==-1) return false;
  if (strone!="" && obj.value.indexOf(mykey)!=-1 && strone.indexOf(mykey)!=-1) return false;

  //VERIFICA MASCARA
  if(mask.charAt(0)=="%"){
    var mylength=0;
    var i=mask.length;
    while(i>0 && mylength==0){
      i--;
      if(obj.value.lastIndexOf(mask.charAt(i))!=-1) mylength=i;
    }
    obj.value=obj.value.substr(0,obj.value.length-mylength)+mykey+mask.substr(1,mask.length);
    return false;
  }

  if(mask.charAt(mask.length-1)=="%"){
    if(obj.value=="") obj.value=mask.substr(0,mask.indexOf("%"));
    return true;
  }

  var tam=obj.value.length;
  while (mask.charAt(tam) && mask.charAt(tam)!=" " && tam<=mask.length){
    if(mask.charAt(tam)!=" ") obj.value+=mask.charAt(tam);
    tam++;
  }
  if(mask.substr(tam+1,mask.length-tam).indexOf(" ")==-1 && tam<mask.length && mask.length-tam!=1){
    obj.value+=mykey+mask.substr(tam+1,mask.length-tam);
    return false;
  }

  if(obj.value.length<mask.length || mask.length==0) return true;
  if(obj.value.length>mask.length) obj.value=obj.value.substr(0,mask.length);
  return false;
}

/*
 * Verifica a mascara e retorna se a tecla pressionada pode ser incluida no campo
 **/
function maskedit(eve,obj,str,strone,mask) {
  var codesIE = new Array(8,9,13);
  var codesMZ = new Array(8,9,13,33,35,36,37,38,39,40,46,112,113,114,115,116,117,118,119,120,121,122,123);
  if (!eve) eve = window.event;
  var code;
  var li;
  if (is_gecko){
    code = eve.keyCode;
    for (li=0; li<codesMZ.length; li++) if(code == codesMZ[li]) return true;
    code = eve.charCode;
  }else{
    code = eve.keyCode ? eve.keyCode : eve.which ? eve.which : void 0;
    for (li=0; li<codesIE.length; li++) if(code == codesIE[li]) return true;
  }
  return testaMascara(obj,str,strone,mask,String.fromCharCode(code));
}

/*
 * Verifica se o valor eh valido
 **/
function isNull(str){ return (str+"" == "null"); }
function isUndefined(str){ return (str+"" == "undefined"); }
function isEmpty(str){
  if(!str) return true;
  if (str.value) str = str.value;
  return (str+"" == "") || (str+"" == ".") || (str+"" == " ");
/*
  var invalid = " .\n\t";
  for(var li=0;li<str.length;li++) {
    if(invalid.indexOf(str.charAt(li)) != -1) return false;
  }
  return true;
*/
}

/*
 * Retorna se o campo TEXT foi preenchido
 **/
function okText(obj,desc,value){
  if(!obj) return true;
  if (isNull(obj.value) || isUndefined(obj.value) || ""+obj.value == "" || obj.value == value) {
    alert("Preencha o campo "+desc+"!");
    obj.focus();
    return false;
  }
  if (isEmpty(obj.value)) {
    alert("Preencha corretamente o campo "+desc+"!");
    obj.focus();
    return false;
  }
  return true;
}

/*
 * Verifica se o numero de caracteres nao excede o limite
 **/
function okLeng(obj,desc,tam){
  if(!obj) return true;
  if (obj.value.length>tam) {
    alert("O numero de caracteres excedeu o limite no campo "+desc+"!");
    obj.focus();
    return false;
  } else return true;
}
function okEqualLeng(obj,desc,tam){
  if(!obj) return true;
  if (obj.value.length != tam) {
    alert("O campo "+desc+" deve ter "+tam+" digitos!");
    obj.focus();
    return false;
  } else return true;
}
function okLessLeng(obj,desc,tam){
  if(!obj) return true;
  if (obj.value.length < tam) {
    alert("O campo "+desc+" deve ter no minimo "+tam+" digitos!");
    obj.focus();
    return false;
  } else return true;
}

/*
 * Retorna se o campo SELECT foi selecionado
 **/
function okList(obj,desc,value){
  if(!obj) return true;
  if (isEmpty(obj.value) || obj.value == value) {
    alert("Selecione o campo "+desc+"!");
    obj.focus();
    return false;
  } else return true;
}

/*
 * Retorna se o campo RADIO foi marcado
 **/
function okRadio(obj,desc){
  if(!obj) return true;
  if (!obj.length) {
    if(obj.checked) return true;
    alert("Selecione o campo "+desc+"!");
    obj.focus();
    return false;
  }

  for(var li=0;li<obj.length;li++){
    if(obj[li].checked) return true;
  }
  alert("Selecione o campo "+desc+"!");
  obj[0].focus();
  return false;
}

/*
 * Retorna se o campo DATA foi preenchido corretamente
 **/
function okDate(obj,desc) {
  if(!obj) return true;
  if (obj.value == "") return true;
  
  var meses = new Array(31,29,31,30,31,30,31,31,30,31,30,31);

  if (obj.value.length==5) obj.value = obj.value + "/2004";
  if (obj.value.length<10 && obj.value.substr(1,1)=="/") obj.value = "0"+obj.value;
  if (obj.value.length<10 && obj.value.substr(4,1)=="/") obj.value = obj.value.substr(0,3)+"0"+obj.value.substr(3);
  if (obj.value.length==8 && obj.value.substr(2,1)=="/" && obj.value.substr(5,1)=="/") obj.value = obj.value.substr(0,6)+"20"+obj.value.substr(6);

  if (obj.value.substr(2,1)!="/" || obj.value.substr(5,1)!="/" || isNaN(obj.value.substr(0,2)) || isNaN(obj.value.substr(3,2)) || isNaN(obj.value.substr(6,4))){
    alert("Preencha corretamente o campo "+desc+"!");
    obj.focus();
    return false;
  }
  
  if (0+obj.value.substr(6,4)<1900 || 0+obj.value.substr(6,4)>2010){
    alert("Ano invalido no campo "+desc+"!");
    obj.focus();
    return false;
  }
  
  if (0+obj.value.substr(3,2)<1 || 0+obj.value.substr(3,2)>12){
    alert("Mes invalido no campo "+desc+"!");
    obj.focus();
    return false;
  }
  
  if (0+obj.value.substr(0,2)<1 || 0+obj.value.substr(0,2)>31 || 0+obj.value.substr(0,2) > meses[obj.value.substr(3,2)-1]){
    alert("Dia invalido para o mes especificado no campo "+desc+"!");
    obj.focus();
    return false;
  }
  
  return true;
}


function DataOK(Dia, Mes, Ano)
{
  var err=0;
  var vl_Dia = Dia.value;
  var vl_Mes = Mes.value;
  var vl_Ano = Ano.value;
  
  if (vl_Dia.length!= 2) { Dia.value = '0'+Dia.value; }
  if (vl_Mes.length!= 2) { Mes.value = '0'+Mes.value; }
  
  var vl_Dia = Dia.value;
  var vl_Mes = Mes.value;  

  if (vl_Dia.length != 2)
      err=12;
  else if (vl_Mes.length != 2)
           err=13;
       else if(vl_Mes<1 || vl_Mes>12)
               err = 1;
            else if(vl_Dia<1 || vl_Dia>31)
                    err = 3;
                 else if(vl_Mes==4 || vl_Mes==6 || vl_Mes==9 || vl_Mes==11)
                       {
                         if(vl_Dia==31) err=6;
                       }
                      else if(vl_Mes==2)
                           {
                             if(vl_Dia>29)
                                err=8;
                             else if(vl_Dia==29 && ((vl_Ano/4)!=parseInt(vl_Ano/4)))
                                     err=9;
                           }
                      if (err!=0)
                           {
                             alert("A data " + vl_Dia + "/" + vl_Mes + "/" + vl_Ano + " não é válida !");
                             return false;
                           }
                      else
                             return true;
}



/*
 * Retorna se o campo EMAIL foi preenchido corretamente
 **/
function okEmail(obj,desc,value) 
{
  if (!obj) return true;
  
  if (!okText(obj,desc,value)) 
     {
       return false;
     } 
  else
     {
       if((obj.value.indexOf("@")     <  2) ||
          (obj.value.substring(obj.value.indexOf("@")+1,obj.value.length).indexOf(".")<2) ||
          (obj.value.indexOf("@")     != obj.value.lastIndexOf("@")) ||
          (obj.value.lastIndexOf(".") >= obj.value.length-2))
          {
            alert("Preencha corretamente o campo "+desc+"!");
            obj.focus();
            return false;
          } 
       else 
         {
           //validacao2 - via expressao regular
           var str = obj.value;
           var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
           if(!filter.test(str))
             {
               alert ("O campo " + desc + " deve ser conter um endereco eletronico!");
               obj.focus();
               return false;
             }  
         }
     }
  return true;  
}

/*
 * Verifica se o digito de um CPF/CNPJ eh valido
 */
function okCPFCNPJ(obj, desc) {
  if(!obj) return true;
	var s_aux = obj.value;
	sOK = false;
	if (s_aux.length == 11 ) {
		var d1, d2;
		var digito1, digito2, resto;
		var digitoCPF;
		var nDigResult;
		d1 = d2 = 0;
		digito1 = digito2 = resto = 0;
		for (var n_Count = 1; n_Count < s_aux.length -1; n_Count++) {
			digitoCPF = eval(s_aux.charAt(n_Count -1));
			d1 = d1 + ( 11 - n_Count ) * digitoCPF;
			d2 = d2 + ( 12 - n_Count ) * digitoCPF;
		}
		resto = (d1 % 11);
		if (resto < 2) digito1 = 0;
		else digito1 = 11 - resto;
		d2 += 2 * digito1;
		resto = (d2 % 11);
		if (resto < 2) digito2 = 0;
		else digito2 = 11 - resto;
		var nDigVerific = s_aux.substring (s_aux.length-2, s_aux.length);
		nDigResult = (""+digito1) + (""+digito2);
		sOK = nDigVerific == nDigResult;
	} else if (s_aux.length == 14) {
		var soma = 0, dig;
		var cnpj_calc = s_aux.substring(0,12);
		var chr_cnpj = s_aux;
		for(var i = 0; i < 4; i++ ) soma += chr_cnpj.charAt(i) * (6 - (i + 1));
		for(var i = 0; i < 8; i++ ) soma += chr_cnpj.charAt(i+4) * (10 - (i + 1));
		dig = 11 - (soma % 11);
		cnpj_calc += ( dig == 10 || dig == 11 ) ? "0" : ""+dig;
		soma = 0;
		for (var i = 0; i < 5; i++ ) soma += chr_cnpj.charAt(i) * (7 - (i + 1));
		for (var i = 0; i < 8; i++ ) soma += chr_cnpj.charAt(i+5) * (10 - (i + 1));
		dig = 11 - (soma % 11);
		cnpj_calc += ( dig == 10 || dig == 11 ) ? "0" : ""+dig;
		sOK = s_aux == cnpj_calc;
	}
	if (!sOK) {
       alert(desc+" invalido!");
       obj.focus();
	}
	return sOK;
}

/*
 * Verifica se o cartao de credito eh valido
 */
function okCartaoCredito(obj) {
	var cartao = obj.value;
	if (cartao.length > 19) return false;
	var sum = 0; 
	var mul = 1; 
	var l = cartao.length;
	for (var i = 0; i < l; i++) {
		var digit = cartao.substring(l-i-1,l-i);
		var tproduct = parseInt(digit ,10)*mul;
		if (tproduct >= 10) sum += (tproduct % 10) + 1;
		else sum += tproduct;
		if (mul == 1) mul++;
		else mul--;
	}
	if (sum % 10 == 0) return true;
	alert("Cartao de Credito invalido!");
	obj.focus();
}

/*
 * Converte a string passada em numero
 **/
function toNumber(valor,depois){
  if(!valor) valor = "0,00";
  if(""+depois=="undefined") depois = 2;
  valor = "" + valor;
  try{
    while(valor.indexOf(".")>-1) valor = valor.replace(".","");
    valor = valor.replace(",",".");
    if(valor.indexOf(".")<0) valor += ".0";
    valor = valor.substring(0,valor.indexOf(".")+depois+1);
    if(valor=="") valor = 0.0;
    return eval("1*"+valor);
    //return Math.round(valor*Math.pow(10,depois))/Math.pow(10,depois);
  }catch(e){
    return "isNaN";
  }
}
function toCurr(valor,depois){
  if(!valor) valor = "0,00";
  if(""+depois=="undefined") depois = 2;
  valor = "" + valor;
  try{
    valor = valor.replace(".",",");
    if(valor.indexOf(",")==-1) valor = valor + ",0";

    var aux = valor.substring(valor.lastIndexOf(","),valor.lastIndexOf(",")+depois+1);
    valor = valor.substring(0,valor.lastIndexOf(","));
    while(valor.length>3){
      aux = "." + valor.substring(valor.length-3,valor.length) + aux;
      valor = valor.substring(0,valor.length-3);
    }
    valor = valor + aux;
  }catch(e){
    valor = "0,00";
  }
  if(depois==0) valor = valor.substring(0,valor.indexOf(","));
  else while(valor.indexOf(",")>=valor.length-depois) valor = valor + "0";
  return valor;
}

function toCurrSemPto(valor,depois){
  if(!valor) valor = "0,00";
  if(""+depois=="undefined") depois = 2;
  valor = "" + valor;
  try{
    valor = valor.replace(".",",");
    if(valor.indexOf(",")==-1) valor = valor + ",0";

    var aux = valor.substring(valor.lastIndexOf(","),valor.lastIndexOf(",")+depois+1);
    valor = valor.substring(0,valor.lastIndexOf(","));
    while(valor.length>3){
      aux = "." + valor.substring(valor.length-3,valor.length) + aux;
      valor = valor.substring(0,valor.length-3);
    }
    valor = valor + aux;
  }catch(e){
    valor = "0,00";
  }
  if(depois==0) valor = valor.substring(0,valor.indexOf(","));
  else while(valor.indexOf(",")>=valor.length-depois) valor = valor + "0";
  
  
  valor = valor.replace(".","");
  
  return valor;
}


/*
 * Retorna se o campo NUMBER eh valido
 **/
function okNumber(obj,desc){
  if(!obj) return true;
  if (isNaN(toNumber(obj.value))) {
    alert("O campo "+desc+" nao contem um numero valido!");
    obj.focus();
    return false;
  } else return true;
}

function disableField(obj,disable) {
  obj.disabled = disable;
  obj.style.backgroundColor = (disable ? "#ECE9D8" : "");
}

// inserão dos swf - animações em flash - bug winxp
function flash (URL, WIDTH, HEIGHT, TRANSPARENT, ID) {
  if (is_ie) {
    document.write (' <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ');
    document.write (' codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" ');
    document.write (' id="'+ ID +'" ');
    document.write (' width="'+ WIDTH +'" height="'+ HEIGHT +'">');
    document.write (' <param name="movie" value="'+ URL +'" />');
    document.write (' <param name="quality" value="high" />');
    document.write (' <param name="salign" value="L" />');
    if ( TRANSPARENT ) document.write (' <param name="Wmode" value="Transparent" />');
    document.write (' </object> ');
  } else {
    document.write (' <embed src="'+ URL +'" quality="high" ');
    if ( TRANSPARENT ) document.write (' Wmode = "transparent" ');
    document.write (' pluginspage="https://www.macromedia.com/go/getflashplayer" ');
    document.write (' type="application/x-shockwave-flash" salign="L" ');
    document.write (' id="'+ ID +'" width="'+ WIDTH +'" height="'+ HEIGHT +'"></embed> ');
  }
}


/*####################################FUNÇÕES NICOLAS###########################################*/

function verifica_horas(obj)
{
	if(obj.value.length < 8)
		obj.value = '';
	else
	{
		hr = parseInt(obj.value.substring(0,2));
		mi = parseInt(obj.value.substring(3,5));
		se = parseInt(obj.value.substring(6,8));
		if((hr < 0 || hr > 23) || (mi < 0 || mi > 60) || (se < 0 || se > 60 ))
		{
			obj.value = '';
			alert('Hora inválida');
		}
	}
}

function valida_horas(edit, ev)
{
	li = new Array(':');
	liE = new Array(58);
	
	somenteNumero(edit,ev,li,liE);
	
	if(edit.value.length == 2 || edit.value.length == 5)
	edit.value += ":";
}

function somenteNumero(obj,e,liberado,liberadoE)
{

	var valor, val;
	
	if(liberado == '')
		liberado = new Array(',','.');
	if(liberadoE == '')
		liberadoE = new Array(188,190,8);

	valor = obj.value;
	if(document.all)
	{
		if(!((e.keyCode > 47 && e.keyCode < 58) || Array.find(liberadoE,e.keyCode) != '-1' ))
		{
			obj.value = valor.substr(0,valor.length - 1);
		}
	}
	else
	{
		val = '';
		
		for (x = 0; x < valor.length; x++)
		{
			if(!isNaN(valor[x]) || Array.find(liberado,valor[x]) != '-1')
			{
				val += valor[x];
			}
		}
		obj.value = val;
	}
}

Array.find = function(ary, element)
{
    for(var i=0; i<ary.length; i++)
	{
        if(ary[i] == element)
		{
            return i;
        }
    }
    return -1;
}

function buscaRetorno(campo, valor, clo)
{
	
	obj = opener.document.getElementById(campo);
	obj.value = valor;
	
	if(clo == 1)
		window.close();
}

function closeObj(id, method)
{
	obj = document.getElementById(id);
	
	if(method == 'display')
		obj.style.display = 'none';
	else
		obj.style.visibility = 'hidden';
	
}

function openObj(id, method)
{
	obj = document.getElementById(id);
	
	if(method == 'display')
		obj.style.display = 'block';
	else
		obj.style.visibility = 'visible';
	
}


function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


function Abas(id)
{
	ob1 = 'evento';
	ob2 = 'ingressos';
	
	bt1 = document.getElementById('ev');
	bt2 = document.getElementById('in');
	
	if(id == 1)
	{
		closeObj(ob2,'display');
		openObj(ob1,'display');
		
		bt1.className = 'choose';
		bt2.className = '';
	}
	else
	{
		closeObj(ob1,'display');
		openObj(ob2,'display');
		
		bt2.className = 'choose';
		bt1.className = '';
	}
	
}



function somente_numero(campo)
{
  var digits="0123456789"
  var campo_temp
  for (var i=0;i<campo.value.length;i++)
   {
      campo_temp=campo.value.substring(i,i+1)
      if (digits.indexOf(campo_temp)==-1)
      {
         campo.value = campo.value.substring(0,i);
         break;
      }
   }
}



//
//onkeypress="return Numerico(event,false);"
// 
function Numerico(p_e,p_virg)
{
         //alert('[' + p_e.keyCode + '][' + p_e.charCode + ']');
         if (isIE())
                     { var Tecla = window.event.keyCode;
                       event.cancelBubble = true;
                       //alert("tecla["+Tecla+"]");
                       if(Tecla == 44)
                         {
                           if (p_virg)
                             { event.returnValue = true; }
                           else
                             { event.returnValue = false; }


                         }
                       else
                        {
                         if((Tecla > 47 && Tecla < 58)||(Tecla == 45))
                            {
                              event.returnValue = true;
                            }
                         else
                            {
                              event.returnValue = false;
                            }
                        }
                     }
                else { 

                       if (p_virg)
                          {
                            if (p_e.charCode == 44 && p_e.keyCode == 0) 
                               { return true; }
                          }    

                       if ((p_e.charCode < 48 || p_e.charCode > 57) && p_e.keyCode == 0)                    
                          { return false; }
                         else
                          { return true;  }

                     }
}


//
//onkeypress="return ehNumerico(event,false);"
// 
function ehNumerico(p_e,p_virg)
        {
         //alert('[' + p_e.keyCode + '][' + p_e.charCode + ']');
         if (isIE())
                     { var Tecla = window.event.keyCode;
                       event.cancelBubble = true;
                       //alert("tecla["+Tecla+"]");
                       if(Tecla == 44)
                         {
                           if (p_virg)
                             { event.returnValue = true; }
                           else
                             { event.returnValue = false; }


                         }
                       else
                        {
                         if((Tecla > 47 && Tecla < 58)||(Tecla == 45))
                            {
                              event.returnValue = true;
                            }
                         else
                            {
                              event.returnValue = false;
                            }
                        }
                     }
                else { 

                       if (p_virg)
                          {
                            if (p_e.charCode == 44 && p_e.keyCode == 0) 
                               { return true; }
                          }    

                       if ((p_e.charCode < 48 || p_e.charCode > 57) && p_e.keyCode == 0)                    
                          { return false; }
                         else
                          { return true;  }

                     }
        }



/* ======================================================================================= */
/* INICIO, TRATAMENTO HORAS                                                                */
/* ======================================================================================= */
function horas_dois_pontos(event, tempo)
{
  if(event.keyCode==8)
    {
      tempo.value = '';
    }
   else
    {
     if(event.keyCode<48 || event.keyCode>57)
       {
          event.returnValue=false;
       }
       
     if(tempo.value.length==2 || tempo.value.length==5)
       {
         tempo.value+=":";
       }
    }
}

function horas_valida(event, tempo){

  if (tempo.maxLength!=tempo.value.length) 
     { 
	   var vl_i = 0;
	   while (tempo.value.length < 8)
	   {
	      vl_i++;
	
	      //alert('tamanho [' + tempo.maxLength + '][' + tempo.value + '] [' + tempo.value.length + ']');
	
	      if (vl_i>20) { alert('culatra [' + tempo.value.length + ']'); return false; }
	      
	      if (tempo.maxLength>5)
	         {
			   if ( tempo.value.length==2 || tempo.value.length==5 ) { tempo.value+=":"; }
	         }
	      else   
	         {
			   if ( tempo.value.length==2 ) { tempo.value+=":"; }
	         }
	      tempo.value+="0";
	   }
     }

   horario = tempo.value.split(":");
   var horas    = horario[0];
   var minutos  = horario[1];
   var segundos = horario[2];
   if (horas > 24)
      { //para relógio de 12 horas altere o valor aqui
        alert('Hora deve ser entre 00 e 24!');
        tempo.value = '';
        tempo.focus();
        return false;
      }
   if (minutos > 59)
      {
        alert('Minutos devem ser entre 00 e 59!');
        tempo.value = '';
        tempo.focus()
        return false;
      }
   if (segundos > 59)
      {
        alert('Segundos devem ser entre 00 e 59!');
        tempo.value = '';
        tempo.focus()
        return false;
      }

  return true;

}



/* ======================================================================================= */
/* INICIO, TRATAMENTO DATA - BISSESTO                                                      */
/* ======================================================================================= */
/* ------------------------------- */
   function data_barras(event, data)
/* ------------------------------- */
{
  if(event.keyCode==8)
    {
      data.value = '';
    }
  else    
    {
      if(event.keyCode<48 || event.keyCode>57)
        {
           event.returnValue=false;
        }
      if(data.value.length==2 || data.value.length==5)
        {
           data.value+="/";
        }
    }
}



/* ------------------------------- */
   function TestaData(vl_data)
/* ------------------------------- */
{
 // ----( checa barras )-------------------------------------//
 if ((vl_data.value.substring(2,3)!="/")||(vl_data.value.substring(5,6)!="/"))
       {
         alert("Você deverá informar a data no formato DD/MM/AAAA \n Importante: utilize '/' para separar dia/mes/ano !");
         return false;
       }

 // ----( checa dia numerico )-------------------------------//
 if (vl_data.value.substring(0,1)=="0")
    { dia=parseInt(vl_data.value.substring(1,2)); }
   else
    { dia=parseInt(vl_data.value.substring(0,2)); }
 if (!parseInt(dia))
       {
         alert("Você deverá informar um dia válido entre 01 e 31 !");
         return false;
       }

 // ----( checa mes numerico )-------------------------------//
 if (vl_data.value.substring(3,4)=="0")
    { mes=parseInt(vl_data.value.substring(4,5)); }
   else
    { mes=parseInt(vl_data.value.substring(3,5)); }
 if (!parseInt(mes))
       {
         alert("Você deverá informar um mes válido entre 01 e 12 !");
         return false;
       }

 // ----( checa ano numerico )-------------------------------//
 ano=parseInt(vl_data.value.substring(6,10));
 if (!parseInt(ano))
       {
         alert("Você deverá informar a data no formato DD/MM/AAAA \n Importante: O ano deverá ser superior a 1870 !");
         return false;
       }

 //==========================================================//

 // ----( checa dia valido   )-------------------------------//
 if (vl_data.value.substring(0,2) > 31)
    {alert("A dia da data esta errado 'maior que 31'!!!");
     return false;
    }
 // ----( checa mes valido   )-------------------------------//
 if (vl_data.value.substring(3,5) > 12)
    {alert("O mes da data esta errado 'maior que 12'!!!");
     return false;
    }
 // ----( checa ano valido   )-------------------------------//
 if (vl_data.value.substring(6,10) < 1870)
    {alert("Você deverá informar a data no formato DD/MM/AAAA \n Importante: O ano deverá ser superior a 1870 !");
     return false;
    }
 if(DataOK(vl_data.value.substring(0,2),
           vl_data.value.substring(3,5),
           vl_data.value.substring(6,10)) == false) return false;

 return true;
}

function DataOK(Dia, Mes, Ano)
{
  var err=0;

  if (Dia.length != 2)
      err=12;
  else if (Mes.length != 2)
           err=13;
       else if(Mes<1 || Mes>12)
               err = 1;
            else if(Dia<1 || Dia>31)
                    err = 3;
                 else if(Mes==4 || Mes==6 || Mes==9 || Mes==11)
                       {
                         if(Dia==31) err=6;
                       }
                      else if(Mes==2)
                           {
                             if(Dia>29)
                                err=8;
                             else if(Dia==29 && ((Ano/4)!=parseInt(Ano/4)))
                                     err=9;
                           }
                      if (err!=0)
                           {
                             alert("A data " + Dia + "/" + Mes + "/" + Ano + " não é válida !");
                             return false;
                           }
                      else
                             return true;
}
/* ======================================================================================= */
/* FINAL FUNCOES, TRATAMENTO DATA                                                          */
/* ======================================================================================= */


function verificaPopupBlocker() {
          var w = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
          if(w == null) {
              alert("Para prosseguir, por favor desabilite o bloqueador de pop-up.");
              return true;
          }
          w.close();
          return false;
}       	





/* ======================================================================================= */
/* Função que transforma um form em uma string que pode ser enviada por get                */
/* ======================================================================================= */
/** 
   idForm = id do form que será transformado
   
   --------------------------------------------------------------------------------------------------------
   p_apartir = Considerar a partir de qual posicao do "p_prefixo", pode ser util nos casos em que
               deve-se considerar tanto "_f_prefixo_campo1" como "nf_prefixo_campo2", sendo que neste caso
               se passar p_prefixo = 'f_prefixo' e p_apartir = '1' ele pegara tanto
               "_f_prefixo_campo1" quanto "nf_prefixo_campo2"
               ja se passar p_prefixo = 'f_prefixo' e p_apartir = '0' ele nao pegara nenhum dos dois
               e entao teria que passar ou p_prefixo = '_f_prefixo' ou p_prefixo = 'nf_prefixo'
   --------------------------------------------------------------------------------------------------------            
*/  
function jsger_BuscaElementosForm_DEPRECATED(idForm,p_prefixo,p_apartir,p_debug) 
{  
    var elementosFormulario = document.getElementById(idForm).elements;  
    var qtdElementos = elementosFormulario.length;  
    var queryString = "";  
    var elemento;  
  
    //Cria uma funcao interna para concatenar os elementos do form  
    this.ConcatenaElemento = function(nome,valor) {  
                                if (queryString.length>0) {  
                                    queryString += "&";  
                                }  
                                queryString += encodeURIComponent(nome) + "=" + encodeURIComponent(valor);  
                             };  
  
    //alert(p_prefixo);
    //alert(p_prefixo.length);
  
    //Loop para percorrer todos os elementos  
    for (var i=0; i<qtdElementos; i++) {  
        //Pega o elemento  
        elemento = elementosFormulario[i];
        
        if (!(elemento.name)) { continue; }
        
        vl_nome_ = elemento.name.substring(p_apartir,p_prefixo.length+p_apartir+1);
        vl_nome  = elemento.name.substring(p_apartir,p_prefixo.length+p_apartir);
        
        if (p_debug) { alert('[' + vl_nome_ + '] comparado com [' + p_prefixo+'_' + ']'); }
        
        if (!(vl_nome_ == p_prefixo+'_')) //Compara com sublinhado porque depois do prefixo sempre tem q ter um underline
           {                              // exemplo: prefixo "_pes"  a variavel deve ser "_fo_pes_nome",  "_fo_pes_id",  etc.. 
             continue;                    //          prefixo "_pesf" a variavel deve ser "_fo_pesf_nome", "_fo_pesf_id", etc..
           }  

        if (p_debug) { alert('ME SERVE => [' + elemento.name + '] >> ['+ vl_nome + ']'); }

        if (!elemento.disabled) {  
            //Trabalha com o elemento caso ele nao esteja desabilitado  
            switch(elemento.type) {  
                //Realiza a acao dependendo do tipo de elemento  
                case 'text': case 'password': case 'hidden': case 'textarea':  
                    this.ConcatenaElemento(elemento.name,elemento.value);  
                    break;  
                case 'select-one':  
                    if (elemento.selectedIndex>=0) {  
                        this.ConcatenaElemento(elemento.name,elemento.options[elemento.selectedIndex].value);  
                    }  
                    break;  
                case 'select-multiple':  
                    for (var j=0; j<elemento.options.length; j++) {  
                        if (elemento.options[j].selected) {  
                            this.ConcatenaElemento(elemento.name,elemento.options[j].value);  
                        }  
                    }  
                    break;  
                case 'checkbox': case 'radio':  
                    if (elemento.checked) {  
                        this.ConcatenaElemento(elemento.name,elemento.value);  
                    }  
                    break;  
            }  
        }  
    }  
    return queryString;  
}




/* ======================================================================================= */
/* Função para limpar os campos de um formulario, pelo prefixo                             */
/* ======================================================================================= */
/** 
   exemplo: jsger_limpaCampos('FPost','_f_ope_pes');
*/
function jsger_limpaCampos_DEPRECATED(p_form,p_prefixo) 
{
  vl_qtdCampos = (document.getElementById(p_form).elements.length-1);
  
  for (vl_x=0;vl_x<=vl_qtdCampos;vl_x++)
  {
     if (document.getElementById(p_form).elements[vl_x].name == undefined  ) { continue; }
     
     if (document.getElementById(p_form).elements[vl_x].name.substring(0,p_prefixo.length) == p_prefixo)
       {
         document.getElementById(p_form).elements[vl_x].value="";
       }
  }
}




/*                                    */
/* mascara generica em javascript     */
/*                                    */
/* 
/* exemplo: ... onKeyUp="mascaraCampos(event,'999.999.999-99')" 
 **/
function jsger_mascaraCampos_DEPRECATED(evento, mascara){  
      
    var campo, valor, i, tam, caracter;  
      
    if (document.all) // Internet Explorer  
       campo = evento.srcElement;  
    else // Nestcape, Mozzila  
        campo= evento.target;  
          
    valor = campo.value;  
    tam = valor.length;  
      
    for(i=0;i<mascara.length;i++){  
       caracter = mascara.charAt(i);  
       if(caracter!="9")   
          if(i<tam & caracter!=valor.charAt(i))  
             campo.value = valor.substring(0,i) + caracter + valor.substring(i,tam);  
                  
    }  
   
 } 



function jsger_getScreenWidth()  
{  
   // Thiago Marotta Couto  
   // thiago@isbyte.com  
   // http://thiagocouto.wordpress.com/
   // http://isbyte.com/?p=63  
   // December, 06 - 2008  
   return window.innerWidth ? window.innerWidth : /* For non-IE */  
               document.documentElement ? document.documentElement.clientWidth : /* IE 6+ (Standards Compilant Mode) */  
               document.body ? document.body.clientWidth : /* IE 4 Compatible */  
               window.screen.width; /* Others (It is not browser window size, but screen size) */  
}  


 
function jsger_getScreenHeight()  
{  
   // Thiago Marotta Couto  
   // thiago@isbyte.com  
   // http://thiagocouto.wordpress.com/
   // http://isbyte.com/?p=63  
   // December, 06 - 2008  
   return window.innerHeight ? window.innerHeight : /* For non-IE */  
               document.documentElement ? document.documentElement.clientHeight : /* IE 6+ (Standards Compilant Mode) */  
               document.body ? document.body.clientHeight : /* IE 4 Compatible */  
               window.screen.height; /* Others (It is not browser window size, but screen size) */  
}  
 

 
 
function jsger_getBodyHeight()  
{  

// VER MELHOR A SINTAXE PARA OUTROS NAVEGADORES
   // Thiago Marotta Couto  
   // thiago@isbyte.com  
   // http://thiagocouto.wordpress.com/
   // http://isbyte.com/?p=63  
   // December, 06 - 2008  

   return ( (jsger_getScreenHeight()>document.body.clientHeight) ? jsger_getScreenHeight() : document.body.clientHeight );
   
   //return document.body.clientHeight; 
   
//   window.innerHeight ? window.innerHeight : /* For non-IE */  
//                 document.documentElement ? document.documentElement.clientHeight : /* IE 6+ (Standards Compilant Mode) */  
//                 document.body ? document.body.clientHeight : /* IE 4 Compatible */  
//                 document.body.clientHeight; /* Others (It is not browser window size, but screen size) */  
}  



