num_KeyPressed   = null;  //Tecla pressionada no campo
obj_CampoAtual   = null;  //Objeto relativo ao campo atual (ativo)
str_ValorLookped = null;  //Valor recolhido via lookup
boo_TrappingKeys = false; //Informa se o script está ou não manipulando teclas
num_LinhaAtual   = 0;     //Linha atual do lookup
num_tempX        = 0;     //Posição horizontal temporária
num_tempY        = 0;     //Posição vertical temporária
num_PosActFieldX = 0;     //Posição horizontal do campo atual
num_PosActFieldY = 0;     //Posição vertical do campo atual
num_PressEnter   = false;


//Manipula o evento OnKeyUp
function OnKeyDown( obj_evento )
{
    //Bom, as coisas mudam um pouco com o IE,
    //então prevemos esse problema aqui...
    if ( !obj_evento )
    {
       obj_evento = window.event;
    }

    //Código correspondente a tecla pressionada
    num_KeyPressed = obj_evento.keyCode;

    //Se o campo estiver vazio ou tiver menos que 3 caracteres o lookup não
    //aparece na tela. Isso evita erros...
    if ( ( obj_CampoAtual != null ) && ( obj_CampoAtual.value.length < 3 ) )
    {
        FechaLookup();
        return;
    }

    //Verifica se tecla "para cima" foi pressionada
    if ( num_KeyPressed == 38 )
    {
        if ( document.getElementById( "lkp_td" + ( num_LinhaAtual - 1 ) ) != undefined )
        {
            boo_TrappingKeys = true;
            num_LinhaAtual--;

            var obj_sel = document.getElementById( "lkp_td" + num_LinhaAtual );

            if ( document.getElementById( "lkp_td" + ( num_LinhaAtual + 1 ) ) != undefined )
            {
                var obj_descel = document.getElementById( "lkp_td" + ( num_LinhaAtual + 1 ) );
                LookupMouseOut( obj_descel );
            }

            LookupMouseOver( obj_sel );
            obj_CampoAtual.value = trim( obj_sel.innerHTML );
        }
    }
    //Verifica se tecla "para baixo" foi pressionada
    else if ( num_KeyPressed == 40 )
    {
        if ( document.getElementById( "lkp_td" +  ( num_LinhaAtual + 1 ) ) != undefined )
        {
            boo_TrappingKeys = true;
            num_LinhaAtual++;
            var obj_sel = document.getElementById( "lkp_td" + num_LinhaAtual );

            if ( document.getElementById( "lkp_td" + ( num_LinhaAtual - 1 ) ) != undefined )
            {
                var obj_descel = document.getElementById( "lkp_td" + ( num_LinhaAtual - 1 ) );
                LookupMouseOut( obj_descel );
            }

            LookupMouseOver( obj_sel );
            obj_CampoAtual.value = trim( obj_sel.innerHTML );
        }
    }
    //Verifica se a tecla <ENTER> foi pressionada
    else if ( num_KeyPressed == 13 )
    {
        num_PressEnter = true;
        FechaLookup();
    }
    //Verifica se a tecla <TAB> foi pressionada
    else if ( num_KeyPressed == 9 )
    {
        FechaLookup();
    }
}


function Lookup( obj_campo, fnc_onkeyup )
{
    var str_entrada = obj_campo.value;

    if ( ( fnc_onkeyup != undefined ) && ( fnc_onkeyup != null ) )
    {
        fnc_onkeyup( obj_campo );
    }

    if ( boo_TrappingKeys )
    {
        return;
    }

    if ( obj_campo.onkeydown == null )
    {
        obj_campo.onkeydown = OnKeyDown;
    }

    if ( str_entrada.length > 3 )
    {
        var str_URL = window.location.href;

        //Se a tecla tab for pressionada, fecha a caixa
        if (   ( window.event != undefined )
            && ( window.event.keyCode == 9 ) )
        {
            FechaLookup();
            return;
        }

        //Se a tecla <ENTER> for pressionada, fecha a caixa
        if (   ( window.event != undefined )
            && ( window.event.keyCode == 13 )
            || ( num_PressEnter ) )
        {
            num_PressEnter = false;
            FechaLookup();
            return;
        }

        if ( ( str_URL.indexOf( "&" ) == -1 ) && ( str_URL.indexOf( "?" ) == -1 ) )
        {
            str_URL += "?saida_simples=true&ajax_valor=" + str_entrada + "&ajax_campo=" + obj_campo.id;
        }
        else
        {
            str_URL += "&saida_simples=true&ajax_valor=" + str_entrada + "&ajax_campo=" + obj_campo.id;
        }

        if ( obj_CampoAtual != obj_campo )
        {
            obj_CampoAtual = obj_campo;
        }

        xmlHttp = GetXmlHttpObject( stateChanged ) ;
        xmlHttp.open( "GET", str_URL , true );
        xmlHttp.send( null );
    }
    else
    {
        FechaLookup();
    }
}


function stateChanged()
{
    if ( ( xmlHttp.readyState == 4 ) || ( xmlHttp.readyState == "complete" ) )
    {
        num_PosActFieldX = getElementPosition( obj_CampoAtual.id ).left;
        num_PosActFieldY = getElementPosition( obj_CampoAtual.id ).top;

        if ( xmlHttp.responseText.length == 0 )
        {
            FechaLookup();
            return;
        }

        with ( document.getElementById( "conteudo" ) )
        {
            style.width  = 320;
            style.height = 115;
            style.top   = num_PosActFieldY + 20;
            style.left  = num_PosActFieldX;

            style.visibility = "visible";
            innerHTML = xmlHttp.responseText;

            MostraDiv( true );
        }
    }
}


function GetXmlHttpObject( fnc_handler )
{
    var obj_XmlHttp = null;

    if ( navigator.userAgent.indexOf("Opera") >= 0 )
    {
        alert( "This example doesn't work in Opera" );
        return;
    }

    if ( navigator.userAgent.indexOf( "MSIE" ) >= 0 )
    {
        var str_Nome = "Msxml2.XMLHTTP";

        if ( navigator.appVersion.indexOf( "MSIE 5.5" ) >= 0 )
        {
            str_Nome = "Microsoft.XMLHTTP";
        }

        try
        {
            obj_XmlHttp = new ActiveXObject( str_Nome );
            obj_XmlHttp.onreadystatechange = fnc_handler;

            return ( obj_XmlHttp );
        }
        catch( e )
        {
            alert( "Error. Scripting for ActiveX might be disabled" );
            return;
        }
    }

    if ( navigator.userAgent.indexOf( "Mozilla" ) >= 0 )
    {
        obj_XmlHttp = new XMLHttpRequest();

        obj_XmlHttp.onload  = fnc_handler;
        obj_XmlHttp.onerror = fnc_handler;

        return ( obj_XmlHttp );
    }
}


function FechaLookup()
{
    num_LinhaAtual   = 0;
    boo_TrappingKeys = false;

    if ( str_ValorLookped != null )
    {
        obj_CampoAtual.value = str_ValorLookped;
        str_ValorLookped     = null;
    }

    with ( document.getElementById( "conteudo" ) )
    {
        style.visibility = "hidden";
        style.top    = 0;
        style.left   = 0;
        style.width  = 0;
        style.height = 0;

        MostraDiv( false );
    }
}


//Função que atribui uma cor na linha des-selecionada na tabela
function LookupMouseOver( obj_td )
{
    obj_td.bgColor = '#F0F0FF';
}


//Função que atribui uma cor na linha selecionada na tabela
function LookupMouseOut( obj_td )
{
    obj_td.bgColor = '#FFFFFF';
}


//Quando o usuário clicar em uma linha do lookup, ela será atribuida ao
//campo do formulário
function LookupMouseClick( obj_td )
{
    str_ValorLookped = trim( obj_td.innerHTML );

    FechaLookup();
}


function TrappMouse()
{
    // Detect if the browser is IE or not.
    // If it is not IE, we assume that the browser is NS.
    var IE = document.all ? true : false;

    // If NS -- that is, !IE -- then set up for mouse capture
    if ( !IE )
    {
        document.captureEvents( Event.MOUSEMOVE );
    }

    // Set-up to use getMouseXY function onMouseMove
    document.onmousemove = getMouseXY;
    document.onclick     = getClick;
}


function getClick()
{
    if (   ( num_tempX <= num_PosActFieldX )
        || ( num_tempY <= num_PosActFieldY )
        || ( num_tempX >= ( num_PosActFieldX + 320 ) )
        || ( num_tempY >= ( num_PosActFieldY + 115 ) ) )
    {
        FechaLookup();
    }
}


function getMouseXY( obj_evento )
{
    var obj_IE = document.all ? true : false;

    // grab the x-y pos.s if browser is IE
    if ( obj_IE )
    {
        num_tempX = event.clientX + document.body.scrollLeft;
        num_tempY = event.clientY + document.body.scrollTop;
    }
    // grab the x-y pos.s if browser is NS
    else
    {
        num_tempX = obj_evento.pageX;
        num_tempY = obj_evento.pageY;
    }

    // catch possible negative values in NS4
    if ( num_tempX < 0 )
    {
        num_tempX = 0;
    }

    if ( num_tempY < 0 )
    {
        num_tempY = 0;
    }
}

//Gambiarra para o div ficar em cima de qualquer componente
function MostraDiv( boo_mostrar )
{
    var obj_Div = document.getElementById('conteudo');
    var obj_Iframe = document.getElementById('DivMestra');

    if ( boo_mostrar )
    {
        obj_Div.style.display    = "block";
        obj_Iframe.style.width   = obj_Div.offsetWidth;
        obj_Iframe.style.height  = obj_Div.offsetHeight;
        obj_Iframe.style.top     = obj_Div.style.top;
        obj_Iframe.style.left    = obj_Div.style.left;
        obj_Iframe.style.zIndex  = obj_Div.style.zIndex - 1;
        obj_Iframe.style.display = "block";
    }
    else
    {
        obj_Div.style.display    = "none";
        obj_Iframe.style.display = "none";
    }
}


function trim( str_texto )
{
    while ( str_texto.substring( 0, 1 ) == ' ' )
    {
        str_texto = str_texto.substring( 1, str_texto.length );
    }

    while ( str_texto.substring( str_texto.length - 1, str_texto.length ) == ' ' )
    {
        str_texto = str_texto.substring( 0, str_texto.length - 1 );
    }

    return str_texto;
}


function getElementPosition( str_id )
{
    var obj_offsetTrail = document.getElementById( str_id );
    var num_offsetLeft  = 0;
    var num_offsetTop   = 0;

    while ( obj_offsetTrail )
    {
        num_offsetLeft += obj_offsetTrail.offsetLeft;
        num_offsetTop  += obj_offsetTrail.offsetTop;

        obj_offsetTrail = obj_offsetTrail.offsetParent;
    }

    if (   ( navigator.userAgent.indexOf( "Mac" ) != -1 )
        && ( typeof document.body.leftMargin != "undefined" ) )
    {
        num_offsetLeft += document.body.leftMargin;
        num_offsetTop  += document.body.topMargin;
    }

    return { left:num_offsetLeft, top:num_offsetTop };
}

TrappMouse();
