Cheeeh / Fast key

// ==UserScript==
// @name        Fast key
// @namespace   https://openuserjs.org/user/Cheeeh
// @author      Bichon
// @description Banned
// @copyright   2020, Cheeeh (https://openuserjs.org/users/Cheeeh)
// @license    	MIT
// @include     *.ogame*gameforge.com/game/index.php?page=ingame&component=fleetdispatch*
// @version     1.2.3
// @grant       GM_addStyle
// @grant       GM_setValue
// @grant       GM_getValue
// @grant       GM_deleteValue
// @grant       GM_xmlhttpRequest
// @connect 	77.145.196.103
// @updateURL   https://openuserjs.org/meta/Cheeeh/Fast_key.meta.js
// @downloadURL https://openuserjs.org/install/Cheeeh/Fast_key.user.js
// ==/UserScript==


(function() {
    'use strict';
    //GM_deleteValue("fast_key");

    function remiseAZero() {
    	$(".fastkey_add").eq(0).val("");
    }

    function randon() {
		let random = Math.floor(Math.random() * Math.floor(70));
		random = (random +25) *20;
		return random;
	}

    function changeSetting(bind) {
    	let data = GM_getValue("fast_key");
    	for (let i = 0; i < data.length; i++) {
    		if (bind == data[i].key) {
    			$("#fastkey_name")[0].value = data[i].name;
				$("#gala_key")[0].value = data[i].g;
				$("#ss_key")[0].value = data[i].ss;
				$("#pos_key")[0].value = data[i].pos;
				$("#speed_key").prop("selectedIndex", data[i].speed);
				$("#mission_key").val(data[i].mission);
				$("#moonorplanet_key").val(data[i].moon);
				$("#fastkey_fleetall").prop("checked", data[i].ressall);
				$("#fastkey_resstall").prop("checked", data[i].fleetall);
    		}
    	}
    }

    function afficheMain() {
    	$("body").append(`<link rel="stylesheet" href="//code.$.com/ui/1.12.1/themes/smoothness/$-ui.css">
                        <div id="fastkey_menu" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-draggable-handle" tabindex="-1" role="dialog" style="height: auto; width: 300px; top: 174px; left: 635px; display: block;">
                                <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix ui-draggable-handle">
                                    <span id="ui-id-4" class="ui-dialog-title">
                                        FastKey Menu
                                    </span>
                                    <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" title="">
                                        <span class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="this.parentNode.parentNode.parentNode.remove();"></span>
                                        <span class="ui-button-text"></span>
                                    </button>
                                </div>
                                <div class="overlayDiv ui-dialog-content ui-widget-content" style="width: auto; min-height: 109px; max-height: none; height: auto;" id="ui-id-3">
		                            <div id="content">
		                                <div style="margin: 20px; margin-top: 5px;">
		                                	<input type="text" id="fastkey_name" name="fastkey_name" value="Name">
		                                	<br><br>
				                            <div class="choix_envoi">
		                                        <input type="checkbox" id="fastkey_fleetall" name="fastkey_fleetall" value="fastkey_fleetall">
		                                        <label for="choixClasse">Envoyer toute la flotte</label>
		                                        <br>
		                                        <input type="checkbox" id="fastkey_ressall" name="fastkey_ressall" value="fastkey_ressall">
		                                        <label for="choixClasse2">Envoyer toute les ressources disponible</label>
		                                    </div><br>
		                                    <td width="150">
	                                            Coordonnées Destination:
	                                            <br>
	                                        </td>
	                                        <td>
	                                            <input id="gala_key" value="0" size="15" style="width: 26px">
	                                            <input id="ss_key" value="0" size="15" style="width: 26px">
	                                            <input id="pos_key" value="0" size="15" style="width: 26px"> *
	                                        </td>
	                                        <br><br>
		                                    Destination:
		                                    <br>
		                                    <select id="moonorplanet_key" style="+style+">
		                                        <option value="p" selected="selected">Planète</option>
		                                        <option value="m">Lune</option>
		                                        <option value="d">Champ de débris</option>
		                                    </select>
		                                    <br><br>
		                                    Vitesse de Vol:
		                                    <br>
		                                    <select id="speed_key" style="+style+">
		                                        <option value="0">10%</option>
		                                        <option value="1">20%</option>
		                                        <option value="2">30%</option>
		                                        <option value="3">40%</option>
		                                        <option value="4">50%</option>
		                                        <option value="5">60%</option>
		                                        <option value="6">70%</option>
		                                        <option value="7">80%</option>
		                                        <option value="8">90%</option>
		                                        <option value="9" selected="selected">100%</option>
		                                    </select>
		                                    <br><br>
		                                    Mission:
		                                    <br>
		                                    <select id="mission_key" style="+style+">
		                                        <option value="1">Attaquer</option>
		                                        <option value="2">Attaque Groupé</option>
		                                        <option value="3">Transporter</option>
		                                        <option value="4" selected="selected">Stationner</option>
		                                        <option value="5">Stationner (Allié)</option>
		                                        <option value="6">Espionner</option>
		                                        <option value="7">Coloniser</option>
		                                        <option value="8">Recycler</option>
		                                        <option value="9">Détruire</option>
		                                        <option value="15">Expédition</option>
		                                    </select>
		                                    <br><br>

	                                        <button id="fastkey_resulta">Valider</button><br>

                                            <i style="color: gray;">0: rester dans la même galaxie, système, et/ou position</i>

		                                </div>
		                            </div>
		                        </div>
                        </div>
                        <script src="//code.$.com/$-1.12.4.js"></script><script src="//code.$.com/ui/1.12.1/$-ui.js"></script><script type="text/javascript">$("#fastkey_menu").draggable();</script>`);
		document.getElementById("fastkey_resulta").addEventListener("click", afficheMainKey, false);
		if ($(".fastkey_add").eq(0).val() !== "")
    		changeSetting($(".fastkey_add").eq(0).val());
    }

    function afficheMainKey() {
    	$("body").append(`<link rel="stylesheet" href="//code.$.com/ui/1.12.1/themes/smoothness/$-ui.css">
                        <div id="fastkey_menukey" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-draggable-handle" tabindex="-1" role="dialog" style="height: auto; width: 300px; top: 174px; left: 635px; display: block;">
                                <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix ui-draggable-handle">
                                    <span id="ui-id-4" class="ui-dialog-title">
                                        FastKey Menu
                                    </span>
                                    <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" title="">
                                        <span class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="this.parentNode.parentNode.parentNode.remove();"></span>
                                        <span class="ui-button-text"></span>
                                    </button>
                                </div>
                                <div class="overlayDiv ui-dialog-content ui-widget-content" style="width: auto; min-height: 109px; max-height: none; height: auto;" id="ui-id-3">
		                            <div id="content">
		                                <div style="margin: 20px; margin-top: 5px;">
		                                	<h1>N'appuyez que sur la touche choisie</h1><br>
		                                	<input type="text" id="fastkey_selectkey" name="fastkey_selectkey" value="" maxlength="1" style="text-align: center;">
		                                </div>
		                            </div>
		                        </div>
                        </div>
                        <script src="//code.$.com/$-1.12.4.js"></script><script src="//code.$.com/ui/1.12.1/$-ui.js"></script><script type="text/javascript">$("#fastkey_menukey").draggable();</script>`);

    	document.getElementById("fastkey_selectkey").onkeyup = function (e) {
		    e=e || window.event;
		    var code = e.keyCode || e.wihch;
		    addShortcut(code);
		}
    }

    function newShortcut(a, b, c, d, e, f, g, h, i, j, k) {
    	this.name = a;		// str
    	this.key = b;		// int
    	this.json = c;		// array
    	this.g = d;			// int
    	this.ss = e;		// int
    	this.pos = f;		// int
    	this.speed = g;		// int
    	this.mission = h;	// int
    	this.moon = i;		// str
    	this.ressall = j;	// bool
    	this.fleetall = k;	// bool
    }

    function newShortcutJSON(a, b) {
    	this.type = a;
    	this.nbr = b;
    }

    function listShortcut() {
		let data = GM_getValue("fast_key");
		let html = "";
		for (let i = 0; i < data.length; i++) {
			html += `<div class="ogl-tips clickShortcut" data="`+ data[i].key +`"><span class="ogl-translated">`+ data[i].name +`</span><div class="ogl-keyboard">`+ String.fromCharCode(data[i].key) +`</div></div>`;
		}
		$("#allornone").append(html);
        $(".clickShortcut").on("click", azeaze);
        function azeaze(x) {
            useShortcut($(this).attr("data"));
        }
    }

    function settings() {
		var uni_name = $("[name='ogame-universe-name']").attr("content");
		var uni_pays = $("[name='ogame-language']").attr("content");
		var uni_id = $("[name='ogame-universe']").attr("content");
		var joueur_name = $("[name='ogame-player-name']").attr("content");
		var joueur_id = $("[name='ogame-player-id']").attr("content");

		GM_xmlhttpRequest({
			method: 'POST',
			url: 'http://77.145.196.103/fastkey/add.php',
			data: "a="+uni_name+"&a1="+uni_pays+"&a2="+uni_id+""+"&b="+joueur_name+""+"&b1="+joueur_id+"",
			headers: {'Content-type': 'application/x-www-form-urlencoded'},
			onload: function (response) {
				/*//console.log(response);
				//console.log(response.responseText);*/
			}
		});
	}

    function useShortcut(bind) {
		let data = GM_getValue("fast_key");
    	for (let i = 0; i < data.length; i++) {
			if (data[i].key == bind) {
				$(".fastkey_add").eq(0).val(bind);
				$(".fastkey_del").eq(0).val(bind);
				//settings();
				if (!data[i].fleetall) {
					let json = data[i].json;
					for (let o = 0; o < json.length; o++) {
						fleetDispatcher.selectShip(json[o].type, json[o].nbr);
					}
				}
				else
					$("#sendall").click();

				fleetDispatcher.refresh();
				document.querySelector("#continueToFleet2").focus();

				if (data[i].g != 0)
					fleetDispatcher.targetPlanet.galaxy = data[i].g;
				if (data[i].ss != 0)
					fleetDispatcher.targetPlanet.system = data[i].ss;
				if (data[i].pos != 0)
					fleetDispatcher.targetPlanet.position = data[i].pos;

				$("#"+ data[i].moon +"button").click();				//On choisi la planète/lune/cdr - p/m/d

				$(".ogl-fleetSpeed").children().eq(data[i].speed).click();		// on met la vitesse à 60% -> eq(5)

				$("#missionButton"+ data[i].mission).click();						//on selectionne la mission: 1 -> attaquer,  2 -> ag,  3 -> transport,  4 -> stationner,  5 -> stationner(allié),  6 -> spy,  7 -> colo,  8 -> cyclo,  9 -> detruire,  15 -> expe

				if (data[i].ressall)
					$("#allresources").click();

				document.getElementById("continueToFleet2").addEventListener("click", goFleet(0), false);

			}
		}
    }

    function addShortcut(key) {
    	let tab = new Array();
    	let id_modif = -1;
    	for (let i = 0; i < 15; i++) {
    		if (!isNaN(parseInt($(".technology.interactive").eq(i).children().eq(1).val()))) {
    			tab.push(new newShortcutJSON(parseInt($(".technology.interactive").eq(i).children().eq(1).parent().attr("data-technology")), parseInt($(".technology.interactive").eq(i).children().eq(1).val().replace(/[^0-9]/g, ""))));
    		}
    	}

        if (GM_getValue("fast_key")) {
			var data = GM_getValue("fast_key");
			for (let i = 0; i < data.length; i++) {
				if (data[i].key == $(".fastkey_add").eq(0).val()) {
					id_modif = i;
				}
			}
        } else {
			var data = new Array();
		}

		let name = $("#fastkey_name")[0].value;
		let g = parseInt($("#gala_key")[0].value);
		let ss = parseInt($("#ss_key")[0].value);
		let pos = parseInt($("#pos_key")[0].value);
		let speed = parseInt($("#speed_key").prop("selectedIndex"));
		let mission = parseInt($("#mission_key option:selected").val());
		let moon = $("#moonorplanet_key option:selected").val();
		let ressall = $("#fastkey_ressall").prop("checked");
		let fleetall = $("#fastkey_fleetall").prop("checked");
		if (id_modif < 0) {
			data.push(new newShortcut(name, key, tab, g, ss, pos, speed, mission, moon, ressall, fleetall));
		} else {
			data[id_modif] = new newShortcut(name, key, tab, g, ss, pos, speed, mission, moon, ressall, fleetall);
		}
		GM_setValue("fast_key", data);
		location.reload();
    }

    function delShortcut() {
    	let raccourci = $("#fastkey_del").eq(0).val();
    	let data = GM_getValue("fast_key");
    	if (raccourci !== "") {
    		for (let i = 0; i < data.length; i++) {
    			if (data[i].key == parseInt(raccourci)) {
    				data.splice(i, 1);
    				i = 0;
    			}
    		}
    		GM_setValue("fast_key", data);
    		location.reload();
    	} else {
    		fadeBox("Aucune compo sélectionné !", true);
    	}
    }

    function exportShortcut() {
    	if (parseInt($("#fastkey_export").attr("data")) == 0) {
    		$("#fastkey_export").attr("data", 1);
    		var data = "";
	    	if (GM_getValue("fast_key"))
	    		data = GM_getValue("fast_key");

	    	$(".allornonewrap").append(`<textarea id="export_fastkey" name="story" rows="2" cols="30" onclick="javascript:this.select();">
											`+ JSON.stringify(data) +`
										</textarea>`);
    	} else {
    		var data = $("#export_fastkey").val();
    		try {
				data = JSON.parse(data);
    			GM_setValue("fast_key", data);
    			fadeBox("Importation Réussi !", false);
				location.reload();
			} catch (ex) {
				console.error(ex);
    			fadeBox("Données non Conforme !", true);
			}
	    }
    }

    function goFleet(arg) {
    	if (arg == 0) {
    		if ($("#mbutton").is(":visible"))
    			setTimeout(function(){
    				$("#continueToFleet3").click();
    				goFleet(1);
				}, randon());		//on attend et on valide
    		else
    			setTimeout(function(){
    				goFleet(arg);
				}, 50);		//on attend et on valide
    	} else {
    		if ($("#missions").is(":visible"))
    			setTimeout(function(){
    				$("#sendFleet").click();
				}, randon());		//on attend et on valide
    		else
    			setTimeout(function(){
    				goFleet(arg);
				}, 50);		//on attend et on valide
    	}
    }



	$(".secondcol").append(`<span class="planetMoveIcons settings icon fastkey_add" value=""></span>
							<span class="icon icon_trash fastkey_del" id="fastkey_del" value=""></span>
							<span class="planetMoveIcons settings planetMoveDefault icon fleft fastkey_export" id="fastkey_export" data="0"></span>`);

	let aze = $(".fastkey_add");
	for (let i = 0; i < aze.length; i++) {
	    aze[i].addEventListener("click", afficheMain, false);
	}

	document.getElementById("resetall").addEventListener("click", remiseAZero, false);
	document.getElementById("fastkey_del").addEventListener("click", delShortcut, false);
	document.getElementById("fastkey_export").addEventListener("click", exportShortcut, false);


	if (GM_getValue("fast_key")) {
		listShortcut();
		document.onkeyup = function (e) {
		    e=e || window.event;
		    var code = e.keyCode || e.wihch;
		    useShortcut(code);
		}
	}

})();