/**
* Incializa o uso do XMLHttp
*
*/
function ajaxInit()
{
    //instancia um novo xmlhttprequest
    //baseado na getXMLHttpObj que possui muitas cópias na net e eu nao sei quem é o autor original
    if ( typeof( XMLHttpRequest ) != 'undefined' )
    {
        return new XMLHttpRequest();
    }

    var arr_Tipos = ['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];

    for( var i = 0; i < arr_Tipos.length; i++ )
    {
        try
        {
            return new ActiveXObject( arr_Tipos[i] );
        }
        catch( e ){}
    }
    return false;
}
/*
* Retorna o erro HTTP traduzido
*
*/
function httpStatus( int_Status )
{
    //retorna o texto do erro http
    switch( int_Status )
    {
        case 400:
            return "400: Solicita&ccedil;&atilde;o incompreensível";
        break;

        case 403:
        case 404:
            return "404: N&atilde;o foi encontrada a URL solicitada";
        break;

        case 405:
            return "405: O servidor n&atilde;o suporta o m&eacute;todo solicitado";
        break;

        case 500:
            return "500: Erro desconhecido de natureza do servidor";
        break;
        
        case 503:
            return "503: Capacidade m&aacute;xima do servidor alcançada";
        break;

        default:
            return "Erro " + int_Status + ". Mais informa&ccedil;&otilde;es em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html";
        break;
    }
}

/**
* Evita a cache
*
*/
function antiCacheRand( str_Url )
{
    var obj_Date = new Date();

    if( str_Url.indexOf( "?" ) >= 0 )
    {
        // já tem parametros
        return str_Url + "&" + encodeURI( Math.random() + "_" + obj_Date.getTime() );
    }
    else
    {
        return str_Url + "?" + encodeURI( Math.random() + "_" + obj_Date.getTime() );
    }
}

/**
* select_innerHTML - altera o innerHTML de um select independente se é FF ou IE
* Corrige o problema de não ser possível usar o innerHTML no IE corretamente
* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Use a vontade mas coloque meu nome nos créditos. Dúvidas, me mande um email.
* Versão: 1.0 - 06/04/2006
* Autor: Micox - Náiron José C. Guimarães - micoxjcg@yahoo.com.br, R. Cabral - reinaldomcabral@gmail.com
* Parametros:
* obj_Objeto(tipo object): o select a ser alterado
* str_innerHTML(tipo string): o novo valor do innerHTML
*/
function selectInnerHTML( obj_Objeto, str_innerHTML )
{
    obj_Objeto.innerHTML = "";
    var obj_SelTemp      = document.createElement( "cabralSelect" );
    var obj_Opt;

    obj_SelTemp.id = "cabralSelect1";

    document.body.appendChild( obj_SelTemp )

    obj_SelTemp               = document.getElementById( "cabralSelect1" );
    obj_SelTemp.style.display = "none";

    if( str_innerHTML.toLowerCase().indexOf( "<option" ) < 0 )
    {
        //se não é option eu converto
        str_innerHTML = "<option>" + str_innerHTML + "</option>";
    }

    str_innerHTML = str_innerHTML.replace( /<option/g, "<span" ).replace(/<\/option/g,"</span");
    obj_SelTemp.innerHTML = str_innerHTML;

    for( var int_I = 0; int_I < obj_SelTemp.childNodes.length; int_I++ )
    {
        if( obj_SelTemp.childNodes[int_I].tagName )
        {
            obj_Opt = document.createElement( "OPTION" );
            for( var int_J = 0; int_J < obj_SelTemp.childNodes[int_I].attributes.length; int_J++ )
            {
                obj_Opt.setAttributeNode( obj_SelTemp.childNodes[int_I].attributes[int_J].cloneNode( true ) );
            }
            obj_Opt.value = obj_SelTemp.childNodes[int_I].getAttribute("value");
            obj_Opt.text  = obj_SelTemp.childNodes[int_I].innerHTML;

            if( document.all )
            {
                //IE
                obj_Objeto.add( obj_Opt );
            }
            else
            {
                obj_Objeto.appendChild( obj_Opt );
            }
        }
    }

    document.body.removeChild( obj_SelTemp );
    obj_SelTemp = null;
}

/**
* urlEncode version 1.0
*
*/
function urlEncode( str_Valor )
{
    var var_HexChars = "0123456789ABCDEF";
    var var_NoEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var str_Code, var_Hex1, var_Hex2, str_Encode = "";

    for( var int_Cont = 0; int_Cont < str_Valor.length; int_Cont++ )
    {
        if ( var_NoEncode.test( str_Valor.charAt( int_Cont ) ) )
        {
            str_Encode += str_Valor.charAt( int_Cont );
        }
        else
        {
            str_Code    = str.charCodeAt( int_Cont );
            var_Hex1    = var_HexChars.charAt( Math.floor( str_Code / 16 ) );
            var_Hex2    = var_HexChars.charAt( str_Code % 16 );
            str_Encode += "%" + ( var_Hex1 + var_Hex2 );
        }
    }
    return str_Encode;
}

/**
* url_decode version 1.0
*
*/
function urlDecode( str_Valor )
{
    var str_Code, str_Decode = "";

    for ( var int_Cont = 0; int_Cont < str_Valor.length; int_Cont++ )
    {
        if ( str_Valor.charAt( int_Cont ) == "%" )
        {
            str_Code    = str_Valor.charAt( int_Cont + 1 ) + str_Valor.charAt( int_Cont + 2 );
            str_Decode += String.fromCharCode( parseInt( str_Code, 16 ) );
            int_Cont   += 2;
        }
        else
        {
            str_Decode += str_Valor.charAt( int_Cont );
        }
    }

    return str_Decode;
}

function decHex( int_Dec2 )
{
    var var_HexChars = "0123456789ABCDEF";

    var int_N1 = var_HexChars.charAt( Math.floor( int_Dec2 / 16 ) );
    var int_N2 = var_HexChars.charAt( int_Dec2 % 16 );

    return int_N1 + int_N2;
}

/**
* Verifica se houve algum erro
*
*/
function verificaErro( var_Valor )
{
    var str_Valor = unescape( escape( urlDecode( var_Valor ) ).replace( /\%0D\%0A/g,"" ) );
    var str_Erro  = str_Valor.substr( 0, 5 );

    if ( str_Erro.trim() == "Erro" )
    {
        alert( str_Valor.substr( 6 ) );
        window.parent.location.reload();
        return false;
    }
    else
    {
        return true;
    }
}

/**
* Coloca o retorno no objeto selecionado
*
*/
function put( str_Retorno, var_Valor, str_Frame )
{
    if ( verificaErro( var_Valor ) )
    {
        if ( typeof( str_Frame ) == 'undefined' )
        {
			var obj_Retorno = ( document.all ? document.all( str_Retorno ) : document.getElementById( str_Retorno ) );
        }
        else
        {
        	var obj_Retorno = ( document.all ? eval( str_Frame + ".document.all( '" + str_Retorno + "' )" ) : eval( str_Frame + ".document.getElementById( '" + str_Retorno + "' )" ) );
        }

        //coloca o valor na variavel/elemento de retorno
		if ( ( typeof( obj_Retorno ) ).toLowerCase() == "string" )
        {
            //se for o nome da string
            if ( var_Valor != "Falha no carregamento" )
            {
                eval( obj_Retorno + '= unescape( "' + escape( urlDecode( var_Valor ) ) + '" )' );
            }
        }
        else if( obj_Retorno.tagName.toLowerCase() == "input" )
        {
            var_Valor = escape( urlDecode( var_Valor ) ).replace( /\%0D\%0A/g,"" );
            obj_Retorno.value = unescape( var_Valor );
        }
        else if( obj_Retorno.tagName.toLowerCase() == "select" )
        {
            selectInnerHTML( obj_Retorno, urlDecode( var_Valor ) )
        }
        else if( obj_Retorno.tagName )
        {
            obj_Retorno.innerHTML = urlDecode( var_Valor );

            if ( obj_Retorno.style.visibility == 'hidden' )
            {
                obj_Retorno.style.visibility = 'visible';
            }
        }
    }
}

function _pegaDadosForm( obj_Form )
{
    var arr_Send      = new Array(); 
    var arr_Radio     = new Array();
    var arr_Elementos = obj_Form.elements; 
    var int_Tamanho   = arr_Radio.length;

    for( var int_I = 0; int_I < arr_Elementos.length; int_I++ ) 
    { 
        var obj_Elementos = arr_Elementos[int_I]; 
        
        if( !obj_Elementos.name ) 
        {
            continue; 
        }
        
        var str_NVal = ""; 
        
        for( var int_X = 0; int_X < obj_Elementos.value.length; int_X++ ) 
        { 
            str_CodeA  = obj_Elementos.value.charCodeAt( int_X ); 
            str_CodeA  = decHex( str_CodeA ); 
            str_NVal  += "%" + str_CodeA; 
        } 
        
        var str_Tipo = obj_Elementos.type.toLowerCase(); 

        if( str_Tipo != "checkbox" && str_Tipo != "radio" ) 
        { 
            arr_Send[arr_Send.length] = obj_Elementos.name + "=" + str_NVal; 
        } 
        else 
        { 
            if ( str_Tipo == "checkbox" )
            {
                arr_Send[arr_Send.length] = ( obj_Elementos.checked ? obj_Elementos.name + "=" + str_NVal : obj_Elementos.name + "=" ); 
            }
            else if ( str_Tipo == "radio" )
            {
                if ( arr_Radio.length == 0 )
                {
                    arr_Radio[arr_Radio.length] = ( obj_Elementos.checked ? obj_Elementos.name + "=" + str_NVal : obj_Elementos.name + "=" );
                }
                else
                {
                    var arr_Qg = arr_Radio[( arr_Radio.length - 1 )].split( "=" );
                    if ( arr_Qg[0] == obj_Elementos.name )
                    {
                        if ( arr_Radio[( arr_Radio.length - 1 )] == obj_Elementos.name + "=" )
                        {
                            if ( obj_Elementos.checked )
                            {
                                arr_Radio[( arr_Radio.length - 1 )] = obj_Elementos.name + "=" + str_NVal;
                            }
                        }
                    }
                    else
                    {
                        arr_Radio[arr_Radio.length] = ( obj_Elementos.checked ? obj_Elementos.name + "=" + str_NVal : obj_Elementos.name + "=" );
                    }
                }
            }
        } 
    }
    return arr_Send.join( "&" ) + "&" + arr_Radio.join( "&" ); 
}

function ajaxSendForm( obj_Form, str_Objeto, boo_Imagem, str_ObjetoMensagem, str_Mensagem, str_Frame )
{
    var str_Acao   = obj_Form.action;
    var str_Metodo = obj_Form.method.toLowerCase();
    if( !str_Acao )
    {
        alert( "Erro: o Valor action do formulario nao foi definido" );
    }

    var str_Send = _pegaDadosForm( obj_Form );
    
    put( str_Objeto, '', str_Frame  );

    if ( !boo_Imagem )
    {
        put( str_ObjetoMensagem, str_Mensagem, str_Frame );
    }
    else
    {
        put( str_ObjetoMensagem, "<div align='center'><img src='/lib/classes/formulario/templates/img/carregando.gif' border='0'></div>", str_Frame );
    }

    
    var obj_Ajax = ajaxInit();

    if( obj_Ajax )
    {
        if( str_Metodo == "post" )
        {
            obj_Ajax.open( "POST", antiCacheRand( str_Acao ), true );
            obj_Ajax.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1" );
        }
        else
        {
            obj_Ajax.open( "GET", antiCacheRand( str_Acao + "?" + str_Send ), true );
        }

        obj_Ajax.onreadystatechange = function()
        {
            //execute aqui as acoes
            if ( obj_Ajax.readyState == 4 )
            {
                if ( obj_Ajax.status == 200 )
                {
                    if ( urlDecode( obj_Ajax.responseText ).indexOf( "¬" ) > 0 )
                    {
                        var arr_ValoresRetorno = urlDecode( obj_Ajax.responseText ).split( "¬" );
                        if ( arr_ValoresRetorno[0] == "R"  ) {
                            window.parent.location.href = arr_ValoresRetorno[1];
                        }
                        else if ( arr_ValoresRetorno[0] == "M"  ) {
                            alert( arr_ValoresRetorno[1] );
                            window.parent.location.href = arr_ValoresRetorno[2];
                        }
                        else if ( arr_ValoresRetorno[0] == "A"  ) {
                            alert( arr_ValoresRetorno[1] );
                            put( str_Objeto, arr_ValoresRetorno[2], str_Frame );
                        }
                    }
                    else
                    {
                        put( str_Objeto, obj_Ajax.responseText, str_Frame );
                    }
//                    put( str_Objeto, obj_Ajax.responseText, str_Frame );
                    if ( str_Objeto != str_ObjetoMensagem )
                    {
                        put( str_ObjetoMensagem, "", str_Frame );
                    }
                }
                else
                {
                    put( str_ObjetoMensagem, "Falha no carregamento. " + httpStatus( obj_Ajax.status ) );
                }
            }
        }

        if( str_Metodo == "post" )
        {
            obj_Ajax.send( str_Send );
        }
        else
        {
            obj_Ajax.send( null );
        }
    }
}

/**
* Envia os dados via metodo GET
*
*
*/
function ajaxSend( str_Url, var_ObjetoRetorno, str_ObjetoMensagem, str_Mensagem, str_Frame, boo_Varios )
{
    var obj_Ajax = ajaxInit();

    if( obj_Ajax )
    {
        //Abre a conexão
        obj_Ajax.open( 'GET', antiCacheRand( str_Url ), true );
//        janelaMensagem( true, document, "layCarregando", 760, 50, 100 );
        put( str_ObjetoMensagem, str_Mensagem );

        //Função para tratamento do retorno
        obj_Ajax.onreadystatechange = function()
        {
            // se o status for 4 já foi finalizada a leitura
            if ( obj_Ajax.readyState == 4 )
            {
                // se o status for 200 está ok
                if ( obj_Ajax.status == 200 )
                {
                    // se o retorno for direto para somente um campo
                    if ( !boo_Varios )
                    {
                        
                        if ( urlDecode( obj_Ajax.responseText ).indexOf( "¬" ) > 0 )
                        {
                            var arr_ValoresRetorno = urlDecode( obj_Ajax.responseText ).split( "¬" );
                            alert( arr_ValoresRetorno[1] );
                            window.parent.top.frames['main'].location.href = arr_ValoresRetorno[2];
                        }
                        else
                        {
//                            alert(var_ObjetoRetorno);
                            put( var_ObjetoRetorno, obj_Ajax.responseText );
                        }
                    }
                    else // caso contrário ele separa os campos para serem alimentados
                    {
                        // pega o retorno e converte do padrão UTF-8 para ISO8859-1
                        var arr_ValoresRetorno = urlDecode( obj_Ajax.responseText ).split( "¬" );

                        // separa os campos de retorno
                        var arr_CamposRetorno  = var_ObjetoRetorno.split( "," );

                        if ( arr_ValoresRetorno[0].trim() == '' )
                        {
                            alert( 'Registro não encontrado!' );
                        }
                        else
                        {
                            // atribui os valores dos campos
                            for ( var int_Cont = 0; int_Cont < arr_CamposRetorno.length; int_Cont++ )
                            {
                                var arr_Campo = arr_CamposRetorno[int_Cont].split( "=>" );
    
                                put( arr_Campo[1], arr_ValoresRetorno[int_Cont] );
                            }
                        }                            
                    }
                }
                else
                {
                    put( str_ObjetoMensagem, "Falha no carregamento. " + httpStatus( obj_Ajax.status ) );
                }
//                janelaMensagem( false, document, "layCarregando", 760, 50, 100 );
            }
        }
        //Executa
        obj_Ajax.send( null );
    }
}