Raw Source
Runy69 / Ordenes de Batalla - MoD eCuba

// ==UserScript==
// @name			Ordenes de Batalla - MoD eCuba
// @version			v8
// @author			Runy69 3.0 & El Bort
// @namespace		#e.cuba irc.rizon.net
// @description		Plugin para visualizar las Ordenes de Batalla de eCuba.
// @require			https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require			https://raw.githubusercontent.com/jaz303/tipsy/master/src/javascripts/jquery.tipsy.js
// @include			http://*.erepublik.com/*
// @include			https://*.erepublik.com/*
// @updateURL		https://dl.dropboxusercontent.com/s/vc9e04zpzt0o8o8/Meta.meta.js
// @downloadURL		https://dl.dropboxusercontent.com/s/xi9kmf824m05dcu/Script.user.js
// ==/UserScript==
var update = false;
var actV = 'v8';
//TXT VARS
var txt = {
//GLOBALS
    'global' : {
    //PRIORITIES ID
        'prio' : {
            '1' : 'ma',
            '2' : 'al',
            '3' : 'me',
            '4' : 'ba',
            '5' : 'se',
            '6' : 'pe',
            '7' : 'no'
        }
    },
//ENGLISH
    'en' : {
    //PRIORITIES
        'prio' : {
            '1' : {
                'label' :  'MAXIMUM',
                'info'  :  'MAXIMUM: Priority or very difficult campaign. Domain bar must be between 52% and 55% to ensure victory.'
            },
            '2' : {
                'label' :  'HIGH',
                'info'  :  'HIGH: Difficult campaign. Domain bar must be between 52% and 55% in all battles as possible to ensure victory.'
            },
            '3' : {
                'label' :  'MEDIUM',
                'info'  :  'MEDIUM: Medium priority campaign. Domain bar must be between 51% and 53% in all battles as possible to ensure victory.'
            },
            '4' : {
                'label' :  'LOW',
                'info'  :  'LOW: Low priority campaign or with high score in favor. Keep an eye on and only fight if higher priorities are controlled.'
            },
            '5' : {
                'label' :  'SECURED',
                'info'  :  'SECURED: Campaign with hight score in favor. IMPORTANT: Don\'t maybe campaign must be elonged, so probably other division should close it.'
            },
            '6' : {
                'label' :  'LOST',
                'info'  :  'LOST: Besides all efforts made it\'s not possible to win this campaign. Don\'t fight on it.'
            },
            '7' : {
                'label' :  'DON\'T FIGHT',
                'info'  :  'DONT FIGHT: We must lose this campaign for strategic reasons, don\'t fight on it, we must lose it.'
            }
        },
			'cold' : "Cold",
			'domination' : "Domination",
			'epic' : "Epic",
			'fight' : "Fight",
			'fightFor' : "Fight for",
			'full' : "Full",
			'orderC' : "ORDERS",
			'order' : "Orders",
			'points' : "Points",
			'priorityFor' : "Priority for",
			'rounds' : "Round",
			'total' : "Total",
			'wall' : "Wall"
    },
    'es' : {
    //PRIORITIES
        'prio' : {
            '1' : {
                'label' :  'MÁXIMA',
                'info'  :  'MAXIMA: Campaña prioritaria y/o muy complicada de cerrar. Se requiere que el porcentaje de dominio en todas las batallas, este entre 52% y 55% para asegurar su victoria.'
            },
            '2' : {
                'label' :  'ALTA',
                'info'  :  'ALTA: Campaña complicada de cerrar. Se requiere que el porcentaje de dominio en todas las batallas, este entre 52% y 55% para asegurar su victoria.'
            },
            '3' : {
                'label' :  'MEDIA',
                'info'  :  'MEDIA: Campaña de mediana prioridad. Se requiere que el porcentaje de dominio en todas las batallas, este entre 51% y 53% para asegurar su victoria.'
            },
            '4' : {
                'label' :  'BAJA',
                'info'  :  'BAJA: Campaña avanzada en punuación a favor o se requiere un minimo de dño para su victoria. Vigilar y combatir SOLO si las prioridades mayores estón muy controladas (barras de las otras batallas sobre 52%).'
            },
            '5' : {
                'label' :  'ASEGURADA',
                'info'  :  'SEGURA: Campaña muy avanza en punuación a favor. IMPORTANTE: muchas veces se necesita NO luchar para demorar el cierre de la camapaña, por asuntos estrategicos. NO luches en esta campaña. Otra/s División/es tiene/n que cerrarla.'
            },
            '6' : {
                'label' :  'PERDIDA',
                'info'  :  'PERDIDA: A pesar de todo el esfuerzo y lucha de nuestras tropas y aliados no es posible ganar esta campaña. NO luches en esta campaña, la perdimos.'
            },
            '7' : {
                'label' :  'NO LUCHAR',
                'info'  :  'NO LUCHAR: Se necesita perder la campaña por asuntos estrategócos. NO luches en esta campaña, debemos perderla.'
            }
		},
			'cold' : "Fría",
			'domination' : "Dominación",
			'epic' : "Épica",
			'fight' : "Luchar",
			'fightFor' : "Luchar por",
			'full' : "Gran Escala",
			'orderC' : "ÓRDENES",
			'order' : "Órdenes",
			'points' : "Puntos",
			'priorityFor' : "Prioridad en",
			'rounds' : "Ronda",
			'total' : "Total",
			'wall' : "Muro"
	}
};
//IMAGE SRCS
var img = {
    "en" : {
        "prio" : {
            "1" : "https://dl.dropboxusercontent.com/s/j7lpaza9m8bpd1b/ma_en.jpg",
            "2" : "https://dl.dropboxusercontent.com/s/ou6j72c7p1hx6bl/al_en.jpg",
            "3" : "https://dl.dropboxusercontent.com/s/9uj8mtcwon6mqum/me_en.jpg",
            "4" : "https://dl.dropboxusercontent.com/s/x49jbvzlnpk5ygp/ba_en.jpg",
            "5" : "https://dl.dropboxusercontent.com/s/q1jnbocowie9fh7/se_en.jpg",
            "6" : "https://dl.dropboxusercontent.com/s/qp3t5wufbe5vj90/pe_en.jpg",
            "7" : "https://dl.dropboxusercontent.com/s/sacivmzuou6u7fx/no_en.jpg"
        }
    },
    "es" : {
        "prio" : {
            "1" : "https://dl.dropboxusercontent.com/s/unevcw5o5itlo5r/ma_es.jpg",
            "2" : "https://dl.dropboxusercontent.com/s/rxduqunh1uv5k5h/al_es.jpg",
            "3" : "https://dl.dropboxusercontent.com/s/8zk5yndg3cu8j0i/me_es.jpg",
            "4" : "https://dl.dropboxusercontent.com/s/wzrg8fsa5pc73ce/ba_es.jpg",
            "5" : "https://dl.dropboxusercontent.com/s/2ldjzx4sc3fmqux/se_es.jpg",
            "6" : "https://dl.dropboxusercontent.com/s/5ovicymgoa5556f/pe_es.jpg",
            "7" : "https://dl.dropboxusercontent.com/s/9y4r3zvx2t06zrx/no_es.jpg"
        }
    }
};

var cult = SERVER_DATA.culture;
if(txt[cult] === undefined) cult = 'en';

function inicio(fn) {
    $.ajax({url: 'https://dl.dropboxusercontent.com/s/vc9e04zpzt0o8o8/Meta.meta.js', dataType: 'text'}).done(function(data){
        var lastV = data.match(/@version[\t]*v(.*)/)[1];
        update = lastV > actV;
        if(document.getElementById('homepage_feed') !== null) {
            var _paso = $;
            $ = jQuery;
            header();
            battles(function(data){
                var shouts = data[data.length-1].shout;
                var batts = data[division()-1];
                var url = cult+'/military/campaigns-new/';
                var active = [];
                $.ajax({url: url, dataType: 'json'}).done(function(data){
                    var dataB = data.battles;
                    var campaignTxt = $('#battle_listing h1').text();
                    if($('#battle_listing h1').text().indexOf(": "+txt[cult].orderC) == -1) $('#battle_listing h1').html(campaignTxt+': ' + txt[cult].orderC);
                    for(var prio in batts){
                        prio = prio.toString();
                        active[prio] = false;
                        if(Object.getOwnPropertyNames(batts[prio]).length > 0 && txt.global.prio[prio] !== undefined){
                            var ico = '<img style="margin-top: 10px;" id="info_' + txt.global.prio[prio] + '" original-title="' + txt[cult].prio[prio].info + '" src="http://www.erepublik.com/images/modules/_icons/small_info_icon.png" style="position:relative;bottom: -5px;right: -5px;" alt="">';
                            var _htmlBattles = '<img src="'+ img[cult].prio[prio] + '">' + ico + '<ul id="prio_' + txt.global.prio[prio] + '" class="prio_' + txt.global.prio[prio] + '"></ul>';
                            $('#mod_orders').append('<div id="info_header_'+txt.global.prio[prio]+'">'+_htmlBattles+'<div>');
                            $('#info_' + txt.global.prio[prio]).tipsy({gravity: $.fn.tipsy.autoNS});
                        }
                        for(var i in batts[prio]){
                            if(dataB[Math.abs(batts[prio][i])] !== undefined){
                                var signedId = batts[prio][i];
                                var id = Math.abs(signedId);
                                var side = (signedId/Math.abs(signedId) == 1 ? "def" : "inv");
                                battle(prio, side, dataB[id], data, shouts[id]);
                                active[prio] = true;
                            }
                        }
                        if(!active[prio]) $('#info_header_'+txt.global.prio[prio]).remove();
                        if ($('.war_versus_img').length > 0) $('.war_versus_img').tipsy({gravity: 's', html: true, opacity: 1.0, trigger: 'manual'});
                    }
                    if(active.indexOf(true) == -1) $('#battle_listing h1').html(campaignTxt);
                    $('#battle_listing h1').after('<small style=\"width: inherit; margin-top: -8px;\" id=\"script_v\">MoD eCuba '+actV+'<\/small><img id="info_translate" original-title="If you want to add your language send PM to Runy69 3.0 or El Bort to talk about translations" src="http://www.erepublik.com/images/modules/_icons/small_info_icon.png" style="margin-top: -8px;" alt="">');
                    if(update) $('#script_v').html('MoD eCuba update avilable: <a href=\"https://dl.dropboxusercontent.com/s/xi9kmf824m05dcu/Script.user.js\">Update '+lastV+'<\/a>');
                    $('#info_translate').tipsy({gravity: $.fn.tipsy.autoNS});
                    fn();
                });
            });
            footer();
            $ = _paso;
        }
    });
}

function header() {
    var orders = '<div id="mod_orders"></div>';
    $('#battle_listing h1').after(orders);
}

function footer() {
    var orders="";
    $(orders).insertAfter('#mod_orders');
}

function division() {
    return parseInt(erepublik.citizen.division);
}

function battles(fn) {
    $.ajax({url: 'https://www.googleapis.com/drive/v3/files/0B0ZftAweIEPLeDItSUkzSEZQU00?acknowledgeAbuse=false&fields=description&key=AIzaSyBN0fqYSh8d5Jb0mtV7eDn6nuK5uy182SM', dataType: 'text'}).done(function(data){
        var json = JSON.parse(data);
        json = json.description;
        fn(JSON.parse(json));
    });
}

function shoutToTxt(shouts, campaign, id, side){
    var region = campaign.region.name;
    var shoutTxt = "";
    var prios = [];
    for(var i = 0; i < shouts.length; i++){
        if(shouts[i] !== false){
            if(prios[parseInt(shouts[i])] === undefined) prios[parseInt(shouts[i])] = 'D'+(i+1);
            else prios[parseInt(shouts[i])] += ', D'+(i+1);
        }
    }
    if(prios !== []) {
        for(i in prios){
            shoutTxt += prios[i] + " " + txt.en.prio[i].label + "\n";
        }
        shoutTxt = "eCuba MoD "+txt[cult].order+":\n"+txt[cult].priorityFor+" "+erepublik.info.countries[campaign[side].id].name+":\n" + shoutTxt + region + " " + 'http://www.erepublik.com/en/military/battlefield-new/'+id;
    }
    return shoutTxt;
}

function battle(prio, side, data, fullData, shouts) {
    var campaign = data;
    var shoutTxt = shoutToTxt(shouts, campaign, campaign.id, side);
    if(fullData.countries[data.inv.id].allies.indexOf(parseInt(erepublik.citizen.country)) > -1) campaign.inv.isMyAlly = true;
    if(fullData.countries[data.def.id].allies.indexOf(parseInt(erepublik.citizen.country)) > -1) campaign.def.isMyAlly = true;
    var html="";
    var div = division();
    if(campaign.div[11] !== undefined) div = 11;
    var epic = campaign.div[div] == 2;
    html += "<li class=\"is_homepage"+(campaign.is_lib?' liberation':'')+(campaign.is_dict?' dictatorship':'')+(epic?' epic_battle_entry':'')+"\">";
    html += "<table>";
    html += "<tr>";
    html += "<td colspan=\"2\">";
    if(campaign.inv.isEmpire) html += "<span class=\"empire_flag_deco medium\"><span class=\"inner_deco_star\"><\/span><\/span>";
    if(campaign.is_dict) html += "<span class=\"dict_war_icon left_side\"><\/span>";
    if(campaign.is_lib) html += "<span class=\"libe_war_icon left_side\"><\/span>";
    html += "<span style=\"zoom: 1;\" id=\"invFlag_"+data.id+"\" value=\""+campaign.inv.id+"\" class=\"country_flags "+erepublik.info.countries[campaign.inv.id].permalink+"\"><\/span>";
    if(campaign.inv.isMyAlly && !campaign.is_rw && !campaign.is_dict  && !campaign.is_lib) html += "<img style=\"top: 20px;\" class=\"mpp_sign one\" src=\"\/\/www.erepublik.net\/images\/modules\/_icons\/small_mpp.png\" title=\""+erepublik.info.countries[campaign.def.id].permalink+"\" alt=\"\" \/>";
    if(campaign.is_rw) html += "<img style=\"top: 20px;\" class=\"resistance_sign one\" src=\"\/\/www.erepublik.net\/images\/modules\/_icons\/small_resistance.png\" title=\""+erepublik.info.countries[campaign.def.id].permalink+"\" alt=\"\">";
    html += "<div style=\"margin-left: -16px!important;"+(div == 11 ? ' background-image: url(/images/modules/misc/versus_aircraft.png?1468398448)':'')+"\" id=\"info_"+campaign.id+"\" class=\"war_versus_img\" original-title=\"Loading Data...\"><\/div>";
    if(campaign.def.isEmpire) html += "<span class=\"empire_flag_deco medium second\"><span class=\"inner_deco_star\"><\/span><\/span>";
    html += "<span style=\"zoom: 1;\" id=\"defFlag_"+data.id+"\" value=\""+campaign.def.id+"\" class=\"country_flags "+erepublik.info.countries[campaign.def.id].permalink+"\"><\/span>";
    if(campaign.def.isMyAlly && !campaign.is_rw &&  !campaign.is_dict && !campaign.is_lib) html += "<img style=\"top: 20px;\"  class=\"mpp_sign two\" src=\"\/\/www.erepublik.net\/images\/modules\/_icons\/small_mpp.png\" title=\""+erepublik.info.countries[campaign.def.id].name+"\" alt=\"\" \/>";
    html += "<strong>"+campaign.region.name+"<\/strong>";
    html += "<span  original-title=\""+txt[cult].fightFor+": "+erepublik.info.countries[campaign[side].id].name+"\" class=\"mod_fight_button fight_button campaign_page\">";
    if(!campaign.is_rw) html += "<a href=\"\/es\/military\/battlefield-new\/"+campaign.id+"\" class=\"std_global_btn smallSize blueColor\"><span>"+txt[cult].fight+"<\/span><\/a>";
    else html += "<a href=\"\/es\/wars\/show\/"+campaign.war_id+"\" class=\"std_global_btn smallSize blueColor\"><span>"+txt[cult].fight+"<\/span><\/a>";
    html += "<\/span>";
    html += "<\/td>";
    html += "<\/tr>";
    html += "<tr>";
    html += "<td style=\"width: 50%\">";
    html += "<a style=\"float: none; margin: 5px 5px; margin-left: 10px!important;\" id=\"info_button_"+campaign.id+"\" "+(div == 11 ? 'type="air"':"")+" value=\""+campaign.id+"\" href=\"javascript:;\" class=\"war_info_button std_global_btn smallSize blueColor\"><span>Info<\/span><\/a>";
    html += "<\/td>";
    if(shoutTxt !== "") {
        html += "<td style=\"width: 48%\">";
        html += "<a style=\"float: none; margin: 5px 5px;\" id=\"shout_button_"+campaign.id+"\" value=\""+shoutTxt+"\" href=\"javascript:;\" class=\"shout_button std_global_btn smallSize blueColor\"><span>Shout<\/span><\/a>";
        html += "<\/td>";
    }
    html += "<\/tr>";
    html += "<\/table>";
    html += "<\/li>";
    $('#prio_'+txt.global.prio[prio]).append(html);
    $('.mod_fight_button').tipsy({gravity: 'e', opacity: 1});
}

function loadBattleData(idElem, fn) {
    var url = cult+'/military/battle-stats/'+$(idElem).attr('value');
    $.ajax({ url: url, dataType: 'json'}).done(function(data){
        fn(idElem, data);
    });
}

function setData(item){
    loadBattleData(item, function(idElem, data){
        var air = $(idElem).attr('type') == 'air';
        var battId = $(idElem).attr('value');
        var round = 0;
        var defId = $('#defFlag_'+battId).attr('value');
        var invId = $('#invFlag_'+battId).attr('value');
        for(var i in data.stats.current){
            if(data.stats.current[i] !== undefined) round = i;
        }
        var epic = [];
        if(!air){
            for(var i = 1; i <= 4; i++){
                epic[i] = data.battle_zone_situation[i];
                epic[i] = (epic[i] > 0 ? (epic[i] == 1 ? txt[cult].full : txt[cult].epic) : txt[cult].cold);
            }
        } else {
            epic[11] = data.battle_zone_situation[11];
            epic[11] = (epic[11] > 0 ? (epic[11] == 1 ? txt[cult].full : txt[cult].epic) : txt[cult].cold);
        }
        var html="";
        html += "<table style=\"padding: 5px!important;\">";
        html += "<tr>";
        html += "<td>"+txt[cult].points+"<\/td><td>"+txt[cult].domination+"<\/td><td>"+txt[cult].wall+"<\/td>";
        html += "<td>"+txt[cult].rounds+" "+round+"<\/td>";
        html += "<td>"+txt[cult].wall+"<\/td><td>"+txt[cult].domination+"<\/td><td>"+txt[cult].points+"<\/td>";
        html += "<\/tr>";
        if(!air){
            for(var i = 1; i <= 4; i++){
                html += "<tr "+(division() == i ? "style=\"background:#83B70B\"" : "")+">";
                html += "<td>"+data.division[invId][i].points+"<\/td><td>"+data.division[invId][i].domination+"<\/td><td>"+(100-data.division.domination[i]).toFixed(2)+"%<\/td>";
                html += "<td class=\"middleCell\">"+epic[i]+"<\/td>";
                html += "<td>"+(data.division.domination[i]).toFixed(2)+"%<\/td><td>"+data.division[defId][i].domination+"<\/td><td>"+data.division[defId][i].points+"<\/td>";
                html += "<\/tr>";
            }
        } else {
            html += "<tr style=\"background:#83B70B\">";
            html += "<td>"+data.division[invId][11].points+"<\/td><td>"+data.division[invId][11].domination+"<\/td><td>"+(100-data.division.domination[11]).toFixed(2)+"%<\/td>";
            html += "<td class=\"middleCell\">"+epic[11]+"<\/td>";
            html += "<td>"+(data.division.domination[11]).toFixed(2)+"%<\/td><td>"+data.division[defId][11].domination+"<\/td><td>"+data.division[defId][11].points+"<\/td>";
            html += "<\/tr>";
        }
        html += "<tr><td>"+data.division[invId].total+"<\/td><td colspan=\"5\"> "+txt[cult].total+" <\/td><td>"+data.division[defId].total+"<\/td><\/tr>";
        html += "<\/table>";
        $("#info_"+battId).attr('original-title', html);
        $('#info_'+battId).tipsy("show");
    });
}

$(document).ready(function(){
    inicio(function(){
        $("<style type='text/css'> .tipsy-inner{max-width:999px!important}.tipsy-inner tr:last-child span{float:right;margin:0 0 0 5px}.tipsy-inner td{min-width:30px; padding: 2px;}.middleCell{text-align:center;padding:0}</style>").appendTo("head");
        $('.war_info_button').one('click', function(){
            setData(this);
        });
        $('.war_info_button').click(function(){
            var battId = $(this).attr('value');
            if($('div[class="tipsy-inner"]').length === 0){
                $("#info_"+battId).tipsy("show");
            } else {
                $("#info_"+battId).tipsy("hide");
            }
        });
        $('.shout_button').click(function(){
            $("#shout").click().val($(this).attr('value').trim());
			unsafeWindow.new_post();
        });
    });
});