/* VALIDA  DADOS DE CMC7 */
	function netTitValidaCMC7(object){
		// CASO UTILIZOU A LEITORA TIRA DIGITOS ESPECIAIS PARA VALIDAR 
		var cmc7temp = "";
		if (object.value.length >= 30) {
			cmc7temp = object.value.replace("<", "");
			cmc7temp = cmc7temp.replace(">", "");
			cmc7temp = cmc7temp.replace("<", "");
		}
		var errorCmC7 = '';
		if (cmc7temp.length != 30) { // Codigo do CmC7 inválido
			alert('CmC7 - Código  Inválido  ');
			object.focus();
			object.value = '';
		}else{
			object.value = cmc7temp;
			
		}
		
		
	}
	

	
	
	// TRUNCAR TEXTO EM JAVASCRIPT 
	
	
 function obStringTruncar(texto,limite){   
    if(texto.length>limite){   
        limite--;   
        last = texto.substr(limite-1,1);   
        while(last!=' ' && limite > 0){   
            limite--;   
            last = texto.substr(limite-1,1);   
        }   
        last = texto.substr(limite-2,1);   
        if(last == ',' || last == ';'  || last == ':'){   
             texto = texto.substr(0,limite-2) + '...';   
        } else if(last == '.' || last == '?' || last == '!'){   
             texto = texto.substr(0,limite-1);   
        } else {   
             texto = texto.substr(0,limite-1) + '...';   
        }   
    }   
    return texto;   
} 

// LAYER FLUTUTANTE 
<!-- Begin
window.onerror = null;
var topMargin = 25;
var slideTime = 1200;
var ns6 = (!document.all && document.getElementById);
var ie4 = (document.all);
var ns4 = (document.layers);
function layerObject(id,left) {
if (ns6) {
this.obj = document.getElementById(id).style;
this.obj.left = left;
return this.obj;
}
else if(ie4) {
this.obj = document.all[id].style;
this.obj.left = left;
return this.obj;
}
else if(ns4) {
this.obj = document.layers[id];
this.obj.left = left;
return this.obj;
   }
}
function layerSetup() {
floatLyr = new layerObject('floatLayer', pageWidth * .0); // POSICAO HORIZNAL
window.setInterval("main()", 10)
}
function floatObject() {
if (ns4 || ns6) {
findHt = window.innerHeight;
} else if(ie4) {
findHt = document.body.clientHeight;
   }
} 
function main() {
if (ns4) {
this.currentY = document.layers["floatLayer"].top;
this.scrollTop = window.pageYOffset;
mainTrigger();
}
else if(ns6) {
this.currentY = parseInt(document.getElementById('floatLayer').style.top);
this.scrollTop = scrollY;
mainTrigger();
} else if(ie4) {
this.currentY = floatLayer.style.pixelTop;
this.scrollTop = document.body.scrollTop;
mainTrigger();
   }
}
function mainTrigger() {
var newTargetY = this.scrollTop + this.topMargin;
if ( this.currentY != newTargetY ) {
if ( newTargetY != this.targetY ) {
this.targetY = newTargetY;
floatStart();
}
animator();
   }
}
function floatStart() {
var now = new Date();
this.A = this.targetY - this.currentY;
this.B = Math.PI / ( 2 * this.slideTime );
this.C = now.getTime();
if (Math.abs(this.A) > this.findHt) {
this.D = this.A > 0 ? this.targetY - this.findHt : this.targetY + this.findHt;
this.A = this.A > 0 ? this.findHt : -this.findHt;
}
else {
this.D = this.currentY;
   }
}
function animator() {
var now = new Date();
var newY = this.A * Math.sin( this.B * ( now.getTime() - this.C ) ) + this.D;
newY = Math.round(newY);
if (( this.A > 0 && newY > this.currentY ) || ( this.A < 0 && newY < this.currentY )) {
if ( ie4 )document.all.floatLayer.style.pixelTop = newY;
if ( ns4 )document.layers["floatLayer"].top = newY;
if ( ns6 )document.getElementById('floatLayer').style.top = newY + "px";
   }
}
function start() {
if(ns6||ns4) {
pageWidth = innerWidth;
pageHeight = innerHeight;
layerSetup();
floatObject();
}
else if(ie4) {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
layerSetup();
floatObject();
   }
}
//  End -->


//se ? netscape
var s = String(navigator.appName).toLowerCase();
var NS4 = (s.indexOf("netscape") >= 0) ? true : false;

window.status = defaultStatus;

function OpenHELPP() {
  window.open('../jsp/netfactormanual/ManualNetF.htm','obModal','width=' + (screen.availWidth - 10) + ',height='+ (screen.availHeight -30) + ',directories=no,location=0,menubar=no,scrollbars=yes,status=no,toolbar=no,resizeable=yes,left=0,top=0,screenX=0,screenY=0');
};

/*
   Parametros:
     sender:   o input
     base  :   Ano base para convers?o quando 2 digito
     e:        Objeto Event(s? no keyPress)
*/


function validaDate(sender,base){
  erro = false;
  var s = String(sender.value);
  s = s.replace("/","").replace("/","");

  dia = s.substr(0,2);
  mes = s.substr(2,2);
  ano = s.substr(4,8);

  if ((Number(ano) >= 0) && (Number(ano) < 1000)){
    var base = Number(base);
    if (isNaN(base))
      base = 50;

    if (Number(ano) > base ) {
      ano = "19" + ano;
    } else {
      ano = "20" + ano;
    }
  }

  var bissexto = (ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0))
  var maxMes = new Array(31, bissexto ? 29: 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

  if (ano.length != 4)
    erro = true;

  if ((dia > maxMes[mes-1] || dia < 1))
    erro = true;

  if (mes >12 || mes < 1)
    erro = true;

  d = new Date(ano,mes,dia);

  if (isNaN(d))
    erro = true;

  if ( sender.value == "" )
    erro = false;

  if(erro){
     if (! NS4){
      sender.focus();
      sender.select();
     }
     alert("Digite a data no formato 'ddmmaa' ou 'ddmmaaaa'.");
     return false;
  }else{
    if (sender.value != "")
      sender.value = s.substring(0,4) + ano;
    return true;
  }

}

var bas_cal,dp_cal,ms_cal;      
function calender(campo ) {
  dp_cal  = new Epoch('epoch_popup','popup',document.getElementById(campo));
};


function onEnterDateField(sender,base){

 // calender(sender.name);
  
  texto = sender.value;
  status = sender.title;
  texto = texto.replace( "/", "" );
  texto = texto.replace( "/", "" );
  if (NS4)
    sender.value = texto;
  else
    sender.value = texto;
  sender.select();
}

function onExitDateField(sender,base){
	bRet = validaDate(sender,base);
	var texto = String(sender.value);
	if (bRet && (texto != "")) {
		sender.value = texto.substring(0,2) + "/" + texto.substring(2,4) + "/" + texto.substring(4,8);
	}
	status = defaultStatus;
	return bRet;
}

function onKeyPressDateField(sender,base,e){
  
 
  var tecla = (e.keyCode);
  var cadeia = String("0123456789");

    var valid = false;
    tecla = String.fromCharCode(NS4?e.which:e.keyCode);
    valid = cadeia.indexOf(tecla) >= 0;

    var condicao = (NS4? (e.keyCode >= 37 && e.keyCode <= 57):false );
    return (valid || ( e.keyCode == 8 || e.keyCode == 9 || condicao));
}

/*
    Fun?ao para Hints
*/

 function MM_findObj(n, d) { //v4.0
	var p,i,x;  
	if (!d) 
  		d=document; 
	if ((p=n.indexOf("?"))>0 && parent.frames.length) {
    	d=parent.frames[n.substring(p+1)].document; 
    	n=n.substring(0,p);
	}
	if (!(x=d[n])&&d.all) 
		x=d.all[n]; 
	for (i=0;!x&&i<d.forms.length;i++) 
		x=d.forms[i][n];
  	for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
  		x=MM_findObj(n,d.layers[i].document);
  	if(!x && document.getElementById) 
  		x=document.getElementById(n); 
	return x;
}

function MMM_showHideLayers(arg1, arg2, arg3, arg4) { //v3.0

	// Pega Valores da posi??o do Mouse
	var IE = document.all?true:false
	if (!IE) 
		document.captureEvents(Event.MOUSEMOVE)
	var tempX = 0
	var tempY = 0



	if (IE) { // grab the x-y pos.s if browser is IE
    	tempY = event.clientY + document.body.scrollTop
	} else {  // grab the x-y pos.s if browser is NS
		tempY = arg4.pageY + 5
	}

	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft
	} else {  // grab the x-y pos.s if browser is NS
		tempX = arg4.pageX + 5
	}

	var i, p, v, obj, args = MMM_showHideLayers.arguments;	

    for (i=0; i<(args.length-2); i+=3) 
    	if ((obj=MM_findObj(args[i]))!=null) { 
    		v=args[i+2];
    		if (obj.style) { 
    			obj=obj.style; 
    			v = (v == 'show') ? 'visible' : (v =='hide') ? 'hidden': v; 
			}
    		obj.visibility = v; 
    		obj.left = tempX;
    		obj.top = tempY;
    	}

  }

/*
 Funcoes de Formatacao de Valor

   Parametros:
     sender:   o input
     decimais: Numero permitido de decimais
     milhar:   Utilizar separador de Milhar
     min:      Valor minimo aceito
     max:      Valor maximo aceito
     e:        Objeto Event(s? no keyPress)
*/


function onEnterValorField(sender,decimais,milhar,min,max){
   var texto = sender.value;
   status = sender.title;
   texto = texto.replace( ".", "" );
   texto = texto.replace( ".", "" );
   texto = texto.replace( ".", "" );
   texto = texto.replace( ".", "" );
   if ( NS4)
     sender.value = texto;
   else
     sender.value = texto;

   sender.select();
   return true;
}

function repeatString(str,substr,count,toLeft){
 var s = String(str);

 if (s.length > count)
   s = s.substring(0,count);
 else
  while (s.length < count)
   s = (toLeft ? s + substr: substr + s);
 return s;
}

function onExitValorField(sender,decimais,milhar,min,max,leaveBlank){
   var texto = String(sender.value);
   if (texto == "")
     if (leaveBlank) return true;
     else
      texto = "0";
   decimais = Number(decimais);

   var sDecim = repeatString("","0",decimais,true);

   var sVal = texto;

   if (texto.indexOf(",") >= 0){
      sVal = texto.substring(0,texto.indexOf(","));
      sDecim   = repeatString(texto.slice(texto.indexOf(",")+1),"0",decimais,true);
   }
   if (sVal == "")
    sVal = "0";


   iVal = new Number(sVal);
   if(min != 0){
     if (iVal < new Number(min)){
       alert("O Campo deve ter Valor M?nimo de "+ min);
       sender.focus();
       return false;
     }
   }
   if(max != 0){
     if (iVal > new Number(max)){
       alert("O Campo deve ter Valor M?ximo de "+ max);
       sender.focus();
       return false;
     }
   }

   if (milhar == "S"){
     var sTemp = "";
     var iLen = new Number(sVal.length);
     for (var i = iLen;i > 0; i-=3)   {
       sTemp = "." +sVal.substring(i-3,i) + sTemp;
     }
     sVal = sTemp.slice(1);
   }

   if (NS4)
    sender.value = sVal + (decimais == 0? "":",") + sDecim;
   else
    sender.value = sVal + (decimais == 0? "":",") + sDecim;

   /*if (String(sender.value).substring(0,1) == "."){
    sender.value =  String(sender.value).slice(1);
   }*/
   status = defaultStatus;

   return true;
}

function onKeyPressValorField(sender,decimais,milhar,min,max,leaveBlank,e){
  var texto = String(sender.value);
  var tecla = (e.keyCode);
  var cadeia = String("0123456789,-");

    var valid = false;
    tecla = String.fromCharCode(NS4?e.which:e.keyCode);
    valid = cadeia.indexOf(tecla) >= 0;
      if (! NS4 && tecla == "."){ //netscape n?o d?
        e.keyCode = 44;
        tecla = ",";
        valid = true;
      }

      if (valid && (tecla == ",")&&(texto.indexOf(",") >= 0 )  ){
        return false;
      }
      if (valid && (tecla == ",")&&(decimais == 0  )  ){
        return false;
      }
      var condicao = (NS4? (e.keyCode >= 37 && e.keyCode <= 57):false );
      return (valid || ( e.keyCode == 44 ||e.keyCode == 8 || e.keyCode == 9 || condicao))

}

//
// Funcao para o salto automatico de campo
//
function saltaCampo (e,sender,target,maxlen){
        tam = String(sender.value).length;
        if (isNaN(maxlen))
        tammax = sender.maxLength
        else
            tammax = maxlen;

        var tecla = (NS4 ? e.which: e.keyCode);
          if ( (tam == tammax || tecla == 13)&&  (tecla != 37) &&(tecla != 39) &&(tecla != 9) && (tecla != 16)){
                if (String(document.all(target).name) != "undefined"){
                 target.focus() ;
         target.select() ;
                }
                else{
                 for (var n=0;n< sender.form.elements.length-1;n++){
                   if (sender.form.elements[n] == sender){
                 sender.form.elements[n+1].focus();
                         if ((sender.form.elements[n+1].type != "button" && sender.form.elements[n+1].type != "submit")&& sender.form.elements[n+1].name != "")
                 sender.form.elements[n+1].select();
                   }
                 }

                }

      }

}


//
// Funcoes para CNPJ e CPF
//


function validaCNPJ(pcgc)
{
   // verifica o tamanho
  if (pcgc.length != 14)
    sim=false;
  else
    sim=true;

  if (sim ){  // verfica se e numero
   for (i=0;((i<=(pcgc.length-1))&& sim); i++){
      iVl = pcgc.charAt(i)
    if ((iVl!="9")&&(iVl!="0")&&(iVl!="1")&&(iVl!="2")&&(iVl!="3")&&(iVl!="4")
        && (iVl!="5")&&(iVl!="6")&&(iVl!="7")&&(iVl!="8"))
          {sim=false}
  }
  if (sim)  // se for numero continua
  {
   m2 = 2
   soma1 = 0
   soma2 = 0
   for (i=11;i>=0;i--)
   {
    iVl = eval(pcgc.charAt(i));
    m1 = m2;
    if (m2<9) { m2 = m2+1}
    else {m2 = 2}
    soma1 = soma1 + (iVl * m1)
    soma2 = soma2 + (iVl * m2)
   }  // fim do for de soma

  soma1 = soma1 % 11
  if (soma1 < 2) {  d1 = 0}
  else { d1 = 11- soma1}

  soma2 = (soma2 + (2 * d1)) % 11
  if (soma2 < 2) { d2 = 0}
  else { d2 = 11- soma2}

   if ((d1==pcgc.charAt(12)) && (d2==pcgc.charAt(13)))
     return true;
   else return false;
  }
 }

}


function validaCPF(pcpf)
{

if (pcpf.length != 11) {sim=false}
else {sim=true}

 if (sim )  // valida o primeiro digito
 {
 for (i=0;((i<=(pcpf.length-1))&& sim); i++)
 {
  iVl = pcpf.charAt(i)
  if

((iVl!="9")&&(iVl!="0")&&(iVl!="1")&&(iVl!="2")&&(iVl!="3")&&(iVl!="4")

&&    (iVl!="5")&&(iVl!="6")&&(iVl!="7")&&(iVl!="8")) {sim=false}
  }

  if (sim)
 {
   soma = 0
   for (i=0;i<=8;i++)
   {
    iVl = eval(pcpf.charAt(i))
    soma = soma + (iVl*(i+1))
   }

   resto = soma % 11
   if (resto>9) dig = resto -10
   else  dig = resto
   if (dig != eval(pcpf.charAt(9))) { sim=false }
   else   // valida o segundo digito
   {

    soma = 0
    for (i=0;i<=7;i++)
    {
     iVl = eval(pcpf.charAt(i+1))
     soma = soma + (iVl*(i+1))
    }

    soma = soma + (dig * 9)
    resto = soma % 11
    if (resto>9) dig = resto -10
    else  dig = resto
   if (dig != eval(pcpf.charAt(10))) { sim = false }
   else sim = true
  }
  }
 }
 return sim;

}

function limpaCNPJCPF(nro) {
   texto = String(nro);
   texto = texto.replace("/", "");
   texto = texto.replace(".", "");
   texto = texto.replace(".", "");
   texto = texto.replace(".", "");
   texto = texto.replace("-", "");
   return texto;
}

function validaCNPJCPF(nro) {
  nro = limpaCNPJCPF(nro);

  var cpft = String(nro);

  while (cpft.length < 11)
    cpft = "0" + cpft;

  if(cpft.length == 11){
	if (validaCPF(cpft)) return cpft;
  
  }else{
	var cgct = String(nro);
	while (cgct.length < 14)
		cgct = "0" + cgct;
	
	if (validaCNPJ(cgct)) return cgct;
  }

  return "inv";

}

function onEnterCGCField(sender,tipo){
   texto = limpaCNPJCPF(sender.value);
   status = sender.title;
   if (NS4)
     sender.value = texto;
   else
     sender.value = texto;
   sender.select();
}

function onEnterCGCSEMVALIDACAOField(sender,tipo){
   texto = limpaCNPJCPF(sender.value);
   status = sender.title;
   if (NS4)
     sender.value = texto;
   else
     sender.value = texto;
   sender.select();
}

function onExitCGCField(sender,tipo){
   sRet = String(validaCNPJCPF(sender.value));
   var texto = String(sender.value);
   if (texto == "") return true;
   if (tipo == "T"){
      if (sRet == "inv" ){
        alert("Digite um CNPJ/CPF V?lido");
        sender.focus();
        sender.select();
        return false;
      }
      if (sRet.length == 11){
        if (NS4)
          sender.value = sRet.substr(0,3) + "." + sRet.substr(3,3) + "." +sRet.substr(6,3) + "-" +sRet.substr(9,2)
        else
          sender.value = sRet.substr(0,3) + "." + sRet.substr(3,3) + "." +sRet.substr(6,3) + "-" +sRet.substr(9,2)
      }
      if (sRet.length == 14){
        if (NS4)
          sender.value = sRet.substr(0,2) + "." + sRet.substr(2,3) + "." +sRet.substr(5,3) + "/" +sRet.substr(8,4) + "-" +sRet.substr(12,2);
        else
          sender.value = sRet.substr(0,2) + "." + sRet.substr(2,3) + "." +sRet.substr(5,3) + "/" +sRet.substr(8,4) + "-" +sRet.substr(12,2);
      }

   }
   if (tipo == "J"){
      if (sRet.length != 14){
        alert("Digite um CNPJ V?lido")  ;
        sender.focus();
        sender.select();
        return false;
      }else
       if (NS4)
        sender.value = sRet.substr(0,2) + "." + sRet.substr(2,3) + "." +sRet.substr(5,3) + "/" +sRet.substr(8,4) + "-" +sRet.substr(12,2);
       else
        sender.value = sRet.substr(0,2) + "." + sRet.substr(2,3) + "." +sRet.substr(5,3) + "/" +sRet.substr(8,4) + "-" +sRet.substr(12,2);
   }

   if (tipo == "F"){
      if (sRet.length != 11){
        alert("Digite um CPF V?lido")  ;
        sender.focus();
        sender.select();
        return false;
      }else
       if (NS4)
        sender.value = sRet.substr(0,3) + "." + sRet.substr(3,3) + "." +sRet.substr(6,3) + "-" +sRet.substr(9,2)
       else
        sender.value = sRet.substr(0,3) + "." + sRet.substr(3,3) + "." +sRet.substr(6,3) + "-" +sRet.substr(9,2)
   }
   status = defaultStatus;
   return true;
}

function onExitCGCSEMVALIDACAOField(sender,tipo){   
   var texto = String(sender.value);
   if (texto == "") return true;
   if (tipo == "T"){   
	  if(texto.length < 12){
		  while (texto.length < 11)
			texto = "0" + texto;	  
	  }else if(texto.length < 15){
		  while (texto.length < 14)		  
			texto = "0" + texto;	
	  }
			  
      if (texto.length == 11){
        if (NS4)
          sender.value = texto.substr(0,3) + "." + texto.substr(3,3) + "." +texto.substr(6,3) + "-" +texto.substr(9,2)
        else
          sender.value = texto.substr(0,3) + "." + texto.substr(3,3) + "." +texto.substr(6,3) + "-" +texto.substr(9,2)
      }else if (texto.length == 14){
        if (NS4)
          sender.value = texto.substr(0,2) + "." + texto.substr(2,3) + "." +texto.substr(5,3) + "/" +texto.substr(8,4) + "-" +texto.substr(12,2);
        else
          sender.value = texto.substr(0,2) + "." + texto.substr(2,3) + "." +texto.substr(5,3) + "/" +texto.substr(8,4) + "-" +texto.substr(12,2);
      }else{
			sender.value = texto;
      }
   }
   status = defaultStatus;
   return true;
}

function onKeyPressCGCField(sender,tipo,e){
   var tecla = (e.keyCode);
   var cadeia = String("0123456789");

    var valid = false;
    tecla = String.fromCharCode(NS4?e.which:e.keyCode);
    valid = cadeia.indexOf(tecla) >= 0;

    var condicao = (NS4? (e.keyCode >= 37 && e.keyCode <= 57):false );
    return (valid || ( e.keyCode == 8 || e.keyCode == 9 || condicao));

}

function onKeyPressCGCSEMVALIDACAOField(sender,tipo,e){
   var tecla = (e.keyCode);
   var cadeia = String("0123456789");

    var valid = false;
    tecla = String.fromCharCode(NS4?e.which:e.keyCode);
    valid = cadeia.indexOf(tecla) >= 0;

    var condicao = (NS4? (e.keyCode >= 37 && e.keyCode <= 57):false );
    return (valid || ( e.keyCode == 8 || e.keyCode == 9 || condicao));
}


function validaForm(form){
 window.status = "Validando Campos digitados..."
 for (var i= 0; i < form.elements.length;i++){
   var item = form.elements(i);

        if ((String(item.branco) == "N") && (String(item.value) == "")){
          alert("Este Campo dever ser preenchido: "+ String(item.title) );
          item.focus();
          item.select();
          return false;
        }
 }
  return true;
}

//funcoes para CEP
function onEnterCepField(sender){
	status = sender.title;
	var s = String(sender.value);
	sender.value =  s.replace("-","");
	sender.select();
}

function onExitCepField(sender){
	var s = String(sender.value);
	if (s=="") return true;
	valor = s.substring(0,5) + "-" + s.substring(5,8);
	sender.maxLength = 9;
	sender.value = valor;
	status = defaultStatus;
	return true;
}

function onKeyPressCepField(sender,e){
  var tecla = (e.keyCode);
  var cadeia = String("0123456789");

    var valid = false;
    tecla = String.fromCharCode(NS4?e.which:e.keyCode);
    valid = cadeia.indexOf(tecla) >= 0;

    var condicao = (NS4? (e.keyCode >= 37 && e.keyCode <= 57):false );
    return (valid || ( e.keyCode == 8 || e.keyCode == 9 || condicao));
}

//funcoes para String apenas declaradas
function onEnterStringField(sender){
   sender.select();
   status = sender.title;
}
function onExitStringField(sender){
   status = defaultStatus;
   return true;
}
function onKeyPressStringField(sender,e){
  tecla = (NS4 ? e.which: e.keyCode);

 return tecla != 13;
}


//funcoes para CheckBox apenas declaradas
function onEnterCheckBoxField(sender){
 status = sender.title;
}
function onExitCheckBoxField(sender){
  return true;
}
function onKeyPressCheckBoxField(sender,e){
  tecla = (NS4 ? e.which: e.keyCode);
  return (tecla == 32)
}

//funcao para retorno do obComboBox
function onKeyPressComboBoxField(sender,e){
  tecla = (NS4 ? e.which: e.keyCode);
  return (tecla != 32)
}

//funcoes para RadioButton apenas declaradas
function onEnterRadioButtonField(sender){
}
function onExitRadioButtonField(sender){
}
function onKeyPressRadioButtonField(sender){}

var fIE4orLater = (document.all);
function OpenCHM(sURL)
{
if (fIE4orLater) window.showHelp(sURL);
else window.open(sURL);


return;
};

/*
TECLAS DE ATALHO
*/
var fIE4orLater = (document.all);
function CHM(sURL) {
  if (fIE4orLater)
    window.showHelp(sURL);
  else
    window.open(sURL);
  return;
};

var ns4=document.layers?1:0
var ie4=document.all?1:0
var ns6=document.getElementById&&!document.all?1:0

if (ns4)
  document.captureEvents(Event.KEYPRESS)








/***********************************************
* Show Hint script
***********************************************/
		
var horizontal_offset="9px" //horizontal offset of hint box from anchor link

/////No further editting needed-  (www.dynamicdrive.com)

var vertical_offset="0" //horizontal offset of hint box from anchor link. No need to change.
var ie=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
if (whichedge=="rightedge"){
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
}
else{
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
}
return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth){
if ((ie||ns6) && document.getElementById("hintbox")){
dropmenuobj=document.getElementById("hintbox")
dropmenuobj.innerHTML=menucontents
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (tipwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=tipwidth
}
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
dropmenuobj.style.visibility="visible"
obj.onmouseout=hidetip
}
}

function hidetip(e){
dropmenuobj.style.visibility="hidden"
dropmenuobj.style.left="-500px"
}

function createhintbox(){
var divblock=document.createElement("div")
divblock.setAttribute("id", "hintbox")
document.body.appendChild(divblock)
}

if (window.addEventListener)
window.addEventListener("load", createhintbox, false)
else if (window.attachEvent)
window.attachEvent("onload", createhintbox)
else if (document.getElementById)
window.onload=createhintbox



/*
  CALENDARIO
*/

/*****************************************************************************
Copyright (C) 2006  Nick Baicoianu

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*****************************************************************************/
//constructor for the main Epoch class (ENGLISH VERSION)
function Epoch(name,mode,targetelement,multiselect)
{
  this.state = 0;
  this.name = name;
  this.curDate = new Date();
  this.mode = mode;
  this.selectMultiple = (multiselect == true); //'false' is not true or not set at all
  
  //the various calendar variables
  //this.selectedDate = this.curDate;
  this.selectedDates = new Array();
  this.calendar;
  this.calHeading;
  this.calCells;
  this.rows;
  this.cols;
  this.cells = new Array();
  
  //The controls
  this.monthSelect;
  this.yearSelect;
  
  //standard initializations
  this.mousein = false;
  this.calConfig();
  this.setDays();
  this.displayYear = this.displayYearInitial;
  this.displayMonth = this.displayMonthInitial;
  
  this.createCalendar(); //create the calendar DOM element and its children, and their related objects
  
  if(this.mode == 'popup' && targetelement && targetelement.type == 'text') //if the target element has been set to be an input text box
  {
    this.tgt = targetelement;
    this.calendar.style.position = 'absolute';
    this.topOffset = this.tgt.offsetHeight; // the vertical distance (in pixels) to display the calendar from the Top of its input element
    this.leftOffset = 0;           // the horizontal distance (in pixels) to display the calendar from the Left of its input element
    this.calendar.style.top = this.getTop(targetelement) + this.topOffset + 'px';
    this.calendar.style.left = this.getLeft(targetelement) + this.leftOffset + 'px';
    document.body.appendChild(this.calendar);
    this.tgt.calendar = this;
    this.tgt.onfocus = function () {this.calendar.show();}; //the calendar will popup when the input element is focused
    this.tgt.onblur = function () {if(!this.calendar.mousein){this.calendar.hide();}}; //the calendar will popup when the input element is focused
  }
  else
  {
    this.container = targetelement;
    this.container.appendChild(this.calendar);
  }
  
  this.state = 2; //0: initializing, 1: redrawing, 2: finished!
  this.visible ? this.show() : this.hide();
}
//-----------------------------------------------------------------------------
Epoch.prototype.calConfig = function () //PRIVATE: initialize calendar variables
{
  //this.mode = 'flat'; //can be 'flat' or 'popup'
  this.displayYearInitial = this.curDate.getFullYear(); //the initial year to display on load
  this.displayMonthInitial = this.curDate.getMonth(); //the initial month to display on load (0-11)
  this.rangeYearLower = 2005;
  this.rangeYearUpper = 2037;
  this.minDate = new Date(2005,0,1);
  this.maxDate = new Date(2037,0,1);
  this.startDay = 0; // the day the week will 'start' on: 0(Sun) to 6(Sat)
  this.showWeeks = true; //whether the week numbers will be shown
  this.selCurMonthOnly = false; //allow user to only select dates in the currently displayed month
  this.clearSelectedOnChange = true; //whether to clear all selected dates when changing months
  
  //flat mode-only settings:
  //this.selectMultiple = true; //whether the user can select multiple dates (flat mode only)

  switch(this.mode) //set the variables based on the calendar mode
  {
    case 'popup': //popup options
      this.visible = false;
      break;
    case 'flat':
      this.visible = true;
      
      break;
  }
  this.setLang();
};
//-----------------------------------------------------------------------------
Epoch.prototype.setLang = function()  //all language settings for Epoch are made here.  Check Date.dateFormat() for the Date object's language settings
{
  this.daylist = new Array('Do','Se','Te','Qu','Qui','Se','Sa','Do','Se','Te','Qu','Qui','Se','Sa'); /*<lang:en>*/
  this.months_sh = new Array('Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez');
  this.monthup_title = 'Ir para prox m?s';
  this.monthdn_title = 'Ir para o m?s anterior';
  this.clearbtn_caption = 'Reset';
  this.clearbtn_title = 'Resetar todas as datas do calendario';
  this.maxrange_caption = 'Maximo';
};
//-----------------------------------------------------------------------------
Epoch.prototype.getTop = function (element) //PRIVATE: returns the absolute Top value of element, in pixels
{
    var oNode = element;
    var iTop = 0;
    
    while(oNode.tagName != 'BODY') {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};
//-----------------------------------------------------------------------------
Epoch.prototype.getLeft = function (element) //PRIVATE: returns the absolute Left value of element, in pixels
{
    var oNode = element;
    var iLeft = 0;
    
    while(oNode.tagName != 'BODY') {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    
    return iLeft;
};
//-----------------------------------------------------------------------------
Epoch.prototype.show = function () //PUBLIC: displays the calendar
{
  this.calendar.style.display = 'block';
  this.visible = true;
};
//-----------------------------------------------------------------------------
Epoch.prototype.hide = function () //PUBLIC: Hides the calendar
{
  this.calendar.style.display = 'none';
  this.visible = false;
};
//-----------------------------------------------------------------------------
Epoch.prototype.toggle = function () //PUBLIC: Toggles (shows/hides) the calendar depending on its current state
{
  if(this.visible) {
    this.hide();
  }
  else {
    this.show();
  }
};
//-----------------------------------------------------------------------------
Epoch.prototype.setDays = function ()  //PRIVATE: initializes the standard Gregorian Calendar parameters
{
  this.daynames = new Array();
  var j=0;
  for(var i=this.startDay; i< this.startDay + 7;i++) {
    this.daynames[j++] = this.daylist[i];
  }
    
  this.monthDayCount = new Array(31,((this.curDate.getFullYear() - 2000) % 4 ? 28 : 29),31,30,31,30,31,31,30,31,30,31);
};
//-----------------------------------------------------------------------------
Epoch.prototype.setClass = function (element,className) //PRIVATE: sets the CSS class of the element, W3C & IE
{
  element.setAttribute('class',className);
  element.setAttribute('className',className); //<iehack>
};
//-----------------------------------------------------------------------------
Epoch.prototype.createCalendar = function ()  //PRIVATE: creates the full DOM implementation of the calendar
{
  var tbody, tr, td;
  this.calendar = document.createElement('table');
  this.calendar.setAttribute('id',this.name+'_calendar');
  this.setClass(this.calendar,'calendar');
  //to prevent IE from selecting text when clicking on the calendar
  this.calendar.onselectstart = function() {return false;};
  this.calendar.ondrag = function() {return false;};
  tbody = document.createElement('tbody');
  
  //create the Main Calendar Heading
  tr = document.createElement('tr');
  td = document.createElement('td');
  td.appendChild(this.createMainHeading());
  tr.appendChild(td);
  tbody.appendChild(tr);
  
  //create the calendar Day Heading
  tr = document.createElement('tr');
  td = document.createElement('td');
  td.appendChild(this.createDayHeading());
  tr.appendChild(td);
  tbody.appendChild(tr);

  //create the calendar Day Cells
  tr = document.createElement('tr');
  td = document.createElement('td');
  td.setAttribute('id',this.name+'_cell_td');
  this.calCellContainer = td;  //used as a handle for manipulating the calendar cells as a whole
  td.appendChild(this.createCalCells());
  tr.appendChild(td);
  tbody.appendChild(tr);
  
  //create the calendar footer
  tr = document.createElement('tr');
  td = document.createElement('td');
  td.appendChild(this.createFooter());
  tr.appendChild(td);
  tbody.appendChild(tr);
  
  //add the tbody element to the main calendar table
  this.calendar.appendChild(tbody);

  //and add the onmouseover events to the calendar table
  this.calendar.owner = this;
  this.calendar.onmouseover = function() {this.owner.mousein = true;};
  this.calendar.onmouseout = function() {this.owner.mousein = false;};
};
//-----------------------------------------------------------------------------
Epoch.prototype.createMainHeading = function () //PRIVATE: Creates the primary calendar heading, with months & years
{
  //create the containing <div> element
  var container = document.createElement('div');
  container.setAttribute('id',this.name+'_mainheading');
  this.setClass(container,'mainheading');
  //create the child elements and other variables
  this.monthSelect = document.createElement('select');
  this.yearSelect = document.createElement('select');
  var monthDn = document.createElement('input'), monthUp = document.createElement('input');
  var opt, i;
  //fill the month select box
  for(i=0;i<12;i++)
  {
    opt = document.createElement('option');
    opt.setAttribute('value',i);
    if(this.state == 0 && this.displayMonth == i) {
      opt.setAttribute('selected','selected');
    }
    opt.appendChild(document.createTextNode(this.months_sh[i]));
    this.monthSelect.appendChild(opt);
  }
  //and fill the year select box
  for(i=this.rangeYearLower;i<=this.rangeYearUpper;i++)
  {
    opt = document.createElement('option');
    opt.setAttribute('value',i);
    if(this.state == 0 && this.displayYear == i) {
      opt.setAttribute('selected','selected');
    }
    opt.appendChild(document.createTextNode(i));
    this.yearSelect.appendChild(opt);    
  }
  //add the appropriate children for the month buttons
  monthUp.setAttribute('type','button');
  monthUp.setAttribute('value','>');
  monthUp.setAttribute('title',this.monthup_title);
  monthDn.setAttribute('type','button');
  monthDn.setAttribute('value','<');
  monthDn.setAttribute('title',this.monthdn_title);
  this.monthSelect.owner = this.yearSelect.owner = monthUp.owner = monthDn.owner = this;  //hack to allow us to access this calendar in the events (<fix>??)
  
  //assign the event handlers for the controls
  monthUp.onmouseup = function () {this.owner.nextMonth();};
  monthDn.onmouseup = function () {this.owner.prevMonth();};
  this.monthSelect.onchange = function() {
    this.owner.displayMonth = this.value;
    this.owner.displayYear = this.owner.yearSelect.value; 
    this.owner.goToMonth(this.owner.displayYear,this.owner.displayMonth);
  };
  this.yearSelect.onchange = function() {
    this.owner.displayMonth = this.owner.monthSelect.value;
    this.owner.displayYear = this.value; 
    this.owner.goToMonth(this.owner.displayYear,this.owner.displayMonth);
  };
  
  //and finally add the elements to the containing div
  container.appendChild(monthDn);
  container.appendChild(this.monthSelect);
  container.appendChild(this.yearSelect);
  container.appendChild(monthUp);
  return container;
};
//-----------------------------------------------------------------------------
Epoch.prototype.createFooter = function () //PRIVATE: creates the footer of the calendar - goes under the calendar cells
{
  var container = document.createElement('div');
  var clearSelected = document.createElement('input');
  clearSelected.setAttribute('type','button');
  clearSelected.setAttribute('value',this.clearbtn_caption);
  clearSelected.setAttribute('title',this.clearbtn_title);
  clearSelected.owner = this;
  clearSelected.onclick = function() { this.owner.resetSelections(false);};
  container.appendChild(clearSelected);
  return container;
};
//-----------------------------------------------------------------------------
Epoch.prototype.resetSelections = function (returnToDefaultMonth)  //PRIVATE: reset the calendar's selection variables to defaults
{
  this.selectedDates = new Array();
  this.rows = new Array(false,false,false,false,false,false,false);
  this.cols = new Array(false,false,false,false,false,false,false);
  if(this.tgt)  //if there is a target element, clear it too
  {
    this.tgt.value = '';
    if(this.mode == 'popup') {//hide the calendar if in popup mode
      this.hide();
    }
  }
    
  if(returnToDefaultMonth == true) {
    this.goToMonth(this.displayYearInitial,this.displayMonthInitial);
  }
  else {
    this.reDraw();
  }
};
//-----------------------------------------------------------------------------
Epoch.prototype.createDayHeading = function ()  //PRIVATE: creates the heading containing the day names
{
  //create the table element
  this.calHeading = document.createElement('table');
  this.calHeading.setAttribute('id',this.name+'_caldayheading');
  this.setClass(this.calHeading,'caldayheading');
  var tbody,tr,td;
  tbody = document.createElement('tbody');
  tr = document.createElement('tr');
  this.cols = new Array(false,false,false,false,false,false,false);
  
  //if we're showing the week headings, create an empty <td> for filler
  if(this.showWeeks)
  {
    td = document.createElement('td');
    td.setAttribute('class','wkhead');
    td.setAttribute('className','wkhead'); //<iehack>
    tr.appendChild(td);
  }
  //populate the day titles
  for(var dow=0;dow<7;dow++)
  {
    td = document.createElement('td');
    td.appendChild(document.createTextNode(this.daynames[dow]));
    if(this.selectMultiple) { //if selectMultiple is true, assign the cell a CalHeading Object to handle all events
      td.headObj = new CalHeading(this,td,(dow + this.startDay < 7 ? dow + this.startDay : dow + this.startDay - 7));
    }
    tr.appendChild(td);
  }
  tbody.appendChild(tr);
  this.calHeading.appendChild(tbody);
  return this.calHeading;  
};
//-----------------------------------------------------------------------------
Epoch.prototype.createCalCells = function ()  //PRIVATE: creates the table containing the calendar day cells
{
  this.rows = new Array(false,false,false,false,false,false);
  this.cells = new Array();
  var row = -1, totalCells = (this.showWeeks ? 48 : 42);
  var beginDate = new Date(this.displayYear,this.displayMonth,1);
  var endDate = new Date(this.displayYear,this.displayMonth,this.monthDayCount[this.displayMonth]);
  var sdt = new Date(beginDate);
  sdt.setDate(sdt.getDate() + (this.startDay - beginDate.getDay()) - (this.startDay - beginDate.getDay() > 0 ? 7 : 0) );
  //create the table element
  this.calCells = document.createElement('table');
  this.calCells.setAttribute('id',this.name+'_calcells');
  this.setClass(this.calCells,'calcells');
  var tbody,tr,td;
  tbody = document.createElement('tbody');
  for(var i=0;i<totalCells;i++)
  {
    if(this.showWeeks) //if we are showing the week headings
    {
      if(i % 8 == 0)
      {
        row++;
        tr = document.createElement('tr');
        td = document.createElement('td');
        if(this.selectMultiple) { //if selectMultiple is enabled, create the associated weekObj objects
          td.weekObj = new WeekHeading(this,td,sdt.getWeek(),row)
        }
        else //otherwise just set the class of the td for consistent look
        {
          td.setAttribute('class','wkhead');
          td.setAttribute('className','wkhead'); //<iehack>
        }
        td.appendChild(document.createTextNode(sdt.getWeek()));      
        tr.appendChild(td);
        i++;
      }
    }
    else if(i % 7 == 0) //otherwise, new row every 7 cells
    {
      row++;
      tr = document.createElement('tr');
    }
    //create the day cells
    td = document.createElement('td');
    td.appendChild(document.createTextNode(sdt.getDate()));// +' ' +sdt.getUeDay()));
    var cell = new CalCell(this,td,sdt,row);
    this.cells.push(cell);
    td.cellObj = cell;
    sdt.setDate(sdt.getDate() + 1); //increment the date
    tr.appendChild(td);
    tbody.appendChild(tr);
  }
  this.calCells.appendChild(tbody);
  this.reDraw();
  return this.calCells;
};
//-----------------------------------------------------------------------------
Epoch.prototype.reDraw = function () //PRIVATE: reapplies all the CSS classes for the calendar cells, usually called after chaning their state
{
  this.state = 1;
  var i,j;
  for(i=0;i<this.cells.length;i++) {
    this.cells[i].selected = false;
  }
  for(i=0;i<this.cells.length;i++)
  {
    for(j=0;j<this.selectedDates.length;j++) { //if the cell's date is in the selectedDates array, set its selected property to true
      if(this.cells[i].date.getUeDay() == this.selectedDates[j].getUeDay() ) {
        this.cells[i].selected = true;
      }
    }

    this.cells[i].setClass();
  }
  //alert(this.selectedDates);
  this.state = 2;
};
//-----------------------------------------------------------------------------
Epoch.prototype.deleteCells = function () //PRIVATE: removes the calendar cells from the DOM (does not delete the cell objects associated with them
{
  this.calCellContainer.removeChild(this.calCellContainer.firstChild); //get a handle on the cell table (optional - for less indirection)
  this.cells = new Array(); //reset the cells array
};
//-----------------------------------------------------------------------------
Epoch.prototype.goToMonth = function (year,month) //PUBLIC: sets the calendar to display the requested month/year
{
  this.monthSelect.value = this.displayMonth = month;
  this.yearSelect.value = this.displayYear = year;
  this.deleteCells();
  this.calCellContainer.appendChild(this.createCalCells());
};
//-----------------------------------------------------------------------------
Epoch.prototype.nextMonth = function () //PUBLIC: go to the next month.  if the month is december, go to january of the next year
{
  
  //increment the month/year values, provided they're within the min/max ranges
  if(this.monthSelect.value < 11) {
    this.monthSelect.value++;
  }
  else
  {
    if(this.yearSelect.value < this.rangeYearUpper)
    {
      this.monthSelect.value = 0;
      this.yearSelect.value++;
    }
    else {
      alert(this.maxrange_caption);
    }
  }
  //assign the currently displaying month/year values
  this.displayMonth = this.monthSelect.value;
  this.displayYear = this.yearSelect.value;
  
  //and refresh the calendar for the new month/year
  this.deleteCells();
  this.calCellContainer.appendChild(this.createCalCells());
};
//-----------------------------------------------------------------------------
Epoch.prototype.prevMonth = function () //PUBLIC: go to the previous month.  if the month is january, go to december of the previous year
{
  //increment the month/year values, provided they're within the min/max ranges
  if(this.monthSelect.value > 0)
    this.monthSelect.value--;
  else
  {
    if(this.yearSelect.value > this.rangeYearLower)
    {
      this.monthSelect.value = 11;
      this.yearSelect.value--;
    }
    else {
      alert(this.maxrange_caption);
    }
  }
  
  //assign the currently displaying month/year values
  this.displayMonth = this.monthSelect.value;
  this.displayYear = this.yearSelect.value;
  
  //and refresh the calendar for the new month/year
  this.deleteCells();
  this.calCellContainer.appendChild(this.createCalCells());
};
//-----------------------------------------------------------------------------
Epoch.prototype.addZero = function (vNumber) //PRIVATE: pads a 2 digit number with a leading zero
{
  return ((vNumber < 10) ? '0' : '') + vNumber;
};
//-----------------------------------------------------------------------------
Epoch.prototype.addDates = function (dates,redraw)  //PUBLIC: adds the array "dates" to the calendars selectedDates array (no duplicate dates) and redraws the calendar
{
  var j,in_sd;
  for(var i=0;i<dates.length;i++)
  {  
    in_sd = false;
    for(j=0;j<this.selectedDates.length;j++)
    {
      if(dates[i].getUeDay() == this.selectedDates[j].getUeDay())
      {
        in_sd = true;
        break;
      }
    }
    if(!in_sd) { //if the date isn't already in the array, add it!
      this.selectedDates.push(dates[i]);
    }
  }
  if(redraw != false) {//redraw  the calendar if "redraw" is false or undefined
    this.reDraw();
  }
};
//-----------------------------------------------------------------------------
Epoch.prototype.removeDates = function (dates,redraw)  //PUBLIC: adds the dates to the calendars selectedDates array and redraws the calendar
{
  var j;
  for(var i=0;i<dates.length;i++)
  {
    for(j=0;j<this.selectedDates.length;j++)
    {
      if(dates[i].getUeDay() == this.selectedDates[j].getUeDay()) { //search for the dates in the selectedDates array, removing them if the dates match
        this.selectedDates.splice(j,1);
      }
    }
  }
  if(redraw != false) { //redraw  the calendar if "redraw" is false or undefined
    this.reDraw();
  }
};
//-----------------------------------------------------------------------------
Epoch.prototype.outputDate = function (vDate, vFormat) //PUBLIC: outputs a date in the appropriate format (DEPRECATED)
{
  var vDay      = this.addZero(vDate.getDate()); 
  var vMonth      = this.addZero(vDate.getMonth() + 1); 
  var vYearLong    = this.addZero(vDate.getFullYear()); 
  var vYearShort    = this.addZero(vDate.getFullYear().toString().substring(3,4)); 
  var vYear      = (vFormat.indexOf('yyyy') > -1 ? vYearLong : vYearShort);
  var vHour      = this.addZero(vDate.getHours()); 
  var vMinute      = this.addZero(vDate.getMinutes()); 
  var vSecond      = this.addZero(vDate.getSeconds()); 
  return vFormat.replace(/dd/g, vDay).replace(/mm/g, vMonth).replace(/y{1,4}/g, vYear).replace(/hh/g, vHour).replace(/nn/g, vMinute).replace(/ss/g, vSecond);
};
//-----------------------------------------------------------------------------
Epoch.prototype.updatePos = function (target) //PUBLIC: moves the calendar's position to target's location (popup mode only)
{
  this.calendar.style.top = this.getTop(target) + this.topOffset + 'px'
  this.calendar.style.left = this.getLeft(target) + this.leftOffset + 'px'
}
//-----------------------------------------------------------------------------

/*****************************************************************************/
function CalHeading(owner,tableCell,dow)
{
  this.owner = owner;
  this.tableCell = tableCell;
  this.dayOfWeek = dow;
  
  //the event handlers
  this.tableCell.onclick = this.onclick;
}
//-----------------------------------------------------------------------------
CalHeading.prototype.onclick = function ()
{
  //reduce indirection:
  var owner = this.headObj.owner;
  var sdates = owner.selectedDates;
  var cells = owner.cells;
  
  owner.cols[this.headObj.dayOfWeek] = !owner.cols[this.headObj.dayOfWeek];
  for(var i=0;i<cells.length;i++) //cycle through all the cells in the calendar, selecting all cells with the same dayOfWeek as this heading
  {
    if(cells[i].dayOfWeek == this.headObj.dayOfWeek && (!owner.selCurMonthOnly || cells[i].date.getMonth() == owner.displayMonth && cells[i].date.getFullYear() == owner.displayYear)) //if the cell's DoW matches, with other conditions
    {
      if(owner.cols[this.headObj.dayOfWeek])     //if selecting, add the cell's date to the selectedDates array
      {
        if(owner.selectedDates.arrayIndex(cells[i].date) == -1) { //if the date isn't already in the array
          sdates.push(cells[i].date);
        }
      }
      else                    //otherwise, remove it
      {
        for(var j=0;j<sdates.length;j++) 
        {
          if(cells[i].dayOfWeek == sdates[j].getDay())
          {
            sdates.splice(j,1);  //remove dates that are within the displaying month/year that have the same day of week as the day cell
            break;
          }
        }
      }
      cells[i].selected = owner.cols[this.headObj.dayOfWeek];
    }
  }
  owner.reDraw();
};
/*****************************************************************************/
function WeekHeading(owner,tableCell,week,row)
{
  this.owner = owner;
  this.tableCell = tableCell;
  this.week = week;
  this.tableRow = row;
  this.tableCell.setAttribute('class','wkhead');
  this.tableCell.setAttribute('className','wkhead'); //<iehack>
  //the event handlers
  this.tableCell.onclick = this.onclick;
}
//-----------------------------------------------------------------------------
WeekHeading.prototype.onclick = function ()
{
  //reduce indirection:
  var owner = this.weekObj.owner;
  var cells = owner.cells;
  var sdates = owner.selectedDates;
  var i,j;
  owner.rows[this.weekObj.tableRow] = !owner.rows[this.weekObj.tableRow];
  for(i=0;i<cells.length;i++)
  {
    if(cells[i].tableRow == this.weekObj.tableRow)
    {
      if(owner.rows[this.weekObj.tableRow] && (!owner.selCurMonthOnly || cells[i].date.getMonth() == owner.displayMonth && cells[i].date.getFullYear() == owner.displayYear)) //match all cells in the current row, with option to restrict to current month only
      {
        if(owner.selectedDates.arrayIndex(cells[i].date) == -1) {//if the date isn't already in the array
          sdates.push(cells[i].date);
        }
      }
      else                    //otherwise, remove it
      {
        for(j=0;j<sdates.length;j++)
        {
          if(sdates[j].getTime() == cells[i].date.getTime())  //this.weekObj.tableRow && sdates[j].getMonth() == owner.displayMonth && sdates[j].getFullYear() == owner.displayYear)
          {
            sdates.splice(j,1);  //remove dates that are within the displaying month/year that have the same day of week as the day cell
            break;
          }
        }
      }
    }
  }
  owner.reDraw();
};
/*****************************************************************************/
//-----------------------------------------------------------------------------
function CalCell(owner,tableCell,dateObj,row)
{
  this.owner = owner;    //used primarily for event handling
  this.tableCell = tableCell;       //the link to this cell object's table cell in the DOM
  this.cellClass;      //the CSS class of the cell
  this.selected = false;  //whether the cell is selected (and is therefore stored in the owner's selectedDates array)
  this.date = new Date(dateObj);
  this.dayOfWeek = this.date.getDay();
  this.week = this.date.getWeek();
  this.tableRow = row;
  
  //assign the event handlers for the table cell element
  this.tableCell.onclick = this.onclick;
  this.tableCell.onmouseover = this.onmouseover;
  this.tableCell.onmouseout = this.onmouseout;
  
  //and set the CSS class of the table cell
  this.setClass();
}
//-----------------------------------------------------------------------------
CalCell.prototype.onmouseover = function () //replicate CSS :hover effect for non-supporting browsers <iehack>
{
  this.setAttribute('class',this.cellClass + ' hover');
  this.setAttribute('className',this.cellClass + ' hover');
};
//-----------------------------------------------------------------------------
CalCell.prototype.onmouseout = function () //replicate CSS :hover effect for non-supporting browsers <iehack>
{
  this.cellObj.setClass();
};
//-----------------------------------------------------------------------------
CalCell.prototype.onclick = function () 
{
  //reduce indirection:
  var cell = this.cellObj;
  var owner = cell.owner;
  if(!owner.selCurMonthOnly || cell.date.getMonth() == owner.displayMonth && cell.date.getFullYear() == owner.displayYear)
  {
    if(owner.selectMultiple == true)  //if we can select multiple cells simultaneously, add the currently selected cell's date to the selectedDates array
    {
      if(!cell.selected) //if this cell has been selected
      {
        if(owner.selectedDates.arrayIndex(cell.date) == -1) {
          owner.selectedDates.push(cell.date);
        }
      }
      else    
      {
        var tmp = owner.selectedDates; // to reduce indirection
        //if the cell has been deselected, remove it from the owner calendar's selectedDates array
        for(var i=0;i<tmp.length;i++)
        {
          if(tmp[i].getUeDay() == cell.date.getUeDay()) {
            tmp.splice(i,1);
          }
        }
      }
    }
    else //if we can only select one cell at a time
    {
      owner.selectedDates = new Array(cell.date);
      if(owner.tgt) //if there is a target element to place the value in, do so
      {
        owner.tgt.value = owner.selectedDates[0].dateFormat();
        if(owner.mode == 'popup') {
          owner.hide();
        }
      }
    }
    owner.reDraw(); //redraw the calendar cell styles to reflect the changes
  }
};
//-----------------------------------------------------------------------------
CalCell.prototype.setClass = function ()  //private: sets the CSS class of the cell based on the specified criteria
{
  if(this.selected) {
    this.cellClass = 'cell_selected';
  }
  else if(this.owner.displayMonth != this.date.getMonth() ) {
    this.cellClass = 'notmnth';  
  }
  else if(this.date.getDay() > 0 && this.date.getDay() < 6) {
    this.cellClass = 'wkday';
  }
  else {
    this.cellClass = 'wkend';
  }
  
  if(this.date.getFullYear() == this.owner.curDate.getFullYear() && this.date.getMonth() == this.owner.curDate.getMonth() && this.date.getDate() == this.owner.curDate.getDate()) {
    this.cellClass = this.cellClass + ' curdate';
  }

  this.tableCell.setAttribute('class',this.cellClass);
  this.tableCell.setAttribute('className',this.cellClass); //<iehack>
};
/*****************************************************************************/
Date.prototype.getDayOfYear = function () //returns the day of the year for this date
{
  return parseInt((this.getTime() - new Date(this.getFullYear(),0,1).getTime())/86400000 + 1);
};
//-----------------------------------------------------------------------------
Date.prototype.getWeek = function () //returns the day of the year for this date
{
  return parseInt((this.getTime() - new Date(this.getFullYear(),0,1).getTime())/604800000 + 1);
};
/*function getISOWeek()
{
  var newYear = new Date(this.getFullYear(),0,1);
  var modDay = newYear.getDay();
  if (modDay == 0) modDay=6; else modDay--;
  
  var daynum = ((Date.UTC(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0) - Date.UTC(this.getFullYear()),0,1,0,0,0)) /1000/60/60/24) + 1;
  
  if (modDay < 4 ) {
      var weeknum = Math.floor((daynum+modDay-1)/7)+1;
  }
  else {
      var weeknum = Math.floor((daynum+modDay-1)/7);
      if (weeknum == 0) {
          year--;
          var prevNewYear = new Date(this.getFullYear(),0,1);
          var prevmodDay = prevNewYear.getDay();
          if (prevmodDay == 0) prevmodDay = 6; else prevmodDay--;
          if (prevmodDay < 4) weeknum = 53; else weeknum = 52;
      }
  }
  
  return + weeknum;
}*/
//-----------------------------------------------------------------------------
Date.prototype.getUeDay = function () //returns the number of DAYS since the UNIX Epoch - good for comparing the date portion
{
  return parseInt(Math.floor((this.getTime() - this.getTimezoneOffset() * 60000)/86400000)); //must take into account the local timezone
};
//-----------------------------------------------------------------------------
Date.prototype.dateFormat = function(format)
{
  if(!format) { // the default date format to use - can be customized to the current locale
    //format = 'm/d/Y';
    format = 'd/m/Y';
  }
  LZ = function(x) {return(x < 0 || x > 9 ? '' : '0') + x};
  var MONTH_NAMES = new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
  var DAY_NAMES = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
  format = format + "";
  var result="";
  var i_format=0;
  var c="";
  var token="";
  var y=this.getFullYear().toString();
  var M=this.getMonth()+1;
  var d=this.getDate();
  var E=this.getDay();
  var H=this.getHours();
  var m=this.getMinutes();
  var s=this.getSeconds();
  var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
  // Convert real this parts into formatted versions
  var value = new Object();
  //if (y.length < 4) {y=''+(y-0+1900);}
  value['Y'] = y.toString();
  value['y'] = y.substring(2);
  value['n'] = M;
  value['m'] = LZ(M);
  value['F'] = MONTH_NAMES[M-1];
  value['M'] = MONTH_NAMES[M+11];
  value['j'] = d;
  value['d'] = LZ(d);
  value['D'] = DAY_NAMES[E+7];
  value['l'] = DAY_NAMES[E];
  value['G'] = H;
  value['H'] = LZ(H);
  if (H==0) {value['g']=12;}
  else if (H>12){value['g']=H-12;}
  else {value['g']=H;}
  value['h']=LZ(value['g']);
  if (H > 11) {value['a']='pm'; value['A'] = 'PM';}
  else { value['a']='am'; value['A'] = 'AM';}
  value['i']=LZ(m);
  value['s']=LZ(s);
  //construct the result string
  while (i_format < format.length) {
    c=format.charAt(i_format);
    token="";
    while ((format.charAt(i_format)==c) && (i_format < format.length)) {
      token += format.charAt(i_format++);
      }
    if (value[token] != null) { result=result + value[token]; }
    else { result=result + token; }
    }
  return result;
};
/*****************************************************************************/
Array.prototype.arrayIndex = function(searchVal,startIndex) //similar to array.indexOf() - created to fix IE deficiencies
{
  startIndex = (startIndex != null ? startIndex : 0); //default startIndex to 0, if not set
  for(var i=startIndex;i<this.length;i++)
  {
    if(searchVal == this[i]) {
      return i;
    }
  }
  return -1;
};
/********************************   ROTINA DE CONCILIACAO *********************************************/


 function StrToDouble(st){
      var s = String(st);
     while (s.indexOf(".") >= 0)
       s = s.replace(".","");
     return new Number(s.replace(",","."));
   }
   function Arredonda( valor , casas ){
    var novo = Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );
    return( novo );
  }

  function acumulaConc(quantidade){
	var somaValor = 0;
     for (i=0;i < quantidade;i++){
            chcado = eval("document.lancamentos.setadomov_"+i+".checked");
     		if(chcado ==  true){
         	  eval("valor = document.lancamentos.valmov_"+ i + ".value;");
         	  somaValor += StrToDouble(valor) ;
          	  somaValor = Arredonda( somaValor , 2 );
		}
	}
          	document.lancamentos.totConc.value = new String(somaValor).replace(".",",");
           onExitValorField(document.lancamentos.totConc,2,"S",0,0);
}
	
	function menuengine(e) {
		//Comentado: retorna o c?digo pressionado
		if(e.which == null){
			// Operacao Cadastro
			if (e.keyCode==124)
				operacaoCadastro();
			// Operacao
			if (e.keyCode==21)
				OpenHELPP();
			else if (e.keyCode==15)
				operacaoLista()
			// Cedente
			else if (e.keyCode==3)
				cedente()
			// Cadastro Conta Grafica
			else if (e.keyCode==7)
				contaGrafica()
			// Lan?amento Conta Grafica
			else if (e.keyCode==20)
				ContaLancamento()
			// Estorno Conta Grafica
			else if (e.keyCode==5)
				estorno()
			// Relatorio de eo Conta Grafica
			else if (e.keyCode==26)
				relEvento()
			// Relatorio de Saldo Conta Grafica
			else if (e.keyCode==18)
				relSaldo()
			// Cadastro de Sacado
			else if (e.keyCode==19)
				sacado()
			// Cadastro de Conta Corrente
			else if (e.keyCode==10)
				contacorrente()
			// Cadastro de Agente
			else if (e.keyCode==1)
				agente()
			// Cadastro De Fornecedor
			else if (e.keyCode==6)
				fornecedor()
			// Carta ao Sacado
			else if (e.keyCode==23)
				cartaSacado()
			// Ingresso Manuten??o
			else if (e.keyCode==14)
				ingManut()
			// Importa??o Operacao
			else if (e.keyCode==9)
				opeImport()
			
			// N?o tem como pq 13 = Enter
			// Monitor Operacao
			else if (e.keyCode==22){
				if ((e.ctrlKey)&&(e.shiftKey)){
					opeMonitor()
				}
			}
			// Liquida?oes por sele?ao
			else if (e.keyCode==12)
				LiquidacaoSelecao()
			// Demonstrativo Operacao
			else if (e.keyCode==4)
				opeDemonstrativo()
			// Bordero
			else if (e.keyCode==2)
				bordero()
			// Pendencia Aberto
			else if (e.keyCode==16)
				penAbe()
			// reembolso
			else if (e.keyCode==11)
				reembolso()
			// Pendencia Liquidada
			else if (e.keyCode==8)
				penLiq()
			// Extrato Conta Gr?fica
			else if (e.keyCode==24){
				contaGraficaExtrato()
			}
			// Recibo de Pendencia  
			else if(e.keyCode==25)
				recPend();
		}else{
			// Operacao Cadastro
			if (e.which==124)
				teclaControle();
			}
	}  



function operacaoCadastro() {
  document.obFormMenuAtalho.action="nfOperacaoCadastro.jsp";
  document.obFormMenuAtalho.submit();
}

function teclaControle() {
  		window.open('../jsp/nfIniciaControleAtalho.jsp?noMenu=true','obModal','width=' + 350 + ',height='+ 650 + ',directories=no,location=0,menubar=no,scrollbars=yes,status=no,toolbar=no,resizeable=yes,left=0,top=0,screenX=0,screenY=0');
}


function LiquidacaoSelecao() {
  document.obFormMenu.action="nfLiquidacaoSelecaoLista.jsp";
  document.obFormMenu.submit();
}
function operacaoLista() {
  document.obFormMenu.action="nfOperacaoLista.jsp";
  document.obFormMenu.submit();
}
function cedente() {
  document.obFormMenu.action="nfCedentesLista.jsp";
  document.obFormMenu.submit();
}
function contaGrafica() {
  document.obFormMenu.action="nfCedContaGraficaLista.jsp";
  document.obFormMenu.submit();
}
function ContaLancamento() {
  document.obFormMenu.action="nfCedContaGraficaListaLancamento.jsp?tipo=lanc";
  document.obFormMenu.submit();
}
function contaGraficaExtrato() {
  document.obFormMenu.action="nfCedContaGraficaExtrato.jsp?fora=true";
  document.obFormMenu.submit();
}
function estorno() {
  document.obFormMenu.action="nfCedContaGraficaEstorno.jsp";
  document.obFormMenu.submit();
}
function relEvento() {
  document.obFormMenu.action="nfCedContaGraficaRelatorioEvento.jsp";
  document.obFormMenu.submit();
}
function relSaldo() {
  document.obFormMenu.action="nfContaGraficaRelacaoSaldo.jsp";
  document.obFormMenu.submit();
}
function agente() {
  document.obFormMenu.action="nfAgenteLista.jsp?tipoRel=3";
  document.obFormMenu.submit();
}
function sacado() {
  document.obFormMenu.action="nfSacadosLista.jsp";
  document.obFormMenu.submit();
}
function contacorrente() {
  document.obFormMenu.action="nfContaCorCaixaLista.jsp";
  document.obFormMenu.submit();
}
function fornecedor() {
        document.obFormMenu.action="nfFornecedorLista.jsp?tipoRel=3";
        document.obFormMenu.submit();
}
function cartaSacado() {
  document.obFormMenu.action="nfCartaSacadoRelatorioSelecao.jsp";
  document.obFormMenu.submit();
}
function ingManut() {
  document.obFormMenu.action="nfManutencaoSelecaoLista.jsp";
  document.obFormMenu.submit();
}
function opeImport() {
  document.obFormMenu.action="nfOperacaoImporta.jsp";
  document.obFormMenu.submit();
}
function opeMonitor() {
  document.obFormMenu.action="nfOperacaoMonitor.jsp";
  document.obFormMenu.submit();
}
function opeDemonstrativo() {
  document.obFormMenu.action="nfDemonstrativo.jsp?tipoRel=4";
  document.obFormMenu.submit();
}
function bordero() {
  document.obFormMenu.action="nfBorderoDigitacaoLista.jsp";
  document.obFormMenu.submit();
}
function penAbe() {
  document.obFormMenu.action="nfPendenciaAbertoLista.jsp";
  document.obFormMenu.submit();
}
function reembolso() {
  document.obFormMenu.action="nfReembolsoLista.jsp";
  document.obFormMenu.submit();
}
function penLiq() {
  document.obFormMenu.action="nfPendenciaLiquidadoLista.jsp";
  document.obFormMenu.submit();
}
function recPend(){
  document.obFormMenu.action="nfReciboPendenciaLista.jsp";
  document.obFormMenu.submit();
}

function onExitHoraField(sender,base){
   //bRet = validaDate(sender,base);

   var texto = String(sender.value);

   if ((texto != "")){
      while(texto.length < 4){
		texto = texto + "0";
		}
	ok = validahora(texto);	
	if(ok){	
    if (NS4)
     sender.value = texto.substring(0,2) + ":" + texto.substring(2,4);
    else
     sender.value = texto.substring(0,2) + ":" + texto.substring(2,4);
     }else{
		sender.focus();
		return false;
     }
     }
   status = defaultStatus;
   return true;
}
function onKeyPressHoraField(sender,base,e){	
  var tecla = (e.keyCode);
  var cadeia = String("0123456789");

    var valid = false;
    tecla = String.fromCharCode(NS4?e.which:e.keyCode);
    valid = cadeia.indexOf(tecla) >= 0;

    var condicao = (NS4? (e.keyCode >= 37 && e.keyCode <= 57):false );
    return (valid || ( e.keyCode == 8 || e.keyCode == 9 || condicao));
}
function validahora(hora){
	var hh = hora.substring(0,2);
	var mm = hora.substring(2,4);
	if(hh>23){
		alert('Digite uma hora válida no formato HHMM');
		return false;
	}
	if(mm > 59){
		alert('Digite uma hora válida no formato HHMM');
		return false;	
	}
	return true;
}
function onEnterHoraField(sender,base){

  //calender(sender.name);
  
  texto = sender.value;
  status = sender.title;
  texto = texto.replace( ":", "" );
  texto = texto.replace( ":", "" );
  if (NS4)
    sender.value = texto;
  else
    sender.value = texto;
  sender.select();
}
