var massa = null;

function carregado(resposta)
{
    massa = resposta;
    gera();
}

function carga_falhou(xhr, stat, error)
{
    alert("Não foi possível obter o banco de dados.");
}

function carrega()
{
    jQuery.ajax({type: "GET", url: "febeapa.dd", error: carga_falhou,
                 success: carregado});
}

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g,"");
}
 
String.prototype.ltrim = function () {
    return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function () {
    return this.replace(/\s+$/,"");
}

$(document).ready(function() {
    carrega();
});

function comprime(r)
{
    var s = "";
    var last = "";
    for (var i = 0; i < r.length; ++i) {
        var c = r.charAt(i);
        if (c != last) {
            s += c;
        }
        last = c;
    }
    return s;
}

function choice(l)
{
    var i = Math.floor(l.length * Math.random());
    var item = l[i];
    if (l.length > 1) {
        delete l[i];
    }
    return item;
}

function gera()
{

var f = massa.split("\n");

var ortotabela = [["deo", "do"], ["dea", "da"], ["deas", "das"], ["deos", "dos"],
              ["aas", "às"], ["aa", "à"]];

var d = {};
d["e"] =  [["e", [""], null, null]];
d["sp"] = [[" ", [""], null, null]];
d["d"] = [["d", [""], null, null]];

for(var i = 0; i < f.length; ++i) {
    var l = f[i];
    var mm = l.split("%");
    var m = [];
    for (var j = 0; j < mm.length; ++j) {
        var mmm = mm[j];
        mmm = mmm.trim();
        if (mmm.length > 0) {
            m.push(mmm);
        }
    }
    if (m.length < 3) {
        continue;
    }
    var tipo = m[0].trim();
    var txt = m[1].trim();
    var siglas = m[2].trim().split(" ");
    var extra1 = null;
    var extra2 = null;
    if (m.length > 3) {
        extra1 = m[3];
    }
    if (m.length > 4) {
        extra2 = m[4];
    }
    if (d[tipo] === undefined) {
        d[tipo] = [];
    }
    d[tipo].push([txt, siglas, extra1, extra2]);
}

// FIXME: tratamento vogais/consoantes 
var entidade = [];
entidade.push(choice(d['E']));
var genero = entidade[entidade.length - 1][2];
entidade[entidade.length - 1][2] = null ; // evita pegar isto como o feminino
entidade.push(choice(d['sp']));

if (Math.random() < 0.33) {
    entidade.push(choice(d['A']));
    entidade.push(choice(d['sp']));
    if (Math.random() < 0.25) {
        entidade.push(choice(d['A']));
        entidade.push(choice(d['sp']));
        if (Math.random() < 0.25) {
            entidade.push(choice(d['A']));
            entidade.push(choice(d['sp']));
        }
    }
}

if (Math.random() < 0.33) {
    entidade.push(choice(d['d']));
    entidade.push(choice(d['B']));
} else {
    entidade.push(choice(d['F']));
    if (entidade[entidade.length - 1][2] != "1") {
        entidade[entidade.length - 1][2] = null;
        entidade.push(choice(d['B']));
    } else {
        entidade[entidade.length - 1][2] = null;
    }
}
entidade.push(choice(d['sp']));

if (Math.random() < 0.20) {
    entidade.push(choice(d['e']));
    entidade.push(choice(d['sp']));
    if (Math.random() < 0.33) {
        entidade.push(choice(d['d']));
        entidade.push(choice(d['B']));
    } else {
        entidade.push(choice(d['F']));
        if (entidade[entidade.length - 1][2] != "1") {
            entidade[entidade.length - 1][2] = null;
            entidade.push(choice(d['B']));
        } else {
            entidade[entidade.length - 1][2] = null;
        }
    }
    entidade.push(choice(d['sp']));
}

entidade.push(choice(d['R']));

var sigla = "";
var nome = "";
for (i = 0; i < entidade.length; ++i) {
    var item = entidade[i];
    if (genero == "f" && item[2] !== null) {
        nome += item[2];
    } else {
        nome += item[0];
    }
    sigla += choice(item[1]);
}

sigla = comprime(sigla);

// corretor ortográfico
for (i = 0; i < ortotabela.length; ++i) {
    item = ortotabela[i];
    nome = nome.replace(" "+item[0]+" ", " "+item[1]+" ");
}

var result = sigla + " - " + nome
$('#alvo').html(result);
}

