Scripts


Styles


Plugins


Users


Forum


Developer
Username:
Password:
User Scripts
Title:

Travian TroopToolUpdater

Date Added:
2011-07-04 09:58:50 Installs: 559
Description: v 0.5.1
Fixed work under IE7.
___________________________

v 05.
Fixed bug with disabled marketplace.
Changed XPath support (now it uses SELENIUM code)
__________________

v 04.

1. Works with the latest Travian version.
2. works with Travian beyond installed.
__________________

Important! You need to use <a href = "http://laffers.net/works/trooptool.php">Super Trooptool mod </a> for this script to work.

The script will ask you for an "authentication key" first time you try to use it. You will find this key in "My profile" in your Super Troop tool. Copy & paste it.
Preview of Travian TroopToolUpdater
View script source of Travian TroopToolUpdater
Comment of Travian TroopToolUpdater
[2009-11-25 03:04:59]uNkind says:
// ==UserScript==
// @author Risi, Hill
// @email rlaffers@gmail.com, hill_devel@hotmail.com
// @namespace http://userscripts.org/
// @name Travian Trooptool Updater
// @description Update your troop tool with a one click from the rally point.
// @include http://s*.travian.*/*
// @include http://s*.travian3.*/*
// @include http://welt*.travian.*/*
// @exclude http://forum.travian.*
// @exclude http://www.travian.*
// @version 0.5
// ==/UserScript==


/************************ XPath Support*******************************/

// release number
document.DomL3XPathRelease = "0.0.3.0";

// XPathException
// An Error object will be thrown, this is just a handler to instantiate that object
var XPathException = new _XPathExceptionHandler();
function _XPathExceptionHandler()
{
this.INVALID_EXPRESSION_ERR = 51;
this.TYPE_ERR = 52;
this.NOT_IMPLEMENTED_ERR = -1;
this.RUNTIME_ERR = -2;

this.ThrowNotImplemented = function(message)
{
ThrowError(this.NOT_IMPLEMENTED_ERR, "This functionality is not implemented.", message);
}

this.ThrowInvalidExpression = function(message)
{
ThrowError(this.INVALID_EXPRESSION_ERR, "Invalid expression", message);
}

this.ThrowType = function(message)
{
ThrowError(this.TYPE_ERR, "Type error", message);
}

this.Throw = function(message)
{
ThrowError(this.RUNTIME_ERR, "Run-time error", message);
}

function ThrowError(code, description, message)
{
var error = new Error(code, "DOM-L3-XPath " + document.DomL3XPathRelease + ": " + description + (message ? ", \"" + message + "\"": ""));
error.code = code;
error.name = "XPathException";
throw error;
}
}

// DOMException
// An Error object will be thrown, this is just a handler to instantiate that object
var DOMException = new _DOMExceptionHandler();
function _DOMExceptionHandler()
{
this.ThrowInvalidState = function(message)
{
ThrowError(13, "The state of the object is no longer valid", message);
}

function ThrowError(code, description, message)
{
var error = new Error(code, "DOM : " + description + (message ? ", \"" + message + "\"": ""));
error.code = code;
error.name = "DOMException";
throw error;
}
}

// XPathEvaluator
// implemented as document object methods

// XPathExpression createExpression(String expression, XPathNSResolver resolver)
document.createExpression = function
(
expression, // String
resolver // XPathNSResolver
)
{
// returns XPathExpression object
return new XPathExpression(expression, resolver);
}

// XPathNSResolver createNSResolver(nodeResolver)
document.createNSResolver = function
(
nodeResolver // Node
)
{
// returns XPathNSResolver
return new XPathNSResolver(nodeResolver);
}

// XPathResult evaluate(String expresison, Node contextNode, XPathNSResolver resolver, Number type, XPathResult result)
document.evaluate = function
(
expression, // String
contextNode, // Node
resolver, // XPathNSResolver
type, // Number
result // XPathResult
)
// can raise XPathException, DOMException
{
// return XPathResult
return document.createExpression(expression, resolver).evaluate(contextNode, type, result);
}

// XPathExpression
function XPathExpression
(
expression, // String
resolver // XPathNSResolver
)
{
this.expressionString = expression;
this.resolver = resolver;

// XPathResult evaluate(Node contextNode, Number type, XPathResult result)
this.evaluate = function
(
contextNode, // Node
type, // Number
result // XPathResult
)
// raises XPathException, DOMException
{
// return XPathResult
return (result && result.constructor == XPathResult ? result.initialize(this, contextNode, resolver, type) : new XPathResult(this, contextNode, resolver, type));
}

this.toString = function()
{
return "[XPathExpression]";
}
}

// XPathNSResolver
function XPathNSResolver(node)
{
this.node = node;

// String lookupNamespaceURI(String prefix)
this.lookupNamespaceURI = function
(
prefix // String
)
{
XPathException.ThrowNotImplemented();
// return String
return null;
}

this.toString = function()
{
return "[XPathNSResolver]";
}
}

// XPathResult
XPathResult.ANY_TYPE = 0;
XPathResult.NUMBER_TYPE = 1;
XPathResult.STRING_TYPE = 2;
XPathResult.BOOLEAN_TYPE = 3;
XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4;
XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5;
XPathResult.UNORDERED_SNAPSHOT_TYPE = 6;
XPathResult.ORDERED_SNAPSHOT_TYPE = 7;
XPathResult.ANY_UNORDERED_NODE_TYPE = 8;
XPathResult.FIRST_ORDERED_NODE_TYPE = 9;

function XPathResult
(
expression, // XPathExpression
contextNode, // Node
resolver, // XPathNSResolver
type // Number
)
{
this.initialize = function(expression, contextNode, resolver, type)
{
this._domResult = null;
this._expression = expression;
this._contextNode = contextNode;
this._resolver = resolver;
if (type)
{
this.resultType = type;
this._isIterator = (type == XPathResult.UNORDERED_NODE_ITERATOR_TYPE ||
type == XPathResult.ORDERED_NODE_ITERATOR_TYPE ||
type == XPathResult.ANY_TYPE);
this._isSnapshot = (type == XPathResult.UNORDERED_SNAPSHOT_TYPE || type == XPathResult.ORDERED_SNAPSHOT_TYPE);
this._isNodeSet = type > XPathResult.BOOLEAN_TYPE;
}
else
{
this.resultType = XPathResult.ANY_TYPE;
this._isIterator = true;
this._isSnapshot = false;
this._isNodeSet = true;
}
return this;
}

this.initialize(expression, contextNode, resolver, type);

this.getInvalidIteratorState = function()
{
return documentChangeDetected() || !this._isIterator;
}

this.getSnapshotLength = function()
// raises XPathException
{
if (!this._isSnapshot)
{
XPathException.ThrowType("Snapshot is not an expected result type");
}
activateResult(this);
// return Number
return this._domResult.length;
}

// Node iterateNext()
this.iterateNext = function()
// raises XPathException, DOMException
{
if (!this._isIterator)
{
XPathException.ThrowType("Iterator is not an expected result type");
}
activateResult(this);
if (documentChangeDetected())
{
DOMException.ThrowInvalidState("iterateNext");
}
// return Node
return getNextNode(this);
}

// Node snapshotItem(Number index)
this.snapshotItem = function(index)
// raises XPathException
{
if (!this._isSnapshot)
{
XPathException.ThrowType("Snapshot is not an expected result type");
}
// return Node
return getItemNode(this, index);
}

this.toString = function()
{
return "[XPathResult]";
}

// returns string value of the result, if result type is STRING_TYPE
// otherwise throws an XPathException
this.getStringValue = function()
{
if (this.resultType != XPathResult.STRING_TYPE)
{
XPathException.ThrowType("The expression can not be converted to return String");
}
return getNodeText(this);
}

// returns number value of the result, if the result is NUMBER_TYPE
// otherwise throws an XPathException
this.getNumberValue = function()
{
if (this.resultType != XPathResult.NUMBER_TYPE)
{
XPathException.ThrowType("The expression can not be converted to return Number");
}
var number = parseInt(getNodeText(this));
if (isNaN(number))
{
XPathException.ThrowType("The result can not be converted to Number");
}
return number;
}

// returns boolean value of the result, if the result is BOOLEAN_TYPE
// otherwise throws an XPathException
this.getBooleanValue = function()
{
if (this.resultType != XPathResult.BOOLEAN_TYPE)
{
XPathException.ThrowType("The expression can not be converted to return Boolean");
}

var
text = getNodeText(this);
bool = (text ? text.toLowerCase() : null);
if (bool == "false" || bool == "true")
{
return bool;
}
XPathException.ThrowType("The result can not be converted to Boolean");
}

// returns single node, if the result is ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE
// otherwise throws an XPathException
this.getSingleNodeValue = function()
{
if (this.resultType != XPathResult.ANY_UNORDERED_NODE_TYPE &&
this.resultType != XPathResult.FIRST_ORDERED_NODE_TYPE)
{
XPathException.ThrowType("The expression can not be converted to return single Node value");
}
return getSingleNode(this);
}

function documentChangeDetected()
{
return document._XPathMsxmlDocumentHelper.documentChangeDetected();
}

function getNodeText(result)
{
activateResult(result);
return result._textResult;
// return ((node = getSingleNode(result)) ? (node.nodeType == 1 ? node.innerText : node.nodeValue) : null);
}

function findNode(result, current)
{
switch(current.nodeType)
{
case 1: // NODE_ELEMENT
var id = current.attributes.getNamedItem("id");
if (id)
{
return document.getElementById(id.value);
}
XPathException.Throw("unable to locate element in XML tree");
case 2: // NODE_ATTRIBUTE
var id = current.selectSingleNode("..").attributes.getNamedItem("id");
if (id)
{
var node = document.getElementById(id.text);
if (node)
{
return node.attributes.getNamedItem(current.nodeName);
}
}
XPathException.Throw("unable to locate attribute in XML tree");
case 3: // NODE_TEXT
var id = current.selectSingleNode("..").attributes.getNamedItem("id");
if (id)
{
var node = document.getElementById(id.value);
if (node)
{
for(child in node.childNodes)
{
if (child.nodeType == 3 && child.nodeValue == current.nodeValue)
{
return child;
}
}
}
}
XPathException.Throw("unable to locate text in XML tree");
}
XPathException.Throw("unknown node type");
}

function activateResult(result)
{
if (!result._domResult)
{
try
{
var expression = result._expression.expressionString;

// adjust expression if contextNode is not a document
if (result._contextNode != document && expression.indexOf("//") != 0)
{

expression = "//*[@id = '" + result._contextNode.id + "']" +
(expression.indexOf("/") == 0 ? "" : "/") + expression;
}

if (result._isNodeSet)
{
result._domResult = document._XPathMsxmlDocumentHelper.getDom().selectNodes(expression);
}
else
{
result._domResult = true;
result._textResult = document._XPathMsxmlDocumentHelper.getTextResult(expression);
}

}
catch(error)
{
//alert(error.description+"\n"+result._expression.expressionString);
XPathException.ThrowInvalidExpression(error.description);
}
}
}

function getSingleNode(result)
{
var node = getItemNode(result, 0);
result._domResult = null;
return node;
}

function getItemNode(result, index)
{
activateResult(result);
var current = result._domResult.item(index);
return (current ? findNode(result, current) : null);
}

function getNextNode(result)
{
var current = result._domResult.nextNode;
if (current)
{
return findNode(result, current);
}
result._domResult = null;
return null;
}
}

document.reloadDom = function()
{
document._XPathMsxmlDocumentHelper.reset();
}

document._XPathMsxmlDocumentHelper = new _XPathMsxmlDocumentHelper();
function _XPathMsxmlDocumentHelper()
{
this.getDom = function()
{
activateDom(this);
return this.dom;
}

this.getXml = function()
{
activateDom(this);
return this.dom.xml;
}

this.getTextResult = function(expression)
{
expression = expression.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "\"");
var xslText = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" +
"<xsl:output method=\"text\"/><xsl:template match=\"*\"><xsl:value-of select=\"" + expression + "\"/>" +
"</xsl:template></xsl:stylesheet>";
var xsl = new ActiveXObject("Msxml2.DOMDocument");
xsl.loadXML(xslText);
try
{
var result = this.getDom().transformNode(xsl);
}
catch(error)
{
alert("Error: " + error.description);
}
return result;
}

this.reset = function()
{
this.dom = null;
}

function onPropertyChangeEventHandler()
{
document._propertyChangeDetected = true;
}

this.documentChangeDetected = function()
{
return (document.ignoreDocumentChanges ? false : this._currentElementCount != document.all.length || document._propertyChangeDetected);
}

function activateDom(helper)
{
if (!helper.dom)
{
var dom = new ActiveXObject("Msxml2.DOMDocument");
/** SELENIUM:PATCH TO ALLOW PROVIDE FULL XPATH SUPPORT */
dom.setProperty("SelectionLanguage", "XPath");
/** END SELENIUM:PATCH */
dom.async = false;
dom.resolveExternals = false;
loadDocument(dom, helper);
helper.dom = dom;
helper._currentElementCount = document.all.length;
document._propertyChangeDetected = false;
}
else
{
if (helper.documentChangeDetected())
{
var dom = helper.dom;
dom.load("");
loadDocument(dom, helper);
helper._currentElementCount = document.all.length;
document._propertyChangeDetected = false;
}
}
}

function loadDocument(dom, helper)
{
return loadNode(dom, dom, document.body, helper);
}


/** SELENIUM:PATCH for loadNode() - see SEL-68 */
function loadNode(dom, domParentNode, node, helper)
{
// Bad node scenarios
// 1. If the node contains a /, it's broken HTML
// 2. If the node doesn't have a name (typically from broken HTML), the node can't be loaded
// 3. Node types we can't deal with
//
// In all scenarios, we just skip the node. We won't be able to
// query on these nodes, but they're broken anyway.
if (node.nodeName.indexOf("/") > -1
|| node.nodeName == ""
|| node.nodeName == "#document"
|| node.nodeName == "#document-fragment"
|| node.nodeName == "#cdata-section"
|| node.nodeName == "#xml-declaration"
|| node.nodeName == "#whitespace"
|| node.nodeName == "#significat-whitespace"
)
{
return;
}

// #comment is a <!-- comment -->, which must be created with createComment()
if (node.nodeName == "#comment")
{
try
{
domParentNode.appendChild(dom.createComment(node.nodeValue));
}
catch (ex)
{
// it's just a comment, we don't care
}
}
else if (node.nodeType == 3)
{
domParentNode.appendChild(dom.createTextNode(node.nodeValue));
}
else
{
var domNode = dom.createElement(node.nodeName.toLowerCase());
if (!node.id)
{
node.id = node.uniqueID;
}
domParentNode.appendChild(domNode);
loadAttributes(dom, domNode, node);
var length = node.childNodes.length;
for(var i = 0; i < length; i ++ )
{
loadNode(dom, domNode, node.childNodes[i], helper);
}
node.attachEvent("onpropertychange", onPropertyChangeEventHandler);
}
}
/** END SELENIUM:PATCH */

function loadAttributes(dom, domParentNode, node)
{
for (var i = 0; i < node.attributes.length; i ++ )
{
var attribute = node.attributes[i];
var attributeValue = attribute.nodeValue;
if (attributeValue && attribute.specified)
{
var domAttribute = dom.createAttribute(attribute.nodeName);
domAttribute.value = attributeValue;
domParentNode.setAttributeNode(domAttribute);
}
}
}

}



/************************End XPath Support*******************************/


var LOG_LEVEL = 1; // 0 - quiet, 1 - nearly quite, 2 - verbose, 3 - detailed
var sLang = "en";
var sGetParameters = "";
var sCurrentServer = ""; // Set this to the server's url to override automatic server detection
// (i.e. s1.travian.net)
// Dont set it if you're playing on multiple servers simultaneously!

var sAuthKey;

var init = detectLanguage() && initialize();

if(init) {

// Images
var sCloseBtn = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAIAAAAmdTLBAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1gYKECMhBqiEGQAAADJ0RVh0Q29tbWVudABFcnN0ZWxsdCB2b24gRmxvcmlhbiBTY2hyZWllciBtaXQgVGhlIEdJTVCOHcWrAAADLUlEQVR42pWUPYhdRRiG32/OuTdZXTcas0n2ZiVVYBttLFLFQuNPZTQgiIIphGBAtNTC0lZBRRQVEYWoBAyk8ActRFCRLa3SpNH9icm699695+6Z+X5ei7Obtc1UH+/MM+/M9w4jJD0wnNi9czVuZ3iwSlKbQ5ohP3rzn+FGTBvmlqbUgpRgBQDdAbC0AOAepbV2ezI3v/Txd+nuQ0Jy4+3XqsMDqeqYjHxryJJRCiPgRneAMKU7rbBktlNrtoaj0WrvrpMXlxMAH29Kf5/0+6hqqXtS16h7SImpkqqSVCHVkipIQqq6NanuTdZXDs7VNQA2WzEZS12znTJvM2eWQi1UpSnDqQUgtcCVpnRHSqmqACQA1BKToY83oxnPPvz0/BvvR9OwaaKZeDOO8TC2NmP077FPfjzw/CvM23STlKTu3eKV04bbE+a8/8FTAI6+dTG00Aq00DK1LF78HcDs6bNwAwPcSaHjc5TCXKh6/fVz3cTggytwQzjc7vt6uRP/OrOEcGEAAXKHB8DcRm5pCvf1V5/pxGOf/kT64pd/7MBPnoArXEEXUrDLRztFyVCFOSMoXH35TMcsfvFrV6ycXUqJIiFwoUmYROz6mzK30LJ7Nwq5+tITt57a6rP3S6IIk0TqeBrC9/oXVhjOcGGIAAmDD7+/xQ+++jMl7PmHwlXC9vrHkqkFYWSQXHjvSkeun3+oK458tizdFjAJEytpz98KNdMK3Ri+8M43O/CFRwBef/EkALlj7sila4IQBlzFC013+bLjT9WFdy938NqFx0CCBHjj3AOdePjyqoSmDv7f+Qtzy9JS8/SXbwGsnT8NN3b5hzP8xnMnALQ/fI5wmkELzQAIyWun5qsD98jMbNq3X6oaAjAEAYRQJYpYFi+wgtKyFMtlPPWrW3zqatQAVEu020kqiZCqliQIh6CLOoXCi1iBFahRzdTVQh0A6pujaA4OuHkDyqqfUdWAgCFCYQi9gsNVwukqZjQ35UghC8cByDSTG3///MKjo7WVfq+mSEhCRJVEAKFXdAlPDPdAeMUozjh6/PFLv/UPDYRkVuzr3dbfh5sjv3OmmunjP4EhhHJu9NM9AAAAAElFTkSuQmCC";

//Styles
var cssStyle = "";
cssStyle += ".ttu_draghandle {font-size: 120%; font-weight:bold;}";
cssStyle += ".ttu_close_btn {float:right; padding:2px 4px; color:white; margin:-5px -15px 0 0;}";
cssStyle += "#ttu_message {position:absolute; z-index:100; border:1px solid black; padding:10px 20px; color:black; width:335px}";
cssStyle += ".handle {cursor: move;}";

PRO_addStyle(cssStyle);

switch(sLang) {
case "sk":
aLangStrings = ["Vlastné jednotky", "Návrat z", "Podpora pre", "Jednotky od", "Útok na", "Lúpež proti", "Špehovanie v", "Preskúmať opustené údolie", "Zajaté jednotky od", "Prebehol pokus o aktualizáciu.", "Aktualizácia úspešná", "Aktualizácia zlyhala!", "Nastaviť Troop Tool Updater", "Aktualizovať Troop Tool", "Troop tool Updater:", "Skopíruj sem autentifikačný kľúč zo svojho profilu v Troop Tool-e"];
break;
case "ua":
aLangStrings = ["Власні війська", "Повернення з", "Підкріплення для", "Війська гравця", "Напад на", "Розбійницький набіг на", "Розвідка проти", "Дослідити покинуту долину", "Полонені війська гравця", "Update attempted with unknown result.", "Your troops were successfully updated.", "Update failed!", "Troop Tool Updater setup", "Update Troop Tool", "Troop tool Updater:", "Enter the authentication key from your Troop tool profile"];
break;
case "ru":
aLangStrings = ["Собственные войска", "Возвращение из", "Подкрепление для", "Войска игрока","Нападение на","Набег на", "Развед. операция против","","","Обновление завершилось с неизвестным результатом", "Войска успешно обновлены","Не удалось обновить войска","Настроить обновление войск","Обновить войска", "Обновитель войск", "Введите ключ аутентификации из вашего профиля в Труптуле"];
break;
case "it":
aLangStrings = ["Proprie truppe", "Ritorna da", "Rinforzi per", "Truppe di", "Attacco a", "Raid a", "Spia", "Preskúmať opustené údolie", "Truppe imprigionate da ", "Update attempted with unknown result.", "Le truppe sono state aggiornate correttamente.", "Aggiornamento fallito!", "Troop Tool Updater setup", "Aggiorna Troop Tool", "Troop tool Updater:", "Inserisci il link che trovi nel menu Profilo del Troop tool"];
break;
case "en":
case "com":
case "uk":

default:
aLangStrings = ["Own troops", "Return from", "Reinforcement for", "'s troops", "Attack", "Raid", "Spy", "Preskúmať opustené údolie", "Captured at", "Update attempted with unknown result.", "Your troops were successfully updated.", "Update failed!", "Troop Tool Updater setup", "Update Troop Tool", "Troop tool Updater:", "Enter the authentication key from your Troop tool profile"];
break;
}

// Do not change the array below!
var aLangStringsMaster = ["user_own_troops", "user_return_from", "user_troops_for", "user_troops_of", "user_attack_to", "user_raid_to", "user_spy_at", "user_explore_oasis", "user_captured_troops", "Update attempted with unknown result.", "Your troops were successfully updated.", "Update failed!", "Troop Tool Updater setup", "Update Troop Tool", "Troop tool Updater:", "Enter the authentication key from your Troop tool profile"];

window.addEvent('domready',onLoad);

} else {
_log(0, "Initialization failed");
alert("Initialization failed, Travian Task Queue is not running");
}


/**
* Custom log function .
* @param {int} level
* @param:{int} msg Message to log.
*/
function _log(level, msg) {

//if (level <= LOG_LEVEL && navigator.userAgent.indexOf("Opera") == -1)
PRO_log(msg);
}

/**
* Performs some initial checkings on conditions that have to be met to run the script
*
* @return true if initialization was successful, false otherwise
*/
function initialize() {

//addXPath();
if (typeof PRO_getValue == null) {
alert('This script requires IEPro v0.9 or newer, please upgrade to latest version!');
_log(0, "The current version of IEPro is too old");
return false;
}

if (sCurrentServer != "") {
return true;
}

// check what Travian server we're using
var re = new RegExp("^http://(.+\.travian3?\.[a-zA-Z.]+)(\/.*)?$", "i");
var server = re.exec(window.location.href);
//addXPathSupport();
if ((server) && (server[1])) {

sCurrentServer = server[1] + "_";
_log(1, "using settings for server '" + server[1] + "'");
return true;
}
else {
_log(0, "ERROR, unknown Travian server!");
return false;
}
}

/**
* Detects the language used based on the server's url
*
* @return true if the language is successfully detected, false otherwise
*/
function detectLanguage() {

//if(sLang != "") {return true;}
var re = null; re = new RegExp("([a-zA-Z]{2,3})(\/.*)?$", "i");
var lang = re.exec(window.location.href);

if(!lang) {
_log(0, "failed to detect language automatically!");
if(sLang == "") sLang = "en";
return true;
} else {
sLang = lang[1];
_log(2, "detected language '" + sLang + "'");
return true;
}
}


function GM_get(url, callback) {
var xmlhttp = PRO_xmlhttpRequest();

xmlhttp.open("GET", url, true); //true for async xmlhttp.send(null);
xmlhttp.setRequestHeader("User-agent","Mozilla/4.0 (compatible)");
xmlhttp.setRequestHeader("Accept","application/atom+xml,application/xml,text/xml");
xmlhttp.onreadystatechange =function(){callback(xmlhttp);};
xmlhttp.send(null);
}

function handleUpdateTroops(httpRequest, options) {

var oMsg = xpath("//div[@id='ttu_message']/div");
if(oMsg.snapshotLength > 0) {
oMsg = oMsg.snapshotItem(0);
var bAddMsg = true;
} else {
var bAddMsg = false;
}

if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) { // ok
var sResponse = httpRequest.responseText;
_log(3, sResponse);
if(!sResponse) { // error retrieving the response
if(!bAddMsg) printMsg( _t("Update attempted with unknown result."), true );
else addMsg(_t("Update attempted with unknown result."), oMsg);
return;
}
var re = new RegExp('<title>(.*)</title>', 'i');
var aMatchResults = sResponse.match(re);
if(aMatchResults[1] == "Success") {

if(!bAddMsg) printMsg(_t("Your troops were successfully updated.")); //Your troops were updated.
else addMsg(_t("Your troops were successfully updated."), oMsg);
} else {
if(!bAddMsg) printMsg(_t("Update failed!"), true); // Update error.
else addMsg(_t("Update failed!"), oMsg);
}
} else { // failed
_log(2, "HTTP request status: " + httpRequest.status);
}

}

}

function addMsg(sMsg, obj) {
obj.innerHTML += "<br/>" + sMsg ;
}

function printMsg(sMsg,bError) {
_log(3, "-> printMsg()");
var oDate = new Date();
var sWhen = oDate.toLocaleString() + "\n";
_log(1, sWhen + sMsg);

// delete old message
var oOldMessage = _$("ttu_message");
if(oOldMessage) {
_log(3, "Removing the old message." +oOldMessage);
oOldMessage.parentNode.removeChild(oOldMessage);
}

// here we generate a link which closes the message
var sLinkClose = "<a href='javascript:void(0)' onclick='document.getElementById(\"ttu_message\").parentNode.removeChild(document.getElementById(\"ttu_message\"));' class='ttu_close_btn'><img src='" +sCloseBtn+ "' alt='X' /></a>";

var sBgColor = (bError) ? "#FFB89F" : "#90FF8F";
var oMsgBox = document.createElement("div");
//oMsgBox.innerHTML = sLinkClose + "<div id='ttq_draghandle_msg' class='handle ttq_draghandle' style='background-color:white; -moz-opacity:0.2; border:1px dashed white;' >&nbsp;</div>" + sMsg;
oMsgBox.innerHTML = "<div id='ttu_draghandle_msg' class='handle'>" + sLinkClose + sMsg + "</div>";
oMsgBox.style.backgroundColor = sBgColor;
var msgCoords = getOption("MSG_POSITION", "215px_215px");
msgCoords = msgCoords.split("_");
oMsgBox.style.top = msgCoords[0];
oMsgBox.style.left = msgCoords[1];
oMsgBox.id = "ttu_message";
document.body.appendChild(oMsgBox);
makeDraggable(_$('ttu_draghandle_msg'));
_log(3, "<- printMsg()");
}

/**
* Retrieves the value corresponding do the given variable name and the current Travian server
* Use greasemonkey's built-in system instead of cookies to permantenly store and read settings
*
* @param name The name of the variable
* @param defaultValue default value if name is not found
*/
function getVariable(name, defaultValue) {
_log(3, "-> getVariable()");

if(!defaultValue) { var defaultValue = ''; }

name = sCurrentServer + name;
var data = PRO_getValue(name, defaultValue);

_log(3, "<- getVariable()");
return data;
}

/**
* Sets the value for the given variable name and the current Travian server
* Use greasemonkey's built-in system instead of cookies to permantenly store and read settings
*
* @param name The name of the variable
* @param value The value to be assigned
*/
function setVariable(name, value) {
_log(3, "-> setVariable()");

name = sCurrentServer + name;
PRO_setValue(name, value);

_log(3, "<- setVariable()");
return true;
}

/**
* @param key: name of the parameter in the TTQ_OPTIONS variable
* @param defaultValue: this is returned if the parameter is not found
* @param type: if set, type conversion occurs. Values {string, integer, boolean} The conversion occurs only if it is not the defaultValue being returned.
*/
function getOption(key, defaultValue, type) {
_log(3, "-> getOption()");

var options = getVariable('TTU_OPTIONS', '');
options = options.split(",");
var myOption = options.indexOf(key);
if(myOption < 0) {return defaultValue;}
switch(type) {
case "boolean":
var myOption = ( options[myOption + 1] == "true") ? true:false;
break;
case "integer":
var myOption = parseInt(options[myOption + 1]);
break;
case "string":
default:
var myOption = options[myOption + 1];
break;
}
_log(3, "<- getOption()");
return myOption;
}

function setOption(key, value) {
_log(3, "-> setOption()");

var options = getVariable('TTU_OPTIONS', '');
if(options != '') options = options.split(",");
else options = [];
var myOption = options.indexOf(key);
if(myOption < 0) {
options.push(key);
options.push(value);
} else {
options[myOption + 1] = value;
}

setVariable('TTU_OPTIONS', options.join(","));
_log(3, "<- setOption()");
}

/************************ Drag n drop*******************************/
var mouseOffset = null;
var iMouseDown = false;
var lMouseState = false;
var dragObject = null;
var curTarget = null;

function mouseCoords(ev){
return {x:ev.pageX, y:ev.pageY};
}

function makeClickable(object){
object.onmousedown = function(){
dragObject = this;
}
}

function getMouseOffset(target, ev){
var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
var left = 0;
var top = 0;
while (e.offsetParent){
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
e = e.offsetParent;
}
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
return {x:left, y:top};
}

function mouseMove(ev){
var target = ev.target;
var mousePos = mouseCoords(ev);

if(dragObject){
dragObject.style.position = 'absolute';
dragObject.style.top = (mousePos.y - mouseOffset.y) +"px";
dragObject.style.left = (mousePos.x - mouseOffset.x) +"px";
}
lMouseState = iMouseDown;
return false;
}

function mouseUp(ev){
if(dragObject) {
switch(dragObject.id) {
case "ttq_message":
var key = "MSG_POSITION";
break;
case "timerform_wrapper":
var key = "FORM_POSITION";
break;
case "ttq_history":
var key = "HISTORY_POSITION";
break;
case "ttq_tasklist":
default:
var key = "LIST_POSITION";
break;
}
setOption(key, dragObject.style.top +"_"+ dragObject.style.left);
}
dragObject = null;
iMouseDown = false;
}

function mouseDown(ev){
var mousePos = mouseCoords(ev);
var target = ev.target;
iMouseDown = true;
if(target.getAttribute('DragObj')){
return false;
}
}

function makeDraggable(item){
if(!item) return;
item.attachEvent("onmousedown",function(ev){
dragObject = this.parentNode;
mouseOffset = getMouseOffset(this.parentNode, ev);
return false;
}, false);
}

//document.attachEvent("onmousemove", mouseMove, false);
//document.attachEvent("onmousedown", mouseDown, false);
//document.attachEvent("onmouseup", mouseUp, false);

/************************************************************************************/

function xpath(query, object) {
if(!object) var object = document;
return document.evaluate(query, object, null, XPathResult.UNORDERED_SNAPSHOT_TYPE, null);
}

/** Kudos to QP for writing this function. */
function coordsXYToZ(x, y) {
x = parseInt(x);
y = parseInt(y);
var coordZ = (x + 401) + ((400 - y) * 801);
return coordZ;
}

function _t(str) {
_log(0,"t("+str+")");
var index = aLangStringsMaster.indexOf(str);
var sTranslatedStr = aLangStrings[index];
if(sTranslatedStr) {

return sTranslatedStr;
} else {

return str;
}
}

function _$(id) {
return document.getElementById(id);
}

function createLink() {

_log(3, "-->createLink");
_log(2, "sAuthKey = "+sAuthKey);
var xpathRes = null;
if(_$("textmenu")!=null)
xpathRes = xpath("//div[@id='textmenu']//a[contains(@href,\"warsim.php\")]");
else
xpathRes=xpath("//div[@id='content']/p[2]/a[contains(@href,\"warsim.php\")]");
if(xpathRes.getSnapshotLength() <= 0) {
_log(1, "This is not Rally point.")
return false;
}

if(!sAuthKey) {
var oLink = document.createElement("a");
oLink.id = "setupTT";
oLink.innerHTML = _t("Troop Tool Updater setup");
oLink.title = _t("Troop Tool Updater setup");
oLink.href = "javascript:void(0)";
oLink.attachEvent('onclick', promptKey);
} else {
var oLink = document.createElement("a");
oLink.id = "updateTT";
oLink.innerHTML = _t("Update Troop Tool");
oLink.title = _t("Update Troop Tool");
oLink.href = "javascript:void(0)";
oLink.attachEvent('onclick', startUpdate, false);
}
//_log(3, "........" + xpathRes.snapshotItem(0).parentNode.innerHTML);f
var oPar = xpathRes.snapshotItem(0).parentNode;
oPar.innerHTML += " | ";
oPar.appendChild(oLink);

_log(3, "<--createLink");
}

function startUpdate() {

printMsg("-->startUpdate");
var oMsg = xpath("//div[@id='ttu_message']/div");
if(oMsg.snapshotLength > 0) {
oMsg = oMsg.snapshotItem(0);
};
//parse page

var aTroops = parse();
aTroops.push("end");
var re = /[0-9]{6}\|[0-9]{6}/;

//send data
var key = getVariable("TTU_KEY", false);
if(key == false) {
_log(1, "No troop tool URL is set!");
promptKey();
return false;
} else if(aTroops.length == 0) {
_log(1, "No troops were found.");
} else {
_log(2, "Sending troops...");

var bHaveCoords = false;
bDoSend = false;
var j = 1;
for(var i=0; i < aTroops.length; i++) {
if(!bHaveCoords && !re.test(aTroops[i])) {
_log(3, "no coords yet, this is not coord");
continue;
} else if(!bHaveCoords && re.test(aTroops[i])) {
_log(3, "no coords yet, this is coords");
var aCoord = aTroops[i].split("|");
url = key + "&fc="+aCoord[0]+"&tc="+aCoord[1];
bHaveCoords = true;
} else if(re.test(aTroops[i])) {
_log(3, "coords yes, this is next coord");
bDoSend = true;
i--;
} else if(aTroops[i] == "end") {
_log(3, "coords yes, this is end");
bDoSend = true;
} else {
_log(3, "coords yes, this is number");
if(j<12) url += "&t"+j+"="+aTroops[i]; //j can be max 11 (11 types of units), but the array may contain a 12th dummy member
j++;

}

if(bDoSend) {
_log(2, "URL is \n"+url)
GM_get(url, handleUpdateTroops);
bHaveCoords = false;
bDoSend = false;
url = "";
j=1;;
}
}

}

_log(0, "<--startUpdate");
}

function parse() {
try
{
var oMsg = xpath("//div[@id='ttu_message']/div");
if(oMsg.snapshotLength > 0) {
oMsg = oMsg.snapshotItem(0);
};
//addMsg("-->parse",oMsg);

var aTroops = new Array();
var matches, coordOrigin, coordPosition, table;
var keywords = _t('user_own_troops')+"|"+
_t('user_return_from')+"|"+
_t('user_troops_for')+"|"+
_t('user_troops_of')+"|"+
_t('user_attack_to')+"|"+
_t('user_raid_to')+"|"+
_t('user_spy_at')+"|"+
_t('user_explore_oasis')+"|"+
_t('user_captured_troops');
var re = new RegExp("(" + keywords + ")");
var re2 = new RegExp(">[0-9]{1,}</TD>", "g");
var skip = 0;
var tables=null;

if(document.getElementById('lmid2')!=null)
tables = xpath("//div[@id='lmid2')/table");
else
tables = xpath("//div[@id='build']/table[@class='troop_details']");
if(tables.snapshotLength < 1) {

addMsg( "No tables with troops found on this page.",oMsg);
_log(2, "No tables with troops found on this page.");
return false;
}
else
//addMsg(tables.snapshotItem(0).innerHTML,oMsg);

var aTroops = new Array();

for(var i=0; i < tables.getSnapshotLength(); i++) {
//_log(2, tables.snapshotItem(i));
table = tables.snapshotItem(i);
if(table.getElementsByTagName('tr')[0].className=='cbgx')
//travian beyond installed
continue;
table = tables.snapshotItem(i).innerHTML; //_log(3, table);


//coordinates
_log(0,table);
matches = table.match(/<a id=[0-9a-z_]* href="karte\.php\?d=[0-9]{6}/gi); _log(3, matches);

coordOrigin = matches[0].match(/[0-9]{6}/);
coordOrigin = coordOrigin[0];
if(matches[1] != null) {
coordPosition = matches[1].match(/[0-9]{6}/);
coordPosition = coordPosition[0];
} else {
coordPosition = coordOrigin;
}

//action
matches = table.match(re); _log(2, i+". searching for keywords:\nexpression= " +re+ "\nmatches\n" +matches);

if(matches == null) {
_log(1, "Warning: Unrecognized key word.")
continue;
}
switch(matches[1]) {
case _t("user_own_troops"):// my troops at home
case _t("user_return_from"):
case _t("user_attack_to"):
case _t("user_raid_to"):
case _t("user_spy_at"):
case _t("user_explore_oasis"):
coordPosition = coordOrigin;
break;
case _t("user_troops_for"): //my troops stationed elsewhere
case _t("user_captured_troops"):
_log(2, "Reinforcements");
break;
case _t("user_troops_of"): //other troops. go to the next table
_log(2, "Other troops");
skip = 1;
}
if(skip) {
skip = 0;
continue;
}

//add new set, or add to an existing one
matches = table.match(re2);
if(matches == null || matches.length < 10) continue; _log(0,"this is not my attack/raid/reinforcement");
var pos = aTroops.indexOf(coordOrigin + '|' + coordPosition); _log(3, "position = "+pos);

if(pos > -1) {

for(var thisMatch in matches) {
if(thisMatch.match(/[0-9]+/)==null)
continue;
thisMatch = parseInt(thisMatch);
var thisNum = matches[thisMatch].match(/[0-9]+/); //_log(3, "add "+thisNum[0] + " to " + aTroops[(pos + 1 + thisMatch)]);
if(thisNum > 0) {
aTroops[pos + 1 + thisMatch] = parseInt(aTroops[pos + 1 + thisMatch]) + parseInt(thisNum);
}
}

} else {

aTroops.push(coordOrigin + '|' + coordPosition);

for(var thisMatch in matches) {
if(thisMatch.match(/[0-9]+/)==null)
continue;
var thisNum = matches[thisMatch].match(/[0-9]+/); _log(3, "new "+thisNum[0]);
aTroops.push(parseInt(thisNum));

}
aTroops.push(0); //dummy space for hero from subsequent tables (if he is not present in this one)
}
_log(2, "aTroops:\n"+aTroops);
}
//addMsg(aTroops,oMsg);
return aTroops;
}
catch(e)
{
_log(0,e.description);
}
//addMsg( "<--parse",oMsg);
}

function promptKey() {

_log(3, "-->promptKey");
//var sAuthKey = getVariable("TTU_KEY", false);
var newKey = false;
var s = _t("Troop tool Updater:") ;
var newKey = PRO_prompt(_t("Troop tool Updater:") + "\n" + _t("Enter the authentication key from your Troop tool profile") + "\n", sAuthKey);
var re = /^http[s]?:\/\/[./?=_&a-zA-Z0-9]*$/i;
if(re.test(newKey)) {
_log(2, "zadana platna adresa");
setVariable("TTU_KEY", newKey);
location.reload();
} else {
_log(2, "zadana NEplatna adresa!");
}
_log(3, "<--promptKey");
}

function onLoad() {
sAuthKey = getVariable("TTU_KEY", false);
PRO_registerMenuCommand(_t("Troop Tool Updater setup"), promptKey);
var re = /.*build\.php.*/i;
if (re.test(window.location.href)) {
createLink();
}
}




[2010-07-17 19:57:32]kimokarlos says:
good aydia


Join Iescripts for a free account, or Login if you are already a member.
Username: Password:

Written by
Name:Hill
Scripts:1
Styles:0
Plugins:0
Tags
 
  About IE7Pro
IE7Pro is a plugin for the Internet Explorer web browser. It allows you to change how your favorite pages behave and look. There are many scripts that have already been written, and if you know javascript you can easily create your own! This site is a repository to download and install IE user scripts.
  How to install user script

1 . First you should have install IE7Pro 0.9.12 and above which support IE user scripts.

2. Check if IE7Pro "Preference" - "User Scripts" - "EnabLe User Script" is enabled.

3. Find your favorite scripts on iescripts.org and click "Install This Script" .

 

iescripts.org