Scripts


Styles


Plugins


Users


Forum


Developer
Username:
Password:
User Scripts
Title:

Farming Machine for Travian 3.5

Date Added:
2009-10-01 23:11:55 Installs: 881
Description: // ==UserScript==

// @name Farming Machine for Travian 3.5

// @author pixelgeek (update from Sowrov)

// @namespace FM

// @description Updated Version from the Version by Sowrov (Adapted to the new Travian Layout)

// @include http://*.travian.*/build.php?*gid=16*

// @include http://*.travian.*/build.php?*id=39*

// @include http://*.travian.*/a2b.php*

// @include http://*.travian.*/karte.php*

// @include http://*.travian.*/berichte.php*

// @exclude http://forum.travian.*

// @email felix@pixelgeek.ch

// @version 1.2.2

// ==/UserScript==



var SCRIPT = {

url : 'http://userscripts.org/scripts/source/48557.user.js',

version : '1.2.2' //same value as @version

};



//adapt these variables to your personal need:

//--------------------------------------------

//Message Window config

var messageWindowTop = 450; //0 means top of the browser window

var messageWindowLeft = 700; //0 means left most point of the browser window

var zIndex = 100; //make it as big as you want to put the message window over top of anything

//Waiting times

var minWait = 5000; //Don't make it smaller then 5000ms!

var maxWait = 2 * minWait;

//Skipping villages

var maxSkipCount = 1; //Max. Number for skipped farms before changing villages, make it -1 to try the whole list

//Map
//new farmImage by g.georgi
var farmImage = "http://img4.imageshack.us/img4/5373/d05.gif";

//var farmImage = "http://imgtrav.ifrance.com/img/m/d130.gif";
//d01 d02 d03 d04 is also possible. but might conflict later when you get allies and stuff like that.
//Default troops
var defTroops = "0,0,0,0,0,0,0,0,0,0";

//Logging

var logLevel = 0; //you probably don't need to change this

//--------------------------------------------



/* Log Levels:

* 0: no special logging (logs general stuff)

* 1: log for testing level1

* 2: log for testing level2

* 3: logs calls of all functions

* 4: logs steps inside of functions

* 5: logs values inside of functions

*/



//global variables (don't changes these)

var dom = new DOMUtils();

var server = location.hostname;

var rootPath = "http://" + server + "/";

var suffixLocal, suffixGlobal;

var lang = new Array(); //language definitions

var image = new Array(); //all images used

var farmList = new Array(); //complete farm List

var fque = new Array(); //farm queue.

var prioque = new Array(); //priority queue.

var user_race = 1; //Default Romans :|

var globalInt = -1;

var totalTroops = new Array(); //for temporary value passing between functions

var runningDiv;

var random; //random farming

var priorityAttack = false;

var vT35;



var XPFirst = XPathResult.FIRST_ORDERED_NODE_TYPE;

var XPList = XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE;

var XPListO = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE;

var XPIter = XPathResult.UNORDERED_NODE_ITERATOR_TYPE;



/*Structure: farmlist, farmque, prioque

*-----------------------------------------------------------------------------------------

* 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 >:)

*x,y|t,r,o,o,p,s|Tribe|FPlayerName|FPlayerId|FVillageName|C_value|activeBool|attackType>:)

*---------------------------------------------------------------------------------------*/



//FM main functions

function main() {

FM_log(3,"main() called");

suffixGlobal = server + '_' + getPlayerId();

suffixLocal = suffixGlobal + '_' + getActiveVillageId();



FM_log(3,"suffixGlobal is: "+suffixGlobal);

FM_log(3,"suffixLocal is: "+suffixLocal);



//define Travian 3.5 Version

getT35version();



FM_log(5,document.URL);

var html = document.body.innerHTML; // In case 'Unable to load site' is showed, try to Refresh the page.

if (html.indexOf(" <!-- ERROR ITEM CONTAINER") != -1) {

window.location.replace(rootPath + "a2b.php");

}



if (GM_getValue("Active_" + suffixGlobal, -1) > -1 && GM_getValue("ReadRep_" + suffixGlobal, -1)==1 )

{

newreport = document.getElementsByTagName('html')[0].innerHTML.indexOf('id=\"n5\" class=\"i1\"')+document.getElementsByTagName('html')[0].innerHTML.indexOf('id=\"n5\" class=\"i3\"');

if ( newreport != -2)

{

if(document.URL.indexOf("berichte.php") == -1) {

window.open("/berichte.php", "_self");

}

checkreports();

return;

}

}



// start countdown and forward to rallypoint if FM is active

// this is not working because FM script not runs on all the Travian pages
// could be working if @includes get changed, but this probably leads to a slow browser


/*

if (GM_getValue("Active_" + suffixGlobal, -1) > -1)

{

//alert("waiting");

setTimeout(function(){window.open("/a2b.php","_self");}, 60000); //wait 1 minute then go back to rally point

}

*/



// get variable for random farming

random = GM_getValue("RandomFarming_" + suffixGlobal, 0);



FM_log(3,"Setting language, images & style");

setLanguage();

loadImage();

loadStyle();

var url = document.URL;

url = url.substring(url.lastIndexOf("/") + 1);

user_race = GM_getValue('Tribe_' + suffixGlobal, -1);

if (user_race != -1) {

user_race = GM_getValue('Tribe_' + suffixGlobal, 0);

user_race = parseInt(user_race);

} else {

if (url.indexOf("a2b.php") != -1) {

user_race = 1 + 10 * getPlayerTribe();

GM_setValue('Tribe_' + suffixGlobal, user_race);

alert(T('SCRIPT_NAME') + " Installation complete\n"

+ T('INSTALL_M1') + "\n" + T('INSTALL_M2') + " \n-pixelgeek");

window.location.replace(rootPath + "build.php?id=39");//ToDo: reload

} else {

window.location.replace(rootPath + "a2b.php");//ToDo: reload

}



}



// Set default values if not defined yet

if (GM_getValue("Maximize_" + suffixGlobal, false) === false) {

GM_setValue("Maximize_" + suffixGlobal, 1);

}

if (GM_getValue("MaximizeSettings_" + suffixGlobal, false) === false) {

GM_setValue("MaximizeSettings_" + suffixGlobal, 0);

}

if (GM_getValue("StartIndex_" + suffixLocal, false) === false) {

GM_setValue("StartIndex_" + suffixLocal, 0);

}

if (GM_getValue("EndIndex_" + suffixLocal, false) === false) {

GM_setValue("EndIndex_" + suffixLocal, -1);

}

if (GM_getValue("Skipcounter_" + suffixGlobal, false) === false) {

GM_setValue("Skipcounter_" + suffixGlobal, 0);

}



//Settings
if (GM_getValue("RandomFarming_" + suffixGlobal, false) == false) {
GM_setValue("RandomFarming_" + suffixGlobal, 0);
}

if (GM_getValue("farmMarking_" + suffixGlobal, false) === false) {

GM_setValue("farmMarking_" + suffixGlobal, 0);

}

if (GM_getValue("VillageSkipping_" + suffixGlobal, false) === false) {

GM_setValue("VillageSkipping_" + suffixGlobal, 0);

}

if (GM_getValue("DelTList_" + suffixLocal, false) === false) {

GM_setValue("DelTList_" + suffixLocal, 1);

}

if (GM_getValue("ReadRep_" + suffixLocal, false) === false) {

GM_setValue("ReadRep_" + suffixLocal, 0);

}



// Setting Travian Version

if (GM_getValue("TravianVersion_" + suffixGlobal, false) === false) {

GM_setValue("TravianVersion_" + suffixGlobal, 0);

}



//insert village selector

rp_villageSelector();

//alert (url);

if (url.indexOf("build.php?") > -1 && (url.indexOf("gid=16") > -1 || url.indexOf("id=39") > -1)) {

if (isReallyRallyPoint()) {

rp_mainPage();

}

activeMain();

} else if (url.indexOf("a2b.php") > -1) {

activeMain();

} else if (url.indexOf("karte.php?") > -1 && url.indexOf("d=") > -1

&& url.indexOf("c=") > -1) { //if user profile page

foundNewFarm();

} else if (url.indexOf("berichte.php") > -1) {

// if no messages there, return to rally point

newreport = document.getElementsByTagName('html')[0].innerHTML.indexOf('id=\"n5\" class=\"i1\"')+document.getElementsByTagName('html')[0].innerHTML.indexOf('id=\"n5\" class=\"i3\"');

if ( newreport == -2 && GM_getValue("Active_" + suffixGlobal, -1) > -1)

{

window.open("/build.php?id=39", "_self");

return;

}

}



// farm marking in the map

if (url.indexOf('karte.php')>-1 && url.indexOf('karte.php?d=')==-1 && GM_getValue("farmMarking_" + suffixGlobal, 0)==1)

{

//get center village

var mapX = dom.get('x').textContent;

var mapY = dom.get('y').textContent;



FM_log(4,"CenterCoords="+mapX+","+mapY);



GM_setValue("MapCenter_"+suffixGlobal,mapX+","+mapY);



// look for arrow buttons

var ex = "//area[contains(@id,'ma_n')]";

tag = document.evaluate(ex,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);



FM_log(4,"adding eventListener");



for(var i=1; i<=tag.snapshotLength;i++)

{

var arrowButton = tag.snapshotItem(i-1);

// call function to check again after listener was activated

FM_log(4,"arrowId="+arrowButton.id);



arrowButton.addEventListener("click", function (e){

var evt = e || event;

var ele = evt.target || evt.srcElement;

setTimeout(function(){getXYtoFarms(ele.id);},500);



}, true); // so that it will check again when scrolling.



}

getXYtoFarms("")

}

}

function activeMain() {

FM_log(3,"activeMain() called");

if (GM_getValue("Active_" + suffixGlobal, -1) > -1) {

FM_log(4,"FM is active");

GM_addStyle("body { color:blue; }");

drawMessageBox();

var messageStr = "", acVillageFlag = true, titleStr = "";

var currentVillageId = getActiveVillageId();

if (isFarmerVillage(currentVillageId)) {

if (farmList == null || farmList.length == 0) {

farmList = GM_getValue("FarmList_" + suffixLocal, "").split(">:)");

}

var sIndex = getStartIndex();

FM_log(4,"activeMain sIndex="+sIndex);

var eIndex = getEndIndex();



//Teuton Mod Code

fque = GM_getValue('farmqueue'+ suffixLocal, '');

if (fque == null || fque.length == 0 || fque.indexOf('>:)') == -1)

{

//alert("neue liste");

fque = new Array();

x = 0;

if(eIndex == -1) //no eIndex set

{ // first fill from sIndex to end, then add from beginning to sIndex

for (var i = sIndex; i < farmList.length; i++)

{

fque[x] = farmList[i];

x++;

}

for (var i = 0; i < sIndex; i++)

{

fque[x] = farmList[i];

x++;

}

}else if(eIndex <= farmList.length){ //fill in between sIndex and eIndex

for (var i = sIndex; i <= eIndex; i++)

{

fque[x] = farmList[i];

x++;

}

}else if(eIndex <= sIndex){ //fill to the End and then from the beginning to eIndex

for (var i = sIndex; i < farmList.length; i++)

{

fque[x] = farmList[i];

x++;

}

for (var i = 0; i < eIndex; i++)

{

fque[x] = farmList[i];

x++;

}

}



//Removing all inactives.

for (var i=0; i < fque.length;i++)

{

temp = fque[i].split('|');

if(temp[7] != 'true')

{

fque.splice(i,1); //removes from array

}

}



if(random==1) {

fque.sort(randOrd);

fque.sort(randOrd);

fque.sort(randOrd);

fque.sort(randOrd);

}

//alert(fque.join('>:)'));

GM_setValue('farmqueue'+ suffixLocal, fque.join('>:)'));

}else{ //fque already existing

fque = fque.split('>:)');

}



// End Teuton Mod



if (eIndex >= farmList.length) {

GM_setValue("EndIndex_" + suffixLocal, -1);

}



var doneHere = GM_getValue("DoneHere_" + suffixLocal, 0);



if (fque == "" || fque.length == 0 || doneHere == 1) {

titleStr = T("NO_FARM");

messageStr = T('CHANGE_VILLAGE');

setTextMessage(titleStr, messageStr);

acVillageFlag = false;

} else {

if (sIndex < farmList.length) {

setAttackMessage();

} else {

titleStr = T("Error");

messageStr = T('CHANGE_VILLAGE');

setTextMessage(titleStr, messageStr);

changeVillage();

return;

}

}

} else {

titleStr = T('NOT_FARMER');

messageStr = T('CHANGE_VILLAGE');

acVillageFlag = false;

setTextMessage(titleStr, messageStr);

}

if (acVillageFlag) {

var url = document.URL;

url = url.substring(url.lastIndexOf("/") + 1);

if (url == "a2b.php") { //ready to fill out form

setTimeout(function(){sendtroops();},Random()/2);

} else { //changing to the send troops form

setTimeout("window.location.replace('" + rootPath + "a2b.php')",Random() / 2);

}

} else {

changeVillage();

}

}

}

function rp_mainPage() {

FM_log(3,"rp_mainPage() called");

if (GM_getValue("Active_" + suffixGlobal, -1) > -1) {

setTimeout("window.location.replace('" + rootPath + "a2b.php')",

Random());

} else {

insertEditFarmBox();

//now Add eventlistener for the save button

dom.get("FMsaveButton")

.addEventListener('click', saveEditedFarm, false);//add eventlistener



var container = dom.get("content");

var newP = dom.cn("p");

newP.id = "FMtitle";

newP.innerHTML += '<b>Farming Machine</b>';

container.appendChild(newP);

//insert a new table



rp_insertTable();

}

}

function rp_villageSelector() { //adds Village checkboxes

FM_log(3,"rp_villageSelector() called");



//get Travian Version

vT35 = GM_getValue("TravianVersion_" + suffixGlobal, false);



var vTableExp = "//a[contains(@href,'newdid')]/parent::td/parent::tr/parent::tbody";

var vTable = dom.find(vTableExp, XPFirst);

if (vTable != null && vTable.firstChild != null) {

for (var i = 0; i < vTable.childNodes.length; i++) {



var search = /\n?\((.*)\n?\s*\|\s*\n?(.*)\)\n?/;

var resultxy = search.exec(vTable.childNodes[i].textContent);



var X = resultxy[1];

var Y = resultxy[2];



var vid = xy2id(X, Y);

var newdid = getParamFromUrl(vTable.childNodes[i].getElementsByTagName("a")[0].getAttribute("href"),"newdid");

var checkButton = createInputButton("checkbox", i);

checkButton.id = "vcb_" + vid + "~" + newdid;

if (isFarmerVillage(vid)) {

checkButton.checked = true;

}

if (GM_getValue("Active_" + suffixGlobal, -1) > -1) {

checkButton.disabled = true;

} else {

checkButton.addEventListener("click", function(event) {

villageCheckBox(event)

}, false);

}



if(vT35==1) {

FM_log(4,"old code version");

var newCol = dom.cn("td");

newCol.appendChild(checkButton);

vTable.childNodes[i].appendChild(newCol);

} else if (vT35==2) {

FM_log(4,"new code version");

var vilExp = vTableExp+"/tr["+(i+1)+"]/td[contains(@class,'dot')]";

dom.xs(vilExp).textContent = "";

dom.xs(vilExp).appendChild(checkButton);

} else {

FM_log(0,"could not attach villagecheckbox - unknown Travian Version");

}

}

}

}

function sendtroops() {

FM_log(3,"sendtroops() called");

prioque = GM_getValue('priorityqueue'+ suffixLocal, '').split('>:)');

fque = GM_getValue('farmqueue'+ suffixLocal, '').split('>:)');



//get Travian Version

vT35 = GM_getValue("TravianVersion_" + suffixGlobal, false);



if (prioque.length >= 1 && prioque[0].length > 2)

{

FM_log(4,"priority attack");

var arr = prioque[0].toString().split("|");

attackList = prioque;

priorityAttack = true;

}else{

var arr = fque[0].toString().split("|");

attackList = fque;

priorityAttack = false;

}



xy = arr[0].split(",");

var sIndex = getSindexFromXY(xy[0],xy[1], suffixLocal);

var eIndex = getEndIndex();



var notFoundHtml = (dom.get("content")).innerHTML;

var formNode = dom.get("content").innerHTML, titleStr = "", messageStr = "";

var attackCount = GM_getValue("Active_" + suffixGlobal, 0);



if(vT35==1) {

var searchStr = "<div class=\"f10 e b\">";

var searchExp = "//div[@class='f10 e b']";

} else if (vT35==2) {

var searchStr = "<p class=\"error\">";

var searchExp = "//p[@class='error']";

}



if (notFoundHtml.indexOf(searchStr) > -1) { //village not found or player bannded

farmSetInactive(sIndex, suffixLocal); // got error on this farm so set it inactive



if (sIndex == eIndex) {

GM_setValue("DoneHere_" + suffixLocal, 1);

}



errText = dom.xs(searchExp).textContent;



FM_log(4,"errText="+errText);



titleStr = T("Error") + " :";

messageStr = errText + "<br>" + T('NEXT_FARM');



setTextMessage(titleStr, messageStr);



removefromque(priorityAttack); //Remove the farm from the attack queue.

setTimeout("window.location.replace('" + rootPath + "a2b.php')",Random());



} else if (sIndex < farmList.length) { // no error message from travian and inside farmList

if(arr[3]=="pixelgeek") {

farmSetInactive(sIndex, suffixLocal); // got error on this farm so set it inactive

if (sIndex == eIndex) {

GM_setValue("DoneHere_" + suffixLocal, 1);

}

titleStr = T("Error") + " :";

messageStr = "...<br>" + T('NEXT_FARM');

setTextMessage(titleStr, messageStr);



removefromque(priorityAttack); //Remove the farm from the attack queue.



setTimeout("window.location.replace('" + rootPath + "a2b.php')",Random());



} else {

if (formNode.indexOf("kid") > -1) { //confimation page

var e = document.getElementsByTagName('form');

e[0].submit(); //submit done

GM_setValue("Active_" + suffixGlobal, attackCount + 1);



if(GM_getValue("RandomFarming_" + suffixGlobal, 1)==0 && priorityAttack==false) {

//keep all villages in the list for making it the same as the inital version of FM

makelastinque(priorityAttack);

} else {

//If prioattack or random farming, this farm needs to be removed from the list

removefromque(priorityAttack);

}



titleStr = T('TROOPS_GONE') + ":";

messageStr = "[" + sIndex + "] " + E2C(arr[3]) + " : "

+ E2C(arr[5]) + "<b>(" + arr[0] + ")</b>";

setTextMessage(titleStr, messageStr);

if (sIndex == eIndex) {

GM_setValue("DoneHere_" + suffixLocal, 1);

}

} else { //filling out the form & sending troops

setAttackMessage();

var i;

if (arr[7] == "true") {

FM_log(4,"checking if there are enough troops");

var xy = arr[0].split(",");

var troopsCount = arr[1].split(",");

var random = GM_getValue("RandomFarming_" + suffixGlobal, 0);

var skipcounter = GM_getValue("Skipcounter_" + suffixGlobal, 0);

var availableTroops = new Array();

//find all the available troops

//alert(getNumber(formNode.substr(formNode.lastIndexOf("t1.value"))));

for (i = 1; i < 11; i++) {

var tt = "t" + i + ".value";

availableTroops.push(getNumber(formNode.substr(formNode

.lastIndexOf(tt))));

}

for (i = 0; i < troopsCount.length; i++) {

if (parseInt(availableTroops[i]) < parseInt(troopsCount[i])) {

FM_log(4,"not enough troops");

titleStr = T("Error") + " :";

tIndex = getSindexFromXY(arr[0].split(",")[0],arr[0].split(",")[1], suffixLocal)

messageStr = T('NOT_ENOUGH') + " :<br>["+tIndex+"] " + E2C(arr[3]) + " : " + E2C(arr[5])

+ "<b>(" + arr[0] + ")</b><br>"

+ "<img src='http://imgtrav.ifrance.com/img/u/"

+ (user_race + (i ? i : "")) + ".gif'>"

+ T("Available") + ": <b>" + availableTroops[i]

+ "</b> " + T("Needed") + ": <b>"

+ troopsCount[i] + "</b>";

setTextMessage(titleStr, messageStr);



//move village to the latest position and continue with next village

//only if skipvillage is activated

if(GM_getValue("VillageSkipping_" + suffixGlobal, 0)==1) {

FM_log(4,"moving village to the end of list");

makelastinque(priorityAttack);

}



//add one unsuccessfull count to the skipcounter

skipcounter++;



GM_setValue("Skipcounter_" + suffixGlobal, skipcounter);



FM_log(5,"Skipcounter="+skipcounter);

FM_log(5,"attackList Length="+attackList.length);



//If all farms were unsuccessfully, change village otherwise continue trying



if(maxSkipCount < 1) {

maxSkipCount = attackList.length;

}

if(maxSkipCount > attackList.length) {

maxSkipCount = attackList.length;

}



FM_log(5,"maxSkipcount="+maxSkipCount);



if (skipcounter >= maxSkipCount )

{

changeVillage();

}else{

setTimeout("window.location.replace('" + rootPath + "a2b.php')",Random());

if(GM_getValue("VillageSkipping_" + suffixGlobal, 0)==1) { //only display message, when it's really skipping to next farm

messageStr = T('NEXT_FARM');

setTextMessage("", messageStr);

}

setTimeout(function(){sendtroops}, 2000);

}



return;

}

}



var theForm = document.forms.namedItem("snd");

for (i = 1; i < 11; i++) {

theForm.elements.namedItem("t" + i).value = troopsCount[i-1];

}

dom.find("//input[@name='c' and @value='" + arr[8] + "']",

XPFirst, theForm).checked = true;

//theForm.elements.namedItem('c').value = 3;

theForm.elements.namedItem('x').value = xy[0];

theForm.elements.namedItem('y').value = xy[1];

//all set.. submit

//reset skipcounter, because a village was successfully attacked

FM_log(3,"Successfully send troops > skipcounter = 0");

GM_setValue("Skipcounter_" + suffixGlobal, 0);

setTimeout(function(){theForm.submit()}, Random());

} else { //farm not active

titleStr = T('FARM_INACTIVE') + ":";

messageStr = E2C(arr[3]) + " : " + E2C(arr[5]) + "<b>(" + arr[0] + ")</b>";

setTextMessage(titleStr, messageStr);



//alert("Farm inactiv: removing it");

removefromque(priorityAttack);

setTimeout("window.location.replace('" + rootPath + "a2b.php')",Random());



setTimeout(function(){sendtroops}, 2000);

return;

}

}

}

} else {

messageStr = T('CHANGE_VILLAGE');

setTextMessage(titleStr, messageStr);

changeVillage();

}

}

function markFarm(x, y) {

FM_log(1,"markFarm("+x+","+y+") called");

//farm coords

var x = parseInt(x);

var y = parseInt(y);



var id = (x + 401) + ((400 - y) * 801);



//get map center

var centerCoords = GM_getValue("MapCenter_"+suffixGlobal,"");

if(centerCoords!="") {

centerCoords = centerCoords.split(',');

FM_log(4,"stored coords:"+centerCoords[0]+","+centerCoords[1]);

} else {

FM_log(4,"no center coords stored");

return;

}



var centerX = parseInt(centerCoords[0]);

var centerY = parseInt(centerCoords[1]);



//get map size

//var ex = "//area[contains(@href,'d=')][contains(@id,'a_')]";

var ex = "//div[contains(@id,'i_')]";

var tag = dom.xo(ex);



mapSize = Math.floor(Math.sqrt(tag.snapshotLength));

FM_log(2,"mapSize="+mapSize);



mapCenterX = (mapSize-1)/2;

mapCenterY = (mapSize-1)/2;

FM_log(4,"mapCenterXY="+mapCenterX+","+mapCenterY);

mapOffsetX = mapCenterX - 3;

mapOffsetY = mapCenterY - 3;





mapOffsetX = 0;

mapOffsetY = 0;



//create coordinates for each cell and compare

for(var i=0; i<mapSize; i++) {

//calculate X-Offset to Center

offX = i - mapCenterX;

FM_log(4,"offX="+offX);

//calculate tCoorX

tCoorX = centerX + offX + mapOffsetX;

for(var j=0; j<mapSize; j++) {

//calculate Y-Offset

offY = j - mapCenterY;

FM_log(4,"offY="+offY);

//calculate tCoorY

tCoorY = centerY + offY + mapOffsetY;

FM_log(4,"tCoords="+tCoorX+"/"+tCoorY);

//compare to farm coords

//FM_log(2,"compare X="+tCoorX+"/"+x);

//FM_log(2,"compare Y="+tCoorY+"/"+y);

if(tCoorX==x && tCoorY==y) {

var exArea = "//div[@id='i_"+i+"_"+j+"']";

FM_log(2,"exArea="+exArea);

tag2 = dom.xs(exArea);

//tag2.innerHTML = "<div class=\"isfarm\">&nbsp;</div>";

tag2.setAttribute("class","isfarm");

//return;

}



}

}

}

function farmSetInactive(index, suffix) {

FM_log(3,"farmSetInactive("+index+","+suffix+") called");

var fList = GM_getValue("FarmList_" + suffix, "").split(">:)");

var newfList = "";

var i, j;

if (index < fList.length) {

for (i = 0; i < fList.length; i++) {

if (i)

newfList += ">:)";

if (i == index) {

var arr = fList[i].split("|");

arr[7] = "false";

for (j = 0; j < arr.length; j++) {

if (j)

newfList += "|";

newfList += arr[j];

}

} else {

newfList += fList[i];

}

}

GM_setValue("FarmList_" + suffixLocal, newfList);

}

}

function changeVillage() {

try{

FM_log(3,"changeVillage() called");

GM_setValue("Skipcounter_" + suffixGlobal, 0);

//clear farmque, because all the other farms are already tried...

if(maxSkipCount==-1 && GM_getValue("RandomFarming_" + suffixGlobal, -1)==1) {

clearque();

}

var vList = GM_getValue("FarmerVillages_" + suffixGlobal);

var newList = new Array();

var i, pause, messageStr = "";

if (vList != null && vList != "") {

vList = vList.toString().split(",");

if (vList.length > 0) {

var activeVId = getActiveVillageId();

for (i = 0; i < vList.length; i++) {

var ids = vList[i].split('~')[0];

if (GM_getValue("DoneHere_" + suffixGlobal + "_" + ids, 0) == 0

&& ids != activeVId) {

newList.push(vList[i]); //only taking villages which is not current village and also not done

}

}

}

}



random = GM_getValue("RandomFarming_" + suffixGlobal, 0);



if (newList.length == 0) { //Village Change is not possible, Engine is pause for X sec

//if there are other villages, reactivate these, otherwise stay in this village

if (vList == "" || vList == null) {

//no farmer village! so set the current village a farmer, important for single village account

GM_setValue("FarmerVillages_" + suffixGlobal, getActiveVillageId()

+ "~-1"); //no newdid

vList = GM_getValue("FarmerVillages_" + suffixGlobal, "");

}

FM_log(4,"Reseting all doneHeres");

//reset DoneHere for all selected village

var arr = vList.toString().split(",");

FM_log(4,"number of villages="+arr.length);

for (var i = 0; i < arr.length; i++) {

arr[i] = arr[i].split("~");

FM_log(4,"villageId="+arr[i][0]);

GM_setValue("DoneHere_" + suffixGlobal + "_" + arr[i][0], 0);

}



pause = Random();

messageStr = T('NO_VILLAGE') + " " + T('WAITING') + " <b>~"

+ Math.floor(pause / 1000) + "</b> " + T('SEC') + " "

setTextMessage("", messageStr);

setTimeout("window.location.replace('" + rootPath + "a2b.php')", pause);

} else {

//In case of random iteration we come up to this point because sIndex was bigger then farmList length

//before we leave this village we have to ensure that when we came back to this village we got the sIndex is in between farmlist length

var sIndex = 0;

if (random == 1 && farmList != null && farmList.length > 0) {

sIndex = Random(0, farmList.length - 1);

GM_setValue("StartIndex_" + suffixLocal, sIndex); //by force set it inside

}

//select a village randomly from the active villages

i = Random(0, newList.length - 1);

newList[i] = newList[i].split('~');

var coord = id2xy(newList[i][0]);

pause = Random();

messageStr = T('SWITCH_V') + ": (" + coord.x + "|" + coord.y + "), "

+ T("after") + " " + Math.floor(pause / 1000) + " " + T("sec");

setTextMessage("", messageStr);

setTimeout("window.location.replace('" + rootPath + "a2b.php?newdid="+ newList[i][1] + "')", pause);

}

} catch(error) {

FM_log(0,"changeVillage(): change not successfull");

}

}

function foundNewFarm() {

FM_log(3,"foundNewFarm() called");

insertEditFarmBox();

var tribe = getFPlayerTribe().toUpperCase();
var tribeG=T('GAUL').toUpperCase();

if (tribe ==tribeG) {

dom.get("radio3").checked = true; //default attack for gauls

} else {

dom.get("radio4").checked = true; //default raid for other

}

dom.get('FMsaveButton').addEventListener('click', addNewFarm, true);

var tbody = dom.xs("//a[contains(@href,'karte.php')]/parent::td/parent::tr/parent::tbody");

if (tbody == null || tbody == "")

return;



/*

Trying to mark already added villages

*/

// getting coordinates

testCoord = getFVillageCoords();

// checking if already existing

if(isFarm(testCoord.split(',')[0],testCoord.split(',')[1])) {

var addOption = createLinkButton('<font style="color: #cd0000;">'+'\u00BB' + " " + T("Add_To") + " "

+ T('SCRIPT_NAME') + "<\/font>", T("Add_As"), showPopupFarmEditBox);

} else {

var addOption = createLinkButton('\u00BB' + " " + T("Add_To") + " "

+ T('SCRIPT_NAME'), T("Add_As"), showPopupFarmEditBox);

}



/* original Code

var addOption = createLinkButton('\u00BB' + " " + T("Add_To") + " "

+ T('SCRIPT_NAME'), T("Add_As"), showPopupFarmEditBox);

*/



var row = dom.cn('tr');

var cell = dom.cn('td');

cell.appendChild(addOption);

row.appendChild(cell);

tbody.appendChild(row);



}

function addNewFarm() {

FM_log(3,"addNewFarm() called");

var formDiv = dom.get("popupFarmEditBox");

var inputTag = formDiv.getElementsByTagName("input");

var troopConfig = "", attackType, activeBool, i;


for (i = 0; i < inputTag.length; i++) {

if (i < 10) {

if (i)

troopConfig += ",";

if (inputTag[i].value == "" || inputTag[i].value == null)

inputTag[i].value = 0;

troopConfig += parseInt(inputTag[i].value);

} else {

if (inputTag[i].getAttribute("type") == "radio"

&& inputTag[i].checked) {

attackType = inputTag[i].value;

} else if (inputTag[i].getAttribute("type") == "checkbox") {

activeBool = inputTag[i].checked;

}

}

}

//alert(troopConfig+"|"+attackType+"|"+activeBool);



var coords = getFVillageCoords();

var tribe = getFPlayerTribe();

var fPlayerName = getFPlayerName();

var fPlayerId = getFPlayerId();

FM_log(3,"getFVillageName");

var fVillageName = getFVillageName();

//alert(fVillageName);

FM_log(3,"getCvalue");

var cValue = getCvalue();

FM_log(3,"window confirm");

if (window.confirm(T('ADD_FARM') + ": " + fVillageName + " (" + coords

+ ")" + "\n" + T('TROOP_CONFIG') + ": \"" + troopConfig + "\"\n"

+ T('CONFIRM') + "?")) {

addList(coords + "|" + troopConfig + "|" + C2E(tribe) + "|"

+ C2E(fPlayerName) + "|" + C2E(fPlayerId) + "|"

+ C2E(fVillageName) + "|" + cValue + "|" + activeBool + "|"

+ attackType);

//alert("New Farm Added: "+fVillageName+"("+coords+") :)");

hidePopupFarmEditBox();

}

FM_log(3,"New Farm Add done");

}

function addList(dataStr) {

FM_log(3,"addList() called");

var oldList = GM_getValue("FarmList_" + suffixLocal, "") + " ";

oldList = trim(oldList);

if (oldList != "") {

oldList += ">:)";//evil face

}

oldList += dataStr; //now it is actually new list ;)

GM_setValue("FarmList_" + suffixLocal, oldList);



}

function randOrd(){ //randomize for farmque

return (Math.round(Math.random())-0.5);

}

function removefromque(prioattack) { //remove farm from farmque or prioque

FM_log(3,"removefromque() called");

if(prioattack)

{

prioque.shift();

GM_setValue('priorityqueue'+ suffixLocal, prioque.join('>:)'));

}else{

fque.shift();

GM_setValue('farmqueue'+ suffixLocal, fque.join('>:)'));

}



}

function makelastinque(prioattack) {

FM_log(3,"makelastinque() called");

if(prioattack)

{

if (prioque.length > 1)

{

info = prioque.shift();

prioque.push(info);

//alert("make last: " + prioque.join('>:)'));

GM_setValue('priorityqueue'+ suffixLocal, prioque.join('>:)'));

}else{

//only one in the list so there is no need to change position

}

}else{

if (fque.length > 1)

{

info = fque.shift();

fque.push(info);

//alert(fque.join('>:)'));

GM_setValue('farmqueue'+ suffixLocal, fque.join('>:)'));

}else{

//only one in the list so there is no need to change position

}

}

}

function addtoprio(info, vilId) { //add farm to prioque

FM_log(0,"addtoprio("+info+","+vilId+" called");

suffixGlobal = server + '_' + getPlayerId();

suffixLocal = suffixGlobal + '_' + vilId;

prioque = GM_getValue('priorityqueue'+ suffixLocal, '') + " ";

prioque = trim(prioque);

if (prioque != "") {

prioque += ">:)";

}

prioque += info;

//alert(prioque);

GM_setValue('priorityqueue'+ suffixLocal, prioque);

}

function clearque() { //delete farmque / prioque

FM_log(3,"clearque() called");

var vListID = getAllVillageId().toString();

FM_log(4,"vListID="+vListID);

var temptemp = vListID.split(",");



//alert(temptemp.length);



for(var i=0; i<temptemp.length;i++)

{

//alert(temptemp[i]);

GM_setValue('farmqueue'+ suffixGlobal + '_' + temptemp[i], '');

GM_setValue('priorityqueue'+ suffixGlobal + '_' + temptemp[i], '');

}

FM_log(4,"Farmqueue cleared");

}

function checkreports() { //analyse new reports

FM_log(3,"checkreports() called");



FM_log(3,"Setting language, images & style");

setLanguage();

loadImage();

loadStyle();

drawMessageBox();



setTextMessage("Checking reports", "Opening report");



url = document.URL;

pulled = document.createElement('div');



if ( (url.indexOf("berichte.php") != -1 && url.indexOf("berichte.php?") == -1) || url.indexOf("berichte.php?s=") != -1) {

ex = "//td/a[contains(@href,'berichte.php?')]/parent::*";

ex2 = "//td/a[contains(@href,'berichte.php?id=')]";

tag = document.evaluate(ex,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);

//alert(tag);

totReports = find(ex2,XPList);

for(i=totReports.snapshotLength-1;i>=0;i--){

pulled.innerHTML = tag.snapshotItem(i).innerHTML;

attackreporturl = pulled.getElementsByTagName('a')[0].href;

endofA = tag.snapshotItem(i).innerHTML.indexOf("</a>");

testIndex = tag.snapshotItem(i).innerHTML.indexOf("(",endofA); // check if line is a new report

if (testIndex != -1 && endofA < testIndex) {
//save url

GM_setValue("lastreportpage_"+suffixGlobal, url);

FM_log(4,"attrepurl="+attackreporturl);

//window.open(attackreporturl, "_self");

setTimeout("window.location.replace('" + attackreporturl + "')",1000);

break;

}

}



if (i==-1){ // all reports from this page done, switching to next page

newreport = document.getElementsByTagName('html')[0].innerHTML.indexOf('id=\"n5\" class=\"i1\"') + document.getElementsByTagName('html')[0].innerHTML.indexOf('id=\"n5\" class=\"i3\"');

if ( newreport == -2 || url.indexOf("berichte.php?s=1000") != -1) {

//no more reports to read, going back to attacks

setTextMessage("Checking reports", "No more reports to read<br/>Going back to rally point")
//resetting lastreportpage

GM_setValue("lastreportpage_"+suffixGlobal, "berichte.php");

setTimeout("window.location.replace('" + rootPath + "a2b.php')",1000);

} else {

//going to next page

next = find("//a[contains(@href,'berichte.php?s=')]",XPList);

if (next.snapshotLength > 0)

{

nextRep = next.snapshotItem(next.snapshotLength-1).href.split("/");

nextRepLink = nextRep[nextRep.length-1];

FM_log(4,"nextRepLink="+nextRepLink);

GM_setValue("lastreportpage_"+suffixGlobal,nextRepLink);

//window.open(next.snapshotItem(next.snapshotLength-1).href, "_self");

setTimeout("window.location.replace('" + next.snapshotItem(next.snapshotLength-1).href + "')",1000);
}

}

}



}



//Is this any report page?

if ((url.indexOf("berichte.php?id=") != -1 || url.indexOf("berichte.php?newdid=") != -1) ) {

FM_log(4,"inside report page");

//alert("analysing report");

test = find("//a[contains(@href,'uid=')]",XPList);

var uids = find("//div[@id='content']//a[contains(@href,'karte.php?d=')]",XPList);



if(test.snapshotLength == 3 && uids.snapshotLength == 2 ){

setTextMessage("Checking reports", "Attack report");

FM_log(4,"report is attack report");

troopsinattack = document.getElementsByTagName('tr')[6].innerHTML.match(/\d+/g).join();

casualties = document.getElementsByTagName('tr')[7].innerHTML.match(/\d+/g).join();

attackedId = uids.snapshotItem(1).href.split('d=')[1].split('&c')[0];

attackerVillageId = uids.snapshotItem(0).href.split('d=')[1].split('&c')[0];

attackerPlayerId = test.snapshotItem(1).href.split('uid=')[1];

playerId = getPlayerId();

thisCValue = uids.snapshotItem(1).href.split('d=')[1].split('&c=')[1];

defenderPlayerId = test.snapshotItem(2).href.split('uid=')[1];

//alert(defenderPlayerId);

//alert(thisCValue);



coords = id2xy(attackedId);

FM_log(4,"coords="+coords.x+"/"+coords.y);



FM_log(2,"going to check attacktable");

temp = attacktable();

efficiency = temp[0];

gain = temp[1];



//adding up casualties

var casTemp = casualties.split(',');

var casNr=0;

for(i=0;i<casTemp.length;i++) {

casNr+casTemp[i];

}



setTextMessage("Checking reports", "Attack report<br/><br/>Efficiency: "+efficiency+"%<br/>Gain: "+gain+"<br/>Casualties: "+casNr);



FM_log(0,"efficiency="+efficiency);



switch (temp[2]){

case 1:tribe=T('ROMAN');break;

case 2:tribe=T('TEUTON');break;

case 3:tribe=T('GAUL');break;

default:tribe=T('ROMAN');break;

}

if (temp[2]==3) {

attType = 3;

} else {

attType = 4;

}



//alert("troopsinattack:"+troopsinattack);

//alert("casualties:"+casualties);

//alert("gain:"+gain);

//alert("efficiency:"+efficiency);



if (troopsinattack.split(',').join() == casualties || gain < 0)

{

//alert("all units lost - deactivating village");

suffix = suffixGlobal + '_' + attackerVillageId;

index = getSindexFromXY(coords.x,coords.y, suffix);

if (index != -2)

{

farmSetInactive(index, suffix);

//alert("farm set inactive");

}

}



FM_log(4,"c="+casualties+"/eff="+efficiency+"/playerId="+playerId+"/attPId="+attackerPlayerId);

if(casualties == "0,0,0,0,0,0,0,0,0,0" && efficiency == 100 && playerId == attackerPlayerId )

{

FM_log(2,"adding this farm to prioque");

villageName = uids.snapshotItem(1).textContent;

FM_log(4,"villageName="+villageName);

playerName = test.snapshotItem(2).textContent + '(Priority)';

FM_log(4,"playerName="+playerName);

attackInfo = coords.x +','+ coords.y +'|'+ troopsinattack +'|'+tribe+'|'+playerName+'|'+defenderPlayerId+'|'+villageName+'|'+ thisCValue +'|true|'+attType;

FM_log(2,"attackInfo="+attackInfo);

addtoprio(attackInfo, attackerVillageId);

}

} else {

setTextMessage("Checking reports", "No Attack report");

}

//going back to last report page

lastRepPage = GM_getValue("lastreportpage_" + suffixGlobal, "berichte.php");

FM_log(4,"RepPage="+lastRepPage);

//window.location.replace(lastRepPage);

setTimeout("window.location.replace('" + lastRepPage + "')",1000);

}



}

function attacktable(){ //analyse report table

try {

FM_log(1,"attacktable() called");

var ats=new Array(0,0,0,0,0,0,0,0,0,0);

var XPFirst=XPathResult.FIRST_ORDERED_NODE_TYPE;

var XPList=XPathResult.ORDERED_NODE_SNAPSHOT_TYPE;

exTab = "//div[@id='content']//a[contains(@href,'spieler.php?')]/parent::*/parent::tr/parent::thead/parent::table/tbody";

tab=find(exTab,XPList);

//alert(tab.snapshotLength);

table=tab.snapshotItem(0).getElementsByTagName("td"); //Item(0)=attacker, Item(1)=bounty, Item(2,3,4)=defender

if(tab.snapshotLength>1) {

//alert("check details");

//real defender is always the last table

tabledefender=tab.snapshotItem(tab.snapshotLength-1).getElementsByTagName("td");



//alert(tabledefender);

if(tabledefender[1].innerHTML.indexOf("unit u1")>0) tribedefender=1;

if(tabledefender[1].innerHTML.indexOf("unit u11")>0) tribedefender=2;

if(tabledefender[1].innerHTML.indexOf("unit u21")>0) tribedefender=3;



} else {

//define tribe for defender

tribedefender = 0;

}

var statushero=0;

var statustrap=0;

var troops=0; //1-romans 2-teutons 3-gauls

var lostres=new Array(0,0,0,0);

var atstemp=new Array(0,0,0,0,0,0,0,0,0,0);



tableattacker=tab.snapshotItem(0).getElementsByTagName("td");



if(tableattacker[1].innerHTML.indexOf("unit u1")>0) troops=1;

if(tableattacker[1].innerHTML.indexOf("unit u11")>0) troops=2;

if(tableattacker[1].innerHTML.indexOf("unit u21")>0) troops=3;

//alert(troops);

switch (troops){ //define need resources for troops

case 1:tm=romans;break;

case 2:tm=teutons;break;

case 3:tm=gauls;break;

default:tm=null;break;

}



var rescell=dom.find("//img[@class='r1']/parent::div",XPFirst);

if (rescell != null){

if(tm!=null){

if(tab.snapshotItem(0).getElementsByTagName("tr")[0].innerHTML.indexOf("unit uhero")>0) {statushero=1;ats[5]=1;}



//alert(statushero);



var tda=11+statushero; //start for sent units

var tdl=20+statushero*2; //start for casualities

var tdt=0;



for(var i=0;i<=(9+statushero);i++){

atstemp[0]=atstemp[0]+table[tda+i].textContent*tm[i][0];

lostres[0]=lostres[0]+table[tdl+i].textContent*tm[i][3];

lostres[1]=lostres[1]+table[tdl+i].textContent*tm[i][4];

lostres[2]=lostres[2]+table[tdl+i].textContent*tm[i][5];

lostres[3]=lostres[3]+table[tdl+i].textContent*tm[i][6];

atstemp[4]=atstemp[4]+table[tda+i].textContent*tm[i][7];

atstemp[6]=atstemp[6]+table[tdl+i].textContent*tm[i][7];

atstemp[8]=atstemp[8]+table[tda+i].textContent*tm[11][i]*tm[i][0];

atstemp[9]=atstemp[9]+table[tda+i].textContent*tm[12][i]*tm[i][0];

if(tdt!=0){

atstemp[7]=atstemp[7]+table[tdt+i].textContent*tm[i][7];

atstemp[3]=atstemp[3]+(table[tda+i].textContent-table[tdl+i].textContent-table[tdt+i].textContent)*tm[i][9];

}else{

atstemp[3]=atstemp[3]+(table[tda+i].textContent-table[tdl+i].textContent)*tm[i][9];

}

}

atstemp[1]=lostres[0]+lostres[1]+lostres[2]+lostres[3];



FM_log(2,"resText="+rescell.textContent);

res=rescell.textContent.split(" | ");

//alert(parseInt(res[0])+"|"+parseInt(res[1])+"|"+parseInt(res[2])+"|"+parseInt(res[3]));

atstemp[2]=parseInt(res[0])+parseInt(res[1])+parseInt(res[2])+parseInt(res[3]);

var efficiency = Math.round(atstemp[2] / atstemp[3] * 100);

gain = atstemp[2] - atstemp[1];

//alert(atstemp[1]);

FM_log(2,efficiency+"/"+gain+"/"+tribedefender);

returnstring = new Array();

returnstring[0] = efficiency;

returnstring[1] = gain;

returnstring[2] = tribedefender;

return (returnstring);

};

}

return 0;

} catch(error) {

FM_log(0,"attacktable(): Error in reading the attack-table");

}

}

function getSindexFromXY(x,y, suffix) {

FM_log(3,"getSindexFromXY() called");

farmList = GM_getValue("FarmList_" + suffix, "");

if (farmList != "" && farmList != null) {

farmList = farmList.split(">:)");

//alert(farmList.length);

for (i=0; i<farmList.length;i++)

{

xy = farmList[i].split("|")[0].split(',');

//alert(xy);

if (x == xy[0] && y == xy[1])

{

return i;

}

}

}

return -2;

}



//FM list functions

function farmRemove(itemToRemove) { //Remove a farm from the list

FM_log(3,"farmRemove("+itemToRemove+") called");

var sIndex = getStartIndex();

var eIndex = getEndIndex();



FM_log(4,"sufLoc:"+suffixLocal);

var fullList = GM_getValue("FarmList_" + suffixLocal);

var farms = new Array;

farms = fullList.split(">:)");



var newFarmList = '', flag = false, i;

if (itemToRemove < farms.length) {

var arr = farms[itemToRemove].split("|");

if (confirm(T('REMOVING') + ": " + E2C(arr[5]) + "(" + arr[0] + ")")) {

for (i = 0; i < farms.length; i++) {

if (i != itemToRemove) {

if (flag) {

newFarmList += ">:)";

}

newFarmList += farms[i];

flag = true;

}

}

//alert(newFarmList);

if (itemToRemove <= sIndex) {

GM_setValue("StartIndex_" + suffixLocal, (sIndex - 1) >= 0

? (sIndex - 1)

: 0);

}

if (itemToRemove <= eIndex) {

GM_setValue("EndIndex_" + suffixLocal, (eIndex - 1) >= 0

? (eIndex - 1)

: 0);

}

GM_setValue("FarmList_" + suffixLocal, newFarmList);



//reload the farm table

clearque();

reloadFarmTable();

}

} else {

alert('???Not a farm for remove');

}

}

function startEngine() {

farmList = new Array();

var vList = GM_getValue("FarmerVillages_" + suffixGlobal, "");

if (vList == "" || vList == null) {

//no farmer village! so set the current village a farmer, important for single village account

GM_setValue("FarmerVillages_" + suffixGlobal, getActiveVillageId()

+ "~-1"); //no newdid

vList = GM_getValue("FarmerVillages_" + suffixGlobal, "");

}

//reset DoneHere for all selected village

var arr = vList.toString().split(","), i;

for (i = 0; i < arr.length; i++) {

arr[i] = arr[i].split("~");

GM_setValue("DoneHere_" + suffixGlobal + "_" + arr[i][0], 0);

}

GM_setValue("Active_" + suffixGlobal, 0);

GM_addStyle("body { color:blue; }");

window.location.replace(rootPath + "a2b.php");

}

function stopEngine() {
// set active variable to -1

GM_setValue("Active_" + suffixGlobal, -1);
// reset skipcounter

GM_setValue("Skipcounter_" + suffixGlobal, 0);
// reset all active farming villages

var vList = GM_getValue("FarmerVillages_" + suffixGlobal, "").split(",");

if (vList.length == 1 && vList[0].split("~")[1] == -1) { //for single village account

GM_setValue("FarmerVillages_" + suffixGlobal, "");

}

// Reset farmques if random is deactivated so it will start where it should start

if(GM_getValue("DelTList_" + suffixGlobal, 0)==1) {

//alert("clearing que");

clearque();

}

GM_addStyle("body { color:black; }");


FM_log(3,"Engine stopped, setting skipcounter=0");

// going back to rallypoint

setTimeout("window.location.replace('build.php?id=39')",1000);

//window.location.replace("build.php?id=39");

}

function updateFM(SCRIPT) { //Update script (by Richard Gibson - modified version)

var loadImg = dom.cn("img");

loadImg.src = image['LOADING'];

var updater = dom.get("updater");

updater.appendChild(loadImg);

try {

/*if (!GM_getValue)

return;*/

GM_xmlhttpRequest({

method : 'GET',

url : SCRIPT.url + '?source', // don't increase the 'installed' count just for checking

onload : function(result) {

updater.removeChild(loadImg);

if (result.status != 200) {

alert(T("UPDATE_M1"));

return;

}

if (!result.responseText.match(/@version\s+([\d.]+)/)) {

alert(T('UPDATE_UNKNOWN') + " v" + RegExp.$1);

return;

}



var onlineVersion = RegExp.$1;

var currentVersion = SCRIPT.version;

if (onlineVersion == SCRIPT.version) {

alert(T('UPDATE_LAST') + " " + T("Script_name") + ' (v'

+ onlineVersion + ')');

return;

} else {

currentVersion = currentVersion.split(".");

var onlineArray = onlineVersion.split(".");

if (currentVersion[0] <= onlineArray[0]

|| currentVersion[1] <= onlineArray[1]

|| currentVersion[2] <= onlineArray[2]) {

var messageStr = "";

if (onlineArray[2] != 0) {

messageStr = T('UPDATE_BETA');

} else {

messageStr = T('UPDATE_NEW') + " v" + onlineVersion;

}

if (confirm(messageStr + "\n\n" + T('CONFIRM') + ":"

+ T('UPDATE_NOW') + "?")) {

window.location.href = SCRIPT.url;

GM_setValue("Tribe_" + suffixGlobal, -1);

}

}

}

}

});

} catch (ex) {

alert("AJAX request Exception! Try later.");

}

}

function reloadFarmTable() {

FM_log(3,"reloadFarmTable() called");

var oldTable;

if ((oldTable = dom.get("farmMachineTable")) != null

|| oldTable != "undefined") {

//then remove it

dom.get("content").removeChild(dom.get("farmMachineTable"));

}

rp_insertTable();

FM_log(4,"Farm Table Reload Complete");

}

function distanceSort(a, b) {

var d1 = a.distance;

var d2 = b.distance;

return (d1 < d2) ? -1 : ((d1 > d2) ? 1 : 0); // -1 a,b | 1 b,a | 0 nothing

}

function sortFarms() {

FM_log(1,"sortFarms() called");

farmList = GM_getValue("FarmList_" + suffixLocal, "");

if (farmList == "" || farmList == null)

return;

farmList = farmList.split(">:)");

if (farmList.length == 1) //just one farm

return;

var arr = new Array(), i;

var xy = getActiveVillageXY(), xyt;

for (i = 0; i < farmList.length; i++) {

xyt = farmList[i].split("|")[0].split(",");

arr[i] = {

FarmInfo : farmList[i],

distance : coordDistXYtoXY(xy[0], xy[1], xyt[0], xyt[1])

};

//alert(xy[0]+" "+xy[1]+" "+xyt[0]+" "+xyt[1]);

}

arr.sort(distanceSort); //sorting

var newList = "";

for (i = 0; i < arr.length; i++) {

if (i)

newList += ">:)";

newList += arr[i].FarmInfo;

}

GM_setValue("FarmList_" + suffixLocal, newList);

reloadFarmTable();

}

function optimizeFarmsByDistance() {

FM_log(3,"optimizeFarmsByDistance() called");

if (confirm(T('OPTIMIZE_SM') + "\n" + T('CONFIRM') + "?")) {

var selectedvList = GM_getValue("FarmerVillages_" + suffixGlobal, ""); //if empty, just one village

var i, j, minDis, k;

if (selectedvList != "" && selectedvList != null) {

var vList = selectedvList.split(",");



if (vList.length < 2) return;



for (i = 0; i < vList.length; i++) {

vList[i] = vList[i].split('~')[0];



}



var allFarms = "", vCoords = new Array(), newFarmList = new Array();



for (i = 0; i < vList.length; i++) {

var fList = GM_getValue("FarmList_" + suffixGlobal + "_" + vList[i], "");



if (fList != "" && fList != null) {

if (allFarms != "") allFarms += ">:)";

allFarms += fList;

}

newFarmList[i] = "";

vCoords[i] = id2xy(vList[i]);

}

if (allFarms != "") {

allFarms = allFarms.split(">:)");

for (i = 0; i < allFarms.length; i++) {

minDis = 5000000.0;

k = -1;

var xy = allFarms[i].split("|")[0].split(",");

for (j = 0; j < vList.length; j++) {

var dis = coordDistXYtoXY(vCoords[j].x, vCoords[j].y,

xy[0], xy[1]);

if (dis < minDis) {

minDis = dis;

k = j;

}

}

if (k != -1) {

if (newFarmList[k] != "") {

newFarmList[k] += ">:)";

}

newFarmList[k] += allFarms[i];

}

}

for (i = 0; i < vList.length; i++) {

GM_setValue("FarmList_" + suffixGlobal + "_" + vList[i],

newFarmList[i]);

}

}

}

reloadFarmTable();

alert(T('OPTIMIZE_DONE'));

}

}

function importExport() {

FM_log(3,"importExport() called");

var farmData = GM_getValue("FarmList_" + suffixLocal, ""), val;

FM_log(4,"suffixLocal="+suffixLocal);

val = prompt(T('LOCAL_IM_EX_PROMPT'), farmData);

if (val != null) {

val = trim(val);

GM_setValue("FarmList_" + suffixLocal, val);

reloadFarmTable();

}

}

function globalImportExport() {

var allVillageId = getAllVillageId();

allVillageId = allVillageId.split(",");

var allData = "", i, j, farmData;

for (i = 0; i < allVillageId.length; i++) {

farmData = GM_getValue("FarmList_" + suffixGlobal + "_"

+ allVillageId[i], "");

farmData = trim(farmData);

if (allData != "")

allData += "//";

allData += allVillageId[i] + ":>" + farmData;

}

var val = prompt(T('GLOBAL_IM_EX_PROMPT'), allData);

if (val != null) {

val = trim(val).split("//");

for (i = 0; i < val.length; i++) {

farmData = val[i].split(":>");

farmData[0] = trim(farmData[0]);

if (farmData.length == 1)

farmData.push("");

for (j = 0; j < allVillageId.length; j++) {

if (farmData[0] == allVillageId[j]) {

break;

}

}

if (j < allVillageId.length) {

//alert(allVillageId[j]+" Data:"+farmData[1]);

GM_setValue("FarmList_" + suffixGlobal + "_" + allVillageId[j],

farmData[1]);

}

}

reloadFarmTable();

}

}

function editFarm(itemToEdit, event) {

FM_log(3,"editFarm("+itemToEdit+",event) called");

farmList = GM_getValue("FarmList_" + suffixLocal, "");

var i;

hidePopupFarmEditBox();

if (farmList != "" && farmList != null) {

farmList = farmList.split(">:)");

if (itemToEdit < farmList.length) {

//initialize the form with old values;

var farmEditBox = dom.get("popupFarmEditBox");

var arr = farmList[itemToEdit].split("|");

var troopsConfig = arr[1].split(",");

var inputTag = farmEditBox.getElementsByTagName("input");

for (i = 0; i < inputTag.length; i++) {

if (i < 10) {

inputTag[i].value = troopsConfig[i];

} else {

if (inputTag[i].getAttribute("type") == "radio") {

if (parseInt(inputTag[i].value) == parseInt(arr[8])) {

inputTag[i].checked = true;

} else {

inputTag[i].checked = false;

}

}

if (inputTag[i].getAttribute("type") == "checkbox") {

if (arr[7] == "true") {

inputTag[i].checked = true;

} else {

inputTag[i].checked = false;

}

}

}

}

FM_log(3,"editFarm: Form Initialization complete " + farmList.length);

//get the globalInt so if the save button get clicked saveEditedFarm function will use it

globalInt = itemToEdit;

//changing position

farmEditBox.style.top = event.pageY + "px";

farmEditBox.style.left = (event.pageX + 20) + "px";

showPopupFarmEditBox(); //Now show the box

}

}

}

function saveEditedFarm() {

FM_log(3,"saveEditedFarm() called");

var itemToEdit = globalInt;

FM_log(4,"itemToEdit="+itemToEdit);

var newList = "", i, j;

hidePopupFarmEditBox();

if (farmList.length == 0 || farmList == null || itemToEdit < 0 || itemToEdit >= farmList.length) {

FM_log(3,"saveEditedFarm: illegal call of this function");

return;

}

FM_log(4,"SaveEditedFarm: Going to save the edited farm " + farmList.length);

for (i = 0; i < farmList.length; i++) {

if (newList != "") {

newList += ">:)";

}

if (i == itemToEdit) {

var formDiv = dom.get("popupFarmEditBox");

var inputTag = formDiv.getElementsByTagName("input");

var troopConfig = "", attackType, activeBool;

for (j = 0; j < inputTag.length; j++) {

if (j < 10) {

if (j)

troopConfig += ",";



if (inputTag[j].value == "" || inputTag[j].value == "NaN" || inputTag[j].value == null)

inputTag[j].value = 0;



troopConfig += parseInt(inputTag[j].value);



} else {

if (inputTag[j].getAttribute("type") == "radio" && inputTag[j].checked) {

attackType = inputTag[j].value;

} else if (inputTag[j].getAttribute("type") == "checkbox") {

activeBool = inputTag[j].checked;

}

}

}

var arr = farmList[i].split("|");

newList += arr[0] + "|" + troopConfig + "|" + C2E(arr[2]) + "|"

+ C2E(arr[3]) + "|" + C2E(arr[4]) + "|" + C2E(arr[5]) + "|"

+ arr[6] + "|" + activeBool + "|" + attackType;

} else {

newList += farmList[i];

}

}

GM_setValue("FarmList_" + suffixLocal, newList);

FM_log(4,"SaveEditedFarm: Edit Farm Save Complete");

clearque();

reloadFarmTable();

}



//get informations

function getT35version() {

try{

plusLogo = dom.get("logo");

if(plusLogo != null) {

if(plusLogo.nodeName == "IMG") {

//de2

GM_setValue("TravianVersion_"+suffixGlobal,1);

vT35=1;

} else if (plusLogo.nodeName == "A") {

//com7, com9, it9, comx

GM_setValue("TravianVersion_"+suffixGlobal,2);

vT35=2;

} else {

GM_setValue("TravianVersion_"+suffixGlobal,0);

vT35=0;

FM_log(0,"unknown Travian Version");

}

}

FM_log(1,"Travian Version is: "+vT35);

return;

} catch (error) {

FM_log(0,"getT35version(): error retrieving Travian35-Version");

}

}

function getStartIndex() {

FM_log(3,"getStartIndex() called");

FM_log(4,"getSIndex suffixLocal="+suffixLocal);

var sIndex = GM_getValue("StartIndex_" + suffixLocal, 0);

FM_log(4,"retrieved sIndex="+sIndex);

return sIndex;

}

function getEndIndex() {

var eIndex = GM_getValue("EndIndex_" + suffixLocal, 0);

return eIndex;

}

function getXYtoFarms(buttonId) {

FM_log(1,"getXYtoFarms("+buttonId+") called");



var xOff = 0, yOff = 0;

if(buttonId!="") {

if (buttonId=="ma_n1") {

xOff = 0; yOff = 1;

} else if (buttonId=="ma_n2") {

xOff = 1; yOff = 0;

} else if (buttonId=="ma_n3") {

xOff = 0; yOff = -1;

} else if (buttonId=="ma_n4") {

xOff = -1; yOff = 0;

} else if (buttonId=="ma_n1p7") {

xOff = 0; yOff = 7;

} else if (buttonId=="ma_n2p7") {

xOff = 7; yOff = 0;

} else if (buttonId=="ma_n3p7") {

xOff = 0; yOff = -7;

} else if (buttonId=="ma_n4p7") {

xOff = -7; yOff = 0;

}

}



FM_log(4,"offsets="+xOff+"/"+yOff);



//get new map center and store it

centerCoords = GM_getValue("MapCenter_"+suffixGlobal,"");

if(centerCoords!="") {

centerCoords = centerCoords.split(',');

FM_log(4,"stored coords:"+centerCoords[0]+","+centerCoords[1]);

} else {

FM_log(4,"no center coords stored");

return;

}



centerX = parseInt(centerCoords[0])+xOff;

centerY = parseInt(centerCoords[1])+yOff;



//store new map Center

FM_log(4,"new mapCenter="+centerX+"/"+centerY);

GM_setValue("MapCenter_"+suffixGlobal,centerX+","+centerY);



var allVillageId = new Array();

var allVillageIdStr = getAllVillageId().toString();

FM_log(4,"allVillageStr="+allVillageIdStr);

if(allVillageIdStr.indexOf(",")<0) {

allVillageId.push(allVillageIdStr);

} else {

allVillageId = allVillageIdStr.split(",");

}

var allData = "", i, farmData;

for (i = 0; i < allVillageId.length; i++) {

farmData = GM_getValue("FarmList_" + suffixGlobal + "_" + allVillageId[i], "");

farmData = trim(farmData);

if(allData !="") allData +=">:)";

allData += farmData;

}

FM_log(4,"allDataString="+allData);

allData = allData.split(">:)");

FM_log(4,"allDatalength="+allData.length);



for (var i = 0; i < allData.length; i++) {

if(allData[i].length>3) {

xyt = allData[i].split("|")[0].split(",");

markFarm(xyt[0], xyt[1]);

}

}



}

function isFarmerVillage(currentVillageId) {

var vList = GM_getValue("FarmerVillages_" + suffixGlobal, "").split(",");

if (vList == "" || vList.length == 0) {

return false;

}

var i;

for (i = 0; i < vList.length; i++) {

if (vList[i].split('~')[0] == currentVillageId) {

return true;

}

}

return false;

}

function isFarm(x,y) {

FM_log(3,"isFarm("+x+","+y+") called");

var allvList = getAllVillageId().toString();

FM_log(4,"allvList="+allvList);

if(allvList != "" && allvList != null) {

var vList = allvList.split(',');

for(i=0; i<vList.length; i++) {

var vId = vList[i];

//Get Farmlist for this village

tList = GM_getValue("FarmList_"+suffixGlobal+"_"+vId, "");

fVillages = tList.split(">:)");

for(j=0; j<fVillages.length; j++) {

vCoords = fVillages[j].split("|")[0];

cooX = vCoords.split(",")[0];

cooY = vCoords.split(",")[1];

if(x==cooX && y== cooY) {

FM_log(4,"it is a farm");

return true;

}

}

}

FM_log(4,"it is not a farm");

return false;

} else {

FM_log(4,"error fetching allvList");

return false;

}

}

function isReallyRallyPoint() {

FM_log(3,"isReallyRallyPoint() called");

// suche muss umgestaltet werden > direkt nach links suchen



var rp_link_overview = dom.xo('//a[contains(@href,"build.php?id=39")]');

var rp_link_sendtroops = dom.xo('//a[contains(@href,"a2b.php")]');

var rp_link_warsim = dom.xo('//a[contains(@href,"warsim.php")]');



FM_log(5,"LinkOverview:"+rp_link_overview.snapshotLength+"/LinkSendtroops:"+rp_link_sendtroops.snapshotLength+"/LinkWarsim:"+rp_link_warsim.snapshotLength);



if (rp_link_overview.snapshotLength < 1 || rp_link_sendtroops.snapshotLength < 1 || rp_link_warsim.snapshotLength < 1) {

//one of the link was not found

FM_log(4,"isReallyRallyPoint() = false");

return false;

}

FM_log(4,"isReallyRallyPoint() = true");

return true;

}

function getPlayerTribe() { //retrieve Player's tribe

FM_log(3,"getPlayerTribe() called");

var tribe = 0; //roman

if (dom.xs("//img[contains(@src,'x.gif')][@class='unit u1']")) {

tribe = 0;

} else if (dom.xs("//img[contains(@src,'x.gif')][@class='unit u11']")) {

tribe = 1;

} else if (dom.xs("//img[contains(@src,'x.gif')][@class='unit u21']")) {

tribe = 2;

}

return tribe;

}

function getFPlayerName() { //retrieve Farm player's name

FM_log(3,"getFPlayerName() called");

var user = dom.xs("//a[contains(@href,'spieler.php')]/parent::td");

//alert(user);

var playerName = (user) ? user.textContent : '';

playerName = trim(playerName);

//alert(playerName);

return playerName;

}

function getFPlayerId() { //retrieve Farm player's ID

FM_log(3,"getFPlayerId() called");

var user = dom.xs("//a[contains(@href,'spieler.php')][1]");

//alert(user);

var playerId = (user) ? getParamFromUrl(user.href, 'uid') : '';

//alert(playerId);

return playerId;

}

function getFPlayerTribe() { //retrieve Farm player's tribe

FM_log(3,"getFPlayerTribe() called");



var playerLink = dom.xs("//a[contains(@href,'spieler.php')]");

var playerTribe = "";



if (playerLink.snapshotLength<2) { //abandoned area/empty oasis

playerTribe = '';

} else {

playerTribe = dom.xs("//a[contains(@href,'spieler.php?')]/parent::td/parent::tr/parent::tbody/tr[1]/td[last()]").textContent;

}

playerTribe = trim(playerTribe.toLowerCase());

//alert(playerTribe);

FM_log(4,"PlayerTribe="+playerTribe);

return playerTribe;

}

function getCvalue() { //retrieve village c value

var url = document.location.href;

var cValue = getParam
Preview of Farming Machine for Travian 3.5
View script source of Farming Machine for Travian 3.5
Comment of Farming Machine for Travian 3.5
[2009-11-16 16:43:42]hunt4grl says:
nmbl;kaaqde

[2009-11-16 16:45:56]hunt4grl says:
slnkcd n


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

Written by
Name:MrSk
Scripts:1
Styles:0
Plugins:0
Tags
Travian
 
  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