Source for "OGame#"

By Spitfire
Has no other scripts.


the source is over 100KB, syntax highlighting in the browser is too slow

/*
 *  This file is part of OGame#, based on OGame++ version 0.9.97 by Unbrained
 *  Copyright (C) 2007 SpitFire (spitfirevampir@gmail.com)
 *  Source code http://userscripts.org/scripts/show/8555
 *
 *  This script is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  General Public License for more details.
 *  http://www.gnu.org/copyleft/gpl.html
 */

// ==UserScript==
// @name			OGame#
// @author			SpitFire
// @description			Has soñado con un OGame mejor?
// @include			http://uni*.ogame.com.es/game/*
// @include			http://drago-sim.com/*
// ==/UserScript==

// Compatible con foxgame hasta la version 0.4.2 por lo menos
// Funciona con servidores galaxieTool a partir de la version 3.51

/*********************************************************/
/*********+-------------------------------+***************/
/*********|      Features list            |***************/
/*********+-------------------------------+***************/
/*********************************************************/
/** QUE HACE ESTE SCRIPT?
 ** Colores configurables para las cabeceras de los mensajes (ahora también se colorea
 *		el contenido de los mensajes)
 ** Auto marca determinados mensajes, también configurable
 ** Auto marca espionajes de planetas con pocos recursos
 ** Corrige los links de coordenadas en los mensajes y en la Visión General, y los colorea
 ** Se añade un enlace a Drago-Sim y otro a o-calc en el menú lateral
 ** Añade información sobre la carga de las naves al escoger la flota
 *		(adaptación del script http://userscripts.org/scripts/show/6189)  
 ** Se añade un botón con una D al lado de los informes de espionaje hechos que
 * 		envia los datos del informe a Drago-Sim para hacer analisis de ataques
 ** Se incorpora un compactador de batallas
 * 	(adaptacion del script http://userscripts.org/scripts/show/3482)
 ** Se incorpora un script de información extendida para los recursos
 * 	(modificación del script http://userscripts.org/scripts/show/6483/)
 ** menú lateral plegable
 ** Se añade funcionalidad para GalaxieTool, se permiten múltiples cuentas
 * 		independientes para cada universo.
 ** Resaltado de campos de escombros. Esta idea la cogí del Foxgame y la he mejorado un poco:
 *		Escoges un color para resaltar, un máximo de escombros resaltables y un mínimo. El máximo
 *		indica a partir de qué cantidad quieres que se resalte. Dependiendo de la cantidad de
 *		escombros que haya se colorea desde el blanco hasta el color indicado. El color indicado se
 *		alcanza cuando la cantidad de escombros supera el máximo especificado  
 ** Función de colorear etiquetas de alianzas. Se puede asociar un grupo de alianzas
 * 		con un color y una etiqueta (opcional). La alianza se mostrará del color especificado
 * 		en la visión de Galaxia y en las Estadísticas con la etiqueta, si existe, a
 * 		continuación. Es muy til para reconocer alianzas amigas/enemigas o pactos con otras alianzas
 * 		NOTA IMPORTANTE: DESACTIVAR ESTA FUNCION SI SE ACCEDE A CUENTAS DE GALAXIETOOL O SIMILARES
 * 		POR UN MEDIO QUE NO SEA ESTE SCRIPT, YA QUE LOS INFORMES APARECERIAN DEFECTUOSOS
 * 		(idea sacada del script http://userscripts.org/scripts/show/4030)
 ** Se añade una tabla de alianza en el menú lateral. Para recoger los datos de la alianza
 *		es necesario abrir la pagina de Alianzas.
 *		(escrito a partir del script http://userscripts.org/scripts/show/3947)
 ** Se pueden guardar coordenadas que aparecerán como destinos extra en la pantalla de escoger
 *		destino al enviar la flota
 *		(escrito a partir del script http://mapaogame.net/farmlist/)
 ** Se actualiza automáticamente
 */

/** NUEVAS OPCIONES EN LA VERSION DE SPITFIRE
 ** Borra los iconitos tan chulos de los oficiales
 ** Quita el letrero de los oficiales del menú lateral
 ** Se puede mandar construir más de 999 unidades en hangar y defensa, se muestra el máximo de unidades que se pueden
 *			construir con los recursos actuales (este máximo se actualiza cuando vamos añadiendo naves), y se muestran
 *			también los recursos que quedarían después de aceptar la construcción
 ** Se añade un simulador de batallas además de Drago-Sim: CSim
 ** Opción para reducir las imágenes de edificios/investigaciones/naves/defensas
 ** Opción para ocultar/mostrar unidades en naves/defensas
 * 	 (idea sacada del script http://userscripts.org/scripts/show/7594)
 ** Con el "modo transporte" podrás enviar los recursos de tus planetas a donde t quieras
 * 		sin ningn tipo de esfuerzo (solo dandole al enter y cambiando de planeta de origen)
 ** Se activa en la galaxia la opcion de espiar lunas y recolectar escombros
 ** Podrás ver si hay mensajes nuevos (aparecen parpadeando en el men, al lado de la opción
 * 		Mensajes). Se actualizan en un intervalo de tiempo determinado especificado, con cierta aleatoriedad
 * 		para no levantar sospechas. Es importante no poner un intervalo de tiempo mucho más pequeño que el
 * 		que hay por defecto.
 ** En Edificios e Investigaciones, si no llegan los recursos, aparecen en rojo, como en el modo
 * 		comandante. Si pasas por encima te sale un titulo con la cantidad que te falta y si pinchas
 * 		se añade esa cantidad a una tabla que aparece en el menú lateral. En esta tabla se guardan los
 * 		recursos en los que pinchaste y las coordenadas del planeta. Mediante esta tabla, podemos ir a otro/s
 * 		planeta/s para llevar los recursos que nos faltaban para poder hacer la construcción. Si no llegan
 * 		los recursos, se van restando los que envías, de modo que puedes mandar desde muchos planetas sin tener
 * 		que hacer círculos. (la tabla la podemos borrar en cualquier momento pinchando en la imagen que tiene encima)
 ** Opción de bloquear aquellas tecnologías que alcanzaron su máximo nivel práctico
 *  		inspirado en funciones de ogamePro
 ** Se cambia el aspecto de la página de salto cuántico
 *  		parte del codigo sacado de http://userscripts.org/scripts/show/7928
 ** Se colorean las coordenadas del planeta actual en la lista de viajes de la pantalla de flotas
 */


/*********************************************************/
/*********+-------------------------------+***************/
/*********|      TODO List                |***************/
/*********+-------------------------------+***************/
/*********************************************************/
/*
 * Colorear misiones a o desde el planeta actual en la vision de flotas
 * Reestructurar menu lateral (menudo caos!)
 * Modificar las tablas de configuración de colores y automarcado
 * Error del linker en vision general (la hora del foxgame aparece en la siguiente linea)
 * 		Curiosamente se resuelve al activar la hora en formato completo
 * Colorear fondo de los mensajes
 * Calculo de naves en los espionajes
 * Separador de miles en retornos de saqueos
 * Mostrar total del saqueo, y el equivalente en metal por regla 3x2x1 (Unidades Comerciales)
 * Comentar más el código... algún día :-)
 * Opción de pasar las cantidades en notación científica a notación normal
 * Añadir posibilidad de medir la rentabilidad del ataque en Unidades comerciales 
 * Añadir ogame tools (calculo de misiles con raksim...) al menu lateral (o incluso enlace
 * 		en informes tipo DS) y eliminar el enlace o-calc (si se consiguen sustituir todas sus funciones)
 * Mejorar GalaxieTool (comprobar que esta activado para nuestro universo o algo asi y mejorar la
 * 		vision de las lucecitas, mejorar el control de distintas cuentas)
 * Crear una paleta de colores para escoger colores (en una funcion) (de momento en la pagina de
 * 		configuración hay un enlace a una página que permite elegir colores y te dice el codigo html)
 * Ver la posibilidad de guardar y cargar la configuración en un archivo de texto
 * 		Una posibilidad es mostar las variables para copiarlas al guardar y para cargar que salga un input 
 * Añadir etiquetas para nicks
 * Color del linkeador dependiente de la distancia con tu principal!! (en proceso)
 * 		Y dependiente del planeta actual?
 */


/********************************************************/
/*********+-------------------------------+**************/
/*********|         Script values         |**************/
/*********+-------------------------------+**************/
/********************************************************/

const scriptSource = 'http://userscripts.org/scripts/source/8555.user.js';
const scriptPage = 'http://userscripts.org/scripts/show/8555';
const scriptAuthor = 'SpitFire';
const scriptName = 'OGame#';
const scriptVersion = '0.1.96';
const debugMode = false;


/********************************************************/
/*********+-------------------------------+**************/
/*********|  Default configuration values |**************/
/*********+-------------------------------+**************/
/********************************************************/

var defScriptConf = [
		'colorMens', true,
			'colorTrans', '#aaaaff', 
			'colorTransR', '#33ff99', 
			'colorDesp', '#11aa99', 
			'colorColo', '#99cc99',
			'colorAlianza', '#00ff00',
			'colorPriv', '#00aaff',
			'colorEsp', '#ff6666',
			'colorMisiles', '#ff3366',
			'colorRec', '#a96030',
			'colorConf', '#ff55dd',
			'colorBuddylist', '#66dddd',
		'autoMark', true,
			'AMTrans', true,
			'AMTransR', true,
			'AMDesp', true,
			'AMColo', true,
			'AMAlianza', false,
			'AMPriv', false,
			'AMEsp', false,
			'AMEspP', false,
			'AMEspPRecMin', '175000',
			'AMAttack', false,
			'AMMisiles', false,
			'AMRec', true,
			'AMConf', false,
			'AMBuddylist', false,
		'dragoSim', true,
		'dragoSimM', false,
		'CSim', true,
		'CSimM', false,
		'ocalc', false,
		'compactar', false,
		'galaxyTool', false,
			'galaxyToolM', false,
			'GTGV', false,
		'allyTags', true,
		'allyTable', true,
			'allyName', '',
			'foroAlly', '',
			'ATColorN', 'lime',
			'ATMembers', true,
			'ATTopP', true,
			'ATTopA', true,
			'ATForo', true,
			'ATBaned', true,
			'ATCC', true,
			'ATCCPriv', false,
		'coordLinker', true,
			'coordLinkerVarG', false,
			'coordLinkerVarM', false,
			'coordLinkerCF', 'orangered',
			'coordLinkerCM', 'lime',
			'coordLinkerCVG', '#ebff8a',
			'coordLinkerCG', 'lime',
		'flottenInfo', true,
		'debris', true,
			'debrisMin', '20000',
			'debrisMax', '100000',
			'debrisColor', '#6b3715',
		'modifyDate', false,
		'improvedResources', true,
		'improvedCuantic', true,
		'specialEffects', true,
		'LMSearch', false,
		'autoUpdate', true,
		'preDest', true,
			'PDGColor', 'orange',
		'proInputs', true,
		'tinyIMG', false,
		'transportMode', false,
		'transportModeEnabled', false,
		'TMDestination', '0;0;0;1',
		'refMens', 0,
		'moonSpy', false,
		'delBanner', false,
		'delBanners', false,
		'delOfficerMenu', false,
		'delOfficer', false,
		'colorBuild', false,
		'SYConst', false,
		'SYReducible', true,
		'colapseFlights', true,
		'blockUselessTechs', true,
		'menuCuantic', true,
		'buildingList', false,
		'imperium', false || debugMode
	].join(':');
var defGTValues = '';
var defAllyTags = 'Prueba:y:#00aaff:y:Ally1|Ally2|Ally3';


/*********************************************************/
/*********+-------------------------------+***************/
/*********|     Translation section       |***************/
/*********+-------------------------------+***************/
/*********************************************************/

const ilegal = ' <font color=red title="Esta opción está prohibida directa/indirectamente por el reglamento de OGame">(ilegal)</font>';
const ilegalCom = ' <font color=red title="Esta opción es ilegal porque implementa funciones del modo comandante">(ilegal)</font>';
const ilegalPub = ' <font color=red title="Esta opción es ilegal porque elimina publicidad">(ilegal)</font>';
const ilegalMenu = ' <font color=orangered title="Esta opción es ilegal porque modifica el menú lateral">(ilegal menú)</font>';
const ilegalDudosa = ' <font color=orangered title="Esta opción es potencialmente ilegal">(casi-ilegal)</font>';
const semiLegal = ' <font color=orange title="Algunos dicen que esta función no es legal 100%">(ilegal?)</font>';
const experimental = ' <font color=lightblue title="Función sin completar">(experimental)</font>';
const notYet = ' <font color=pink title="Aun no funciona">(sin acabar)</font>';

const c_mainTable = 'Ajustes Generales';
const c_colorMens = 'Colorear los mensajes (cabeceras y contenido)';
const c_colorTrans = 'Mensajes de llegada a un planeta';
const c_colorTransR = 'Mensajes de retorno de un planeta';
const c_colorDesp = 'Mensajes de despliegues en un planeta';
const c_colorAlianza = 'Mensajes de la Alianza';
const c_colorPriv = 'Mensajes privados';
const c_colorRec = 'Mensajes de reciclajes';
const c_colorEsp = 'Mensajes de espionajes sufridos';
const c_colorConf = 'Invitación de ataque de confederación';
const c_colorColo = 'Mensajes de colonización';
const c_colorMisiles = 'Mensajes de ataques con misiles';
const c_colorBuddylist = 'Mensajes de petición de amigos';
const c_autoMark = 'Auto marcar mensajes de transporte, recolección, etc.';
const c_allyTable = 'Activar tabla de alianza en el menú lateral (entrar en Alianzas para coger los datos)'+ilegalMenu;
const c_tablaAllyTable = 'Ajustes de la tabla de alianza';
const c_coordLinker = 'Colorear y arreglar links de coordenadas en los mensajes y visión general';
const c_tablaCoordLinker = 'Configuración del linkeador de coordenadas';
const c_coordLinkerVarG = 'Color en visión general dependiente de la distancia a tu planeta principal'+experimental;
const c_coordLinkerVarM = 'Color en mensajes dependiente de la distancia a tu planeta principal'+experimental;
const c_coordLinkerCF = 'Color del planeta actual en la pantalla de flotas';
const c_coordLinkerCM = 'Color de los links en los Mensajes';
const c_coordLinkerCVG = 'Color de los links en la Visión General';
const c_coordLinkerCG = 'Color del número de planeta marcado en Galaxia';
const c_dragoSim = 'Mostrar enlaces a Drago-Sim en los mensajes de espionaje';
const c_dragoSimM = 'Mostrar enlace a Drago-Sim en el menú lateral'+ilegalMenu;
const c_CSim = 'Mostrar enlaces a CSim en los mensajes de espionaje';
const c_CSimM = 'Mostrar enlace a CSim en el menú lateral'+ilegalMenu;
const c_ocalc = 'Mostrar enlace a O-Calc en el menú lateral'+ilegalMenu;
const c_modifyDate = 'Mostrar fecha en formato completo y reducir a una sola linea'+semiLegal;
const c_flottenInfo = 'Mostrar información de carga al escoger flota'+semiLegal;
const c_debris = 'Activar resaltado avanzado de escombros';
const c_tablaDebris = 'Configuración del resaltado de escombros <a color="lightblue" title="De blanco (min) al color seleccionado (máx)">(info)</a>';
const c_debrisColor = 'Color de resaltado';
const c_debrisMin = 'Máxima cantidad de escombros resaltable';
const c_debrisMax = 'Cantidad en la que el color es máximo';
const c_compactar = 'Usar compactador en los reportes de ataque';
const c_tinyIMG = 'Ver las imágenes de edificios, investigaciones, defensas y hangar en pequeño';
const c_proInputs = 'Añadir botones para control de unidades en hangar/defensas/flotas/salto cuántico';
const c_allyTags = 'Colorear etiquetas de alianzas en la visión de galaxia y en estadísticas'+semiLegal;
const c_tablaAllyTags = 'Etiquetar alianzas en visión de galaxia y estadísticas';
const c_galaxyTool = "Usar <a href='http://www.galaxietool.de/spanish/index.php' title='Qué es esto?' target='new'>Galaxy Tool</a>";
const c_GTGV = "Mostrar enlace a galaxia en galaxyTool al lado de Galaxia en el menú lateral"+ilegalMenu;
const c_galaxyToolM = "Mostrar enlace al servidor de GalaxyTool en el menú lateral"+ilegalMenu;
const c_tablaGTool = 'Configuración de Galaxy Tool ('+location.hostname+')';
const c_improvedResources = 'Mostrar información extra en la pantalla de recursos';
const c_improvedCuantic = 'Mejorar aspecto de la pantalla de salto cuántico';
const c_moonSpy = 'Habilita la posibilidad de espiar lunas y recolectar escombros en la Galaxia'+ilegalCom;
const c_refMens = 'Intervalo de actualización de los mensajes (0 deshabilita)'+ilegal;
const c_transportMode = 'Usar modo transporte'+ilegalDudosa;
const c_transportModeTable = 'Configuración del modo transporte';
const c_delBanner = 'Eliminar banner de la visión general'+ilegalPub;
const c_delBanners = 'Eliminar banners de publicidad'+ilegalPub;
const c_delOfficerMenu = 'Eliminar letrero de Casino de los Oficiales del menú lateral'+ilegalPub;
const c_delOfficer = 'Elimina los iconos de publicidad de los oficiales en todas las páginas'+ilegalPub;
const c_colorBuild = 'Colorear en rojo construcciones e investigaciones demasiado caras'+ilegalCom;
const c_SYConst = 'Indica máximo de unidades a crear en hangar/defensa y permite contruir más de 999'+ilegalCom;
const c_SYReducible = 'Añadir botones para ocultar/mostrar unidades en hangar/defensa';
const c_colapseFlights = 'Añadir botones para ocultar/mostrar vuelos en visión general y flotas';
const c_AMTrans = 'Mensajes de llegada a un planeta';
const c_AMTransR = 'Mensajes de retorno de un planeta';
const c_AMDesp = 'Mensajes de despliegues en un planeta';
const c_AMColo = 'Mensajes de colonización';
const c_AMAlianza = 'Mensajes de la Alianza';
const c_AMPriv = 'Mensajes privados';
const c_AMEsp = 'Mensajes de espionajes sufridos';
const c_AMEspP = 'Mensajes de espionajes hechos';
const c_AMEspPRecMin = 'Espionajes con menos recursos que esta cantidad'+ilegalDudosa;
const c_AMAttack = 'Informes de ataques';
const c_AMMisiles = 'Avisos de ataques con misiles';
const c_AMRec = 'Mensajes de reciclajes';
const c_AMConf = 'Mensajes de invitación a un ataque de confederación';
const c_AMBuddylist = 'Mensajes de petición de amigos';
const c_ATMembers = 'Mostrar enlace a los miembros de alianza ordenados por puntuación';
const c_ATTopP = 'Mostrar enlace al top 100 de jugadores';
const c_ATTopA = 'Mostrar enlace al top 100 de alianzas';
const c_ATForo = 'Mostrar enlace al foro';
const c_ATCC = 'Mostrar enviar CC (si se tiene permiso)';
const c_ATBaned = 'Mostrar enlace a la página de jugadores baneados';
const c_ATColorN = 'Color del nombre de alianza en la tabla';
const c_specialEffects = 'Activar efectos especiales';
const c_autoUpdate = 'Buscar actualizaciones automáticamente (una vez al día)';
const c_LMSearch = 'Cambiar la opción de búsqueda del menú lateral por un formulario'+ilegalMenu;
const c_blockUselessTechs = 'Bloquear tecnologías que han alcanzado su límite práctico';
const c_menuCuantic = 'Añadir un enlace al salto cuántico en el menú lateral'+ilegalMenu;
const c_buildingList = 'Cola de construcción para los edificios'+notYet+ilegalCom;

const c_cuantic = 'Salto cuántico';
const c_full = 'LLeno';
const c_noProduction = 'Sin producción';
const c_emptyingStore = '¡El almacén se está vaciando!';


// Names of buildings, ships, ...
const c_gidNames = new Array();
/* buildings */
c_gidNames['1'] = 'Mina de metal';
c_gidNames['2'] = 'Mina de cristal';
c_gidNames['3'] = 'Sintetizador de deuterio';
c_gidNames['4'] = 'Planta de energía solar';
c_gidNames['12'] = 'Planta de fusión';
c_gidNames['14'] = 'Fábrica de Robots';
c_gidNames['15'] = 'Fábrica de Nanobots';
c_gidNames['21'] = 'Hangar';
c_gidNames['22'] = 'Almacén de metal';
c_gidNames['23'] = 'Almacén de cristal';
c_gidNames['24'] = 'Contenedor de deuterio';
c_gidNames['31'] = 'Laboratorio de investigación';
c_gidNames['33'] = 'Terraformer';
c_gidNames['34'] = 'Depósito de la Alianza';
c_gidNames['41'] = 'Base lunar';
c_gidNames['42'] = 'Sensor Phalanx';
c_gidNames['43'] = 'Salto cuántico';
c_gidNames['44'] = 'Silo';

/* investigaciones */
c_gidNames['106'] = 'Tecnología de espionaje';
c_gidNames['108'] = 'Tecnología de computación';
c_gidNames['109'] = 'Tecnología militar';
c_gidNames['110'] = 'Tecnología de defensa';
c_gidNames['111'] = 'Tecnología de blindaje';
c_gidNames['113'] = 'Tecnología de energía';
c_gidNames['114'] = 'Tecnología de hiperespacio';
c_gidNames['115'] = 'Motor de combustión';
c_gidNames['117'] = 'Motor de impulso';
c_gidNames['118'] = 'Propulsor hiperespacial';
c_gidNames['120'] = 'Tecnología láser';
c_gidNames['121'] = 'Tecnología iónica';
c_gidNames['122'] = 'Tecnología de plasma';
c_gidNames['123'] = 'Red de investigación intergaláctica';
c_gidNames['199'] = 'Tecnología de gravitón';

/* naves */
c_gidNames['202'] = 'Nave pequeña de carga';
c_gidNames['203'] = 'Nave grande de carga';
c_gidNames['204'] = 'Cazador ligero';
c_gidNames['205'] = 'Cazador pesado';
c_gidNames['206'] = 'Crucero';
c_gidNames['207'] = 'Nave de batalla';
c_gidNames['208'] = 'Colonizador';
c_gidNames['209'] = 'Reciclador';
c_gidNames['210'] = 'Sonda de espionaje';
c_gidNames['211'] = 'Bombardero';
c_gidNames['212'] = 'Satélite solar';
c_gidNames['213'] = 'Destructor';
c_gidNames['214'] = 'Estrella de la muerte';
c_gidNames['215'] = 'Acorazado';

/* defensas */
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';
c_gidNames[''] = '';


/********************************************************/
/*********+-------------------------------+**************/
/*********|         Script graphics       |**************/
/*********+-------------------------------+**************/
/********************************************************/

const ledGreen = 'data:image/gif;base64,R0lGODlhDgAOAMIGAL+/vwAAADLNMi6LV5j7mC9PT////////yH5BAEAAAcALAIAAgAKAAsAAAMqeBoc+oFI4RYxRIjh4p0bI2TZYDKkthWiag5soA0bzB7Ba1e4fT+4xiMBADs=';
const ledRed = 'data:image/gif;base64,R0lGODlhDgAOAMIGAL+/vwAAAP9EH+ozIOJtWZ02Ev///////yH5BAEAAAcALAIAAgAKAAsAAAMqeBoc+oFI4RYxRIjh4p0bI2TZYDKkthWiag5soA0bzB7Ba1e4fT+4xiMBADs=';
const lessButton = 'data:image/gif;base64,R0lGODlhCQAJAPAAAAAAAP///yH5BAAAAAAALAAAAAAJAAkAAAggAAEIHEgwgMGDAQQiPKhwYUIADwc+dDjRYcOFBDMCCAgAOw==';
const moreButton = 'data:image/gif;base64,R0lGODlhCQAJAPAAAAAAAP///yH5BAAAAAAALAAAAAAJAAkAAAghAAEIHEgwgMGDAQQeBLCQoUGHCRkSlAixYsWGCBtOHBgQADs=';
const DSimIco = 'data:image/gif;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAEgAAABIAAAAAAAAAAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8AAP8AAP8AAP8AAP8AAP8AAP8AAP8AAP////////////////////////////////8AAP8AAP8AAP8AAP8AAP8AAP8AAP8AAP8AAP////////////////////////////////8AAP8AAP////////////////8AAP8AAP8AAP////////////////////////////8AAP8AAP////////////////////8AAP8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////////8AAP8AAP////////////////////8AAP8AAP8AAP////////////////////////8AAP8AAP////////////////8AAP8AAP8AAP////////////////////////8AAP8AAP8AAP8AAP8AAP8AAP8AAP8AAP8AAP////////////////////////////8AAP8AAP8AAP8AAP8AAP8AAP8AAP8AAP////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
const CSimIco = 'data:image/gif;base64,R0lGODlhZABkAOYAAJGZpYOMm73Bybe8xHJ7jHuElKOptJqhrWFsfoyUokNQZWl0hcbJ0BkqRYqRnGxxe1VcZpSbqBYmQUFOZElVaUNMW0VSaElTYx4uSHyBisnM0kVHSzU3PFRXXCk5UoSJkktYbTJAWXF0eS08VVF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035IIASzAgKwJFm2Jl/jUPYor7iEhFFIjVx3XHvIhIHId2pEqdnIib8YVocHUNC0lELoe/swaxCUhU30f9pH/HyFCXLRBzRG9Kl+tJAViCPTHB4JwV5SGCF/WemOaIIC9qcihGq2hXs3hHKZt2qQ9G3cd0UjyEBKxXBDDE4Nwowlinme6Hj26m6qhHD7GGo/hpLdxGdyRGVWBJ3ghauMR24kAee/zB8yNCMzN1OQpFiNhEiiBFEuR2we23dvtoZmhGTRx3MslUrItnj/hoBIpEppaFCmxEiAKFXMhFSIKEzLBEJxx3CG1RSp0CH8mCP3N334mCX82sUDhDEKBDgExEAaREAxe3ypKBA9xF85wTuiUTuWdCKpAses64UIREuxQE+YgEROuFXqxRVzkCDxySX+Q4oLA4ivOIy3OIxuRo64U6xHiUA04bg0UUeK7xEVKfeGI4La48ApEXuQ9zhf7DQnSIQhL/gdN/uTR0baoEAtUPgrgAuRYnuW1gBohIAgHJgjB3eV/EOZgvhZiruVonuZqngkyIROCYBAGIQgJ8eZw/uYKseZ4nud6bghIpgyC0Od78OdItgaCjmSCYA3WsOfcQB2M3uiOPlyKHumSPumUXumWfumYnumavumc3ulrHggAOw==';


/*********************************************************/
/*********+-------------------------------+***************/
/*********|         content               |***************/
/*********+-------------------------------+***************/
/*********************************************************/

try {
	var contentSection = location.href.match(/page=([^&]+)/)[1];
	if (debugMode) GM_log('Section: ' + contentSection);
} catch(e){'Error detecting section: '+GM_log(e)}

/*********************************************************/
/*********+-------------------------------+***************/
/*********|   Detecting some sections     |***************/
/*********+-------------------------------+***************/
/*********************************************************/

var buildingsSection = contentSection == 'b_building';
var techsSection = document.baseURI.indexOf('mode=Forschung')!=-1;
var hangarSection = document.baseURI.indexOf('mode=Flotte')!=-1 && document.baseURI.indexOf('page=buildings')!=-1;
var defenseSection = document.baseURI.indexOf('mode=Verteidigung')!=-1;
var cuanticSection = document.baseURI.indexOf('&gid=43')!=-1;


/*********************************************************/
/*********+-------------------------------+***************/
/*********| Variable management functions |***************/
/*********+-------------------------------+***************/
/*********************************************************/


/******* Generalized conf functions section ***************/

function getConf(nombre, confName, defConfName, separator) {
	var conf = GM_getValue(confName,defConfName).split(separator);
	for (var i=0; i<conf.length; i+=2) {
		if (conf[i]==nombre) {
			if (conf[i+1]=='false')
				return false;
			return conf[i+1];
		}
	}
	conf = defConfName.split(separator);
	for (var i=0; i<conf.length; i+=2) {
		if (conf[i]==nombre) {
			if (conf[i+1]=='false')
				return false;
			return conf[i+1];
		}
	}
	return false;
}

function setConf(nombre, valor, confName, defConfName, separator) {
	var confStr = GM_getValue(confName, '');
	if (confStr=='') {
		GM_setValue(confName, [nombre, valor].join(separator));
		return;
	}
	var conf = confStr.split(separator);
	var valorDef = (String(getDefConf(nombre, defConfName, separator))==String(valor));
//		GM_log(getDefConf(nombre, defConfName, separator)+' -> '+valor);
		if (conf.length<=1) {
			if (!valorDef) GM_setValue(confName, [nombre, valor].join(separator))
			return;
		}
		for (var i=0; i<conf.length; i+=2) {
			if (conf[i]==nombre) {
				if (valorDef) conf.splice(i, 2);
				else conf[i+1]=valor;
				GM_setValue(confName, conf.join(separator));
				return;
			}
		}
		if (!valorDef) GM_setValue(confName, [confStr,nombre,valor].join(separator));
}

unsafeWindow.getConf=getConf;
unsafeWindow.setConf=setConf;

/*********** Specific conf functions *********************/

function getScriptConf(nombre) {
	return getConf(nombre, "scriptConf_"+location.hostname, defScriptConf, ':');
}

function setScriptConf(nombre, valor) {
	setConf(nombre, valor, "scriptConf_"+location.hostname, defScriptConf, ':');
}

function getBuildings(planetCode) {
	if (planetCode) {
		return getConf(planetCode,'buildings_' + location.hostname, '', ':');
	}
	else return GM_getValue('buildings_' + location.hostname, '').split(':');
}

function setBuildings(planetCode, gids, levels) {
	return setConf(planetCode, [gids.join('-'), levels.join('-')].join(';'),'buildings_' + location.hostname, planetCode+':;', ':');
}

function getGidTag(gid) {
	return getConf(gid, 'gidTags', '', ':');
}

function setGidTag(gid, nam) {
	return setConf(String(gid), nam, 'gidTags', '', ':');
}

function getBLStatus(planetCode) {
	if (planetCode)
		return getConf(planetCode, 'BLStatus_'+location.hostname, '', ':');
	else return GM_getValue('BLStatus_'+location.hostname, '').split(':');
}

// status can be: 'stopped' or the UTC when the build ends
function setBLStatus(planetCode, status) {
	return setConf(planetCode, status, 'BLStatus_'+location.hostname, '', ':');
}

function getTech(nombre) {
	var tech = getConf(nombre, "techs_"+location.hostname, '', ':');
	if (tech) return parseInt(tech, 10);
	else return 0;
}

function setTech(nombre, valor) {
	setConf(nombre, valor, "techs_"+location.hostname, '', ':');
}

function getSession(hostname) {
	return getConf(hostname, "session", '', ':');
}

function setSession(hostname, session) {
	return setConf(hostname, session, "session", '', ':');
}

function getUserName() {
	return getConf(location.hostname, 'userName', '', ':');
}

function setUserName(name) {
	return setConf(location.hostname, name, "userName", '', ':');
}

function setBooleanConf(nombre, value) {
	var hiddenStr = GM_getValue(nombre+'_'+location.hostname, '');
	var hiddenVec = hiddenStr.split(':');
	for (var h in hiddenVec) {
		if (hiddenVec[h]==value) {
			return false;
		}
	}
	GM_setValue(nombre+'_'+location.hostname, (hiddenStr==''?String(value):hiddenStr+':'+value));
	return true;
}

function delBooleanConf(nombre, value) {
	var hiddenVec = GM_getValue(nombre+'_'+location.hostname, '').split(':');
	for (var h in hiddenVec) {
		if (hiddenVec[h]==value) {
			hiddenVec.splice(h, 1);
			GM_setValue(nombre+'_'+location.hostname, hiddenVec.join(':'));
			return true;
		}
	}
	return false;
}

function getBooleanConf(nombre, value) {
	var hiddenVec = GM_getValue(nombre+'_'+location.hostname, '').split(':');
	for (var h in hiddenVec) {
		if (hiddenVec[h]==value) {
			return h;
		}
	}
	return false;
}

function getMainP() {
	var temp = getConf(location.hostname, "MainP", '', ';');
	if (temp) return temp;
	else return '1:1:1';
}

function setMainP(MainP) {
	return setConf(location.hostname, MainP, "MainP", '', ';');
}

function getSpyReports(SpyID) {
	return GM_getValue('SpyReports_' + location.hostname, '').split(':y:');
}

function getSpyPosById(SpyID) {
	return getBooleanConf('SpyReportIDs', spyID);
}

function getSpyPosByCoords(coords) {
	var validatedCoords;
	if (validatedCoords = validCoords(coords))
		return getBooleanConf('SpyReportCoords', validatedCoords[0].replace(/:/g, ';'));
	return false;
}

function getSpy(n) {
	return GM_getValue('SpyReports_' + location.hostname, '').split(':y:')[n].split(':x:');
}

function saveSpy(SpyID, SpyCoords, SpyContent) {
	var validatedCoords;
	if (validatedCoords = validCoords(SpyCoords)) {
	// y por que no con setbooleanconf??????
		SIDs = GM_getValue('SpyReportIDs_' + location.hostname, '');
		GM_setValue('SpyReportIDs_' + location.hostname, (SIDs!=''?SIDs + ':':'') + SpyID);
		SCs = GM_getValue('SpyReportCoords_' + location.hostname, '');
		GM_setValue('SpyReportCoords_' + location.hostname, (SCs!=''?SCs + ':':'') + validatedCoords[0].replace(/:/g, ';'))
		SC = GM_getValue('SpyReports_' + location.hostname, '');
		return setConf(SpyID, SpyContent, 'SpyReports_' + location.hostname, '', ':y:');
	}
	return false;
}

function delSpy(n) {
	
}

function getDefConf(nom, defConfNam, sep) {
	return getConf(nom, '', defConfNam, sep);
}

function getDefScriptConf(nom) {
	return getConf(nom, '', defScriptConf, ':');
}

unsafeWindow.getScriptConf=getScriptConf;
unsafeWindow.setScriptConf=setScriptConf;
unsafeWindow.getSession=getSession;
unsafeWindow.setSession=setSession;
unsafeWindow.getMainP=getMainP;
unsafeWindow.setMainP=setMainP;
unsafeWindow.getSpyReports=getSpyReports;
unsafeWindow.getSpyPosById=getSpyPosById;
unsafeWindow.saveSpy=saveSpy;


/*************** GalaxieTool Section *********************/

function getGTName(hostname) {
	var GTValues = GM_getValue("GTValues",defGTValues);
	if (GTValues!='') GTValues=GTValues.split(':x:');
	else return '';
	for (var i=0; i<GTValues.length; i+=4) {
		if (GTValues[i]==hostname) {
			return GTValues[i+1];
		}
	}
	return '';
}
unsafeWindow.getGTName=getGTName;

function getGTPass(hostname) {
	var GTValues = GM_getValue("GTValues",defGTValues).split(':x:');
	for (var i=0; i<GTValues.length; i+=4) {
		if (GTValues[i]==hostname) {
			return GTValues[i+2];
		}
	}
	return '';
}
unsafeWindow.getGTPass=getGTPass;

function getGTUrl(hostname) {
	var GTValues = GM_getValue("GTValues",defGTValues).split(':x:');
	for (var i=0; i<GTValues.length; i+=4) {
		if (GTValues[i]==hostname) {
			return GTValues[i+3];
		}
	}
	return '';
}
unsafeWindow.getGTUrl=getGTUrl;

function addGTUser(hostname, username, pass, url) {
	var GTValuesStr = GM_getValue("GTValues",defGTValues);
	var GTValues = GTValuesStr.split(':x:');
	for (var i=0; i<GTValues.length; i+=4) {
		if (GTValues[i]==hostname) {
			GTValues[i+1]=username;
			GTValues[i+2]=pass;
			GTValues[i+3]=url;
			GM_setValue("GTValues", GTValues.join(':x:'));
			return;
		}
	}
	if (GTValuesStr!='') GM_setValue("GTValues", ([GTValuesStr,hostname,username,pass,url].join(':x:')));
	else GM_setValue("GTValues", ([hostname,username,pass,url].join(':x:')));
}
unsafeWindow.addGTUser=addGTUser;

function delGTUser(hostname) {
	var GTValuesStr = GM_getValue("GTValues",defGTValues);
	var GTValues = GTValuesStr.split(':x:');
	for (var i=0; i<GTValues.length; i+=4) {
		if (GTValues[i]==hostname) {
			GTValues.splice(i, 4);
			GM_setValue("GTValues", GTValues.join(':x:'));
			return;
		}
	}
}
unsafeWindow.delGTUser=delGTUser;

/*************** reset/save functions ********************/

unsafeWindow.saveScriptConf = function saveScriptConf(hostname) {
	var config = document.getElementsByName('conf');
	for (var i=0; i<config.length;i++) {
		if (config[i].value!='on') setScriptConf(config[i].id, config[i].value);
		else {
			setScriptConf(config[i].id, config[i].checked);
			if (config[i].id=='colorMens' && config[i].checked) {
				var color = document.getElementsByName('color');
				for (var j=0; j<color.length;j++) {
					setScriptConf(color[j].id, color[j].value);
				}    
			}
			else if (config[i].id=='autoMark' && config[i].checked) {
				var autoMark = document.getElementsByName('autoMark');
				for (var j=0; j<autoMark.length;j++) {
					setScriptConf(autoMark[j].id, autoMark[j].checked);
				}    
			}
			else if (config[i].id=='galaxyTool' && config[i].checked) {
				var nodos = document.getElementsByName('GTUser');
				var loc=location.hostname;
			  var j = '1';
				for (var k=1; k<nodos.length; k++)
					if (nodos[k].childNodes[1].firstChild.value!='') {
						addGTUser(loc+(j=='1'?'':j), nodos[k].childNodes[1].firstChild.value, nodos[k].childNodes[2].firstChild.value, nodos[k].childNodes[3].firstChild.value);
						j++;
					}
					for (var x=j; getGTName(loc+x!=''); x++)
						alert('borrando ' +loc+x);
						delGTUser(loc+x);
			}
			else if (config[i].id=='allyTags' && config[i].checked) {
				var nodos = document.getElementsByName('allyTag');
				var tags = document.getElementsByName('ATTag');
				var colores = document.getElementsByName('ATColor');
				var alianzas = document.getElementsByName('ATAllys');
				var cadena='';
				for (var k=1; k<nodos.length; k++) {
					if ((colores[k].value!='')&&(alianzas[k].value!='')) {
						if (cadena=='') cadena = [tags[k].value, colores[k].value, alianzas[k].value].join(':y:');
						else cadena = [cadena, [tags[k].value, colores[k].value, alianzas[k].value].join(':y:')].join(':x:');
					}
				}
				GM_setValue('allyTags', cadena);
			}
		}
	}
	location.reload();
}

unsafeWindow.resetScriptConf = function resetScriptConf() {
	GM_setValue('scriptConf', defScriptConf);
}
unsafeWindow.resetCompactConf = function resetCompactConf() {
	GM_setValue('compactConf', defCompactConf);
}
unsafeWindow.loadScriptConf = function loadScriptConf() {
	alert('Función aun no implementada');
}
unsafeWindow.printScriptConf = function printScriptConf() {
	alert('Función aun no implementada');
}

/*********************************************************/
/*********+-------------------------------+***************/
/*********|        Misc functions         |***************/
/*********+-------------------------------+***************/
/*********************************************************/

function locate(xpath, xpres, where) {
	if (where==null)
		return document.evaluate(xpath, document, null, xpres, null);
	return document.evaluate(xpath, where, null, xpres, null);
}

function locateFirst(xpath, where) {
	return locate(xpath, XPathResult.FIRST_ORDERED_NODE_TYPE, where).singleNodeValue;
}

function locateSnapshot(xpath, where) {
	return locate(xpath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, where);
}

function fill(string) {
	while (string.length<6) string += '0';
	return parseInt(string, 10);
}

function tiempo2str(max, cur, prod) {
	if (prod==0) return c_noProduction;
	if (prod<0) {
		var result = "<font color=red title='"+c_emptyingStore+"'>-";
		var negative = true;
		var totalSecs = Math.floor(-(max-cur)/prod * 3600);
	}
	else {
		if (cur>max) return c_full;
		var result = "";
		var totalSecs = Math.floor((max-cur)/prod * 3600);
	}
	var secs = Math.floor(totalSecs%60);
	var mins = Math.floor((totalSecs/60)%60);
	var hours = Math.floor((totalSecs/3600)%24);
	var days = Math.floor(totalSecs/(3600*24));

	if (days>0) result += days+'d ';
	if (hours>0 || days>0) result += hours+'h ';
	if (mins>0 || hours>0 || days>0) result += mins+'m ';
	if (secs>0 || mins>0 || hours>0 || days>0) result += secs+'s';
	if (negative) result += "</font>";
	return result;
}
		

function validCoords(coords) {
	try {
		var sepCoords=coords.match(/^\[?([1-9]):([1-4]\d{2}|[1-9]\d|[1-9]):(1[0-5]|[1-9])\]?$/);
		return sepCoords;
	} catch (e) {}
	return false;
}

function getColorLinker(planet) {
	var mainP = getMainP().split(':');
	var coord = planet.replace(/[\[\]]/g, '').split(':');
	var color = '';
			
	var distancia = 0;
	if (coord[0]!=mainP[0]) {
		distancia = 1000000 + 5000 * (Math.abs(parseInt(coord[0], 10)-parseInt(mainP[0], 10)));
		color = 'red';
	}
	else if (coord[1]!=mainP[1]) {
		distancia = 2700000 + 95000 * (Math.abs(parseInt(coord[1], 10)-parseInt(mainP[1], 10)));
		color = 'orange';
	}
	else if (coord[2]!=mainP[2]) {
		distancia = 20000000 * (Math.abs(parseInt(coord[2], 10)-parseInt(mainP[2], 10)));
		color = 'yellow';
	}
	else {
		distancia = 0;
		color = 'lightblue';
	}
	// eliminar color de los ifs y hacer que el color dependa de la distancia
//	GM_log(distancia);
	return color;
}

function setMoonList(list) {
	return GM_setValue('moonList_' + location.hostname, list);
}

/*function getMoonList() {
	return
}*/

function isMoon(planetCode) {
	return GM_getValue('moonList_' + location.hostname, '').indexOf(planetCode)!=-1;
}

function setHiddenShip(shipId) {
	hideIdNoEffects('photo_'+shipId);
	hideIdNoEffects('desc_'+shipId);
	hideIdNoEffects('input_'+shipId);
	showId('mini_'+shipId);
	return setBooleanConf('hiddenShips', shipId);
}

function delHiddenShip(shipId) {
	showId('photo_'+shipId);
	showId('desc_'+shipId);
	showId('input_'+shipId);
	hideIdNoEffects('mini_'+shipId);
	return delBooleanConf('hiddenShips', shipId);
}

function setFlightsHidden(page) {
	hideIdNoEffects('flight_minus');
	showIdNoEffects('flight_plus');
	showId('numFlights');
	var i=0;
	while (hideId('flight'+i)) {i++;}
	return setBooleanConf('hiddenFlights', page);
} unsafeWindow.setFlightsHidden = setFlightsHidden;
		
function delFlightsHidden(page) {
	showIdNoEffects('flight_minus');
	hideIdNoEffects('flight_plus');
	hideId('numFlights');
	var i=0;
	while (showId('flight'+i)) {i++;}
	return delBooleanConf('hiddenFlights', page);
} unsafeWindow.delFlightsHidden = delFlightsHidden;
		
function isHiddenShip(shipId) {
	return getBooleanConf('hiddenShips', shipId);
}

function setHidden(n) {
	return setBooleanConf('hiddenTabs', n);
}

function delHidden(n) {
	return delBooleanConf('hiddenTabs', n);
}

function isHidden(n) {
	return getBooleanConf('hiddenTabs', n);
}

function checkUpdates(manualUpdate) {
	if (manualUpdate || (new Date()).getDate() != GM_getValue('lastUpdate', 0)) // Se actualiza solo de forma manual o de forma automatica una vez al dia
	GM_xmlhttpRequest({
		method:"POST",
		url:scriptPage,
		headers:{
			"User-Agent" : navigator.userAgent,
			"Accept" : "text/xml",
			"Content-type" : 'application/x-www-form-urlencoded'
		},
		onload:function(details) {
			try {
				GM_setValue('lastUpdate', (new Date()).getDate());
				var newVer = details.responseText.match(/Version (\d+)\.(\d+)\.(\d+)/);
				var Current = scriptVersion.match(/(\d+)\.(\d+)\.(\d+)/);
				if (parseInt([fill(newVer[1]), fill(newVer[2]), fill(newVer[3])].join(''), 10)>parseInt([fill(Current[1]), fill(Current[2]), fill(Current[3])].join(''), 10)) {
					if (confirm('Hay una versión nueva de '+scriptName+' ('+newVer[0]+')!! Quieres instalarla?')) {
						win = window.open(scriptSource, 'Actualizar script');
						if (!win) alert('Firefox está bloqueando las ventanas emergentes, habilita las ventanas emergentes para TU SERVIDOR concreto (el titulo de esta ventana de aviso) o bien dale a mostrar la pagina en el icono de bloqueo')
					}
				}
				else if (manualUpdate) alert('Tu versión es la más reciente');
			} catch (e) {}
		},
		data: ''
	});
}

function puntuar(numero, separador) {
	if (!separador) var separador = '.';
	var strNum=String(parseInt(numero, 10));
	var strNum2='';
	var i=0;
	for(i=strNum.length-4;i>=0;i-=3) {
		strNum2=(strNum[i]=='-'?'':separador)+strNum.substring(i+1, i+4)+strNum2;
	}
	strNum2=strNum.substr(0, i+4)+strNum2;
	return strNum2;
}

unsafeWindow.checkUpdates = checkUpdates;
unsafeWindow.fill = fill;
unsafeWindow.setHiddenShip = setHiddenShip;
unsafeWindow.delHiddenShip = delHiddenShip;
unsafeWindow.isHiddenShip = isHiddenShip;
//unsafeWindow.validCoords=validCoords;
//unsafeWindow.puntuar=puntuar;


/*********************************************************/
/*********+-------------------------------+***************/
/*********|    Functions for proInputs    |***************/
/*********+-------------------------------+***************/
/*********************************************************/

if (getScriptConf('proInputs') && ((contentSection=='buildings' && (document.baseURI.indexOf('mode=Flotte')!=-1 ||
	document.baseURI.indexOf('mode=Verteidigung')!=-1)) || contentSection=='flotten1' || document.baseURI.indexOf('&gid=43')!=-1)) {
	unsafeWindow.incrementar = function incrementar(variable) {
		return variable += parseInt((1+variable)/2, 10);
	}

	unsafeWindow.contador = 5;
	unsafeWindow.incremento = 1;
	unsafeWindow.pressed = false;
				
	unsafeWindow.cambiar = function(nombre, aumentar, max) {
		if (debugMode) GM_log('contador: '+unsafeWindow.contador+ ' incremento: ' + unsafeWindow.incremento);
		var input = document.getElementsByName(nombre)[0];
		if (aumentar) 
			var newValue = parseInt(input.value, 10) + unsafeWindow.incremento;
		else
			var newValue = parseInt(input.value, 10) - unsafeWindow.incremento;
		if (unsafeWindow.pressed) {
			if ((newValue<=max && aumentar) || (newValue>=0 && !aumentar)) {
				input.value = newValue;
				setTimeout('cambiar("'+nombre+'", '+aumentar+', '+max+')', 200);
				unsafeWindow.contador--;
				if (unsafeWindow.contador==0) {
					unsafeWindow.incremento=unsafeWindow.incrementar(unsafeWindow.incremento);
					unsafeWindow.contador=5;
				}
			}
			else {
				if (aumentar) input.value = max;
				else input.value = 0;
				unsafeWindow.contador=5;
				unsafeWindow.incremento=1;
			}
		}
	}
}


/*********************************************************/
/*********+-------------------------------+***************/
/*********|      Effects functions        |***************/
/*********+-------------------------------+***************/
/*********************************************************/

	function hideEffects(path, list, level) {
		var object = locateSnapshot(path);
		var pos = list.split(':');
		if (!level) {
			setHidden(pos[0])
			var level = 1.0;
		}
		for (var i in pos) {
			object.snapshotItem(pos[i]).style['opacity']=level;
			if (parseFloat(level)<0.1) {
				object.snapshotItem(pos[i]).style['display']='none';
			}
		}
		if (parseFloat(level)>0.1) setTimeout("hide('"+path+"', '"+list+"', "+(parseFloat(level)-0.1)+")", 30);
		else {
			object.snapshotItem(parseInt(pos[0])-1, 10).setAttribute('onclick', "show('"+path+"', '" + list + "')");
			object.snapshotItem(parseInt(pos[0])-1, 10).title='Click aqui para expandir';
		}
	}
	function showEffects(path, list, level) {
		var pos = list.split(':');
		var object = locateSnapshot(path);
		if (!level) {
			delHidden(pos[0]);
			var level = 0.0;
		}
		for (var i in pos) {
			if (level==0.0) object.snapshotItem(pos[i]).style['display']='';
			object.snapshotItem(pos[i]).style['opacity']=level;
		}
		
		if (parseFloat(level)<0.9) {
			setTimeout("show('"+path+"', '"+list+"', "+String(parseFloat(level)+0.1)+")", 30);
		}
		else {
			object.snapshotItem(parseInt(pos[0])-1, 10).setAttribute('onclick', "hide('"+path+"', '" + list + "')");
			object.snapshotItem(parseInt(pos[0])-1, 10).title='Click aqui para contraer';
		}
	}
	function hideIdEffects(id, level) {
		if (!level) var level = 1.0;
		var object = document.getElementById(id);
		if (object) {
			object.style['opacity']=level;
			if (parseFloat(level)<0.1) {
				object.style['display']='none';
				object.style['opacity']='1.0';  // por el caso de mostrarlo desde otro frame
			}
			else setTimeout("hideId('"+id+"', "+(level-0.1)+")", 30);
			return true;
		} else return false;
	}
	function showIdEffects(id, level) {
		var object = document.getElementById(id);
		if (object) {
			if (!level) {
				var level = 0.0;
				object.style['display']='';
			}
			object.style['opacity']=level;
			if (parseFloat(level)<1.0) setTimeout("showId('"+id+"', "+(level+0.1)+")", 30);
			return true;
		} else return false;
	}
	function hideIdNoEffects(id, level) {
		try {
			document.getElementById(id).style['display']='none';
			return true;
		} catch(e) {return false}
	}
	function showIdNoEffects(id, level) {
		try {
			document.getElementById(id).style['display']='';
			return true;
		} catch(e) {return false}
	}
	function hideNoEffects(path, list, level) {
		var pos = list.split(':');
		var object = locateSnapshot(path);
		setHidden(pos[0]);
		for (var i in pos)
			object.snapshotItem(pos[i]).style['display']='none';
		object.snapshotItem(parseInt(pos[0])-1, 10).setAttribute('onclick', "show('"+path+"', '" + list + "')");
		object.snapshotItem(parseInt(pos[0])-1, 10).title='Click aqui para expandir';
	}
	function showNoEffects(path, list, level) {
		var pos = list.split(':');
		var object = locateSnapshot(path);
		delHidden(pos[0]);
		for (var i in pos)
			object.snapshotItem(pos[i]).style['display']='';
		object.snapshotItem(parseInt(pos[0])-1, 10).setAttribute('onclick', "hide('"+path+"', '" + list + "')");
		object.snapshotItem(parseInt(pos[0])-1, 10).title='Click aqui para contraer';
	}
if (getScriptConf('specialEffects')) {
	var hide = hideEffects;
	var show = showEffects;
	var hideId = hideIdEffects;
	var showId = showIdEffects;
}
else { // no special effects
	var hide = hideNoEffects;
	var show = showNoEffects;
	var hideId = hideIdNoEffects;
	var showId = showIdNoEffects;
}
unsafeWindow.hide = hide;
unsafeWindow.show = show;
unsafeWindow.hideId = hideId;
unsafeWindow.showId = showId;


/*********************************************************/
/*********+-------------------------------+***************/
/*********|      FarmList functions       |***************/
/*********+-------------------------------+***************/
/*********************************************************/

var server = location.host;

function addCoords(coords, name) {
	if (!coords) {
		var coords = prompt('Introduce coordenadas en formato X:XXX:XX');
		if (coords==null) return false;
	}
	if (!validCoords(coords)) {
		alert('Las coordenadas no son validas!');
		return false;
	}
	var name2 = searchCoords(coords);
	if (name2) {
		if (!confirm('Coordenadas guardadas como \''+name2+'\', quieres cambiar la descripción?'))
			return false;
	}
	var desc = prompt('Introduce una descripción para ' + coords, (name?name:(name2?name2:'')));
	if (!desc) return false;
	var coordList = GM_getValue('coordList_' + server, '');
	if (name2)
		GM_setValue('coordList_'+server, coordList.replace(new RegExp(coords+'|'+name2), coords+'|'+desc));
	else
		GM_setValue('coordList_'+server, (coordList==''?'':coordList+'^')+coords+'|'+desc);
	return true;
}

function searchCoords(coords) {
	var coordList = GM_getValue('coordList_'+server, '').split('^');
	for (var i in coordList) {
		var x = coordList[i].split('|');
		if (x[0]==coords) return x[1];
	}
	return false;
}

function delAll() {
	if (confirm ('Eliminar todas las coordenadas?')) {
		GM_setValue('coordList_'+server,'');
		alert('Coordenadas Eliminadas!');
		if (typeof(ramka)!='undefined') makeCoordListPage();
	}
}
	
function delCoord(nr) {
	newAddress = '';
	address = GM_getValue('coordList_'+server, '').split('^');
	address.splice(nr, 1);
	GM_setValue('coordList_'+server, address.join('^'));
	makeCoordListPage();
}
	
function moveCoord(nr) {
	CoordsTab = loadCoords();
	if ((poz = prompt ('Mover coordenadas a la posicion:', nr+1)) && (poz>0) && (poz<=CoordsTab.length)) {
		var moved = CoordsTab.splice(nr, 1);
		var rest = CoordsTab.splice(poz-1, CoordsTab.length);
		CoordsTab = CoordsTab.concat(moved, rest);
		saveCoords(CoordsTab);
		makeCoordListPage();
	}
}

function loadCoords() {
	var CoordsTab = new Array;
	address = GM_getValue('coordList_' + server, '').split( '^' );
	for (i in address)
			CoordsTab[i] = address[i].split('|');
	return CoordsTab;
}

function saveCoords(CoordsTab) {
	str = '';
	for (i in CoordsTab)
		str = (str==''?'':str + '^') + CoordsTab[i][0] + '|' + CoordsTab[i][1];
	GM_setValue ('coordList_' + server, str);
}

function editCoord(nr) {
	coordsTab = loadCoords();
	if (desc = prompt('Introduce una nueva descripción', coordsTab[nr][1])) {
		coordsTab[nr][1] = desc;
		saveCoords(coordsTab);
		makeCoordListPage();
	}
}

unsafeWindow.addCoords = addCoords;
unsafeWindow.searchCoords = searchCoords;
unsafeWindow.delAll = delAll;
unsafeWindow.delCoord = delCoord;
unsafeWindow.moveCoord = moveCoord;
unsafeWindow.loadCoords = loadCoords;
unsafeWindow.saveCoords = saveCoords;
unsafeWindow.editCoord = editCoord;


/*********************************************************/
/*********+-------------------------------+***************/
/*********|    sendGTool function         |***************/
/*********+-------------------------------+***************/
/*********************************************************/


if (getScriptConf('galaxyTool')) {
	sendGTool = function (nodo, typ, content) {
		nodo.innerHTML=nodo.innerHTML.fontcolor('orange');
		nodo.title='Enviando información...';
		var loc = location.hostname;
		for (var k=1; getGTName(loc+(k<2?'':k))!=''; k++) {
			GM_xmlhttpRequest({
				method:"POST",
				url:getGTUrl(loc+(k<2?'':k)),
				headers:{
					"User-Agent" : navigator.userAgent,
					"Accept" : "text/xml",
					"Content-type" : 'application/x-www-form-urlencoded'
				},
				onload:function(details) {
//					alert(details.responseText)
					if (details.status==403) {
						nodo.innerHTML+="<img title='Error: acceso denegado' src='"+ledRed+"' >";
//						alert('Acceso denegado, comprueba tu nombre de usuario y tu password');
					}
					else if (details.status==404) {
						nodo.innerHTML+="<img title='Error: la página no existe' src='"+ledRed+"' >";
//						alert('Página no encontrada, comprueba la url de Galaxy Tool');
					}
					else if (details.status==200) {
						try {
							var code=parseInt(details.responseText.match(/(\d\d\d)$/)[1], 10);
						} catch (e) {}
						if (code==601)
							nodo.innerHTML+="<img title='Galaxia "+[typ.replace(/.*y=(\d+).*/, '$1'), typ.replace(/.*m=(\d+).*/, '$1')].join(':')+" actualizada' src='"+ledGreen+"' >";
						else if (code==602)
							nodo.innerHTML+="<img title='Error al actualizar la galaxia "+[typ.replace(/.*y=(\d+).*/, '$1'), typ.replace(/.*m=(\d+).*/, '$1')].join(':')+"' src='"+ledRed+"' >";						
						else if (code==611)
							nodo.innerHTML+="<img title='Informe de espionaje de "+content.replace(/.*%5B(\d)+%3A(\d+)%3A(\d+)%5D.*/, '$1:$2:$3')+" enviado' src='"+ledGreen+"' >";
						else if (code==612)
							nodo.innerHTML+="<img title='Error al enviar informe de espionaje de "+content.replace(/.*%5B(\d)+%3A(\d+)%3A(\d+)%5D.*/, '$1:$2:$3')+"' src='"+ledRed+"' >";							
						else if (code==621) {
							var cosa = typ.match(/.*who=(\d)&what=(\d)/);
							var cadena = (cosa[1]=='0'?'jugadores':'alianzas') +
									(cosa[2]=='0'?' en puntos':(cosa[2]=='1'?' en flotas':' por investigaciones'))
							nodo.innerHTML+="<img title='Estadísticas de "+cadena+" actualizadas' src='"+ledGreen+"' >";
						}
						else if (code==622) {
							var cosa = typ.match(/.*who=(\d)&what=(\d)/);
							var cadena = (cosa[1]=='0'?'jugadores':'alianzas') +
									(cosa[2]=='0'?' en puntos':(cosa[2]=='1'?' en flotas':' por investigaciones'))
							nodo.innerHTML+="<img title='Error al actualizar las estadísticas de "+cadena+"' src='"+ledRed+"' >";
						}
						else if (code==631)
							nodo.innerHTML+="<img title='Historial de alianza actualizado' src='"+ledGreen+"' >";
						else if (code==632)
							nodo.innerHTML+="<img title='Error al actualizar el historial de alianza' src='"+ledRed+"' >";
//					alert('La url especificada no es correcta');
						else {
							nodo.innerHTML+="<img title='Error: url incorrecta o error desconocido' src='"+ledRed+"' >";
							if (debugMode) alert('Error desconocido, el contenido de la respuesta es:\n'+details.responseHeaders+details.responseText);
						}
					}
				},
				onerror: function(detError) {
					alert(detError.statusText);
				},
				data: 'user=' + getGTName(loc+(k<2?'':k)) + '&password=' + getGTPass(loc+(k<2?'':k)) + '&typ=' +typ+ '&content=' + content
			});
		}
	}
	unsafeWindow.sendGTool=sendGTool;     
}

	function makeCoordListPage() {
		ramka = content;
		body = ramka;
		body.innerHTML='';
		tab = document.createElement('TABLE');
		tab.style.padding=30;
		tr = tab.appendChild(document.createElement('TR'));
		td = tr.appendChild(document.createElement('TD'));
		td.className='c';
		td.colSpan=4;
		td.appendChild(document.createTextNode('Listado de coordenadas'));
		
		array1 = GM_getValue('coordList_'+server, '').split( '^' );
		len = array1.length;		
		for( i = 0; i < len; i++ ) {
			x = array1[i];
			arr = x.split( '|' );
			if( arr[0] != null && typeof(arr[1])!='undefined') {
				coord = arr[0].split(':');
				tr = tab.appendChild(document.createElement('TR'));
				
				th = tr.appendChild(document.createElement('TH'));
				a = document.createElement('A');
				a.style['cursor']='pointer';
				a.title='Cambiar orden';
				a.setAttribute('onclick', 'moveCoord('+i+')');
				a.appendChild(document.createTextNode(i+1));
				th.appendChild(a);
					
				th = tr.appendChild(document.createElement('TH'));
				a = document.createElement('A');
				a.href = 'index.php?page=galaxy&session=' + getSession(location.hostname) +
							'&galaxy='+coord[0] + '&system=' + coord[1] + '&position='+coord[2];
				a.title='Ver en galaxia';
				a.appendChild(document.createTextNode(arr[0]));
				th.appendChild(a);
				
				th = tr.appendChild(document.createElement('TH'));
				a = document.createElement('A');
				a.style['cursor']='pointer';
				a.title='Cambiar descripción';
				a.setAttribute('onclick', 'editCoord('+i+')');
				a.appendChild(document.createTextNode(arr[1]));
				th.appendChild(a);
				
				th = tr.appendChild(document.createElement('TH'));
				a = document.createElement('A');
				a.style['cursor']='pointer';
				a.title='Eliminar este destino';
				a.setAttribute('onclick', 'delCoord('+i+')');
				a.appendChild(document.createTextNode('Eliminar'));
				th.appendChild(a);
			}
		}
		body.appendChild(tab);
	}
	unsafeWindow.makeCoordListPage = makeCoordListPage;


/*********************************************************/
/*********+-------------------------------+***************/
/*********|        Reduced images         |***************/
/*********+-------------------------------+***************/
/*********************************************************/

if (buildingsSection || techsSection || hangarSection || defenseSection) {
		var table = locateFirst("//table[@width='530']");
		if (getScriptConf('tinyIMG')) {
			var imgs = table.getElementsByTagName('img');
			for (var i=0; i<imgs.length; i++) {
				imgs[i].setAttribute('height', '70');
				imgs[i].setAttribute('width', '70');
			}
		}
}


/*********************************************************/
/*********+-------------------------------+***************/
/*********|    getting page parts         |***************/
/*********+-------------------------------+***************/
/*********************************************************/


var leftmenu  = document.getElementById('leftmenu');
var content = document.getElementById('content');
var messagebox = document.getElementById('messagebox');
var header_top = document.getElementById('header_top');
var errorbox = document.getElementById('errorbox');

/*********************************************************/
/*********+-------------------------------+***************/
/*********|    eliminar banners           |***************/
/*********+-------------------------------+***************/
/*********************************************************/

if (getScriptConf('delBanners')) {
	var banners = locateSnapshot("//a/div[@style]");
	for (var i=0; i<banners.snapshotLength; i++) {
		if (banners.snapshotItem(i).style['background-image']!='') {
			if (debugMode) GM_log('Banner deleted!');
			banners.snapshotItem(i).parentNode.parentNode.removeChild(banners.snapshotItem(i).parentNode)
		}
	}
}

/*********************************************************/
/*********+-------------------------------+***************/
/*********|    Loading building lists     |***************/
/*********+-------------------------------+***************/
/*********************************************************/

unsafeWindow.loadBuilding = function(planet) {
	
}

/*
var dates = getBLStatus();
for (var i=0; i<dates.length; i+=2) {
// 	GM_log('Planeta '+dates[i]+' acaba '+new Date(parseInt(dates[i+1])));
	timeLeft = parseInt(dates[i+1])-new Date().getTime();
	if (timeLeft<0) {
		
	}
	else 
		setTimeout("alert('"+dates[i]+"'+' ha acabado')", timeLeft+Math.random()*10000);
}

var dataa = new Date();
dataa.setMinutes(29)
GM_log(dataa.getTime())
*/


/*********************************************************/
/*********+-------------------------------+***************/
/*********|         header_top            |***************/
/*********+-------------------------------+***************/
/*********************************************************/

if (header_top) {
	// save current planet coords
	var thisCoords = header_top.getElementsByTagName('select')[0];
	thisCoords = thisCoords.options[thisCoords.selectedIndex];
	var thisPlanetCode = thisCoords.value.split('cp=')[1].split('&')[0];
	thisCoords = thisCoords.innerHTML.split('[')[1].split(']')[0];
	if (debugMode) GM_log('Planet coords: ' + thisCoords + '\nPlanet code: ' + thisPlanetCode);

	// set Main Planet
	setMainP(header_top.getElementsByTagName('option')[0].innerHTML.match(/\[(.*)\]/)[1]);

	// save planet resources
	var resources = locateSnapshot("//table[@id='resources']//tr/td/font");
	var metal = parseInt(resources.snapshotItem(0).innerHTML.replace(/\./g, ''), 10);
	var cristal = parseInt(resources.snapshotItem(1).innerHTML.replace(/\./g, ''), 10);
	var deuterio = parseInt(resources.snapshotItem(2).innerHTML.replace(/\./g, ''), 10);
	var energia = parseInt(resources.snapshotItem(4).innerHTML.replace(/\./g, ''), 10);
	var energiaTotal = parseInt(resources.snapshotItem(4).nextSibling.nodeValue.replace(/[\.\/]/g, ''), 10);

	
	// delete officer stuff
	if (getScriptConf('delOfficer')) {
		// delete officer icons
		var aux = header_top.getElementsByTagName('tr');
		aux[aux.length-1].parentNode.parentNode.parentNode.style['display'] = 'none';

		// delete darkmatter counter
		var DMsnap = locateSnapshot("//table[@id='resources']/tbody/tr/td[4]");
		for (var i=0; i<DMsnap.snapshotLength; i++) {
			DMsnap.snapshotItem(i).style['display']='none';
		}
		// center header_top table
		header_top.getElementsByTagName('table')[0].width='50%';
	}
}


/*********************************************************/
/*********+-------------------------------+***************/
/*********|         leftmenu              |***************/
/*********+-------------------------------+***************/
/*********************************************************/

if (leftmenu) {
	if (getScriptConf('autoUpdate')) checkUpdates();
	
	var nodo = locateFirst("//font[a='Alianzas']/../../..");
	if (nodo) {
		var indSession = nodo.innerHTML.indexOf('session=');
		setSession(location.hostname, nodo.innerHTML.substring(indSession+8, indSession+20));
		if (getScriptConf('dragoSimM')) {
			var drago = nodo.cloneNode(true);
			var drago2 = drago.getElementsByTagName('a')[0];
			drago2.href = "http://drago-sim.com/index.php?lang=spanish&style=g3ck0&template=Standard" +
				'&techs[0][0][w_t]=' + getTech('militar') + 
				'&techs[0][0][s_t]=' + getTech('defensa') + 
				'&techs[0][0][r_p]=' + getTech('blindaje');
			drago2.innerHTML = "Drago-Sim";
			drago2.title = "Ir a Drago-Sim";
			nodo.parentNode.insertBefore(drago, nodo.nextSibling);
		}
		if (getScriptConf('CSimM')) {
			var csim = nodo.cloneNode(true);
			var csim2 = csim.getElementsByTagName('a')[0];
			csim2.href = "http://www.o-o-d.com/tool/sim/index.cgi?lang=sp" +
				'&aattack=' + getTech('militar') +
				'&ashield=' + getTech('defensa') +
				'&aarmory=' + getTech('blindaje');
			csim2.innerHTML = "CSim";
			csim2.title = "Ir a CSim";
			nodo.parentNode.insertBefore(csim, nodo.nextSibling);
		}
		if (getScriptConf('galaxyTool')) {
			if (getScriptConf('galaxyToolM')) {
				var url = getGTUrl(location.hostname);
				if (url) {
					var GTM = nodo.cloneNode(true);
					var GTM2 = GTM.getElementsByTagName('a')[0];
					GTM2.href = getGTUrl(location.hostname).split('secret')[0]+'/secret/index.php';
					GTM2.innerHTML = 'GalaxieTool';
					GTM2.title = 'Ir al servidor GalaxieTool';
					nodo.parentNode.insertBefore(GTM, nodo.nextSibling);
				}
			}
			if (getScriptConf('GTGV')) {
				var Galaxia = locateFirst("//table/tbody/tr/td/div/font[a='Galaxia']");
				var GTGView = Galaxia.cloneNode(true);
				var GTGView2 = GTGView.getElementsByTagName('a')[0];
				GTGView2.style['color'] = 'lightblue';
				var coord = getMainP().split(':');
				GTGView2.href = getGTUrl(location.hostname).split('secret')[0]+'secret/view.php?gala='+coord[0]+'&system='+coord[1];
				GTGView2.innerHTML = 'GT';
				GTGView2.title = 'Ver galaxia a traves de GalaxieTool';
				Galaxia.parentNode.appendChild(GTGView);
			}
		}

		if (parseInt(getScriptConf('refMens'), 10)>0) {
			unsafeWindow.actualizaMesg = function () {
				var numMens=0;
				GM_xmlhttpRequest({
					method:"GET",
					url:"http://"+location.hostname+"/game/index.php?page=overview&session=" + getSession(location.hostname),
					headers:{
						"User-Agent": navigator.userAgent,
						"Accept":"text/xml",
					},
					onload:function(details) {
						var texto = details.responseText;
						try {
							var numMens = parseInt(texto.match(/Tienes (\d+)/)[1], 10);
//							var ataque = texto.match(/(flight attack)/m)[0];
						} catch (e) {}
//						if (ataque!='') alert('Nos atacan!')
						if (!isNaN(numMens)) {
							var ind = 20;
							if (drago) ind++;
							var mesg = nodo.parentNode.getElementsByTagName('tr')[ind];
							var mesg2 = mesg.getElementsByTagName('a')[0];
							mesg2.innerHTML = "Mensajes <blink> (" + numMens + ")</blink>";
						}
					}
				});
		// generare el tiempo de actualizacion con algo de aleatoriedad, para que sea mas dificil saber
		// si usamos un script. Tener en cuenta que, a pesar de la aleatoriedad, el tiempo no puede
		// ser muy pequeña. La funcion de tiempo es: t(segundos) * (0.8+0.4*rand(0-1))
				var tiempo = parseInt(getScriptConf('refMens'), 10)*Math.floor(800+400*Math.random());
				if (tiempo!=0) unsafeWindow.setTimeout('actualizaMesg()', tiempo);
			}
			unsafeWindow.actualizaMesg();
		}

		// Elimina el letrero de "Casino de los oficiales" del menu lateral
		if (getScriptConf('delOfficerMenu')) {
			document.getElementById('darkmatter2').parentNode.parentNode.style['display']='none';
		}

		if (getScriptConf('ocalc')) {
			var ocalc = nodo.cloneNode(true);
			var ocalc2 = ocalc.getElementsByTagName('a')[0];
			ocalc2.innerHTML = "o-calc";
			ocalc2.href='http://es.o-calc.com';
			nodo.parentNode.insertBefore(ocalc, nodo.parentNode.childNodes[18]);
		}

		if (getScriptConf('menuCuantic') && isMoon(thisPlanetCode)) {
			var cuantic = nodo.cloneNode(true);
			var cuantic2 = cuantic.getElementsByTagName('a')[0];
			cuantic2.innerHTML = c_cuantic;
			cuantic2.href='index.php?session='+getSession(location.hostname)+'&page=infos&gid=43';
			nodo.parentNode.insertBefore(cuantic, nodo.parentNode.childNodes[18]);
		}


		unsafeWindow.saveResourcesTable = function(reset) {
			if (reset) return GM_setValue('resourcesTable_'+location.hostname, '');
			else return	GM_setValue('resourcesTable_'+location.hostname, [document.getElementById('RTGalaxy').value,
			document.getElementById('RTSystem').value, document.getElementById('RTPlanet').value,
			document.getElementById('RTDestType').selectedIndex, document.getElementById('RTmetal').value,
			document.getElementById('RTcristal').value, document.getElementById('RTdeuterio').value].join(':'));
		}

		unsafeWindow.RT = {coords:':::',resources:':'};
		unsafeWindow.RT.watch('coords', function(id, oldval, newval) {
			var coords = newval.split(':');
			var RTGalaxy = document.getElementById('RTGalaxy');
			var RTSystem = document.getElementById('RTSystem');
			var RTPlanet = document.getElementById('RTPlanet');
			var RTDestType = document.getElementById('RTDestType');
			if ([RTGalaxy.value,RTSystem.value,RTPlanet.value,RTDestType.selectedIndex].join(':')!= newval) {
				RTGalaxy.value = coords[0];
				RTSystem.value = coords[1];
				RTPlanet.value = coords[2];
				RTDestType.selectedIndex = coords[3];
				document.getElementById('RTmetal').value='0';
				document.getElementById('RTcristal').value='0';
				document.getElementById('RTdeuterio').value='0';
			}
			return newval;
		});
		unsafeWindow.RT.watch('resources', function(id, oldval, newval) {
			var values = newval.split(';');
			var cantidad = parseInt(values[1], 10);
			var cantidadActual = document.getElementById('RT'+values[0]);
			if (cantidad < 0) {
				cantidadActual.value = Math.max(parseInt(cantidadActual.value, 10)+cantidad, 0);
			}
			else {
				unsafeWindow.RT.coords = values[2];
				cantidadActual.value = cantidad;
			}
			setTimeout("document.getElementById('resourcesTable').onchange()", 100);
		});
		

		unsafeWindow.RTcalc = function() {
			var RTmetal = document.getElementById('RTmetal').value;
			var RTcristal = document.getElementById('RTcristal').value;
			var RTdeuterio = document.getElementById('RTdeuterio').value;
			var total = document.getElementById('RTtotal');
			var capacity = parseInt(document.getElementById('RTCargoType').value, 10);
			total.innerHTML = Math.ceil((parseInt(RTmetal,10) + parseInt(RTcristal,10) + parseInt(RTdeuterio,10))/capacity);
			if (parseInt(total.innerHTML)==0) {
				document.getElementById('resourcesTable').style['display']='none';
				return true;
			}
			document.getElementById('resourcesTable').style['display']='';
			return false;
		}


		var rec = document.createElement('table');
		rec.width='110';
		rec.cellSpacing=0;
		rec.cellPadding=0;
		rec.id='resourcesTable';
		rec.setAttribute('onchange', "saveResourcesTable(RTcalc());");
		rec.appendChild(nodo.previousSibling.previousSibling.cloneNode('true')); // añadimos la imagen separadora
		rec.lastChild.childNodes[1].colSpan=3;
		rec.lastChild.childNodes[1].title='Ocultar tabla de recursos';
		rec.lastChild.childNodes[1].style['cursor']='pointer';
		rec.lastChild.childNodes[1].setAttribute('onclick', "RT.resources='metal;0;0:0:0:0';");

		var data = GM_getValue('resourcesTable_'+location.hostname, '');
		if (data=='') {
			data = '0:0:0:0:0:0:0';
			rec.style['display']='none';
		}
		data = data.split(':');

		rec.appendChild(document.createElement('tr')).appendChild(document.createElement('td'));
		var input = document.createElement('input');
		input.type = 'text';
		input.size = '3';
		
		input.id='RTGalaxy';
		input.title = 'galaxia destino';
		input.value=data[0];
		rec.lastChild.lastChild.appendChild(input.cloneNode(true));

		input.id='RTSystem';
		input.title='sistema destino';
		input.value=data[1];
		rec.lastChild.appendChild(document.createElement('td')).appendChild(input.cloneNode(true));
		
		input.id='RTPlanet';
		input.title='planeta destino';
		input.value=data[2];
		rec.lastChild.appendChild(document.createElement('td')).appendChild(input.cloneNode(true));
		
		var select = rec.appendChild(document.createElement('tr')).appendChild(document.createElement('td'));
		select.colSpan=3;
		select.appendChild(document.createElement('select'));
		select.lastChild.id='RTDestType';
		select.lastChild.title='tipo de planeta destino';
		select.lastChild.innerHTML="<option value='1' title='El destino es un planeta'>Planeta</option><option value='3' "+(data[3]=='1'?'selected':'')+" title='El destino es una luna'>Luna</option>";
		
		rec.appendChild(document.createElement('tr'));
		rec.lastChild.appendChild(document.createElement('td'));
		rec.lastChild.appendChild(document.createElement('td'));
		rec.lastChild.lastChild.colSpan=2;
		rec.lastChild.firstChild.innerHTML="<a title='Borrar campo' onclick=\"this.parentNode.nextSibling.firstChild.value='0'; document.getElementById('resourcesTable').onchange() \">M: </a>";
		rec.lastChild.lastChild.appendChild(document.createElement('input'));
		rec.lastChild.lastChild.lastChild.type='text';
		rec.lastChild.lastChild.lastChild.size='10';
		rec.lastChild.lastChild.lastChild.setAttribute('onchange', "if (this.value=='') this.value='0'; else this.value=parseInt(this.value, 10)");
		rec.lastChild.lastChild.lastChild.id='RTmetal';
		rec.lastChild.lastChild.lastChild.value=data[4];
		rec.lastChild.lastChild.lastChild.title='metal a transportar';
		unsafeWindow.resources='metal;-2000';
		rec.appendChild(rec.lastChild.cloneNode(true));
		rec.lastChild.lastChild.lastChild.id='RTcristal';
		rec.lastChild.lastChild.lastChild.value=data[5];
		rec.lastChild.lastChild.lastChild.title='cristal a transportar';
		rec.lastChild.firstChild.firstChild.innerHTML='C: ';

		rec.appendChild(rec.lastChild.cloneNode(true));
		rec.lastChild.lastChild.lastChild.id='RTdeuterio';
		rec.lastChild.lastChild.lastChild.value=data[6];
		rec.lastChild.lastChild.lastChild.title='deuterio a transportar';
		rec.lastChild.firstChild.firstChild.innerHTML='D: ';


		unsafeWindow.setCargoType = function(value) {
			return GM_setValue('RTCargoType_'+location.hostname, value);
		}
		rec.appendChild(document.createElement('tr'));
		rec.lastChild.appendChild(document.createElement('td'));
		rec.lastChild.lastChild.colSpan=3;
		rec.lastChild.lastChild.innerHTML="<center>total <span id='RTtotal'></span> <select id='RTCargoType' onchange='setCargoType(this.selectedIndex)' title='Tipo de naves de transporte'><option title='Nave grande de carga' value='25000'>NGC</option><option title='Nave pequeña de carga' "+(GM_getValue('RTCargoType_'+location.hostname, '1')=='1'?'selected':'')+" value='5000'>NPC</option></select></center";

		nodo.parentNode.parentNode.parentNode.appendChild(rec);
		setTimeout("document.getElementById('resourcesTable').onchange()", 500);

		var allyTable = document.createElement('table');
		allyTable.width='110';
		allyTable.cellSpacing=0;
		allyTable.cellPadding=0;
		allyTable.id='allyTable';
		var allyName=getScriptConf('allyName');
		var foroAlly=getScriptConf('foroAlly').replace(/;/g, ':');
		var Session=getSession(location.hostname);
		if (allyName=='' || !getScriptConf('allyTable')) allyTable.style['display']='none';
		allyTable.innerHTML=nodo.previousSibling.previousSibling.cloneNode('true').innerHTML + // añadimos la imagen separadora
			(getScriptConf('ATMembers')?'<tr><td><div align="center"><font color="#FFFFFF"><a href="index.php?page=allianzen&session=' + Session + '&a=4&sort1=3&sort2=0">Miembros <font id="allyName1" color="'+getScriptConf('ATColorN')+'">'+allyName+'</font></a></font></div></td></tr>':'')+
			(getScriptConf('ATTopP')?'<tr><td><div align="center"><font color="#FFFFFF"><a href="index.php?page=stat&session=' + Session + '&start=1&sort1=1&sort2=2">Jugadores Top</a></font></div></td></tr>':'')+
				(getScriptConf('ATTopA')?'<tr><td><div align="center"><font color="#FFFFFF"><a href="index.php?page=stat&session=' + Session + '&start=1&who=ally">Alianzas Top</a></font></div></td></tr>':'')+
			(getScriptConf('ATForo')?'<tr><td><div align="center"><font color="#FFFFFF"><a id="foroAlly" href='+foroAlly+' target="newwindow">Foro <font id="allyName2" color="'+getScriptConf('ATColorN')+'">'+allyName+'</font></a></font></div></td></tr>':'') +
				(getScriptConf('ATCC')?'<tr id="ATCC"' +(getScriptConf('ATCCPriv')?'':'style="display:none"')+'><td><div align="center"><font color="#FFFFFF"><a href="index.php?page=allianzen&session=' + Session + '&a=17">Enviar CC</a></font></div></td></tr>':'') +
			(getScriptConf('ATBaned')?'<tr><td><div align="center"><font color="#FFFFFF"><a href="pranger.php" target="new">Baneos</a></font></div></td></tr>':'');
		nodo.parentNode.parentNode.parentNode.appendChild(allyTable);
		
		var coordTable = document.createElement('table');
		coordTable.width='110';
		coordTable.cellSpacing=0;
		coordTable.cellPadding=0;
		coordTable.id='coordTable';
		coordTable.innerHTML = nodo.previousSibling.previousSibling.cloneNode('true').innerHTML +
					"<tr><td><div align='center'><font color='#ffffff'><a onclick='addCoords()' style='cursor:pointer'>+ Coordenadas</a></font></div></td></tr>" +
					"<tr><td><div align='center'><font color='#ffffff'><a onclick='delAll()' style='cursor:pointer'>- Coordenadas</a></font></div></td></tr>" +
					"<tr><td><div align='center'><font color='#ffffff'><a onclick='makeCoordListPage()' style='cursor:pointer'>Lista</a></font></div></td></tr>";
		nodo.parentNode.parentNode.parentNode.appendChild(coordTable);
	}

	if (getScriptConf('LMSearch')) {
		var nodo = locateFirst("//table/tbody/tr/td/div/font[a='Buscar']/..");
		if (nodo) {
			nodo.innerHTML='';
			
			var formulario = document.createElement('form');
			formulario.setAttribute("action","index.php?page=suche&session="+getSession(location.hostname));
			//formulario.setAttribute("target","Hauptframe");
			formulario.setAttribute("method","post");
			formulario.heigth='0';
			formulario.innerHTML += '<select name="type"><option value="playername" selected>Jugador</option>' +
								'<option value="planetname" >Planeta</option>' +
								'<option value="allytag" >Etiqueta A.</option>' +
								'<option value="allyname" >Alianza</option></select>';
			nodo.appendChild(formulario);

			var texto = document.createElement('input');
			texto.size='13';
			texto.setAttribute("type","text");
			texto.setAttribute("name","searchtext");
			formulario.appendChild(texto);

			var boton = document.createElement('input');
			boton.setAttribute("type","submit");
			boton.setAttribute("value","Buscar");
			formulario.appendChild(boton);
		}
	}	

	// Hacemos el menu lateral plegable
	var path = "//div[@id=\"menu\"]/table/tbody/tr/td";
	var tds = locateSnapshot(path);
	var j=0;
	for (var i=0; i<tds.snapshotLength; i++) {
		if (tds.snapshotItem(i).firstChild.nodeName=='IMG' || i==tds.snapshotLength-1) {
			if (i!=0) {
				var string='';
				for (var k=j+1; k<i; k++) string = (string==''?string=k:string=[string, k].join(':'));
				if (i==tds.snapshotLength-1) string += ':'+i;
				if (isHidden(j+1)) {
					hideNoEffects(path, string);
					//tds.snapshotItem(j).setAttribute('onclick', "show('"+path+"', '"+string+"')");
					//tds.snapshotItem(j).title='Click aqui para expandir';
				} else {
					tds.snapshotItem(j).setAttribute('onclick', "hide('"+path+"', '"+string+"')");
					tds.snapshotItem(j).title='Click aqui para contraer';
				}
				tds.snapshotItem(j).style['cursor']='pointer';
			}
			j=i;
		}
	}
}

/*********************************************************/
/*********+-------------------------------+***************/
/*********|           options             |***************/
/*********+-------------------------------+***************/
/*********************************************************/

if (contentSection == 'options') {
	function initTab(labels, ids) {
		var table = document.createElement('table');
		var row = table.appendChild(document.createElement('tr'));
		var tab = document.createElement('td');
		tab.className = 'b';
		tab.setAttribute('onclick', 'tab.position=this.id');
		tab.style['cursor']= 'pointer';
		for (var i in labels) {
			concreteTab = row.appendChild(tab.cloneNode(true));
			concreteTab.innerHTML = labels[i];
			concreteTab.id = ids[i];
		}
		return table;
	}

	var defConfigTab = "script";
	unsafeWindow.tab = {position:defConfigTab};
	unsafeWindow.tab.watch("position", function(id, oldval, newval) {
		document.getElementById(oldval).className = 'b';
		document.getElementById(newval).className = 'c';

		objects = document.getElementsByName(oldval);
		for (i=0;i<objects.length;i++)
			objects[i].style['display'] = 'none';
		objects = document.getElementsByName(newval);
		for (i=0;i<objects.length;i++)
			objects[i].style['display'] = '';

		if (debugMode) GM_log('tab.position ' + oldval + ' -> ' + newval);
		return newval;
	});
	
	var config = locateFirst('//table[@width=519]');
	config.setAttribute('name', 'ogame');
	
	
	
	makeConfig = function () {
		function newTable(title, colspan) {
			return "<table width='519'><tr><td class='c' colspan ="+colspan+">"+title+"</td></tr>";
		}
		function endTable() {
			return '</table>';
		}
		function newNestledTable(id, depend, title, colspan, parentColspan) {
			return "<tr id='"+id+"' align='center' "+((depend!=''&&!getScriptConf(depend))?"style='display:none'":'')+"><td colspan='"+parentColspan+"'><table width='95%' colspan="+colspan+" >" +
			"<tr><td class='c' colspan ="+colspan+">"+title+"</td></tr>";
		}
		function endNestledTable() {
			return "</table></td></tr>";
		}
		function newTableRowCk(nam, id, desc, table, colspan) {
			return "<tr><th width='50'><input type='checkbox' name='"+nam+"' id='" + id + "' " +
			(getScriptConf(id)?'checked=true':'') +
			
			(!table||table==''?" />":" onclick='if (this.checked) showId(\""+table+"\"); else hideId(\""+table+"\")' />") +
			"</th><th"+(colspan?" colspan='"+(colspan-1)+"'":"")+">" + desc + "</th></tr>";
		}

		function newTableRowNb(nam, id, desc) {
			return "<tr><th width='50'><input type='text' size='3' name='"+nam+"' id='" + id + "' " +
			"value='" + getScriptConf(id) + "'/>" +
			"</th><th>" + desc + "</th></tr>";
		}
		
		function newTableRowColor(nam, id, desc) {
			var temp = getScriptConf(id);
			return "<tr><th>" +
				"<input type='button' title='restaurar valor' value='<' style='display:none' " +
				"onclick='this.style[\"display\"]=\"none\";this.nextSibling.nextSibling.style[\"display\"]=\"none\";this.nextSibling.value=getScriptConf(this.nextSibling.id); this.parentNode.nextSibling.firstChild.attributes[0].value=this.nextSibling.value' />" +
				"<input type='text' name='"+nam+"' id='"+id+"' size='5' onkeyup='"+ "this.parentNode.nextSibling.firstChild.attributes[0].value=this.value;this.previousSibling.style[\"display\"]=\"\";this.nextSibling.style[\"display\"]=\"\"" +"' value='" + temp + "'/>" +
				"<input type='button' title='guardar valor' value='>' style='display:none' " +
				"onclick='this.style[\"display\"]=\"none\";this.previousSibling.previousSibling.style[\"display\"]=\"none\";setScriptConf(this.previousSibling.id, this.previousSibling.value)' />" + 
				"</th><th><font color='"+temp+"'>"+desc+"</font></th></tr>";
		}

		var size = 5;
		var cad = "<br><h1><a href='"+scriptPage+"' target='_blank' style='color:lightblue'>"+scriptName+"</a><small title='click para buscar actualizaciones' onclick='checkUpdates(true)' style='color:lightgreen; cursor:pointer'>  v"+scriptVersion+"</small> by <font color='orangered'>"+scriptAuthor+"</font> </h1>" +
			"<br /><center>Descubre los <a href='http://roble.cnice.mecd.es/~apuente/applet1.html' target='new'>colores</a>";

		// Ajustes

		cad += newTable(c_mainTable, 2);
		cad += newTableRowCk('conf', 'compactar', c_compactar);
		cad += newTableRowCk('conf', 'ocalc', c_ocalc);
		cad += newTableRowCk('conf', 'dragoSim', c_dragoSim);
		cad += newTableRowCk('conf', 'dragoSimM', c_dragoSimM);
		cad += newTableRowCk('conf', 'CSim', c_CSim);
		cad += newTableRowCk('conf', 'CSimM', c_CSimM);
		cad += newTableRowCk('conf', 'modifyDate', c_modifyDate);
		cad += newTableRowCk('conf', 'tinyIMG', c_tinyIMG);
		cad += newTableRowCk('conf', 'proInputs', c_proInputs);
		cad += newTableRowCk('conf', 'flottenInfo', c_flottenInfo);
		cad += newTableRowCk('conf', 'specialEffects', c_specialEffects);
		cad += newTableRowCk('conf', 'autoUpdate', c_autoUpdate);
		cad += newTableRowCk('conf', 'improvedResources', c_improvedResources);
		cad += newTableRowCk('conf', 'improvedCuantic', c_improvedCuantic);
		cad += newTableRowCk('conf', 'delBanner', c_delBanner);
		cad += newTableRowCk('conf', 'delBanners', c_delBanners);
		cad += newTableRowCk('conf', 'delOfficerMenu', c_delOfficerMenu);
		cad += newTableRowCk('conf', 'delOfficer', c_delOfficer);
		cad += newTableRowCk('conf', 'colorBuild', c_colorBuild);
		cad += newTableRowCk('conf', 'SYConst', c_SYConst);
		cad += newTableRowCk('conf', 'SYReducible', c_SYReducible);
		cad += newTableRowCk('conf', 'colapseFlights', c_colapseFlights);
		cad += newTableRowCk('conf', 'LMSearch', c_LMSearch);
		cad += newTableRowCk('conf', 'blockUselessTechs', c_blockUselessTechs);
		cad += newTableRowCk('conf', 'menuCuantic', c_menuCuantic);
		cad += newTableRowCk('conf', 'buildingList', c_buildingList);
		cad += newTableRowCk('conf', 'coordLinker', c_coordLinker, 'tablaCoordLinker');
		cad += newNestledTable('tablaCoordLinker', 'coordLinker', c_tablaCoordLinker, 2, 2);
		cad += newTableRowCk('conf', 'coordLinkerVarG', c_coordLinkerVarG);
		cad += newTableRowCk('conf', 'coordLinkerVarM', c_coordLinkerVarM);
		cad += newTableRowColor('color', 'coordLinkerCF', c_coordLinkerCF);
		cad += newTableRowColor('color', 'coordLinkerCM', c_coordLinkerCM);
		cad += newTableRowColor('color', 'coordLinkerCVG', c_coordLinkerCVG);
		cad += newTableRowColor('color', 'coordLinkerCG', c_coordLinkerCG);
		cad += endNestledTable();
		cad += newTableRowCk('conf', 'allyTable', c_allyTable, 'tablaAllyTable');
		cad += newNestledTable('tablaAllyTable', 'allyTable', c_tablaAllyTable, 2, 2);
		cad += newTableRowCk('conf', 'ATMembers', c_ATMembers);
		cad += newTableRowCk('conf', 'ATTopP', c_ATTopP);
		cad += newTableRowCk('conf', 'ATTopA', c_ATTopA);
		cad += newTableRowCk('conf', 'ATForo', c_ATForo);
		cad += newTableRowCk('conf', 'ATCC', c_ATCC);
		cad += newTableRowCk('conf', 'ATBaned', c_ATBaned);
		cad += newTableRowColor('color', 'ATColorN', c_ATColorN);
		cad += endNestledTable();
		cad += newTableRowCk('conf', 'debris', c_debris, 'tablaDebris');
		cad += newNestledTable('tablaDebris', 'debris', c_tablaDebris, 4, 2);
		cad += newTableRowColor('color', 'debrisColor', c_debrisColor);
		cad += newTableRowNb('conf', 'debrisMin', c_debrisMin);
		cad += newTableRowNb('conf', 'debrisMax', c_debrisMax);
		cad += endNestledTable();
		// AllyTags
		
		cad += newTableRowCk('conf', 'allyTags', c_allyTags, 'tablaAllyTags');
		cad += newNestledTable('tablaAllyTags', 'allyTags', c_tablaAllyTags, 4, 2);
		cad += "<tr><th><input type='button' value='+' title='Añadir nueva etiqueta' onclick=\"this.parentNode.parentNode.parentNode.appendChild(this.parentNode.parentNode.nextSibling.cloneNode(true));this.parentNode.parentNode.parentNode.lastChild.style['display']=''\" ></th>" + 
			"<th>Etiqueta</th>" +
			"<th>Color</th>" +
			"<th>Alianza/s implicada/s (separar con '|' )</th>" +
			"</tr>";

		cad += "<tr style='display:none' name='allyTag'><th><input type='button' value='-' title='Eliminar etiqueta' " +
			" onclick=\"this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)\" /></th>" +
			"<th><input size='10' type='text' name='ATTag' value='' /></th>" +
			"<th><input size='10' type='text' name='ATColor' value='' onchange=\"this.parentNode.nextSibling.firstChild.style['color']=this.value\" /></th>" + 
			"<th><input size='48' type='text' name='ATAllys' value='' /></th></tr>";
		var tags = GM_getValue('allyTags', defAllyTags).split(':x:');
		for (var k=0; k<tags.length; k++) {
			tags2 = tags[k].split(':y:');
			cad += "<tr name='allyTag'><th><input type='button' value='-' title='Eliminar etiqueta' " + 		 
				" onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)' /></th>" +
				"<th><input size='10' type='text' name='ATTag' value='"+tags2[0]+"' /></th>" +
				"<th><input size='10' type='text' name='ATColor' value='"+tags2[1]+
				"' onchange=\"this.parentNode.nextSibling.firstChild.style['color']=this.value\" /></th>" + 
				"<th><input size='48' type='text' name='ATAllys' style='color:"+tags2[1]+"' value='"+
				tags2[2]+"' /></th></tr>";
		}
		cad += endNestledTable();
		// GalaxyTool
		
		cad += newTableRowCk('conf', 'galaxyTool', c_galaxyTool, 'tablaGTool');
		cad += newNestledTable('tablaGTool', 'galaxyTool', c_tablaGTool, 4, 2);
		cad += newTableRowCk('conf', 'galaxyToolM', c_galaxyToolM, '', 4);
		cad += newTableRowCk('conf', 'GTGV', c_GTGV, '', 4);
		cad += "<tr><th><input type='button' value='+' title='Añadir cuenta nueva' onclick=\"this.parentNode.parentNode.parentNode.appendChild(this.parentNode.parentNode.nextSibling.cloneNode(true));this.parentNode.parentNode.parentNode.lastChild.style['display']=''\" ></th>" + 
			"<th>Usuario:</th>" +
			"<th>Password:</th>" +
			"<th>Dirección de Galaxy Tool (pregunta al administrador)</th>" +
			"</tr>";

		var loc = location.hostname;
		cad += "<tr style='display:none' name='GTUser'><th><input type='button' value='-' title='Eliminar cuenta' " +
			" onclick=\"this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)\" /></th>" +
			"<th><input size='10' type='text' name='GTName' value='' /></th>" +
			"<th><input size='10' type='password' name='GTPass' value='' /></th>" +
			"<th><input size='48' type='text' name='GTUrl' value='' /></th></tr>";
		for (var k=1; getGTName(loc+(k<2?'':k))!=''; k++) {
			cad += "<tr name='GTUser'><th><input type='button' value='-' title='Eliminar cuenta' " + 		 
				" onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)' /></th>" +
				"<th><input size='10' type='text' name='GTName' value='"+getGTName(loc+(k<2?'':k))+"' /></th>" +
				"<th><input size='10' type='password' name='GTPass' value='"+getGTPass(loc+(k<2?'':k))+"' /></th>" +
				"<th><input size='48' type='text' name='GTUrl' value='"+getGTUrl(loc+(k<2?'':k))+"' /></th></tr>";
		}
		cad += endNestledTable();
	
		cad += newTableRowNb('conf', 'refMens', c_refMens);
		cad += newTableRowCk('conf', 'moonSpy', c_moonSpy);
		cad += newTableRowCk('conf', 'transportMode', c_transportMode, 'transportTable');
		cad += newNestledTable('transportTable', 'transportMode', c_transportModeTable, 2, 2);
//		cad += newTableRowCk('conf', 'transportModeEnabled', c_transportModeEnabled);
	
		var temp = getScriptConf("TMDestination");
		if (temp == "0;0;0;1") {
			temp = getMainP().replace(/:/g, ';')+';1';
		}
		cad += "<tr><input type=\"hidden\" name='conf' id=\"TMDestination\" value=\"" +
			temp + "\" />" +
			"<th width=90 onchange=\"document.getElementById('TMDestination').value=[this.childNodes[0].value,this.childNodes[1].value,this.childNodes[2].value,this.childNodes[3].value].join(';')\">";
		temp = temp.split(';');
		for (var i=0; i<temp.length-1; i++)
			cad += "<input size=1 type=\"text\" value=\""+temp[i]+"\">";
		cad += "<select><option value=1 "+(temp[3]=='1'?'selected=\"yes\"':'')+">Planeta</option><option value=3 "+(temp[3]=='3'?'selected=\"yes\"':'')+">Luna</option></select>";
		cad += "</th><th>Destino por defecto</th></tr>";
		cad += endNestledTable();

		cad += newTableRowCk('conf', 'colorMens', c_colorMens, 'tablaColores');
		cad += newTableRowCk('conf', 'autoMark', c_autoMark, 'tablaAutoMark');
		// AutoMark

		cad += "</table><table width=\"600\"><tr><td width=\"50%\"><table id='tablaAutoMark' style='display:"+(getScriptConf('autoMark')?'':'none')+"' ><tr><td class=\"c\" colspan =\"2\">Auto marcar mensajes de:</td></tr>";
		
		cad += newTableRowCk('autoMark', 'AMTrans', c_AMTrans);
		cad += newTableRowCk('autoMark', 'AMTransR', c_AMTransR);
		cad += newTableRowCk('autoMark', 'AMDesp', c_AMDesp);
		cad += newTableRowCk('autoMark', 'AMColo', c_AMColo);
		cad += newTableRowCk('autoMark', 'AMAlianza', c_AMAlianza);
		cad += newTableRowCk('autoMark', 'AMPriv', c_AMPriv);
		cad += newTableRowCk('autoMark', 'AMEsp', c_AMEsp);
		cad += newTableRowCk('autoMark', 'AMEspP', c_AMEspP);
		cad += newTableRowNb('conf', 'AMEspPRecMin', c_AMEspPRecMin);
		cad += newTableRowCk('autoMark', 'AMAttack', c_AMAttack);
		cad += newTableRowCk('autoMark', 'AMMisiles', c_AMMisiles);
		cad += newTableRowCk('autoMark', 'AMRec', c_AMRec);
		cad += newTableRowCk('autoMark', 'AMConf', c_AMConf);
		cad += newTableRowCk('autoMark', 'AMBuddylist', c_AMBuddylist);

		// Colores

		cad += "</table></td><td width='50%'><table id='tablaColores' style='display:"+(getScriptConf('colorMens')?'':'none')+"' ><tr><td class=\"c\" colspan =\"2\">Colores de los mensajes</td></tr>";
    
		cad += newTableRowColor('color', 'colorTrans', c_colorTrans);
		cad += newTableRowColor('color', 'colorTransR', c_colorTransR);
		cad += newTableRowColor('color', 'colorDesp', c_colorDesp);
		cad += newTableRowColor('color', 'colorAlianza', c_colorAlianza);
		cad += newTableRowColor('color', 'colorPriv', c_colorPriv);
		cad += newTableRowColor('color', 'colorRec', c_colorRec);
		cad += newTableRowColor('color', 'colorEsp', c_colorEsp);
		cad += newTableRowColor('color', 'colorConf', c_colorConf);
		cad += newTableRowColor('color', 'colorBuddylist', c_colorBuddylist);
		cad += newTableRowColor('color', 'colorColo', c_colorColo);
		cad += newTableRowColor('color', 'colorMisiles', c_colorMisiles);
		
		cad += "</table></td></tr></table><center><table width='60%'><tr>" +
			"<td><div align=left><input type='button' value='Guardar cambios' onclick='saveScriptConf(location.hostname)' /></div></td>" +
			"<td><div><input type='button' value='Exportar configuraci&oacute;n' onclick='printScriptConf()' /></div></td>" +
			"<td><div><input type='button' value='Cargar configuraci&oacute;n' onclick='loadScriptConf()' /></div></td>" +
			"<td><div align=right><input type='button' value='Valores iniciales' onclick='resetScriptConf()' /></div></td>" +
			"</tr></table></center>";

		return cad;
	} // makeConfig

	
	var scriptConf = document.createElement('table');
	scriptConf.setAttribute('name', 'script');
	scriptConf.innerHTML = makeConfig();

	config.parentNode.insertBefore(initTab(['Configuraci&oacute;n OGame', 'Configuraci&oacute;n '+scriptName],['ogame', 'script']), config);
	config.parentNode.insertBefore(scriptConf, config);
	unsafeWindow.tab.position = 'ogame';
}

/*********************************************************/
/*********+-------------------------------+***************/
/*********|         overview              |***************/
/*********+-------------------------------+***************/
/*********************************************************/

else if (contentSection=='overview') {
	if (getScriptConf('delBanner')) document.getElementById('combox_container').style['display']='none';
	nodo = locateFirst("//td[@class='c']");
	try {
		setUserName(nodo.innerHTML.match(/\((.*)\)/)[1]);
	} catch (e) {GM_log(e)}
	if (getScriptConf('modifyDate')) {
		nodo = locateFirst("//div[@id='content']//table/tbody/tr[th[2]]/th[2]");
		nodo.previousSibling.previousSibling.innerHTML='Hora';
		try{
			var days = new Array();
			days['Mon'] = 'Lunes';
			days['Tue'] = 'Martes';
			days['Wed'] = 'Miércoles';
			days['Thu'] = 'Jueves';
			days['Fri'] = 'Viernes';
			days['Sat'] = 'Sábado';
			days['Sun'] = 'Domingo';
			var months = new Array();
			months['Jan'] = 'Enero';
			months['Feb'] = 'Febrero';
			months['Mar'] = 'Marzo';
			months['Apr'] = 'Abril';
			months['May'] = 'Mayo';
			months['Jun'] = 'Junio';
			months['Jul'] = 'Julio';
			months['Aug'] = 'Agosto';
			months['Sep'] = 'Septiembre';
			months['Oct'] = 'Octubre';
			months['Nov'] = 'Noviembre';
			months['Dec'] = 'Diciembre';
			var fecha=nodo.innerHTML.match(/(\S\S\S) (\S\S\S) (\d+) (\d+:\d\d:\d\d)/);
			nodo.innerHTML=days[fecha[1]]+' '+fecha[3]+' de '+months[fecha[2]]+', '+fecha[4];
		} catch(e) {GM_log(e)}
	}
	
	if (getScriptConf('coordLinker')) {
		var links = locateSnapshot("//div[@id='content']//table/tbody/tr[@class]/th[2]/span/a[text()]");
		var colorVG = getScriptConf('coordLinkerCVG');
		var colorVariable = getScriptConf('coordLinkerVarG');
		for (var i=0; i<links.snapshotLength; i++) {
			try {
				var linkText = links.snapshotItem(i).innerHTML;
				var coord = linkText.match(/\[(\d+:\d+:\d+)\]/)[1];
				links.snapshotItem(i).style['color'] = colorVariable?getColorLinker(coord):colorVG;
			} catch (e) {GM_log(e)}
		}
	}
	
	if (getScriptConf('buildingList')) {
		try {
			var blists = getBuildings(thisPlanetCode).split(';');
			var gids = blists[0].split('-');
			var levels = blists[1].split('-');
		
			var center = locateFirst("//img[@width=200]/../center");
			if (center) {
				var div = document.createElement('div');
				center.parentNode.appendChild(div);
				div.innerHTML='Cola de edificios';
				var select = div.appendChild(document.createElement('select'));
				select.size = 7;
				for (var i=0; i<gids.length; i++) {
					select.innerHTML += "<option>" + getGidTag(gids[i]) + ' (' + levels[i] + ")</option>";
				}
			}
		}catch(e){GM_log(e)}
	}
	
	if (getScriptConf('colapseFlights')) {
		var hidden = getBooleanConf('hiddenFlights', contentSection);
		
		var more = document.createElement('img');
		more.src = moreButton;
		more.style['cursor']='pointer';
 		if (!hidden) more.style['display']='none';
		more.title = 'Mostrar vuelos';
		more.id = 'flight_plus';
		more.setAttribute('onclick', "delFlightsHidden('"+contentSection+"')");

		var less = document.createElement('img');
		less.src = lessButton;
		less.style['cursor']='pointer';
		if (hidden) less.style['display']='none';
		less.title = 'Ocultar vuelos';
		less.id = 'flight_minus';
		less.setAttribute('onclick', "setFlightsHidden('"+contentSection+"')");

		var flightsHeader = locateFirst("//div[@id='content']//tr[position()>1]/td[@class='c']");
		flightsHeader.appendChild(more);
		flightsHeader.appendChild(less);
		flightsHeader.appendChild(flightsHeader.firstChild);

		var flights = locateSnapshot("//div[@id='content']//tr[@class]");
		var numFlights = document.createElement('font');
		numFlights.id = 'numFlights';
		numFlights.innerHTML=' ('+flights.snapshotLength+' vuelos)';
		if (!hidden) numFlights.style['display']='none';
		flightsHeader.appendChild(numFlights);

		for (var i=0; i<flights.snapshotLength; i++) {
			flights.snapshotItem(i).id = 'flight' + i;
			if (hidden) flights.snapshotItem(i).style['display'] = 'none';
		}
	}
}

else if (buildingsSection || techsSection || hangarSection || defenseSection || cuanticSection) {
				
	// Tech Section
	if (techsSection) {
		var response = document.body.innerHTML.replace(/\n/g, '');

		// Block technologies
		if (getScriptConf('blockUselessTechs')) {
			function blockTech(gid) {
				var blockedTech = locateFirst('//a[@href="index.php?page=infos&session='+getSession(location.hostname)+'&gid='+gid+'"]/../..');
//				if (blockedTech.lastChild.innerHTML != ' - ')
				blockedTech.lastChild.innerHTML = "<font color='red'>Máximo nivel útil alcanzado</font>";
			}
		
			var gids = [
				113, // energy
				114, // hyperspace
				120, // laser
				121, // ionic
				122, // plasma
				199 // graviton
			];
			var limits = [12, 8, 12, 5, 7, 1];
			var tech=0;
			for (var i in gids) {
				try {
					tech = response.match(new RegExp("gid="+gids[i]+".{0,50}Nivel (\\d+) ?\\)"))[1];
				} catch(e) {}
				if (tech>=limits[i]) blockTech(gids[i]);
				tech=0;
			}
		}

		// Save technologies
		var techsSaved = ['computacion', 'militar', 'defensa', 'blindaje'];
		var techsSavedIds = [108, 109, 110, 111];
		var tech=0;
		for (var i in techsSaved) {
			try {
				tech = response.match(new RegExp("gid="+techsSavedIds[i]+".{0,50}Nivel (\\d+)\\)"))[1];
			} catch(e) {}
			if (tech!=0) {
				setTech(techsSaved[i], tech);
				if (!debugMode) GM_log('Tecnologia ' + techsSaved[i] + ' nivel ' + tech + ' guardada');
			}
			tech=0;
		}

		// motor techs for consumptions
		var combustion=0;
		var impulso=0;
		var hiper=0;

		try {
			combustion = response.match(/gid=115.{0,50}Nivel (\d+)\)/)[1];
		} catch(e) {}
		
		try {
			impulso = response.match(/gid=117.{0,50}Nivel (\d+)\)/)[1];
		} catch(e) {}
		
		try {
			hiper = response.match(/gid=118.{0,50}Nivel (\d+)\)/)[1];
		} catch(e) {}
		
		GM_setValue('velocidadesBase_'+location.hostname, [Math.round(impulso<5?5000*(1+combustion/10):10000*(1+impulso/5)), Math.round(7500*(1+combustion/10)), Math.round(12500*(1+combustion/10)), Math.round(10000*(1+impulso/5)), Math.round(15000*(1+impulso/5)), Math.round(10000*(1+hiper*0.3)), Math.round(2500*(1+impulso/5)), Math.round(2000*(1+combustion/10)), Math.round(100000000*(1+combustion/10)), Math.round(hiper<8?4000*(1+impulso/5):5000*(1+hiper*0.3)), 0, Math.round(5000*(1+hiper*0.3)), Math.round(100*(1+hiper*0.3)), Math.round(10000*(1+hiper*0.3))].join(':'));
	}
	
	else if (cuanticSection && getScriptConf('improvedCuantic')) {
		var coordsTable = locateFirst('//table[@border=1]');
		var timeLeft = locateFirst("//center[font[@color='#ff0000']]");
		if (coordsTable) {
			// Añadimos un espacio
			coordsTable.parentNode.insertBefore(document.createElement('br'), coordsTable);
			// Ponemos la tabla algo mas chula
			coordsTable.removeAttribute('border');
			coordsTable.width='519';
			var select = coordsTable.getElementsByTagName('select')[0];
			// Guardamos los codigos de planeta de las lunas
			var options = select.options;
			var moonCodes = thisPlanetCode;
			for (var i=0; i<options.length; i++) moonCodes = [moonCodes, options[i].value].join(';');
			setMoonList(moonCodes);
			// Ahora modificamos un poco la tabla
			select.removeAttribute('size');
			select.selectedIndex='0';
			var tds = coordsTable.getElementsByTagName('td');
			for (var i in tds) tds[i].className='f';
			var trs = coordsTable.getElementsByTagName('tr');
			// juntamos las dos filas en una
			trs[0].appendChild(tds[2]);
			trs[0].appendChild(tds[3]);
			trs[1].parentNode.removeChild(trs[1]);
			// ponemos un titulo
			var title = document.createElement('tr');
			title.appendChild(document.createElement('td'));
			title.firstChild.className='c';
			title.firstChild.innerHTML='Coordenadas de origen y destino';
			title.firstChild.colSpan=4;
			trs[0].parentNode.insertBefore(title, trs[0]);
			// creamos un desplegable también para el origen
			var select2 = select.cloneNode(true);
			select2.removeAttribute('name');
			select2.setAttribute('onchange', 'haha(this)');
			var selectPlanet = document.getElementsByTagName('select')[0];
			var selectedPlanet = selectPlanet.options[selectPlanet.selectedIndex].cloneNode(true);
			for (var i in select2.options) {
				select2.options[i].value = selectedPlanet.value.replace(/(cp=)\d+/, '$1'+select2.options[i].value);
			}
			select2.insertBefore(selectedPlanet, select2.firstChild);
			tds[2].innerHTML='';
			tds[2].appendChild(select2);

			var shipsTable = coordsTable.nextSibling.nextSibling.lastChild;
			//Le ponemos un nombre al formulario para usarlo mas facilmente.
			shipsTable.parentNode.parentNode.setAttribute("name", "salto");
			shipsTable.rows[0].cells[0].setAttribute("colspan","4");
			shipsTable.rows[shipsTable.rows.length - 1].cells[0].setAttribute("colspan","4");

			title = shipsTable.rows[0].cloneNode(true);
			shipsTable.insertBefore(title, shipsTable.rows[1]);
			title.innerHTML = "<th>Naves</th><th>Disponibles</th><th>-</th><th>-</th>";
			
			var todas = '';
			var ninguna = '';
			for(var i = 2; i < shipsTable.rows.length - 1; i++) {
				matches = shipsTable.rows[i].cells[0].innerHTML.match(/(.*)\((\d+)/);
				cantidad = matches[2];
				texto = matches[1];
				nombre = shipsTable.rows[i].cells[1].firstChild.name;
				//if (getScriptConf('cuanticAllShips')) shipsTable.rows[i].cells[1].firstChild.value=cantidad;

				//Modificamos el nombre de las naves, quedando unicamente el nombre sin la cantidad disponible.
				shipsTable.rows[i].cells[0].innerHTML = texto;
				//Agregamos una celda indicando la cantidad disponible.
				nodo = shipsTable.rows[i].cells[0].cloneNode(true);
				shipsTable.rows[i].insertBefore(nodo, shipsTable.rows[i].cells[shipsTable.rows[i].cells.length - 1]);
				nodo.innerHTML = cantidad;
				//Agregamos una celda con un boton para seleccionar el maximo.
				nodo = shipsTable.rows[i].cells[0].cloneNode(true);
				nodo.innerHTML = '';
				shipsTable.rows[i].insertBefore(nodo, shipsTable.rows[i].cells[shipsTable.rows[i].cells.length - 1]);
				if (getScriptConf('proInputs')) {
					var a = document.createElement("a");
					a.setAttribute("href", "javascript:void(salto."+nombre+".value="+cantidad+");");
					a.innerHTML = "&infin;";
					nodo.appendChild(a);

					var a = document.createElement("a");
					a.style['cursor'] = 'pointer';
					a.setAttribute("onmousedown", "pressed=true;cambiar('"+nombre+"', true, "+cantidad+")");
					a.setAttribute("onmouseout", "if (pressed=true) {pressed=false; contador=5; incremento=1;}");
					a.setAttribute("onmouseup", "pressed=false; contador=5; incremento=1;");
					a.innerHTML='+';
					nodo.appendChild(a);

					var a = document.createElement("a");
					a.style['cursor'] = 'pointer';
					a.setAttribute("onmousedown", "pressed=true;cambiar('"+nombre+"', false, "+cantidad+")");
					a.setAttribute("onmouseout", "if (pressed=true) {pressed=false; contador=5; incremento=1;}");
					a.setAttribute("onmouseup", "pressed=false; contador=5; incremento=1;");
					a.innerHTML = "&minus;";
					nodo.appendChild(a);

					var a = document.createElement("a");
					a.setAttribute("href", "javascript:void(salto." + nombre + ".value=0);");
					a.innerHTML = "&bull;";
					nodo.appendChild(a);
				}
				else
					nodo.innerHTML = "<a href=\"javascript:void();\" onclick=\"salto." + nombre + ".value='" + cantidad + "';\" >m&aacute;x</a>";
				todas = todas + "salto." + nombre + ".value='" + cantidad + "';";
				ninguna = ninguna + "salto." + nombre + ".value='0';";
			}
			nodo = shipsTable.rows[0].cloneNode(true);
			shipsTable.insertBefore(nodo, shipsTable.rows[shipsTable.rows.length - 1]);
			nodo.innerHTML = "<th colspan='2'><a href=\"javascript:void();\" onclick=\"" + ninguna + "\">Ninguna nave</a></th><th colspan='2'><a href=\"javascript:void();\" onclick=\"" + todas + "\">Todas las naves</a></th>";
		}
		else if (timeLeft) {
			unsafeWindow.t = function t() {
				minDiv = document.getElementById('min');
				secDiv = document.getElementById('sec');
				min = parseInt(minDiv.innerHTML, 10);
				sec = parseInt(secDiv.innerHTML, 10);

				if (sec == 0)
					if (min == 0) {
						minDiv.innerHTML = '-';
						secDiv.innerHTML = '-';
						document.location.reload();
						return;
					}
					else {
						minDiv.innerHTML = min-1;
						secDiv.innerHTML = '59';
					}
				else {
					secDiv.innerHTML = sec-1;
				}
				unsafeWindow.setTimeout("t();", 999);
			}
			
			var time = timeLeft.innerHTML.match(/(\d+)/g);
			var tabla = document.createElement('table');
			tabla.width = '519';
			tabla.innerHTML = "<tbody><tr><td class='c'>"+timeLeft.firstChild.firstChild.nodeValue+"</td></tr>";
			tabla.innerHTML += "<tr><th>" +
					timeLeft.firstChild.lastChild.nodeValue.replace(/(\d+)([\s\S]* )(\d+)/, '<b id=min>$1</b> $2<b id=sec>$3</b> ') +
					"</th></tr></tbody>";
			timeLeft.parentNode.insertBefore(document.createElement('br'), timeLeft);
			timeLeft.parentNode.insertBefore(tabla, timeLeft);
			timeLeft.parentNode.removeChild(timeLeft);
			unsafeWindow.t();
		}
	}
	
	else if (getScriptConf('proInputs') && (hangarSection || defenseSection)) {
		var inputs = locateSnapshot("//div[@id='content']//input[@type='text' or not(@type)]");

		for (var i=0; i<inputs.snapshotLength; i++) {
			inputs.snapshotItem(i).parentNode.appendChild(document.createElement('br'));

			var a = document.createElement("a");
			a.setAttribute("href", "javascript:var texto=document.getElementsByName('"+inputs.snapshotItem(i).name+"')[0];texto.value=999999;texto.onchange();");
			a.innerHTML = "&infin;";
			inputs.snapshotItem(i).parentNode.appendChild(a);
				var a = document.createElement("a");
			a.style['cursor'] = 'pointer';
			a.setAttribute("onmousedown", "pressed=true;cambiar('"+inputs.snapshotItem(i).name+"', true, this.parentNode.lastChild.firstChild.value)");
			a.setAttribute("onmouseout", "if (pressed=true) {pressed=false; contador=5; incremento=1;}");
			a.setAttribute("onmouseup", "pressed=false; contador=5; incremento=1; this.parentNode.firstChild.onchange()");
			a.innerHTML="+";
			inputs.snapshotItem(i).parentNode.appendChild(a);

			var a = document.createElement("a");
			a.style['cursor'] = 'pointer';
			a.setAttribute("onmousedown", "pressed=true;cambiar('"+inputs.snapshotItem(i).name+"', false, this.parentNode.lastChild.firstChild.value)");
			a.setAttribute("onmouseout", "if (pressed=true) {pressed=false; contador=5; incremento=1;}");
			a.setAttribute("onmouseup", "pressed=false; contador=5; incremento=1; this.parentNode.firstChild.onchange()");
			a.innerHTML = "&minus;";
			inputs.snapshotItem(i).parentNode.appendChild(a);

			var a = document.createElement("a");
			a.setAttribute("href", "javascript:var texto=document.getElementsByName('"+inputs.snapshotItem(i).name+"')[0];texto.value=0;texto.onchange();");
			a.innerHTML = "&bull;";
			inputs.snapshotItem(i).parentNode.appendChild(a);
		}
	}
	
	var element = locateFirst("//table[@id='resources']/tbody/tr[3]").getElementsByTagName('td');

	if (hangarSection || defenseSection) {
		if (GM_getValue('sinConstruir', '')=='') {
			if (getScriptConf('SYConst')) {
				element[0].innerHTML+= "<br/><font color=lightgreen id='metalRestante' title='Metal restante'>"+puntuar(metal)+"</font>";
				element[1].innerHTML+= "<br/><font color=lightgreen id='cristalRestante' title='Cristal restante'>"+puntuar(cristal)+"</font>";
				element[2].innerHTML+= "<br/><font color=lightgreen id='deuterioRestante' title='Deuterio restante'>"+puntuar(deuterio)+"</font>";

				var inputs = locateSnapshot("//div[@id='content']//input[@type='text' or not(@type)]");
				for (var i=0; i<inputs.snapshotLength; i++) {
					var recursos = inputs.snapshotItem(i).parentNode.parentNode.getElementsByTagName('b');
					var metalNew=0;
					var cristalNew=0;
					var deuterioNew=0;
					for (var j=0; j<recursos.length; j++) {
						if (recursos[j].previousSibling.nodeValue.indexOf('Metal')!=-1)
							metalNew=parseInt(recursos[j].innerHTML.replace(/\./g, ''), 10);
						else if (recursos[j].previousSibling.nodeValue.indexOf('Cristal')!=-1)
							cristalNew=parseInt(recursos[j].innerHTML.replace(/\./g, ''), 10);
						else if (recursos[j].previousSibling.nodeValue.indexOf('Deuterio')!=-1)
							deuterioNew=parseInt(recursos[j].innerHTML.replace(/\./g, ''), 10);
					}
					recursos = [metalNew, cristalNew, deuterioNew].join(':');
					inputs.snapshotItem(i).setAttribute('onchange', "if (this.value=='') this.value='0'; if (parseInt(this.value, 10)>parseInt(this.parentNode.lastChild.firstChild.value, 10)) this.value=this.parentNode.lastChild.firstChild.value; calcularMax(calcularRecursos())");
					inputs.snapshotItem(i).setAttribute('onkeyup', 'onchange()');
					var nodo = document.createElement('div');
					// faltaria poner el tiempo
					nodo.innerHTML="<input type='hidden' name='max'/><input type='hidden' name='recursos' value='"+recursos+"'/><input type='hidden' name='time'/><br/>máx <a name='maxRel'></a>";
					nodo.setAttribute("onclick", "this.parentNode.firstChild.value=parseInt(this.parentNode.firstChild.value, 10)+parseInt(this.lastChild.innerHTML, 10);this.parentNode.firstChild.onchange()");
					inputs.snapshotItem(i).parentNode.appendChild(nodo);
//					document.getElementById('max').id='max_'+inputs.snapshotItem(i).name.match(/\[(.*)\]/)[1];
				}

				unsafeWindow.calcularRecursos = function() {
					var metalNew = metal;
					var cristalNew = cristal;
					var deuterioNew = deuterio;

					for (var i=0; i<inputs.snapshotLength; i++) {
						var nShips = parseInt(inputs.snapshotItem(i).value, 10);
						var recursos = inputs.snapshotItem(i).parentNode.lastChild.childNodes[1].value.split(':');
						metalNew -= nShips*parseInt(recursos[0], 10);
						cristalNew -= nShips*parseInt(recursos[1], 10);
						deuterioNew -= nShips*parseInt(recursos[2], 10);
					}
					if (debugMode) GM_log('Recursos restantes:\nmetal: '+metalNew+' cristal: '+cristalNew+' deuterio: '+deuterioNew);
					return [metalNew, cristalNew, deuterioNew].join(':');
				} // calcularRecursos()
				
				unsafeWindow.calcularMax = function(recursos) {
					var metalNew = parseInt(recursos.split(':')[0], 10);
					var cristalNew = parseInt(recursos.split(':')[1], 10);
					var deuterioNew = parseInt(recursos.split(':')[2], 10);
					
					for (var i=0; i<inputs.snapshotLength; i++) {
						var recursos = inputs.snapshotItem(i).parentNode.lastChild.childNodes[1].value.split(':');
						var metal2=(recursos[0]=='0')?999999:Math.floor(metalNew/parseInt(recursos[0], 10));
						var cristal2=(recursos[1]=='0')?999999:Math.floor(cristalNew/parseInt(recursos[1], 10));
						var deuterio2=(recursos[2]=='0')?999999:Math.floor(deuterioNew/parseInt(recursos[2], 10));
						var min = metal2;
						min = Math.min(min, cristal2);
						min = Math.min(min, deuterio2);
						if (min==999999) min=0;
						inputs.snapshotItem(i).parentNode.lastChild.lastChild.innerHTML=min;
						inputs.snapshotItem(i).parentNode.lastChild.firstChild.value=parseInt(inputs.snapshotItem(i).value,10)+min;
						document.getElementById('metalRestante').innerHTML=puntuar(metalNew);
						document.getElementById('cristalRestante').innerHTML=puntuar(cristalNew);
						document.getElementById('deuterioRestante').innerHTML=puntuar(deuterioNew);
					}
				} // calcularMax()
				
				unsafeWindow.enviar = function enviar() {
					var cade