var packlist_total;
var status_total;

/*
    CONVERTE DE FT² PARA M² E VICE-VERSA
*/
function converte ( direcao, el )
{
    // PEGO A ID DA LINHA
    //var mask = /item/;
    var mask = /[^0-9]{4}/;
    id = Number ( el.parentNode.parentNode.id.replace ( mask, '' ) );

    // RELAÇÃO ENTRE PÉS QUADRADOS E METROS QUADRADOS
    var fator = 0.09290304;
    var valor;

    // CONVERTE
    if ( direcao == 'ft2m' )
    {
        dest = document.getElementById ( 'm2_'+id );
        valor = el[el.selectedIndex].text * fator;
        //alert ( valor );
    }
    else
        return false;

    // FORMATA O NÚMERO COM DUAS CASAS DECIMAIS
    valor *= 100;
    valor = Math.round ( valor ) ;
    valor /= 100;

    dest.value = valor;

    getTotal ( )
}

/*
    SOMA O TOTAL DOS CAMPOS FT² E M²
*/
function getTotal ( )
{
    var totalM2  = 0;
    var totalFT2 = 0;

    // PERCORRE AS LINHAS DA TABELA
    for ( i=1; i<=packlist_total; i++ )
    {
        // AVALIA SE O VALOR DO CAMPO É UM NÚMERO
        valorM2  = parseFloat ( document.getElementById ( 'm2_'+i ).value );
        valorFT2 = parseFloat ( document.getElementById ( 'ft2_'+i )[document.getElementById ( 'ft2_'+i ).selectedIndex].text );

        if ( valorFT2 > 0 )
        {
            // E ADICIONA AO TOTAL
            totalM2  += valorM2;
            totalFT2 += valorFT2;
        }
    }

    // FORMATA O NÚMERO COM DUAS CASAS DECIMAIS
    totalM2 *= 100;
    totalM2 = Math.round ( totalM2 ) ;
    totalM2 /= 100;

    totalFT2 *= 100;
    totalFT2 = Math.round ( totalFT2 ) ;
    totalFT2 /= 100;

    // ESCREVE O TOTAL NO CAMPO
    document.getElementById ( 'm2_total' ).value  = totalM2;
    document.getElementById ( 'ft2_total' ).value = totalFT2;
}

/*
    REMOVE UM ITEM DA PACKING LIST
*/
function limpaPallet(el)
{
    if ( confirm ( "All the informations of this pallet will be lost." ) )
    {
        var mask = /[^0-9]{4}/;
        id = Number(el.parentNode.parentNode.id.replace ( mask, '' ));

        if ( packlist_total > 1 )
        {
            // PEGO A TABELA DA PACKLIST
            tbody = document.getElementById ( 'tab_packlist' );
            tbody.deleteRow ( id - 1 );

            // PERCORRO OS ITENS SEGUINTES, TROCANDO AS IDs DAS LINHAS E OS NOMES DOS ELEMENTOS
            for ( id; id < packlist_total; id++ )
            {
                linha    = document.getElementById ( 'item'+(id+1) );
                linha.id = 'item'+id;

                elNome      = document.getElementById ( 'popli_nome_'+(id+1) );
                elDimensoes = document.getElementById ( 'popli_dimensoes_'+(id+1) );
                elEspecies  = document.getElementById ( 'popli_especies_'+(id+1) );
                elSKU       = document.getElementById ( 'sku_'+(id+1) );
                elFT2       = document.getElementById ( 'ft2_'+(id+1) );
                elM2        = document.getElementById ( 'm2_'+(id+1) );
				elBtClonar  = document.getElementById ( 'adicionarIgual'+(id+1) );

                elNome.id      = 'popli_nome_'+id;
                elNome.value   = 'Pallet '+id;
                elDimensoes.id = 'popli_dimensoes_'+id;
                elEspecies.id  = 'popli_especies_'+id;
                elSKU.id       = 'sku_'+id;
                elFT2.id       = 'ft2_'+id;
                elM2.id        = 'm2_'+id;

                elBtClonar.id	   = 'adicionarIgual'+id;
                elBtClonar.onclick = function(){ addPackItem(true,this.id.replace('adicionarIgual',''));};
            }

            // DECREMENTO O TOTAL DE CAMPOS DE ITENS DA PACKLIST
            packlist_total--;
        }
        else
        {
            elDimensoes = document.getElementById ( 'popli_dimensoes_'+id );
            elEspecies  = document.getElementById ( 'popli_especies_'+id );
            elSKU       = document.getElementById ( 'sku_'+id );
            elFT2       = document.getElementById ( 'ft2_'+id );
            elM2        = document.getElementById ( 'm2_'+id );

            elDimensoes.value   = '';
            elEspecies.value    = '';
            elSKU.value         = '';
            elFT2.value         = '';
            elM2.value          = '';
        }
        getTotal ( 'm2' );
        getTotal ( 'ft2' );
    }
}

/*
    REMOVE UM STATUS DO HISTÓRICO
*/
function limpaStatus ( el, id )
{
    if ( confirm ( "This status will be permanently lost." ) )
    {
        // PEGA A LINHA DO STATUS
        tr = el.parentNode.parentNode;

        // APAGA A LINHA DO STATUS
        tr.style.color='#CCCCCC'
        el.parentNode.innerHTML = '&nbsp;';

        // ENVIA A ID PARA O AJAX PRA APAGAR DO STATUS
        loadXMLPOST ( 'aj_removeStatus.php', 'id='+id );
    }
}

/*
    CRIA UMA LINHA NA PACKING LIST
*/
function addPackItem (clonar, idClonar)
{
    if(!idClonar)
    {
    	idClonar = packlist_total;
    }

    // INCREMENTO O TOTAL DE CAMPOS DE ITENS DA PACKLIST
    packlist_total++;


    // PEGO A TABELA EM UMA VARIÁVEL
    tabela = document.getElementById ( 'tab_packlist' );

    // CRIO OS ELEMENTOS DA TABELA
    tr = document.createElement ( 'tr' );
    tr.id = "item"+packlist_total;

    td1 = document.createElement ( 'td' );
    td1.align = 'center';

    td2 = document.createElement ( 'td' );
    td3 = document.createElement ( 'td' );
    td4 = document.createElement ( 'td' );
    td5 = document.createElement ( 'td' );
    td6 = document.createElement ( 'td' );
    td7 = document.createElement ( 'td' );

    // PEGO O CONTEÚDO DE CADA SELECT PRA MONTAR
    var arrDim      = document.getElementById('strDim').value.split('{{brk}}');
    var arrSKU      = document.getElementById('strSKU').value.split('{{brk}}');
    var arrFT2      = document.getElementById('strFT2').value.split('{{brk}}');
    var arrEspec    = document.getElementById('strEspec').value.split('{{brk}}');

    var arrDim_id   = document.getElementById('strDim_id').value.split('{{brk}}');
    var arrSKU_id   = document.getElementById('strSKU_id').value.split('{{brk}}');
    var arrFT2_id   = document.getElementById('strFT2_id').value.split('{{brk}}');
    var arrEspec_id = document.getElementById('strEspec_id').value.split('{{brk}}');

    // CRIO OS SELECTS
    comboDim    = document.createElement ( 'select' );
    comboEspec  = document.createElement ( 'select' );
    comboSKU    = document.createElement ( 'select' );
    comboFT2    = document.createElement ( 'select' );

    // DEFINO AS PROPRIEDADES DOS SELECTS
    comboDim.setAttribute ( 'class', 'input2' );
    comboDim.className      = 'input2';
    comboDim.tabIndex       = '1';
    comboDim.id             = 'popli_dimensoes_'+packlist_total;
    comboDim.name           = 'popli_dimensoes[]';
    comboDim.style.width    = '100%';
    comboDim.style.margin   = '0';
    comboDim.style.border   = '0';
    comboDim.onfocus        = function () {
        this.className = 'input2_over';
        this.setAttribute ( 'class', 'input2_over' );
    }
    comboDim.onblur         = function () {
        this.className = 'input2';
        this.setAttribute ( 'class', 'input2' );
    }

    comboEspec.setAttribute ( 'class', 'input2' );
    comboEspec.className    = 'input2';
    comboEspec.tabIndex     = '1';
    comboEspec.id           = 'popli_especies_'+packlist_total;
    comboEspec.name         = 'popli_especies[]';
    comboEspec.style.width  = '100%';
    comboEspec.style.margin = '0';
    comboEspec.style.border = '0';
    comboEspec.onfocus        = function () {
        this.className = 'input2_over';
        this.setAttribute ( 'class', 'input2_over' );
    }
    comboEspec.onblur         = function () {
        this.className = 'input2';
        this.setAttribute ( 'class', 'input2' );
    }

    comboSKU.setAttribute ( 'class', 'input2' );
    comboSKU.className      = 'input2';
    comboSKU.tabIndex       = '1';
    comboSKU.id             = 'sku_'+packlist_total;
    comboSKU.name           = 'sku[]';
    comboSKU.style.width    = '100%';
    comboSKU.style.margin   = '0';
    comboSKU.style.border   = '0';
    comboSKU.onfocus        = function () {
        this.className = 'input2_over';
        this.setAttribute ( 'class', 'input2_over' );
    }
    comboSKU.onblur         = function () {
        this.className = 'input2';
        this.setAttribute ( 'class', 'input2' );
    }

    comboFT2.setAttribute ( 'class', 'input2' );
    comboFT2.className      = 'input2';
    comboFT2.tabIndex       = '1';
    comboFT2.id             = 'ft2_'+packlist_total;
    comboFT2.name           = 'ft2[]';
    comboFT2.style.width    = '100%';
    comboFT2.style.margin   = '0';
    comboFT2.style.border   = '0';
    comboFT2.setAttribute ( 'onchange', "converte ('ft2m', this )" );
    comboFT2.onchange       = function () {
        javascript:converte ('ft2m', this )
    }
    comboFT2.onfocus        = function () {
        this.className = 'input2_over';
        this.setAttribute ( 'class', 'input2_over' );
    }
    comboFT2.onblur         = function () {
        this.className = 'input2';
        this.setAttribute ( 'class', 'input2' );
    }

    // MONTO OS SELECTS DE DIMENSÕES
    comboDim.options.length++
    comboDim.options[0].value = '';
    comboDim.options[0].text  = '';
    if ( arrDim [0] )
    {
        for ( i = 0; i < arrDim.length; i++ )
        {
            comboDim.options.length++
            comboDim.options[i+1].value = arrDim_id [i];
            comboDim.options[i+1].text  = htmldecode ( arrDim [i] );
		   	if(clonar && clonar==true)
		   	{
				if($('popli_dimensoes_'+idClonar).value==arrDim_id [i])
				{
					comboDim.options[i+1].selected  = 'selected';
				}
		   	}
        }
    }

    // MONTO OS SELECTS DE ESPÉCIES
    comboEspec.options.length++
    comboEspec.options[0].value = '';
    comboEspec.options[0].text  = '';
    if ( arrEspec [0] )
    {
        for ( i = 0; i < arrEspec.length; i++ )
        {
            comboEspec.options.length++
            comboEspec.options[i+1].value = arrEspec_id [i];
            comboEspec.options[i+1].text  = htmldecode ( arrEspec [i] );
		   	if(clonar && clonar==true)
		   	{
				if($('popli_especies_'+idClonar).value==arrEspec_id [i])
				{
					comboEspec.options[i+1].selected  = 'selected';
				}
		   	}
        }
    }

    // MONTO OS SELECTS DE SKU
    comboSKU.options.length++
    comboSKU.options[0].value = '';
    comboSKU.options[0].text  = '';
    if ( arrSKU [0] )
    {
        for ( i = 0; i < arrSKU.length; i++ )
        {
            comboSKU.options.length++
            comboSKU.options[i+1].value = arrSKU_id [i];
            comboSKU.options[i+1].text  = htmldecode ( arrSKU [i] );
		   	if(clonar && clonar==true)
		   	{
				if($('sku_'+idClonar).value==arrSKU_id [i])
				{
					comboSKU.options[i+1].selected  = 'selected';
				}
		   	}
        }
    }

    // MONTO OS SELECTS DE FT2
    comboFT2.options.length++
    comboFT2.options[0].value = '';
    comboFT2.options[0].text  = '';
    if ( arrFT2 [0] )
    {
        for ( i = 0; i < arrFT2.length; i++ )
        {
            comboFT2.options.length++
            comboFT2.options[i+1].value = arrFT2_id [i];
            comboFT2.options[i+1].text  = htmldecode ( arrFT2 [i] );
		   	if(clonar && clonar==true)
		   	{
				if($('ft2_'+idClonar).value==arrFT2_id [i])
				{
					comboFT2.options[i+1].selected  = 'selected';
				}
		   	}
        }
    }

    // INSIRO O CONTEÚDO DE CADA CÉLULA, UMA A UMA
    td1.innerHTML = '<a href="javascript:void(0);" onclick="javascript:limpaPallet(this);" title="Click here to delete this item from the packing list"><img border="0" alt="x" src="img/ico-erro.gif" width="14" height="14" id="teste" /></a>';
    td1.innerHTML = td1.innerHTML + '<a href="javascript:void(0);" onclick="javascript:addPackItem(true,'+packlist_total+');" id="adicionarIgual'+packlist_total+'" title="Click here to clone this item"><img border="0" alt="x" src="img/ico-incluir-conteudo.gif" /></a>';
    td2.innerHTML = '<input tabindex="1" readonly="readonly" type="text" id="popli_nome_'+packlist_total+'" name="popli_nome[]" value="Pallet '+packlist_total+'" size="20" maxlength="28" style="width:100%; margin:0; border:0;" class="input2" onfocus="this.className=\'input2_over\'" onblur="this.className=\'input2\'" />';
    td3.appendChild ( comboDim );
    td4.appendChild ( comboEspec );
    td5.appendChild ( comboSKU );
    td6.appendChild ( comboFT2 );
    td7.innerHTML = '<input tabindex="1" type="text" id="m2_'+packlist_total+'" id="m2_'+packlist_total+'" readonly="readonly" value="" size="12" maxlength="28" style="width:100%; margin:0; border:0; text-align: right;" class="input2" onkeypress="return formataCampo(event, this, \'dotnum\');" onkeyup="javascript:getTotal(\'ft2\');javascript:converte(\'m2ft\',this);" onfocus="this.className=\'input2_over\'" onblur="this.className=\'input2\'" />';

    // APENDO AS CÉLULAS NA LINHA
    tr.appendChild ( td1 );
    tr.appendChild ( td2 );
    tr.appendChild ( td3 );
    tr.appendChild ( td4 );
    tr.appendChild ( td5 );
    tr.appendChild ( td6 );
    tr.appendChild ( td7 );

    // APENDO A LINHA NA TABELA
    tabela.appendChild ( tr );

	if(clonar && clonar==true)
	{
		converte('ft2m', comboFT2);
	}

    //document.getElementById('teste').src = 'img/ico-erro.gif';
    document.getElementById('teste').id = '';
}

function abrePopupFoto ( foto, titulo )
{
    window.open ( 'foto.htm?'+foto, '', 'width=100, height=100, status=no' );
}

function toggleHistory ( )
{
    div  = document.getElementById('historico_conteudo');
    link = document.getElementById('link_toggle');

    if ( div.style.display != 'none' )
    {
        div.style.display = 'none';
        link.innerHTML = '[ Historic ]';
    }
    else
    {
        div.style.display = '';
        link.innerHTML = '[ Current ]';
    }
}

/* funções pra abrir janelas */

var window_update_historico;
var onthefly_window;

function popupHistory ( po_id )
{
    window_update_historico = window.open ( 'popup_adm_historico.php?'+po_id, 'history', 'width=610, height=210, top=100, left=100, status=no' );
    window_update_historico.focus();
}

function popupOnTheFly ( tipo )
{
    if ( tipo == 'status' )
        php = 'popup_new_status.php';
    else if ( tipo == 'dimensions' )
        php = 'popup_new_dimensions.php';
    else if ( tipo == 'species' )
        php = 'popup_new_species.php';
    else if ( tipo == 'sku' )
        php = 'popup_new_sku.php';
    else if ( tipo == 'ft2' )
        php = 'popup_new_ft2.php';
    else return false;

    onthefly_window = window.open ( php, 'novostatus', 'width=500, height=80, top=200, left=200, status=no' );
    onthefly_window.focus();
}

function fechaPopups( )
{
    if ( window_update_historico )
    {
        if ( window_update_historico.onthefly_window )
            window_update_historico.onthefly_window.close();
        window_update_historico.close();
    }
    else if ( onthefly_window )
        onthefly_window.close();
}

function updateHistorico ( novostatus )
{
    // CRIO A LINHAS DO NOVO STATUS
    old_tbody = opener.document.getElementById( 'tbody_status' );
    tr = old_tbody.insertRow( 0 );

    // CRIO AS CÉLULAS
    td0 = tr.insertCell ( 0 );
    td1 = tr.insertCell ( -1 );
    td2 = tr.insertCell ( -1 );
    td3 = tr.insertCell ( -1 );
    td4 = tr.insertCell ( -1 );

    // SETO OS ATRIBUTOS
    first_line = opener.document.getElementById( 'linha_status_atual' );
    if ( first_line )
        var classLinha = first_line.className == 'tab_linha1' ? 'tab_linha2' : 'tab_linha1';
    else
        var classLinha = 'tab_linha1';


    tr.setAttribute( 'class', classLinha );
    tr.className = classLinha;

    td0.align = 'center';

    td1.align = 'center';
    td1.vAlign='top'
    td1.style.padding = "3px";
    td1.setAttribute( 'class', 'hora' );
    td1.className = 'hora';

    td2.vAlign='top'
    td2.style.padding = "3px";

    td3.vAlign='top'
    td3.style.padding = "3px";

    td4.vAlign='top'
    td4.style.padding = "3px";


    // ESTE SEPARADOR SERVE PARA QUEBRAR A STRING QUE VEM DO SERVIDOR
    separador = '(((x)))';
    novostatus = novostatus.split ( separador );

    // INSERINDO O CONTEÚDO...
    td0.innerHTML = '<a href="javascript:void(0);" onclick="javascript:limpaStatus(this,'+novostatus[6]+');" title="Click here to delete this status from the order historic"><img border="0" alt="x" src="img/ico-erro.gif" /></a>';
    td1.innerHTML = novostatus[1];
    td2.innerHTML = novostatus[3];
    td3.innerHTML = novostatus[0];
    td4.innerHTML = novostatus[5];

    // TROCO AS IDs
    if ( first_line ) first_line.id = '';
    tr.id = 'linha_status_atual';

    // SETA O FOCO E FECHA A JANELA
    opener.focus();
    window.close();
}

function ontheflyStatus ( combobox, id )
{
    // SUBSTITUO OS "<" E ">" PRA MONTAR A COMBOBOX
    combobox = combobox.replace ( /\(\(\(LT\)\)\)/g, '<' );
    combobox = combobox.replace ( /\(\(\(GT\)\)\)/g, '>' );

    opener.document.getElementById( 'div_status' ).innerHTML = combobox;
    opener.document.getElementById( 'posta_id' ).value = id;
    opener.focus();
    window.close();
}

function ontheflyPackingList ( nome, id, tipo )
{

    // PEGO OS DADOS DOS SELECTS DE ACORDO COM O TIPO PASSADO
    if ( tipo == 'dimensions' )
    {
        var nomeCombo = 'popli_dimensoes_';
        var inputItens = opener.document.getElementById('strDim');
        var inputItens_id = opener.document.getElementById('strDim_id');
    }
    else if ( tipo == 'species' )
    {
        var nomeCombo = 'popli_especies_';
        var inputItens = opener.document.getElementById('strEspec');
        var inputItens_id = opener.document.getElementById('strEspec_id');
    }
    else if ( tipo == 'sku' )
    {
        var nomeCombo = 'sku_';
        var inputItens = opener.document.getElementById('strSKU');
        var inputItens_id = opener.document.getElementById('strSKU_id');
    }
    else if ( tipo == 'ft2' )
    {
        var nomeCombo = 'ft2_';
        var inputItens = opener.document.getElementById('strFT2');
        var inputItens_id = opener.document.getElementById('strFT2_id');
    }
    else
    {
        alert ( 'Tipo inválido' );
        return false;
    }
    var arrItens = inputItens.value.split('{{brk}}');
    var arrItens_id = inputItens_id.value.split('{{brk}}');


    for ( j = 1; j <= opener.packlist_total; j++ )
    {
        combo           = opener.document.getElementById ( nomeCombo+j );
        option          = combo.options[combo.options.length++];
        option.value    = id;
        option.text     = nome;
    }

    if ( inputItens.value.length > 0 )
        inputItens.value += '{{brk}}';
    inputItens.value += nome;

    if ( inputItens_id.value.length > 0 )
        inputItens_id.value += '{{brk}}';
    inputItens_id.value += id;

    opener.focus();
    window.close();
}

function get_lastchild ( n )
{
    var x=n.lastChild;
    while (x.nodeType!=1)
    {
        x=x.previousSibling;
    }
    return x;
}

function validaForm ( tipo )
{
    if ( tipo == 1 )
    {
        msg = document.getElementById( 'mensagem' );

        if ( ! msg.value )
        {
            alert ( 'Fill up the MESSAGE field' );
            msg.focus();
            return false;
        }
        else
        {
            document.forms[0].submit();
            return true;
        }
    }
}

function validaFormNewHistory ()
{
    form = document.forms[0];
    if ( ! form.popos_local.value )
    {
        alert ( 'Fill up the PLACE field' );
        form.popos_local.focus();
        return false;
    }
}

/* Mascaras */
formataCampo = function ( tecla, obj, tipo ) {
  var key;
  var keyNum;
  if ( navigator.userAgent.indexOf( "MSIE" ) > 0 ) key = tecla.keyCode;
  if ( navigator.userAgent.indexOf( "Gecko" ) > 0 ) key = tecla.which;
  if ( ( key == 8 ) || ( key == 0 ) ) return true;
  keyNum = key;
  key = String.fromCharCode(key);

  if ( tipo == 'numero' || tipo == 'dotnum' )
    var erNum = /[0-9\,\.]/i;
  else
    var erNum = /[0-9]/i;

  if (erNum.test(key)) {
    /**** NÚMERO ****/
    if (tipo == 'numero') {
      if ( key == "," || key == "." )
      {
        if ( strpos ( obj.value, ',') !== false )
          return false;
        else
        {
          obj.value += ",";
          return false;
        }
      }
      return true; }

    /**** NÚMERO COM SEPARADOR ESTILO PONTO "." ****/
    if (tipo == 'dotnum') {
      if ( key == "." || key == "," )
      {
        if ( strpos ( obj.value, '.') !== false )
          return false;
        else
        {
          obj.value += ".";
          return false;
        }
      }
      return true; }

    /**** CEP ****/
    if (tipo == 'cep') {
      if (obj.value.length == 4) { obj.value = obj.value + key + '-'; return false; }
      else return true;

    /**** CPF ****/
    } else if (tipo == 'cpf') {
      if ((obj.value.length == 2) || (obj.value.length == 6)) { obj.value = obj.value + key + '.'; return false; }
      else if (obj.value.length == 10) { obj.value = obj.value + key + '-'; return false; }
      else if (obj.value.length > 13) { return false }
      else return true;

    /**** Fone ****/
    } else if (tipo == 'fone') {
      if ((obj.value.length == 0)) { obj.value = '(' + key ; return false; }
      else if (obj.value.length == 2) { obj.value = obj.value + key + ') '; return false; }
      else if (obj.value.length == 8) { obj.value = obj.value + key + '-'; return false; }
      else return true;

    /**** CNPJ ****/
    } else if (tipo == 'cnpj') {
      if ((obj.value.length == 1) || (obj.value.length == 5)) { obj.value = obj.value + key + '.'; return false; }
      else if (obj.value.length == 9) { obj.value = obj.value + key + '/'; return false; }
      else if (obj.value.length == 14) { obj.value = obj.value + key + '-'; return false; }
      else return true;

    /**** MOEDA ****/
    } else if (tipo == 'moeda') {

        objTextBox = obj ;
        SeparadorMilesimo = '' ;
        SeparadorDecimal = '.' ;
        e = tecla ;
            //-----------------------------------------------------
            //Funcao: MascaraMoeda
            //Autor: Gabriel Fróes
            //-----------------------------------------------------
            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) 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;
            for(i = 0; i < len; i++)
                if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
            aux = '';
            for(; i < len; i++)
                if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
            aux += key;
            len = aux.length;
            if (len == 0) objTextBox.value = '';
            if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
            if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
            if (len > 2) {
                aux2 = '';
                for (j = 0, i = len - 3; i >= 0; i--) {
                    if (j == 3) {
                        aux2 += SeparadorMilesimo;
                        j = 0;
                    }
                    aux2 += aux.charAt(i);
                    j++;
                }
                objTextBox.value = '';
                len2 = aux2.length;
                for (i = len2 - 1; i >= 0; i--)
                objTextBox.value += aux2.charAt(i);
                objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
            }
            return false;

    /**** DATA ****/
    } else if (tipo == 'data') {
      if ((obj.value.length == 1) || (obj.value.length == 4)) { obj.value = obj.value + key + '/'; return false; }
      else return true;

    /**** HORA ****/
    } else if (tipo == 'hora') {
      if (obj.value.length == 1) { obj.value = obj.value + key + ':'; return false; }
      else return true;

    } else { return false; }
  } else if ( keyNum == 13 ) {
    return true;
  }
  else return false;
}

/*
    LOADXML
    INSTANCIA O OBJETO XML E ENVIA AS VARIÁVEIS
*/
function loadXML ( url, valor )
{
    req = null;

    // PROCURA POR UM OBJETO NATIVO (MOZILLA/SAFARI)
    if ( window.XMLHttpRequest )
    {
        req = new XMLHttpRequest();
        req.open("GET", url+escape(valor), true);
        req.send(null);
    }
    // PROCURA POR UMA VERSAO ACTIVEX (IE)
    else if ( window.ActiveXObject )
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if ( req )
        {
            req.open("GET", url+escape(valor), true);
            req.send();
        }
    }
}

function loadXMLPOST ( url, param )
{
    req = null;
    // PROCURA POR UM OBJETO NATIVO (MOZILLA/SAFARI)
    if ( window.XMLHttpRequest )
        req = new XMLHttpRequest();
    // PROCURA POR UMA VERSAO ACTIVEX (IE)
    else if ( window.ActiveXObject )
        req = new ActiveXObject("Microsoft.XMLHTTP");
    else
        alert( 'Seu browser não suporta AJAX! Está página não funcionará corretamente.' )

    req.open('POST', url, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", param.length);
    req.setRequestHeader("Connection", "close");
    req.send(param);
}
function strpos( haystack, needle, offset){
    // http://kevin.vanzonneveld.net
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14

    var i = haystack.indexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}

function htmlencode (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};

function htmldecode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}