Amynka / EasyGame

// ==UserScript==
// @name           EasyGame
// @namespace      minotor45
// @description    Gestion compte Ogame plus facile
// @version        3.0.0b
// @author         minotor45
// @include        http://*.ogame.*
// ==/UserScript==


(function( window, undefined ) {
    var debug = 0;
    var $ = window.jQuery;
    if(!$) throw new Error('jQuery is not initialized.');
    Math.clamp = function(low, n, high) { return Math.min(Math.max(low, n), high); };
    String.prototype.pick  = function (reg, def) { var m; return (m = this.match(reg)) ? m[m.length - 1 && 1] : def === undefined ? false : def; };
    Number.prototype.pick  = function (reg, def) { String.prototype.pick.call(this.toString(), reg, def); };
    String.prototype.find  = function (value) { return this.search(value) > -1; };
    String.prototype.changeKey = function() { return this.replace(new RegExp('-([a-z]){1}', 'gi'),function(c) {return c.substr(1).toUpperCase();}); };

    /********************* OLD ******************************/
    function makeUrl(page,complement) {
        var url = '';
        url += 'http://'+eg.metas.get('universe')+'/game/index.php?page='+page;
        if(complement) url += '&'+complement;
        return url;
    }
    function makeUrlAPI(name,params) {
        var url = '';
        url += 'http://'+eg.metas.get('universe')+'/api/';
        url += name+'.xml';
        if(params != undefined) url += '?'+$.param(params);
        return url;
    }
    function redirectPage(page,time) {
        setTimeout(function() {
            window.location.replace(makeUrl(page));
        },time);
    }
    function redirectToPlanet(cp,time) {
        if(cp != Planets.Current().getId()) {
            setTimeout(function() {
                window.location.replace(makeUrl(eg.global.page,'cp='+cp));
            },time);
        }
        else redirectPage(eg.global.page,time);
    }

    function random(min,max) { return Math.random()*(max-min)+min; }

    function toInt(value) {
        if(value == undefined) return 0;
        return parseInt(value.toString().replace(/[^0-9-]/g,''));
    }

    function AddPoint(nombre) {
        return window.tsdpkt(Math.round(nombre));
    }
    function consoEnergie(build_id,level) {
        return Math.ceil( ((build_id==3)?20:10) * level * Math.pow(1.1,level));
    }

    $.fn.addStyle = function(key,value) {
        var obj_css = {};
        if(typeof key == 'object') obj_css = key;
        else obj_css[key] = value;

        var styles = '';
        $.each(obj_css,function(i,style) { styles +=i+':'+style +' !important;'; });

        $('head').append($('<style>',{
            type:'text/css'
        }).html(this.selector +' {' +styles+' } '));

        return this;
    };


    $.fn.makebox = function(title,content) {
        var affiche = '<div class="content-box-xl" style="margin:0 0 5px 0;width:670px;float:left;overflow:hidden;">';
        affiche +='<div class="header" style="background:url(http://gf3.geo.gfsrv.net/cdnef/77c5d0b60f22b387b9dc90e2c4a30e.gif) no-repeat;';
        affiche += 'height:32px;font-size:11px;text-transform:uppercase;">';
        affiche +='<h3 style="color:#6F9FC8;font-size:11px;font-weight:700;padding-top:11px;width:670px;text-align:center;">';
        affiche += title;
        affiche+='</h3></div>';
        affiche +='<div class="content" style="background:url(http://gf1.geo.gfsrv.net/cdn03/db530b4ddcbe680361a6f837ce0dd7.gif) repeat-y;padding:5px 20px;">';
        affiche+='<table cellpadding="0" cellspacing="0">';
        affiche+='<tbody><tr>';
        affiche+='<td colspan="2" class="idle">';
        affiche += content;
        affiche+='</td>';
        affiche+='</tr>';
        affiche+='</tbody></table>';
        affiche+='</div>';
        affiche+='<div class="footer" style="background:url(http://gf3.geo.gfsrv.net/cdnef/77c5d0b60f22b387b9dc90e2c4a30e.gif) no-repeat transparent 0 -100px"></div>';
        affiche+='</div>';

        return this.html(affiche).insertAfter('.content-box-s:eq(2)');
    };


    function derniereMaj() {
        var reste = Math.round(100*($.now() - eg.gbdd.load('dateinstallMaJ',0))/86400000 )/100;
        var nb_jour = Math.floor(reste);
        if(nb_jour<0) return '';
        var nb_heure = Math.floor(24*(reste-nb_jour));
        return " ("+nb_jour +" j "+nb_heure+" h)";
    }
    function Changelog() {
        if(eg.gbdd.load('currentVersion','') < eg.version) {
            var lv = eg.gbdd.load('lastVersion','');
            if(lv != '' && lv  < '3.0.0') localStorage.clear();
            //eg.query('install',function() {
                eg.gbdd.save('lastVersion',eg.gbdd.load('currentVersion',''));
                eg.gbdd.save('currentVersion',eg.version);
                eg.gbdd.save('aJours',true);
                eg.gbdd.save('dateinstallMaJ',$.now());
                eg.gbdd.save('datecheckMaJ',$.now());
            //});
        }
        var datecheckMaj = eg.gbdd.load('datecheckMaJ',0);
        var aJour = eg.gbdd.load('aJours',true);

        if (aJour && toInt(datecheckMaj)+8*3600*1000 < $.now()) {
            /*eg.query('getLastVersion',function(data) {
                eg.gbdd.save('aJours',eg.version <= data.version);
                eg.gbdd.save('datecheckMaJ',$.now());
            });*/
            eg.gbdd.save('aJours',true);
            eg.gbdd.save('datecheckMaJ',$.now());
        }

        if (!aJour) {
            if(eg.gbdd.load('currentVersion','') != eg.version) {
                eg.query('getChangelog',function(data) {
                    var chglog  = '<tr><th><a href="http://userscripts.org/scripts/source/'+eg.number +'.user.js">';
                    chglog += '<br />Installer la derniere version '+derniereMaj()+'</a></th></tr>';
                    chglog += data.log;
                    $('<span>').attr('id','affichagechangelog').makebox('Changelog : '+eg.name+' v'+data.lastVersion,chglog);
                });
            }
            else eg.gbdd.save('aJours',true);
        }
    }
    function pourcentCEF(Manque_energie, CEF, NRJ, Pourcent) {
        var P_CEF,E_CEF_Max,Reste;
        if(!CEF) P_CEF = Pourcent / 100;
        else {
            Reste = Manque_energie + Build.prodCEF(CEF,NRJ,Pourcent);
            E_CEF_Max = Build.prodCEF(CEF,NRJ,100);

            if( Manque_energie >= 0 )
                P_CEF = Reste / E_CEF_Max;
            else {
                P_CEF = -Reste / E_CEF_Max;
                if( P_CEF > 1 )
                    P_CEF = 0;
            }
            if( P_CEF < 0 ) P_CEF = -P_CEF;
            P_CEF = Math.ceil(P_CEF * 10) / 10;
            if( P_CEF > 1 ) P_CEF = 1;
            if( P_CEF < 0.1 ) P_CEF = 0;
        }

        return Math.ceil(100 * P_CEF);
    }
    /********************************************************/


    function EasyGame() {
        var self = this;

        function Meta() {
            var tabs = $('meta[name]').toArray();
            for(let i = 0; i < tabs.length; i++) this[tabs[i].name.substr(6).changeKey()] = tabs[i].content;
        }

        function Bdd(global) {
            var key = self.name + '-';
            if (global) key += 'global';
            else if(self.global.getMode() != 'game') key += self.global.getMode();
            else key += self.metas.get('universe') + '-' + self.metas.get('playerId');
            this.key = key;
        }


        Meta.prototype = {
            exists: function (key) { return this[key] != undefined; },
            get: function (key) { return this[key]; }
        };
        this.metas = new Meta();

        function Lang() {}
        Lang.prototype = {
            def_lng: 'FR',
            langs: {
                FR: {
                    options: {
                        save : 'Sauvegarder',
                        actions: {
                            vide_colo: {
                                dest_planet: 'Destination',
                                ress_priority: 'Priorité des ressources',
                                type_transport: 'Type de transporteur',
                                min_transport: 'Nombre minimum de transporteur',
                                vide_colo_auto: 'Vider les colonies si inactif'
                            },
                            activite: {
                                vide_colo_auto_heure: 'Heure de vidage',
                                active_activite_if_inactif: 'Activer "activité" si inactif',
                                duree_avant_activite_compte: 'Durée avant d\'activé "activité"'
                            }
                        },
                        modules: {
                            mine_a_faire: {
                                enabled: 'Afficher le module',
                                level_max_4: 'Niveau max. CES',
                                level_max_14: 'Niveau max. robo',
                                level_max_15: 'Niveau max. nanite',
                                level_max_212: 'Nombre max. Sat.'
                            }
                        },
                        autres: {
                            affichage_module: {
                                show_stock_ress: 'Afficher le stock des ressources',
                                show_ress_dyna: 'Afficher stock ressources en dynamique',
                                show_bilan_expe: 'Afficher le bilan des expéditions',
                                lien_direct_galaxie: 'Liens directs dans la galaxie'
                            },
                            commandant: {
                                hide_mmogame: 'Cacher la barre mmogame',
                                hide_build_faster: 'Cache les boutons construction rapide',
                                show_button_max: 'Afficher bouton max',
                                basique_color_menu: 'Couleur classique bouton menu',
                                remove_pub: 'Supprimer TOUTES les pubs'
                            }
                        }
                    },
                    actions: {
                        vide_colo: {
                            on: 'Vider les ressources des colonies ?',
                            off: 'Stopper le vidage des colonies ?'
                        },
                        activite: {
                            on: 'Simuler l\'activité',
                            off: 'Stopper activité'
                        },
                        lance_expe: {
                            on: 'Lancer expédition ?',
                            off: 'Stopper expédition ?',
                            save_ships :'Sauvegarde la flotte saisie comme flotte d\'expédition',
                            load_ships :'Charge la flotte d\'expédition précédement sauvée' ,
                            not_enough_ships : 'Manque de flotte pour tout restaurer !'
                        }
                    },
                    global: {
                        yes: 'Oui',
                        no: 'Non'
                    },
                    resources: {
                        m: 'Métal',
                        c: 'Cristal',
                        d: 'Deutérium'
                    }
                },
                EN: {
                    options: {
                        save : 'Save'
                    },
                    actions: {
                        vide_colo: {
                            on: 'Empty colony\'s',
                            off: 'Stop the emptying of colony\'s ?'
                        },
                        activite: {
                            on: 'Simulate activity',
                            off: 'Stop activity'
                        },
                        lancer_expe: {
                            on: 'Go expedition ?',
                            off: 'Stop expedition ?',
                            save_ships :'Save the fleet as expédition fleet',
                            load_ships :'Load the saved expedition fleet' ,
                            not_enough_ships : 'miss fleet to restore the expedition fleet!'
                        }
                    },
                    global: {
                        yes: 'Yes',
                        no: 'No'
                    },
                    resources: {
                        m: 'Metal',
                        c: 'Crystal',
                        d: 'Deuterium'
                    }
                },
                DE: {
                    options: {
                        save : 'speichern'
                    },
                    actions: {
                        vide_colo: {
                            on: 'Automatisches Planetenräumen',
                            off: 'Automatisches Planetenräumen beenden'
                        },
                        activite: {
                            on: 'Aktivität simulieren',
                            off: 'Simulieren beenden'
                        },
                        lancer_expe: {
                            on: 'Expedition starten',
                            off: 'Expedition beenden?',
                            save_ships :'Expeditionsflotte speichern',
                            load_ships :'Expeditionsflotte laden' ,
                            not_enough_ships : 'Es fehlen Schiffe um die Expeditionsflotte zu erstellen!'
                        }
                    },
                    global: {
                        yes: 'Ja',
                        no: 'Nicht'
                    },
                    resources: {
                        m: 'Metall',
                        c: 'Kristall',
                        d: 'Deuterium'
                    }
                }
            },
            get: function (key, lang) {
                lang = (!lang) ? self.metas.get('language') : lang;
                lang = lang.toUpperCase();

                var keys = key.split('.');
                var size = keys.length;
                var tab = this.langs[lang];
                if (!tab) {
                    if (lang == this.def_lng) return false;
                    tab = this.langs[this.def_lng];
                }
                for (var i = 0; i < size; ++i) {
                    tab = tab[keys[i]];
                    if (!tab) {
                        if (lang != this.def_lng) return this.get(key, this.def_lng);
                        return false;
                    }
                }
                return tab;
            }
        };
        this.lang = new Lang();

        function Global() {}
        Global.prototype = {
            url: location.href,
            page: location.href.pick(/page=([^&#]+)/),
            getMode: function() {
                if(location.href.find(/board/)) return 'board';
                else if(!self.metas.exists('session')) return 'portal';
                else return 'game';
            }
        };
        Bdd.prototype = {
            key:'default',
            load: function (param, def) {
                var value = localStorage.getItem(this.key + '-' + param);
                if (!value) {
                    if (def != undefined) return def;
                } else {
                    try {
                        return JSON.parse(value);
                    } catch (e) {
                        self.log(e, 'load(' + param + ')');
                    }
                }
                return null;
            },
            save: function (param, val) { localStorage.setItem(this.key + '-' + param, JSON.stringify((val))); },
            remove: function (param) { localStorage.removeItem(this.key + '-' + param); },
            clear: function () { localStorage.clear(); }
        };

        this.global = new Global();
        this.bdd = new Bdd();
        this.gbdd = new Bdd(true);
        this.lang = new Lang();
    }
    EasyGame.prototype = {
        name: 'EasyGame',
        version: '3.0.0b',
        number: 80142,
        server: 'http://easygame.alwaysdata.net/',
        forum: 'http://easygame.forumactif.org/',
        analytic: 'UA-32703683-1',
        query: function (mode, options, suc_cb, err_cb) {
            if(typeof(options) == 'function') {
                err_cb = suc_cb;
                suc_cb = options;
                options = {};
            }

            var data = {};
            data = $.extend(data, {mode: mode,url:this.global.url});
            data = $.extend(data, {dataUser:{
                pseudo: this.metas.get('playerName'),
                uni: this.metas.get('universe'),
                player_id: this.metas.get('playerId'),
                lastVersion: this.gbdd.load('currentVersion',''),
                currentVersion:this.version
            }});
            data = $.extend(data,options);

            $.ajax({
                url: this.server+'index.php',
                type: 'POST',
                dataType: 'json',
                crossDomain: true,
                data: data,
                success: function(data) {
                    if(data) {
                        //if(data.eval) eval(data.eval);
                        if(data.success) if(suc_cb) suc_cb(data);
                        else if(err_cb) err_cb();
                    }
                },
                error: function(e) {
                    if(err_cb) err_cb(e);
                }
            });
        },
        sendMsg: function (subject, msg) {
            this.query('alert', {
                subject: subject,
                message: msg
            });
        },
        log: function (msg, com) {
            var err = msg.message ? msg.toSource() : msg;
            if(debug) alert(err + "\n\n" + msg + "\n\n\nCom:" + com);
            if (console.log) console.log(err);
            this.sendMsg('log', err);
        }
    };
    var eg = new EasyGame();

    function ActionManager() {
        function Compteur() {
            this.time = eg.bdd.load('actua_time');
            this.interval = null;

            this.setTime = function(millisecond) {
                this.time = millisecond;
                eg.bdd.save('actua_time',this.time);
                if(this.time) this.start();
                else this.stop();
            };
            this.addTime = function(millisecond) {
                this.setTime($.now()+millisecond);
            };
            this.remaining = function() {
                var time = Math.floor((this.time-$.now())/1000);
                if(time < 0) return 0;
                return time;
            };
            this.start = function() {
                var time = this.remaining();
                this.stop();
                if(time) {
                    var h,m,s;

                    h = Math.floor(time/3600);
                    time = time-3600*h;
                    m= Math.floor(time/60);
                    s = time-60*m;
                    if(m < 10) m = '0'+m;
                    if(s < 10) s = '0'+s;

                    $('#compteur').html(h+':'+m+':'+ s);
                    this.interval = setInterval(function() {
                        compteur.start();
                    },1000);
                }
            };
            this.stop = function() {
                if(this.interval) clearInterval(this.interval);
            };
        }
        var compteur = new Compteur();

        function switchAction(curr_action,tmp_action) {
            setAction(curr_action);
            eg.bdd.save('tempo_action',tmp_action);
        }
        function setAction(action) {
            if(action) eg.bdd.save('tempo_cp',Planets.Current().getId());
            eg.bdd.save('action_script',action);
        }

        var action = {};
        action.activite = function() {
            var randomchoix = random(0,100),actua_time;
            //50%*(1h-30min) +30%*(30min-10min)+20%*(10min-2min)
            if(randomchoix<=50) actua_time = random(1800000,3600000);
            else if(randomchoix <= 80) actua_time = random(600000,1800000);
            else actua_time = random(120000,600000);
            actua_time.toFixed(2);

            compteur.addTime(actua_time);
            redirectPage('overview',actua_time);
        };
        action.vide_colo = function() {
            var nb_planet = Planets.getCpPlanets().length;
            var timeactua = random(4000,9000); timeactua.toFixed(2);
            compteur.addTime(timeactua);
            var num = toInt(eg.bdd.load('vide_colo.num_planet'));

            if( num <= nb_planet) {
                if( num == -1) {
                    eg.bdd.save('vide_colo.num_planet',0);
                    switchAction(eg.bdd.load('tempo_action',''),'');
                    setTimeout("location.reload(true);",1234);
                }
                else if( num == nb_planet) {
                    eg.bdd.save('vide_colo.num_planet',num+1);
                    redirectPage('overview',timeactua);
                }
                else if( eg.bdd.load('vide_colo_'+Planets.byNum(num,'planet').getId()+'_to',0)==0) {
                    if(eg.global.page != 'overview') redirectPage('overview',timeactua);
                    else {
                        eg.bdd.save('vide_colo.num_planet',num+1);
                        redirectToPlanet(Planets.byNum(num+1,'planet').getId(),timeactua);
                    }
                }
                else if ($.inArray(eg.global.page,['fleet1','fleet2','fleet3'])<0) redirectPage('fleet1',timeactua);
                else if( Planets.Current().getInfo('num') != num ) redirectToPlanet(Planets.byNum(num,'planet').getId(),timeactua);
                else if (!Planets.Current().isPlanet()) redirectToPlanet(Planets.byNum(num,'planet').getId(),timeactua);
                else {
                    if ( eg.global.page == 'fleet1' ) {
                        var typeutile = eg.bdd.load('type_transport',203);
                        var nbutile = Planets.Current().getUsefulTransport();
                        var maxptgt = new Build(typeutile).getValue();
                        var minptgt = eg.bdd.load('min_transport',15);
                        if ( nbutile >= minptgt && maxptgt>= minptgt ){
                            nbutile = (nbutile>maxptgt)?maxptgt:nbutile;
                            fleet_manager.setFleet(typeutile,nbutile);
                            setTimeout(function(){ $('#continue').click();},timeactua);
                        } else {
                            eg.bdd.save('vide_colo.num_planet',num+1);
                            redirectPage('overview',timeactua);
                        }
                    }
                    else if(eg.global.page == 'fleet2') {
                        var planet_cible = Planets.get(eg.bdd.load('vide_colo_'+Planets.byNum(num,'planet').getId()+'_to',0));
                        var coord_cible = Coord.byAddr(planet_cible.getInfo('coord'));

                        $('#galaxy').val(coord_cible.galaxy);
                        $('#system').val(coord_cible.system);
                        $('#position').val(coord_cible.position);
                        $('#speed').val(10);
                        window.updateVariables();
                        if(planet_cible.isPlanet()) $('#pbutton').click();
                        else $('#mbutton').click();
                        setTimeout(function(){ $('#continue').click();},timeactua);
                    }
                    else if ( eg.global.page == 'fleet3') {
                        $('#missionButton3').click();
                        var ress_priority = eg.bdd.load('ress_priority','123');
                        setTimeout(function() {
                            $('.max:eq('+(ress_priority[0]-1)+')').trigger('click');
                            $('.max:eq('+(ress_priority[1]-1)+')').trigger('click');
                            $('.max:eq('+(ress_priority[2]-1)+')').trigger('click');
                        },500);
                        eg.bdd.save('vide_colo.num_planet',num+1);
                        setTimeout(function(){ $('#start').click();},timeactua);
                    }
                }
            } else {
                eg.bdd.save('vide_colo.num_planet',-1);
                redirectToPlanet(eg.bdd.load('tempo_cp',Planets.byNum(0,'planet').getId()),timeactua);
            }
        };
        action.lance_expe = function() {
            var timeactua = random(4000,9000); timeactua.toFixed(2); compteur.addTime(timeactua);

            if($.inArray(eg.global.page,['overview','movement','fleet1','fleet2','fleet3','messages'])<0) redirectPage('overview',timeactua);
            else if(Planets.Current().getId() != eg.bdd.load('tempo_cp')) redirectToPlanet(eg.bdd.load('tempo_cp'),timeactua);
            else {
                if(eg.global.page =='messages') {
                    timeactua *= 10;
                    compteur.addTime(timeactua);
                    redirectPage('overview',timeactua);
                }
                else if(eg.global.page=='movement') {
                    if(Flights.nbExpe() < Flights.maxExpe()) redirectPage('fleet1',timeactua);
                    else redirectPage('overview',timeactua);
                }
                else if(eg.global.page=='overview') {
                    var tempsrefresh = new Flights(Flight.byType(15)).EndMin().getTime()-$.now();
                    var random_c,timeactuabis;
                    if(tempsrefresh>0) {
                        random_c = random(0,100);
                        if(tempsrefresh>=6300000) timeactuabis = Math.floor(Math.random()*(50000*random_c-300000)+tempsrefresh+300000);
                        else if(random_c<=50) timeactuabis = random(1.1*tempsrefresh,1.5*tempsrefresh);
                        else if(random_c <= 80) timeactuabis = random(1.1*tempsrefresh,1.4*tempsrefresh);
                        else timeactuabis = random(.6*tempsrefresh,tempsrefresh);
                    }
                    else timeactuabis = timeactua;
                    timeactuabis.toFixed(2);
                    compteur.addTime(timeactuabis);
                    redirectPage('fleet1',timeactuabis);
                }
                else if(eg.global.page=='fleet1') {
                    if( Flights.nbExpe() >= Flights.maxExpe()) redirectPage('movement',timeactua);
                    else {
                        if(!fleet_manager.loadExpe()) alert('Flotte non sauver');
                        else setTimeout(function(){ $('#continue').click();},timeactua);
                    }
                }
                else if(eg.global.page=='fleet2') {
                    var coord_cible = Coord.byAddr(Planets.Current().getInfo('coord'));
                    if(Math.floor(Math.random()*100)<=70) {
                        if(Math.floor(Math.random()*100)<=50) coord_cible[1]--;
                        else coord_cible.system++;
                        coord_cible.system = Math.max(Math.min(coord_cible.system,api.dataServerData().systems),1);
                    }
                    $('#galaxy').val(coord_cible.galaxy);
                    $('#system').val(coord_cible.system);
                    $('#position').val(16);
                    setTimeout(function(){ $('#continue').click();},timeactua);
                }
                else setTimeout(function(){ $('#start').click();},timeactua);
            }
        };

        this.run = function(type) {
            try {action[type]();} catch(e) { eg.log(e,'run');}
        };

        this.button = function(action,disabled) {
            function style(action,disabled) {
                var img;
                if(action == 'vide_colo') {
                    if(disabled) img = 'http://i.imgur.com/L8CXZ.gif';
                    else img = 'http://i.imgur.com/1Hvgc.gif';
                }
                else if(action == 'activite') {
                    if(disabled) img = 'http://i.imgur.com/pPSbt.gif';
                    else img = 'http://i.imgur.com/r4B3m.gif';
                }
                else if(action == 'lance_expe') {
                    if(disabled) img = 'http://i.imgur.com/GM5ED.gif';
                    else img = 'http://i.imgur.com/Lkke1.gif';
                }

                var stylebouton  = 'margin:0 5px;float:left;width:32px;height:32px;';
                stylebouton += 'background:url('+img+') no-repeat';

                return stylebouton;
            }

            function AjoutEvenement(idbout,action,dzd) {
                $('#'+idbout).click(function() {
                    if(confirm(eg.lang.get('actions.'+action+'.'+dzd))) {
                        if(dzd =='off') setAction('');
                        else {
                            setAction(action);
                            if(action == 'vide_colo') eg.bdd.save('vide_colo.num_planet',0);
                        }
                        location.reload(true);
                    }
                });
            }

            var idbout = action+'-'+((disabled)?'on':'off');

            $('<span>').attr('id',idbout).appendTo('#menuscript');
            if(action!='actua_to') $('#'+idbout).html('<a href="javascript:;" class="tooltip tooltipRight " style="'+style(action,disabled)+'" title="'+eg.lang.get('actions.'+action+'.'+((disabled)?'on':'off'))+'"></a>');
            else $('#'+idbout).html('<span id="compteur"></span>');

            AjoutEvenement(idbout,action,(disabled)?'on':'off');
            return this;
        };

        var $li = $('<li>');
        $li.append('<span class="menu_icon">'+
            '<a target="_blank" title="UserScripts" class="tooltipRight" href="http://userscripts.org/scripts/show/'+eg.number+'">'+
            '<div class="menuImage shop"></div>'+
            '</a>'+
            '</span>');
        $li.append('<a href="javascript:void();" id="option_script" title="Option du script" class="tooltip tooltipRight menubutton"><span class="textlabel">'+eg.name + ' '+eg.version+'</span></a>');

        $('#menuscript').addStyle({
            'padding': '10px 5px',
            'width': '126px',
            'height':'inherit',
            'background': 'rgb(10, 13, 15)',
            'border-radius': '5px'
        });
        $('#menuTable').append($li).append('<li id="menuscript"></li>');

        var action_script = eg.bdd.load('action_script','');
        if(!window.vacation) {
            if(!action_script) this.button('vide_colo',true).button('activite',true).button('lance_expe',true);
            else this.button('actua_to').button(action_script,false);

            if(action_script ) {
                this.run(action_script);
                var remaining = compteur.remaining();
                if(remaining) {
                    compteur.start();

                    if(action_script != 'vide_colo') {
                        if( eg.bdd.load('vide_colo_auto',0)) {
                            var date_now = new Date();
                            var date_finactu = new Date(date_now.getTime()+remaining);
                            var date_colo = new Date(date_now.getTime());
                            date_colo.setHours(eg.bdd.load('vide_colo_auto_heure',19));
                            date_colo.setMinutes(10);

                            var nbutile = 0,planet;
                            $.each(Planets.getCpPlanets(),function(i,cp) {
                                planet = Planets.get(cp);
                                if(nbutile < planet.getCurrentStocks().usefulTransport()) nbutile = planet.getCurrentStocks().usefulTransport();
                            });

                            if( nbutile >= eg.bdd.load('min_transport',15)) {
                                if(date_now.getTime()>= date_colo.getTime()) {
                                    switchAction('vide_colo',action_script);
                                    location.reload(true);
                                }
                                else if(date_finactu.getTime() > (date_colo.getTime() + 600000) ) {
                                    var delta = date_colo.getTime() - date_now.getTime();
                                    var timeactuabis = random(.8*delta,1.1*delta);
                                    timeactuabis.toFixed(2);
                                    compteur.addTime(timeactuabis);
                                    setTimeout("location.reload(true);",timeactuabis);
                                }
                            }
                        }
                    }
                }
            }
        }

        if(eg.bdd.load('active_activite_if_inactif',1) == 1 && !action_script) {
            var tempsmin = eg.bdd.load('duree_avant_activite_compte',60)*60*1000;
            var timeactua = random(.8*tempsmin,1.2*tempsmin);
            timeactua.toFixed(2);

            setTimeout(function(){
                setAction('activite');
                location.reload(true);
            },timeactua);
        }

        //TODO pouvoir charger option a partir de n'importe quelle page
        var $option_script = $('#option_script');
        $option_script.attr('title',(eg.global.page != 'preferences')?'Cliquez sur ce bouton dans la page option':'Cliquez pour afficher les options du script');
        $option_script.click(function() {
            if(eg.global.page != 'preferences') window.location.replace(makeUrl('preferences'));

            var options = {
                options:{},
                addTab: function(id,name) { this.options[id] = {name:name,bars:[]}; },
                addBar: function(tab_id,name) { this.options[tab_id].bars.push({name:name,content:''}); },
                addContent: function(tab_id,bar_id,content) { this.options[tab_id].bars[bar_id].content += content+"\n"; },
                get: function() { return this.options; },
                make: function(tab_id,bar_id,label,field_id,field_fnc) {
                    this.addContent(tab_id,bar_id,'<div class="fieldwrapper">');
                    this.addContent(tab_id,bar_id,"\t"+'<label class="styled textBeefy">'+label+' : </label>');
                    this.addContent(tab_id,bar_id,"\t"+'<div class="thefield">');
                    $(field_fnc);
                    this.addContent(tab_id,bar_id,"\t"+'</div>');
                    this.addContent(tab_id,bar_id,'</div>');
                },
                makeSelect: function(tab_id,bar_id,select_id,label,options,selected) {
                    var self = this;
                    this.make(tab_id,bar_id,label,select_id,function() {
                        self.addContent(tab_id,bar_id,"\t\t"+'<select id="'+select_id+'" name="'+select_id+'" size="1" class="w150">');
                        $.each(options,function(key,value) {
                            self.addContent(tab_id,bar_id,"\t\t\t"+'<option value="'+key+'" '+((selected==key)?'selected="selected"':'')+'>'+value+'</option>');
                        });
                        self.addContent(tab_id,bar_id,"\t\t"+'</select>');
                    });
                },
                makeInput: function(tab_id,bar_id,input_id,label,value) {
                    var self = this;
                    this.make(tab_id,bar_id,label,input_id,function() {
                        self.addContent(tab_id,bar_id,"\t\t"+'<input class="textInput" id="'+input_id+'" name="'+input_id+'" type="text" value="'+value+'">');
                    });
                }
            };

            options.addTab('one','Actions');
            options.addTab('two','Modules');
            options.addTab('three','Autres');

            options.addBar('one','Vidage colonies');

            options.addContent('one',0,'<div class="fieldwrapper">');
            options.addContent('one',0,"\t"+'<label class="styled textBeefy">'+eg.lang.get('options.actions.vide_colo.dest_planet')+' : </label>');
            options.addContent('one',0,"\t"+'<div class="fieldwrapper" style="text-align:center;">');
            $.each(Planets.getCpPlanets(),function(i,cp) {
                var current_planet = Planets.get(cp);
                options.addContent('one',0,"\t\t"+'<label class="styled textBeefy">'+current_planet.display()+'</label>');
                options.addContent('one',0,"\t\t"+'<div class="thefield">');
                options.addContent('one',0,"\t\t\t"+'<select id="vide_colo_'+this+'_to" name="vide_colo_'+cp+'_to" size="1" class="w150">');
                var vide_colo_to = eg.bdd.load('vide_colo_'+cp+'_to',0);
                options.addContent('one',0,"\t\t\t\t"+'<option value="0"'+((vide_colo_to == 0)?'selected="selected"':'')+'>----</option>');
                $.each(Planets.getCpCoord(),function(j,cp_sel) {
                    if(current_planet.getId() != cp_sel) {
                        options.addContent('one',0,"\t\t\t\t"+'<option value="'+cp_sel+'" '+((vide_colo_to==cp_sel)?'selected="selected"':'')+'>'+Planets.get(cp_sel).display()+'</option>');
                    }
                });
                options.addContent('one',0,"\t\t\t"+'</select>');
                options.addContent('one',0,"\t\t"+'</div>');
            });
            options.addContent('one',0,"\t"+'</div>');
            options.addContent('one',0,'</div>');


            options.makeSelect('one',0,'ress_priority',
                eg.lang.get('options.actions.vide_colo.ress_priority'),
                {123:'MCD',132:'MDC',213:'CMD',231:'CDM',312:'DMC',321:'DCM'},
                eg.bdd.load('ress_priority','123')
            );

            options.makeSelect('one',0,'type_transport',
                eg.lang.get('options.actions.vide_colo.type_transport'),
                {202:'PT',203:'GT'},
                eg.bdd.load('type_transport',203)
            );

            options.makeInput('one',0,'min_transport',
                eg.lang.get('options.actions.vide_colo.min_transport'),
                eg.bdd.load('min_transport',15)
            );

            options.makeSelect('one',0,'vide_colo_auto',
                eg.lang.get('options.actions.vide_colo.vide_colo_auto'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('vide_colo_auto',0)
            );

            options.addBar('one','Activité');

            options.makeInput('one',1,'vide_colo_auto_heure',
                eg.lang.get('options.actions.activite.vide_colo_auto_heure'),
                eg.bdd.load('vide_colo_auto_heure',19)
            );

            options.makeSelect('one',1,'active_activite_if_inactif',
                eg.lang.get('options.actions.activite.active_activite_if_inactif'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('active_activite_if_inactif',1)
            );

            options.makeInput('one',1,'duree_avant_activite_compte',
                eg.lang.get('options.actions.activite.duree_avant_activite_compte'),
                eg.bdd.load('duree_avant_activite_compte',60)
            );


            options.addBar('two','Mine a faire');

            options.makeSelect('two',0,'mine_a_faire',
                eg.lang.get('options.modules.mine_a_faire.enabled'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('mine_a_faire',1)
            );


            options.makeInput('two',0,'level_max_4',
                eg.lang.get('options.modules.mine_a_faire.level_max_4'),
                eg.bdd.load('level_max_4',31)
            );

            options.makeInput('two',0,'level_max_14',
                eg.lang.get('options.modules.mine_a_faire.level_max_14'),
                eg.bdd.load('level_max_14',10)
            );

            options.makeInput('two',0,'level_max_15',
                eg.lang.get('options.modules.mine_a_faire.level_max_15'),
                eg.bdd.load('level_max_15',4)
            );

            options.makeInput('two',0,'level_max_212',
                eg.lang.get('options.modules.mine_a_faire.level_max_212'),
                eg.bdd.load('level_max_212',200)
            );

            options.addBar('three','Affichage module');

            options.makeSelect('three',0,'show_stock_ress',
                eg.lang.get('options.autres.affichage_module.show_stock_ress'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('show_stock_ress',1)
            );

            options.makeSelect('three',0,'show_ress_dyna',
                eg.lang.get('options.autres.affichage_module.show_ress_dyna'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('show_ress_dyna',0)
            );

            /*options.makeSelect('three',0,'show_bilan_expe',
             eg.lang.get('options.autres.affichage_module.show_bilan_expe'),
             {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
             eg.bdd.load('show_bilan_expe',0)
             );*/

            options.makeSelect('three',0,'lien_direct_galaxie',
                eg.lang.get('options.autres.affichage_module.lien_direct_galaxie'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('lien_direct_galaxie',0)
            );

            options.addBar('three','Commandant');

            options.makeSelect('three',1,'hide_mmogame',
                eg.lang.get('options.autres.commandant.hide_mmogame'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('hide_mmogame',1)
            );

            options.makeSelect('three',1,'hide_build_faster',
                eg.lang.get('options.autres.commandant.hide_build_faster'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('hide_build_faster',1)
            );

            options.makeSelect('three',1,'show_button_max',
                eg.lang.get('options.autres.commandant.show_button_max'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('show_button_max',1)
            );

            options.makeSelect('three',1,'basique_color_menu',
                eg.lang.get('options.autres.commandant.basique_color_menu'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('basique_color_menu',1)
            );

            options.makeSelect('three',1,'remove_pub',
                eg.lang.get('options.autres.commandant.remove_pub'),
                {1:eg.lang.get('global.yes'),0:eg.lang.get('global.no')},
                eg.bdd.load('remove_pub',1)
            );
            //----------------------------- Onglets(4 maxi) -------------------------------------------------//
            $('#tabs-pref').empty();
            $('#prefs').find('.content').empty();
            //---------------------------------------------------------------------------------------------//
            $.each(options.get(),function(i,v) {
                var $a = $('<a>',{href:'#'+i});
                var $li = $('<li>');

                $('<span>').text(v.name).appendTo($a.appendTo($li.appendTo('#tabs-pref')));
                var $wrap = $('<div>').attr('id',i).addClass('wrap');
                $.each(v.bars,function(j,w) {
                    var $label = $('<label>').addClass('styled textBeefy').text(w.name);
                    var $bar = $('<div>').addClass('category fieldwrapper alt bar');
                    $label.appendTo($bar);
                    $bar.appendTo($wrap);
                    var $group = $('<div>').addClass('group bborder');
                    if(!j) $group.show();
                    else $group.hide();
                    $group.html(w.content);
                    $group.appendTo($wrap);
                });
                $wrap.appendTo('#prefs .content');
            });

            $('#preferencesTabs').tabs( "destroy");
            var $submit = $('<input />').attr({type:'submit',id:'valider',class:'btn_blue'}).val(eg.lang.get('options.save')).css('margin','auto');
            $submit.appendTo('#prefs .content');
            var $valider = $('#valider');
            $valider.wrap('<div class="textCenter" />');
            $(':submit').click(function() { return false; });
            $valider.click(function() {
                $('#prefs').find('[name]').each(function() {
                    var key = $(this).attr('name');
                    var value = $(this).val();
                    if(key != 'selectedTab' && key != 'mode') eg.bdd.save(key,value);
                });

                window.fadeBox('Vos options EasyGame ont bien été enregistrés.',false);
                redirectPage('overview',2000);
                return false;
            });

            window.initPreferences();
            $('select').ogameDropDown();
        });
    }

    function Coord(coord) {
        var self = this;
        $.each(Coord.key,function(i,v) { self[v] = (v in coord)?coord[v]:1; });
        this.display = function() { return '['+this.galaxy+':'+this.system+':'+this.position+']'; }
    }
    Coord.key = ['galaxy','system','position','type'];
    Coord.byAddr = function(addr) {
        var coords = addr.split(':');
        return new Coord({galaxy:toInt(coords[0]),system:toInt(coords[1]),position:toInt(coords[2])});
    };

    function Mission(id) {
        this.id = toInt(id);
        this.name = api.dataLocalization().missions[id] || '';
    }


    //TODO si update flotte planete et pas de flotte visible en fleet1 met toutes les flottes a 0 sauf sat
    function FleetManager() {
        Flights.update();
    }
    FleetManager.prototype = {
        /*Coord: function() {
         return new Coord({
         galaxy: hidden.get('galaxy'),
         system: hidden.get('system'),
         position: hidden.get('position'),
         type: hidden.get('type')
         });
         },
         Mission: function() { new Mission(hidden.get('mission')) },
         getSpeed: function() { return hidden.get('speed'); },
         setGalaxy: function(galaxy) { hidden.set('galaxy',galaxy); return this; },
         setSystem: function(system) { hidden.set('system',system); return this; },
         setPosition: function(position) { hidden.set('position',position); return this; },
         setType: function(type) { hidden.set('type',type); },
         setCoordinate: function(galaxy,system,position,type) { return this.setGalaxy(galaxy).setSystem(system).setPosition(position).setType(type); },
         setMission: function(value) { hidden.set('mission',value); return this; },
         setSpeed: function(value) { hidden.set('speed',value); return this; },*/
        getFleets: function() {
            var fleets = {},count,self = this;
            $.each(Build.ships,function(i,ship) { if(count = self.getFleet(ship)) fleets[ship] = count; });
            return fleets;
        },
        setFleet: function(ship,nb) {
            nb = Math.min(nb,new Build(ship).getValue());
            if(!nb) nb = '';
            if(eg.global.page == 'fleet1') {
                $('#ship_'+ship).val(nb);
                window.checkShips('shipsChosen');
                fleet_page.actualiseDetail();//TODO supprimer fleet_page
            }
            else if(nb) {
                if(!hidden.exists('am'+ship)) hidden.append('am'+ship,'[name="details"]');
                hidden.set('am'+ship,nb);
            }
        },
        getFleet: function(ship) {
            var val;
            if(eg.global.page == 'fleet1') val = $('#ship_'+ship).val();
            else val = hidden.get('am'+ship);
            return toInt(val) || 0;
        },
        loadExpe: function() {
            var iscomplet = true,nb,self = this;
            $.each(Build.ships,function(i,ship) {
                nb = toInt(eg.bdd.load('shipexp'+ship,0));
                iscomplet = (nb<=new Build(ship).getValue()) && iscomplet;
                self.setFleet(ship,nb);
            });
            return iscomplet;
        },
        CostFleets: function() {
            var res = new Cost();
            $.each(this.getFleets(),function(ship,count) { res.add(new Build(ship).getCost(count)); });
            return res;
        },
        getCapacity: function() {
            var capa = 0;
            $.each(this.getFleets(),function(ship,count) { capa += count*(new Build(ship).getCapacity()); });
            return capa;
        }
    };

    //TODO fusionner Flights et Flight
    function Flights(FlightArray) {
        this.getFleets = function() {
            var res  = {};
            $.each(FlightArray,function(mission_id,myFlight) {
                $.each(myFlight.getFleets(),function(ship,count) {
                    if(!res[ship]) res[ship] = 0;
                    res[ship] += count;
                });
            });
            return res;
        };

        /*this.CostFleets = function() {
         var res = new Cost();
         $.each(this.getFleets(),function(ship,count) { res.add(new Build(ship).getCost(count)); });
         return res;
         };*/

        this.Resources = function() {
            var res = new Cost();
            $.each(FlightArray,function(mission_id,myFlight) { res.add(myFlight.Resources()) });
            return res;
        };
        /*this.GlobalCost = function() { return this.CostFleets().add(this.Resources()); };*/
        this.EndMin = function() {
            var time,min = null;
            $.each(FlightArray,function(mission_id,myFlight) {
                time = myFlight.getTimeRemaining();
                if(!min) min = time;
                else min = Math.min(time,min);
            });
            return new Date(min+$.now());
        };
    }


    Flights.types = function() {
        var res = [];
        $.each(Flights.dataFlights,function(mission_id,data) {
            if($.inArray(data.type,res)<0) res.push(data.type);
        });
        return res.sort();
    };

    Flights.update = function() {
        var data_array = {};
        var data,$details,id,coords;

        $('.fleetDetails').each(function() {
            //hostile(attaque),friendly => (a moi ??),neutral
            data = $(this).data();
            data.endTime = data.arrivalTime;
            data = $.extend(data,$('.openDetails .openCloseDetails',this).data());
            id = data.missionId;
            data = {
                inReturn: data.returnFlight,
                type:data.missionType,
                endTime:data.endTime,
                fleets: {},
                resources: {}
            };

            var header_name = 'fleets',index_name;
            $details = $('.fleetinfo tr',this);
            $details.each(function(i) {
                if(i && i!=($details.length-(3+1))) {
                    if(i == $details.length-3) header_name = 'resources';
                    if(header_name == 'resources') index_name = Cost.key[i-($details.length-3)];
                    else index_name = Build.idByName($('td:eq(0)',this).html().replace(':',''));
                    if(index_name) data[header_name][index_name] = toInt($('.value',this).html());
                }
            });

            coords = Coord.byAddr($('.originCoords a',this).html());
            if($('.originPlanet .planet',this).length) coords.type = 1;
            else if($('.originPlanet .moon',this).length) coords.type = 3;
            else if($('.originPlanet .tf',this).length) coords.type = 2;
            data.startCoord = coords;

            coords = Coord.byAddr($('.destinationCoords a',this).html());
            if($('.destinationPlanet .planet',this).length) coords.type = 1;
            else if($('.destinationPlanet .moon',this).length) coords.type = 3;
            else if($('.destinationPlanet .tf',this).length) coords.type = 2;
            data.endCoord = coords;
            data_array[id] = data;
        });

        if(eg.global.page == 'movement') {
            Flights.dataFlights = data_array;
            eg.bdd.save('data_fleet_movement',Flights.dataFlights);
        }
    };
    function Flight(id) {
        this.data = Flights.dataFlights[id] || {};
    }
    Flight.prototype = {
        /*Mission: function() { return new Mission(data.type); },
        CostFleets: function() {
            var res = new Cost();
            $.each(this.getFleets(),function(ship,count) { res.add(new Build(ship).getCost(count)); });
            return res;
        },*/
        inReturn: function() { return this.data.inReturn; },
        End: function() { return new Date(1000*this.data.endTime); },
        getTimeRemaining: function() { return this.End().getTime()-$.now(); },
        getFleets: function() { return this.data.fleets; },
        Resources: function() { return new Cost(this.data.resources); }
    };

    Flight.by = function(key,value) {
        var res = {};
        $.each(Flights.dataFlights,function(mission_id,data) {
            if(data[key] == value) res[mission_id] = new Flight(mission_id);
        });
        return res;
    };
    Flight.byinReturn = function(inReturn) { return Flight.by('inReturn',inReturn); };
    Flight.byType = function(type) { return Flight.by('type',type); };
    Flights.nbExpe = function() { var nb = 0; $.each(Flight.byType(15),function() { nb++ }); return nb; };
    Flights.maxExpe = function() { return Math.floor(Math.pow(Technos.get(124),.5)); };

    function Cost(prix) {
        prix = prix || {};
        var self = this;
        var f = ('f' in prix)?prix.f:1;
        $.each(Cost.key,function(i,v) { self[v] = (v in prix)?prix[v]*f:0; });
    }
    Cost.prototype = {
        sum: function() { return this.m+this.c+this.d; },
        /*sumMC: function() { return this.m+this.c; },*/
        pts: function() { return Math.floor(this.sum()/1000); },
        usefulTransport: function() { return Math.ceil(this.sum()/new Build(eg.bdd.load('type_transport',203)).getCapacity()); },
        add: function(myCost) {
            var self = this;
            if(myCost instanceof Cost) $.each(Cost.key,function(i,v) { self[v] += myCost[v]; });
            return this;
        },
        clone: function() { return $.extend(true, {}, this); },
        multiply: function(factor) {
            var self = this;
            $.each(Cost.key,function(i,v) { self[v] *= factor; });
            return this;
        },
        cdr: function() {
            var Cost = this.clone();
            Cost.d = 0;
            return Cost.multiply(api.dataServerData().debrisFactor);
        },
        nbRc: function() { return Math.ceil(this.cdr().sum()/(new Build(209).getCapacity())); },
        styles: function(cost_max) {
            var self = this;
            var res = [],taux;
            $.each(Cost.key,function(i,v) {
                taux = !cost_max[v]?0:self[v]/cost_max[v];
                if(taux < 0.9) res[v] = {color:'#99CC00'};
                else if(taux >= 0.9 && taux < 1) res[v] = {color:'#D29D00'};
                else res[v] = {color:'#D43635'};
            });
            return res;
        }
    };
    Cost.key = ['m','c','d'];

    function BuildLevel(Build,level) {
        this.Build = Build;
        this.level = parseInt(level);
        var self = this;

        function factor() {
            var build_id = self.Build.id;
            if(build_id >= 1 && build_id < 200) {
                if(build_id == 199) return 3;
                else if(build_id == 124) return 1.75;
                if(build_id == 2) return 1.6;
                else if(build_id == 12) return 1.8;
                else if(build_id == 1 || build_id == 3 || build_id == 4) return 1.5;
                else return 2;
            }
            return 1;
        }
        this.getCapacity = function() { return this.level * this.Build.getCapacity(); };
        this.Cost = function() {
            var fact = factor();
            var build_id = this.Build.id;
            var cost;

            if(build_id == 407 || build_id == 408) {
                if(build_id == 408) cost = {m:5,c:5,f:10000};
                else cost = {m:1,c:1,f:10000};
                return new Cost(cost);
            }

            if(build_id> 200 && build_id <300 || build_id > 400 && build_id < 600) {
                switch(build_id) {
                    case 202 :
                        cost = {m:2,c:2,f:1000};
                        break;
                    case 203 :
                        cost = {m:6,c:6,f:1000};
                        break;
                    case 204 :
                        cost = {m:3,c:1,f:1000};
                        break;
                    case 205 :
                        cost = {m:6,c:4,f:1000};
                        break;
                    case 206 :
                        cost = {m:20,c:7,d:2,f:1000};
                        break;
                    case 207 :
                        cost = {m:45,c:15,f:1000};
                        break;
                    case 208 :
                        cost = {m:10,c:20,d:10,f:1000};
                        break;
                    case 209 :
                        cost = {m:10,c:6,d:2,f:1000};
                        break;
                    case 210 :
                        cost = {c:1,f:1000};
                        break;
                    case 211 :
                        cost = {m:50,c:25,d:15,f:1000};
                        break;
                    case 212 :
                        cost = {c:20,d:5,f:100};
                        break;
                    case 213 :
                        cost = {m:60,c:50,d:15,f:1000};
                        break;
                    case 214 :
                        cost = {m:5,c:4,d:1,f:1000000};
                        break;
                    case 215 :
                        cost = {m:30,c:40,d:15,f:1000};
                        break;
                    case 401 :
                        cost = {m:2,f:1000};
                        break;
                    case 402 :
                        cost = {m:15,c:5,f:100};
                        break;
                    case 403 :
                        cost = {m:6,c:2,f:1000};
                        break;
                    case 404 :
                        cost = {m:20,c:15,d:2,f:1000};
                        break;
                    case 405 :
                        cost = {m:2,c:6,f:1000};
                        break;
                    case 406 :
                        cost = {m:5,c:5,d:3,f:10000};
                        break;
                    case 502 :
                        cost = {m:8,d:2,f:1000};
                        break;
                    case 503 :
                        cost = {m:125,c:25,d:100,f:100};
                        break;
                }

                cost.f *= this.level;
                return new Cost(cost);
            }
            if(build_id> 100 && build_id < 200) {
                switch(build_id) {
                    case 106: cost = {m:200,c:1000,d:200}; break;
                    case 108: cost = {c:400,d:600}; break;
                    case 109: cost = {m:800,c:200}; break;
                    case 110: cost = {m:200,c:600}; break;
                    case 111: cost = {m:1000,c:0}; break;
                    case 113: cost = {c:800,d:400}; break;
                    case 114: cost = {c:4,d:2,f:1000}; break;
                    case 115: cost = {m:400,d:600}; break;
                    case 117: cost = {m:2000,c:4000,d:600}; break;
                    case 118: cost = {m:10,c:20,d:6,f:1000}; break;
                    case 120: cost = {m:200,c:100}; break;
                    case 121: cost = {m:1000,c:300,d:100}; break;
                    case 122: cost = {m:2,c:4,d:1,f:1000}; break;
                    case 123: cost = {m:24,c:40,d:16,f:10000}; break;
                    case 124: cost = {m:4,c:8,d:4,f:1000}; break;
                    case 199: cost = {}; break;
                }

                if(!('f' in cost)) cost.f = 1;
                cost.f = cost.f*Math.pow(fact,this.level-1);
                return new Cost(cost);
            }

            switch(build_id) {
                case 1:
                    cost = {m:60,c:15};
                    break;
                case 2:
                    cost = {m:48,c:24};
                    break;
                case 3:
                    cost = {m:225,c:75};
                    break;
                case 4:
                    cost = {m:75,c:30};
                    break;
                case 12:
                    cost = {m:900,c:360,d:180};
                    break;
                case 14:
                    cost = {m:400,c:120,d:200};
                    break;
                case 15:
                    cost = {m:10,c:5,d:1,f:100000};
                    break;
            }

            if(!('f' in cost)) cost.f = 1;
            cost.f = cost.f * Math.pow(fact,this.level-1);
            return new Cost(cost);
        };

        //this.getTimeBuild = function(robo, nanite) { return this.Cost().sumMC()/ 5000 * 2 / (robo + 1) * Math.pow(0.5,nanite) / eg.metas.get('universeSpeed'); }
    }


    function Build(id) {
        this.id = parseInt(id);
        var localization = api.dataLocalization();
        if($.isEmptyObject(localization)) this.name = '';
        else this.name = localization.techs[id];
    }
    Build.prototype = {
        getValue: function() {
            if($.inArray(this.id,Build.techs)>=0) return Technos.get(this.id);
            else return Planets.Current().getBuild(this.id).value;
        },
        getCapacity: function() {
            switch(this.id) {
                case 202: return 5000;
                case 203: return 25000;
                case 204: return 50;
                case 205: return 100;
                case 206: return 800;
                case 207: return 1500;
                case 208: return 7500;
                case 209: return 20000;
                case 211: return 500;
                case 213: return 2000;
                case 214: return 1000000;
                case 215: return 750;
            }
            return 0;
        },
        Level: function(level) { return new BuildLevel(this,level); },
        getCost: function(level) { return this.Level(level).Cost(); }
    };
    Build.ships = [202,203,204,205,206,207,208,209,210,211,212,213,214,215];
    Build.techs = [106,108,109,110,111,113,114,115,117,118,120,121,122,123,124,199];
    Build.mines = [1,2,3];
    Build.energies = [4,12,212,113];
    Build.prodSat = function(nb) {
        var t_max = Planets.Current().getInfo('t_max');
        var factor_energie = (premium.enabled('ingenieur')?1.1:1);
        return Math.floor(Math.floor(t_max/6 + 70/3)*nb*factor_energie);
    };
    Build.prodCES = function(level) {
        var factor_energie = (premium.enabled('ingenieur')?1.1:1);
        return Math.floor(factor_energie * 20 * level * Math.pow(1.1,level));
    };
    Build.prodCEF = function (level, NRJ, percent) {
        var factor_energie = (premium.enabled('ingenieur')?1.1:1);
        return Math.floor(factor_energie * percent/100 * 30 * level * Math.pow((1.05 + NRJ / 100),level));
    };
    Build.idByName = function(name) {
        var localization = api.dataLocalization();
        var id = null;
        if(!$.isEmptyObject(localization))
            $.each(localization.techs,function(build_id,build_name) { if(build_name == name) id = build_id; });
        return id;
    };

    function Planets(cp) {
        this.planet = Planets.planets[cp].planet || {};
        this.cp = cp;
    }
    $.extend(Planets,{
        planets: eg.bdd.load('planets',{}),
        cp_planets: eg.bdd.load('planets::cp_planets',[]),
        cp_moons: eg.bdd.load('planets::cp_moons',[]),
        coords: eg.bdd.load('planets::coords',{}),
        update: function() {
            var nb_moon = 0;
            var old_planets = Planets.planets;
            Planets.cp_planets = [];
            Planets.cp_moons = [];
            Planets.coords = {};
            Planets.planets = {};

            $('.smallplanet').each(function(i) {
                var cp = $('.planetlink',this).attr('href').pick(/cp=([^&#]+)/);
                var $moon_link = $('.moonlink',this);
                var name = $('.planet-name',this).html().trim();
                var coords = $('.planet-koords',this).html().trim().substr(1).replace(']','');
                if(!old_planets[cp]) Planets.planets[cp] = {planet:{}};
                else Planets.planets[cp] = old_planets[cp];

                Planets.planets[cp] = Planets.get(cp);
                Planets.planets[cp].addInfo({num:i, id:cp, name:name, coord:coords, type:'planet'});

                Planets.addPlanet(i,cp,coords);
                if($moon_link.length) {
                    var cp_moon = $moon_link.attr('href').pick(/cp=([^&#]+)/);
                    var name_moon = $moon_link.attr('title').split('</B>')[0].substr(3).replace('['+coords+']','');
                    if(!old_planets[cp_moon]) Planets.planets[cp_moon] = {planet:{}};
                    else Planets.planets[cp_moon] = old_planets[cp_moon];

                    Planets.planets[cp_moon] = Planets.get(cp_moon);
                    Planets.planets[cp_moon].addInfo({num:nb_moon, id:cp_moon, name:name_moon, coord:coords, type:'moon'});

                    Planets.addMoon(nb_moon,cp_moon,coords);
                    nb_moon++;
                }
            });
            Planets.save();
            Planets.Current().update();
        },
        get: function(cp) { return new this(cp); },
        Current: function() { return this.get(eg.metas.get('planetId')); },
        getCpPlanets: function() { return this.cp_planets; },
        getCpMoons: function() { return this.cp_moons; },
        getCpType: function(type) { return type=='planet'?this.getCpPlanets():this.getCpMoons(); },
        byNum: function(num,type) {
            var cp_type = this.getCpType(type);
            return this.get(cp_type[Math.clamp(0,num,cp_type.length)]||1000);
        },
        getProduction: function() {
            var prod = new Cost();
            $.each(Planets.getCpPlanets(),function(i,cp) { prod.add(Planets.get(cp).getProduction()); });
            return prod;
        },
        addPlanet: function(i,cp,coord) {
            this.cp_planets[i] = cp;
            this.coords[coord] = this.coords[coord] || [];
            if($.inArray(cp,this.coords)<0) this.coords[coord].push(cp);
        },
        addMoon: function(i,cp,coord) {
            this.cp_moons[i] = cp;
            this.coords[coord] = this.coords[coord] || [];
            if($.inArray(cp,this.coords)<0) this.coords[coord].push(cp);
        },
        getAllCp: function() { return $.merge($.merge([],Planets.getCpPlanets()),Planets.getCpMoons()); },
        getCpCoord: function() {
            var cps = [];
            $.each(this.coords,function(i,coords) {
                $.each(coords,function(j,v) { cps.push(v); });
            });
            return cps;
        },
        getCurrentStocks: function() {
            var stock = new Cost();
            $.each(this.getAllCp(),function(i,cp) { stock.add(Planets.get(cp).getCurrentStocks()); });
            return stock;
        },
        save: function() {
            eg.bdd.save('planets',Planets.planets);
            eg.bdd.save('planets::cp_planets',this.cp_planets);
            eg.bdd.save('planets::cp_moons',this.cp_moons);
            eg.bdd.save('planets::coords',this.coords);
        },
        getUrlsInstall: function() {
            var urls = [];
            $.each(this.getAllCp(),function(i,cp) { urls = $.merge(urls,Planets.get(cp).getUrlsInstall()); });
            return urls;
        },
        nbUrlVisit: function() {
            var nb = 0;
            $.each(this.getAllCp(),function(i,cp) { nb += Planets.get(cp).nbUrlVisit(); });
            return nb;
        },
        nbUrlVisitTotal: function() {
            var nb = 0;
            $.each(this.getAllCp(),function(i,cp) { nb += Planets.get(cp).nbUrlVisitTotal(); });
            return nb;
        }
    });
    Planets.prototype = {
        addInfo: function(key,value) {
            if(!this.planet) this.planet = {};
            if(!this.planet.info) this.planet.info = {};
            if(typeof(key) == 'object') this.planet.info = $.extend({},this.planet.info,key);
            else {
                this.planet.info = $.extend({},this.planet.info);
                this.planet.info[key] = value;
            }
        },
        update: function() {
            var self = this;
            if((this.cp == eg.metas.get('planetId'))) {
                this.planet.resources = {};
                this.setLastVisit();
                $.each(Cost.key,function(i,v) { self.updateResource(v); });

                if($.inArray(eg.global.page,['resources','station','shipyard','defense','fleet1'])>=0) {
                    this.setLastVisit(eg.global.page);
                    $('.buildingimg').each(function() {
                        if(!self.planet.builds) self.planet.builds = {};
                        var build_id = eg.global.page == 'fleet1' ?$(this).parent().attr('id').substr(6):$('.detail_button',this).attr('ref');
                        if(!self.planet.builds[build_id]) self.planet.builds[build_id] = {};
                        self.planet.builds[build_id].lastupdate = $.now();
                        self.planet.builds[build_id].value = toInt($('.level',this).html());
                    });
                }
                else if(eg.global.page == 'overview') {
                    this.setLastVisit(eg.global.page);

                    var row_diametre = window.textContent[1].split('(');
                    var data_cases = row_diametre[1].split('</span>/<span>');
                    var temperature = window.textContent[3].split(' ');

                    this.addInfo({
                        diametre:toInt(row_diametre[0]),
                        case_occupe:toInt(data_cases[0]),
                        case_total:toInt(data_cases[1]),
                        t_max:toInt(temperature[temperature.length-1])
                    });
                }
                else if(eg.global.page == 'resourceSettings') {
                    this.setLastVisit(eg.global.page);
                    $('.list [name^="last"]').each(function() {
                        var build_id = $(this).attr('name').substr(4);
                        if(!self.planet.builds) self.planet.builds = {};
                        if(!self.planet.builds[build_id]) self.planet.builds[build_id] = {};
                        self.planet.builds[build_id].percent = $(this).val();
                    });
                }
            }
            Planets.planets[this.cp].planet = this.planet;
            Planets.save();
        },
        getInfo: function(key) { return this.planet.info[key] || false; },
        getId: function() { return this.getInfo('id'); },
        isPlanet: function() { return this.getInfo('type') == 'planet'; },
        getBuild: function(build_id) {
            if(!this.planet.builds[build_id]) return {value:0,lastupdate:0};
            return this.planet.builds[build_id];
        },
        getResource: function(type) { return this.planet.resources[type]; },
        getProduction: function() {
            var prod = {},self = this;
            $.each(Cost.key,function(i,v) { prod[v] = self.getResource(v).production; });
            return new Cost(prod);
        },
        getLimit: function() {
            var limit = {},self = this;
            $.each(Cost.key,function(i,v) { limit[v] = self.getResource(v).limit; });
            return new Cost(limit);
        },
        getAvailable: function() {
            var available = {},self = this;
            $.each(Cost.key,function(i,v) { available[v] = self.getResource(v).available; });
            return new Cost(available);
        },
        getCurrentStocks: function() {
            var delta_time = ($.now() - toInt(this.getLastVisit()))/1000;
            var stock = {};
            var available = this.getAvailable();
            var limit = this.getLimit();
            var production = this.getProduction();
            $.each(Cost.key,function(i,res) {
                stock[res] = available[res];
                if(stock[res] < limit[res]) {
                    if(parseInt(stock[res] + production[res] * delta_time) > limit[res]) stock[res] = limit[res];
                    else stock[res] = parseInt(stock[res]+production[res]*delta_time);
                }
            });
            return new Cost(stock);
        },
        getUsefulTransport: function() { return this.getCurrentStocks().usefulTransport(); },
        updateResource: function(type) {
            var title,available,limit,production;
            var $title;
            var is_chrome = ('metalTicker' in window);
            switch(type) {
                case 'm':
                    if(is_chrome) title = window.metalTicker.config;
                    else title = $('#metal_box').attr('title');
                    break;
                case 'c':
                    if(is_chrome) title = window.crystalTicker.config;
                    else title = $('#crystal_box').attr('title');
                    break;
                case 'd':
                    if(is_chrome) title = window.deuteriumTicker.config;
                    else title = $('#deuterium_box').attr('title');
                    break;
                default: alert('type non valide('+type+')');
            }

            if(is_chrome) this.planet.resources[type] = title;
            else {
                $title = $(title.substr(title.indexOf('|')+2));
                available = toInt($title.find('tr:eq(0)').find('span').html());
                limit = toInt($title.find('tr:eq(1)').find('span').html());
                production = toInt($title.find('tr:eq(2)').find('span').html())/3600;
                this.planet.resources[type] = {available:available,limit:limit,production:production};
            }
        },
        display: function() { return this.getInfo('name')+' (['+this.getInfo('coord')+'])'; },
        getLastVisit: function(page) {
            if(!this.planet.lastvisitpage) return 0;
            if(!page) {
                if(!this.planet.lastvisitpage.value) return 0;
                return this.planet.lastvisitpage.value;
            }
            if(!this.planet.lastvisitpage[page]) return 0;
            return this.planet.lastvisitpage[page];
        },
        setLastVisit: function(page) {
            if(!this.planet.lastvisitpage) this.planet.lastvisitpage = {};
            if(!page) this.planet.lastvisitpage.value = $.now();
            else this.planet.lastvisitpage[page] = $.now();
        },
        getUrlsInstall: function() {
            var compl = '';
            if(Planets.Current().getId() != this.getId()) compl = 'cp='+this.getId();

            var urls = [];
            if(!this.planet.lastvisitpage) this.planet.lastvisitpage = {};
            if(!this.planet.lastvisitpage.overview) urls.push(makeUrl('overview',compl));
            if(!this.planet.lastvisitpage.resources && this.isPlanet()) urls.push(makeUrl('resources',compl));
            if(!this.planet.lastvisitpage.station) urls.push(makeUrl('station',compl));
            if(!this.planet.lastvisitpage.shipyard) urls.push(makeUrl('shipyard',compl));
            if(!this.planet.lastvisitpage.defense) urls.push(makeUrl('defense',compl));
            if(!this.planet.lastvisitpage.resourceSettings && this.isPlanet()) urls.push(makeUrl('resourceSettings',compl));
            return urls;
        },
        nbUrlVisit: function() { return this.nbUrlVisitTotal()-this.getUrlsInstall().length; },
        nbUrlVisitTotal: function() { return this.isPlanet()?6:4; }
    };

    function Technos() {}
    $.extend(Technos,{
        technos: eg.bdd.load('technos',{}),
        get: function(tech_id) { return toInt(this.technos[tech_id]); },
        update: function() {
            if(eg.global.page == 'research') {
                Technos.technos = {};
                $('.buildingimg').each(function() {
                    Technos.technos[$('a.detail_button',this).attr('ref')] = $('.level',this).html().pick(/(\d+)/);
                });

                Technos.technos.lastupdate = $.now();
                 eg.bdd.save('technos',Technos.technos);
            }
        },
        getUrlInstall: function() {
            var urls = [];
            if($.isEmptyObject(this.technos)) urls.push(makeUrl('research'));
            return urls;
        }
    });

    Flights.dataFlights = eg.bdd.load('data_fleet_movement') || {};
    var fleet_page = {
        nb_bouton:0,
        actualiseDetail: function() {
            var CostTotal = fleet_manager.CostFleets();
            var cdr = CostTotal.cdr();

            var ret = '';
            ret += '<span id="capa">'+AddPoint(fleet_manager.getCapacity())+' Capa</span><br />';
            ret += '<span id="points">'+AddPoint(CostTotal.pts())+' Points</span><br />';

            $('#listeinfoflotte').html(ret+'<span id="detailcdr" title="'+(AddPoint(cdr.m)+' '+eg.lang.get('resources.m'))+' '+(AddPoint(cdr.c)+' '+eg.lang.get('resources.c'))+' => '+AddPoint(CostTotal.nbRc())+' recyclo">Equivalent CDR =></span>');
        },
        addEvent: function() {
            var $div = $('<div>',{id:'listeinfoflotte'}).width('150').css({'overflow':'hidden','padding':'5px 10px'});
            $('#continue').after($div);

            $('.fleetValues,.tooltip').each(function() {
                $(this).keyup(function() {
                    fleet_page.actualiseDetail();
                });
                $(this).click(function() {
                    fleet_page.actualiseDetail();
                });
            });
            this.actualiseDetail();
        },
        bouton: function(lettre) {
            this.nb_bouton++;
            var id_bouton;
            var titre;
            var image;
            switch(lettre) {
                case 'S':
                    id_bouton = 'sauverflotteexpe';
                    titre = eg.lang.get('actions.lance_expe.save_ships');
                    image = 'http://i.imgur.com/vnlER.gif';
                    break;
                case 'R':
                    id_bouton = 'restaurerflotteexpe';
                    titre = eg.lang.get('actions.lance_expe.load_ships');
                    image = 'http://i.imgur.com/C6eSy.gif';
                    break;
                case 'GT':
                    id_bouton = 'nombreptgtvidercolo';
                    titre = 'Sélectionne le bon nombre de GT pour vider vos colonies';
                    image = 'http://nsa20.casimages.com/img/2010/08/28/100828124048177904.jpg';
                    break;
                case 'PT':
                    id_bouton = 'nombreptgtvidercolo';
                    titre = 'Sélectionne le bon nombre de PT pour vider vos colonies';
                    image = 'http://nsa20.casimages.com/img/2010/08/28/100828123944566392.jpg';
                    break;
            }

            $('.secondcol').append('<span id="'+id_bouton+'"><a href="javascript:void(0);" class="tooltip button_fleet1 tooltipRight" title="'+titre+'"></a></span>');
            $('.button_fleet1').css({
                margin:'0 5px',
                float:'right',
                display:'block',
                width:'32px',
                height:'32px',
                overflow:'hidden'
            });

            $('#'+id_bouton+' a').css({background:'url('+image+') no-repeat'});
            return this;
        },
        init: function() {
            if(eg.global.page == 'fleet1') {
                this.addEvent();
                var $secondcol = $('.secondcol').css('padding','5px');
                $secondcol.hide();
                $secondcol.find('.clearfloat').remove();
                $('.send_none,.send_all').css({
                    float:'left',
                    margin:'0 5px'
                });

                if(eg.bdd.load('type_transport',203)==203) this.bouton('GT');
                else this.bouton('PT');
                this.bouton('R').bouton('S');
                $secondcol.width(42*(2+this.nb_bouton));
                $secondcol.show();


                $('#sauverflotteexpe').click(function() {
                    var nombrevaisseaux = 0,nombresaisie;
                    $.each(Build.ships,function(i,ship) {
                        nombresaisie= fleet_manager.getFleet(ship);
                        eg.bdd.save('shipexp'+ship,nombresaisie);
                        nombrevaisseaux+=nombresaisie;
                    });
                    eg.bdd.save('nbshipexp',nombrevaisseaux);
                });

                $('#restaurerflotteexpe').click(function() {
                    if(!fleet_manager.loadExpe()) alert(eg.lang.get('actions.lance_expe.not_enough_ships'));
                });

                $('#nombreptgtvidercolo').click(function() {
                    var nb_utile = Planets.Current().getUsefulTransport();
                    if (nb_utile >= eg.bdd.load('min_transport',15)) fleet_manager.setFleet(eg.bdd.load('type_transport',203),nb_utile)
                });
            }
        }
    };


    var stock_ress = {
        make: function() {
            $('<span>').attr('id','lesstock').makebox('Les Stock ressources','');
            var $lesstock = $('#lesstock');
            $lesstock.hide();
            $lesstock.find('table').addStyle({
                'margin':'0 20px',
                'color':'white'
            });
            $lesstock.find('tr').addStyle('height','20px');
        },
        calcul: function() {
            var $lesstock = $('#lesstock');
            var tstock = new Cost();
            var $html = $lesstock.find('.idle').empty();
            var $tr = $('<tr>');

            $tr.append($('<th>').width(130));
            $tr.append($('<th>').width(105).html(eg.lang.get('resources.m')));
            $tr.append($('<th>').width(105).html(eg.lang.get('resources.c')));
            $tr.append($('<th>').width(105).html(eg.lang.get('resources.d')));
            $tr.append($('<th>').width(135).html('Total (Transpo)'));
            $html.append($tr);

            function MiseEnFormeAffichage($html,titre,stock,style) {
                if( style == undefined ) style = '';

                var $tr = $('<tr>');
                var $td;
                $td = $('<td>').html(titre); if(style['titre']) $td.css(style['titre']); $tr.append($td);
                $.each(Cost.key,function(i,v) {
                    $td = $('<td>').html(AddPoint(stock[v]));
                    if(style[v]) $td.css(style[v]); $tr.append($td);
                });
                $td = $('<td>').html(AddPoint(stock.sum())+' <span style="font-size:9px">('+AddPoint(stock.usefulTransport())+')</span>');
                if(style['T']) $td.css(style['T']); $tr.append($td);
                $html.append($tr);
            }
            $.each(Planets.getCpCoord(),function(i,cp) {
                var pla = Planets.get(cp);
                tstock.add(pla.getCurrentStocks());
                MiseEnFormeAffichage($html,pla.display(),pla.getCurrentStocks(),pla.getCurrentStocks().styles(pla.getLimit()));
            });

            var style = [];
            style['titre'] = {color:'red'};
            MiseEnFormeAffichage($html,'Total a quai',tstock,style);


            var flights;
            var en_vol = new Cost();
            $.each(Flights.types(),function(i,type) {
                flights = new Flights(Flight.byType(type));
                if((flights.Resources().sum()) > 0) MiseEnFormeAffichage($html,'Total '+new Mission(type).name,flights.Resources());
                en_vol.add(flights.Resources());
            });
            tstock.add(en_vol);
            if(en_vol.sum()) MiseEnFormeAffichage($html,'Total en vol',en_vol);



            MiseEnFormeAffichage($html,'Total compte',tstock,style);

            var prod_total = Planets.getProduction();
            MiseEnFormeAffichage($html,'Prod total',prod_total.multiply(24*60*60));
            $lesstock.show();
        },
        init: function() {
            if(eg.bdd.load('show_stock_ress',1) == 1) {
                this.make();
                if(eg.bdd.load('show_ress_dyna',0) == 1) setInterval(stock_ress.calcul,1000);
                else stock_ress.calcul();
            }
        }
    };


    function BuildSuggest() {
//TODO Build.getTimeBuild(level,robo,nanite),getTimeTech(),getTimeShip temps construction batiment, recherche, vaisseaux/défenses
        function doIt(retour) {
            if(!retour.id) return 'Veuillez vérifier vos réglage';
            var level = retour.level_up;
            if($.inArray(retour.id,Build.ships) == -1) level += self.builds[retour.id];

            var build;
            if(retour.id == '12_percent') {
                build = new Build(12);
                level+='%';
            }
            else build = new Build(retour.id);

            var ret = '';
            ret += build.name+'('+level+')';

            if($.inArray(retour.id,[1,2,3,4,12,212,113,'12_percent'])>=0) ret += ' => Rst.Enr.:'+AddPoint(retour.reste);
            if(retour.id != '12_percent') ret += ' Transpo:'+AddPoint(build.getCost(level).usefulTransport());
            return ret;
        }

        this.builds = [];
        var self = this;
        this.init = function() {
            if(!window.vacation && Planets.Current().isPlanet() && eg.bdd.load('mine_a_faire',1)) {
                this.nb_planet = Planets.getCpPlanets().length;

                $.each([1,2,3,4,12,14,15,212,113,122,124],function(i,v) { self.builds[v] = new Build(v).getValue(); });
                this.builds['12_percent'] = toInt(Planets.Current().getBuild(12).percent);

                this.level_max = [];
                this.level_max[212] = toInt(eg.bdd.load('level_max_212',200));
                this.level_max[14] = toInt(eg.bdd.load('level_max_14',10));
                this.level_max[15] = toInt(eg.bdd.load('level_max_15',4));
                this.level_max[4] = toInt(eg.bdd.load('level_max_4',25));
                this.t_max = Planets.Current().getInfo('t_max');

                var Je_doit = '',retour;
                for(var i=0;i<10;i++) {
                    retour = this.Mine_a_faire();
                    Je_doit += '<div>'+doIt(retour) +'</div>';
                    if(retour.id) this.builds[retour.id] = this.builds[retour.id] + retour.level_up;
                    this.nb_planet = Math.floor((this.builds[124]+3)/2);
                }

                $('#header_text').after($('<div>',{id:'minesafaire'}).css({
                    marginTop:'30px',
                    background:'rgba(0,0,0,.65)'
                }).html(Je_doit));
                $('#minesafaire').find('div').css({
                    fontWeight:'bold',
                    color:'white',
                    margin:'0 0 5px 75px',
                    textAlign:'left'
                });
            }
        };

        this.Gestion_energie = function(Reste_energie_actu, Conso_plus) {
            var Manque_energie = Conso_plus - Reste_energie_actu;

            var Cout_C_CES = new Build(4).getCost(this.builds[4] + 1).c;
            var Cout_C_CEF = 4 * new Build(12).getCost(this.builds[12] + 1).c;
            var Cout_C_NRJ = 2 / this.nb_planet * new Build(113).getCost(this.builds[113] + 1).c;
            var Nb_sat = Math.ceil(Manque_energie/Build.prodSat(1))+1;

            if( Nb_sat + this.builds[212] > this.level_max[212] ) Nb_sat = this.level_max[212] - this.builds[212];
            var Cout_C_Sat = 2 * new Build(212).getCost(Nb_sat).c;

            var ProdEnergie = [],ProdUp = [],Renta = [];


            ProdEnergie[4]    = Build.prodCES(this.builds[4]);
            ProdEnergie[12]   = Build.prodCEF(this.builds[12],this.builds[113],this.builds['12_percent']);
            ProdUp[4]         = Build.prodCES(this.builds[4]+1) - ProdEnergie[4];
            ProdUp[12]        = Build.prodCEF(this.builds[12]+1,this.builds[113],this.builds['12_percent']) - ProdEnergie[12];
            ProdUp[113]       = Build.prodCEF(this.builds[12],this.builds[113]+1,this.builds['12_percent']) - ProdEnergie[12];
            ProdUp[212]       = Build.prodSat(Nb_sat);


            if( this.builds[4] >= this.level_max[4]) Renta[4] = 0;
            else Renta[4] = ProdUp[4] / Cout_C_CES;

            if( this.builds[12] == 0 && this.builds[4] < 28 ) Renta[12] = 0;
            else Renta[12] = ProdUp[12] / Cout_C_CEF;
            if( Renta[4] * 10000 < 4 ) Renta[12] = ProdUp[12] / Cout_C_CEF;

            Renta[113] = ProdUp[113] / Cout_C_NRJ;

            if( Cout_C_Sat == 0 || (Nb_sat + this.builds[212]) > this.level_max[212] || Nb_sat < 0 ) Renta[212] = 0;
            else Renta[212] = ProdUp[212] / Cout_C_Sat;

            var reste_energie_apres = '';
            var Energie_en_plus = 0;

            var id,level_up = 1;

            if( Renta[4] >= Renta[12] && Renta[4] >= Renta[113] && Renta[4] >= Renta[212] ) id = 4;
            else if( Renta[12] >= Renta[4] && Renta[12] >= Renta[113] && Renta[12] >= Renta[212] ) id = 12;
            else if( Renta[113] >= Renta[4] && Renta[113] >= Renta[12] && Renta[113] >= Renta[212] ) id = 113;
            else if( Renta[212] >= Renta[4] && Renta[212] >= Renta[12] && Renta[212] >= Renta[113] ) {
                id = 212;
                level_up = Nb_sat;
            }

            if(id) {
                Energie_en_plus = ProdUp[id];
                reste_energie_apres = Reste_energie_actu + Energie_en_plus;
            }


            var P_CEF = pourcentCEF(Manque_energie, this.builds[12], this.builds[113], this.builds['12_percent']);
            var diff = Math.floor(10 * (P_CEF - this.builds['12_percent'])) / 10;

            if(diff) {
                reste_energie_apres = Conso_plus+Build.prodCEF(this.builds[12],this.builds[113],diff);
                id = '12_percent';
                level_up = diff;
            }
            return {id:id,level_up:level_up,reste:reste_energie_apres};
        };

        this.Gestion_temps = function() {
            var Facteur_div_robo = (1 + this.builds[14] + (2)) / (1 + this.builds[14]);
            var Facteur_div_nanite = 2;

            var Cout_up_robo = Math.pow(1.3,this.builds[14]) * new Build(14).getCost(this.builds[15] + 1).c;
            var Cout_up_nanite = new Build(15).getCost(this.builds[15] + 1).c;

            var Renta = [];
            if( this.level_max[14] < this.builds[14] + 1 ) Renta[14] = 0;
            else Renta[14] = Facteur_div_robo / Cout_up_robo;

            if( this.level_max[15] < (this.builds[15] + 1) || this.builds[14] < 10 ) Renta[15] = 0;
            else Renta[15] = Facteur_div_nanite / Cout_up_nanite;

            if(Renta[14] || Renta[15]) {
                if( Renta[14] > Renta[15] ) return {build_id:14,level:(this.builds[14] + 1)};
                else if( Renta[15] >= Renta[14] ) return {build_id:15,level:(this.builds[15] + 1)};
            }
            return {build_id:null,build_level:null};
        };

        this.Mine_a_faire = function() {
            var cost_build = {};
            $.each(Build.mines,function(i,v) { cost_build[v] = new Build(v).getCost(self.builds[v]+1); });
            cost_build[122] = new Build(122).getCost(this.builds[122]+1);
            cost_build[124] = new Build(124).getCost(this.builds[124]+1);
            if(this.builds[124]%2) cost_build[124].add(new Build(124).getCost(this.builds[124]+2));

            var CostPond = [];
            CostPond[1]   = 1.5 * cost_build[1].c;
            CostPond[2]   = 1.1 * cost_build[2].c;
            CostPond[3]   = 2 * cost_build[3].c;
            CostPond[124] = cost_build[124].c * (3/2)/(this.nb_planet+1);
            CostPond[122] = 10*cost_build[122].c *2/this.nb_planet;

            var Temps_maxi = 999 * 24;

            var Conso_actu = [];
            $.each(Build.mines,function(i,v) { Conso_actu[v] = consoEnergie(v,self.builds[v]); });
            var Conso_actu_total = Conso_actu[1] + Conso_actu[2] + Conso_actu[3];

            var ProdNRJ = [];
            ProdNRJ[4]   = Build.prodCES(this.builds[4]);
            ProdNRJ[12]  = Build.prodCEF(this.builds[12],this.builds[113],this.builds['12_percent']);
            ProdNRJ[212] = Build.prodSat(this.builds[212]);
            var Prod_actu_total = ProdNRJ[4] + ProdNRJ[12] + ProdNRJ[212];
            var Reste_energie_actu = Prod_actu_total - Conso_actu_total;

            var Temps;
            var Conso_en_plus;
            var id,level_up = 1;

            if( CostPond[1] <= CostPond[2] && CostPond[1] <= CostPond[3]) id = 1;
            else if( CostPond[3] < CostPond[1] && CostPond[3] <= CostPond[2] ) id = 3;
            else id = 2;

            Conso_en_plus = consoEnergie(id, this.builds[id]+1) - Conso_actu[id];
            var reste_after = Reste_energie_actu - Conso_en_plus;

            //TODO a supprimer => BuildLevel.getTimeBuild
            function tempsConstruction(M_C, Robo, Nanite) {
                return (M_C) / 5000 * 2 / (Robo + 1) * Math.pow(0.5,Nanite) / eg.metas.get('universeSpeed');
            }
            Temps = tempsConstruction(cost_build[id].m+cost_build[id].c, this.builds[14], this.builds[15]);

            if($.inArray(id,[1,2])>=0 && CostPond[122] <= CostPond[id]) id = 122;
            else if(CostPond[124] <= CostPond[id]) id = 124;

            if(id == 124 || id == 122) {
                reste_after = Reste_energie_actu;
                Temps = 0;
            }

            if( Temps > Temps_maxi ) {
                var data = this.Gestion_temps();
                id = data.id;
                level_up = data.level_up;
            }
            else {
                var P_CEF = pourcentCEF(-reste_after, this.builds[12], this.builds[113], this.builds['12_percent']);
                var diff = Math.floor(10*(P_CEF - this.builds['12_percent']))/10;
                if(diff) {
                    reste_after = Reste_energie_actu-ProdNRJ[12]+Build.prodCEF(this.builds[12],this.builds[113],P_CEF);
                    id = '12_percent';
                    level_up = diff;
                }
                else if(reste_after < 0 ) return this.Gestion_energie(Reste_energie_actu,Conso_en_plus);
            }
            return {id:id,level_up:level_up,reste:reste_after};
        };
        this.init();
    }


    function Hidden() {}
    Hidden.prototype = {
        Selector: function (key) { return $('[type="hidden"][name="' + key + '"]'); },
        exists: function (key) { return this.Selector(key).length; },
        get: function (key) { return this.Selector(key).val(); },
        set: function (key, value) { return this.Selector(key).val(value); },
        append: function (key, selector) { return $(selector).append($('<input />', { name: key, type: 'hidden' })); }
    };
    function API() {
        this.check();
        //highscore.xml?category=1&type=1
//players.xml
        //universe.xml
        //alliances.xml
        //serverData.xml
        //localization
    }
    API.prototype = {
        xml2array: function(xml,tag) {
            var $childrens = $(xml).children();
            var data = {};

            var nb_attr = 0;
            $.each(['id','name','type','score','coords','size','ships',
                'timestamp','alliance','status','player','position','href'],function(i,v) {
                if($(xml).attr(v)) {
                    if(tag == 'techs') {
                        alert(v+' '+$(xml).attr(v));
                    }
                    data[v] = $(xml).attr(v);
                    nb_attr++;
                }
            });

            var lng = $childrens.length;
            if(!lng) {
                if(xml.textContent) {
                    if(!nb_attr) data = xml.textContent;
                    else data['value'] = xml.textContent;
                }
            }
            else {
                var is_array = false;
                if($.inArray(tag,['players','universe','alliances','universes'])>=0) {
                    data = [];
                    is_array = true;
                }
                $childrens.each(function() {
                    var subArray = API.prototype.xml2array(this,this.tagName);
                    var subTag = this.tagName;
                    if($.inArray(tag,['techs','missions','planets','positions'])>=0) {
                        if($.inArray(tag,['techs','missions'])>=0) data[subArray.id] = subArray.value;
                        else if(tag == 'planets') data[subArray.id] = subArray;
                        else if(tag == 'positions') data[subArray.type] = subArray;
                    }
                    else if(is_array) {
                        var o = {};
                        o[subTag] = subArray;
                        data.push(o);
                    }
                    else data[subTag] = subArray;
                });
            }
            return data;
        },
        callback: function(xml,name,params) {
            var data = this.xml2array(xml,name)[name];
            eg.bdd.save('api.'+name+(params?'.'+$.param(params):'')+'.lastupdate',$.now());
            eg.bdd.save('api.'+name+(params?'.'+$.param(params):''),data);
        },
        check: function() {
            var self = this;
            $.each([
                {deltaUpdate:8,name:'playerData',params:{id:eg.metas.get('playerId')}},
                {deltaUpdate:24*6,name:'localization'},
                {deltaUpdate:24*6,name:'serverData'}
            ],function(i,v) {
                var data = self.get(v.name, v.params);
                if(($.now()-data.lastupdate)/(1000*3600) >= v.deltaUpdate) self.load(v.name, v.params);
            })
        },
        load: function(name,params) {
            var self = this;
            $.ajax( {
                type: "GET",
                url: makeUrlAPI(name,params),
                dataType: "xml",
                success: function(xml) {
                    self.callback(xml,name,params);
                }
            });
        },
        get: function(name,params) {
            return {
                lastupdate: eg.bdd.load('api.'+name+(params?'.'+$.param(params):'')+'.lastupdate',0),
                data: eg.bdd.load('api.'+name+(params?'.'+$.param(params):''),{})
            };
        },
        dataLocalization: function() { return this.get('localization').data; },
        dataServerData: function() { return this.get('serverData').data; }
    };

    function Premium() {
        var self = this;
        $('#officers').find('a').each(function () {
            self[this.href.pick(/openDetail=([0-9]+)/)] = $(this).hasClass('on');
        });
    }
    Premium.prototype = {
        enabled: function (key) {
            if (key == 'commandant') key = '2';
            else if (key == 'amiral') key = '3';
            else if (key == 'ingenieur') key = '4';
            else if (key == 'geologue') key = '5';
            else if (key == 'technocrate') key = '6';
            return this[key];
        }
    };


    try {
        var hidden = new Hidden();
        if(eg.gbdd.load('dateinstallMaJ',0) == 0) eg.gbdd.save('dateinstallMaJ',$.now());

        if(eg.global.getMode() == 'game') {
            Planets.update();
            Technos.update();
            var api = new API();
            var premium = new Premium();

            if(Planets.getUrlsInstall().length || Technos.getUrlInstall().length) {
                $(function() {
                    var url = $.merge(Planets.getUrlsInstall(),Technos.getUrlInstall());
                    var timeactua = random(1300,3500); timeactua.toFixed(2);

                    $('#menuTable').append('<li id="menuscript"></li>');
                    $('#menuscript').addStyle({
                        padding: '5px',
                        width: '126px',
                        height:'inherit',
                        background: 'rgb(10, 13, 15)',
                        'border-radius': '5px',
                        'text-align':'center'
                    }).html('Installation<br /><br />'+Math.round(10000*(Planets.nbUrlVisit())/(Planets.nbUrlVisitTotal()))/100+' %');
                    setTimeout(function() { window.location.replace(url[0]); },timeactua);
                });
            }
            else {
                var fleet_manager = new FleetManager();
                if(eg.bdd.load('hide_mmogame',1) == 1) {
                    $('body.no-commander').addStyle({ backgroundPosition:'0% 0',margin: '0'});
                    $('#mmonetbar').addStyle('display','none');
                    $('body.no-commander .contentBoxBody').addStyle('top','0');
                }
                if(eg.bdd.load('hide_build_faster',1) == 1) $('.build-faster').addStyle('display','none');
                if(eg.bdd.load('basique_color_menu',1) == 1) $('.premiumHighligt span').addStyle('color','inherit');
                if(eg.bdd.load('remove_pub',1) == 1) $('#banner_skyscraper').addStyle('display','none');

                $( document ).ajaxSuccess(function( event, xhr, settings ) {
                    var page = settings.url.pick(/page=([^&#]+)/);
                    if(page == 'allianceOverview') {
                        $(function() {
                            var $span = $('<span>');
                            $span.attr('id','boutonBBcode').css('cursor','pointer').html('Liste Membres');
                            $('#allyData').find('table').after($span);
                            $('#boutonBBcode').click(function() {
                                var infoJoueur = [],pseudo,point,classement,texte = '';

                                $('#member-list').find('tbody').find('tr').each(function(i) {
                                    pseudo = $.trim($(this).find('td').html());
                                    point = toInt($(this).find('td').eq(3).attr('title'));
                                    if(!point) alert('erreur');
                                    classement = toInt($(this).find('td').eq(3).find('a').html());

                                    infoJoueur[i] = [pseudo,point,classement];
                                });

                                for (var i =0 ; i< infoJoueur.length ; i++)
                                    texte += (i+1) +'\t'+ infoJoueur[i][0] +'\t\t\t'+infoJoueur[i][1]+'\t\t\t\t'+infoJoueur[i][2]+'\n';
                                alert(texte);
                            });
                        });
                    }
                    else if(page == 'galaxyContent') {
                        if(!premium.enabled('commandant')) {
                            var $galaxytable = $('#galaxytable');
                            var galaxy = toInt($galaxytable.data('galaxy'));
                            var system = toInt($galaxytable.data('system'));
                            var url_base = makeUrl('fleet1','galaxy='+galaxy+'&system='+system);

                            $galaxytable.find('.row').each(function() {
                                var $row = $(this);

                                var $planet = $row.find('.microplanet');
                                var $debris = $row.find('.debris');
                                var $moon = $row.find('.moon');
                                var $player = $row.find('.playername');
                                var position = toInt($row.find('.position').html());
                                var recy = Math.min(toInt($debris.find('.debris-recyclers').html()),new Build(209).getValue());

                                if(recy) {
                                    var $debris_link = $debris.find('.ListLinks').find('a');
                                    $debris_link.attr('href',url_base+'&position='+position+'&type=2&mission=8&am209='+recy);
                                    $debris_link.removeAttr('onclick');
                                }

                                if($planet.length && !$player.hasClass('vacation') && !$player.hasClass('js_no_action') && !$player.hasClass('noob')) {
                                    var $planet_link = $planet.find('.ListLinks');

                                    var $crach_link = $('<a>');
                                    $crach_link.attr('href',url_base+'&position='+position+'&type=1&mission=1&am210=1');
                                    $crach_link.html('Crach sonde');
                                    $planet_link.append($crach_link);
                                    $planet_link.find('li:last').next().wrap('<li>');

                                    if($moon.length) {
                                        var $moon_link = $moon.find('.ListLinks');
                                        if($moon_link.length) {
                                            var $spy_link = $('<a>');
                                            $spy_link.click(function() {
                                                window.sendShips(6,galaxy,system,position,3,10);
                                                return false;
                                            }).html('Espionner').attr('href','javascript:void(0);');
                                            $moon_link.append($spy_link).find('li:last').next().wrap('<li>');

                                            $crach_link = $('<a>');
                                            $crach_link.attr('href',url_base+'&position='+position+'&type=3&mission=1&am210=1');
                                            $crach_link.html('Crach sonde');
                                            $moon_link.append($crach_link);
                                            $moon_link.find('li:last').next().wrap('<li>');
                                        }
                                    }
                                }
                            });
                        }
                    }
                    else if($.inArray(page,['resources','shipyard','defense','research'])>=0) {
                        $(function() {
                            var build_id = $('[name="type"]','#detail').val();
                            var cost = new Build(build_id).getCost(1);
                            var tab = [],max;
                            $.each(Cost.key,function(i,v) { if(cost[v]) tab.push(Planets.Current().getResource(v).available/cost[v]); });
                            if(!tab.length) max = 0;
                            else {
                                max = tab[0];
                                var length = tab.length;
                                for (var i = 1; i < length; i++) if (tab[i] < max) max = tab[i];
                            }
                            max = Math.floor(max);

                            var $number = $('#number');
                            if(!premium.enabled('commandant') && eg.bdd.load('show_button_max',1) == 1) {
                                $('#costs .enter p br','#detail').after('[<a id="maxlink" class="tooltipRight tooltipRight" title="Nombre maximum" href="javascript:void(0);"></a>]');
                                $('#maxlink').html('max. '+max).click(function() { $number.val(max).trigger('change'); });
                            }
                            $number.on('keyup change focus',function() {
                                var index = 0;
                                var local_cost = cost.clone().multiply($(this).val() || 1);
                                var styles = local_cost.styles(Planets.Current().getAvailable());
                                $.each(Cost.key,function(i,v) {
                                    if(local_cost[v]) $('.cost:eq('+(index++)+')').html(AddPoint(local_cost[v])).css(styles[v]);
                                });
                                $('#transpo_build').html(AddPoint(local_cost.usefulTransport()));
                            });

                            var $action = $('#action');
                            var $li = $('<li>');
                            $li.html('Nombre de transporteur: ');
                            var $span = $('<span>',{class:'time',id:'transpo_build'});

                            var level;
                            if(eg.global.page == 'resources' && build_id != 212 || eg.global.page == 'research') {
                                if(eg.global.page == 'research') level = Technos.get(build_id) + 1;
                                else level = new Build(build_id).getValue() + 1;
                            }
                            else level = 1;
                            var cost_level_next = new Build(build_id).getCost(level);
                            $span.html(AddPoint(cost_level_next.usefulTransport()));
                            $li.append($span);
                            $action.find('ul').append($li);
                        });
                    }
                });

                fleet_page.init();
                if(eg.global.page == 'resources') {
                    new BuildSuggest();
                    $('.detail_button').click(function() {
                        setTimeout(function() {
                            if($('#detail').css('display') == 'none') $('#minesafaire').show();
                            else $('#minesafaire').hide();
                        },200);
                    });
                }
                $(function() {
                    try { $(ActionManager); } catch(e) { eg.log(e,'ActionManager'); }
                    if(eg.global.page == 'overview') {
                        new Changelog();
                        stock_ress.init();
                    }
                });
            }
        }
    } catch(e) {
        eg.log(e,'script');
    }
})( unsafeWindow|| window);