function fade(it, inicio, fim, time){
	
obj = document.getElementById(it);
obj.style.width='100%';

//document.getElementById(it).style.filter = 'Alpha(Opacity=50)';
//document.getElementById(it).style["opacity"] = 0.5;

if(inicio < fim) {
inicio += 10;
}else if(fim < inicio){
inicio -= 10;
}else{
return;
}

obj.style["filter"] = "Alpha(opacity="+inicio+")";
obj.style["opacity"] = inicio/100;
setTimeout(function(){ fade(it, inicio, fim,time); }, time);
}


   function Contador(field,MaxLength) {
      obj = document.all(field);
      if (MaxLength !=0) {
         if (obj.value.length > MaxLength)  {
            obj.value = obj.value.substring(0, MaxLength);
            }
      }
      document.getElementById('contador').value = MaxLength-obj.value.length+" caracteres restantes";
   }



function mascaraMil(objTextBox, SeparadorMilesimo, SeparadorDecimal, e,limite)
{
    
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    
    if (whichCode == 13 || whichCode == 8 || whichCode == 0) return true;
    
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    if (len > limite) return false; 
     
    var num = objTextBox.value.replace(/\./g, "");
    num = num.replace(/\,/g, "");
    num += key;
      
    for (i = num.length -1 ; i >= 0; i--){
        j++
        aux += num.charAt(i);
        if (j == 3){ 
            
            aux += SeparadorMilesimo;
            j = 0;
        }
        
    }
    
    if (aux.charAt(aux.length - 1) == ".") aux = aux.substring(0, aux.length -1);
    
    for(i = aux.length; i >= 0; i--){
        aux2 += aux.charAt(i - 1); 
    }
    
    objTextBox.value = aux2;
    
    /* 
    if (event.stopPropagation) {
        event.stopPropagation();
    }        
    event.cancelBubble = true; */ //para resolver o problema de duplicar o valor do campo, qdo tiver o atributo default button definido.
    
    return false;
}
documentall = document.all;
function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;      
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
           t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
   if (len== 0){
      return 0.00;
   }

   if (currency ==true){   
      /* Elimina os zeros à esquerda 
      * a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
      * val2 contém os caracteres (descontando os zeros à esquerda)
      */
      
      for(var i = 0; i < len; i++)
         if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
      
      for(; i < len; i++){
         if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
      }

      if(val2.length==0) return "0.00";
      if (val2.length==1)return "0.0" + val2;
      if (val2.length==2)return "0." + val2;
      
      var parte1 = val2.substring(0,val2.length-2);
      var parte2 = val2.substring(val2.length-2);
      var returnvalue = parte1 + "." + parte2;
      return returnvalue;
      
   }
   else{
         /* currency é false: retornamos os valores COM os zeros à esquerda, 
         * sem considerar os últimos 2 algarismos como casas decimais 
         */
         val3 ="";
         for(var k=0; k < len; k++){
            if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
         }         
   return val3;
   }
}

function reais(obj,event){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatação após o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {   
/*
Previne a ação padrão nos navegadores
*/
   if (event.preventDefault){ //standart browsers
         event.preventDefault();
      }else{ // internet explorer
         event.returnValue = false;
   }
   var valor = obj.value;
   var x = valor.substring(0,valor.length-1);
   obj.value= demaskvalue(x,true).formatCurrency();
   return false;
}
/*
Executa o Formata Reais e faz o format currency novamente após o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {   
   var valor = obj.value;
   var x = valor.substring(0,valor.length-1);
   var y = demaskvalue(x,true).formatCurrency();

   obj.value =""; //necessário para o opera
   obj.value += y;
   
   if (event.preventDefault){ //standart browsers
         event.preventDefault();
      }else{ // internet explorer
         event.returnValue = false;
   }
   return false;

   }// end if      
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
      e.preventDefault()
   }else{ // internet explorer
      e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}
var weekdaystxt=["Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"]

function showLocalTime(container, servermode, offsetMinutes, displayversion){



if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.displayversion=displayversion
var servertimestring='<? echo  date("F d, Y H:i:s", time())?>'
this.localtime=this.serverdate=new Date(servertimestring)
this.localtime.setTime(this.serverdate.getTime()+offsetMinutes*60*1000) //add user offset to server time
this.updateTime()
this.updateContainer()
}

showLocalTime.prototype.updateTime=function(){
var thisobj=this
this.localtime.setSeconds(this.localtime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

showLocalTime.prototype.updateContainer=function(){
var thisobj=this
if (this.displayversion=="long")
this.container.innerHTML=this.localtime.toLocaleString()
else{
var hour=this.localtime.getHours()
var minutes=this.localtime.getMinutes()
var seconds=this.localtime.getSeconds()
var ampm=(hour>=12)? "PM" : "AM"
var today='<? echo  date("d/m")?>'
var dayofweek=weekdaystxt[this.localtime.getDay()]
this.container.innerHTML= today+"&nbsp;&nbsp;&nbsp;&nbsp; "+formatField(hour, 1)+":"+formatField(minutes)
}
setTimeout(function(){thisobj.updateContainer()}, 1000) //update container every second
}

function formatField(num, isHour){
if (typeof isHour!="undefined"){ //if this is the hour field
var hour=(num>12)? num-12 : num
return (hour==0)? 12 : hour
}
return (num<=9)? "0"+num : num//if this is minute or sec field
}


<!-- Favoritos - ini

<!--
function addFavoritos(url,title) {
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){		
		alert("Pressione Ctrl+D para adicionar aos favoritos");
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.style.filter = "alpha(opacity=" + opacity + ")";
} 


function carrega(arquivo,divi,divicancelada){
if(divicancelada){
	var ax = "<br><a class=cancelar href=javascript:abreDIV('"+divicancelada+"');>cancelar</a></div>";
}else{
	var ax = "";
}
var div = document.getElementById(divi);
div.innerHTML = '<div align=center><br /><br /><img src=/loader.gif><br><font class=arial-11 style=color:black>aguarde</font><br /><br /><br /></div>';
var ajax = new Ajax();
ajax.set_receive_handler(
function(c) {
div.innerHTML = c;
}
);
ajax.send(arquivo);
}
//--><!]]>

function enviaForm(frmNome, url, destino,loader){

//alert(document.getElementById(destino));
f = document.getElementById(frmNome);
var query=url;
for (i=0;i<f.elements.length;i++){
query += i==0 ? '?' : '&';
query += f.elements[i].name + '=' + escape(f.elements[i].value);
}
document.getElementById(destino).innerHTML=loader;
loading(query, destino);

}

		
function muda_cor_tbl(id,cor_1){

document.getElementById(id).style.background=cor_1;

}

function muda_classe(id,classe){
document.getElementById(id).className =classe;

}

function troca_img(id,url){//(id_da_img, 1 para img inicial e 0 para img final, url da img, ext da imagem ex.: gif ou jpg, nome da ativação ex.: bot_barra_ativo)
				elem = document.getElementById(id);		
				elem.src=url;

}

function escondeDiv(id) {
document.getElementById(id).style.display = "none";
}
function mostraDiv(id) {
document.getElementById(id).style.display = "block";
}
//-->

function troca_img_fundo(id,url){


				document.getElementById(id).style.backgroundImage = 'url('+url+')';
		


}

function dinheiro(num) {

   x = 0;

   if(num<0) {
      num = Math.abs(num);
      x = 1;
   }

   if(isNaN(num)) num = "0";
      cents = Math.floor((num*100+0.5)%100);

   num = Math.floor((num*100+0.5)/100).toString();

   if(cents < 10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
         num = num.substring(0,num.length-(4*i+3))+'.'
               +num.substring(num.length-(4*i+3));

   ret = num + ',' + cents;

   if (x == 1) ret = ' - ' + ret;return ret;

}

function imprimiDiv(id, pg) {
    var oPrint, oJan;
    oPrint     = window.document.getElementById(id).innerHTML;
    oJan     = window.open(pg);
    oJan.document.write(oPrint);
    oJan.history.go();
    oJan.window.print();
}

function validaConfirmacao(){
if(document.getElementById('confirmaEmail').value==''){document.getElementById('validaConfirmaEmail').innerHTML = '<table border=0 cellpadding=3 cellspacing=1 bgcolor=#FF6600><tr><td bgcolor=#FFFFE6><font class=arial-11>Digite a confirmação de <strong>e-mail</strong></font></td></tr></table>';autoriza3=0} else if(document.getElementById('cadEmail').value!=document.getElementById('confirmaEmail').value){ document.getElementById('validaConfirmaEmail').innerHTML = '<table border=0 cellpadding=3 cellspacing=1 bgcolor=#FF6600><tr><td bgcolor=#FFFFE6><font class=arial-11>Repita seu <strong>e-mail</strong></font></td></tr></table>'  ; autoriza3=0;}else{ document.getElementById('validaConfirmaEmail').innerHTML = '';autoriza3=1;}
}

function validaConfirmacaoSenha(){
if(document.getElementById('confirmaSenha').value==''){document.getElementById('validaConfirmaSenha').innerHTML = '<table border=0 cellpadding=3 cellspacing=1 bgcolor=#FF6600><tr><td bgcolor=#FFFFE6><font class=arial-11>Digite a <strong>confirmação</strong></font></td></tr></table>';autoriza5=0} else if(document.getElementById('senha').value!=document.getElementById('confirmaSenha').value){ document.getElementById('validaConfirmaSenha').innerHTML = '<table border=0 cellpadding=3 cellspacing=1 bgcolor=#FF6600><tr><td bgcolor=#FFFFE6><font class=arial-11>Repita sua <strong>senha</strong></font></td></tr></table>'  ; autoriza5=0;}else{ document.getElementById('validaConfirmaSenha').innerHTML = '';autoriza5=1;}
}

function checaEmail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
                    return true;
                }
    }else{
        return false;
        }
}