/**********************************************************
  Liguagem: JavaScript
  Arqivo criado por: Geraldo José Ferreira Chagas Júnior
  Empresa: WebZet Tecnologia & Integrações LTDA
  Data: 07/08/2009
  Ultima atualização: 09/10/2009
***********************************************************/
var Navgador_Cliente = 0;

var MSIE = false;
var Opera = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;

String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,'');}
Number.prototype.roundRM = function (dec) {return (Math.round(this*Math.pow(10,dec))/Math.pow(10,dec)).toFixed(dec);}
Number.prototype.zeroFormatInt = function(n) {return n=new Array((++n,(t=(this+"").length)<n?n-t:0)).join(0),n+this;}

Number.prototype.mod = function (dvsor)
{
   var dvdendo=parseFloat(this.roundRM(4));
   dvsor=parseFloat(dvsor.roundRM(4));
   if(dvdendo<dvsor) return dvdendo;
   var result=dvdendo/dvsor;
   return ((result.roundRM(10)-parseInt(result))*dvsor).roundRM(4);
}

function $(id){return document.getElementById(id);}

function ajaxInit()
{
   var xmlhttp ;
   try
   {
      xmlhttp = new XMLHttpRequest();
      Navgador_Cliente = 1;
   }
   catch(ee)
   {
      try
      {
         xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP");
         Navgador_Cliente = 2;
      }
      catch(e)
      {
         try
         {
            xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
            Navgador_Cliente = 3;
         }
         catch(E)
         {
            xmlhttp = false;
            Navgador_Cliente = 0;
         }
      }
   }
   return xmlhttp;
}

function select_innerHTML(objeto,innerHTML)
{
   /******
   * OBS.: A função foi alterada de forma que a teg <option> e </option> devem estar
   *       escritas em minúsculo no código HTML
   * Auterada por: Geraldo José Ferreira Chagas Júnior
   /******
   * select_innerHTML - corrige o bug do InnerHTML em selects no IE
   * Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
   * Versão: 2.1 - 04/09/2007
   *  Autor: Micox - Náiron José C. Guimarães - micoxjcg@yahoo.com.br
   * @objeto(tipo HTMLobject): o select a ser alterado
   * @innerHTML(tipo string): o novo valor do innerHTML
   *******/

   objeto.innerHTML = ""
   var selTemp = document.createElement("micoxselect")
   var opt;
   selTemp.id="micoxselect1"
   document.body.appendChild(selTemp)
   selTemp = $("micoxselect1")
   selTemp.style.display="none"
   if(innerHTML.indexOf("<option")<0)
   {//se não é option eu converto
       innerHTML = "<option>" + innerHTML + "</option>"
   }
   innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
   selTemp.innerHTML = innerHTML

   for(var i=0;i<selTemp.childNodes.length;i++)
   {
      var spantemp = selTemp.childNodes[i];
      if(spantemp.tagName)
      {
         opt = document.createElement("OPTION")
         if(document.all)
         { //IE
            objeto.add(opt)
         }
         else
         {
            objeto.appendChild(opt)
         }

         //getting attributes
         for(var j=0; j<spantemp.attributes.length ; j++)
         {
            var attrName = spantemp.attributes[j].nodeName;
            var attrVal = spantemp.attributes[j].nodeValue;
            if(attrVal)
            {
               try
               {
                  opt.setAttribute(attrName,attrVal);
                  opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
               }
               catch(e){}
            }
         }
         //getting styles
         if(spantemp.style)
         {
            for(var y in spantemp.style)
            {
               try{opt.style[y] = spantemp.style[y];}catch(e){}
            }
         }
         //value and text
         opt.value = spantemp.getAttribute("value")
         opt.text = spantemp.innerHTML
         //IE
         opt.selected = spantemp.getAttribute('selected');
         opt.className = spantemp.className;
      }
   }
   document.body.removeChild(selTemp)
   selTemp = null
}

function formatNumber(objTextBox, tamInt, numCasasDec, sepDec, e)
{
    var whichCode = (window.Event) ? e.which : e.keyCode;
    var posI = objTextBox.selectionStart;
    var posF = objTextBox.selectionEnd;

    //pra variar um pouco, no caso so IE temos que "rebolar" para conseguir
    //fazer algo simples
    if (!((posI) || (posI==0)))
    {
       var range = document.selection.createRange();
       var posF =  Math.abs(range.duplicate().moveEnd('character', -1000000));
       var posI =  Math.abs(range.duplicate().moveStart('character', -1000000));
    }

    var tamO = objTextBox.value.length;

    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8)) return true;

    //posição do separador decimal
    posv = objTextBox.value.indexOf(String.fromCharCode(sepDec));

    //Limita a parte inteira
    if ((posv >= tamInt) && (posI == posF) && (posI <= posv)) whichCode = 1;

    //na digitação do separador decimal, ou ela não existe ou tem que está marcada
    if ((whichCode == sepDec) && (numCasasDec > 0))
    {
       //a vírgula só pode entrarem uma posição que não faça o número
       //de casas decimais extrapolar e
       if ((posv == -1) && ((tamO-posF) <= numCasasDec))
          return true;
       //se já existir uma vírgula, ela poderá ser digitada desde que
       //a já existente seja apagado, ou seja, esteja dentro do compo de seleção
       else if ((posv >= posI) && (posv < posF))
          return true;
    }

    //Permitindo números (caracteres de 0 a 9)
    if ((whichCode >= 48) && (whichCode <= 59))
    {
       //se não tiver vrigula, não tem porque limitar o número de casas decimais
       if (posv == -1)
       {
          if ((tamO < tamInt) || (posI != posF)) return true;
       }
       else if ((posI <= posv) || (((tamO-posv)-(posF-posI)) <= numCasasDec))
          return true;
    }

    return false;
}

function valorNum (str)
{
   var _temp = parseFloat(str.replace(".","").replace(",","."));
   if (!(_temp)) _temp=0;
   return _temp;
}

function valorStr (int)
{
   return int.toString().replace(".",",");
}

function scrollCab(listaCab, lista)
{
   var Lst = $(lista);
   var LstCab = $(listaCab);

   if (Lst.scrollLeft!=LstCab.scrollLeft) LstCab.scrollLeft=Lst.scrollLeft;
}

function mouseSobre(tr)
{
   if(MSIE)
   {
      tr.style.backgroundColor='#000066';
      tr.style.color='#FFFFFF';
   }
}

function mouseFora(tr)
{
   if(MSIE)
   {
      tr.style.removeAttribute('backgroundColor');
      tr.style.removeAttribute('color');
   }
}

function markRow (tr, req)
{
   if (tr.className.indexOf('marked')!=-1)
   {
      return tr;
   }
   else
   {
      try
      {
         req.className = req.className.replace(' marked', '');
      }
      catch(e){}
   }

   tr.className += ' marked';
   return tr;
}

function marcaTextBox (obj)
{
   try
   {
      var range = document.selection.createRange();
      range.moveStart('character', -100000);
      range.moveEnd('character', 100000);
      range.select();
   }
   catch(e)
   {
      obj.selectionStart=0;
      obj.selectionEnd=1000;
   }
}
