var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function containsElement(arr, ele)
{
    var found = false, index = 0;
    while(!found && index < arr.length)
        if(arr[index] == ele)
            found = true;
        else
            index++;
    return found;
}
function getIndex(input)
{
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
        if (input.form[i] == input)index = i;
        else i++;
    return index;
}

function autoTab(input,len, e)
{
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode))
    {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }
    return true;
}

function validaChar(input,e)
{
    var keypress = (isNN) ? e.which : e.keyCode;
    if (keypress == 13 )
    {
        input.form[(getIndex(input)+1) % input.form.length].focus();
        return false;
    }

    return true;
}


function mascara_upper(thisc,keyp)
{
    if (keyp.keyCode == 8)
    {
        return true;
    }
    thisc.value = thisc.value.toUpperCase();
}

function mascara_cnpj(thisc,keyp)
{
    cpf=thisc.value;

    if (!(keyp == 'aa'))
    {
        if (keyp.keyCode == 8)
        {
            if (cpf.length == 16)
            {
                thisc.value = cpf.substr(0,cpf.length -1);
            }

            if (cpf.length == 11)
            {
                thisc.value = cpf.substr(0,cpf.length -1);
            }

            if (cpf.length == 7)
            {
                thisc.value = cpf.substr(0,cpf.length -1);
            }

            if (cpf.length == 3)
            {
                thisc.value = cpf.substr(0,cpf.length -1);
            }
            return true;
        }

        var tecla = keyp.keyCode;
        if (tecla < 40)
        {
            return false;
        }
        if (!(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58))))
        {
            thisc.value = cpf.substr(0,cpf.length -1);
            return false;
        }
    }

    var mycpf = '';
    cpf = cpf.toString().replace( "-", "" );
    cpf = cpf.toString().replace( ".", "" );
    cpf = cpf.toString().replace( ".", "" );
    cpf = cpf.toString().replace( "/", "" );

    if (cpf.length < 2 )
    {
        mycpf = cpf
        }

    if (cpf.length >= 2 && cpf.length < 5)
    {
        mycpf = cpf.substr(0,2) + '.' + cpf.substr(2,cpf.length)
        }

    if (cpf.length >= 5 && cpf.length < 8)
    {
        mycpf = cpf.substr(0,2) + '.' + cpf.substr(2,3)  + '.' +cpf.substr(5,cpf.length)
        }

    if (cpf.length >= 8 && cpf.length <12)
    {
        mycpf = cpf.substr(0,2) + '.' + cpf.substr(2,3)  + '.' +cpf.substr(5,3) + '/'+cpf.substr(8,cpf.length);
    }

    if (cpf.length >= 12)
    {
        mycpf = cpf.substr(0,2) + '.' + cpf.substr(2,3)  + '.' +cpf.substr(5,3) + '/'+cpf.substr(8,4) + '-'+cpf.substr(12,cpf.length);
    }

    thisc.value = mycpf;
}

function mascara_cpf(thisc,keyp)
{
    cpf=thisc.value;

    if (!(keyp == 'aa'))
    {
        if (keyp.keyCode == 8)
        {
            if (cpf.length == 12)
            {
                thisc.value = cpf.substr(0,cpf.length -1);
            }

            if (cpf.length == 8)
            {
                thisc.value = cpf.substr(0,cpf.length -1);
            }

            if (cpf.length == 4)
            {
                thisc.value = cpf.substr(0,cpf.length -1);
            }
            return true;
        }

        var tecla = keyp.keyCode;
        if (tecla < 40)
        {
            return false;
        }

        if (!(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58))))
        {
            thisc.value = cpf.substr(0,cpf.length -1);
            return false;
        }
    }

    var mycpf = '';
    cpf = cpf.toString().replace( "-", "" );
    cpf = cpf.toString().replace( ".", "" );
    cpf = cpf.toString().replace( ".", "" );
    cpf = cpf.toString().replace( "/", "" );

    if (cpf.length < 3 )
    {
        mycpf = cpf
        }

    if (cpf.length >= 3 && cpf.length < 6)
    {
        mycpf = cpf.substr(0,3) + '.' + cpf.substr(3,cpf.length)
        }

    if (cpf.length >= 6 && cpf.length < 9)
    {
        mycpf = cpf.substr(0,3) + '.' + cpf.substr(3,3)  + '.' +cpf.substr(6,cpf.length)
        }

    if (cpf.length >= 9)
    {
        mycpf = cpf.substr(0,3) + '.' + cpf.substr(3,3)  + '.' +cpf.substr(6,3) + '-'+cpf.substr(9,2);
    }

    thisc.value = mycpf;
}

function mascara_cc (thisc,event)
{
    __frm=document.getElementById('clientes');
    if (__frm.elements['tipo_pessoa'].value == 1)
        mascara_cpf(thisc,event);
    else
        mascara_cnpj(thisc,event);
}

function cpf(s)
{
    s = s.toString().replace( "-", "" );
    s = s.toString().replace( ".", "" );
    s = s.toString().replace( ".", "" );
    s = s.toString().replace( "/", "" );
    var i;
    var c = s.substr(0,9);
    var dv = s.substr(9,2);
    var d1 = 0;
    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(10-i);
    }
    if (d1 == 0){
        return false;
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1)
    {
        return false;
    }

    d1 *= 2;
    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(11-i);
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1)
    {
        return false;
    }
    return true;
}


function mascara_cep(thisc,keyp)
{
    s=thisc.value;

    if (!(keyp == 'aa'))
    {
        if (keyp.keyCode == 8)
        {
            return true;
        }

        var tecla = keyp.keyCode;
        if (tecla < 40)
        {
            return false;
        }
        if (!(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58))))
        {
            thisc.value = s.substr(0,s.length -1);
            return false;
        }
    }
    s = s.toString().replace( "-", "" );
    s = s.toString().replace( ",", "" );
    s = s.toString().replace( ".", "" );
    s = s.toString().replace( "/", "" );

    if (s.length <5)
    {
        ret=s;
    }
    else
    {
        part1=s.substr(0,5);
        part2=s.substr(5);
        ret=part1+'-'+part2;
    }
    thisc.value=ret;
}

function mascara_moeda(thisc,keyp)
{
    s=thisc.value;
    if (!(keyp == 'aa'))
    {
        if (keyp.keyCode == 8)
        {
            return true;
        }

        var tecla = keyp.keyCode;
        if (tecla < 40)
        {
            return false;
        }
        if (!(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58))))
        {
            thisc.value = s.substr(0,s.length -1);
            return false;
        }
    }
    s = s.toString().replace( "-", "" );
    s = s.toString().replace( ",", "" );
    s = s.toString().replace( ".", "" );
    s = s.toString().replace( "/", "" );

    if (s.length == 1)
    {
        ret=".0"+s;
    }
    else if (s.length < 2)
    {
        ret="."+s;
    }
    else
    {
        part1=s.substr(0,s.length-2);
        part2=s.substr(s.length-2);
        if (part1.length == 0)
        {
            part1="0";
        }
        while ( (part1.substr(0,1) == "0") & (part1.length >1) )
        {
            part1=part1.substr(1);
        }
        if (part1.length <= 3)
        {
            ret=part1+"."+part2;
        }
        else if (part1.length <=6)
        {
            part1_=part1.substr(0,part1.length-3);
            part1__=part1.substr(part1.length-3);
            ret=part1_+""+part1__+"."+part2;
        }
    }
    thisc.value=ret;
}

function mascara_numero(thisf,keyp)
{
    fone=thisf.value;

    var tecla = keyp.keyCode;

    if (keyp.keyCode == 8)
    {
        return true;
    }
    if (tecla < 40)
    {
        return false;
    }
    if (!(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58))))
    {
        thisf.value = fone.substr(0,fone.length -1);
        return false;
    }
}

function mascara_fone(thisf,keyp)
{
    fone=thisf.value;
    if (!(keyp == 'aa'))
    {
        if (keyp.keyCode == 8)
        {
            if (fone.length == 10)
            {
                thisf.value = fone.substr(0,fone.length -1);
            }

            if (fone.length == 5)
            {
                thisf.value = fone.substr(0,fone.length -2);
            }

            return true;
        }

        var tecla = keyp.keyCode;
        if (tecla < 40)
        {
            return false;
        }
        if (!(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58))))
        {
            thisf.value = fone.substr(0,fone.length -1);
            return false;
        }
    }

    var myfone = '';
    fone = fone.toString().replace( "-", "" );
    fone = fone.toString().replace( ".", "" );
    fone = fone.toString().replace( "(", "" );
    fone = fone.toString().replace( ")", "" );
    fone = fone.toString().replace( " ", "" );

    if (fone.length < 2 )
    {
        myfone = '('+fone;
    }

    if (fone.length >= 2 && fone.length < 6)
    {
        myfone = '('+fone.substr(0,2)+') '+fone.substr(2,fone.length);
    }

    if (fone.length >= 6)
    {
        myfone = '('+fone.substr(0,2)+') '+fone.substr(2,4)+'-'+fone.substr(6,fone.length);
    }

    thisf.value = myfone;

}

function Pesquisar(e)
{
    var keypress = (isNN) ? e.which : e.keyCode;
    if (keypress == 13 )
    {
        __pesquisar();
    }

    return true;
}

function loadData(url)
{
    req = null;
    time = new Date();
    timed = time.getTime();
    url = url + '&timed='+timed;
    if (window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
        req.onreadystatechange = getData;
        req.open("GET", url, true);
        req.send(null);
    }
    else if (window.ActiveXObject)
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req)
        {
            req.onreadystatechange = getData;
            req.open("GET", url, true);
            req.send();
        }
    }
}

function $import(path){
    var i, base, src = "grid.js", scripts = document.getElementsByTagName("script");
    for (i=0; i<scripts.length; i++){
        if (scripts[i].src.match(src)){
            base = scripts[i].src.replace(src, "");
            break;
        }
    }
document.write("<" + "script src=\"" + base + path + "\"></" + "script>");
}

function getData()
{
    if (req.readyState == 4)
    {
        if (req.status == 200)
        {
            var ok = new Function( req.responseText )();
            ok;
        }
        else if (req.status == 404)
        {
            document.getElementById('msg_type').className = 'errors';
            document.getElementById('msg_type').innerHTML ='<ul>Erro ao requisitar o XMLHttpRequest : ('+req.statusText+')</ul>';
        }
    }
}

function ___pesquisar_ura()
{
    var largura = 750;
    var altura = 350;
    var esquerda = (screen.width - largura) / 2;
    var cima = (screen.height - altura) / 2 -50;
    var rolagem = 'no';

    __pesq = window.open('http://www.sistema.net.br/ura_status.php','','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',resizable=no,copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
}


function ___pesquisar(schema)
{
    var largura = 750;
    var altura = 350;
    var esquerda = (screen.width - largura) / 2;
    var cima = (screen.height - altura) / 2 -50;
    var rolagem = 'no';

    __pesq = window.open('http://www.sistema.net.br/select.php?schema='+schema+'&query='+document.getElementById('__search').value,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',resizable=no,copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
}

function ___adicionar(url)
{
    window.location='http://www.sistema.net.br/'+url;
}

function ___pacesso(db)
{
    var largura = 750;
    var altura = 650;
    var esquerda = (screen.width - largura) / 2;
    var cima = (screen.height - altura) / 2 -50;
    var rolagem = 'yes';
    __pacessot = window.open('http://www.sistema.net.br/politica_acesso.php?id=/'+db,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',resizable=no,copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
}

function ___audit(db)
{
    var largura = 750;
    var altura = 350;
    var esquerda = (screen.width - largura) / 2;
    var cima = (screen.height - altura) / 2 -50;
    var rolagem = 'yes';
    frm=document.getElementById(db);
    if (frm.elements['acao'].value == 'add')
    {
        __auditt = window.open('http://www.sistema.net.br/auditar.php?schema='+db,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',resizable=no,copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
    }
    else
    {
        __auditt = window.open('http://www.sistema.net.br/auditar.php?schema='+db+'&chave='+frm.elements['primary_key'].value,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',resizable=no,copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
    }
}

function ___anexar(db)
{
    var largura = 900;
    var altura = 700;
    var esquerda = (screen.width - largura) / 2;
    var cima = (screen.height - altura) / 2 -50;
    var rolagem = 'yes';
    frm=document.getElementById(db);
    if (frm.elements['acao'].value == 'add')
    {
        alert('É necessário selecionar um cadastro...');
    }
    else
    {
        __auditt = window.open('http://www.sistema.net.br/anexar_doc.php?schema='+db+'&chave='+frm.elements['primary_key'].value,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',resizable=no,copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
    }
}

function ___excluir(id)
{
    frm=document.getElementById(id);
    if (frm.elements['acao'].value == 'add')
    {
        alert('É necessário selecionar um cadastro...');
    }
    else
    {
        if (confirm('Tem certeza que deseja excluir o registro: '+frm.elements['primary_key'].value+' ?'))
        {
            loadData('http://www.sistema.net.br/xmlRequest.php?method=del&schema='+id+'&id='+frm.elements['primary_key'].value);
        }
    }
}


function ___url(url,largura,altura)
{
    var esquerda = (screen.width - largura) / 2;
    var cima = (screen.height - altura) / 2 -50;
    var rolagem = 'yes';
    window.open('http://www.sistema.net.br/'+url,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
}

function ____url(url,id,largura,altura)
{
    frm=document.getElementById(id);
    if (frm.elements['acao'].value == 'add')
    {
        var esquerda = (screen.width - largura) / 2;
        var cima = (screen.height - altura) / 2 -50;
        var rolagem = 'yes';

        window.open('http://www.sistema.net.br/'+url,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
    }
    else
    {
        alert('Clique em Adicionar para iniciar o processo de seleção UID...');
    }
}

function __url(url,id,largura,altura)
{
    frm=document.getElementById(id);
    if (frm.elements['acao'].value == 'add')
    {
        alert('É necessário selecionar um cadastro...');
    }
    else
    {
        var esquerda = (screen.width - largura) / 2;
        var cima = (screen.height - altura) / 2 -50;
        var rolagem = 'yes';

        window.open('http://www.sistema.net.br/'+url+'?id='+frm.elements['primary_key'].value,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
    }
}

function _cc(id,color)
{
    obj=document.getElementById(id);
    obj.style.backgroundColor=color;
}

function selected(cal, date) {
    cal.sel.value = date; // just update the date in the input field.
    if (cal.dateClicked && (cal.sel.id == "_inn_data_base" || cal.sel.id == "sel3"))
        // if we add this call we close the calendar on single-click.
        // just to exemplify both cases, we are using this only for the 1st
        // and the 3rd field, while 2nd and 4th will still require double-click.
        cal.callCloseHandler();
}

function closeHandler(cal) {
    cal.hide();                        // hide the calendar
    //  cal.destroy();
    _dynarch_popupCalendar = null;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

function showCalendar(id, format, showsTime, showsOtherMonths) {
    var el = document.getElementById(id);
    if (_dynarch_popupCalendar != null) {
        // we already have some calendar created
        _dynarch_popupCalendar.hide();                 // so we hide it first.
    } else {
        // first-time call, create the calendar.
        var cal = new Calendar(1, null, selected, closeHandler);
        // uncomment the following line to hide the week numbers
        // cal.weekNumbers = false;
        if (typeof showsTime == "string") {
            cal.showsTime = true;
            cal.time24 = (showsTime == "24");
        }
        if (showsOtherMonths) {
            cal.showsOtherMonths = true;
        }
        _dynarch_popupCalendar = cal;                  // remember it in the global var
        cal.setRange(1900, 2070);        // min/max year allowed.
        cal.create();
    }
    _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
    _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
    _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

    // the reference element that we pass to showAtElement is the button that
    // triggers the calendar.  In this example we align the calendar bottom-right
    // to the button.
    _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

    return false;
}

function get(form)
{
    var fields = form.getElementsByTagName('input');
    dados = '';
    for (var i	= 0; i < fields.length; i++)
    {
        if (fields[i].type == 'radio' && fields[i].checked == false ) continue;
        if (fields[i].type == 'checkbox' && fields[i].checked == false ) continue;
        if (i > 0)
        {
            dados = dados + '&'	+ fields[i].name + '=' + fields[i].value;
        }
        else
        {
            dados = fields[i].name + '=' + fields[i].value;
        }
    }
    return dados;
}

function getPost(fform,url)
{
    form = document.getElementById(fform);
    formstring = get(form);
    req = null;
    time = new Date();
    timed = time.getTime();
    url = url + '?timed='+timed;
    if (window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
        req.onreadystatechange = getData;
        document.getElementById('msg_type').innerHTML = '';
        document.getElementById('msg_type').className = '';
        show_div(true, 'progress_div');
        progress();
        req.open("POST", url, true);
        req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        req.send(formstring);
    }
    else if (window.ActiveXObject)
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req)
        {
            req.onreadystatechange = getData;
            document.getElementById('msg_type').innerHTML = '';
            document.getElementById('msg_type').className = '';
            show_div(true, 'progress_div');
            progress();
            req.open("POST", url, true);
            req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            req.send(formstring);
        //echo "myProgBar.setBar('". $ii / count($boletos)."');";
        }
    }
}

function progress()
{
    if (time < 1)
        time = time + 0.0003;
    else
    {
        time = 0;
    }
    setTimeout('progress()',30);
    myProgBar.setBar(time);
}

function newurl(url,largura,altura)
{
    var esquerda = (screen.width - largura) / 2;
    var cima = (screen.height - altura) / 2 -50;
    var rolagem = 'yes';

    window.open('http://www.sistema.net.br/'+url,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
}

function xmlGps(id,lat,lng)
{
    loadData("http://www.sistema.net.br/xmlGps.php?id="+id+"&lat="+lat+"&lng="+lng);
}

function Ajax(url,fid,campo,sel,upd)
{
    frm=document.getElementById(fid);
    var indice = frm[campo].selectedIndex;
    var vl = frm[campo].value;
    loadData("http://www.sistema.net.br/"+url+"?form="+fid+"&sel="+sel+"&id="+vl+'&upd='+upd);
}

function migracaoXml(ip,mac,descr,contrato,backbone)
{
    metragem=document.getElementById('met'+ip).value;
    er=document.getElementById('er'+ip).value;
    loadData("http://www.sistema.net.br/migracaoXml.php?ip="+ip+"&mac="+mac+"&descr="+descr+'&met='+metragem+'&er='+er+'&contrato='+contrato+'&backbone='+backbone);
}

function mostradata(__date)
{
    var NomeMes=new Array(12);
    NomeMes[0] = "01";
    NomeMes[1] = "02";
    NomeMes[2] = "03";
    NomeMes[3] = "04";
    NomeMes[4] = "05";
    NomeMes[5] = "06";
    NomeMes[6] = "07";
    NomeMes[7] = "08";
    NomeMes[8] = "09";
    NomeMes[9] = "10";
    NomeMes[10] = "11";
    NomeMes[11] = "12";

    var DiaMes=new Array(31);
    DiaMes[1] = "01";
    DiaMes[2] = "02";
    DiaMes[3] = "03";
    DiaMes[4] = "04";
    DiaMes[5] = "05";
    DiaMes[6] = "06";
    DiaMes[7] = "07";
    DiaMes[8] = "08";
    DiaMes[9] = "09";
    DiaMes[10] = "10";
    DiaMes[11] = "11";
    DiaMes[12] = "12";
    DiaMes[13] = "13";
    DiaMes[14] = "14";
    DiaMes[15] = "15";
    DiaMes[16] = "16";
    DiaMes[17] = "17";
    DiaMes[18] = "18";
    DiaMes[19] = "19";
    DiaMes[20] = "20";
    DiaMes[21] = "21";
    DiaMes[22] = "22";
    DiaMes[23] = "23";
    DiaMes[24] = "24";
    DiaMes[25] = "25";
    DiaMes[26] = "26";
    DiaMes[27] = "27";
    DiaMes[28] = "28";
    DiaMes[29] = "29";
    DiaMes[30] = "30";
    DiaMes[31] = "31";

    dataAtual = new Date();
    dia = dataAtual.getDate();
    mes = dataAtual.getMonth();
    ano = dataAtual.getYear();
    hora = dataAtual.getHours();
    minuto = dataAtual.getMinutes();
    segundo = dataAtual.getSeconds();
    ano = (ano < 1000) ? ano + 1900 : ano;
    __date.value = ano+'-'+NomeMes[mes]+'-'+DiaMes[dia]+' '+hora+':'+minuto+':'+segundo;
}
