function trace(s){ window.open("","trace").document.write(s) }
//-------------------------------------------------------------------------------------------------------------------------------------------------
function getNav() {
    var nv = navigator.userAgent;
    var vs = navigator.appVersion;
    var q = "IE";
    if (nv.indexOf("Opera")>-1) q = "OPERA";
    if (nv.indexOf("Firefox")>-1) q = "FIREFOX";
    if (nv.indexOf("Netscape")>-1) q = "NETSCAPE";
    if (nv.indexOf("Mozilla")>-1 && nv.indexOf("Netscape")==-1 && nv.indexOf("MSIE")==-1 && nv.indexOf("Firefox")==-1) q = "MOZILLA";

	var avs = null;
    if (q=="IE") {
        avs = vs.split(";");
        vs = parseFloat(avs[1].substring(5));
    } else if (q=="FIREFOX") {
        avs = nv.split("/");
        vs = parseFloat(avs[3]);
    } else
        vs = 0;

    var r = { n: q, v: vs };
    
    return r;
}
var NV = getNav();
var IE5 = NV.n=="IE"&NV.v<6?true:false;
var IE6 = NV.n=="IE"&NV.v==6?true:false;
var IE7 = NV.n=="IE"&NV.v==7?true:false;
var IE = NV.n=="IE"?true:false;
var FF = NV.n=="FIREFOX"?true:false;
var FF3 = NV.n=="FIREFOX"&NV.v==3?true:false;
var OP = NV.n=="OPERA"?true:false;
var MZ = NV.n=="MOZILLA"?true:false;
var NS = NV.n=="NETSCAPE"?true:false;
var VS = NV.v;
//###################################################################################################################################
//Apenas para IE6-
function fixLayerIE6(el) {
    var fr = ID(el.id + "_iframeIE");
    if(IE && el!=null) { 		
            if (fr==null) {
                    fr = CE("iframe");
                    fr.id = el.id + "_iframeIE";
            }
            var z = parseInt(el.style.zIndex)-1;
            var w = parseInt(el.offsetWidth);
            var h = parseInt(el.offsetHeight);

            //se as propriedades offset nï¿½o retornarem nada, tentar as style...
            if ( w==0 && parseInt(el.style.width)>0 ) w = parseInt(el.style.width);
            if ( h==0 && parseInt(el.style.width)>0 ) h = parseInt(el.style.height);

            //se estes valores forem zero, ï¿½ porque el ï¿½ uma tabela, com isso devo recuperar medidas para cada cï¿½lula
            if (w==0) {
                    var tb = getCellMaxTable(el); //Retorna qual linha tem mais cï¿½lunas e quantas sï¿½o			
                    var c = null;  
                    for(var y=0;y<tb.lengthCells;y++) {
                            c = el.rows[tb.indexRowMaxCells].cells[y];
                            w += parseInt(c.style.width);
                            h += parseInt(c.style.height);					
                    }		
            }
            with(fr.style) {
                    position = "absolute";		
                    zIndex = z;
                    width = w + "px";
                    height = h + "px";
                    top = parseInt(el.style.top) + "px";		
                    left = parseInt(el.style.left) + "px";							
                    filter = "alpha(opacity=00)";
            }		
            document.body.appendChild(fr);
    }	
    return fr;
}
//------------------------------------------
function clearFixLayerIE6(fr) {
    if(fr!=null) document.body.removeChild(fr);	
}	
//----------------------------------------------------------------------------
function createCookie(name, value, expires, path, domain, secure) {
    var objDate = new Date();
    objDate.setMonth(objDate.getMonth()+expires);
    document.cookie = name + "=" + escape(value) + 
    ((expires) ? "; expires=" + objDate.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +  
    ((secure) ? "; secure=" + secure : "");  
}
//------------------------------------------
function getValueCookie(name) {
    
    var valueCookie = function(offset){
        var endstr = document.cookie.indexOf(";", offset);
        if (endstr == -1) endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
    }
    
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
      var j = i + alen;
      if (document.cookie.substring(i,j) == arg) return valueCookie(j);
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) break;
    }
    return "";
}
//----------------------------------------------------------------------------
//Evitar que conteudo seja selecionado
function notSeletionDocument(evt,f) { 
    var e = IE?event.srcElement:evt.target; 
    var t = e.tagName.toLowerCase();
    //try {
            if (f==true && t!="input" && t!="textarea") {
                    if (IE) {
                            document.selection.empty(); 
                    } else {
                            var selection = window.getSelection(); 
                            selection.removeAllRanges();
                    }
            }
    //} catch(e) {};
}
//----------------------------------------------------------------------------
//Verifica qual e a medida e qual linha/coluna de uma tabela tem mais celulas
function getCellMaxTable(tb) {
    var c = 0,i,tC,y;
    for(y=0;y<tb.rows.length;y++) {
            tC = tb.rows[y].cells.length;
            if (c<tC) { //Linha com mais cï¿½lulas e seu index
                    c = tC;
                    i = y;
            }
    }	
    return { lengthCells:c , indexRowMaxCells:i };
}
//----------------------------------------------------------------------------
function setActionKeyPress(fcAnon,aKey,evt) {
    var k = IE ? event.keyCode : evt.keyCode; 
    for(var i=0;i<aKey.length;i++) if(aKey[i]==k) fcAnon();
    return true;
}
//----------------------------------------------------------------------------
//atribui ao keypress para cada elemento "aEl" uma action para cada keyCode "aKey"
function setKeyPress(aEl,aKey,fcAnon) {
    for(var i=0;i<aEl.length;i++) aEl[i].onkeypress = function(event){setActionKeyPress(fcAnon,aKey,event)};
}
//----------------------------------------------------------------------------
var TIMEKEYUP = null;
function setActionKeyTime(fnc,time) {
    time = time!=null ? time : 1100;
    clearTimeout(TIMEKEYUP);
    TIMEKEYUP = setTimeout(fnc,time);
}
//----------------------------------------------------------------------------
//Preenche combo com lista de valores
//----> listValues tem que ser uma string com formato possï¿½vel de transformar num array bidimencional
function setOptions(cb,listValues,vDefault) {
    var o = null, op = null, d = new Array(); 
    d = eval(listValues);
    cb.length = 0;
    for (var i=0;i<d.length;i++) {
            o = addOptions(cb,d[i][0],d[i][1]);	
            if (o.value.toUpperCase()==vDefault.toUpperCase()) {
                    o.selected = true;
                    op = o; //option atual selecionado
            }
    }
    return op;
}
//###################################################################################################################################
String.prototype.trim = function() {
    var r = this;
    var er = /^\s|\s$/;
    while (er.test(r)) r = r.replace(/^\s|\s$/g,"");
    return r;
}
//---------------------------------------------------------------------
// s = string e ser cadastrada na enumeration 
// b = 1 -> incluir nova se nao existir / b = 0 -> excluir valor de existir
String.prototype.setEnum = function(s,b) {
    var e = this; //alert(s);
    s = "{" + s + "}";
    e = b==1 ? (e.toUpperCase().indexOf(s.toUpperCase())==-1?e+=s:e) : e.replace(s,"").trim();
    return e.trim();
}
//-------------------------------------------
String.prototype.replaceAll = function(str,newStr){
    var r = this;
    while (r.indexOf(str)>-1) r = r.replace(str,newStr);
    return r;
}
//-------------------------------------------
String.prototype.toDate = function(){ //Somente formatos: dd/MM/yyyy HH:mm:ss
    var s = this;
    var x = s.length>10 ? s.indexOf(" ") : s.length;
    var a = s.substring( s.lastIndexOf("/")+1, x).trim();
    var m = s.substring( s.indexOf("/")+1, s.lastIndexOf("/") );
    var d = s.substring( 0, s.indexOf("/") ); 
    var H=0,M=0,S=0;
    if(s.length>10){ //data posssui HH:mm:ss
       H = s.substring( x, s.indexOf(":") ).trim();
       M = s.substring( s.indexOf(":")+1, s.lastIndexOf(":") );
       S = s.substring( s.lastIndexOf(":")+1 );
    } //alert(a + "\n" + m + "\n" + d + "\n" + H + "\n" + M + "\n" + S);
    return (s.length>10) ? new Date(a,m,d,H,M,S) : new Date(a,m,d);
}
//-------------------------------------------
//Verifica se "o" ja esta no array
Array.prototype.isExist = function(o){
    var a = this;
    var b = false;
    if(a.length>0){ //alert("Array: " + a);
        for(var i=0;i<a.length;i++){ //alert(a[i] + " = " + o);
            if(a[i].toLowerCase()==o.toLowerCase()) {
                b = true;
                break;
            }
        }
    }
    return b;
}
//---------------------------------------------------------------------
function isInt(n){ return n.toString().indexOf(".")>-1 ? false : true; }
//---------------------------------------------------------------------
function getEvent(evt){
    evt = IE?event:evt;
    var el = IE?event.srcElement:evt.target;
    return {event: evt, element: el};
}
//---------------------------------------------------------------------
//retorna codigo ou caracter capturado sobre o evento gerado pelo teclado
function getKey(evt){
    evt = getEvent(evt).event;
    var keyCode = evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.charCode);
    return { Char:String.fromCharCode( keyCode ), Code: keyCode }
}
//---------------------------------------------------------------------
function ID(id){  return document.getElementById(id) }
//---------------------------------------------------------------------
function CE(tg, id){
    var e = document.createElement(tg);
    if(typeof id!="undefined") e.id = id;
    return e;
}
//---------------------------------------------------------------------
function Div(id,html,css,objFather) {
    var d = CE("div", id);
    if(html!="undefined"&&html!=null) {
        if (typeof html=="object") d.appendChild(html); else d.innerHTML=html;
    }
    if(css!="undefined" && css!=null) d.className=css;
    if(objFather!="undefined" && objFather!=null) objFather.appendChild(d);
    return d;
}
//---------------------------------------------------------------------
function A(id,html,css,fa,objFather){
    var a = CE("a", id);
    if(IE) a.href = "javascript:void(0)";
    if(fa!="undefined") a.onclick = fa;
    if(html!="undefined"&&html!=null) { if (typeof html=="object") a.appendChild(html); else a.innerHTML=html; }
    if(css!="undefined" && css!=null) a.className=css;
    if(objFather!="undefined" && objFather!=null) objFather.appendChild(a);
    return a;
}
//---------------------------------------------------------------------
function Table(id,nRows,nCols,css,objFather){
    var tb = CE("table");
    tb.cellPadding = tb.cellSpacing = "0";
    tb.id = id;
    var r, c, i, y;
    for(i=0;i<nRows;i++){
        r = tb.insertRow(-1);
        for(y=0;y<nCols;y++) c = r.insertCell(-1);
    }
    if(css!="undefined" && css!=null) tb.className=css;
    if(objFather!="undefined" && objFather!=null) objFather.appendChild(tb);
    this.getTable = function(){ return tb; }
    this.getRow = function(r){
        r = r>=tb.rows.length ? tb.rows.length-1 : r;
        return tb.rows[r];
    }
    this.getCell = function(r,c){
        r = r>=tb.rows.length ? tb.rows.length-1 : r;
        c = c>=tb.rows[r].cells.length ? tb.rows[r].cells.length-1 : c;
        return tb.rows[r].cells[c];
    }
    this.getTable = function(){ return tb; }
    return this;
}
//---------------------------------------------------------------------
//verifica se elemento existe, se existir retorna proprio elemento, caso contrario cria um novo
function getElement(tag,id){
    var e = ID(id);
    if(e==null){
        e = CE(tag);
        e.id = id;
    }
    return e;
}
//---------------------------------------------------------------------
//Percorre todos elementos pai de cada elemento verificando se trecho de id e igual
function isParentElementId(e,id){
    var b = false;
    //percorre Dom ate tag HTML (ultima na hierarquia)
    while(e.offsetParent){ //alert(e.id);
        if(e.id.indexOf(id)>-1){
            b = true;
            break;
        } else
            e = e.offsetParent;
    }
    return b;
}
//---------------------------------------------------------------------
//Altera conteudo de um elemento
function setContent(e,html,cls){
    e = typeof e=="object" ? e : ID(e);
    cls = cls!="undefined"?cls:false; //se deve limpar o conteudo do elemento
    if(cls) e.innerHTML = "";
    if(typeof html=="object") e.appendChild(html); else e.innerHTML = html;
    return e;
}
//---------------------------------------------------------------------
//Altera conteudo de um elemento por um deternimado tempo
var _setTimeMessage = null;
function setTimeMessage(obj,msg1,msg2,time){
   setContent(obj,msg1);
   clearTimeout(_setTimeMessage);
   _setTimeMessage = setTimeout(function(){ setContent(obj,msg2) }, time!=null?time:3000 );
}
//---------------------------------------------------------------------
//retorna valor de um atributo se ele existir, caso contrario retorna vazio
function getAttrib(e,at,vlDefault){
    var a = e.getAttribute(at);
    a = a!=null ? a : vlDefault; //alert(e.id + " = " + a);
    return a;
}
//---------------------------------------------------------------------
function getChar13(s) {
    var ql = String.fromCharCode(13);
    if (s.indexOf(ql)>-1) {
            while (s.indexOf(ql)>-1) {
                    s = s.replace(ql,"{13}");      
                    s = s.replace(String.fromCharCode(9),"");  
                    s = s.replace(String.fromCharCode(10),""); 
            }
    } //alert(s);
    return s;
}
//---------------------------------------------------------------------
function validCharCode(s) {
    var c9 = String.fromCharCode(9);
    var c10 = String.fromCharCode(10);
    var c13 = String.fromCharCode(13);
    while ( 
            s.indexOf("{9}")>-1 ||
            s.indexOf("{10}")>-1 ||
            s.indexOf("{13}")>-1 ||
            s.indexOf(c10)>-1 || 
            s.indexOf(c9)>-1 || 
            s.indexOf(c10)>-1 || 
            s.indexOf(c13)>-1
          ){
                  s = s.replace("9"," ");
                  s = s.replace("10","\r");
                  s = s.replace("{13}","\n");
                  s = s.replace(c9," ");
                  s = s.replace(c10,"\r");  
                  s = s.replace(c13,"\n"); 
          }
    return s;
}
//---------------------------------------------------------------------
//Retorna posicao absoluta do elemento "el"
function getAbsolutePos(el) {
    el = typeof el=="object" ? el : ID(el);
    var SL = el.scrollLeft;
    var ST = el.scrollTop;
    var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
    if (el.offsetParent) { //Passa por cada elemento parent ate chegar no ultimo, o que ser usado como parametro de posicao
                    var tmp = this.getAbsolutePos(el.offsetParent);
                    r.x += tmp.x;
                    r.y += tmp.y;
    }
    return r;
}
//.....................................................
//retorna posicao do elemento "eIn" dentro do elemento "eSuper"
function getAbsolutePosInElement(eIn,eSuper){
    eIn = typeof eIn=="object" ? eIn : ID(eIn);
    eSuper = typeof eSuper=="object" ? eSuper : ID(eSuper);                    

    var pIn = getAbsolutePos(eIn);
    var pSuper = getAbsolutePos(eSuper); //alert(pSuper.y + "\n\n" + pIn.y);

    return { x:(pIn.x-pSuper.x), y:(pIn.y-pSuper.y) };                    
}
//---------------------------------------------------------------------
//offsetParent real para IE e FF, pois "offsetParent" retorna valores diferentes nestes navegadores
function getOffSetParent(elem) {
    if (elem.parentNode) {
            while (elem.parentNode != document.body) {
                    elem = elem.parentNode;
                    while (elem.nodeType != 1) {
                            elem = elem.parentNode;
                    }
                    if (elem.style.position == "absolute" || elem.style.position == "relative") {
                            return elem;
                    }
                    elem = elem.parentNode;
            }
            return null;
    } else if (elem.offsetParent && elem.offsetParent.tagName != "HTML") {
            return elem.offsetParent;
    } else {
            return null;
    }
}
//---------------------------------------------------------------------
function addOptions(cp,valor,texto) {	
    var oOption = CE("Option");
    oOption.value = valor;
    oOption.text = texto;
    try { cp.add(oOption, null); } // NS/FF
    catch(e) { cp.add(oOption); } // IE
    return oOption;
}
//---------------------------------------------------------------------
function isDate(d) { //Verifica se data  valida
    //Separa valores
    var dd = d.substring(0,d.indexOf("/"));	
    var mm = d.substring(d.indexOf("/")+1,d.lastIndexOf("/"));
    var aa = d.substring(d.lastIndexOf("/")+1,10);
    //alert(dd + " - " + mm + " - " + aa);

    //Inverter data para valor inglï¿½s, e cria data
    var dt = new Date(mm+"/"+dd+"/"+aa);
    var ddd = dt.getDate();
    var mmm = (dt.getMonth()+1);
    var aaa = dt.getFullYear();            
    //alert(ddd + " - " + mmm + " - " + aaa);

    return ( (dd==ddd & mm==mmm & aa==aaa) & parseInt(aa) > 1900 ) ? true : false;
}
//---------------------------------------------------------------------
//retorna diferenca em dias entre duas datas
function getDiffDays(objDate1, objDate2){
    var d1 = objDate1.getTime(); 
    var d2 = objDate2.getTime();
    var diff = d1-d2;
    diff = Math.floor(diff / (1000 * 60 * 60 * 24));	
    diff = parseInt(diff) + parseInt(1);
    return diff;
}
//---------------------------------------------------------------------
function maxLength(cp,mx) {
    var v = cp.value;
    if (v.length>mx) cp.value = v.substring(0,mx);
}
//---------------------------------------------------------------------
function setFormatDecimal(f,dc) {
    var str = f.value;
    var Dgts = "0123456789,";
    var temp = "";
    var dgt = "";
		
    for ( var i = 0; i < str.length; i++ ) {
    	dgt = str.charAt(i);
      	if ( Dgts.indexOf(dgt) >= 0 ) {
			if (dgt == "," & temp.indexOf(",") < 0) temp += dgt;
          	if (dgt != ",") temp += dgt;
		}
    }
    if (temp.indexOf(",") > 0) temp = temp.substring(0,temp.indexOf(",")+1+dc);
    f.value = temp;
}
//---------------------------------------------------------------------
//Formata value do input com formato numérico, respeitando valo maximo e casas dedimais
function setValueNumber(f,vMax) {
    var mx = vMax;
    var dc = mx.indexOf(".")>-1 ? mx.substring(mx.indexOf(".")+1).length : 0; 
    maxChar = mx.replace(/\D/g,"").length;
    setFormatDecimal(f,dc);
    var v = f.value.trim().replace(",",".");
    v = parseFloat(v)>parseFloat(vMax) ? mx : v;
    v = v.replace(".",",");
    f.value = v.substring(0, v.indexOf(",")==-1?maxChar:maxChar+1 );		
}
//---------------------------------------------------------------------
function getQueryString(f,esc){ //esc -> para setar "escape" no valores dos campos
    var qs = "", c, cfg, s, v, y, n;
    var t = f.elements.length;
    for(var i=0;i<t;i++){
        c = f.elements[i];
        if(c.type!="button" && qs.indexOf("&"+c.name+"=")==-1){ 
            s = "yes";
            v = "";            
            
            cfg = c.getAttribute("conf");
            if (cfg!=null) s = getParams(cfg,"save","yes");
            
            if(s=="yes"){
                n = c.name.toLowerCase();
                
                if(c.type=="radio" || c.type=="checkbox"){

                      for(y=i;y<t;y++){
                          c = f.elements[y];
                          if( (c.type=="radio" || c.type=="checkbox") && n==c.name.toLowerCase() ){
                            if(c.checked) v += "," + c.value;
                          }
                      }
                      if(v.substring(0,1)==",") v = v.substring(1);

                } else {

                    v = c.getAttribute("values"); //atributo especial do campos setados como droplist
                    v = v!=null ? v : c.value.trim();
                    v = v.trim().length==0 ? "null" : v; //alert(f.name + "\n\n" + c.type + " ---> " + c.name + " = " + c.value.trim());
                }

                //Nome do campo trocado pelo name do parametro "conf"
                if (cfg!=null) n = getParams(cfg,"name",n);
                
                qs += "&" + n + "=" + (esc?escape(v):v);
            }
        }        
    }  //trace(qs);
    if(qs.length>0) qs = qs.substring(1).trim(); //retirando primeiro "&"   
    return qs;
}
//---------------------------------------------------------------------
function clearInputsForms(f){
    var c, v, t;
    for(var i=0;i<f.elements.length;i++){
        c = f.elements[i];
        if (c.getAttribute("clear")!="no"){
            t = c.type; 

            if(t.indexOf("select")>-1) c.options[0].selected = true;
            if(t.indexOf("radio")==-1 && t.indexOf("checkbox")==-1 && t.indexOf("button")==-1) c.value = ""; 

            if (c.getAttribute("values")!=null) c.setAttribute("values",""); //atributo especial do campos setados como droplist
            if (c.getAttribute("defaultvalues")!=null){ //alert(c.name + " = " + c.getAttribute("defaultvalues"));
                c.setAttribute("values",c.getAttribute("defaultvalues")); 
                c.setAttribute("currentvalue",c.getAttribute("defaulttext"));
                c.value = c.getAttribute("defaulttext");
            }                     
        }
    }
}
//---------------------------------------------------------------------
//Seta valor para campo
function setValueInput(c,v){ //alert(c.name + " = " + v);
    var t = c.type;
    var f = getElementFather(c,"form");
    var i = 0;
    var dl = null;
    var s = "";
    if(t.indexOf("radio")>-1 || t.indexOf("checkbox")>-1){
        c = document.forms[f.name].elements[c.name];
        if(typeof c.length!="undefined"){ 
            for(i=0;i<c.length;i++) {
                c[i].checked = (c[i].value==v) ? true : false;
            }
        } else {
            c.checked = (c.value==v) ? true : false;
        }
    } else if (t.indexOf("select")>-1){
        for(i=0;i<c.options.length;i++){
            if(c.options[i].value==v) c.options[i].selected = true;
        }        
    } else {
        dl = c.getAttribute("droplist");
        if(dl!=null){            
            s = c.id;
            s = getDropListValues(s, v);
            setDropListValues(c,s.values,s.text); //caso existe, seleciona dados no div droplist
            c.setAttribute("values",v); //seta valor em "values" do droplist
        } else {
            //Trata da conversï¿½o dos caracteres especiais
            v = v.replaceAll("{13}", String.fromCharCode(13) );
            v = v.replaceAll("{10}", String.fromCharCode(10) );
            c.value = v;
        }        
    }
}
//---------------------------------------------------------------------
function getParams(args,param,valueDefault) {
    var s = valueDefault;
    var a = args.split(";");
    var p, v;
    for(var i=0;i<a.length;i++) {
            p = a[i].substring(0,a[i].indexOf(":")).trim(); 
            v = a[i].substring(a[i].indexOf(":")+1).trim(); //alert(p + "\n\n" + v);
            if (p.toLowerCase()==param.toLowerCase()) {
                    s = v=="true"||v=="false" ? eval(v) : v;
                    break;
            }
    }
    return s;
}
//---------------------------------------------------------------------
//Retorna elemento "el" acima de tag
function getElementFather(el,tag) {
    var f = null;
    el = el.parentNode;
    while (el) {
        if (el.tagName==tag.toUpperCase()) { 
            f = el;	
            break;
        }
        el = el.parentNode;				
    }
    return f;	
}
//---------------------------------------------------------------------
//gera um numero sempre diferente para uso de identificacao unica
function getUniqueKey(){
    var dt = new Date();
    return dt.getTime().toString();
}
//---------------------------------------------------------------------
//++++++++++++++++++++++++++++++++++++++++
Masks = {
    ALFANUMERIC : /[\w\s\-]/,
    NAMEFILE : /[a-zA-Z0-9\-]/,
    NUMERIC : /[\d]/,
    CURRENCY : /[0-9]/
}
//++++++++++++++++++++++++++++++++++++++++
function setInputMask(input, maskType, maxlength, valuemax){
    var mask = typeof maskType=="undefined" ? Masks.ALFANUMERIC : maskType;
    mask = typeof mask=="string" ? new RegExp(mask) : mask;
    maxlength = typeof maxlength=="undefined" ? 250 : maxlength;

    /* para masks currency */
    if(maskType.toString().indexOf("0-9")>-1){
        input.setAttribute("masktype","currency");
    }

    input.onkeypress = function(evt){
        var b = true;
        var k = getKey(evt); //document.title = k.Code;
        if( IE ? true : (FF && k.Code>0 && k.Code!=8 ? true : false) ){ //para o firefox, 0 = teclas navagacao, backspace, ... / 8 = tecla apagar
            var d = k.Char;
            var er = mask;
            b = er.test(d);
        }
        if(this.value.length >= maxlength) b = false;

        if(this.getAttribute("masktype")=="currency") b = maskCurrency(this,2);

        return b;
    }

    return true;
}
//++++++++++++++++++++++++++++++++++++++++
function maskCurrency(cp,cd){
    var b = true;
    var v = cp.value;
    var p = v.indexOf(",");
    if(p>-1 && v.substring(p).length>2) b = false;
    return b;
}
//---------------------------------------------------------------------
//Configura estado dos campos dos forms para apresentarem cor diferente quando estiverem com focus
function setStateInputForms(f){      
    this.activeStateInputs = function(f){
        var c, t, cfg, s = [], p, lbActv, clb, tp;
        for(var i=0;i<f.elements.length;i++){
            c = f.elements[i];
            t = c.type;            
            
            if (t!="hidden" && t!="button" && t!="submit" && t!="resize"){
                
                   
                cfg = c.getAttribute("conf"); //configuracoes personalizadas para o campo 
                
                if (cfg!=null){ //alert(cfg + "\n\n\nnull = " + getParams(cfg, "null", "yes"));
                    if (getParams(cfg, "null", "yes").toLowerCase()=="no") c.className += "_obrig";
                    
                    //campos numericos
                    tp = getParams(cfg,"type","");
                    if (tp.toLowerCase().indexOf("number")>-1){ 
                        c.setAttribute("masknumber", tp.substring( tp.indexOf("(")+1, tp.length-1 )); //alert(c.name + " = " + mask);
                        c.onkeyup = c.onkeypress = c.onkeydown = function(){ setValueNumber(this, this.getAttribute("masknumber") ) };
                    }
                    
                }
                
                s[f.name.concat(c.name)] = c.className;
                c.onfocus = function(){ this.className = this.className.replace("_obrig","").trim().concat("_focus") }
                c.onblur = function(){ this.className = s[f.name.concat(this.name)] }
                
                /* seta acao para ativar labels que envolvem inputs Radio ou Checkbox */
                if (t=="radio" || t=="checkbox"){
                    p = c.parentNode; //alert(p.tagName + "\n\n" + p.getAttribute("labelactive"));
                    lbActv = p.getAttribute("labelactive");
                    if (lbActv!=null){
                        p.onclick = function(){ 
                            clb = this.childNodes[0];
                            clb.checked = true; 
                            if(lbActv!="true" && lbActv!="false") clb.value = lbActv;
                        }
                    }
                }
            }
            
            //botoes para exibcao de detalhes de dados
            if (t=="button" && c.id.substring(0,7).toLowerCase()=="details"){
                c.appendChild(iconsSystem().Up);
                c.className = "btDetails";
                c.onmouseover = function(){ this.className = "btDetails_2" }
                c.onmouseout = function(){ this.className = "btDetails" }
                c.onclick = function(){
                    cfg = this.getAttribute("conf"); //configuracoes personalizadas para o campo 
                    var id = f.elements[ getParams(cfg, "id", "") ].getAttribute("values");
                    var module = getParams(cfg, "module", "");                    
                    if(id.length>0 && module.length>0){ //alert("id: " + id + " - module: " + module);
                        //chamar modulo passando id referencial
                        goActionModules(null,module,id);
                    }
                }
            }
        }
    }
    
    if (f!="undefined")
        activeStateInputs( typeof f=="object" ? f : ID(f) );
    else {
        var el = document.getElementsByTagName("form");
        for(var i=0;i<el.length;i++){ /*interar por cada form*/
            activeStateInputs(el[i]);
        }
    }   
}
//---------------------------------------------------------------------
function focusInputFirst(f){
    var c = null;
    for(var i=0;i<f.elements.length;i++){
        c = f.elements[i];       
        if (c.type!="hidden" && c.type!="button" && c.type!="submit" && c.type!="resize"){
            c.focus();
            break;
        }
    }
}
//---------------------------------------------------------------------
function isFormCorrect(f){
    var m = "", cfg, c, v;
    for(var i=0;i<f.elements.length;i++){
        c = f.elements[i];
        cfg = c.getAttribute("conf");
        if (cfg!=null){
            v = c.getAttribute("values"); //atributo especial do campos setados como droplist
            v = v!=null ? v : c.value.trim();
            if(getParams(cfg,"null","yes").toLowerCase()=="no" && v.length==0){
                m += "<li>O campo <strong>" + getParams(cfg,"legend",c.name) + "</strong> precisa ter um valor válido!</li>";
            }
        }
    }
    
    if(m.length>0) showDialogMessage("<ul>"+m+"</ul>");
   
    return m.length>0 ? false : true;
}
//---------------------------------------------------------------------
function setData(d){ //retorna objeto JSON 
    var o = eval(d); //alert(d);
    d = o.load();
    return { 
        size : o.size,
        fields : function(n){ return d[n] },            
        remove : function(n,i){ //remove elemento index = i
            var e = d[n];
            var ne = [];
            for(var y=0;y<e.length;y++){
                if(y!=i) ne.push(e[y]);
            }
            d[n] = ne; //seta novo array como novo conjunto de elementos
            return ne;
        }
    }
}
//---------------------------------------------------------------------
function openImage(e){

    if(typeof e=="string"){
        var elImg = new Image();
        elImg.src = e;
        e = elImg;
    }

    var closeImage = function(b,i){
        document.body.removeChild(b);
        if(i!=null) $(i).fadeOut("fast", function(){ document.body.removeChild(i) });
    }

    var img = null;
    var bkg = Div("background_" + e.id); //background
    with(bkg.style){
        position = "absolute";
        top = "0px";
        left = "0px";
        width = "100%";
        height = "100%";
        background = "#000 url(imgs/ajax-loader_0.gif) no-repeat 50% 50%";
        filter = "alpha(opacity:50)";
        opacity = "0.5";
        cursor = "pointer";
    }
    bkg.onclick = function(){ closeImage(this,img) }
    document.body.appendChild(bkg);

    //aguarda imagem carregar
    var setImage = function(el){

        el = typeof el=="undefined" ? this : el;


        bkg.style.backgroundImage = "none";

        var w = el.width;
        var h = el.height;
        var leg = el.title;

        img = CE("img");
        img.id = "open_image_" + el.id;
        img.title = "Clique na imagem para fechar!";
        img.src = el.src;
        img.onclick = function(){ closeImage(bkg,this) }

        with(img.style){
            position = "absolute";
            top = "50%";
            left = "50%";
            width = w + "px";
            height = h + "px";
            marginLeft = (-1*(w/2)) + "px";
            marginTop = (-1*(h/2)) + "px";
            border = "3px solid #000";
            display = "none";
            cursor = "pointer";
        }

        document.body.appendChild(img);
        $(img).fadeIn(150);
    }

    //este trecho cuida da situação de tentar reexibir a imagem, pois uma vez que a imagen foi carregada seu evento onload não mais é chamado
    if(e.complete) setImage(e);
    else e.onload = function(){ setImage(this) };

}
//---------------------------------------------------------------------
function getCoordMouse(evt){
    evt = getEvent(evt).event;
    return {
        x: !FF?evt.offsetX:evt.layerX, y: !FF?evt.offsetY:evt.layerY, /* ---------> coordenadas em relação ao elemento */
        X: evt.clientX, Y: evt.clientY /* ---------> coordenadas em relação ao Body */
    }
}
//---------------------------------------------------------------------
//retorna array de elementos "tag" que estão nivel abaixo de "e". Opção à getElementsByTagName que retorna os todos niveis abaixo.
function getChildTagName(e,tag){
    var c = e.childNodes;
    var a = [];
    for(var i=0;i<c.length;i++){
        if(c[i].tagName==tag.toUpperCase()) a[a.length] = c[i];
    }
    return a;
}
//---------------------------------------------------------------------
function getElementsByType(f,t){
    var e = f.elements, a = [];
    for(var i=0;i<e.length;i++){ if(e[i].type.indexOf(t)>-1) a[a.length] = e[i] }
    return a;
}
//---------------------------------------------------------------------
//Retorna próximo elemento superior que possui barra de rolagem. Recurso necessário para posicionamento absoluto correto.
function getElementScroll(e){
    var el = e.parentNode;
    while(el){
        if(el.scrollHeight > el.offsetHeight) break;
        el = el.parentNode;
    }
    return el;
}
//---------------------------------------------------------------------
function getAbsolutePosInElementScroll(e){
    var p, x, y;
    if(IE){
        p = getAbsolutePos(e);
        x = p.x;
        y = p.y;
    } else {
        p = getElementScroll(e);
        x = e.offsetLeft;
        y = e.offsetTop - (p ? p.scrollTop : 0);
    }
    return { x:x, y:y }
}
//---------------------------------------------------------------------
var listEVENTS = [];
function setEvents(objEvent,funcao,v) { 		
	var evento = objEvent.toLowerCase();
	evento = evento.substring( evento.indexOf(".on")+3 );		
	if (typeof listEVENTS[evento] == "undefined") listEVENTS[evento] = [];		
	
	//Add/Remove evento a lista
	if (v==true) listEVENTS[evento][listEVENTS[evento].length] = funcao;
	else { for (var i=0;i<listEVENTS[evento].length;i++) listEVENTS[evento][i] = (listEVENTS[evento][i]==funcao) ? "" : listEVENTS[evento][i]; }		
			
	evalEvents = function(evt,evento,funcao) {
		var s="";
		for (var i=0;i<listEVENTS[evento].length;i++) s += listEVENTS[evento][i] + "; ";        
		if (NS|MZ|FF) s = s.replace(/\bevent\b/g,"evt");
		return eval(s);
	}
	
	eval( objEvent + " = " + function(evt){ evalEvents(evt,evento,funcao); } ); //Seta evento e suas fun??es 
			
	return true;
}

//IEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIE
//Executa transparencia de arquivos PNG no IE
function validaAlphaPNG() {
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);    
    if ((version >= 5.5 && version < 7) && (document.body.filters)) {
        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:hand;" + 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-=1;
            }
        }
    }
}
//IEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIE