Advertisement
FiendKing04

LuXBot

Jul 13th, 2016
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name            KoC LuXBot Script
  3. // @description     KoC LuXBot Script
  4. // @include         http://*kingsofchaos.com/*
  5. // @exclude         http://*kingsofchaos.com/chat/*
  6. // @require         http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
  7. // @require         http://bot.luxbot.net/includes/md5.js
  8. // @require         http://bot.luxbot.net/includes/highstock.js
  9. // ==/UserScript==
  10.  
  11. /* This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Germany License.
  12.     To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/de/
  13.     or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
  14. */ 
  15.  
  16. //
  17. // For information on the development of this through the ages please visit: http://stats.luxbot.net/about.php
  18. //
  19.  
  20.  
  21.  
  22. //todo writemail, autosave
  23. //todo last attacks on player..
  24.  
  25. /*
  26.     UPDATE LOG:
  27.    
  28. */
  29.  
  30.     var User = [];
  31.     var changeLog = [];
  32.  
  33.     function addChange(date,text) {
  34.         changeLog.push([date,text]);
  35.     }
  36.  
  37.  
  38.     addChange("6/26/2012 -Venar", 'Added an "Armory Differences" module, to show changes since last viewing of armory. Also reformatted the armory page a little bit so that if you collapse suggestions or lost weapons log it would look normal. Biggest change was to the Targets implementation, replacing the previous toggled mode system, with a simple auto-fill based based on current stats, with the ability to update.');
  39.  
  40.     addChange("6/21/2012 -Venar", 'Created this "beta" change log section at the request of Pingu. Also made most of the features of luxbot into options, and created a simple way to make any future option toggle-able as well. Some minor updates to the GUI code as well.');
  41.  
  42.     addChange("6/14/2012 -Venar", 'Added the "refresh" to stats pages statistics and neatened the code a little for that section.');
  43.    
  44.     addChange("6/05/2012 - Dokken", "Invalid id's in statsPage() were no longer removed from the active list (function logStats() : 'invalid' has to be send as 6th parameter since 'chain' was added)");
  45.    
  46.     addChange("4/23/2012 -Ven", "* added unheld display in trainpage\
  47.         * added graphs for TFF and armory value");
  48.        
  49.     addChange("4/11/2012 11pm - dokken", "* added FakesabList \
  50.         * moved the online image on statspage to the left. It's now next to the label and no longer the name. This caused a wrong call for history.php when targetted user was online.");
  51.  
  52.     addChange("4/10/2012 11am -Ven", "* Re-fixed income calc\
  53.         * Added clickable \"sabbable weapons\" on sab pages\
  54.         * Made all tables in armory page expandable, isntead of just a few\
  55.         * Changed the way that the command center is recorded.\
  56.         * Added some js prototypes, courtesy isFargy of RL");
  57.        
  58.     addChange("4/4/2012 1am - dokken", "Cinch gave us a better version of addIncomeCalc that works for chainheads too");
  59.    
  60.     addChange("4/3/2012 3am - dokken", "Fixed addIncomeCalc which took wronf values, due to 2 new table-rows 'Supreme Commander' & 'Chain Name'");
  61.  
  62.     addChange("4/1/2012 4am", "Rolled back the changes that were made to deal with End of Age counter");
  63.  
  64.     addChange("3/7/2012 1pm", "Rewrote a lot of the auth stuff to work with 'VBulletin 4' our new forum system. The authsystem will be slower until everyone updates to new lux and I can remove the legacy features. Should speed things up in the end, and be more secure since we're using a salt on the hashing serverside.  - Venar");
  65.        
  66.     addChange("1/20/2012 2pm", "Lots of updates, rewrote the 'buttons' for buying things, the armory suggestions, and the sablogs. Also implemented getLux and did tons of bug /security fixes  - Venar");
  67.        
  68.     addChange("1/5/2012 400pm", "Wrote the function bf_online, which will display users who used luxbot in the past half hour.\
  69.         Also added a button linking the stats page of users to the user history, for easier usage of stats.luxbot.net ;)\
  70.         ALSO small change to the 'Out of date' such that it has a tooltip, and also is a link the the players stats page.  - Venar");
  71.    
  72.     addChange("1/4/2012 155am", "Wrote the function bf_needsRecon, and with an icon from Wulfric, and some code in lux_needsRecon.php, enabled one to see\
  73.         on the battlefield whether or not all of a players stats have been updated in the past 24 hours.  - Venar");
  74.    
  75.     addChange("1/3/2012 11:18pm ", "Update to recon request system, storing the name of who initially requested it. Also security upgrade so only forum users can make requests.\
  76.         Includes changes to lux_reconrequest.php and lux_reconrequestlist.php  - Venar");
  77.        
  78.     addChange("3/7/2011 12:35pm", "Added hoverover gold projections in attack targets menu.\
  79.         Changes involved gettargets() function and on server the lux_targets2.php file - Venar");
  80.    
  81.  
  82.  
  83.     /****************************
  84.     // End of Change Log
  85.     ****************************/
  86.  
  87.  
  88.    
  89.  
  90.  
  91.  
  92. // These helper functions are slightly modified versions of code taken from isFargy (RL), thanks :)
  93. String.prototype.trim = function () {return this.replace(/^\s+|\s+$/g, '');};
  94. String.prototype.between = function(first,second) {var x = this.indexOf(first) + first.length;var z = this.substring(x);var y = z.indexOf(second);return z.substring(z,y);};
  95. String.prototype.instr = function(strFind){return (this.indexOf(strFind) >= 0);};
  96. String.prototype.int = function() {
  97.     var r = parseInt(this.replace(/,/g,''),10);
  98.     if (isNaN(r)) r=-1;
  99.     return r;
  100.     };
  101. String.prototype.float = function() {
  102.     var r = parseFloat(this.replace(/[^0-9\.]*/g,''),10);
  103.     if (isNaN(r)) r=-1;
  104.     return r;
  105.     };
  106. Number.prototype.int = function() {
  107.     return this;
  108. }
  109.  
  110. var db = {
  111.     id : '',
  112.     init :function(kocid) {
  113.         if (kocid != null) {
  114.             GM_setValue("lux_last_user",kocid);
  115.             this.id = kocid;
  116.             return;
  117.         }
  118.         else
  119.             this.id = GM_getValue("lux_last_user",0);
  120.     },
  121.     get : function(option,def) {
  122.         option += "_"+this.id;
  123.         var value =GM_getValue(option,def);
  124.         if (option.indexOf('gold_')>0)
  125.             value=parseInt(value);
  126.         return value;
  127.     },
  128.     put: function(option,val) {
  129.         option += "_"+this.id;
  130.         GM_setValue(option,val);
  131.     },
  132.     del : function(option) {
  133.         option += "_"+this.id;
  134.         GM_deleteValue(option);
  135.     },
  136. };
  137.  
  138. var loadUser = function(kocid) {
  139.     db.init(kocid)
  140.     if (db.id == 0)
  141.         return false;
  142.        
  143.     userObject = {};
  144.     //koc info
  145.     userObject.kocid = db.get('kocid','');
  146.     userObject.nick = db.get('kocnick',''); //koc nick
  147.     userObject.race = db.get('race',-1);
  148.     userObject.tff = db.get('tff',0);
  149.     userObject.income = db.get('income',-1);
  150.    
  151.     //forum info
  152.     userObject.forumName = db.get('forumName','');
  153.     userObject.forumPass = db.get('forumPass','');
  154.     userObject.auth = db.get('auth','');
  155.    
  156.     userObject.sa = db.get('sa',0);
  157.     userObject.da = db.get('da',0);
  158.     userObject.spy = db.get('spy',0);
  159.     userObject.sentry = db.get('sentry',0);
  160.     userObject.spyWeaps = db.get('spyWeaps',0);
  161.     userObject.sentryWeaps = db.get('sentryWeaps',0);
  162.     userObject.daWeaps = db.get('daWeaps',0);
  163.     userObject.saWeaps = db.get('saWeaps',0);
  164.    
  165.     //user options
  166.     userObject.logself = db.get('logself','');
  167.  
  168.    
  169.     // floaty gold on teh left side
  170.     var gold = TextBetween(document.body.innerHTML, 'Gold:<font color="#250202">', '<');
  171.  
  172.     if (gold != '') {
  173.         gold = gold.replace('B', '000000000');
  174.         gold = gold.replace('M', '000000');
  175.         gold = gold.replace('K', '000');
  176.         gold = to_int(gold);
  177.     }
  178.    
  179.     userObject.gold=gold;
  180.    
  181.     var d = new Date();
  182.     userObject.time = d.getTime()+1000*60;
  183.    
  184.     return userObject;
  185. };
  186.  
  187. var page = {
  188.     which : function() {
  189.         return document.URL.substring(document.URL.indexOf('.com')+5, document.URL.indexOf('.php'));   
  190.     },
  191. }
  192.  
  193. //end of prototypes
  194.  
  195.  
  196.     //GENERAL
  197.    
  198.     function to_int(str) {
  199.         str = str.replace(/[^0-9]/g,'');
  200.         if (str == '')
  201.             return '';
  202.         return parseInt(str);
  203.     }
  204.    
  205.     function remove_delimiters(str) {
  206.         str = str.replace(/[;:&?]/g,'');
  207.         return str;
  208.     }
  209.        
  210.     function btn_update(rows, num_rows, cost_col, max_col) {
  211.         function btn_cost(rows) {
  212.             var total_cost = 0;
  213.             $(".btn_go").each(function(i,e) {
  214.                 var amount = $(e).parent().parent().find("input").eq(0).val(); 
  215.                 if (amount=="")
  216.                     amount=0;
  217.                 var price = $(e).attr('cost');
  218.                
  219.                 total_cost += amount*price;
  220.             });
  221.             return total_cost;
  222.         }
  223.        
  224.         var g = String(User.gold).replace(/[^0-9]/g,'');   
  225.         var cur_cost = btn_cost(rows);
  226.         var money_left = Math.max(0, g - cur_cost);
  227.        
  228.         var sum_trained=0;
  229.         rows.each(function(index,element) {
  230.             var cols = $(element).children("td");
  231.             //alert($(cols).size()+" "+num_rows);
  232.             if ($(cols).size() == (1+num_rows)) {
  233.                 var cost = $(element).find("td>input:eq(1)").attr("cost");
  234.  
  235.                 var amount = Math.floor(money_left/cost);
  236.                 if(max_col) {
  237.                     var max = $(cols).eq(max_col).text().replace(/[^0-9]/g,'');
  238.                     amount = Math.min(amount, max);
  239.                 }
  240.                 if (document.URL.match('train.php')) {
  241.                     sum_trained += parseInt($(cols).eq(2).children("input").val());
  242.                 }
  243.                 $(element).find(".btn_go").val(amount);
  244.             }
  245.         });
  246.        
  247.         if (document.URL.match('train.php')) {     
  248.             var untrained = $("table.personnel>tbody>tr").eq(5).find("td").eq(1).text().replace(/[^0-9]/g,'');
  249.            
  250.             untrained = untrained - sum_trained;
  251.             rows.each(function(i,e) {
  252.                 var a = $(e).find(".btn_go").val();
  253.                
  254.                 a = Math.min(a,untrained);
  255.                 $(e).find(".btn_go").val(a);
  256.             });
  257.         }
  258.     }
  259.  
  260.  
  261.     function btn_init(rows, num_rows, cost_col, max_col) {
  262.         $(rows).find("input").keyup(function() {
  263.             btn_update(rows, num_rows, cost_col, max_col);
  264.         });
  265.         rows.each(function(index,element) {
  266.             var cols = $(element).children("td");
  267.             if ($(cols).size() == num_rows) {
  268.                 var cost = $(cols).eq(cost_col).text().replace(/[^0-9]/g,'');
  269.                 if (cost > 0)
  270.                     $(element).append("<td><input type='button' cost="+cost+" value=0 class='btn_go' /></td>");
  271.             }
  272.         });
  273.        
  274.         btn_update(rows, num_rows, cost_col, max_col);
  275.        
  276.         $(".btn_go").click(function(element) {
  277.             var amount = $(element.target).val();
  278.             $(this).parent().parent().find("input").eq(0).val(amount);
  279.             btn_update(rows, num_rows, cost_col, max_col);
  280.         });
  281.     }
  282.  
  283.  
  284.     function TextBetween (str,first,second) {
  285.         if (str==null) {
  286.             alert("Unexpected page formatting, please reload.");
  287.             return "";
  288.         }
  289.         var x = str.indexOf(first) + first.length;
  290.         var z = str.substr(x);
  291.         var y = z.indexOf(second);
  292.         return z.substr(z,y);
  293.     }
  294.    
  295.     function timeToSeconds (time, timeunit) {
  296.         if (timeunit.match('minute')) { time = time * 60; }
  297.         else if (timeunit.match('hour')) { time = time * 60*60; }
  298.         else if (timeunit.match('day')) { time = time * 60*60*24; }
  299.         else if (timeunit.match('week')) { time = time * 60*60*24*7; }
  300.         else { time = time; }
  301.         return time;
  302.     }
  303.    
  304.     function timeElapsed(time) {
  305.             var d = new Date()
  306.             var ds =  d.getTime();
  307.             timespan = Math.floor((ds - time) / 1000)
  308.             var time = "";
  309.             if ((timespan > 1209600) && (time == "")) time += Math.floor(timespan / 604800) + ' weeks ago';
  310.             if ((timespan > 604800) && (time == "")) time += '1 week ago';
  311.             if ((timespan > 172800) && (time == "")) time += Math.floor(timespan / 86400) + ' days ago';
  312.             if ((timespan > 86400) && (time == "")) time += '1 day ago';
  313.             if ((timespan > 7200) && (time == "")) time += Math.floor(timespan / 3600) + ' hours ago';
  314.             if ((timespan > 3600) && (time == "")) time += '1 hour ago';
  315.             if ((timespan > 120) && (time == "")) time += Math.floor(timespan / 60) + ' minutes ago';
  316.             if ((timespan > 60) && (time == "")) time += '1 minute ago';
  317.             if ((timespan > 1) && (time == "")) time += timespan + ' seconds ago'; 
  318.             if (time == "") time += '1 second ago';    
  319.         return time;
  320.     }
  321.  
  322.     function checkOption(opt) {
  323.         if (db.get(opt, "true") == "true")
  324.             return true;
  325.         else
  326.             return false;
  327.     }
  328.  
  329. (function(){
  330.  
  331.  
  332.     var action = page.which();
  333.    
  334.     var kocid = null;
  335.  
  336.     if (action =='base') {
  337.         var html = document.body.innerHTML.split("stats.php?id=");
  338.         html = html[1];
  339.         kocid = html.slice(0,html.indexOf('"'));
  340.     }
  341.    
  342.     User = loadUser(kocid);
  343.  
  344.     //version is year, month, day OR yymmdd
  345.     const version = '0.4.120710';  
  346.     const serverURL = 'luxbot.net/bot/';
  347.     const baseURL = 'http://' + serverURL + 'luxbot.php?';
  348.    
  349.    
  350.     var querying = false;   //for battlefield, "clicking" and expanding
  351.     var previd;
  352.    
  353.     var c = 0;
  354.     var c2 = 0;
  355.     var r;
  356.     var prevuser;
  357.    
  358.    
  359.     var statsdesc = {0:'Strike Action', 1:'Defensive Action', 2:'Spy Rating', 3:'Sentry Rating', 4:'Gold'};
  360.    
  361.     var direct;
  362.     var messages;
  363.     var darken;
  364.     var guicontent;
  365.     var widget;
  366.    
  367.     var bfusers;
  368.     var coltables = [];
  369.    
  370.     checkForUpdate(1);
  371.     createGUIContainer();
  372.     initReconRequest();
  373.    
  374.     if(checkUser() == 0) {
  375.         return;
  376.     }
  377.  
  378.  
  379.     // Turn clock
  380.     if (checkOption('option_clock')) {
  381.         updateClock();
  382.     }
  383.  
  384.     if (checkOption('option_goldProjection')) {
  385.         updateGold();
  386.     }
  387.  
  388.    
  389.  
  390.  
  391.     switch (action) {
  392.         case 'base':
  393.             basePage();
  394.             coltables = db.get('coltables' + action, '').split(';');
  395.             makeCollapsable();
  396.             moveRecruitbox();
  397.             commandCenterStats();
  398.             break;
  399.        
  400.         case 'inteldetail':
  401.             processIntelLog();
  402.             break;
  403.            
  404.         case 'battlefield':
  405.             battlefieldAct();
  406.             showUserInfoB();
  407.             break;
  408.  
  409.         case 'attacklog':
  410.             attacklogPage();
  411.             break;
  412.        
  413.         case 'armory':
  414.        
  415.             $("table.table_lines:eq(2)").attr("id","military_effectiveness");
  416.             $("table.table_lines:eq(5)").attr("id","buy_weapons_form");
  417.             armoryPage();
  418.             armory_buyButton();
  419.            
  420.             makeCollapsable(); 
  421.            
  422.             //next two lines adds the clickable buttons
  423.             var rows = $("form[name='buyform']").find("table>tbody>tr");
  424.             btn_init(rows,4,2);        
  425.             break;
  426.        
  427.         case 'stats':
  428.             // show info about user
  429.             statsPage();
  430.             collapseAllianceInfoS();
  431.             showUserInfoS();
  432.             addStatsPageButtons();
  433.             statsOnlineCheck();
  434.             makeCollapsable();
  435.             break;
  436.  
  437.         case 'security':
  438.             if (db.get('securityfocus', 0) == 1) {
  439.                 alert('Security Page encountered...');
  440.             }
  441.             break;
  442.            
  443.         case 'conquest':
  444.             conquestPage();
  445.             break;
  446.            
  447.         case 'train':
  448.             trainPage();
  449.            
  450.             //next two lines sets up the clickable buttons
  451.             var rows = $("form").eq(0).find("table>tbody>tr");
  452.             btn_init(rows, 3, 1);
  453.             makeCollapsable();
  454.             break;
  455.            
  456.         case 'mercs':
  457.             var rows = $("form").find("table>tbody>tr");
  458.             btn_init(rows,4,1, 2);
  459.             break;
  460.            
  461.         case 'detail':
  462.             showBattleLog();
  463.             // Gold Update on attacks
  464.             processAttackLogDetail();
  465.             break;
  466.        
  467.         case 'attack':
  468.             getSabInfo();
  469.             checkCap();
  470.             break;
  471.     }
  472.  
  473.  
  474.  
  475.    
  476.     // GENERAL
  477.    
  478.     function updateGold() {
  479.    
  480.         var newTime = new Date();
  481.         newTime = newTime.getTime();
  482.        
  483.         if (newTime < User.time) {
  484.             setTimeout(updateGold,100);
  485.             return;
  486.         }
  487.        
  488.         elapsedMinutes = Math.floor((newTime - User.time)/1000/60);
  489.        
  490.         var temp = $("#gold_projection");
  491.         if (temp.size() ==0) {
  492.             $("tr:contains('Last Attacked:'):last").parent().find("tr:eq(0)").after("<tr><td colspan=2 style='color: BLUE; font-size: 6pt;text-align:center' id='gold_projection'></td></tr>");
  493.             temp = $("#gold_projection");
  494.         }
  495.        
  496.        
  497.         var newGold = Math.floor(User.gold.int() + (User.income.int()*elapsedMinutes));
  498.         $(temp).text("Projection: "+addCommas(newGold));
  499.    
  500.         // alert(elapsedMinutes + " "+User.gold + " "+ User.income);
  501.         setTimeout(updateGold,2000);
  502.     }
  503.    
  504.    
  505.    
  506.     function updateClock() {
  507.         var turnsoon = 0;
  508.         var currentTime = new Date ( );
  509.         var currentHours = currentTime.getHours ( );
  510.         var currentMinutes = currentTime.getMinutes ( );
  511.         var currentSeconds = currentTime.getSeconds ( );
  512.         currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  513.         currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
  514.         var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " ";
  515.         /*
  516.         //This is legacy from when the turns came once every 30 minutes//
  517.         if (((currentMinutes == "06") || (currentMinutes == 36)) && (currentSeconds > 30)) {
  518.             currentTimeString = '<span align="center;" style="font-size: 13pt;">Rank soon<br \></span>' +currentTimeString;
  519.             turnsoon = 1;
  520.         }
  521.        
  522.         if (turnsoon == 0) {
  523.             $("#_md_clock").css("background","#000000");
  524.         }
  525.         else {
  526.             $("#_md_clock").css("background","#FF0000");
  527.         }
  528.  
  529.         */
  530.        
  531.         var clock = document.getElementById("_md_clock");
  532.  
  533.         if (!clock) {
  534.             $(".textad:first").prepend("<div style='font-size:18pt;' id='_md_clock'></div>");
  535.         }
  536.        
  537.         $(clock).text(currentTimeString);
  538.         setTimeout(updateClock,500);
  539.     }
  540.    
  541.  
  542.     function createGUIContainer() {
  543.  
  544.         addCSS('#_luxbot_gui{position:fixed;top:0;right:0;background-color:#000000;padding:15px;border:1px solid #ffffff;}');
  545.         addCSS('#_luxbot_gui ul,#_luxbot_nav{list-style:none;margin:0;padding:0;');
  546.         addCSS('#_luxbot_nav li{float:left;margin-right:10px;}');
  547.         addCSS('._luxbotago{color:#aaaaaa;font-style:italic}');
  548.  
  549.         $("body").append("<div id='_luxbot_gui'><ul></ul></div>");
  550.         // var q = document.createElement('div');
  551.         // q.id = '_luxbot_gui';
  552.         // document.body.appendChild(q);
  553.  
  554.         // var x = document.createElement('ul');
  555.         // q.appendChild(x);
  556.         // direct = x;
  557.        
  558.         createGUIBox();
  559.        
  560.         addGUILink('Open Control Panel<br>' + version, toggleGUI, "#_luxbot_gui");
  561.        
  562.         addGUILink('Show links', showLinkBox, "#_luxbot_nav_div"); //Show links in luxbot control panel - ZnakeY
  563.         addGUILink('Farmlist Setup', showFarmList, "#_luxbot_nav_div");
  564.         addGUILink('Check for update', checkForUpdate, "#_luxbot_nav_div");
  565.        
  566.        
  567.         q = document.getElementsByTagName('td');
  568.         for (i = 0; i < q.length; i++) {
  569.             if (q[i].className == 'menu_cell' && q[i].innerHTML.indexOf('username') == -1) {
  570.                 if (checkOption('option_sabTargets')) {
  571.                     var t = q[i].childNodes[1].insertRow(3);
  572.                     t.innerHTML = '<a href="javascript:void(0);" id="_luxbot_sablist_nav"><img src="http://www.luxbot.net/bot/button_koc_sabtargets.gif" /></a>';
  573.                     document.getElementById("_luxbot_sablist_nav").addEventListener('click', sabTargetsButton, true);
  574.                 }
  575.                 if (checkOption('option_Targets')) {
  576.                     var t = q[i].childNodes[1].insertRow(3);
  577.                     t.innerHTML = '<a href="javascript:void(0);" id="_luxbot_farmlist_nav"><img src="data:image/gif;base64,R0lGODlhiQAXAPcAAAAAAP///7m5ua+vr6ysrIB3d2s/QEsoKVMuL3peX4hvcGFMTWNPUKyYmca3uGhaW3FjZGteX5aKi7KlprSqq6CXmKujpL62t83FxrOsrbWur7evsVhUVbm1trSwsbewsrKprK2nqV5bXLq3uLCtrvDt7snGx8XCw5uWmLWwsrKtr97Z2/37/NTS08/Nzs3LzMG/wL27vK+trvTx87myt7SutK2qrfXz9fj3+PLx8vHw8fDv8OLh4t7d3tLR0tDP0La1trSztLKxsrCvsLq3u7Gvs/v6/Lu6vNva3cbFyN/f4uHh48vLzc3Nzq+vsKytr83Oz76/wODi4+bo6La4uNfY2LS1ta+wsLG2tcrNzL2/vt/i3/z+/Lm7ua+xr/Hy8evs6+fo583OzcPEw8HCwcDBwLq7ura3trW2tbO0s7GysYqLirq9ubW4tKutqdzd27O0sbm6tq2tquXl49HRz7e3ta+vrfz8++zs6+rq6eHh4MzMy8rKycjIx8DAv76+vby8u7q6ubW1tLKysbCwr6+rpPHw7+no5+Pi4dnY18/OzcXEw7KxsLCurbOwrygkI4p9fGZXVp6Lin5mZVcjI1omJkYfH1wpKWtAP2s/P3JKShQNDWxSUnxfX1NAQIZtbR0YGI12dpF6epeBgaSSkpSGhpOFhX90dAwLC6aZmaebm3hwcKecnKOZma+lpa2jo6mgoIB5eYqDg87FxbCoqJWPj7myspqUlM3GxpeSksjCwqqlpaCbm87JyU1LS7aysq2pqdPPz7+8vL26urCtra+srKGenuTh4ejm5ufl5dbU1Pr5+fj39/Lx8eTj4+Pi4uLh4eDf397d3d3c3Nva2tjX19bV1dPS0tHQ0NDPz8fGxr++vra1tbSzs7Cvr6+urq2srKyrq6moqKSjo5ybm/7+/vz8/Pv7+/j4+Pb29vPz8+7u7uvr6+np6ejo6Ofn5+Xl5d/f39jY2M7Ozs3Nzb29vbi4uLe3t7Ozs7KysrCwsK6urq2trTMzMy4uLv///ywAAAAAiQAXAAAI/wARPIgVr8IxAJJEPFh1qkDDAhAjSpwYq6LFihMzatz4oEDHByBDihxJsuQDgSZTjvQEcgEDkAwKVFsxzRkBPAByPjiWTUCFB2DWpSsXIIA5c0WTKl3KtKnTpeiiSpWaA12OqlFzgNm61Z3Xr2DDegXDjt2hsmjTHlrLti3aZGB05NHqrlUsmjUjBAOAAECFC7q4sUPAhg+1dUifKk5a7pw5oouLZtUKxp0UJfFWVKvmwwc9emL4DKOCpjQBAgNOq049oLU3R3DQxOHGTUBtAbhtc+vWrUjq08VaF7HCzZErWhJgqGIzwC7eaREA8QUZQVuwB5IE0IOXo9zRxJHDL/+e3PXZlsycO3+mpw3QmdJYnthRTR9169ZXrKChzb8/7W5qtEafcFac8conqpQCwwZR7FMRXs6ssFcsvvhSyjEuBBELPyfo0Z14IBYFnmJ0PfNMPPFsRo9n9OyhTT3v4ZOGE/yA89uAwA2gTz5BAHFPbkDqBmCA9xFoRQoHdGIKDDBss48pMuEVAU4PRDCCBbroAoQk22ynDlLeQRbimEudUx6KKXbGIh9jAFKHFYN4wVp9qe2z4z46qtFjB7jd1uduvRUhw6AytMaIFUHc04mS25SxTTG5FJDNNNNYIEkEADwCgQUQuLCTJ/bQ48yXZIa4QSqopprKBDuciaKKLNL/00cZZqCRhj4CqsbPrvxcQWShA1yBDxBB5mYPbWrogys/r/BD4C5pTHBBDGX4IYwrUM60wml9PVABKSdEE0sRpwxCDzvoHEWUmKU61YkDuLhiSSe44KLADq26Y2I80mzmQqza/HEPGkTyg9ppu4YSyiD68BMgP/sMgc8Z9uBmz8UX6xaEEPrss08xr9zHjX72CKMFDGTYM0AunVRDqTN6+QXBKr1AQE40qNgDCBhVGdVuZKkUhcu8RamCQ4knpukDNvS8wIQ2fnQQBzECDhCOOMDwowAlrwghhAzh4DnAN/mgcU/GQP5XhG+vrNYaNxd3I4wwTAqzskyUQicduD44/0MLKRAA4MQJPpB61M/hDd1JAOXcoIM8piiJogOmQG7KZ51YosAki+aTWgGZFEAAP59c8g0hg+SSSSYPNNBI2RUXq3HDrXncWgi0oUFLDNuQQcY2d09ak4QARHBBL73IAw8rngjgQzzoIB6i4oyrk8O7madCTeaLdkJP5tg4MK8rAzRQyT4EVPIAOJpQookmuVTSgTDrk1A2scWWZoUVYxMK7DfEKYYVOvCBD8DAbqWI0jTyEDNIhEIY8tBDMtbgCyv4gDvmiJ70IkO9cqRDHc/4wtBSMQ15OeAHL6DHvKygOFzog3WoeUAl+DEKSsxCHwWohDEMZgOy7edsGLPHGf/eY4UhtAYcxUhia7xQoF1kwAMUsAUrWDGAWhQAGyuwCx5w8goJ6MMZyoDHKRAgAC0EZYPioR7j0oEtU1giFfFIhSVwgY1gfM8S9pBjKoqhhkqwDiS50JrpBjGBShgyE7kIh4y6QTF7jEAAQiSi54qkClW0xgr3gMUrRmAPGBSDFuOYRAHKQBMLtAIn/fCFB+ShDXfA4gFB2McZGecUdiFOjedwozxGGA954cIHKbxjJ1KBhgGkwY9jGEM+8kGA0p0uH98ohjEqgYlw5KNAscNNIHBTGjQMQQYIC0FwPLC/DMAiBvUQhi0YQY5bXJEmzjglAETBiw7AgwftWAMA2ED/D+gZxZZoXIoa0ZE5eeiRGnLEBT1MMI/IXUMb3eRHDnNxmnCQznSSKMAVZLCNjoTgmmcrFiNIYKtc8SNsAxiEB+6BnGGYQZ3CEEcCtUWAPOTBL72oxjuO4Q59osEa8/gSmALaFFy48Y0BwIG83jgvXHAPFz+4oyWmagllDUCGqyvALhpwiUs0IH4eMQAN7CAEQTTyYkNEAwmGMIIZ3Sgc44irPnSXilcAgwysSGKkJhUEZ/hDnyLgxQqccYwRmIGMPgADM4ZKpnIANDznyME7khE9dEwjRS4wQQvoYQpTnCAQaJiXGgxmNawN4RsDKIaySLAPcMihGI0YhFmDKMQg/3SDEWlIwwBkgNpihGAcMrDBNbthClV8wBYSoIUMZIE3WcSiBjlxAB848wxk3MMf+UhsDhhLpnM8djGNyUNlkqa0qFoiHosYgTwsYYqH7cNgBPjGN+YDsfq6wVn5EEQdsimAQPyHAN1wQpHCUSh9WKEbVljVtSQwDFMkoGXKmMYmAMEBAFjjBNSoBg984AtOOE+x3G2KY5fy3RDlgB36kgI1+mUNejBtXn1gQ+YwgAb40gccOO4hIXjrMSeA1FjafA8a9GFEhNnHCVYgQQ2mOAxXfKADsIBEAazhjGk8whftAAA4ThCDYSBCG5HgQBd84I7F0jI8ji0xmjOIB3Y84/8y0pCGNTjzGWWU4gCTMAURDjwAj9mYADjmBwlwZbsrgBRjFjsDIw7Fv/vIIDg6sgI+XkGLI2xAFbBoRQiknI01PEIW/bAAADwBgVqcYBgo4IAsQkAHd8wAHVx4rJpLVQ4umIMFRtDKFN6MBBYrIhtNyMIJbFEIGQhiN4R4b30AXYxv4Oo+hMAHNotlDzTsrzUk+AY47MMIONiBFbQIxAc0QAESDEACeAMAOVhxCgBs4hGrgAEf9FELWRTjBc4wxGJnzRR+i9gcRlgGM9SxDnbMAc7SqAJnXPCCPoxBGCPoQB0EIQRvfGMf4NQVxKyKJ31I+wyyOwOg1kYCEuC4GN6DUAMjGkELEATipYD4xQDciY1pQCAWa/AHAA4AClkI4wQjQAYk2pCNY5QgHXfwN+NGXCounEPgN2jGOvLgjCUooQdvSIQ1fAAFJvAhCQcMRBwEkY9nfwO+NvKYPtRgcTt4fNpBEjlvSE6CYhBABimHgwpAoIEODGMbMZ+5TJyxBwpLJyAAOw==" /></a>';
  578.                     document.getElementById("_luxbot_farmlist_nav").addEventListener('click', showFarmList, true);
  579.                 }
  580.                
  581.                 if (checkOption('option_fakeSabTargets')) {
  582.                     var t = q[i].childNodes[1].insertRow(3);
  583.                     t.innerHTML = '<a href="javascript:void(0);" id="_luxbot_fakesablist_nav"><img src="http://www.luxbot.net/bot/button_koc_fakesabtargets.gif" /></a>';
  584.                     document.getElementById("_luxbot_fakesablist_nav").addEventListener('click', showFakeSabList, true);
  585.                 }
  586.                 break;
  587.             }
  588.         }  
  589.     }
  590.    
  591.     function createGUIBox() {
  592.         if (widget == undefined) {
  593.            
  594.             var x = document.createElement('div');
  595.             x.style.width = document.body.clientWidth + 'px';
  596.             x.style.height = document.body.offsetHeight + 'px';
  597.             x.style.position = 'absolute';
  598.             x.style.top = '0px';
  599.             x.style.left = '0px';
  600.             x.style.backgroundColor = '#000000';
  601.             x.style.opacity = '0.5';
  602.             x.id = '_luxbot_darken';
  603.            
  604.             var q = document.createElement('div');
  605.             q.id = '_luxbot_guibox';
  606.             addCSS('#_luxbot_guibox{width:80%;background-color:#333333;border:1px solid #00007f;position:absolute;padding:10px;}\
  607.             #_luxbot_guibox a{color:#cccccc;text-decoration:underline;}\
  608.             #_luxbot_closenav {position:absolute;right:0;top:0;text-decoration:none;color:#ffffff;}\
  609.             #_luxbot_guibox fieldset{font-size:0.9em}');
  610.             document.body.appendChild(x);
  611.             document.body.appendChild(q);
  612.            
  613.             darken = x;
  614.             widget = q;
  615.            
  616.             q.innerHTML = '<button id="_luxbot_closenav">X</button><div id="_luxbot_nav_div"><ul id="_luxbot_nav"></ul></div><div style="clear:both;"></div><div id="_luxbot_content"></div>';
  617.             document.getElementById("_luxbot_closenav").addEventListener('click', toggleGUI, true);
  618.             document.getElementById("_luxbot_darken").addEventListener('click', toggleGUI, true);
  619.            
  620.             guicontent = document.getElementById('_luxbot_content');
  621.            
  622.             toggleGUI();
  623.         }
  624.        
  625.         guicontent.innerHTML = '<h1>This is the Control Panel for LuXBOT</h1>Please select a task from above!<br /><button id="_luxbot_close">Close</button>';
  626.         document.getElementById('_luxbot_nav_div').style.display = 'block';
  627.         document.getElementById("_luxbot_close").addEventListener('click', toggleGUI, true);
  628.         alignGUI();
  629.     }
  630.    
  631.    function alignGUI() {
  632.         w = widget.clientWidth;
  633.         h = widget.clientHeight;
  634.         xc = Math.round((document.body.clientWidth/2)-(w/2));
  635.         yc = Math.round((document.body.clientHeight/2)-(h/2));
  636.         if (xc < 0) {
  637.             xc = 0;
  638.         }
  639.         if (yc < 0) {
  640.             yc = 0;
  641.         }
  642.         widget.style.left = xc + 'px';
  643.         widget.style.top = yc + 'px';
  644.     }
  645.    
  646.     function showMessage(text, backAction, backText) {
  647.         if (widget.style.display == 'none') {
  648.             toggleGUI();
  649.         }  
  650.         if (backAction == undefined) {
  651.             backAction = createGUIBox;
  652.         }
  653.         if (backText == undefined) {
  654.             backText = '&lt; Back';
  655.         }
  656.         guicontent.innerHTML = text + '<br /><button id="_luxbot_showgui">' + backText + '</button>';
  657.         document.getElementById("_luxbot_showgui").addEventListener('click', backAction, true);
  658.         document.getElementById('_luxbot_nav_div').style.display = 'none';
  659.         alignGUI();
  660.     }
  661.    
  662.     function toggleGUI() {
  663.         if (widget.style.display == 'none') {
  664.             widget.style.visibility = darken.style.visibility = 'visible';
  665.             widget.style.display = darken.style.display = 'block';
  666.             createGUIBox();
  667.         } else {
  668.             widget.style.visibility = darken.style.visibility = 'hidden';
  669.             widget.style.display = darken.style.display = 'none';
  670.         }
  671.     }
  672.    
  673.     function addGUILink(text, event, parent) {
  674.         var id = '_luxbot_' + event.name;
  675.         $(parent+">ul").append("<li><a href='javascript:void(0);' id='"+id+"'>"+text+"</a></li>");
  676.         $("#"+id).click(event);
  677.     }
  678.  
  679.     //Added linkbox - ZnakeY
  680.     function showLinkBox() {
  681.    
  682.         var html =  " <table class='table_lines' id='_luxbot_links_table' width='100%' cellspacing='0'\
  683.  cellpadding='6' border='0'>\
  684.    <tr>\
  685.      <th colspan='7'>FF Links</th>\
  686.    </tr>\
  687.    <tr>\
  688.      <td><a href='http://stats.luxbot.net/'>Player Statistics</a></td>\
  689.      <td><a href='http://fearlessforce.net/'>FF Forums</a></td>\
  690.      <td><a href='http://stats.luxbot.net/sabbing.php'>Enemies Sablist</a></td>\
  691.    </tr>\
  692.  </table> ";
  693.         searchtype = db.get("searchtype", 0);
  694.  
  695.         html += '<table class="table_lines" id="_luxbot_links_table" width="100%" cellspacing="0" cellpadding="6" border="0">\
  696.                     <tr><th>Recruiters Links</th></tr>\
  697.                     <tr><td><a href="http://stats.luxbot.net/clicks.php">Clitclick</a></td>\
  698.                     </tr></table>';
  699.                
  700.         showMessage(html);
  701.         document.getElementById('_luxbot_targets_searchtype1').addEventListener('click', targetsToggleSetup, true);
  702.         document.getElementById('_luxbot_targets_searchtype2').addEventListener('click', targetsToggleSetup, true);
  703.         targetsToggleSetup();
  704.         document.getElementById('_luxbot_targets_save').addEventListener('click', targetsSetupSave, true);
  705.        
  706.     }
  707.    
  708.     function showMessageBox() {
  709.         if (messages == undefined) {
  710.             return;
  711.         }
  712.         var content = '';
  713.         for (i = 0; i < messages.length; i++) {
  714.             var y = messages[i].split('|');
  715.             content += '<tr id="_luxbot_message_' + y[3] + '"><td><a href="javascript:void(0);" name="' + y[3] + '">+</a></td><td>' + y[1] + '</td><td>' + y[0] + '</td><td>' + y[2] + '</td></tr>';
  716.         }
  717.        
  718.         showMessage('<h3>Messages</h3><table id="_luxbot_messages" width="100%"><tr><th>Show</th><th>Sender</th><th>Subject</th><th>Date</th></tr>' + content + '</table>');
  719.         document.getElementById("_luxbot_guibox").addEventListener('click', showMessageDetails, true);
  720.     }
  721.    
  722.     function showMessageDetails(event) {
  723.         if (event.target.name != undefined) {
  724.            
  725.             getLux('&a=getmessage&id=' + String(event.target.name),
  726.                function(r) {
  727.                     var q = document.getElementById('_luxbot_message_' + String(event.target.name));
  728.                     showMessage('<h3>Messages</h3><table id="_luxbot_messages" width="100%"><tr><th>From</th><td>' + q.childNodes[1].innerHTML + '</td></tr><tr><th>Subject</th><td>' + q.childNodes[2].innerHTML + '</td></tr><tr><th>Date</th><td>' + q.childNodes[3].innerHTML + '</td></tr><tr><th>Message</th><td>' + r.responseText + '</td></tr>', showMessageBox);
  729.                     addCSS('#_luxbot_messages {border-spacing:4px;}\
  730.                     #_luxbot_messages th{width:100px;padding:6px;}');
  731.             });
  732.         }
  733.     }
  734.    
  735.  
  736.     //
  737.     // Recon Request
  738.     //
  739.    
  740.     function initReconRequest() {
  741.         //runs on every page, adds box to upper left of page.
  742.        
  743.         var x = $('<div id="_luxbot_ReconRequestPopup" style="display:none; position: absolute; top:0px; margin:15px; padding:20px;background-color: black; border: 1px solid green; font-family: arial; font-size: 10px;  overflow: auto;">');
  744.         $("body").append(x);
  745.         x.css("left",(document.body.clientWidth/2)-100 + "px");
  746.         $("#_luxbot_ReconRequestPopup").click(function () {
  747.             fillReconRequest(! db.get('reconRequest'));
  748.         });
  749.  
  750.         fillReconRequest(db.get('reconRequest')!=0);
  751.     }
  752.    
  753.     function fillReconRequest(bool) {
  754.         //if bool == true, then show info
  755.         //if bool == false then hide and show number
  756.        
  757.         getLux('&a=reconrequestlist',
  758.             function(r,debug) {
  759.                 q = $('#_luxbot_ReconRequestPopup');
  760.                 incoming = r.responseText.split(';');
  761.                 var numberRequests = r.responseText.split('(s)').length - 1;
  762.                
  763.                 if (numberRequests > 0) {
  764.                     q.slideDown();
  765.                     var stringBuilder = "<span style=\"color: red;\">("+numberRequests+") Recon Requests</span><br />";
  766.                     if (bool) {
  767.                         for (i = 0; i < incoming.length; i++) {
  768.                             info = incoming[i].split(':');
  769.                             stringBuilder+= info[0]+" | <a href='stats.php?id="+info[1]+"'>"+info[2]+"</a> by "+info[3]+ "<br />";
  770.                         }
  771.                         db.put('reconRequest', 1);     
  772.                     } else {
  773.                         db.put('reconRequest', 0);
  774.                     }
  775.                     q.html(stringBuilder);
  776.                 }
  777.             });
  778.     }
  779.  
  780.  
  781.  
  782.     // INIT
  783.     function showInitBox() {
  784.         welcome ='<h1>Welcome</h1>There is no data for your LuX account.<br /><br />';
  785.         showMessage(welcome + 'Please login with your <a href="http://www.fearlessforce.net">FF Forums</a> info.<br /><br /> '+
  786.                     'User: <input type="text" id="_forum_username" value="'+User.forumName+'"/> Password: <input type="password" id="_forum_password" /> <input type="button" value="Login"'+
  787.                                     'id="_luxbot_login" /><br />');  
  788.                                    
  789.         $("#_luxbot_login").click(initLogin);
  790.    
  791.     }
  792.    
  793.     function gui_showChangeLog() {
  794.         welcome ='<div style="text-align:center;"><h2>LuXBoT Change Log</h2><p style="padding-left:30px;width:500px">This is relatively new, and does not include all changes done to previous versions by various awesome coders. For more Information please visit our <a href="http://stats.luxbot.net/about.php">About</a> page.</p><br /><br />';
  795.        
  796.         var text = "";
  797.         for (i = 0; i < changeLog.length ; i++) {
  798.             text += "<tr><td>"+changeLog[i][0]+"</td><td>"+changeLog[i][1]+"</td></tr>";
  799.        
  800.         }
  801.         showMessage(welcome+"<table border=1><tr><th>Date</th><th>Info</th></tr>"+text+"</table></div>");  
  802.                                    
  803.     }
  804.    
  805.    
  806.    
  807.     function initLogin() {
  808.  
  809.         f_user = $("#_forum_username").val();
  810.         f_pass = $("#_forum_password").val();
  811.  
  812.         if (f_pass == '' || f_user== '')
  813.             return;
  814.  
  815.         showMessage(welcome+"Verifying...<br />");
  816.        
  817.         GM_xmlhttpRequest({
  818.                 method: 'GET',
  819.                 url: 'http://www.kingsofchaos.com/base.php',
  820.                 onload: function(responseDetails) {
  821.                     var html = responseDetails.responseText;
  822.                     user = TextBetween(html,'<a href="stats.php?id=', '</a>');
  823.                     user = user.split('">');
  824.                    
  825.                     db.put('kocnick', user[1]);
  826.                     db.put('kocid', user[0]);
  827.  
  828.                     password = hex_md5(f_pass);
  829.                     db.put('forumPass', password);
  830.                     db.put('forumName', f_user);
  831.                     initVB();
  832.                 }
  833.         });
  834.     }
  835.    
  836.     function initVB() {
  837.         getLux('&a=vb_login&kocid=' + db.get('kocid')+'&username=' + db.get('forumName','')+"&password="+db.get('forumPass'),
  838.             function(r) {
  839.                 var ret = r.responseText;
  840.                 if (ret.indexOf("Error") == -1) {
  841.                     //success
  842.                     db.put('auth', ret);
  843.                     alert("Success");
  844.                     toggleGUI();
  845.                 } else {
  846.                     showMessage(welcome + ret+"<br />",showInitBox,"Try again");
  847.                 }
  848.         });
  849.     }
  850.    
  851.     function gui_showUserOptions() {
  852.        
  853.         var c = (User.logself == 1) ?  ' checked="checked"' : '';
  854.        
  855.         var battlelog = db.get('battlelog', 0);
  856.        
  857.         showMessage('<h3>LuXBOT User Options</h3> <br />\
  858.         <fieldset><legend>User Options</legend>\
  859.             Log own details and gold from base: <input type="checkbox" id="_luxbot_logself"' + c + ' /><br />\
  860.             Battle Log: <input type="radio" name="_luxbot_battlelog" value="0"' + (battlelog == 0 ? ' checked="checked"' : '') + ' />\
  861.                 No Action <input type="radio" name="_luxbot_battlelog" value="1"' + (battlelog == 1 ? ' checked="checked"' : '') + ' /> \
  862.                 Show Full Log with Bottom Scroll <input type="radio" name="_luxbot_battlelog" value="2"' + (battlelog == 2 ? ' checked="checked"' : '') + ' /> \
  863.                 Show Full Log with Top Scroll <input type="radio" name="_luxbot_battlelog" value="3"' + (battlelog == 3 ? ' checked="checked"' : '') + ' /> \
  864.                 Show Full Log with Redirect<br />\
  865.             Always Focus Security Pages: <input type="checkbox" id="_luxbot_securitycheck" ' + (db.get('securityfocus', 0) == 1 ? ' checked="checked"' : '') + '/></fieldset>\
  866.         <fieldset><legend>Battlefield Options</legend>\
  867.             Filter Battlefield users: <input type="checkbox" id="_luxbot_bffilterna" ' + (db.get('bffilterna', 0) == 1 ? ' checked="checked"' : '') + ' /><br />\
  868.             Filter Players with less than <input type="text" value="' + db.get('bffiltergold', 0) + '" id="_luxbot_bffiltergold" /> Gold<br />\
  869.             Filter Players with less than <input type="text" value="' + db.get('bffiltertff', 0) + '" id="_luxbot_bffiltertff" /> Soldiers</fieldset><br />'
  870.             +'<table>'
  871.             +htmlToggle("Turn Clock","option_clock")
  872.             +htmlToggle("Stats In Command Center","option_commandCenterStats","Top","Side")
  873.             +htmlToggle("Attack Targets","option_Targets")
  874.             // +htmlToggle("Show Enemy Sab List","option_sabTargets")
  875.             +htmlToggle("Show Fake Sab Targets","option_fakeSabTargets")
  876.             +htmlToggle("Show Personal Gold Projections","option_goldProjection")
  877.             +htmlToggle("Show Stats Changes in Armory","option_armory_diff")
  878.             +htmlToggle("Show Armory Value Graph in Armory","option_armory_graph")
  879.             +"</table>"
  880.            
  881.             + '<br /><br /><input type="button" value="Save!" id="_luxbot_save" /> <br />');
  882.            
  883.         document.getElementById("_luxbot_save").addEventListener('click', saveUserOptions, true);
  884.     }
  885.      
  886.     function htmlToggle(name,value,opt1,opt2) {
  887.         current = db.get(value, "true");
  888.        
  889.         if (!opt1)
  890.             opt1 = "Enabled";
  891.         if (!opt2)
  892.             opt2 = "Disabled";
  893.         if (current == "true") {
  894.             var html = "<tr><td> "+name+"</td><td><input type='radio' name='"+value+"' checked='checked' value='true'>"+opt1+"</input>"
  895.                     +"<input type='radio' name='"+value+"' value='false'>"+opt2+"</input></tr>";
  896.         } else {
  897.             var html = "<tr><td> "+name+"</td><td><input type='radio' name='"+value+"' value='true'>"+opt1+"</input>"
  898.             +"<input type='radio' name='"+value+"' checked='checked' value='false'>"+opt2+"</input></tr>";
  899.         }
  900.         return html;
  901.     }
  902.     function saveUserOptions() {
  903.  
  904.         var logselfn = Number(document.getElementById('_luxbot_logself').checked);
  905.         if (User.logself != logselfn) {
  906.             User.logself = logselfn;
  907.             db.put('logself',logselfn);
  908.         }
  909.        
  910.         var battlelog = document.getElementsByName('_luxbot_battlelog');
  911.         for (i = 0; i < battlelog.length; i++) {
  912.             if (battlelog[i].checked == true) {
  913.                 db.put('battlelog', battlelog[i].value);
  914.                 break;
  915.             }
  916.         }
  917.        
  918.         db.put('securityfocus', document.getElementById('_luxbot_securitycheck').checked);
  919.        
  920.         db.put('bffilterna', document.getElementById('_luxbot_bffilterna').checked);
  921.         db.put('bffiltergold', document.getElementById('_luxbot_bffiltergold').value);
  922.         db.put('bffiltertff', document.getElementById('_luxbot_bffiltertff').value);
  923.        
  924.         db.put('option_clock', $("input[name='option_clock']:checked").val());
  925.         db.put('option_commandCenterStats', $("input[name='option_commandCenterStats']:checked").val());
  926.         db.put('option_Targets', $("input[name='option_Targets']:checked").val());
  927.         // db.put('option_sabTargets', $("input[name='option_sabTargets']:checked").val());
  928.         db.put('option_fakeSabTargets', $("input[name='option_fakeSabTargets']:checked").val());
  929.         db.put('option_goldProjection', $("input[name='option_goldProjection']:checked").val());
  930.         db.put('option_armory_graph', $("input[name='option_armory_graph']:checked").val());
  931.         db.put('option_armory_diff', $("input[name='option_armory_diff']:checked").val());
  932.        
  933.         toggleGUI();
  934.     }
  935.    
  936.  
  937.    
  938.  
  939.     //
  940.     // Sab Targets Button
  941.     //
  942.    
  943.     function sabTargetsButton() {
  944.    
  945.         var html = '<table class="table_lines" id="_luxbot_targets_table" width="100%" cellspacing="0" cellpadding="6" border="0">'
  946.         html += '<tr><td><input type="button" id="getTodaysSabs" value="View Your Sabs" /></td></tr><tr><td id="_sab_content">Loading... Please wait...</td></tr> </table>';
  947.         showMessage(html);
  948.         getSabTargets();
  949.    
  950.    }
  951.  
  952.     function getTodaysSabs() {
  953.        getLux('&a=getTodaysSabs',
  954.             function(r) {
  955.                 document.getElementById('_sab_content').innerHTML = r.responseText;
  956.                 document.getElementById('getTodaysSabs').value="View Sab List";
  957.                 document.getElementById('getTodaysSabs').addEventListener('click',getSabTargets,true);
  958.                 document.getElementById('getTodaysSabs').removeEventListener('click',getTodaysSabs,false);
  959.         });    
  960.     }
  961.  
  962.     function getSabTargets() {
  963.         getLux('&a=getsabtargets',
  964.             function(r) {
  965.                 if ( r.responseText != '403' ) {
  966.                     document.getElementById('_sab_content').innerHTML = r.responseText;
  967.                 }
  968.                
  969.                 var q = document.getElementsByName('_luxbot_targets_t');
  970.                 for (i = 0; i < q.length; i++) {
  971.                     q[i].addEventListener('click', function(e){GM_openInTab('http://www.kingsofchaos.com/attack.php?id=' + String(e.target.id).replace(/__/, ''))}, true);
  972.                 }
  973.                
  974.                 document.getElementById('getTodaysSabs').value="View Your Sabs";
  975.                 document.getElementById('getTodaysSabs').addEventListener('click',getTodaysSabs,true);
  976.                 document.getElementById('getTodaysSabs').removeEventListener('click',getSabTargets,false);
  977.  
  978.             });
  979.     }
  980.  
  981.  
  982.     //
  983.     // Attack Targets Button
  984.     //
  985.     function html_row(col1,col2) {
  986.         return "<tr><td>"+col1+"</td><td>"+col2+"</td></tr>";
  987.     }
  988.     function showFarmList() {
  989.         searchtype = GM_getValue("searchtype", 0);
  990.         goldInputType = db.get("goldinput", 0);
  991.         tffInputType = db.get("tffinput", 0);
  992.         daInputType = db.get("dainput", 0);
  993.        
  994.         maxDa = db.get("maxDa", 1000);
  995.         minTff = db.get("minTff", 10);
  996.         minGold = db.get("minGold", 0);
  997.         maxSeconds = db.get("maxSeconds", 120);
  998.        
  999.         saMultiplier = db.get("saMultiplier", .80);
  1000.         tffAdder = db.get("tffAdder", 50);
  1001.        
  1002.          var html = '<table class="table_lines" id="_luxbot_targets_table" width="100%" cellspacing="0" cellpadding="6" border="0">'
  1003.         +'<tr><th colspan="7">Master Targets (Loading)</th></tr>'
  1004.         +'<tr id="targetsFirstRow"><td><b>Name</b></td><td colspan="2" align="center"><b>Defensive Action</b></td><td align="center"><b>Total Fighting Force</b></td><td width=200 align="right"><b>Gold</b></td><td>&nbsp;</td><td>&nbsp;</td></tr>'
  1005.         +'<tr><th colspan="7">Settings</th></tr>'
  1006.         +'<tr><td colspan=7 id="targets_settings"> </td></tr>'
  1007.         +'</table>';
  1008.        
  1009.          
  1010.         var form1 = $("<fieldset style='width: 20%; padding:10px 0 5px 10%; float: left;' id='autofill'><legend>Autofill</legend></fieldset>");
  1011.             form1.append($("<label for=saMultiplier />").text("SA x "));
  1012.             form1.append($("<input type=text name=saMultiplier size=5/><br />").val(saMultiplier));
  1013.  
  1014.             form1.append($("<label for=tffAdder>").text("TFF + "));
  1015.             form1.append($("<input type=text name=tffAdder size=4/><br />").val(tffAdder));
  1016.             form1.append($("<input type=button id='targets_autofill' value='Autofill' /><br />"));
  1017.        
  1018.         var form2 = $("<fieldset style='width: 30%; padding:10px; float: left;' id='values'><legend>Filter Settings</legend></fieldset>");
  1019.             form2.append($("<label  class='tLabel' for=maxDa />").text("Max Defense: "));
  1020.             form2.append($("<input type=text name=maxDa /><br />").val(maxDa));
  1021.             form2.append($("<label class='tLabel' for=minTff>").text("Min TFF: "));
  1022.             form2.append($("<input type=text name=minTff /><br />").val(minTff));
  1023.             form2.append($("<label  class='tLabel' for=minGold>").text("Min Gold: "));
  1024.             form2.append($("<input type=text name=minGold /><br />").val(minGold));
  1025.             form2.append($("<label  class='tLabel' for=maxSeconds>").text("Max Gold Age: "));
  1026.             form2.append($("<input type=text name=maxSeconds /><br />").val(maxSeconds));
  1027.  
  1028.         var form3 = $("<fieldset style='width: 20%; padding:10px 0 5px 10%; float: left;' id='autofill'><legend>Reset / Save</legend></fieldset>");
  1029.             form3.append($("<input type=button id='targets_refresh' value='Refresh' /><br /><br />"));
  1030.             form3.append($("<input type=button id='targets_save' value='Save' /><br />"));
  1031.             form3.append($("<input type=button id='targets_reset' value='Reset' /> "));
  1032.  
  1033.         showMessage(html);
  1034.         $("#targets_settings").append(form1);  
  1035.         $("#targets_settings").append(form2);  
  1036.         $("#targets_settings").append(form3);  
  1037.            
  1038.         $("#targets_refresh").click(function() {
  1039.             getTargets();
  1040.         });        
  1041.         $("#targets_autofill").click(function() {
  1042.             var tffAdd = $("input[name='tffAdder']").val();
  1043.             var saMult = $("input[name='saMultiplier']").val();
  1044.             $("input[name='minTff']").val(Math.floor(User.tff.int()+tffAdd.int()));
  1045.             $("input[name='maxDa']").val(Math.floor(User.sa.int() * saMult ));
  1046.         });
  1047.         $("#targets_reset").click(function() {
  1048.             $("input[name='minTff']").val(10);
  1049.             $("input[name='maxDa']").val(1000);
  1050.             $("input[name='minGold']").val(0);
  1051.             $("input[name='maxSeconds']").val(120);
  1052.             $("input[name='saMultiplier']").val(0.80);
  1053.             $("input[name='tffAdder']").val(50);
  1054.         });
  1055.         $("#targets_save").click(function() {
  1056.             db.put("maxDa", $("input[name='maxDa']").val().int().toString());
  1057.             db.put("minTff", $("input[name='minTff']").val().int());
  1058.             db.put("minGold", $("input[name='minGold']").val().int());
  1059.             db.put("maxSeconds", $("input[name='maxSeconds']").val().int());
  1060.             db.put("saMultiplier", $("input[name='saMultiplier']").val().float().toString());
  1061.             db.put("tffAdder", $("input[name='tffAdder']").val().int());
  1062.             getTargets();
  1063.  
  1064.         });
  1065.          
  1066.         getTargets();
  1067.        
  1068.     }
  1069.    
  1070.     function getTargets() {
  1071.         $(".targetTR").remove();
  1072.         getLux('&a=gettargets&g=' + db.get('minGold',0) + '&t=' + db.get('minTff', 0) + '&d=' + db.get('maxDa', 0) + '&q=' + db.get('maxSeconds', 0),
  1073.            function(r) {
  1074.                 var x = r.responseText.split(';');
  1075.                 var html="";
  1076.                 for(i = 0; i < x.length-1; i++) {
  1077.                     row = x[i].split(':');
  1078.                     html += '<tr class="targetTR"><td><a href="/stats.php?id=' + row[1] + '">' + row[0] + '</a></td><td align="right">' + (row[3]) + '</td><td>(' + row[4] + ')</td><td align="center">' + row[2] + '</td>'
  1079.                     +'<td align="right">'
  1080.                         +'<span class="gold">' + row[5] + '</span>'
  1081.                         +'<span class="projection" style="display:none;">Projected: '+row[7] + '</span>' +
  1082.                     '</td><td align="left">(' +row[6] + ')</td><td align="right"><input type="button" value="Attack" style="cursor:pointer" name="_luxbot_targets_t" id="__' + row[1] + '"></td></tr>';
  1083.                 }
  1084.                 $("#targetsFirstRow").after(html);
  1085.                
  1086.                
  1087.                 //$(".projection").hide();
  1088.                 $(".projection").css("color","#B3FFF8");
  1089.                 $(".targetTR").hover(
  1090.                   function () {
  1091.                     //alert("on");
  1092.                     $(this).find(".gold").hide();
  1093.                     $(this).find(".projection").show();
  1094.                   },
  1095.                   function () {
  1096.                   //alert("off");
  1097.                     $(this).find(".gold").show();
  1098.                     $(this).find(".projection").hide();              
  1099.                 });
  1100.  
  1101.             });    
  1102.     }
  1103.    
  1104.     function showFakeSabList() {
  1105.    
  1106.         var html = '<table class="table_lines" id="_luxbot_targets_table" width="100%" cellspacing="0" cellpadding="6" border="0">'
  1107.         html += '<tr><td id="_sab_content">Loading... Please wait...</td></tr> </table>';
  1108.         showMessage(html);
  1109.         getFakeSabTargets();
  1110.    }
  1111.  
  1112.     function getFakeSabTargets() {
  1113.         //GM_log('http://' + serverURL + 'targets.php?username=' + username + '&password=' + password + '&g=' + GM_getValue('mingold', stats['goldx']) + '&t=' + GM_getValue('mintff', stats['tffx']) + '&d=' + GM_getValue('minda', stats['dax']) + '&a=' + GM_getValue('minage', 120));
  1114.         getLux('&a=getfakesabtargets',
  1115.             function(r) {
  1116.                 if ( r.responseText != '403' ) {
  1117.                     document.getElementById('_sab_content').innerHTML = r.responseText;
  1118.                 }
  1119.                
  1120.                 var q = document.getElementsByName('_luxbot_targets_t');
  1121.                 for (i = 0; i < q.length; i++) {
  1122.                     q[i].addEventListener('click', function(e){GM_openInTab('http://www.kingsofchaos.com/attack.php?id=' + String(e.target.id).replace(/__/, ''))}, true);
  1123.                 }
  1124.                
  1125.                 document.getElementById('getTodaysSabs').value="View Your Sabs";
  1126.                 document.getElementById('getTodaysSabs').addEventListener('click',getTodaysSabs,true);
  1127.                 document.getElementById('getTodaysSabs').removeEventListener('click',getSabTargets,false);
  1128.  
  1129.             });
  1130.     }
  1131.  
  1132.  
  1133.  
  1134.  
  1135.  
  1136.  
  1137.     //
  1138.     // GENERAL
  1139.     //
  1140.        
  1141.     function checkForUpdate(startup) {
  1142.         if (db.get("luxbot_version",0) != version) {
  1143.             //if the version changes
  1144.             db.put("luxbot_version",version);
  1145.             db.put("luxbot_needsUpdate",0);
  1146.         }
  1147.         if (startup == 1 && db.get("luxbot_needsUpdate",0) == 1) {
  1148.             setTimeout(function() {
  1149.                 $("#_luxbot_gui>ul").append("<li id='getUpdate' style='padding-top:5px;color:yellow'>Get Update!</li>");
  1150.                 $("#getUpdate").click(function() {
  1151.                     GM_openInTab('http://' + serverURL + 'luxbot.user.js');
  1152.                 });
  1153.             },1000);
  1154.             return;
  1155.         }
  1156.        
  1157.         var now = new Date();
  1158.         var lastCheck = db.get('luxbot_lastcheck', 0);
  1159.  
  1160.         if (startup != 1 || (now - new Date(lastCheck)) > (60*1000)) {
  1161.             GM_xmlhttpRequest({
  1162.                 method: 'GET',
  1163.                 url: 'http://' + serverURL + 'luxbot.version.php',
  1164.                 onload: function(responseDetails) {
  1165.                         var latestVersion = Number(responseDetails.responseText.replace(/\./, ''));
  1166.                         var thisVersion = Number(version.replace(/\./, ''));
  1167.                         if (latestVersion > thisVersion){
  1168.                             db.put("luxbot_needsUpdate",1);
  1169.                             db.put("luxbot_version",version);
  1170.                             if (startup != 1) {
  1171.                                 alert("There is an update!");
  1172.                                 GM_openInTab('http://' + serverURL + 'luxbot.user.js');
  1173.                             }
  1174.                         } else if (startup != 1) {
  1175.                             alert("You are up to date!");
  1176.                         }
  1177.                 }
  1178.             });
  1179.             db.put('luxbot_lastcheck', now.toString());
  1180.         }
  1181.     }
  1182.    
  1183.     function checkUser() {
  1184.  
  1185.         if (User.forumName == 0 || User.forumPass == 0 || User.forumName == undefined || User.forumPass == undefined || User.auth == undefined || User.auth == 0 || User.auth.length != 32) {
  1186.             showInitBox();
  1187.             return 0;
  1188.         } else {
  1189.             addGUILink('User Options', gui_showUserOptions, "#_luxbot_nav_div");
  1190.             addGUILink('Show Messages (loading...)', showMessageBox, "#_luxbot_nav_div");
  1191.             addGUILink('Change Account',showInitBox,"#_luxbot_nav_div");
  1192.             addGUILink('Change Log',gui_showChangeLog,"#_luxbot_nav_div");
  1193.            
  1194.             getLux('&a=vb_auth',
  1195.                 function(r) {
  1196.                     if (r.responseText == '403') {
  1197.                         showInitBox();
  1198.                         return 0;
  1199.                     }
  1200.                    
  1201.                     var x = r.responseText.split(';');
  1202.                     logself = x.shift();
  1203.                     // GM_setValue('logself', logself);
  1204.                    
  1205.                     stats = {'tffx':x.shift(), 'dax':x.shift(), 'goldx':x.shift()};
  1206.                    
  1207.                     document.getElementById('_luxbot_showMessageBox').innerHTML = 'Show Messages (' + (x.length-1) + ')';
  1208.                     messages = x;
  1209.                    
  1210.                     if (messages.pop() == '1') {
  1211.                         showMessageBox();
  1212.                     }
  1213.                 });
  1214.            
  1215.             return 1;
  1216.         }
  1217.         return 1;
  1218.     }
  1219.  
  1220.     function addCSS(cssText) {
  1221.         $("head").append("<style>"+cssText+"</style>");
  1222.     }
  1223.    
  1224.     function addJS(jsText) {
  1225.         //$("head").append('<script>'+jsText+'</script>');
  1226.        
  1227.        
  1228.         var head = document.getElementsByTagName("head")[0];
  1229.         if (!head) {
  1230.             return;
  1231.         }
  1232.         var style = document.createElement("script");
  1233.         style.type = "text/javascript";
  1234.         style.innerHTML = jsText;
  1235.         head.appendChild(style);
  1236.        
  1237.     }
  1238.    
  1239.     function striptags(html) {
  1240.         var re= /<\S[^>]*>/g;
  1241.         return html.replace(re, " ").replace(/^\s+|\s+$/g, '');
  1242.     }
  1243.    
  1244.     function addCommas(sValue) { //"addCommas function wrote by Lukas Brueckner..." thanks =) but not really true ^.^
  1245.  
  1246.     sValue = String(sValue);
  1247.         var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
  1248.        
  1249.         while(sRegExp.test(sValue)) {
  1250.             sValue = sValue.replace(sRegExp, '$1,$2');
  1251.         }
  1252.         return sValue;
  1253.     }
  1254.    
  1255.  
  1256.     //
  1257.     // LOGGING
  1258.     //
  1259.     function getLux(url, callback) {
  1260.         address= baseURL+'&username='+User.nick+'&password=' + User.forumPass +'&auth=' + User.auth + url;
  1261.         GM_log("Get URL: " +address);
  1262.         GM_xmlhttpRequest({
  1263.             method: 'GET',
  1264.             url: address,
  1265.             headers: {
  1266.                 'User-agent': 'Mozilla/4.0 (compatible)',
  1267.                 'Accept': 'application/atom+xml,application/xml,text/xml',
  1268.             },
  1269.             onload: function(r) {
  1270.                 //alert(url+"\n"+r.responseText);
  1271.                 if (callback)
  1272.                     callback(r);
  1273.             }
  1274.         });
  1275.     }    
  1276.  
  1277.     function postLux(url, data, callback) {
  1278.         address= baseURL+'&username='+User.nick+'&password=' + User.forumPass +'&auth=' + User.auth + url;
  1279.         GM_log("Post URL: "+ address);
  1280.         GM_xmlhttpRequest({
  1281.             method: "POST",
  1282.             url: address,
  1283.             headers:{'Content-type':'application/x-www-form-urlencoded'},
  1284.             data:encodeURI(data),
  1285.             onload: function(r) {
  1286.                 if (callback)
  1287.                     callback(r);
  1288.             }
  1289.             });
  1290.     }
  1291.  
  1292.     function post(url, data,debug) {
  1293.         GM_xmlhttpRequest({
  1294.             method: "POST",
  1295.             url: url,
  1296.             headers:{'Content-type':'application/x-www-form-urlencoded'},
  1297.             data:encodeURI(data),
  1298.             onload: function(r,debug) {
  1299.                 if(debug == true) {
  1300.                     alert('Information sent. ' + r.responseText);
  1301.                 }
  1302.             }
  1303.             });
  1304.     }
  1305.  
  1306.     function sendLogDetails(user, opponent, oppid, siege, data, weaponstring,officers, logid) {
  1307.         getLux('&a=logspy&user=' + user +
  1308.                                 '&enemy=' + opponent + ';' + oppid + ';' + siege +
  1309.                                 '&data=' + data +
  1310.                                 '&weapons=' + weaponstring +
  1311.                                 '&officers=' + officers +
  1312.                                 '&logid=' + logid,
  1313.                     function(responseDetails) {
  1314.                             GM_log("SendLogDetails Response: "+ responseDetails.responseText);
  1315.                             // alert(responseDetails.responseText);
  1316.                     });
  1317.     }
  1318.    
  1319.  
  1320.  
  1321.     //
  1322.     // Command Center Functions
  1323.     //
  1324.    
  1325.     function basePage() {
  1326.         db.put('race', TextBetween($("head>link").eq(3).attr("href"),"css/",".css"));
  1327.  
  1328.         var stable = $("table:contains('Military Effectiveness')").last();
  1329.         var sa = $(stable).find("tr:contains('Strike Action'):first>td:eq(1)").text();
  1330.         var da = $(stable).find("tr:contains('Defensive Action'):first>td:eq(1)").text();
  1331.         var spy = $(stable).find("tr:contains('Spy Rating'):first>td:eq(1)").text();
  1332.         var sentry = $(stable).find("tr:contains('Sentry Rating'):first>td:eq(1)").text();
  1333.  
  1334.        
  1335.         stable = $("table:contains('Military Overview')").last();
  1336.         var fort = $(stable).find("tr:contains('Fortification'):first>td:eq(1)").text();
  1337.         var siege = $(stable).find("tr:contains('Siege Technology'):first>td:eq(1)").text();
  1338.         var economy = $(stable).find("tr:contains('Economy'):first>td:eq(1)").text();
  1339.         var technology = $(stable).find("tr:contains('Technology'):last>td:eq(1)").text();
  1340.         var conscription = $(stable).find("tr:contains('Conscription'):first>td:eq(1)").text();
  1341.         conscription = conscription.substr(0, conscription.indexOf(' soldiers'));
  1342.         var tff = $("body").find("tr:contains('Total Fighting Force'):last>td:eq(1)").text();
  1343.         var turns = $(stable).find("tr:contains('Game Turns'):first>td:eq(1)").text();
  1344.         turns = turns.substr(0,turns.indexOf(" /"));
  1345.         var covertlevel = $(stable).find("tr:contains('Covert Level'):first>td:eq(1)").text();
  1346.         var income = $(stable).find("tr:contains('Projected Income'):first>td:eq(1)").text();
  1347.         income = income.substr(0,income.indexOf(" Gold")).int();
  1348.  
  1349.         officers = stats_getOfficers(false);
  1350.  
  1351.         var bonus = TextBetween($(".officers>tbody>tr:last").text(), "(x ",")");
  1352.        
  1353.         nav();
  1354.        
  1355.         db.put('sa',sa);
  1356.         db.put('da',da);
  1357.         db.put('spy',spy);
  1358.         db.put('sentry',sentry);
  1359.         db.put('income',income + "");
  1360.         db.put('tff',tff);
  1361.        
  1362.         logBase(sa.int() + ";"+da.int()+";"+spy.int()+";"+sentry.int(), fort+";"+siege+";"+economy+";"+technology+";"+conscription.int()+";"+turns.int()+";"+covertlevel+";"+bonus, officers);
  1363.     }
  1364.    
  1365.     function logBase(stats, data, officers) {
  1366.         //stats=sa;da;spy;sentry;
  1367.         //details=fort;siege;econ;tech;conscription;turns;covertlevel;bonus
  1368.                            
  1369.         getLux('&a=base' +
  1370.                 '&stats=' + stats +
  1371.                 '&data=' + data +
  1372.                 '&officers=' + officers,
  1373.             function(responseDetails) {
  1374.                     GM_log("LogBase: "+ responseDetails.responseText);
  1375.         });
  1376.     }
  1377.  
  1378.  
  1379.     //
  1380.     // Conquest Page Functions
  1381.     //
  1382.    
  1383.     function conquestPage() {
  1384.    
  1385.         function doConquest() {
  1386.             // var count = 1 + to_int($("#wCount").text());
  1387.             // $("#wCount").text('Wizards (x'+count+')');
  1388.             // post("http://www.kingsofchaos.com/conquest.php",
  1389.                 // "conquest_target=Wizards&conquest=Go+on+a+conquest+against+Wizards%21&hash=",false);
  1390.  
  1391.             $("tr:contains('Wizards')").last().find("input[type='submit']").click();;//last().submit();
  1392.         }
  1393.        
  1394.         if ($("table.table_lines>tbody>tr").size() > 10) {
  1395.             $("table.table_lines>tbody>tr:eq(2)").before("<tr><td id='wCount'>Wizards (x0)</td><td align='right'>1,000,000,000</td><td align='center'><button style='width:90%' id='doCon'>Go on a conquest against Wizards!</button></td></tr>");
  1396.             $("#doCon").click(doConquest);
  1397.         }
  1398.     }
  1399.    
  1400.     function SendConquestDetails(contype) {
  1401.         getLux('a=logcon&contype=' + contype);
  1402.     }
  1403.    
  1404.  
  1405.  
  1406.     //
  1407.     // Armory Page Functions
  1408.     //
  1409.    
  1410.     function armoryPage()  {
  1411.         var spyWeaps = Array("Rope","Dirk","Cloak","Grappling Hook","Skeleton Key","Nunchaku");
  1412.         var sentryWeaps = Array("Big Candle","Horn","Tripwire","Guard Dog","Lookout Tower");    
  1413.         var daWeaps = Array('Helmet', 'Shield','Chainmail','Plate Armor', 'Mithril', 'Elven Cloak', 'Gauntlets', 'Heavy Shield', 'Dragonskin', 'Invisibility Shield')  
  1414.         spyWeaps = spyWeaps.join(",");
  1415.         sentryWeaps = sentryWeaps.join(",");
  1416.         daWeaps = daWeaps.join(",");
  1417.        
  1418.         var stable = $("table:contains('Military Effectiveness')").last();
  1419.         var sa = $(stable).find("tr:contains('Strike Action'):first>td:eq(1)").text();
  1420.         var da = $(stable).find("tr:contains('Defensive Action'):first>td:eq(1)").text();
  1421.         var spy = $(stable).find("tr:contains('Spy Rating'):first>td:eq(1)").text();
  1422.         var sentry = $(stable).find("tr:contains('Sentry Rating'):first>td:eq(1)").text();
  1423.         if (checkOption('option_armory_diff'))
  1424.             armory_diff(sa,da,spy,sentry);
  1425.                
  1426.         //Send Armory to Luxbot
  1427.         var spyWeapsQty = 0;
  1428.         var sentryWeapsQty = 0;
  1429.         var daWeapsQty = 0;
  1430.         var saWeapsQty = 0;
  1431.        
  1432.         function retrieveWeapons(str) {
  1433.             //name:qty:repair
  1434.             var str = str.split("\n");
  1435.             str[1] = str[1].split(" (")[0];
  1436.            
  1437.             if (spyWeaps.instr($.trim(str[1])))
  1438.                 spyWeapsQty +=  $.trim(str[2]).int();
  1439.             else if (sentryWeaps.instr($.trim(str[1])))
  1440.                 sentryWeapsQty +=  $.trim(str[2]).int();
  1441.             else if (daWeaps.instr($.trim(str[1])))
  1442.                 daWeapsQty += $.trim(str[2]).int();
  1443.             else
  1444.                 saWeapsQty +=  $.trim(str[2]).int();
  1445.                
  1446.             return $.trim(str[1]) + ':' + $.trim(str[2]) + ':' + $.trim(str[3]) + ';';
  1447.         }
  1448.  
  1449.         // This will be sent to luxbot server.
  1450.         var tempvar = '';
  1451.        
  1452.         // gets an array of weapons and tools
  1453.         var arr = $("input[name='doscrapsell']").parent().parent().parent().parent().parent().parent();
  1454.  
  1455.  
  1456.         arr.each(function(){
  1457.             tempvar+=retrieveWeapons($(this).text());
  1458.         });
  1459.        
  1460.         sabLogs_update(tempvar);
  1461.         sabLogs_init();
  1462.        
  1463.         armory_upgradeSuggestions(User);
  1464.         armory_aat();
  1465.         db.put('sa',sa);
  1466.         db.put('da',da);
  1467.         db.put('spy',spy);
  1468.         db.put('sentry',sentry);
  1469.         db.put('sentryWeaps',sentryWeapsQty);
  1470.         db.put('spyWeaps',spyWeapsQty);
  1471.         db.put('daWeaps',daWeapsQty);
  1472.         db.put('saWeaps',saWeapsQty);
  1473.        
  1474.         postLux('&a=armory', '&data='+tempvar); // pass the info to the db. // DEBUG //     alert(tempvar);
  1475.        
  1476.         if (checkOption('option_armory_graph'))
  1477.             armory_stats();
  1478.     }  
  1479.  
  1480.     function armory_stats() {
  1481.         addCSS("#container {max-width:500px;height:300px;}");
  1482.         $(".personnel").before('<table class="table_lines" width="100%" cellspacing="0" cellpadding="6" border="0"><tbody><tr><th>Armory Value Stats</th></tr><tr><td><div id="container"></div></td></tr></tbody></table><br />');
  1483.  
  1484.         getLux('&a=armoryStats',function(a) {
  1485.            
  1486.                 window.chart = new Highcharts.StockChart({
  1487.                     chart : {
  1488.                         renderTo : 'container',
  1489.                         zoom : 'none',
  1490.                         // width: '100%'
  1491.                     },
  1492.                     rangeSelector: {
  1493.                         enabled: false,
  1494.                     },
  1495.                     scrollbar : {
  1496.                         enabled : false,
  1497.                     },
  1498.                     yAxis: {
  1499.                         min: 0,
  1500.                         // startOnTick: false,
  1501.                         // endOnTick: false    
  1502.                     },
  1503.  
  1504.                     title : {
  1505.                         text : 'Armory Value'
  1506.                     },
  1507.                    
  1508.                     series : [{
  1509.                         name : 'Weapon Value',
  1510.                         data : $.parseJSON(a.responseText),
  1511.                         tooltip: {
  1512.                             valueDecimals: 0
  1513.                         }
  1514.                     }]
  1515.                 });    
  1516.             });
  1517.         }
  1518.        
  1519.     function armory_diff(sa,da,spy,sentry) {
  1520.    
  1521.         function describeDiff(diff,total) {
  1522.             if (diff == 0)
  1523.                 return '<span style="color:white"> + '+diff+'</span></td><td>&nbsp;';
  1524.             else if (diff < 0)
  1525.                 diff = '<span style="color:red"> '+addCommas(diff)+'</span></td><td>&nbsp;&nbsp;<span style="color:red">  '+(diff/total ).toFixed(4)+' %</span>';
  1526.             else
  1527.                 diff = '<span style="color:green"> + '+addCommas(diff)+'</td><td>&nbsp;&nbsp;<span style="color:green">  + '+(diff/total).toFixed(4)+' %</span>';
  1528.             return diff;
  1529.         }
  1530.        
  1531.         $("#military_effectiveness").after('<table id="armory_diff" class="table_lines" width="100%" cellspacing="0" cellpadding="6" border="0"><tbody id="diffFirstRow"><tr><th colspan=3>Stats Differences</th></tr></tbody></table>');
  1532.        
  1533.         $("#diffFirstRow").append("<tr><td>Strike Action: </td><td>"+describeDiff(sa.int() - User.sa.int(),User.sa.int())+"</td></tr>");
  1534.         $("#diffFirstRow").append("<tr><td>Defensive Action: </td><td>"+describeDiff(da.int() - User.da.int(),User.da.int())+"</td></tr>");
  1535.         $("#diffFirstRow").append("<tr><td>Spy: </td><td>"+describeDiff(spy.int() - User.spy.int(),User.spy.int())+"</td></tr>");
  1536.         $("#diffFirstRow").append("<tr><td>Sentry: </td><td>"+describeDiff(sentry.int() - User.sentry.int(),User.sentry.int())+"</td></tr>");
  1537.    
  1538.     }
  1539.     function armory_buyButton() {
  1540.         var html ='<td colspan="5" align="center"><br><input name="buybut" type="submit" value="Buy Weapons" onclick="document.buyform.buybut.value="Buying.."; document.buyform.buybut.disabled=true; document.buyform.submit();"><br><br></td>';        
  1541.  
  1542.         $("#buy_weapons_form>tbody>tr").eq(1).before("<tr>"+html+"</tr>");
  1543.     }
  1544.    
  1545.     function sabLogs_update(weapList) {
  1546.         weapList = ';'+weapList;    //this is hack is important because of "shield" vs "invis shield"
  1547.  
  1548.         var d = new Date()
  1549.         var time = "" + d.getTime() + "";
  1550.  
  1551.         var old_weapList = db.get('lux_weaponList', '');
  1552.         old_weapList = old_weapList.split(';');
  1553.         var losses = '';
  1554.         $(old_weapList).each(function (i,e) {
  1555.             if (e) {
  1556.                 var weapName = e.split(':')[0];
  1557.                 var old_weapCount = parseInt(e.split(':')[1].replace(/[^0-9]/g,''));
  1558.                
  1559.                 //notice we search for weapName after a semi-colon, explaining prev hack.
  1560.                 var new_weapCount = parseInt(TextBetween(weapList, ';'+weapName+':', ':').replace(/[^0-9]/g,''));
  1561.                
  1562.                 if (old_weapCount > new_weapCount) {
  1563.                     losses += (old_weapCount-new_weapCount) +":"+weapName +":"+time+";";
  1564.                 }
  1565.                 //handle if it is no longer in the list
  1566.                 if (weapList.indexOf(';'+weapName+':')== -1) {
  1567.                     losses += (old_weapCount) +":"+weapName+":"+time +";";
  1568.                 }
  1569.             }
  1570.         });
  1571.        
  1572.         if (losses != '') {
  1573.             var arr = losses.split(';');
  1574.             var i=0;
  1575.             var h ="";
  1576.             for (i=0;i<=arr.length;i++) {
  1577.                 if(arr[i]){
  1578.                     var cols = arr[i].split(":");
  1579.                     h += "You have lost "+ cols[0] + " "+cols[1]+"s<br />";
  1580.                 }
  1581.             }
  1582.  
  1583.            
  1584.            
  1585.             addCSS("#_lux_sabbed_popup {text-align:center;border-top: 5px solid red; border-left: 5px solid red; border-right: 5px solid darkred; border-bottom: 5px solid darkred;position:fixed;right:10px;bottom:10px;width:auto;}");
  1586.            
  1587.             $("body").append("<table id='_lux_sabbed_popup'><tbody><tr><th>Attention!</th></tr></tbody></table>");
  1588.             $('#_lux_sabbed_popup>tbody').append("<tr><td>"+h+"</td></tr>");
  1589.            
  1590.            
  1591.             old_losses = db.get('lux_lostWeapons','');
  1592.             db.put('lux_lostWeapons', losses + old_losses);
  1593.         }
  1594.         db.put('lux_weaponList', weapList);
  1595.     }
  1596.  
  1597.     function sabLogs_init() {
  1598.         $("#military_effectiveness").before('<table id="_lux_sabbed" class="table_lines" width="100%" cellspacing="0" cellpadding="6" border="0"></table>');
  1599.         $("#buy_weapons_form").before('<table id="_lux_upgrades" class="table_lines" width="100%" cellspacing="0" cellpadding="6" border="0"></table>');
  1600.         sabLogs_display();
  1601.     }
  1602.    
  1603.     function sabLogs_display() {
  1604.         var losses = db.get('lux_lostWeapons','').split(';');
  1605.    
  1606.         $("#_lux_sabbed").html('<table class="table_lines" width="100%" cellspacing="0" cellpadding="6" border="0"><tbody><tr><th colspan=2>Lost Weapons Log </th></tr><tr><td colspan=2 style="border-bottom:none"><div id="lux_sablogs_2"></div></td></tr></tbody></table>');
  1607.         $("#lux_sablogs_2").html('<table width="100%" cellspacing="0" cellpadding="6" border="0"><tbody></tbody></table>');
  1608.        
  1609.         for (i=0;i<5;i++) {
  1610.             if(losses[i]){
  1611.                 var cols = losses[i].split(':');
  1612.                 $("#lux_sablogs_2>table>tbody").append("<tr><td>"+cols[0]+" "+cols[1]+"s</td><td align=right>"+timeElapsed(cols[2])+"</td></tr>");
  1613.             }
  1614.         }
  1615.         $("#lux_sablogs_2>table>tbody").append("<tr><td>(<a id='viewSablog'>View All</a>)</td><td>(<a id='clearSablog'>Clear</a>)</td></tr>");
  1616.         $("#clearSablog").click(function() { sabLogs_clear();});
  1617.         $("#viewSablog").click(function() { sabLogs_viewAll();});
  1618.     }
  1619.    
  1620.     function sabLogs_clear() {
  1621.         db.put("lux_lostWeapons",'');
  1622.         $("#lux_sablogs_2>table>tbody>tr>td").parent().remove();
  1623.     }
  1624.    
  1625.     function sabLogs_viewAll() {
  1626.         $("#lux_sablogs_2").css("overflow-y","scroll");
  1627.         $("#lux_sablogs_2").css("height","180px");
  1628.         var losses = db.get('lux_lostWeapons','').split(';');
  1629.         $("#lux_sablogs_2>table>tbody>tr>td").parent().remove();
  1630.        
  1631.         for (i=0;i<losses.length;i++) {
  1632.             if(losses[i]){
  1633.                 var cols = losses[i].split(':');
  1634.                 $("#lux_sablogs_2>table>tbody").append("<tr><td>"+cols[0]+" "+cols[1]+"s</td><td align=right>"+timeElapsed(cols[2])+"</td></tr>");
  1635.             }
  1636.         }
  1637.         $("#_lux_sabbed>table>tbody").append("<tr><td>(<a id='viewSablogLess'>View Less</a>)</td><td>(<a id='clearSablog'>Clear</a>)</td></tr>");
  1638.         $("#clearSablog").click(function() { sabLogs_clear();});
  1639.         $("#viewSablogLess").click(function() { sabLogs_display();});
  1640.     }
  1641.  
  1642.     function armory_aat() {
  1643.         var sellVal = 0;
  1644.         $("input[name='doscrapsell']").each(function(i,e) {
  1645.             var row = $(e).parents("tr").eq(1);    
  1646.             var qty = to_int($(row).children("td").eq(1).text());
  1647.             var cost = to_int($(e).val());
  1648.    
  1649.             sellVal += qty*cost;
  1650.         });
  1651.         retailValue = sellVal*10/7;
  1652.        
  1653.        
  1654.         $("input[name='doscrapsell']").each(function(i,e) {
  1655.             var row = $(e).parents("tr").eq(1);    
  1656.             var cost = to_int($(e).val());
  1657.             $(row).children("td:eq(0)").append(" (" + Math.floor(retailValue / 400 / (cost*10/7)) + " aat)");
  1658.         });    
  1659.        
  1660.         $("table.table_lines:eq(0)>tbody>tr:eq(0)>th").append(" (Total Sell Off Value: "+ addCommas(sellVal)+" Gold)");
  1661.     }
  1662.    
  1663.     function armory_upgradeSuggestions(User) {
  1664.  
  1665.         var gold = User.gold;
  1666.         function get_da(fort){
  1667.             var cb = 0;
  1668.             if (fort == "Camp") cb = 0;
  1669.             if (fort == "Stockade") cb = 1;
  1670.             if (fort == "Rabid") cb = 2;
  1671.             if (fort == "Walled") cb = 3;
  1672.             if (fort == "Towers") cb = 4;
  1673.             if (fort == "Battlements") cb = 5;
  1674.             if (fort == "Portcullis") cb = 6;
  1675.             if (fort == "Boiling Oil") cb = 7;
  1676.             if (fort == "Trenches") cb = 8;
  1677.             if (fort == "Moat") cb = 9;
  1678.             if (fort == "Drawbridge") cb = 10;
  1679.             if (fort == "Fortress") cb = 11;
  1680.             if (fort == "Stronghold") cb = 12;
  1681.             if (fort == "Palace") cb = 13;
  1682.             if (fort == "Keep") cb = 14;
  1683.             if (fort == "Citadel") cb = 15;
  1684.             if (fort == "Hand of God") cb = 16;
  1685.             //cb = Math.pow(1.25,cb);
  1686.             //cb = Math.round(cb*1000)/1000;
  1687.             return cb;
  1688.         }
  1689.  
  1690.         function get_sa(siege){
  1691.             var cb = 0;
  1692.             if (siege == "None") cb = 0;
  1693.             if (siege == "Flaming Arrows") cb = 1;
  1694.             if (siege == "Ballistas") cb = 2;
  1695.             if (siege == "Battering Rams") cb = 3;
  1696.             if (siege == "Ladders") cb = 4;
  1697.             if (siege == "Trojan") cb = 5;
  1698.             if (siege == "Catapults") cb = 6;
  1699.             if (siege == "War Elephants") cb = 7;
  1700.             if (siege == "Siege Towers") cb = 8;
  1701.             if (siege == "Trebuchets") cb = 9;
  1702.             if (siege == "Black Powder") cb = 10;
  1703.             if (siege == "Sappers") cb = 11;
  1704.             if (siege == "Dynamite") cb = 12;
  1705.             if (siege == "Greek Fire") cb = 13;
  1706.             if (siege == "Cannons") cb = 14;
  1707.             //cb = Math.pow(1.3,cb);
  1708.             //cb = Math.round(cb*1000)/1000;
  1709.             return cb;
  1710.         }
  1711.  
  1712.  
  1713.         var race = User.race;
  1714.         var da_race_factor = 1;
  1715.         var sa_race_factor = 1;
  1716.         if (race == "Dwarfs")
  1717.             da_race_factor = 1.4;
  1718.         if (race == "Orcs") {
  1719.             da_race_factor = 1.2;
  1720.             sa_race_factor = 1.35;
  1721.         }
  1722.  
  1723.         var fort = $("form:nth-child(4) td:nth-child(1)").text();
  1724.         fort = fort.substr(0,fort.indexOf("("));
  1725.         var siege = $("form:nth-child(5) td:nth-child(1)").text();
  1726.         siege = siege.substr(0,siege.indexOf("("));
  1727.        
  1728.         var da_factor = get_da($.trim(fort));
  1729.         var sa_factor = get_sa($.trim(siege));
  1730.  
  1731.  
  1732.        
  1733.         var t = $("#military_effectiveness");
  1734.         var sa = to_int($(t).find("tbody>tr:eq(1)>td:eq(1)").text());
  1735.         var da = to_int($(t).find("tbody>tr:eq(2)>td:eq(1)").text());
  1736.    
  1737.         //sure this can be optimized but cba right now
  1738.         var saCost = new Array(40000,80000,160000,320000,640000,1280000,2560000,5120000,10240000,20480000,40960000,81920000,163840000,327680000);
  1739.         var daCost = new Array(40000,80000,160000,320000,640000,1280000,2560000,5120000,10240000,20480000,40960000,81920000,163840000,327680000,655360000,1310720000);
  1740.  
  1741.         sa_cost = saCost[sa_factor];
  1742.         da_cost = daCost[da_factor];
  1743.        
  1744.             sa_bonus = Math.pow(1.3,sa_factor);
  1745.             sa_bonus_new = Math.pow(1.3,sa_factor+1);
  1746.             da_bonus = Math.pow(1.25,da_factor);
  1747.             da_bonus_new = Math.pow(1.25,da_factor+1);
  1748.        
  1749.         var sell_ivs = Math.ceil((da_cost - gold) / 700000 );
  1750.         var sell_bpms = Math.ceil((sa_cost - gold) / 700000 );
  1751.         var sell_chars = Math.ceil((sa_cost - gold) / 315000 );
  1752.         var sell_skins = Math.ceil((da_cost - gold) / 140000 );
  1753.        
  1754.             var valPerBPM = sa_race_factor * 1000 * 5 * ((db.get("Tech",100) +1)/ 100) * (db.get("Offiebonus",100) / 100);
  1755.             var valPerCHA = sa_race_factor * 600 * 5 * (db.get("Tech",100) / 100) * (db.get("Offiebonus",100) / 100);
  1756.             var valPerIS = da_race_factor * 1000 * 5 * (db.get("Tech",100) / 100) * (db.get("Offiebonus",100) / 100);
  1757.             var valPerDS = da_race_factor * 256 * 5 * (db.get("Tech",100) / 100) * (db.get("Offiebonus",100) / 100);   
  1758.        
  1759.         var weaps = db.get('lux_weaponList');
  1760.         if (weaps.instr("Invisibility Shield"))
  1761.             ivs = to_int(TextBetween(weaps,"Invisibility Shield:",":"));
  1762.         else
  1763.             ivs = 0;
  1764.         if (weaps.instr("Blackpowder Missile:"))
  1765.             bpms = to_int(TextBetween(weaps,"Blackpowder Missile:",":"));
  1766.         else
  1767.             bpms = 0;
  1768.         if (weaps.instr("Chariot:"))
  1769.             chars = to_int(TextBetween(weaps,"Chariot:",":"));
  1770.         else
  1771.             chars = 0;
  1772.         if (weaps.instr("Dragonskin:"))
  1773.             skins = to_int(TextBetween(weaps,"Dragonskin:",":"));
  1774.         else
  1775.             skins = 0;
  1776.        
  1777.        
  1778.         var oldDa = Math.floor((valPerDS * skins + valPerIS *ivs) *da_bonus);
  1779.         var oldSa = Math.floor((valPerCHA * chars + valPerBPM *bpms) *sa_bonus);
  1780.  
  1781.         var newDa_skins = 0;
  1782.         var newDa_ivs = 0;
  1783.         var newSa_chars = 0;
  1784.         var newSa_bpms = 0;
  1785.         if (skins >= sell_skins) {
  1786.             newDa_skins = valPerDS * (skins-sell_skins) + valPerIS *ivs;
  1787.             newDa_skins *= da_bonus_new;
  1788.             newDa_skins = Math.floor(newDa_skins);
  1789.         }
  1790.         if (ivs >= sell_ivs) {
  1791.             newDa_ivs = valPerDS *skins + valPerIS *(ivs-sell_ivs);
  1792.             newDa_ivs *= da_bonus_new;
  1793.             newDa_ivs = Math.floor(newDa_ivs);
  1794.  
  1795.         }
  1796.        
  1797.         if (chars >= sell_chars) {
  1798.             newSa_chars = valPerCHA *(chars - sell_chars) + valPerBPM*bpms;
  1799.             newSa_chars *= sa_bonus_new;
  1800.             newSa_chars = Math.floor(newSa_chars);
  1801.  
  1802.         }
  1803.         if (bpms >= sell_bpms) {
  1804.             newSa_bpms = valPerCHA *(chars) + valPerBPM*(bpms-sell_bpms);
  1805.             newSa_bpms *= sa_bonus_new;
  1806.             newSa_bpms = Math.floor(newSa_bpms);
  1807.            
  1808.         }
  1809.  
  1810.         //DA first
  1811.         //Create thing with id ="_lux_armory_suggestions"
  1812.         var da_html = '<span style="color:red"> Not enough tools</span>';
  1813.         if (da_factor < 16) {
  1814.             da_sellRow = addCommas(da_cost);
  1815.  
  1816.             if (ivs >= sell_ivs) {
  1817.                 if (sell_ivs > 0)  
  1818.                     da_sellRow = addCommas(da_cost) + ' (Sell ' + addCommas(sell_ivs) + ' Invisibility Shields)';
  1819.                    
  1820.                 if (oldDa < newDa_ivs)
  1821.                      da_html = addCommas(Math.floor(newDa_ivs)) + ' (<a style="color:green"><b>+</b></a>' + addCommas(Math.floor(Math.abs(newDa_ivs-oldDa))) + ')';
  1822.                 else
  1823.                      da_html = addCommas(Math.floor(newDa_ivs)) + ' (<a style="color:red"><b>-</b></a>' + addCommas(Math.floor(Math.abs(newDa_ivs-oldDa))) + ')';
  1824.             }
  1825.             if (skins >= sell_skins) {
  1826.                 if (sell_skins > 0)    
  1827.                     da_sellRow = addCommas(da_cost) + ' (Sell ' + addCommas(sell_skins) + ' Dragonskins)';
  1828.                    
  1829.                 if (oldDa < newDa_skins)
  1830.                      da_html = addCommas(Math.floor(newDa_skins)) + ' (<a style="color:green"><b>+</b></a>' + addCommas(Math.floor(Math.abs(newDa_skins-oldDa))) + ')';
  1831.                 else
  1832.                      da_html = addCommas(Math.floor(newDa_skins)) + ' (<a style="color:red"><b>-</b></a>' + addCommas(Math.floor(Math.abs(newDa_skins-oldDa))) + ')';
  1833.             }
  1834.         }
  1835.        
  1836.         //SA second
  1837.         var sa_html = '<span style="color:red"> Not enough tools</span>';
  1838.         if (sa_factor < 14) {
  1839.              sa_sellRow = addCommas(sa_cost);
  1840.            
  1841.             if (bpms >= sell_bpms) {
  1842.                 if (sell_bpms > 0) 
  1843.                     sa_sellRow = addCommas(sa_cost) + ' (Sell ' + addCommas(sell_bpms) + ' Blackpowder Missles)';
  1844.                    
  1845.                 if (newSa_bpms > oldSa)
  1846.                     sa_html = addCommas(newSa_bpms) + ' (<a style="color:green"><b>+</b></a>' + addCommas(Math.floor(Math.abs(oldSa-newSa_bpms))) + ')';
  1847.                 else
  1848.                     sa_html = addCommas(newSa_bpms) + ' (<a style="color:red"><b>-</b></a>' + addCommas(Math.floor(Math.abs(oldSa-newSa_bpms))) + ')';
  1849.             }
  1850.             if (chars >= sell_chars) {
  1851.                 if (sell_chars > 0)    
  1852.                     sa_sellRow = addCommas(sa_cost) + ' (Sell ' + addCommas(sell_chars) + ' Chariots)';
  1853.                    
  1854.                 if (newSa_chars > oldSa)
  1855.                     sa_html = addCommas(newSa_chars) + ' (<a style="color:green"><b>+</b></a>' + addCommas(Math.floor(Math.abs(oldSa-newSa_chars))) + ')';
  1856.                 else
  1857.                     sa_html = addCommas(newSa_chars) + ' (<a style="color:red"><b>-</b></a>' + addCommas(Math.floor(Math.abs(oldSa-newSa_chars))) + ')';
  1858.             }
  1859.         }  
  1860.        
  1861.         $("#_lux_upgrades").html('<table class="table_lines" width="100%" cellspacing="0" cellpadding="6" border="0"><tbody><tr><th colspan="2">Upgrade Suggestions</th></tr></tbody></table>');
  1862.         var temp = $("#_lux_upgrades>tbody");
  1863.         temp.append("<tr><td><b>Current Fortifications:</b></td><td align='right'>"+fort+" (" + da_factor + ")</td></tr>");
  1864.         if(da_factor<16) {
  1865.             temp.append("<tr><td>Upgrade Cost:</td><td align='right'>"+da_sellRow+"</td></tr>");
  1866.             temp.append("<tr><td>Estimated new DA</td><td align='right'>"+da_html+"</td></tr>");
  1867.         } else
  1868.             temp.append("<tr><td colspan=2>There are no more upgrades</td></tr>");
  1869.            
  1870.         temp.append("<tr><td><b>Current Siege:</b></td><td align='right'>"+siege+" (" + sa_factor + ")</td></tr>");
  1871.         if (sa_factor<14) {
  1872.             temp.append("<tr><td>Upgrade Cost:</td><td align='right'>"+sa_sellRow+"</td></tr>");
  1873.             temp.append("<tr><td>Estimated new SA</td><td align='right'>"+sa_html+"</td></tr>");
  1874.         } else
  1875.             temp.append("<tr><td colspan=2>There are no more upgrades</td></tr>");
  1876.        
  1877.     }
  1878.    
  1879.  
  1880.  
  1881.     //
  1882.     // Train Page Functions
  1883.     //
  1884.  
  1885.     function trainPage() {
  1886.         var stable = $("table.personnel").last();
  1887.        
  1888.         var spies = $(stable).find("tr:contains('Spies'):first>td:last").html().trim();
  1889.         var sentries = $(stable).find("tr:contains('Sentries'):first>td:last").html().trim();
  1890.         var attackers = $(stable).find("tr:contains('Trained Attack Soldiers'):first>td:last").html().trim();
  1891.         var attackMercs = $(stable).find("tr:contains('Trained Attack Mercenaries'):first>td:last").html().trim();
  1892.         var defenders = $(stable).find("tr:contains('Trained Defense Soldiers'):first>td:last").html().trim();
  1893.         var defenseMercs = $(stable).find("tr:contains('Trained Defense Mercenaries'):first>td:last").html().trim();
  1894.        
  1895.  
  1896.         $(stable).after("<table width='100%' cellspacing='0' cellpadding='6' border='0' id='holding' class='table_lines'><tbody><tr><th colspan=3>Troops/Weapons</th></tr><tr><th class='subh'>Troops</th><th  class='subh'>Weapons</th><th align='right' class='subh'>Unhelds</th></tr></tbody></table>");
  1897.        
  1898.         var unheldSpy = User.spyWeaps - spies.int();
  1899.         var unheldSentry = User.sentryWeaps - sentries.int();
  1900.         var unheldStrike = User.saWeaps - attackers.int() - attackMercs.int();
  1901.         var unheldDefense = User.daWeaps - defenders.int() - defenseMercs.int();
  1902.        
  1903.         function describe(unheld) {
  1904.             if (unheld < 0)
  1905.                 unheld = '<span style="color:white">None ('+unheld+')</span>';
  1906.             else
  1907.                 unheld = '<span style="color:red">'+unheld+'</span>';
  1908.             return unheld;
  1909.         }
  1910.         unheldSpy = describe(unheldSpy);
  1911.         unheldSentry = describe(unheldSentry);
  1912.         unheldStrike = describe(unheldStrike);
  1913.         unheldDefense = describe(unheldDefense);
  1914.  
  1915.            
  1916.         $("#holding").append("<tr><td><b>Strike Weapons&nbsp;</b></td><td>"+User.saWeaps+"&nbsp;&nbsp;</td><td align='right'> "+ unheldStrike+" </td></tr>");
  1917.         $("#holding").append("<tr><td><b>Defense Weapons&nbsp;</b></td><td>"+User.daWeaps+"&nbsp;&nbsp;</td><td align='right'> "+ unheldDefense+" </td></tr>");
  1918.         $("#holding").append("<tr><td><b>Spy Weapons&nbsp;</b></td><td>"+User.spyWeaps+"&nbsp;&nbsp;</td><td align='right'> "+ unheldSpy +"</td></tr>");
  1919.         $("#holding").append("<tr><td><b>Sentry Weapons&nbsp;</b></td><td>"+User.sentryWeaps+"&nbsp;&nbsp;</td><td align='right'> "+ unheldSentry+" </td></tr>");
  1920.  
  1921.        
  1922.         stable = $("table:contains('Train Your Troops')").last();
  1923.         $(stable).after("<table width='100%' cellspacing='0' cellpadding='6' border='0' id='growth' class='table_lines'><tbody><tr><th colspan=3>Growth Stats</th></tr></tbody></table>");
  1924.         $("#growth").append("<tr><td><div id='container' style='height:250px'></div></td></tr>");
  1925.  
  1926.        
  1927.         getLux('&a=trainStats',function(a) {
  1928.            
  1929.                 window.chart = new Highcharts.StockChart({
  1930.                     chart : {
  1931.                         renderTo : 'container',
  1932.                         zoom : 'none'
  1933.                     },
  1934.                     navigator : {
  1935.                         enabled : true
  1936.                     },
  1937.                     scrollbar : {
  1938.                         enabled : false
  1939.                     },
  1940.                     yAxis: {
  1941.                         min: 0,
  1942.                         // startOnTick: false,
  1943.                         // endOnTick: false    
  1944.                     },
  1945.                     rangeSelector: {
  1946.                         enabled: false,
  1947.                     },
  1948.                     title : {
  1949.                         text : 'Total Fighting Force'
  1950.                     },
  1951.                    
  1952.                     series : [{
  1953.                         name : 'Army Size',
  1954.                         data : $.parseJSON(a.responseText),
  1955.                         tooltip: {
  1956.                             valueDecimals: 0
  1957.                         }
  1958.                     }]
  1959.                 });    
  1960.             });
  1961.  
  1962.         var notech = document.body.innerHTML.split('You have no technology');
  1963.         if (notech[1]) {
  1964.             db.put("Tech",1);
  1965.         }
  1966.         else {
  1967.             var tech = document.body.innerHTML.split('(x ');
  1968.             tech = tech[1].split(' ');
  1969.             tech = parseFloat(tech[0]);
  1970.             tech = Math.floor(tech*100);
  1971.             db.put("Tech",tech);
  1972.         }
  1973.     }
  1974.  
  1975.  
  1976.  
  1977.  
  1978.     //
  1979.     // Attack Page Functions
  1980.     //
  1981.     function getSabInfo() {
  1982.         var userid = document.URL.substr(document.URL.indexOf('=')+1, 7);
  1983.         if (userid == "http://") {
  1984.             getopponent = document.getElementsByName('defender_id');
  1985.             userid = getopponent[0].value;
  1986.         }
  1987.        
  1988.  
  1989.         addCSS(".sabbable>span { border-bottom:thin dotted white;}");
  1990.         $(".personnel").before("<table id='lux_sabbable' class='table_lines' width='100%' cellpadding='6' cellSpacing='0'><th colspan='3'>LuXBot Info - Sabbable<span style='float:right;'><a href='http://www.kingsofchaos.com/intelfile.php?asset_id="+userid+"'>(Logs)</a></span></th></table>");
  1991.    
  1992.        
  1993.  
  1994.         $("input[name='numsab']").after("&nbsp;<input type='button' id='bumpup' value='+1' />");
  1995.         $("#bumpup").click(function() {
  1996.             $("input[name='numsab']").val($("input[name='numsab']").val().int() + 1);
  1997.         });
  1998.        
  1999.         getLux('&a=getsab2&userid=' + userid,
  2000.             function(responseDetails) {
  2001.                
  2002.                 if (responseDetails.responseText == '403') {
  2003.                     $("#lux_sabbable").append('<td colspan="2" style="font-weight:bold;text-align:center;">Access denied</td>');
  2004.                 } else if (responseDetails.responseText == 'N/A') {
  2005.                     $("#lux_sabbable").append('<td colspan="2" style="font-weight:bold;text-align:center;">No data available</td>');
  2006.                 } else if (responseDetails.responseText.indexOf('<') > -1) {
  2007.                     $("#lux_sabbable").append('<td colspan="2" style="font-weight:bold;text-align:center;">Server Error. Contact Admin.</td>');
  2008.                 } else {
  2009.                     var rt = responseDetails.responseText;
  2010.                     var sabInfo = parseResponse(rt, "sabinfo");
  2011.                     var hilight = parseResponse(rt, "hilight");
  2012.                     userInfo = sabInfo.split(';');
  2013.  
  2014.                     for (i = 0; i < userInfo.length-1; i+=2) {
  2015.                         var builder = '<tr><td class="sabbable">';
  2016.                         if (! isNaN(userInfo[i].charAt(0)))
  2017.                             builder += '<span>'+userInfo[i]+'</span>';
  2018.                         else
  2019.                             builder += userInfo[i];
  2020.                         builder += '</td><td class="sabbable"><span>'+userInfo[i+1]+"</span></td></tr>";
  2021.                        
  2022.                          $("#lux_sabbable").append(builder);
  2023.                     }
  2024.  
  2025.                     if (hilight.length > 0)
  2026.                         $("#lux_sabbable").find("td").eq(hilight).css("border","1px solid #00FF66");
  2027.                    
  2028.                     $(".sabbable>span").click(function(e) {
  2029.                         var t = $(e.target).text();
  2030.                         t = t.trim().split(" ");
  2031.                         var count = t.shift();
  2032.                         var weap = t.join(" ");
  2033.                         weap = weap.substr(0,weap.length-1);//take off last "s"
  2034.  
  2035.                         val = $("option[label='"+weap+"']").val();
  2036.                         $("select[name='enemy_weapon']").val(val);
  2037.                         $("input[name='numsab']").val(count);
  2038.                         $("input[name='numspies']").val('1');
  2039.                         $("select[name='sabturns']").val('5');
  2040.                     });
  2041.                 }
  2042.             });
  2043.     }
  2044.    
  2045.     function checkCap() {
  2046.         var getopponent = document.getElementsByName('defender_id');
  2047.         var userid = getopponent[0].value;
  2048.         //alert(userid);
  2049.        
  2050.         if (document.body.innerHTML.indexOf('Your opponent has already suffered heavy losses today') != -1) {
  2051.             var data = userid;
  2052.             postLux('&a=logcap','targetID='+userid,function(){});
  2053.         }
  2054.     }
  2055.    
  2056.  
  2057.    
  2058.     //Attack Logs
  2059.  
  2060.     function processAttackLogDetail() {
  2061.         //send specific attack to Lux
  2062.         attackReport = $("td.report:first").text();
  2063.            
  2064.         if (attackReport.indexOf('counter-attack') == -1) {
  2065.             processDefendLog();
  2066.             return;
  2067.         }
  2068.        
  2069.         var your_damage = TextBetween(attackReport, 'Your troops inflict',' damage on the enemy!');
  2070.         var enemy_damage = TextBetween(attackReport, 'counter-attack and inflict ', ' damage on your army!');
  2071.         var enemy_name = attackReport.match(/As (.*)'s army runs from the/);
  2072.             enemy_name = enemy_name[1];
  2073.         var your_losses = TextBetween(attackReport, 'Your army sustains ', ' casualties');
  2074.  
  2075.         var enemy_losses = TextBetween(attackReport, 'The enemy sustains ', ' casualties');
  2076.  
  2077.         var enemy_id = $("form > input [name='id']").val();
  2078.         enemy_id = TextBetween(attackReport, 'name="id" value="', '"');
  2079.         enemy_id = $("input[name='id']").val();
  2080.        
  2081.         if (attackReport.indexOf('You stole') == -1)
  2082.             var gold_stolen = 'defended';
  2083.         else
  2084.             var gold_stolen = TextBetween(attackReport, 'You stole ', ' gold');
  2085.        
  2086.         if (document.URL.indexOf('&') == -1)
  2087.             var attack_id = document.URL.substring(document.URL.indexOf('attack_id=')+10);
  2088.         else
  2089.             var attack_id = document.URL.substring(document.URL.indexOf('attack_id=')+10,document.URL.indexOf('&'));
  2090.  
  2091.         sendAttackLogDetails(User.nick, "attack", enemy_id, enemy_name, your_damage, enemy_damage, your_losses, enemy_losses, gold_stolen, attack_id, 'now');
  2092.     }
  2093.  
  2094.     function attacklogPage() {
  2095.         //send entire attacklog to lux
  2096.         function AttackLogHelper(rows, shift ) {
  2097.             //rows.slideUp();
  2098.             for (var i = 2; i < rows.size()-1; i++) {
  2099.                 var rawData = rows.eq(i).html().split("<td");
  2100.                 //alert(rawData[3]);
  2101.                 //this removes the junk to get value (ie. align="right">2</td> becomes 2)
  2102.                 var enemy_id;
  2103.                 var enemy;
  2104.                 if (rawData[3].indexOf("not active") == -1) {
  2105.                     enemy_id = rawData[3].match(/id=(\d*)"/)[1];
  2106.                     enemy = rawData[3].match(/\d">(.+)<\/a>/)[1];
  2107.                 } else {
  2108.                     enemy_id = "";
  2109.                     enemy = rawData[3].match(/">(.+)\(not active/)[1];
  2110.                 }
  2111.                 var logid = rawData[5+shift].match(/id=(\d*)"/)[1];
  2112.                 var goldTemp = rawData[5+shift].match(/">([\d,]*) Gold/);
  2113.                 var gold;
  2114.                 if (goldTemp== null)
  2115.                     gold = "defended";
  2116.                 else
  2117.                     gold=goldTemp[1];
  2118.  
  2119.                 $.each(rawData, function (i,val) {
  2120.                     rawData[i] = TextBetween(val, ">","<");
  2121.                 });
  2122.                 var time = rawData[1];
  2123.                 var timeunit = rawData[2];
  2124.                 var type = rawData[4];
  2125.                 var enemy_losses = rawData[6+shift];
  2126.                 var your_losses = rawData[7+shift];
  2127.                 var enemy_damage = rawData[8+shift];
  2128.                 var your_damage = rawData[9+shift];
  2129.                    
  2130.                 //alert(your_damage);
  2131.                
  2132.                 time = timeToSeconds(time,timeunit);
  2133.                 if(!enemy_id)
  2134.                     enemy_id=":invalid";//DONATO, Check this before release
  2135.  
  2136.                 if(type.indexOf("attack")!=-1 || type.indexOf("raid")!=-1)  //this seems contradictory but it makes sense
  2137.                     type="defend";
  2138.                 else
  2139.                     type="attack";
  2140.                    
  2141.                 //alert('time: ' + time + ' :: enemy: ' + enemy + ' :: gold: ' + gold + ' :: enemy_losses: ' + enemy_losses + ' :: your_losses: ' + your_losses + ' ::  enemy_damage: ' + enemy_damage + ' :: your_damage: ' + your_damage + ' :: logid: ' + logid);
  2142.                 sendAttackLogDetails(User.nick, type, enemy_id, enemy, your_damage, enemy_damage, your_losses, enemy_losses, gold, logid, time);
  2143.             }
  2144.         }
  2145.    
  2146.    
  2147.         var defendedRows = $("td.content > table.attacklog > tbody > tr");
  2148.         AttackLogHelper(defendedRows,0);
  2149.        
  2150.         var attackRows = $("td.content > p > table.attacklog > tbody > tr");
  2151.         AttackLogHelper(attackRows, -1);
  2152.  
  2153.     }
  2154.  
  2155.     function sendAttackLogDetails(user, type, oppid, opponent, user_damages, opponent_damages, user_losses, opponent_losses, gold_stolen, logid, time) {
  2156.         getLux( '&a=logattack&type=' + type + '&user=' + user +
  2157.             '&enemy=' + opponent + ';' + oppid + ';' + opponent_damages + ';' + opponent_losses +
  2158.             '&data=' + user_damages + ';' + user_losses +
  2159.             '&gold=' + gold_stolen +
  2160.             '&time=' + time +
  2161.             '&logid=' + logid,
  2162.             function(responseDetails) {
  2163.        
  2164.         });
  2165.     }  
  2166.    
  2167.     function showBattleLog() {
  2168.         var a = db.get('battlelog', 0);
  2169.         if (a == 0) {
  2170.             return;
  2171.         } else if (a == 2 || a == 1) {
  2172.             var table;
  2173.             var q = document.getElementsByTagName('td');
  2174.             for (i = 0; i < q.length; i++) {
  2175.                 if (q[i].className.indexOf('report') != -1) {
  2176.                     table = q[i];
  2177.                     break;
  2178.                 }
  2179.             }
  2180.            
  2181.             for (i = 0; i < table.childNodes.length; i++) {
  2182.                 if (table.childNodes[i].nodeName != '#text') {
  2183.                     table.childNodes[i].style.display = 'block';
  2184.                 }
  2185.             }
  2186.            
  2187.             document.getElementsByClassName('battle')[0].className += '2';
  2188.            
  2189.             var dummyTable = document.body.appendChild(document.createElement('table'));
  2190.             dummyTable.className = 'battle';
  2191.             dummyTable.style.display = 'none';
  2192.             dummyTable.style.height = document.body.scrollTop;
  2193.             window.addEventListener(
  2194.                 'scroll',
  2195.                 function () {
  2196.                   dummyTable.style.height = document.body.scrollTop;
  2197.                 },
  2198.                 false);
  2199.         } else if (a == 3) {
  2200.             if (document.URL.indexOf('suspense') != -1) {
  2201.                 document.location = document.URL.substr(0, document.URL.indexOf('suspense'));
  2202.             }
  2203.         }
  2204.     }
  2205.    
  2206.     function processIntelLog()  {
  2207.         //proccess recons and sabotages
  2208.          
  2209.         function processSabLog(sabtext) {
  2210.  
  2211.             if (sabtext.indexOf('Your spies successfully enter') == -1) {
  2212.               //turned illegal
  2213.               //  history.back();
  2214.                 return;
  2215.             }
  2216.            
  2217.             var beforeName, afterName, differenceName, targetName;
  2218.             beforeName = sabtext.indexOf(" enter ");
  2219.             afterName = sabtext.indexOf("'s armory");
  2220.             differenceName = afterName - beforeName - 7;
  2221.             targetName = sabtext.substr(beforeName + 7, differenceName);
  2222.            
  2223.             var beforeAmount, afterAmount, differenceAmount, targetAmount;
  2224.             beforeAmount = sabtext.indexOf(" destroy ");
  2225.             afterAmount = sabtext.indexOf(" of the enemy's");
  2226.             differenceAmount = afterAmount - beforeAmount - 9;
  2227.             targetAmount = sabtext.substr(beforeAmount + 9, differenceAmount);
  2228.            
  2229.             var beforeWeapon, afterWeapon, differenceWeapon, targetWeapon;
  2230.             beforeWeapon = afterAmount;
  2231.             afterWeapon = sabtext.indexOf(" stockpile.");
  2232.             differenceWeapon = afterWeapon - beforeWeapon - 16;
  2233.             targetWeapon = sabtext.substr(beforeWeapon + 16, differenceWeapon);
  2234.            
  2235.             var logid = String(document.location).substr(String(document.location).indexOf('=')+1);
  2236.  
  2237.             getLux('&a=logsab&target=' + targetName + '&weapon=' + targetWeapon + '&amount=' + targetAmount + '&logid=' + logid,
  2238.                 function(responseDetails) {
  2239.                     //GM_log(responseDetails.responseText);
  2240.                 });
  2241.         }
  2242.  
  2243.         var q = $("td.content");
  2244.         var tables = q.html().split('<table');
  2245.        
  2246.  
  2247.         var domGrab = $("td.content > p:first");
  2248.         var infoText = domGrab.html();
  2249.  
  2250.         //notice for sabotages it says "your spies" for recon "your spy"
  2251.         if (tables[0].indexOf('Your spy') == -1) {
  2252.             processSabLog(tables[0]);
  2253.             return;
  2254.         }
  2255.  
  2256.         if (tables[0].indexOf('As he gets closer, one of the sentries spots him and sounds the alarm.') != -1) {
  2257.             //now illegal
  2258.             //history.back();
  2259.             return;
  2260.         }
  2261.  
  2262.  
  2263.         var enemy = TextBetween(tables[0],"your spy sneaks into ","'s camp");
  2264.         var enemyid = TextBetween(tables[5],'value="','"');
  2265.         //GM_log(enemy+" "+enemyid);
  2266.        
  2267.         var units = tables[1].replace(/ align="right"/g, '').split('<td>');
  2268.         var unitstring =
  2269.             units[2].substr(0, units[2].indexOf('</td>')) + ';' +
  2270.             units[3].substr(0, units[3].indexOf('</td>')) + ';' +
  2271.             units[4].substr(0, units[4].indexOf('</td>')) + ';' +
  2272.             units[6].substr(0, units[6].indexOf('</td>')) + ';' +
  2273.             units[7].substr(0, units[7].indexOf('</td>')) + ';' +
  2274.             units[8].substr(0, units[8].indexOf('</td>'));
  2275.         unitstring = unitstring.replace(/\?\?\?/g, '').replace(/,/g, '');  
  2276.         //GM_log(unitstring);
  2277.        
  2278.         var stats = tables[3].replace(/ align="right"/g, '').split('<td>');
  2279.         var actionstring =
  2280.             stats[2].substr(0, stats[2].indexOf('</td>')) + ';' +
  2281.             stats[4].substr(0, stats[4].indexOf('</td>')) + ';' +
  2282.             stats[6].substr(0, stats[6].indexOf('</td>')) + ';' +
  2283.             stats[8].substr(0, stats[8].indexOf('</td>'));
  2284.         actionstring = actionstring.replace(/\?\?\?/g, '').replace(/,/g, '');
  2285.        // GM_log(actionstring);
  2286.        
  2287.         var statsstring =
  2288.             stats[10].substr(0, stats[10].indexOf('</td>')) + ';' +
  2289.             stats[12].substr(0, stats[12].indexOf('</td>')) + ';' +
  2290.             stats[16].substr(0, stats[16].indexOf('</td>')) + ';' +
  2291.             stats[18].substr(0, stats[18].indexOf('</td>')) + ';' +
  2292.             TextBetween(tables[4], '<td align="center">',' Gold');
  2293.         statsstring = statsstring.replace(/\?\?\?/g, '').replace(/,/g, '');
  2294.         //GM_log(statsstring);
  2295.        
  2296.         var siege = stats[14].substr(0, stats[14].indexOf('</td>')).replace(/\?\?\?/g, '');
  2297.         //GM_log(siege);
  2298.        
  2299.         var weapons = tables[5].replace(/ align="right"/g, '').split(/\<td\>/);
  2300.         var i = 1;
  2301.         var weaponstring = '';
  2302.         while (i < weapons.length) {
  2303.             weaponstring +=
  2304.                 weapons[i].substr(0, weapons[i].indexOf('</td>')) + ':' +
  2305.                 weapons[i+1].substr(0, weapons[i+1].indexOf('</td>')) + ':' +
  2306.                 weapons[i+2].substr(0, weapons[i+2].indexOf('</td>')) + ':' +
  2307.                 weapons[i+3].substr(0, weapons[i+3].indexOf('</td>')) + ';';
  2308.             i += 4;
  2309.         }
  2310.         weaponstring = weaponstring.replace(/\?\?\?/g, '').replace(/,/g, '').substr(0, weaponstring.length-1);
  2311.         //alert(weaponstring);
  2312.        
  2313.         var data = actionstring + ';' + unitstring + ';' + statsstring;
  2314.         var logid = String(document.location).substr(String(document.location).indexOf('=')+1);
  2315.         sendLogDetails(User.nick, enemy, enemyid, siege, data, weaponstring,'', logid);
  2316.     }
  2317.  
  2318.     //Not finished yet!
  2319.     // function processRecon() {
  2320.         // var html = document.body.innerHTML;
  2321.         // if (html.instr('As he gets closer, one of the sentries spots him and sounds the alarm.')) {
  2322.             // //now illegal
  2323.             // //history.back();
  2324.             // return;
  2325.         // }
  2326.  
  2327.         // var enemy = html.between("your spy sneaks into ","'s camp");
  2328.         // var enemyid = html.between('value="','"');
  2329.        
  2330.         // var stable = $("table:contains('Army Size:')").last();
  2331.         // var mercs_a = $(stable).find("tr:eq(1)>td:eq(1)").text();
  2332.         // var mercs_d = $(stable).find("tr:eq(1)>td:eq(2)").text();
  2333.         // var mercs_u = $(stable).find("tr:eq(1)>td:eq(3)").text();
  2334.         // var troops_a = $(stable).find("tr:eq(2)>td:eq(1)").text();
  2335.         // var troops_d = $(stable).find("tr:eq(2)>td:eq(2)").text();
  2336.         // var troops_u = $(stable).find("tr:eq(2)>td:eq(3)").text();
  2337.  
  2338.         // stable = $("table:contains('Military Stats')").last();
  2339.         // var sa = $(stable).find("tr:contains('Strike Action'):first>td:eq(1)").text();
  2340.         // var da = $(stable).find("tr:contains('Defensive Action'):first>td:eq(1)").text();
  2341.         // var spy = $(stable).find("tr:contains('Spy Rating'):first>td:eq(1)").text();
  2342.         // var sentry = $(stable).find("tr:contains('Sentry Rating'):first>td:eq(1)").text();
  2343.         // var covert_skill = $(stable).find("tr:contains('Covert Skill'):first>td:eq(1)").text();
  2344.         // var coverts = $(stable).find("tr:contains('Covert Operatives'):first>td:eq(1)").text();
  2345.         // var siege = $(stable).find("tr:contains('Siege Technology'):first>td:eq(1)").text();
  2346.         // var turns = $(stable).find("tr:contains('Attack Turns'):first>td:eq(1)").text();
  2347.         // var conscription = $(stable).find("tr:contains('Unit Production'):first>td:eq(1)").text();
  2348.  
  2349.         // stable = $("table:contains('Treasury')").last();
  2350.         // var gold = to_int($(stable).find("tr>td").text());
  2351.        
  2352.        
  2353.         // stable = $("table:contains('Weapons')").last();
  2354.         // var weap_rows = $(stable).find("tbody>tr>td").parent();
  2355.         // var weapons = "";
  2356.         // $(weap_rows).each(function(i,e) {
  2357.             // var r = $(e).text().split("\n");
  2358.             // var g = r[1].trim()+","+r[2].trim()+","+r[3].trim()+","+r[4].trim();
  2359.             // weapons += g +";";
  2360.         // });
  2361.  
  2362.         // var logid = String(document.location).substr(String(document.location).indexOf('=')+1);
  2363.  
  2364.         // logRecon(enemy,enemyid, gold, sa.int() + ";"+da.int()+";"+spy.int()+";"+sentry.int()+";"+covert_skill.int()+";"+coverts.int()+";"+siege+";"+turns.int()+";"+conscription.int(), mercs_a.int()+";"+mercs_d.int()+";"+mercs_u.int()+";"+troops_a.int()+";"+troops_d.int()+";"+troops_u.int(), weapons, logid);
  2365.     // }
  2366.    
  2367.  
  2368.  
  2369.     //
  2370.     // Stats Page Functions
  2371.     //
  2372.    
  2373.     function statsPage() {
  2374.         var enemyid = document.URL.split(/[=&?]/)[2];
  2375.         if (document.body.innerHTML.indexOf('Invalid User ID') != -1) {
  2376.             logStats('', enemyid, '', '','', 'invalid', '');
  2377.         } else {
  2378.             var stable = $("table:contains('User Stats')").last();
  2379.            
  2380.             var name = $(stable).find("tr:contains('Name:'):first>td:last").html().trim();
  2381.             var comid = $(stable).find("tr:contains('Commander:')>td:last").html().trim();
  2382.             comid = TextBetween(comid,'id=','"');
  2383.             var race = $(stable).find("tr:contains('Race:')>td:last").html().trim();
  2384.             var rank = $(stable).find("tr:contains('Rank:'):first>td:last").html().trim();
  2385.             var highest_rank = $(stable).find("tr:contains('Highest Rank:')>td:last").html().trim();
  2386.             var tff = to_int($(stable).find("tr:contains('Army Size:')>td:last").html().trim());
  2387.             var morale = $(stable).find("tr:contains('Army Morale:')>td:last").text().trim();
  2388.             var chain = $(stable).find("tr:contains('Chain Name:')>td:last");
  2389.             if ($(chain).size() > 0)
  2390.                 chain = $(chain).html().trim();
  2391.             else
  2392.                 chain = "";
  2393.                                  
  2394.             var treasury = $(stable).find("tr:contains('Treasury:')>td:last").html();
  2395.             if (treasury)
  2396.                 treasury = to_int(treasury);
  2397.             else
  2398.                 treasury = '';
  2399.             var fort = $(stable).find("tr:contains('Fortifications:')>td:last").html().trim();
  2400.            
  2401.             officers = stats_getOfficers(false);
  2402.             alliances = stats_getAlliances(stable);
  2403.  
  2404.  
  2405.  
  2406.             addIncomeCalc(race, tff);
  2407.             nav();
  2408.             logStats(name, enemyid, chain, alliances[0],alliances[1], comid + ";"+race+";"+rank+";"+highest_rank+";"+tff+";"+morale+";"+fort+";"+treasury, officers);
  2409.         }
  2410.     }
  2411.  
  2412.     function logStats(nick, kocid, chain, palliance, alliances, data, officers) {
  2413.         //data = comid;race;rank;highest_rank;tff;morale;fortifications;treasury
  2414.         getLux('&a=stats' +
  2415.                             '&nick=' + nick +
  2416.                             '&kocid=' + kocid +
  2417.                             '&chain='+chain+
  2418.                             '&palliance=' + palliance +
  2419.                             '&alliances=' + alliances +
  2420.                             '&data=' + data +
  2421.                             '&officers=' + officers,
  2422.                 function(responseDetails) {
  2423.                         GM_log("LogStats: "+ responseDetails.responseText);
  2424.                         // alert(responseDetails.responseText);
  2425.                 });
  2426.     }
  2427.    
  2428.     function showUserInfoS() {
  2429.         var userid = document.URL.substr(document.URL.indexOf('=')+1, 7);
  2430.  
  2431.  
  2432.         $("#luxstats_reload").live("click",function() {
  2433.             updateUserInfoS(userid);
  2434.         });
  2435.        
  2436.         var offieTable = $("body").find("table:contains('Officers'):last");
  2437.         offieTable.parent().prepend("<table id='luxstats_info' class='table_lines' width='100%' cellPadding=6 cellSpacing=0><tbody></tbody></table><br />");
  2438.        
  2439.         $("#luxstats_info>tbody").html('<tr><th colspan="3">LuXBot Info<span id="luxstats_reload" style="cursor:pointer;color:pink;font-size:8pt;float:right">(reload)</span></th></tr>');
  2440.        
  2441.         updateUserInfoS(userid);
  2442.     }
  2443.     function updateUserInfoS(userid) {
  2444.             getLux('&a=getstats&userid=' + userid,
  2445.             function(responseDetails) {
  2446.        
  2447.                 var container = $("#luxstats_info");
  2448.                 $(container).find(".statsrow").remove();
  2449.                 if (responseDetails.responseText == '403') {
  2450.                     container.append('<td colspan="2" style="font-weight:bold;text-align:center;">Access denied</td>');
  2451.                 } else if (responseDetails.responseText == 'N/A') {
  2452.                     container.append('<td colspan="2" style="font-weight:bold;text-align:center;">No data available</td>');
  2453.  
  2454.                 } else {
  2455.                     userInfo = responseDetails.responseText.split(';');
  2456.  
  2457.  
  2458.                     for (i = 0; i < userInfo.length-1; i+=2) {
  2459.                         if (userInfo[i]== '???') {
  2460.                             // alert(i);
  2461.                             container.append("<tr class='statsrow'><td>"+statsdesc[i/2]+"</td><td colspan=2>"+userInfo[i]+"</td></tr>");
  2462.                             // i++;
  2463.                         }
  2464.                         else
  2465.                             container.append("<tr class='statsrow'><td>"+statsdesc[i/2]+"</td><td>"+userInfo[i]+"</td><td class='_luxbotago'>"+userInfo[i+1]+"</td></tr>");
  2466.                     }
  2467.                 }
  2468.             });
  2469.     }
  2470.  
  2471.    function collapseAllianceInfoS() {
  2472.         var nameRE = /User Stats\<\/th\>/ig;
  2473.         var q = document.getElementsByTagName('table');
  2474.         var statstable;
  2475.  
  2476.         for(var i = 0; i < q.length; i++){
  2477.             if(q[i].innerHTML.match(nameRE) && !q[i].innerHTML.match(/\<table/)) {
  2478.                 statstable = q[i];
  2479.                 break;
  2480.             }
  2481.         }
  2482.        
  2483.         if (statstable == undefined) {
  2484.             return;
  2485.         }
  2486.        
  2487.         var allianceindex;
  2488.         for (var i = 0; i < statstable.rows.length; i++) {
  2489.             if (statstable.rows[i].cells[0].innerHTML.indexOf('Alliances') > -1) {
  2490.                 allianceindex = i;
  2491.                 break;
  2492.             }
  2493.         }
  2494.  
  2495.         // alliance splitted
  2496.         var alliances = statstable.rows[allianceindex].cells[1].innerHTML.split(',');
  2497.         var pri_alliance = 'None';
  2498.         var sec_alliances = new Array();
  2499.         for (var i = 0; i < alliances.length; i++) {
  2500.             if (alliances[i].indexOf('(Primary)') > -1) {
  2501.                 pri_alliance = alliances[i];
  2502.             } else {
  2503.                 sec_alliances[sec_alliances.length] = alliances[i];
  2504.             }
  2505.             continue;
  2506.         }
  2507.         statstable.rows[allianceindex].cells[0].innerHTML = '<b>Alliances (' + alliances.length + '):</b>';
  2508.         statstable.rows[allianceindex].cells[1].innerHTML = pri_alliance + '<br><div id="_luxbot_alliances">' + sec_alliances.join(', ') + '</div><a href="javascript:LuXBotShowAlliances();"> + Show Secondary</a>';
  2509.         addCSS('#_luxbot_alliances{display:none;visibility:hidden;}');
  2510.         addJS('function LuXBotShowAlliances(){var q = document.getElementById(\'_luxbot_alliances\');q.style.display = \'block\';q.style.visibility = \'visible\';q.nextSibling.href = \'javascript:LuXBotHideAlliances();\';q.nextSibling.innerHTML = \' - Hide Secondary\'}');
  2511.         addJS('function LuXBotHideAlliances(){var q = document.getElementById(\'_luxbot_alliances\');q.style.display = \'none\';q.style.visibility = \'hidden\';q.nextSibling.href = \'javascript:LuXBotShowAlliances();\';q.nextSibling.innerHTML = \' + Show Secondary\'}');
  2512.     }
  2513.    
  2514.  
  2515.     function addRequestRecon() {
  2516.         var getopponent = document.getElementsByName('defender_id');
  2517.         var data = getopponent[0].value;
  2518.         document.getElementById("_luxbot_requestRecon").disabled = true;
  2519.         document.getElementById("_luxbot_requestRecon").style.color = "gray";
  2520.         postLux('&a=reconrequest','kocid=' +data, function(r,debug) {
  2521.                 if(r.responseText == 'OWK') {
  2522.                     alert('A request has already been sent.');
  2523.                 } else if(r.responseText == 'OK') {
  2524.                     alert('Your request has been sent.');
  2525.                 } else {
  2526.                     alert('Your request could not be sent, try again later!'+r.responseText);
  2527.                 }
  2528.         });
  2529.     }
  2530.    
  2531.    
  2532.     function addIncomeCalc(race, tff) {
  2533.    
  2534.         var bonus = 1;     
  2535.         if(race == 'Humans') {
  2536.             bonus = 1.30;
  2537.         }
  2538.         if(race == 'Dwarves') {
  2539.             bonus = 1.15;
  2540.         }
  2541.        
  2542.         // var calBonus = Math.floor(tff*bonus);
  2543.         // var CalBonusInt = parseInt(calBonus);
  2544.         // var tffInt = parseInt(tff);
  2545.         // var calTbgMin = Math.floor(CalBonusInt + tffInt);
  2546.         // var CalHourTbg = Math.floor(calTbgMin * 60);
  2547.         var formattedTbg = addCommas(Math.floor(60* tff *bonus));
  2548.        
  2549.         var nameIC = /\<td><b\>Name:\<\/b\>/;
  2550.         var z = document.getElementsByTagName('table');
  2551.         var table;
  2552.        
  2553.          for(var i = 0; i < z.length; i++){
  2554.             if(z[i].innerHTML.match(nameIC) && !z[i].innerHTML.match(/\<table/)) {
  2555.                 table = z[i];
  2556.                 break;
  2557.             }
  2558.         }
  2559.          
  2560.          var x = table.insertRow(10);
  2561.          x.insertCell(0).innerHTML = '<b>Estimated gold per Hour:<b>';
  2562.          x.insertCell(1).innerHTML = '(' + formattedTbg + ')';
  2563.    
  2564.     }
  2565.    
  2566.     function addStatsPageButtons() {
  2567.         // updated to avoid impact of end-of-age counter - tx Cinch for the assitance -- rolled back
  2568.         $("td.content>table>tbody>tr>td").children("table").eq(1).children("tbody").append('<tr><td align=center colspan=2><input style="width:100%;" type="button" name="_luxbot_requestRecon" id="_luxbot_requestRecon" value="Request Recon on User"></td><td align=center colspan=2><input style="width:100%;"  type="button" name="_luxbot_viewHistory" id="_luxbot_viewHistory" value="View Player History"></td></tr>');
  2569.         //$("td.content>p>table>tbody>tr>td").children("table").eq(1).children("tbody").append('<tr><td align=center colspan=2><input style="width:100%;" type="submit" name="_luxbot_requestRecon" id="_luxbot_requestRecon" value="Request Recon on User"></td><td align=center colspan=2><input style="width:100%;"  type="submit" name="_luxbot_viewHistory" id="_luxbot_viewHistory" value="View Player History"></td></tr>');
  2570.    
  2571.         $("#_luxbot_requestRecon").click(addRequestRecon);
  2572.         $("#_luxbot_viewHistory").click(function() {
  2573.             // updated to avoid impact of end-of-age counter - tx Cinch for the assitance
  2574.             var name = $("td.content > table > tbody> tr>td>table.table_lines>tbody>tr").eq(1).children("td").eq(1).text();
  2575.             //var name = $("td.content > p> table > tbody> tr>td>table.table_lines>tbody>tr").eq(1).children("td").eq(1).text();
  2576.             GM_openInTab("stats.luxbot.net/history.php?playerSearch="+name);
  2577.         });
  2578.     }
  2579.    
  2580.    
  2581.     function nav() {
  2582.         $("table.officers tr.nav a").click(function() {
  2583.             setTimeout(function() {
  2584.                 statsPage();
  2585.             },100);
  2586.             nav();
  2587.         });
  2588.     }
  2589.    
  2590.     function stats_getOfficers(tolog) {
  2591.         var officers = "";
  2592.         var rows = $("table.officers>tbody>tr>td>a").parent().parent();
  2593.         $(rows).each(function(i,row) {
  2594.             if ( ! $(row).hasClass('nav')) {
  2595.                 offieInfo = $(row).find("td:eq(0)").html();
  2596.                 officers += TextBetween(offieInfo,"id=",'"') +";";
  2597.             }
  2598.         });
  2599.        
  2600.         //cut off trailing semicolon
  2601.         officers = officers.slice(0, -1);
  2602.         //alert(officers);
  2603.         // if (tolog==true)
  2604.             // sendLogDetails(username, name, userid, '', gold + ';' + rank + ';' + tff + ';' + chain + ';' + comid + '&morale='  + morale , '',officers, -1);
  2605.  
  2606.         return officers;           
  2607.     }
  2608.  
  2609.     function stats_getAlliances(stable) {
  2610.         var row = $(stable).find("tr:contains('Alliances:')>td:last").html();
  2611.         allys = row.split('alliances.php?');
  2612.        
  2613.         var primary = ''
  2614.         var secondary = [];
  2615.         for (a in allys) {
  2616.             name = TextBetween(allys[a],'id=','">');
  2617.             if (allys[a].indexOf('(Primary)') == -1) {
  2618.                 if (name != '')
  2619.                     secondary[secondary.length] = name;
  2620.             }
  2621.             else
  2622.                 primary = name;
  2623.         }  
  2624.         return new Array(primary,secondary);
  2625.     }
  2626.  
  2627.     function statsOnlineCheck() {
  2628.  
  2629.         var userid = document.URL.split(/[=&?]/)[2];
  2630.         addCSS(" ._lux_online {position:absolute;}");
  2631.  
  2632.         //response in form of
  2633.         //key=val\n
  2634.         //key=val\n
  2635.         getLux('&a=stats_online&u=' + userid,
  2636.             function(r) {
  2637.                 var stable = $("table:contains('User Stats')").last();
  2638.                 var tx = r.responseText;
  2639.             //alert("hello");
  2640.                 if (parseResponse(tx, "online") != "") {
  2641.                     $(stable).find("tr:contains('Name')").first().find("td:eq(1)").append('&nbsp;<img title="Player is online"  class="_lux_online" src="http://www.luxbot.net/bot/img/online2.gif" />');
  2642.                 }
  2643.                
  2644.                 var msg = parseResponse(tx, "message");
  2645.                 if (User.kocid == userid) {
  2646.                     //if it is the users stats page, allow them to update
  2647.                     $(stable).find("tr:contains('Fortifications')").after("<tr><td colspan=2><center><textarea id='aaa' style='width:360px;height:100px;'>"+msg+"</textarea><br /><input type='button' value='Update' id='lux_updateMessage' /></center></td></tr>");
  2648.                     $("#lux_updateMessage").click(function() {
  2649.                         postLux('&a=set_message', '&msg=' + $("#aaa").val());                  
  2650.                     });
  2651.                 }
  2652.                 else {
  2653.                     if (msg != "") {
  2654.                         $(stable).find("tr:contains('Fortifications')").after("<tr><td colspan=2><center><textarea style='width:50%'>"+msg+"</textarea></center></td></tr>");
  2655.                     }
  2656.                 }
  2657.             });
  2658.     }
  2659.  
  2660.  
  2661.  
  2662.    
  2663.     //
  2664.     // BATTLEFIELD
  2665.     //
  2666.    
  2667.     function battlefieldAct() {
  2668.         c2++;
  2669.         var xtables = document.getElementsByTagName('table');
  2670.         var tables;
  2671.         for (i = 0; i < xtables.length;i++) {
  2672.             if (xtables[i].className.indexOf('battlefield') != -1) {
  2673.                 tables = xtables[i];
  2674.             }
  2675.         }
  2676.        
  2677.         bfusers = tables.getElementsByTagName('tr');
  2678.        
  2679.         var newuser = bfusers[1].getElementsByTagName('td')[2].getElementsByTagName('a')[0].innerHTML;
  2680.         if (bfusers == undefined || tables == undefined || newuser == prevuser) {
  2681.             if (c2 < 20) {
  2682.                 setTimeout(battlefieldAct, 250);
  2683.             } else {
  2684.                 //GM_log('x');
  2685.                 addGUILink('Reactivate Script', battlefieldAct, "#_luxbot_gui");
  2686.             }
  2687.             return;
  2688.         }
  2689.         if (c2 > 20) {
  2690.             document.getElementById('_luxbot_gui').childNodes[0].removeChild(document.getElementById('_luxbot_gui').childNodes[0].childNodes[1]);
  2691.         }
  2692.         c2 = 0;
  2693.         prevuser = newuser;
  2694.        
  2695.         bfusers[0].childNodes[1].innerHTML = '<input type="checkbox" id="_luxbot_bffiltertoggle" ' + (db.get('bffilterna', 0) == 1 ? 'checked="checked"' : '') + ' />';
  2696.         document.getElementById('_luxbot_bffiltertoggle').addEventListener('click',
  2697.             function (e)
  2698.             {
  2699.                 if (e.target.checked == true) {
  2700.                     db.put('bffilterna', 1);
  2701.                     filterUsers(bfusers);
  2702.                 } else {
  2703.                     db.put('bffilterna', 0);
  2704.                     var q = document.getElementsByTagName('tr');
  2705.                     for (i = 0; i < q.length; i++) {
  2706.                         q[i].style.display = 'table-row';
  2707.                     }
  2708.                 }
  2709.             }, true);
  2710.        
  2711.        
  2712.         missedGold = bf_logGold(bfusers);
  2713.         bf_showGold(missedGold);
  2714.         filterUsers(bfusers);
  2715.         bf_needsRecon(bfusers);
  2716.         bf_online(bfusers);
  2717.         if (bfusers.length > 21) {
  2718.             var q = bfusers[21].getElementsByTagName('a');
  2719.             q[0].addEventListener('click', battlefieldAct, true);
  2720.             if (q.length > 1) {
  2721.                 q[1].addEventListener('click', battlefieldAct, true);
  2722.                 q[1].accessKey = 'c';
  2723.                 q[0].accessKey = 'x';
  2724.             } else {
  2725.                 if (q[0].innerHTML.indexOf('lt') != -1) {
  2726.                     q[0].accessKey = 'x';
  2727.                 } else {
  2728.                     q[0].accessKey = 'c';
  2729.                 }
  2730.             }
  2731.         }
  2732.     }
  2733.    
  2734.     function bf_logGold(users) {
  2735.     //name,userid,gold,rank,alliance,Tff
  2736.  
  2737.         var unscannedGold ='';
  2738.         var logstr = '';
  2739.         $(users).each(function(index, row) {
  2740.        
  2741.             var userid= $(row).attr("user_id");
  2742.             if (userid) {
  2743.                
  2744.                 var x = $(row).find("td");
  2745.                
  2746.                 var name =  remove_delimiters($(x[2]).text());
  2747.                 var tff =   to_int($(x[3]).text());
  2748.                 var rank = to_int($(x[6]).text());
  2749.                 var alliance = remove_delimiters($.trim($(x[1]).text()));
  2750.                 var gold = to_int($(x[5]).text());
  2751.                
  2752.                 if(gold =='')
  2753.                     unscannedGold += userid + ";";
  2754.                    
  2755.                 if (name == User.nick && User.logself == 0)
  2756.                     gold = '';
  2757.                                
  2758.                 var temp = name + ":" + userid + ":" + gold + ":" + rank + ":" + alliance + ":" + tff +";";
  2759.                
  2760.                 logstr+= temp;
  2761.             }
  2762.         });
  2763.            
  2764.         if (logstr != '') {
  2765.             postLux('&a=loggold','&g=' + logstr ,
  2766.                 function(responseDetails) {
  2767.                     GM_log("Response: "+responseDetails.responseText);
  2768.                 });
  2769.         }
  2770.         return unscannedGold;
  2771.     }
  2772.    
  2773.     function bf_showGold(userstr) {
  2774.         if (userstr=="")
  2775.             return;
  2776.            
  2777.         //cut off trailing comma
  2778.         userstr = userstr.slice(0, -1);
  2779.        
  2780.        
  2781.         getLux('&a=loggold&u=' + userstr,
  2782.             function(r) {
  2783.                 //GM_log(r.responseText);
  2784.                 var players = r.responseText.split(';');
  2785.                 $(players).each(function(index, val) {
  2786.                     if (val !="") {
  2787.                         var info = val.split(":");
  2788.                         var GoldTd = $("tr[user_id='"+info[0]+"'] > td").eq(5);
  2789.                         GoldTd.text( info[1] + ' Gold, ' + info[2]);
  2790.                         GoldTd.css("color","#aaaaaa");
  2791.                         GoldTd.css("font-style","italic");
  2792.  
  2793.                     }
  2794.                 });
  2795.         });
  2796.     }
  2797.        
  2798.     function bf_needsRecon(users) {
  2799.    
  2800.         var kocids = '';
  2801.         $(".battlefield>tbody>tr.player").each(function() {
  2802.             kocids += TextBetween($(this).children('td').eq(2).html(),'id=','">')+",";
  2803.         });
  2804.         kocids = kocids.slice(0,-1);
  2805.         if (kocids == '')
  2806.             return;
  2807.  
  2808.         var page = TextBetween($(".battlefield>tbody>tr").last().text(), 'page ', ' of');
  2809.         var ppx = (page-1)*20+1;
  2810.  
  2811.         addCSS(" ._lux_needs_update {position:absolute; padding-left:12px;}");
  2812.  
  2813.         getLux('&a=bf_needsrecon&u=' + kocids,
  2814.             function(r) {
  2815.                 //GM_log(r.responseText);
  2816.                
  2817.                 var players = r.responseText.split(';');
  2818.                
  2819.                 for (i = 0; i < players.length; i++) {
  2820.                     if (players[i] == '') {
  2821.                         continue;
  2822.                     }
  2823.                     var s = players[i].split(':');
  2824.                     var id = s[0];
  2825.                     var rank = s[1];
  2826.                     var name = s[2];
  2827.                     $(".battlefield>tbody>tr.player[user_id='"+id+"']").children("td").eq(2).append('<a href="http://www.kingsofchaos.com/attack.php?id='+id+'"><img title="Stats are out of date" class="_lux_needs_update" src="http://www.luxbot.net/bot/img/luxupdate.gif" /></a>');
  2828.                 }
  2829.             });
  2830.     }
  2831.    
  2832.     function bf_online(users) {
  2833.  
  2834.         var kocids = '';
  2835.         $(".battlefield>tbody>tr.player").each(function() {
  2836.             kocids += TextBetween($(this).children('td').eq(2).html(),'id=','">')+",";
  2837.         });
  2838.        
  2839.         kocids = kocids.slice(0,-1);
  2840.         if (kocids == '')
  2841.             return;
  2842.  
  2843.         var page = TextBetween($(".battlefield>tbody>tr").last().text(), 'page ', ' of');
  2844.         var ppx = (page-1)*20+1;
  2845.  
  2846.         addCSS(" ._lux_online {position:absolute; right:240px;}");
  2847.  
  2848.         getLux('&a=bf_online&u=' + kocids,
  2849.             function(r) {
  2850.                 //GM_log(r.responseText);
  2851.                 var players = r.responseText.split(';');
  2852.                
  2853.                 for (i = 0; i < players.length; i++) {
  2854.                     if (players[i] == '') {
  2855.                         continue;
  2856.                     }
  2857.                     var s = players[i].split(':');
  2858.                     var id = s[0];
  2859.                     var rank = s[1];
  2860.                     var name = s[2];
  2861.                     $(".battlefield>tbody>tr.player").eq(rank-ppx).children("td").eq(2).append(' <sup style="color:0066CC">Online</sup>');
  2862.                 }
  2863.             });
  2864.     }  
  2865.        
  2866.     function filterUsers(users) {
  2867.         if (db.get('bffilterna', 0) == 0) {
  2868.             return;
  2869.         }
  2870.         var gold = db.get('bffiltergold', 0);
  2871.         var tff = db.get('bffiltertff', 0);
  2872.         for (i = 1; i < users.length-1;i++) {
  2873.             var x = users[i].getElementsByTagName('td');
  2874.             if (x[5].innerHTML.indexOf('???') != -1
  2875.                 || Number(x[5].innerHTML.substr(0, x[5].innerHTML.indexOf(' ')).replace(/,/g, '')) < gold
  2876.                 || Number(x[3].innerHTML.replace(/,/g, '')) < tff) {
  2877.                 users[i].style.display = 'none';
  2878.             }
  2879.         }
  2880.     }
  2881.    
  2882.     function battlefieldShowInfo() {
  2883.         c++;
  2884.         var q = document.getElementsByTagName('tr');
  2885.         var statstable;
  2886.         var lstatstable;
  2887.        
  2888.         for(var i = 0; i < q.length; i++){
  2889.             if(q[i].className == 'profile')
  2890.             {
  2891.                 statstable = q[i].getElementsByTagName('table')[2];
  2892.                 lstatstable = q[i].getElementsByTagName('table')[1];
  2893.                 break;
  2894.             }
  2895.         }
  2896.        
  2897.         if (statstable == undefined || lstatstable == undefined || lstatstable.rows[1].cells[1].childNodes[0].href.indexOf(previd) == -1) {
  2898.             if (c > 3) {
  2899.                 return;
  2900.             }
  2901.             setTimeout(battlefieldShowInfo, 1000);
  2902.             return;
  2903.         }
  2904.        
  2905.         if (lstatstable.rows[ lstatstable.rows.length-2 ].cells[0].innerHTML.indexOf('Alliances') > -1)
  2906.         {
  2907.             lstatstable.rows[ lstatstable.rows.length-2 ].cells[1].innerHTML = '<div id="_luxbot_alliances">' + lstatstable.rows[ lstatstable.rows.length-2 ].cells[1].innerHTML + '</div><a href="javascript:LuXBotShowAlliances();"> + Show</a>';
  2908.             addCSS('#_luxbot_alliances{display:none;visibility:hidden;}');
  2909.             addJS('function LuXBotShowAlliances(){var q = document.getElementById(\'_luxbot_alliances\');q.style.display = \'block\';q.style.visibility = \'visible\';q.nextSibling.href = \'javascript:LuXBotHideAlliances();\';q.nextSibling.innerHTML = \' - Hide\'}\
  2910.             function LuXBotHideAlliances(){var q = document.getElementById(\'_luxbot_alliances\');q.style.display = \'none\';q.style.visibility = \'hidden\';q.nextSibling.href = \'javascript:LuXBotShowAlliances();\';q.nextSibling.innerHTML = \' + Show\'}');
  2911.         }
  2912.        
  2913.         if (r == '403') {
  2914.             statstable.insertRow(statstable.rows.length-2).innerHTML = '<td colspan="4" style="font-weight:bold;text-align:center;background-color:#B4B5B4;color:#181818;border-bottom:1px solid black;padding:5px 0 5px 10px;">Access denied</td>';
  2915.         } else if (r == 'N/A') {
  2916.             statstable.insertRow(statstable.rows.length-2).innerHTML = '<td colspan="4" style="font-weight:bold;text-align:center;background-color:#B4B5B4;color:#181818;border-bottom:1px solid black;padding:5px 0 5px 10px;">No data available</td>';
  2917.  
  2918.  
  2919.         } else {
  2920.             var userInfo = r.split(';');
  2921.             var x;
  2922.  
  2923.             for (i = userInfo.length-1; i >= 0; i-=2) {
  2924.                 var x = statstable.insertRow(1);
  2925.                 if(typeof statsdesc[(i-1)/2] == "undefined") {
  2926.                     x.insertCell(0).innerHTML = userInfo[i-2];
  2927.                     x.insertCell(1).innerHTML = userInfo[i-1];
  2928.                     if (userInfo[i-1] == '???') {
  2929.                         x.cells[1].colSpan = 2;
  2930.                     } else {
  2931.                         x.insertCell(2).innerHTML = userInfo[i];
  2932.  
  2933.                         x.cells[2].className = '_luxbotago';
  2934.                     }
  2935.                     i -= 1;  
  2936.                 } else {
  2937.                     x.insertCell(0).innerHTML = statsdesc[(i-1)/2];
  2938.                     x.insertCell(1).innerHTML = userInfo[i-1];
  2939.                     if (userInfo[i-1] == '???') {
  2940.                         x.cells[1].colSpan = 2;
  2941.  
  2942.                     } else {
  2943.                         x.insertCell(2).innerHTML = userInfo[i];
  2944.                         x.cells[2].className = '_luxbotago';
  2945.  
  2946.                     }
  2947.                 }
  2948.             }
  2949.         }
  2950.     }
  2951.  
  2952.     function showUserInfoB() {
  2953.         document.addEventListener('click', function(event) {
  2954.             if (String(event.target).indexOf('stats.php') > -1) {
  2955.                 if (querying == true) {
  2956.                     return;
  2957.                 }
  2958.                 // battlefieldCurTarget = String(event.target);
  2959.                 var userid = String(event.target).substr(String(event.target).indexOf('=')+1, 7);
  2960.                 if (userid == previd) {
  2961.                     previd = 0;
  2962.                     return;
  2963.                 }
  2964.                 previd = userid;
  2965.                 var user;
  2966.                 querying = true;
  2967.                 //GM_log('http://' + serverURL + 'userinfo.php?userid=' + userid + '&username=' + username + '&password=' + password);
  2968.                 getLux('&a=getstats&userid=' + userid,
  2969.                     function(responseDetails) {
  2970.                         querying = false;
  2971.                         c = 0;
  2972.                         r = responseDetails.responseText;
  2973.                         //GM_log(r);
  2974.                         battlefieldShowInfo();
  2975.                 });
  2976.             }
  2977.         }, true);
  2978.     }
  2979.  
  2980.  
  2981.     //
  2982.     // LAYOUT
  2983.     //
  2984.     function commandCenterStats() {
  2985.        
  2986.         if (checkOption('option_commandCenterStats'))
  2987.             $("td.content > table > tbody").eq(0).prepend("<tr id='ff-stats'><td colspan='2'><table class='table_lines' cellpadding=6 width='100%'><tbody><tr><th colspan='2' align='center'>Your Statistics</th></tr><tr><td id='ff-load'></td></tr></tbody></table></td></tr>");//prepend(tab);
  2988.         else
  2989.             $("tr:contains('Recent Attacks'):last").parent().parent().before("<table class='table_lines' cellpadding=6 width='100%'><tbody><tr><th colspan='2' align='center'>Your Statistics</th></tr><tr><td id='ff-load'></td></tr></tbody></table>");//prepend(tab);
  2990.         getLux("&a=sabstats",
  2991.              function(r) { $("#ff-load").html(""+r.responseText);
  2992.         });
  2993.     }
  2994.    
  2995.  
  2996.     function moveRecruitbox() {
  2997.         //if player is blocking adds, this adds some extra space.
  2998.         $("td.content").parent().children("td").eq(2).attr("width","50");
  2999.    
  3000.  
  3001.  
  3002.  
  3003.         var q = document.getElementsByTagName('table');
  3004.         var x = q[6];
  3005.         var y = q[12];
  3006.         var z = q[10];
  3007.         var s = q[14];
  3008.         y.parentNode.removeChild(y.previousSibling);
  3009.         y.parentNode.removeChild(y.previousSibling);
  3010.         y.parentNode.removeChild(y.previousSibling);
  3011.         y.parentNode.removeChild(y.previousSibling);
  3012.         y.parentNode.removeChild(s.previousSibling);
  3013.         y.parentNode.removeChild(s.previousSibling);
  3014.         y.parentNode.insertBefore(s, q[11]);
  3015.         s.style.marginBottom = '20px';
  3016.        
  3017.         y.parentNode.previousSibling.previousSibling.insertBefore(y, y.parentNode.previousSibling.previousSibling.childNodes[3]);
  3018.         y.parentNode.insertBefore(document.createElement('br'), y.parentNode.childNodes[3]);
  3019.        
  3020.         x.parentNode.insertBefore(x, x.parentNode.childNodes[6]);
  3021.        
  3022.         z.childNodes[1].childNodes[0].removeEventListener('click', toggleTable, true);
  3023.         z.childNodes[1].childNodes[0].addEventListener('click', function(){
  3024.                 var q = this.parentNode.getElementsByTagName('tr');
  3025.                
  3026.                 for (b = 1; b < q.length-1;b++){
  3027.                     if (q[b].style.visibility == 'hidden') {
  3028.                         q[b].style.visibility = 'visible';
  3029.                         q[b].style.display = '';
  3030.                         if (b == 1) {
  3031.                             q[0].childNodes[1].childNodes[0].innerHTML = '-';
  3032.                             remCollapsed(this.parentNode.getElementsByTagName('span')[0].title);
  3033.                         }
  3034.                     } else {
  3035.                         q[b].style.visibility = 'hidden';
  3036.                         q[b].style.display = 'none';
  3037.                         if (b == 1) {
  3038.                             var id = this.parentNode.getElementsByTagName('span')[0].title;
  3039.                             q[0].childNodes[1].childNodes[0].innerHTML = '+';
  3040.                             if (isCollapsedx(id) == 0) {
  3041.                                 addCollapsed(id);
  3042.                             }
  3043.                         }
  3044.                     }
  3045.                 }
  3046.                 q[0].style.cursor = 'pointer';
  3047.             }, true);
  3048.        
  3049.         if (isCollapsedx(z.getElementsByTagName('span')[0].title) == 1) {
  3050.             var evt = document.createEvent("MouseEvents");
  3051.             evt.initMouseEvent("click", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
  3052.             z.childNodes[1].childNodes[0].dispatchEvent(evt);
  3053.             z.childNodes[1].childNodes[0].dispatchEvent(evt);
  3054.         }
  3055.     }
  3056.    
  3057.     function makeCollapsable() {
  3058.             coltables = db.get('coltables' + action, '').split(';');
  3059.  
  3060.         // if (action != 'base' && action != 'armory' && action != 'stats') {
  3061.             // return;
  3062.         // }
  3063.         var x = document.getElementsByTagName('table');
  3064.        
  3065.         for (j = 0; j < x.length; j++) {
  3066.             if (x[j].className.indexOf('table_lines') != -1) {
  3067.                 var row = x[j].getElementsByTagName('tr')[0];
  3068.                 var evt = document.createEvent("MouseEvents");
  3069.                 evt.initMouseEvent("click", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
  3070.                
  3071.                 if (x[j].className.indexOf('personnel') != -1) {
  3072.                     row.getElementsByTagName('span')[0].title = j;
  3073.                     if (row.getElementsByTagName('span')[0].innerHTML == '+') {
  3074.                         row.childNodes[1].dispatchEvent(evt);
  3075.                     }
  3076.                     row.addEventListener('click', function(e){
  3077.                         var span = this.getElementsByTagName('span')[0];
  3078.                         if (span.innerHTML == '+') {
  3079.                             remCollapsed(span.title);
  3080.                         } else {
  3081.                             if (isCollapsedx(span.title) == 0) {
  3082.                                 addCollapsed(span.title);
  3083.                             }
  3084.                         }
  3085.                     }, true);
  3086.                     if (isCollapsedx(j) == 1) {
  3087.                         row.childNodes[1].dispatchEvent(evt);
  3088.                     }
  3089.                 } else {
  3090.                     x[j].getElementsByTagName('th')[0].innerHTML = '<span style="float: right;" title="' + j + '">-</span>' + x[j].getElementsByTagName('th')[0].innerHTML;
  3091.                     row.addEventListener('click', toggleTable, true);
  3092.                     row.style.cursor = 'pointer';
  3093.                     if (isCollapsedx(j) == 1) {
  3094.                         row.dispatchEvent(evt);
  3095.                     }
  3096.                 }
  3097.             }
  3098.         }
  3099.     }
  3100.    
  3101.     function isCollapsedx(x) {
  3102.         for (c = 0; c < coltables.length; c++) {
  3103.             if (coltables[c] == x) {
  3104.                return 1;
  3105.             }
  3106.         }
  3107.         return 0;
  3108.     }
  3109.    
  3110.     function remCollapsed(x) {
  3111.         for (i = 0; i < coltables.length; i++) {
  3112.             if (coltables[i] == x) {
  3113.                 coltables.splice(i, 1);
  3114.             }
  3115.         }
  3116.         saveCollapsed();
  3117.     }
  3118.    
  3119.     function addCollapsed(x) {
  3120.         coltables.push(x);
  3121.         saveCollapsed();
  3122.     }
  3123.    
  3124.     function toggleTable(e) {
  3125.         var q = this.parentNode.parentNode.getElementsByTagName('tr');
  3126.        
  3127.         for (a = 1; a < q.length;a++){
  3128.             if (q[a].style.visibility == 'hidden') {
  3129.                 q[a].style.visibility = 'visible';
  3130.                 q[a].style.display = '';
  3131.                 if (a == 1) {
  3132.                     this.parentNode.getElementsByTagName('span')[0].innerHTML = '-';
  3133.                     remCollapsed(this.parentNode.getElementsByTagName('span')[0].title);
  3134.                 }
  3135.             } else {
  3136.                 q[a].style.visibility = 'hidden';
  3137.                 q[a].style.display = 'none';
  3138.                 if (a == 1) {
  3139.                     this.parentNode.getElementsByTagName('span')[0].innerHTML = '+';
  3140.                     var id = this.parentNode.getElementsByTagName('span')[0].title;
  3141.                     if (isCollapsedx(id) == 0) {
  3142.                         addCollapsed(id);
  3143.                     }
  3144.                 }
  3145.             }
  3146.         }
  3147.     }
  3148.    
  3149.     function saveCollapsed() {
  3150.         db.put('coltables' + action, coltables.join(';'));
  3151.     }
  3152.    
  3153.  
  3154.     function parseResponse(text,key) {
  3155.         tx = text.split("\t\t");
  3156.         for (t in tx) {
  3157.             var s = tx[t].split("\t");
  3158.             if (s[0] == key)
  3159.                 return s[1];
  3160.         }
  3161.         return "";
  3162.     }
  3163. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement