﻿/************************************************************************************************************
(C) ww	w.dhtmlgoodies.com, November 2005

This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.

Thank you!

www.dhtmlgoodies.com
Alf Magne Kalleland

ex: 
input type="text" id="campoa" name="campoa" nexttab="campob" 
input type="text" id="campob" name="campob" nexttab="button"  
************************************************************************************************************/


var currentlyActiveInputRef = false;
var currentlyActiveInputClassName = false;

/*************************************************************************
// Posiciona o foco em um determinado Campo
// exemplo: onPosiciona('txtCampo');
*************************************************************************/
function onPosiciona(fld) {
  try {
    //if(document.getElementById(fld))
    document.getElementById(fld).focus();
  }
  catch (e) {
    // ops! algum erro ocorreu
    var x = 1;
  }
}


/*************************************************************************
// captura teclas versao III
// ev (event)
// tf = this Field - objeto campo que está recebendo o onEnter
// ft = field target
// fl = field lenght
// fu = function a ser executado
// exemplo: <input type='text' name='x' onkeypress='return onEnter(event,this,'proximo_campo',10,'alert("tecla enter acionada");return false',false);" />
*************************************************************************/
function onEnterHL(ev, thisF, targetF, thisL, Fun, isDebug) {
  // verifica os parametros enviados
  Fun = ((Fun == null || Fun == 'null') ? '' : Fun);
  targetF = ((targetF == null || targetF == 'null') ? '' : targetF);

  var eKey = new Array(); kCode = 0; msg = '';
  eKey[0] = 35; // Hme
  eKey[1] = 36; //'end';
  eKey[2] = 37; //'<-- key';
  eKey[3] = 38; //'^ key';
  eKey[4] = 39; //'--> key';
  eKey[5] = 40; //'v key';
  eKey[6] = 33; //'pg up
  eKey[7] = 34; //'pg dw


  var args = onEnterHL.arguments;
  for (var z = 0; z < args.length; z++) {
    if (args[z] != null) {
      msg += 'Argumento ' + z + '=' + args[z] + '';
      if (typeof (args[z]) == 'event')
        msg += ' tipo = event';
      if (typeof (args[z]) == 'string')
        msg += ' tipo=string ';

      msg += '\n';
    }
  }
  if (ev.which)
    kCode = ev.which;
  else {
    ev = ev || window.event;
    kCode = window.event.keyCode;
  }


  // Trata das teclas de navegação
  if (document.all) { // IE
    var ok = false;
    for (var i = 0; i < eKey.length; i++) {
      if (eKey[i] == kCode) {
        ok = true;
        break;
      }
    }
    if (ok) {
      if (isDebug)
        alert('code capturado: ' + kCode);
      return true;
    }
  }
  else {
    if (eKey.indexOf(kCode) > -1) // setas direita, esquerda, cima baixo
    {
      if (isDebug)
        alert('code capturado: ' + kCode);
      return true;
    }
  }

  if (isDebug) {
    if (document.getElementById('lbl'))
      document.getElementById('lbl').innerHTML = 'kCode: ' + kCode + '. ev: ' + ev
						+ ' (' + ((window.event) ? 'ev.keyCode' : 'ev.which') + '). Tam: ' + thisF.value.length + '. TF: ' + targetF + '. ' +
						' thisF.id-' + thisF.id + '. Args: ' + args.length + '. args: ' + msg;
    document.getElementById('lbl').innerHTML += '. code: <font color=navy>' + kCode + '</font>';
  }

  if (self.status.length > 100)
    self.status = '';


  if (kCode != 13) {
    if (isDebug)
      document.getElementById('lbl').innerHTML += '. len: <font color=navy>' + thisL + "/" + thisF.value.length + '</font>';

    if ((thisF.value.length - 1) == parseInt(thisL) - 1) {
      if (Fun != '') {
        if (isDebug)
          document.getElementById('lbl').innerHTML += '. fun is passed: <font color=navy>' + Fun + '</font>';

        try {
          eval(Fun);
          if (window.event) {
            event.bubleCancel = true;
            event.returnValue = false; // no more processing..
          }
          else
            return false;

        }
        catch (e) {
          return true;
        }
        return false;
      }
      if (targetF != '') {
        if (isDebug)
          document.getElementById('lbl').innerHTML += '. Target is passed: <font color=navy>' + targetF + '</font>';
        if (isDebug)
          document.getElementById('lbl').innerHTML += '. target: <font color=navy>' + targetF + '</font>';

        if (window.event) {
          event.bubleCancel = true;
          event.returnValue = false; // no more processing..

        }
        document.getElementById(targetF).focus();
        return false;
      }
      else
        return true;
    }
    return true;
  }
  else {
    //alert('kcode=13');
    // Foi passado funcao?	
    if (Fun != '') {
      if (isDebug)
        document.getElementById('lbl').innerHTML += '. funcao: <font color=navy>' + Fun + '</font>';

      try {
        eval(Fun);
        if (window.event) {
          event.bubleCancel = true;
          event.returnValue = false; // no more processing..
        }
        else
          return false;
      }
      catch (e) {
        return true;
      }

    }

    //alert('enter');

    // tem campo destino?
    if (targetF != '') {
      if (isDebug)
        document.getElementById('lbl').innerHTML += '. target: <font color=navy>' + targetF + '</font>';
      if (window.event) {
        event.bubleCancel = true;
        event.returnValue = false; // no more processing..
      }
      document.getElementById(targetF).focus();

      return false;
    }

    if (window.event) {
      event.bubleCancel = true;
      event.returnValue = false; // no more processing..
    }
    else
      return false;
  }
}
// causa HighLight no campo quando evento onfocus ativo
function highlightActiveInput() {
  if (currentlyActiveInputRef) {
    currentlyActiveInputRef.className = currentlyActiveInputClassName;
  }
  currentlyActiveInputClassName = this.className;
  this.className = 'inputHighlighted';
  currentlyActiveInputRef = this;


}

// desativa evento highlight quando onblur ocorre
function blurActiveInput() {
  this.className = currentlyActiveInputClassName;


}


// Inicializa funcao hightling
function initInputHighlightScript(isDebug) {

  //a=a+12;
  var tags = ['input', 'textarea', 'password'];
  var cont = 0; msg = '';
  var isFirst = true;
  var hasNextTab = false;

  for (tagCounter = 0; tagCounter < tags.length; tagCounter++) {
    var inputs = document.getElementsByTagName(tags[tagCounter]);
    for (var no = 0; no < inputs.length; no++) {
      if (inputs[no].className && inputs[no].className == 'doNotHighlightThisInput')
        continue;

      if (inputs[no].tagName.toLowerCase() == 'textarea' ||
			      (inputs[no].tagName.toLowerCase() == 'input' &&
			        (inputs[no].type.toLowerCase() == 'text') ||
			        inputs[no].type.toLowerCase() == 'password')) {
        cont++;
        inputs[no].onfocus = highlightActiveInput;
        inputs[no].onblur = blurActiveInput;

        // ATL - 16/06/2007 - Verifica se tem a TAG NextTab e coloca codigo
        try {
          nexttab = inputs[no].getAttribute('nexttab');
          funcao = inputs[no].getAttribute('funcao');
          funcao = ((funcao == null) ? 'null' : funcao);
          funcao = inputs[no].getAttribute('funcao');
          funcao = ((funcao == null) ? 'null' : funcao);
          var isHightLighted = inputs[no].getAttribute('isHightLighted'); // necessário para não replcar a fun~ção no objeto
          tipo = inputs[no].getAttribute('tipo');

          if (tipo != null) {
            tipo = ((tipo.toLowerCase().indexOf('numero') == -1) ? null : tipo);
          }

          if (nexttab && tipo == null && isHightLighted == null) { // so processa se tipo = null
            try { tm = inputs[no].getAttribute('maxlength'); }
            catch (e) { tm = 999; }

            inputs[no].removeAttribute('onkeyup');

            if (navigator.appName.toLowerCase().indexOf('explorer') > -1)  // porra IE! que trabalhao para achar esta funcao - rs
            {
              var fn = new Function("onEnterHL(event,document.getElementById('" + inputs[no].id + "'),'" + nexttab + "', " +
										tm + ", \"" + funcao + "\",false)");
              var fn2 = new Function("return window.event.keyCode != 13");

              // puta-que-o-pariu  IE!!! --> para poder capturar a tEcla <ENTER> foi necessario incluir o evento onkeypress
              inputs[no].setAttribute('onkeypress', fn2);
              inputs[no].setAttribute('onkeyup', fn); //function(event) {onEnterHL(event, this, nexttab , tm , funcao , false);});
              //inputs[no].setAttribute('onkeypress', 'return window.event.keyCode != 13');
              //inputs[no].setAttribute('onkeyup', 'onEnterHL(event, this, "' + nexttab + '", ' + tm + ',' + ((funcao=='null')?'null':'"' +  funcao + '"') + ', false);');
              
              inputs[no].setAttribute('isHightLighted', 'true');
              if (isDebug)
                alert(inputs[no].onkeyup);
            }
            else
              document.getElementById(inputs[no].id).setAttribute("onkeyup", "onEnterHL(event,this,'" +
												nexttab + "', " + tm + ", " + funcao + ", false)");

            if (isFirst) {
              isFirst = false;
              msg = inputs[no].onkeypress;
            }
            hasNextTab = true;
          }
        }
        catch (e) {

        }
      }
    }
    if (hasNextTab && isDebug)
      alert('nexttab encontrado! ' + msg);

  }
  if (isDebug)
    alert('Pegou ' + cont + ' campos');

  if (isDebug)
    a = a + 1;

}


// captura teclas versao I
function onEnterI(thisF, thisEv, objTarget, objTam, objFun, isDebug) {
  // thisF = field (this)
  // thisEv = event; 
  // objTarget = Campo de destino
  // objFun = funcao do usuario --> obrigatoriamente a funcao deve retornar true ou false; 
  // objTam = Tamanho maximo para o campo
  // Exemplo:  <input type=texte value='xxx' onKeyPress="return onEnter(this,event,'proximo_campo', 10,null,false);">

  var keycode = 0; var isOK = false;

  if (window.event)
    keycode = window.event.keyCode;   // Windows?
  else if (ev)
    keycode = ev.which;                    // noWindows (NS, FF, mozilla)
  else
    return true;                                   // Ops!, nao detectou nada


  if (isDebug != null) self.status = 'Codigo: ' + keycode;

  // não é codigo 13, então retorna
  if (keycode != 13) {
    if (objTam != 999) {
      if (thisF.lenght == objTam) {
        if (objTarget != "") {
          document.getElementById(objTarget).focus();
          return false;
        }
      }
    }
    return true;
  }

  if (fu != null && fu != '') {
    try {
      return eval(fu);
    }
    catch (err) {
      txt = "Há um erro nesta página.\n\n"
      txt += "Descrição do Erro: " + err.description + "\n\n"
      txt += "Clicar OK para continuar.\n\n"
      alert(txt)
    }
  }

  //alert('ft='+ft+' fu='+fu+' fi='+fi+' df='+document.forms[0].elements[ft]);
  // Campu para pular
  if (ft != null) {
    //alert('ok');
    //document.forms[0].elements[ft].focus();
    document.getElementById(ft).focus();
    if (window.event) {
      event.bubleCancel = true;
      event.returnValue = false; // no more processing..
    }
    else
      return false;
  }

}


/*************************************************************************
// captura teclas versao II
// ev (event)
// tf = this Field - objeto campo que está recebendo o onEnter
// ft = field target
// fl = field lenght
// fu = function a ser executado
// exemplo: <input type='text' name='x' onkeypress='return onEnter(event,this,'proximo_campo',10,'alert("tecla enter acionada");return false',false);" />
*************************************************************************/
function onEnterHL2(ev, tf, ft, fl, fu, isDebug) {
  var kCode = 0;

  if (ev.which)
    kCode = ev.which;

  if (window.event)
    kCode = ev.keyCode;

  //	ev = ev || window.event;             // gets the event in ie or ns
  //	kCode = ev.keyCode || ev.which;

  var ret = ':: keyCode=' + kCode + ' ::';

  ft = ((ft == null) ? '' : ft);
  fl = ((fl == null) ? 999 : fl);
  fu = ((fu == null) ? '' : fu);
  ft = ((ft == null) ? '' : ft);
  tf = ((tf == null) ? '' : tf);
  //a=a+1;

  if (isDebug) {
    if (document.getElementById('lblMsg'))
      document.getElementById('lblMsg').innerHTML = 'KeyCode: ' + kCode + '. Campo: ' + tf.name + '. Target: ' + ft + '. Tam: ' + tf.value.length + '. Max: ' + fl + '. Tipo de Evento: ' + ((window.event) ? 'window.event' : ((ev.which) ? 'ev.which' : 'ndf'));
  }

  // tecla apertada não é 13
  if (kCode != 13) {
    ret += '>> nao é 13';
    a = a + 1;
    // Verifica tamanho
    if ((tf.value.lenght + 1) == parseInt(fl)) {
      ret += '>> tf.lenght=' + tf.value.length;
      if (ft != '') {
        ret += ' ft = ' + ft;
        document.getElementById(ft).focus();
        alert(ret);
        if (window.event) {
          event.bubleCancel = true;
          event.returnValue = false; // no more processing..
        }
        return false;
      }
    }
    return true;
  }

  // tecla ENTER foi acionada

  // foi passado função?
  if (fu != '') {
    try {
      return eval(fu);
    }
    catch (e) {
      var erro = 'Erro ao executar função no campo ' + tf.name + ': ' + e.Description;
      if (typeof (showMensagem) == 'function')
        showMensagem(erro);
      else if (typeof (parent.showMensagem) == 'function')
        parent.showMensagem(erro);
      else
        alert(erro);
      return false;
    }
  }

  // posicionar no campo
  if (ft != '') {
    document.getElementById(ft).focus();
  }

  if (window.event) {
    event.bubleCancel = true;
    event.returnValue = false; // no more processing..
  }
  else
    return false;

}


function addEvent(obj, evType, fn, useCapture) {
  if (obj.addEventListener) {
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent) {
    var r = obj.attachEvent("on" + evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
}

function removeEvent(obj, evType, fn, useCapture) {
  if (obj.removeEventListener) {
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent) {
    var r = obj.detachEvent("on" + evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}
