// JavaScript Document
function iniAjax() //Inicializa a variavel para utilização do Ajax
{
    var cajx;
    if(window.XMLHttpRequest){
        cajx = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        try{
            cajx = new ActiveXObject("Msxml2.XMLHTTP.4.0");
        }catch(e){
            try{
                cajx = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }
            catch(e){
                try{
                    cajx = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e){
                    try{
                        cajx = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch(e){
                        cajx = false;
                    }
                }
            }
        }
     }
     return cajx;
}

function popula_sel(retorno, tagname, selectname){
    var agt = navigator.userAgent.toLowerCase();
    var tags = retorno.getElementsByTagName(tagname);
    var select = document.getElementsByName(selectname)[0];
    select.options.length = 0;
    for(a = 0 ; a < tags.length ; a++){
        value = tags[a].childNodes[0].childNodes[0].nodeValue;
        texto = tags[a].childNodes[1].childNodes[0].nodeValue;
        op = new Option(texto,value);
        select.options[a] = op;
	}
}

function loading(element, tipo){
    if(document.getElementById('msg')){ destroyElement('msg');  }
    if(tipo == 'xml'){
        var ele = document.getElementsByName(element)[0];
        ele.options[0].text = "CARREGANDO...";
    }else{
        try { ShadowIn(); }catch(err){ }
        if(!document.getElementById('loading')){
            var objCorpo = document.getElementsByTagName('body').item(0);
            var objLoad = document.createElement('div');
            objLoad.setAttribute('id','loading');
            objLoad.style.top = '0px';
            objLoad.style.left = '0px';
            objLoad.style.position = 'fixed';
            objLoad.style.border = '2px solid #225699';
            objLoad.style.backgroundColor = '#FFFFFF';
            objLoad.innerHTML  = '<img src="/imagens/loader.gif" /><br/>Aguarde...';
            objLoad.style.textAlign = 'center';
            objLoad.style.fontSize = '14px';
            objLoad.style.width = '110%';
            objLoad.style.height = '80px';
            objLoad.style.paddingTop = '5px';
            objLoad.style.zIndex = 20;
            objCorpo.appendChild(objLoad);
            centerElement('loading');
            fadeIn('loading', 0.5);
        }
    }
}

function refreshAjax(url, elemento){
    alert('teste');
    window.setTimeOut(rajax(url, '', elemento, 'texto', ''), 2500);
}

function onLoad(){
    ShadowIn();
    var objCorpo = document.getElementsByTagName("body").item(0);
    var objLoad = document.createElement("div");
    style = "position:fixed;padding:5px;text-align:center;z-index:20;";
    style+= "background:#fff;width:110%;min-height:30px;font-weight:bold;";
    objLoad.setAttribute("id", "load");
    objLoad.setAttribute("style", style);
    objLoad.innerHTML = "<img src=\"../../imagens/loader.gif\" /><br/>AGUARDE";
    objCorpo.appendChild(objLoad);
    centerElement("load");
    $("#load").fadeIn("slow");
}

function unLoad(vCode){
    $("#load").fadeOut("slow", function(){
        $("#load").remove();
        vCode();
    });
}

function mAjax(url, data, type, method, callBack){
    url += (data != null) ? '?'+data : '';
    var ajax  = iniAjax();
    if(ajax){
        ajax.open(method, url, true);
        ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");
        ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        ajax.setRequestHeader("Pragma", "no-cache");
        ajax.onreadystatechange = function (){ //Verificações
            if((ajax.readyState == 4) && (ajax.status == 200)){
                switch(type){
                    case 'xml' : callBack(ajax.responseXML);  break;
                    case 'text': callBack(ajax.responseText); break;
                }
            }
        }
    }
    if(method.toLowerCase() == 'get'){ data = null; }
    ajax.send(data);
}


function sAjax(url, type, callBack){
    var bool  = true;
    var ajax  = iniAjax();
    if(ajax){
        ajax.open('GET', url, true);
        ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");
        ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        ajax.setRequestHeader("Pragma", "no-cache");
        ajax.onreadystatechange = function (){ //Verificações
            if((ajax.readyState == 4) && (ajax.status == 200)){
                switch(type){
                    case 'xml' : callBack(ajax.responseXML);  break;
                    case 'text': callBack(ajax.responseText); break;
                }
            }
        }
    }
    ajax.send(null);
}

function ajaxSend(url, data, ret){
    onLoad();
    var ajax = iniAjax();
    if(ajax){
        ajax.open("POST", url, true);
        ajax.setRequestHeader("Content-Type","text/html; charset=iso-8859-1");
        ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        ajax.setRequestHeader("Pragma", "no-cache");
        ajax.onreadystatechange = function(){
            if(ajax.readyState == 4){
                if(ajax.status == 200){
                    unLoad(function(){
                        ret(ajax.responseText);
                    });
                }else{
                    alert("Houve um problema ao obter os dados:\n" + ajax.statusText);
                }
            }
        }
        ajax.send(data);
    }
}

function rajax(url, tagname, elemento, tresp, tfunc){
    var bool  = true;
    var ajax  = iniAjax();
    tresp = tresp.toLowerCase();
    if(ajax){
        if(tresp != 'texto' && tresp != ''){
            try{  loading(elemento, tresp);  }catch(err){  }
        }
        ajax.open('GET', url, true);
        ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");
        ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        ajax.setRequestHeader("Pragma", "no-cache");
        ajax.onreadystatechange = function(){ //Verificações
            if((ajax.readyState == 4) && (ajax.status == 200)){
                switch(tresp){
                    case 'xml':
                    popula_sel(ajax.responseXML, tagname, elemento);
                    break;
                    case 'texto':
                    if(document.getElementById(elemento)){
                        document.getElementById(elemento).innerHTML = ajax.responseText;
                    }else{
                        popUp('Elemento Não encontrado');
                    }
                    break;
                    case 'retxml':
                    tfunc(ajax.responseXML);
                    break;
                    case 'rettxt':
                    tfunc(ajax.responseText);
                    break;
                    case 'refreshajax':
                    popUpRefresh(ajax.responseText, "rajax('"+tfunc+"', '', '"+elemento+"', 'texto', '')");
                    break;
                    case 'image':
                        windowElement(ajax.responseText, '', tresp);
                    break;
                    default:
                        if(tfunc) tfunc(ajax.responseText);
                }
                if(tresp != 'texto') destroyElement('loading');
                if(!document.getElementById('msg')){
                    if(document.getElementById('loading'))
                        closeElement('loading');
                window.setTimeout('fadeOut("sombra", 0.5)', 500);
                }
            }
        }
    }
    ajax.send(null);
}

function altStatus(tabela, coluna, campoid, id){
    var url = '/ajax/altstatus.php?tab='+tabela+'&col='+coluna+'&cid='+campoid+'&id='+id;
    rajax(url,'','','','');
}

function update(tabela, coluna, novovalor, id){
    var url = '/ajax/update.php?tab='+tabela+'&col='+coluna+'&nval='+novovalor+'&id='+id;
    rajax(url,'','','rettxt', show);
}

/*
Monta a url com os itens do formulario para posterior envio via Ajax
*/

function enviando(local, parametros){
    var ajax = iniAjax();
    ajax.open("POST", local, true);
    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
    ajax.setRequestHeader("encoding", "iso-8859-1");
    ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    ajax.setRequestHeader("Pragma", "no-cache");
    if(parametros != null){
        ajax.setRequestHeader("Content-length", parametros.length);
        ajax.send(parametros);
    }
    ajax.onreadystatechange = function (){ //Verificações
        if(ajax.readyState==4){
            if(ajax.status==200){
                closeElement('loading');
                popUp('Dados Cadastrados com Sucesso');
            }
        }
    }
}

function recForm(idform, url){
    if(validaform(idform) != false){
        loading('', 'rettxt');
        var form    = document.getElementById(idform);
        var nro     = form.elements.length;
        var params  = "";
        for(x = 0; x < nro; x++){
            if(form.elements[x].id != "")
                params+= form.elements[x].id+"="+form.elements[x].value+"&";
        }
        params = params.substr(0,(params.length - 1));
        rajax(url+'?'+params, '', '', 'rettxt', show);
    }
}

function retCpf(retorno){
	valor = retorno.split(';');
	var cod = valor[0];
	var msg = valor[1];
	var cpf = valor[2];
	if(cod==1){
		document.forms[0].cpf.value = cpf;
	}else{
		document.forms[0].cpf.value = "";
	}
	document.forms[0].ret.value = msg;
}

function carrega_dados(retorno, tagname){
    document.forms[0].reset();
    opcoes = retorno.getElementsByTagName(tagname); //Retorna os options do select
    var form = document.forms[0];
    if(opcoes.length > 0){
        for(x=0;x<form.elements.length;x++){
            if(form.elements[x].name != "" && form.elements[x].name != undefined){
                var campo = limpa_elemento(form.elements[x].name);
                valor = retorno.getElementsByTagName(campo);
                try{
                    if(valor[0].childNodes[0].nodeValue!="NULL")
                    {
                        if(form.elements[x].type == "select-one")
                        {
                            var value = valor[0].childNodes[0].nodeValue;
                            sel = form.elements[x].options;
                            achou = false;
                            for(y=0;y<sel.length;y++){
                                if(sel[y].value == value)
                                {
                                    sel[y].selected = true;
                                    achou = true;
                                    break;
                                }
                            }
                            if(achou==false){
                                sel[0] = new Option(value,value);
                                sel[0].selected = true;
                            }
                        }
                        else
                        {
                            form.elements[x].value = valor[0].childNodes[0].nodeValue;
                        }
                    }
                }catch(err){ }
            }
        }
    }
    else
    {
        enter();
    }
}
function busca_dados(banco, field, valor){
    document.getElementById("msg_retorno").innerHTML = "";
    ajax = iniAjax();
    if(ajax){
        url = '/ajax/dados.php?banco='+banco+'&field='+field+'&valor='+valor;
        ajax.open('GET',url,true); //Abre a página XML
        ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded;');
        ajax.setRequestHeader("CharSet","iso-8859-2");
        ajax.setRequestHeader('Cache-Control','no-store, no-cache, must-revalidate');
        ajax.setRequestHeader('Cache-Control','post-check=0, pre-check=0');
        ajax.setRequestHeader('Pragma', 'no-cache');
        ajax.onreadystatechange = function (){ //Verificações
            if(ajax.readyState==4){
                if(ajax.status==200){
                    carrega_dados(ajax.responseXML, banco);
                }
            }
        }
    }
    ajax.send(null);
}

function limpa_elemento(element){
    var temp = element.replace("*","");
    temp = temp.replace("#","");
    temp = temp.replace("$","");
    return temp;
}
// Validação de formularios
function validaform_ajax(name, retorno){
    var formu   = document.getElementById(name);
    var retor   = true;
    for(x = 0; x < formu.elements.length; x++){
        if(formu.elements[x].className == "valida"){
            var value = formu.elements[x].value;
            if(value == "" || value.length < 4){
                var msg = "Preencha o campo "+formu.elements[x].alt+" corretamente.";
                if(retorno){ document.getElementById(retorno).innerHTML = msg; }
                else { alert(msg); }
                formu.elements[x].focus();
                retor = false;
                break;
            }
        }
    }
    return retor;
}

function deletando(banco, id){
    var tmp = confirm("DELETAR "+sel.options[sel.selectedIndex].text+" ?");
    if(tmp == true){
        carregando("Deletando",535,190,true);
        ajax = iniAjax();
        if(ajax){
            var url = "/ajax/deletando.php?banco="+banco+"&id="+sel.value;
            ajax.open("GET",url,true);
            ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            ajax.onreadystatechange = function (){ //Verificações
                if(ajax.readyState==4){
                    if(ajax.status==200){
                        setTimeout("carregando('',0,0,false)",2000);
                        if(ajax.responseText==1){ alert("Deletado com sucesso!"); }
                        else{ alert("Não foi possivel efetuar a deleção!"); }
                        window.history.go(0);
                    }
                }
            }
        }
        ajax.send(null);
    }
}

/*
function timeClose(resp){
    var dados = resp.split(';');

    $("#msg").fadeOut("slow", function(){
        $("#sombra").fadeOut("slow", function(){
            if(dados[0] == '00'){ window.location.href = dados[2]; }
        });
    });
}
*/

function retLogon(resp){
    var dados = resp.split(';');
    mensagem  = '<center><br/><b>'+dados[1]+'</b></center>';
    if(dados[0] != '00'){
        windowElement(mensagem, '', false);
        setTimeout(function(){
            $("#msg").fadeOut("slow", function(){
                $("#sombra").fadeOut("slow", function(){
                    $("#sombra").remove();
                })
            });
        }, 2000);
    }else{
        window.location.href = dados[2];
    }
}

function logonAjax(modulo, iduser, idpass){
    var user = document.getElementById(iduser).value;
    var pass = document.getElementById(idpass).value;
    try{
        modu = document.getElementById(modulo).value;
    }catch(err){
        modu = modulo;
    }
    var url  = '../ajax/logonAjax.php?mod='+modu+'&user='+user+'&pass='+pass;
    rajax(url,'','','rettxt', retLogon);
}

function carregando(text, tp, lft, vis){
    if(text==""){ text = "Carregando"; }
    var load = document.getElementById("loading");
    if(vis){
        load.style.visibility = "visible";
        load.style.top = tp;
        load.style.left = lft;
        load.innerHTML = "<img src='../imagens/loading.gif'> "+text+"...";
    }else{
        load.style.visibility = "hidden";
        load.innerHTML = "";
    }
}
// Altera todas os caracteres
function str_replace(string,busca,altera){
    while(string.search(busca) != -1){
        string = string.replace(busca,altera);
    }
    return string;
}

function grava_dados(url, elid, tabela, coluna, id, value){
    if(value){
        var loc = document.getElementById(elid);
        var gets = url+'?tab='+tabela+'&col='+coluna+'&val='+value+'&vid='+id;
        rajax(gets,'','','','');
        if(elid){
            loc.innerHTML = value;
            loc.onclick = function(){
                edita_dados(url, elid, tabela, coluna, value, id);
            }
        }
    }
}

function edita_dados(url, elid, tabela, coluna, value, id){
    var loc = document.getElementById(elid);
    var input = "<input type='text' name='val_"+elid+"' id='val_"+elid+"' size='30' ";
    input+= "onBlur=\"grava_dados('"+url+"', '"+elid+"', '"+tabela+"', '"+coluna+"', '"+id+"', this.value)\" ";
    input+= "onkeydown=\"enter(event, this.id);\" value='"+value+"' style=\"height:16px;\">";
    loc.onclick = "";
    loc.innerHTML = input;
    document.getElementById('val_'+elid).focus();
}