Advertisement
Tw100

Gerador Lista de aldeias No Mapa

Jul 20th, 2017
2,531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var debugEnabled=false;
  2. var branch=''; // for compatibility
  3. // ########################################################################
  4. // IMPORTANT: Version Information !!!
  5. // ########################################################################
  6. (window.main||self).twsfwConfig={
  7.     id:'twsfwStandalone',
  8.     version:'v0.08'
  9. };
  10. // ########################################################################
  11.  
  12. /*
  13.     Author  : Dale McKay
  14.     Email   : dalesmckay@gmail.com
  15.     Purpose : To help simplify Tribal Wars scripting by providing a common framework.
  16.     Credit  :
  17.     Todo    :
  18.     Notes   :
  19.  
  20. ____________________________________________________________
  21.  
  22. Copyright (C) 2011 Dale McKay, all rights reserved
  23. version 1.0, 10 April 2011
  24.  
  25. This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software.
  26.  
  27. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  28. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  29. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  30. This notice may not be removed or altered from any source distribution.
  31. ____________________________________________________________
  32. */
  33.  
  34.  
  35. /* *************************************** */
  36. // Borrowed plugin for converting XML to JSON
  37. /* *************************************** */
  38. if(!(window.main||self).jQuery.xml2json){
  39. /*
  40.  ### jQuery XML to JSON Plugin v1.0 - 2008-07-01 ###
  41.  * http://www.fyneworks.com/ - diego@fyneworks.com
  42.  * Dual licensed under the MIT and GPL licenses:
  43.  *   http://www.opensource.org/licenses/mit-license.php
  44.  *   http://www.gnu.org/licenses/gpl.html
  45.  ###
  46.  Website: http://www.fyneworks.com/jquery/xml-to-json/
  47. */
  48. eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';5(10.M)(w($){$.N({11:w(j,k){5(!j)t{};w B(d,e){5(!d)t y;6 f=\'\',2=y,E=y;6 g=d.x,12=l(d.O||d.P);6 h=d.v||d.F||\'\';5(d.G){5(d.G.7>0){$.Q(d.G,w(n,a){6 b=a.x,u=l(a.O||a.P);6 c=a.v||a.F||\'\';5(b==8){t}z 5(b==3||b==4||!u){5(c.13(/^\\s+$/)){t};f+=c.H(/^\\s+/,\'\').H(/\\s+$/,\'\')}z{2=2||{};5(2[u]){5(!2[u].7)2[u]=p(2[u]);2[u][2[u].7]=B(a,R);2[u].7=2[u].7}z{2[u]=B(a)}}})}};5(d.I){5(d.I.7>0){E={};2=2||{};$.Q(d.I,w(a,b){6 c=l(b.14),C=b.15;E[c]=C;5(2[c]){5(!2[c].7)2[c]=p(2[c]);2[c][2[c].7]=C;2[c].7=2[c].7}z{2[c]=C}})}};5(2){2=$.N((f!=\'\'?A J(f):{}),2||{});f=(2.v)?(D(2.v)==\'16\'?2.v:[2.v||\'\']).17([f]):f;5(f)2.v=f;f=\'\'};6 i=2||f;5(k){5(f)i={};f=i.v||f||\'\';5(f)i.v=f;5(!e)i=p(i)};t i};6 l=w(s){t J(s||\'\').H(/-/g,"18")};6 m=w(s){t(D s=="19")||J((s&&D s=="K")?s:\'\').1a(/^((-)?([0-9]*)((\\.{0,1})([0-9]+))?$)/)};6 p=w(o){5(!o.7)o=[o];o.7=o.7;t o};5(D j==\'K\')j=$.S(j);5(!j.x)t;5(j.x==3||j.x==4)t j.F;6 q=(j.x==9)?j.1b:j;6 r=B(q,R);j=y;q=y;t r},S:w(a){6 b;T{6 c=($.U.V)?A 1c("1d.1e"):A 1f();c.1g=W}X(e){Y A L("Z 1h 1i 1j 1k 1l")};T{5($.U.V)b=(c.1m(a))?c:W;z b=c.1n(a,"v/1o")}X(e){Y A L("L 1p Z K")};t b}})})(M);',62,88,'||obj|||if|var|length||||||||||||||||||||||return|cnn|text|function|nodeType|null|else|new|parseXML|atv|typeof|att|nodeValue|childNodes|replace|attributes|String|string|Error|jQuery|extend|localName|nodeName|each|true|text2xml|try|browser|msie|false|catch|throw|XML|window|xml2json|nn|match|name|value|object|concat|_|number|test|documentElement|ActiveXObject|Microsoft|XMLDOM|DOMParser|async|Parser|could|not|be|instantiated|loadXML|parseFromString|xml|parsing'.split('|'),0,{}));
  49. }
  50. /* *************************************** */
  51. // Borrowed plugin for detecting RTL
  52. /* *************************************** */
  53. if(!(window.main||self).jQuery().isRTL){
  54. /**
  55.  * Jquery Direction Detector
  56.  * Copyright (c) 2009 behrooz shabani <behrooz@rock.com>
  57.  **/
  58.  
  59. eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(9($){6 l=f;6 B=9(s){4(c s!=c""||s.y<1)2 f;6 7=s.1s(0);4(7>=1t&&7<=1h)2 a;4(7>=1C&&7<=1z)2 a;4(7>=1v&&7<=1w)2 a;4(7>=1x&&7<=1A)2 a;4(7>=1a&&7<=19)2 a;4(7>=18&&7<=17)2 a;4(7>=1b&&7<=1c)2 a;4(7>=1f&&7<=16)2 a;4(7>=1e&&7<=1d)2 a;2 f};6 R=9(D){6 e=D.1g;w(e){4(!z(e))2 e;e=e.O}2 o};6 z=9(k){2(k.h!=1&&k.h!=3)||((k.h==3)&&15(k))||((k.h==3)&&A(k))};6 15=9(k){2!(/[^\\t\\n\\r ]/.M(k.8))};6 A=9(N){4(l==f)2 f;2 l.M(N.8)};6 S=9(d){w((d=d.O))4(!z(d)&&!A(d))2 d;2 o};6 H=9(p,n){6 5=R(p);4(5&&5.h==3)2 5;w(5!=o){6 j=f;4(5&&n&&5.h==1&&5.Z())j=H(5,a);4(j&&j.h==3)2 j;4(5&&5.h==3)2 5;5=S(5)}2 f};6 P=9(d){w((d=d.10))4(!z(d)&&!A(d))2 d;2 o};6 T=9(D){6 e=D.1D;w(e){4(!z(e))2 e;e=e.10}2 o};6 J=9(p,n){6 5=T(p);4(5&&5.h==3)2 5;w(5!=o){6 j=f;4(5&&n&&5.h==1&&5.Z())j=J(5,a);4(j&&j.h==3)2 j;4(5&&5.h==3)2 5;5=P(5)}2 f};6 G=9(K){4(!K)2"";6 8=K.8;8=8.C(/[\\t\\n\\r ]+/g," ");4(l!=f)8=8.C(I,"");4(8.Q(0)==" ")8=8.L(1,8.y);4(8.Q(8.y-1)==" ")8=8.L(0,8.y-1);2 8};$.12.1u=9(m,Y,x,v){4(c x!=c a)x=a;4(c v==c\'\'){6 11=["\\\\","[","]","{","}","\\n","\\t","\\r"];6 E=["\\\\\\\\",\'\\\\[\',\'\\\\]\',\'\\\\{\',\'\\\\}\',\'\\\\n\',\'\\\\t\',\'\\\\r\'];1B(6 i=0;i<E.y;i++)v=v.C(11[i],E[i]);l=13 14(\'^[\'+v+\']+$\',\'g\');I=13 14(\'^[\'+v+\']+\',\'g\')}u l=f;2 b.1l(9(){4(b.V.F()==\'1k\'||b.V.F()==\'1j\'&&b.U(\'W\')&&b.U(\'W\').F()==\'1i\')q=l==f?$(b).X():$(b).X().C(I,\'\');u{4(Y==a)6 q=G(J(b,x));u 6 q=G(H(b,x))}4(c m==c 9(){})m(b,B(q),q);u 4(B(q)){4(c m==c"")$(b).1m(m);u 4(c m==c{})$(b).1n(m);u b.1r("1q","1p")}})};$.12.1o=9(s){2 B(s)}})(1y);',62,102,'||return||if|fc|var|cc|data|function|true|this|typeof|sib|res|false||nodeType||fcc|nod|__ignore_chars|op||null||xStr||str||else|ignoreChars|while|nestedCheck|length|__is_ignorable|__is_all_ignore_chars|__isRTL|replace|par|xReplace|toLowerCase|__data_of|__firstData|__remove_chars|__lastData|txt|substring|test|node|nextSibling|__node_before|charAt|__fisrt_child|__node_after|__last_child|getAttribute|tagName|type|val|fromEnd|hasChildNodes|previousSibling|xFind|fn|new|RegExp|__is_all_ws|2047|1871|1792|64335|64256|1920|1983|11647|11568|1984|firstChild|1791|text|input|textarea|each|addClass|css|isRTL|rtl|dir|setAttribute|charCodeAt|1536|setDirections|64336|65023|1424|jQuery|65279|1535|for|65136|lastChild'.split('|'),0,{}))
  60. }
  61. /* *************************************** */
  62.  
  63.  
  64. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  65. // $.twCache(), $.twConfig(), $.twUtil()
  66. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  67. (function($){
  68.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  69.     // Public:
  70.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  71.     function fnAjax(url,method,params,type,isAsync,callback){
  72.         var payload=null;
  73.        
  74.         $.ajax({
  75.             'async':isAsync,
  76.             'url':url,
  77.             'data':params,
  78.             'dataType':type,
  79.             'type':String(method||'GET').toUpperCase(),
  80.             'error':function(req,status,err){throw(status);},
  81.             'success':function(data,status,req){if(!isAsync){payload=data;}if(typeof(callback)=='function'){callback(data,status,req);}}
  82.         });
  83.        
  84.         if(!isAsync){
  85.             if(typeof(callback)=='function'){
  86.                 callback(payload);
  87.             }
  88.  
  89.             return payload;
  90.         }
  91.     } // fnAjax
  92.     // ........................................................................
  93.     function fnAsString(AObj,showFuncCode,maxDepth){
  94.         function fnRecursiveAsString(object,depth){
  95.             if(depth>maxDepth){
  96.                 return false;
  97.             }
  98.  
  99.             var indent='';
  100.             for(var ii=0; ii<depth; ii++){
  101.                 indent+='\t';
  102.             }
  103.  
  104.             var output='';  
  105.             for(var key in object){
  106.                 output+='\n'+indent+key+': ';
  107.                 switch(typeof(object[key])){
  108.                     case 'object':output+=fnRecursiveAsString(object[key],depth+1);break;
  109.                     case 'function':output+=((showFuncCode||false)?object[key]:'function');break;
  110.                     default:output+=object[key];break;        
  111.                 }
  112.             }
  113.  
  114.             return output;
  115.         }
  116.  
  117.         maxDepth=maxDepth||10;
  118.         return fnRecursiveAsString((typeof(AObj)=='undefined')?this||{}:AObj,0)||'';
  119.     } // fnAsString
  120.     // ........................................................................
  121.     function fnPrint(msg,id){
  122.         var myself=this;
  123.         var outputID=(myself.id||win.twsfwConfig.id);
  124.    
  125.         if($('#'+outputID).length<=0){
  126.             $('body').append('<div id="'+outputID+'"></div>');
  127.         }
  128.    
  129.         $('#'+outputID).append('<span id="'+(id||'')+'">'+msg+'</span><br/>');
  130.     } // fnPrint
  131.     // ........................................................................
  132.     function fnDebug(msg){
  133.         var myself=this;
  134.         if(debugEnabled){
  135.             fnPrint(msg);
  136.         }
  137.     } // fnDebug
  138.     // ........................................................................
  139.     function fnHandleError(objError,showAlert){
  140.         var myself=this;
  141.    
  142.         var errMsg=String(objError.message||objError||'');
  143.         if(errMsg){
  144.             fnPrint('Error: ' + errMsg);
  145.            
  146.             if((typeof(showAlert)=='undefined')||showAlert){
  147.                 alert('Error: ' + errMsg);
  148.             }
  149.         }
  150.     } // fnHandleError
  151.     // ........................................................................
  152.     function fnDebugEnabled(isEnabled){
  153.         if(typeof(isEnabled)=='undefined'){
  154.             return debugEnabled;
  155.         }
  156.        
  157.         debugEnabled=isEnabled;
  158.     } // fnDebugEnabled
  159.     // ........................................................................
  160.     // NOTE: this function must be called externally since it uses $.twConfig()
  161.     function fnPrintVersion(script){
  162.         var twConfig=$.twConfig();
  163.        
  164.         var authorURL=script.author.url?('<a href="'+script.author.url+'" target="_blank">'+script.author.name+'</a>'):script.author.name;
  165.        
  166.         fnPrint("=========================");
  167.         fnPrint(authorURL + "'s " + script.name + ": v" + script.version.toFixed(2) + (script.credit?('<br/>'+script.credit):''));
  168.         fnPrint("=========================");
  169.         fnPrint($.trim($('.server_info').text().match(/\|\s*(.+)/)[1]));
  170.         fnPrint("Account: "+win.game_data.player.name);
  171.         fnPrint("Premium: "+(twConfig.isPremium?"yes":"no"));
  172.         fnPrint("Church : "+(twConfig.hasChurch?"yes":"no"));
  173.         fnPrint("Statue : "+(twConfig.hasPaladin?"yes":"no"));
  174.         fnPrint("Archer : "+(twConfig.hasArchers?"yes":"no"));
  175.         fnPrint("Militia: "+(twConfig.hasMilitia?"yes":"no"));
  176.         fnPrint("Notes  : "+(twConfig.hasVillageNotes?"yes":"no"));
  177.         //fnPrint("Sitter : "+(win.location.href.match(/t\=\d+/i)?"yes":"no"));
  178.         fnPrint("Sitter : "+((fnInt(win.game_data.player.sitter_id)>0)?("yes - "+win.game_data.player.sitter_id):"no"));
  179.         fnPrint("=========================");
  180.         fnPrint("Version: "+win.game_data.version);
  181.         fnPrint("World  : "+win.game_data.world);
  182.         fnPrint("Screen : "+win.game_data.screen);
  183.         fnPrint("Mode   : "+win.game_data.mode);
  184.         fnPrint("URL    : "+win.location.href);
  185.         //fnDebug("isRTL  : "+(twConfig.isRTL?"yes":"no"));
  186.         fnPrint("Browser: "+navigator.userAgent);
  187.         fnPrint("=========================");
  188.         fnPrint("Framework Version: "+win.twsfwConfig.version+' - '+win.twsfwConfig.id);
  189.         fnPrint("=========================");
  190.     } // fnPrintVersion
  191.     // ........................................................................
  192.     function fnFisherYatesShuffle(srcArray){
  193.         // This function privates a better "random" implementation.
  194.         var ii=srcArray.length;
  195.        
  196.         if(ii>1){
  197.             var kk,tmp;
  198.            
  199.             while(--ii){
  200.                 kk=Math.floor(Math.random()*(ii+1));
  201.                 tmp=srcArray[ii];
  202.                 srcArray[ii]=srcArray[kk];
  203.                 srcArray[kk]=tmp;
  204.             }
  205.         }
  206.        
  207.         return srcArray;
  208.     } // fnFisherYatesShuffle
  209.     // ........................................................................
  210.     function fnStrToDate(value){
  211.         // Remove milli-seconds.
  212.         var zzz=value.match(/\b.(\d{3})$/i);
  213.         zzz=fnInt(zzz?zzz[1]:'0');
  214.         value=value.replace(/\b(.\d{3})$/i,'');
  215.            
  216.         // Date format: May 10 2011 03:00:00
  217.         if(value.match(/\b(\w{3})\b/i)){
  218.             var dtNew=new Date(value);
  219.             if(zzz>0){
  220.                 // Add the milli-seconds
  221.                 dtNew.setMilliseconds(zzz);
  222.             }
  223.                
  224.             return dtNew;
  225.         }
  226.  
  227.         // Date Format: 10.05.11 03:00:00
  228.         var arrDate=value.match(/\b(\d+)\b/ig);
  229.         var dd=fnInt(arrDate[0]||'1');
  230.         var mm=fnInt(arrDate[1]||'1')-1; // Month is Zero-based
  231.         var yy=fnInt(arrDate[2]);if(yy<100){yy+=1900+Math.floor(new Date().getYear()/100)*100;}
  232.         var hh=fnInt(arrDate[3]);
  233.         var nn=fnInt(arrDate[4]);
  234.         var ss=fnInt(arrDate[5]);
  235.        
  236.         return new Date(yy,mm,dd,hh,nn,ss,zzz);
  237.     } // fnStrToDate
  238.     // ........................................................................
  239.     function fnFormatMilliSeconds(value){
  240.         var ss=value/1000;
  241.         var nn=ss/60;
  242.         var hh=Math.floor(nn/60);
  243.         nn=Math.floor(nn) % 60;
  244.         ss=Math.floor(ss) % 60;
  245.    
  246.         return (hh<10?'0':'')+hh+':'+(nn<10?'0':'')+nn+':'+(ss<10?'0':'')+ss;
  247.     } // fnFormatMilliSeconds
  248.     // ........................................................................
  249.     function fnFormatMilliSeconds2(ms,wantExtendedTime){
  250.         var sec=ms/1000;
  251.         var min=sec/60;
  252.         var hrs=min/60;
  253.         var days=hrs/24;
  254.         var wk=days/7;
  255.         var mth=wk/4;
  256.         var yr=mth/12;
  257.        
  258.         if(wantExtendedTime){
  259.             // Years:Months
  260.             if(Math.floor(yr)>0){
  261.                 return Math.floor(yr)+':'+((Math.round(mth)%(12))<10?'0':'')+Math.round(mth)%(12)+' Yr';
  262.             }
  263.            
  264.             // Weeks:Days
  265.             if(Math.floor(wk)>4){
  266.                 return Math.floor(wk)+':'+((Math.round(days)%(7))<10?'0':'')+Math.round(days)%(7)+' Wk';
  267.             }
  268.            
  269.             // Days:Hours
  270.             if(Math.floor(days)>0){
  271.                 return Math.floor(days)+':'+((Math.round(hrs)%(24))<10?'0':'')+Math.round(hrs)%(24)+' D';
  272.             }
  273.            
  274.             // Hours:Minutes
  275.             if(Math.floor(hrs)>0){
  276.                 return Math.floor(hrs)+':'+((Math.floor(min)%(60))<10?'0':'')+Math.floor(min)%(60)+' hrs';
  277.             }
  278.            
  279.             // Minutes:Seconds
  280.             return (Math.floor(min)%(60))+':'+((Math.floor(sec)%(60))<10?'0':'')+Math.floor(sec)%(60)+' min';
  281.         }
  282.        
  283.         // Display as fraction.
  284.         if(Math.floor(days)>0){
  285.             return days.toFixed(2)+' D';
  286.         }
  287.         if(Math.floor(hrs)>0){
  288.             return hrs.toFixed(2)+' hrs';
  289.         }
  290.        
  291.         // Minutes:Seconds
  292.         return (Math.floor(min)%(60))+':'+((Math.floor(sec)%(60))<10?'0':'')+Math.floor(sec)%(60)+' min';
  293.     } // fnFormatMilliSeconds2
  294.     // ........................................................................
  295.     function fnInt(value){return parseInt(value||'0',10);}
  296.     // ........................................................................
  297.     function fnResourceProduction(lvl){return ((lvl==0)?5:Math.round(30*Math.pow(80,(lvl-1)/29)))*fnInt($.twConfig().world.speed||'1');}
  298.     // ........................................................................
  299.     function fnWarehouseCapacity(lvl){return(lvl<=1)?1000:Math.round(1000*Math.pow(400,(lvl-1)/29));}
  300.     // ........................................................................
  301.     function fnHidingPlaceCapacity(lvl){return(lvl<=1)?0:Math.round(150*Math.pow(40/3,(lvl-1)/9));}
  302.     // ........................................................................
  303.     function fnServerTime(){
  304.         var servertime = $('#serverTime').text().match(/\d+/g);
  305.         var serverDate = $('#serverDate').text().match(/\d+/g);
  306.         return new Date(serverDate[1]+'/'+serverDate[0]+'/'+serverDate[2]+' '+servertime.join(':'));
  307.     } // fnServerTime
  308.     // ........................................................................
  309.     function fnFields(from,to){
  310.         var source=((from instanceof Array)?from:from.split('|')).map(function(e){return fnInt(e);});
  311.         var target=((to instanceof Array)?to:to.split('|')).map(function(e){return fnInt(e);});
  312.         return Math.sqrt(Math.pow(target[0]-source[0],2)+Math.pow(target[1]-source[1],2));
  313.     } // fnFields
  314.     // ........................................................................
  315.     // ISSUE: converts some legimate '+' characters to whitespace
  316.     // TODO: raise a support ticket to get world data generated using encodeURIComponent (rather than escape)
  317.     function fnDecode(value){return decodeURIComponent(value).replace(/\+/g,' ');} 
  318.     // ........................................................................
  319.     function fnFetchVillagesWorldDAT(refreshRateHRS){
  320.         var villagesDAT=cache.fetch('villagesDAT');
  321.        
  322.         // Minimum refreshRateHRS is 1 hour.
  323.         refreshRateHRS=Math.max(1,fnInt(refreshRateHRS));
  324.        
  325.         if(!villagesDAT||(Math.floor(((new Date().getTime())-villagesDAT.lastRefresh)/(1000*60*60))>=refreshRateHRS)){
  326.             fnPrint('Refreshing villages from worldDAT...');
  327.  
  328.             var villages={};
  329.  
  330.             fnAjax('/map/village.txt','GET',{},'text',false,function(data,status,req){     
  331.                 $.each((data||'').split(/\n/g),function(i,e){
  332.                     var line=e.split(/,/);
  333.                     var x=fnInt(line[2]);
  334.                     var y=fnInt(line[3]);
  335.                     var coord=x+'|'+y;
  336.                     var village={
  337.                         id:fnInt(line[0]),
  338.                         name:fnDecode(line[1]),
  339.                         coord:coord,
  340.                         ownerID:fnInt(line[4]),
  341.                         points:fnInt(line[5]),
  342.                         continent:(Math.floor(y/100)*10)+Math.floor(x/100)
  343.                     };
  344.  
  345.                     villages[coord]=village;
  346.                 });
  347.                
  348.                 cache.store('villagesDAT',{lastRefresh:(new Date().getTime()),data:villages});
  349.             });
  350.            
  351.             return villages;
  352.         }
  353.  
  354.         return villagesDAT.data;
  355.     } // fnFetchVillagesWorldDAT
  356.     // ........................................................................
  357.     function fnFetchPlayersWorldDAT(refreshRateHRS){
  358.         var playersDAT=cache.fetch('playersDAT');
  359.        
  360.         // Minimum refreshRateHRS is 1 hour.
  361.         refreshRateHRS=Math.max(1,fnInt(refreshRateHRS));
  362.        
  363.         if(!playersDAT||(Math.floor(((new Date().getTime())-playersDAT.lastRefresh)/(1000*60*60))>=refreshRateHRS)){
  364.             fnPrint('Refreshing players from worldDAT...');
  365.  
  366.             var players={};
  367.  
  368.             fnAjax('/map/player.txt','GET',{},'text',false,function(data,status,req){      
  369.                 $.each((data||'').split(/\n/g),function(i,e){
  370.                     var line=e.split(/,/);
  371.                     var name=fnDecode(line[1]);
  372.                     var player={
  373.                         id:fnInt(line[0]),
  374.                         name:name,
  375.                         tribeID:fnInt(line[2]),
  376.                         villages:fnInt(line[3]),
  377.                         points:fnInt(line[4]),
  378.                         rank:fnInt(line[5])
  379.                     };
  380.  
  381.                     players[name.toLowerCase()]=player;
  382.                 });
  383.  
  384.                 cache.store('playersDAT',{lastRefresh:(new Date().getTime()),data:players});
  385.             });
  386.            
  387.             return players;
  388.         }
  389.  
  390.         return playersDAT.data;
  391.     } // fnFetchPlayersWorldDAT
  392.     // ........................................................................
  393.     function fnFetchTribesWorldDAT(refreshRateHRS){
  394.         var tribesDAT=cache.fetch('tribesDAT');
  395.        
  396.         // Minimum refreshRateHRS is 1 hour.
  397.         refreshRateHRS=Math.max(1,fnInt(refreshRateHRS));
  398.        
  399.         if(!tribesDAT||(Math.floor(((new Date().getTime())-tribesDAT.lastRefresh)/(1000*60*60))>=refreshRateHRS)){
  400.             fnPrint('Refreshing tribes from worldDAT...');
  401.  
  402.             var tribes={};
  403.  
  404.             fnAjax('/map/ally.txt','GET',{},'text',false,function(data,status,req){    
  405.                 $.each((data||'').split(/\n/g),function(i,e){
  406.                     var line=e.split(/,/);
  407.                     var tag=fnDecode(line[2]);
  408.                     var tribe={
  409.                         id:fnInt(line[0]),
  410.                         name:fnDecode(line[1]),
  411.                         tag:tag,
  412.                         members:fnInt(line[3]),
  413.                         villages:fnInt(line[4]),
  414.                         points:fnInt(line[5]),
  415.                         allPoints:fnInt(line[6]),
  416.                         rank:fnInt(line[7])
  417.                     };
  418.  
  419.                     tribes[tag.toLowerCase()]=tribe;
  420.                 });
  421.  
  422.                 cache.store('tribesDAT',{lastRefresh:(new Date().getTime()),data:tribes});
  423.             });
  424.            
  425.             return tribes;
  426.         }
  427.  
  428.         return tribesDAT.data;
  429.     } // fnFetchTribesWorldDAT
  430.     // ........................................................................
  431.     function fnFetchConquersWorldDAT(refreshRateHRS){
  432.         var conquersDAT=cache.fetch('conquersDAT');
  433.        
  434.         // Minimum refreshRateHRS is 1 hour.
  435.         refreshRateHRS=Math.max(1,fnInt(refreshRateHRS));
  436.        
  437.         if(!conquersDAT||(Math.floor(((new Date().getTime())-conquersDAT.lastRefresh)/(1000*60*60))>=refreshRateHRS)){
  438.             fnPrint('Refreshing conquers from worldDAT...');
  439.  
  440.             var ennoblement={};
  441.  
  442.             fnAjax('/map/conquer.txt','GET',{},'text',false,function(data,status,req){     
  443.                 $.each((data||'').split(/\n/g),function(i,e){
  444.                     var line=e.split(/,/);
  445.                     var ennoblement={
  446.                         villageID:fnInt(line[0]),
  447.                         unixTime:fnInt(line[1]),
  448.                         attackerID:fnInt(line[2]),
  449.                         victimID:fnInt(line[3])
  450.                     };
  451.  
  452.                     conquers[villageID]=ennoblement;
  453.                 });
  454.  
  455.                 cache.store('conquersDAT',{lastRefresh:(new Date().getTime()),data:conquers});
  456.             });
  457.            
  458.             return conquers;
  459.         }
  460.  
  461.         return conquersDAT.data;
  462.     } // fnFetchConquersWorldDAT
  463.     // ........................................................................
  464.     function fnZeroPad(value,length){var n=value.toString();while(n.length<length){n='0'+n;}return n;}
  465.     // ........................................................................
  466.     function fnExtractCoord(aText){var coord=(aText||'').match(/\d+\|\d+/g);return coord?coord[coord.length-1]:null;}
  467.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  468.     // Private:
  469.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  470.     function fnAppendToJQueryNamespace(){
  471.         $.extend({
  472.             'twCache':function(createNew){
  473.                 return ((createNew||false)?(new CacheProvider()):cache);
  474.             },
  475.             'twConfig':function(){return{
  476.                 'buildings':buildingConfig,
  477.                 'units':unitConfig,
  478.                 'world':worldConfig,
  479.                 'fetchVillagesDAT':fnFetchVillagesWorldDAT,
  480.                 'fetchPlayersDAT':fnFetchPlayersWorldDAT,
  481.                 'fetchTribesDAT':fnFetchTribesWorldDAT,
  482.                 'fetchConquersDAT':fnFetchConquersWorldDAT,
  483.                 'version':gameVersion,
  484.                 'hasChurch':(fnInt(worldConfig.game.church)>0),
  485.                 'hasPaladin':(fnInt(worldConfig.game.knight)>0),
  486.                 'hasArchers':(fnInt(worldConfig.game.archer)>0),
  487.                 'hasMilitia':(typeof(unitConfig.militia)!='undefined'),
  488.                 'isPremium':($('#quickbar_outer').length>0),
  489.                 'hasVillageNotes':($('[src*="note.png"],[class*="note-icon"]').length>0),
  490.                 'hasMinVersion':function(minVersion){return (gameVersion>=minVersion);},
  491.                 'isRTL':$().isRTL($('body').text()),
  492.                 'printVersion':fnPrintVersion
  493.             };},
  494.             'twUtil':function(){return{
  495.                 'ajax':fnAjax,
  496.                 'asString':fnAsString,
  497.                 'print':fnPrint,
  498.                 'debug':fnDebug,
  499.                 'handleError':fnHandleError,
  500.                 'debugEnabled':fnDebugEnabled,
  501.                 'shuffle':fnFisherYatesShuffle,
  502.                 'strToDate':fnStrToDate,
  503.                 'formatMS':fnFormatMilliSeconds,
  504.                 'formatMS2':fnFormatMilliSeconds2,
  505.                 'int':fnInt,
  506.                 'resourceProduction':fnResourceProduction,
  507.                 'warehouseCapacity':fnWarehouseCapacity,
  508.                 'hidingPlaceCapacity':fnHidingPlaceCapacity,
  509.                 'serverTime':fnServerTime,
  510.                 'fields':fnFields,
  511.                 'zeroPad':fnZeroPad,
  512.                 'extractCoord':fnExtractCoord
  513.             };}
  514.         });
  515.     } // fnAppendToJQueryNamespace
  516.     // ........................................................................
  517.     function fnCheckFrameworkVersion(){
  518.         // Update any data if a different version is found.
  519.         var myVersion=cache.fetch('twsfwVersion');
  520.         var needReset=(!myVersion||(myVersion!==win.twsfwConfig.version));
  521.         if(needReset){
  522.             cache.clear('buildingConfig');
  523.             cache.clear('unitConfig');
  524.             cache.clear('worldConfig');
  525.            
  526.             // Don't reset these... they can be refreshed hourly
  527.             //cache.clear('villagesDAT');
  528.             //cache.clear('playersDAT');
  529.             //cache.clear('tribesDAT');
  530.        
  531.             myVersion=cache.store('twsfwVersion',win.twsfwConfig.version);
  532.         }
  533.     } // fnCheckFrameworkVersion
  534.     // ........................................................................
  535.     function fnEnsureBrowserCompatibility(){
  536.         'use strict';
  537.  
  538.         /* Add ECMA262-5 method binding if not supported natively */
  539.         /**/
  540.         if (!('bind' in Function.prototype)) {
  541.             Function.prototype.bind= function(owner) {
  542.                 var that= this;
  543.                 if (arguments.length<=1) {
  544.                     return function() {
  545.                         return that.apply(owner, arguments);
  546.                     };
  547.                 }
  548.                 else {
  549.                     var args= Array.prototype.slice.call(arguments, 1);
  550.                     return function() {
  551.                         return that.apply(owner, arguments.length===0? args : args.concat(Array.prototype.slice.call(arguments)));
  552.                     };
  553.                 }
  554.             };
  555.         }
  556.  
  557.         /* Add ECMA262-5 string trim if not supported natively */
  558.         /**/
  559.         if (!('trim' in String.prototype)) {
  560.             String.prototype.trim= function() {
  561.                 return this.replace(/^\s+/, '').replace(/\s+$/, '');
  562.             };
  563.         }
  564.  
  565.         /* Add ECMA262-5 Array methods if not supported natively */
  566.         /**/
  567.         if (!('indexOf' in Array.prototype)) {
  568.             Array.prototype.indexOf= function(find, i /*opt*/) {
  569.                 if (i===undefined) i= 0;
  570.                 if (i<0) i+= this.length;
  571.                 if (i<0) i= 0;
  572.                 for (var n= this.length; i<n; i++)
  573.                     if (i in this && this[i]===find)
  574.                         return i;
  575.                 return -1;
  576.             };
  577.         }
  578.         if (!('lastIndexOf' in Array.prototype)) {
  579.             Array.prototype.lastIndexOf= function(find, i /*opt*/) {
  580.                 if (i===undefined) i= this.length-1;
  581.                 if (i<0) i+= this.length;
  582.                 if (i>this.length-1) i= this.length-1;
  583.                 for (i++; i-->0;) /* i++ because from-argument is sadly inclusive */
  584.                     if (i in this && this[i]===find)
  585.                         return i;
  586.                 return -1;
  587.             };
  588.         }
  589.         if (!('forEach' in Array.prototype)) {
  590.             Array.prototype.forEach= function(action, that /*opt*/) {
  591.                 for (var i= 0, n= this.length; i<n; i++)
  592.                     if (i in this)
  593.                         action.call(that, this[i], i, this);
  594.             };
  595.         }
  596.         if (!('map' in Array.prototype)) {
  597.             Array.prototype.map= function(mapper, that /*opt*/) {
  598.                 var other= new Array(this.length);
  599.                 for (var i= 0, n= this.length; i<n; i++)
  600.                     if (i in this)
  601.                         other[i]= mapper.call(that, this[i], i, this);
  602.                 return other;
  603.             };
  604.         }
  605.         if (!('filter' in Array.prototype)) {
  606.             Array.prototype.filter= function(filter, that /*opt*/) {
  607.                 var other= [], v;
  608.                 for (var i=0, n= this.length; i<n; i++)
  609.                     if (i in this && filter.call(that, v= this[i], i, this))
  610.                         other.push(v);
  611.                 return other;
  612.             };
  613.         }
  614.         if (!('every' in Array.prototype)) {
  615.             Array.prototype.every= function(tester, that /*opt*/) {
  616.                 for (var i= 0, n= this.length; i<n; i++)
  617.                     if (i in this && !tester.call(that, this[i], i, this))
  618.                         return false;
  619.                 return true;
  620.             };
  621.         }
  622.         if (!('some' in Array.prototype)) {
  623.             Array.prototype.some= function(tester, that /*opt*/) {
  624.                 for (var i= 0, n= this.length; i<n; i++)
  625.                     if (i in this && tester.call(that, this[i], i, this))
  626.                         return true;
  627.                 return false;
  628.             };
  629.         }
  630.     } // fnEnsureBrowserCompatibility
  631.     // ........................................................................
  632.     function fnLoadBuildingConfig(){
  633.         buildingConfig=cache.fetch('buildingConfig');
  634.         if(!buildingConfig){
  635.             fnPrint('Refreshing buildingConfig...');
  636.  
  637.             fnAjax('/interface.php','GET',{'func':'get_building_info'},'xml',false,function(data,status,req){
  638.                 buildingConfig=$.xml2json(data);
  639.                 cache.store('buildingConfig',buildingConfig);
  640.             });
  641.         }
  642.        
  643.         if(!buildingConfig.main.name){
  644.             fnPrint('Refreshing Building Translation Strings...');
  645.  
  646.             var hasHelpPageContent=false;
  647.  
  648. /*
  649.             fnAjax('/help2.php','GET',{'article':'buildings'},'html',false,function(data,status,req){  
  650.                 var buildingInfo=$(data).find('[href*="building="]');
  651.                 hasHelpPageContent=(buildingInfo&&(buildingInfo.length>0));
  652.                 if(hasHelpPageContent){
  653.                     buildingInfo.each(function(i,e){
  654.                         var buildingID=e.href.match(/building\=(\w+)/i)[1];
  655.                         buildingConfig[buildingID].name=$.trim($(e).text());
  656.                     });
  657.                    
  658.                     hasHelpPageContent=!!buildingConfig.main.name;
  659.                 }
  660.  
  661.                 if(hasHelpPageContent){
  662.                     cache.store('buildingConfig',buildingConfig);
  663.                 }
  664.             });
  665. */
  666.             if(!hasHelpPageContent){
  667. //              fnPrint('<span style="color:red;">ERROR: Missing "/help2.php?article:buildings" page content... (SEND A SUPPORT TICKET!!!)</span>');
  668.  
  669.                 // NOTE: This will cause issues for non-English Servers.
  670.                 var defaultBuildingNames={
  671.                     main:{name:'Village Headquarters'},
  672.                     barracks:{name:'Barracks'},
  673.                     stable:{name:'Stable'},
  674.                     garage:{name:'Workshop'},
  675.                     church:{name:'Church'},
  676.                     church_f:{name:'First church'},
  677.                     snob:{name:'Academy'},
  678.                     smith:{name:'Smithy'},
  679.                     place:{name:'Rally point'},
  680.                     statue:{name:'Statue'},
  681.                     market:{name:'Market'},
  682.                     wood:{name:'Timber camp'},
  683.                     stone:{name:'Clay pit'},
  684.                     iron:{name:'Iron mine'},
  685.                     farm:{name:'Farm'},
  686.                     storage:{name:'Warehouse'},
  687.                     hide:{name:'Hiding place'},
  688.                     wall:{name:'Wall'}
  689.                 };
  690.  
  691.                 $.extend(true,buildingConfig,defaultBuildingNames);
  692.             }
  693.         }
  694.     } // fnLoadBuildingConfig
  695.     // ........................................................................
  696.     function fnLoadUnitConfig(){
  697.         unitConfig=cache.fetch('unitConfig');
  698.         if(!unitConfig){
  699.             fnPrint('Refreshing unitConfig...');
  700.            
  701.             fnAjax('/interface.php','GET',{'func':'get_unit_info'},'xml',false,function(data,status,req){
  702.                 unitConfig=$.xml2json(data);
  703.                 cache.store('unitConfig',unitConfig);
  704.             });
  705.         }
  706.            
  707.         if(!unitConfig.spear.name){
  708.             fnPrint('Refreshing Unit Translation Strings...');
  709.  
  710.             var hasHelpPageContent=false;
  711.  
  712. /*
  713.             fnAjax('/help2.php','GET',{'article':'units'},'html',false,function(data,status,req){
  714.                 var unitInfo=$(data).find('[href*="unit="]');
  715.                 hasHelpPageContent=(unitInfo&&(unitInfo.length>0));
  716.                 if(hasHelpPageContent){
  717.                     unitInfo.each(function(i,e){
  718.                         var unitID=e.href.match(/unit\=(\w+)/i)[1];
  719.                         unitConfig[unitID].name=$.trim($(e).text());
  720.                     });
  721.                    
  722.                     hasHelpPageContent=!!unitConfig.spear.name;
  723.                 }
  724.  
  725.                 if(hasHelpPageContent){
  726.                     cache.store('unitConfig',unitConfig);
  727.                 }
  728.             });
  729. */
  730.  
  731.             if(!hasHelpPageContent){
  732. //              fnPrint('<span style="color:red;">ERROR: Missing "/help2.php?article:units" page content... (SEND A SUPPORT TICKET!!!)</span>');
  733.                
  734.                 // NOTE: This will cause issues for non-English Servers.
  735.                 var defaultUnitNames={
  736.                     spear:{name:'Spear fighter'},
  737.                     sword:{name:'Swordsman'},
  738.                     axe:{name:'Axeman'},
  739.                     archer:{name:'Archer'},
  740.                     spy:{name:'Scout'},
  741.                     light:{name:'Light cavalry'},
  742.                     marcher:{name:'Mounted archer'},
  743.                     heavy:{name:'Heavy cavalry'},
  744.                     ram:{name:'Ram'},
  745.                     catapult:{name:'Catapult'},
  746.                     knight:{name:'Paladin'},
  747.                     snob:{name:'Nobleman'},
  748.                     militia:{name:'Militia'}
  749.                 };
  750.  
  751.                 $.extend(true,unitConfig,defaultUnitNames);
  752.             }
  753.         }
  754.     } // fnLoadUnitConfig
  755.     // ........................................................................
  756.     function fnLoadWorldConfig(){
  757.         worldConfig=cache.fetch('worldConfig');
  758.         if(!worldConfig){
  759.             fnPrint('Refreshing worldConfig...');
  760.             fnAjax('/interface.php','GET',{'func':'get_config'},'xml',false,function(data,status,req){
  761.                 worldConfig=cache.store('worldConfig',$.xml2json(data));
  762.             });
  763.         }
  764.     } // fnLoadWorldConfig
  765.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  766.     // Class: CacheProvider
  767.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  768.     function CacheProvider(){
  769.         var myself=this;
  770.  
  771.         myself._cache={};
  772.  
  773.         myself._useLocalStorage=true;
  774.         try{
  775.             myself._useLocalStorage=myself._useLocalStorage&&('localStorage' in win)&&(win['localStorage']!==null);
  776.         }
  777.         catch(objError){
  778.             myself._useLocalStorage=false;
  779.         }
  780.    
  781.         return{
  782.             'fetch':function(key){
  783.                 return (myself._useLocalStorage?JSON.parse(localStorage.getItem(key)):myself._cache[key])||undefined;
  784.             },
  785.        
  786.             'store':function(key,value){
  787.                 if(myself._useLocalStorage){
  788.                     try{
  789.                         localStorage.setItem(key,JSON.stringify(value));
  790.                     }
  791.                     catch(objError){
  792.                         if(objError.name=='QUOTA_EXCEEDED_ERR'){
  793.                             throw new Exception(value);
  794.                         }
  795.                     }
  796.                 }
  797.                 else{
  798.                     myself._cache[key]=value;
  799.                 }
  800.  
  801.                 return value;
  802.             },
  803.  
  804.             'clear':function(key){
  805.                 if(myself._useLocalStorage){
  806.                     if(key){
  807.                         localStorage.removeItem(key);
  808.                         return;
  809.                     }
  810.                
  811.                     if(confirm('Are you sure you really want to delete ALL LocalStorage\nitems from this Domain?\n(This action can NOT be undone)')){
  812.                         for(key in localStorage){
  813.                             if(localStorage.hasOwnProperty(key)){
  814.                                 localStorage.removeItem(key);
  815.                             }
  816.                         }
  817.                     }
  818.                 }
  819.                 else{
  820.                     // NOTE: "delete" is not supported by some flavours of IE
  821.                     //delete myself._cache[key];
  822.                     myself._cache[key]=null;
  823.                 }
  824.             },
  825.        
  826.             'rename':function(oldKey,newKey,overwrite){
  827.                 var obj=this.fetch(newKey);
  828.                 if(obj&&!overwrite){
  829.                     return false;
  830.                 }
  831.                
  832.                 obj=this.fetch(oldKey);
  833.                 if(obj){
  834.                     this.clear(oldKey);
  835.                     return this.store(newKey,obj);
  836.                 }
  837.                
  838.                 return false;                  
  839.             },
  840.  
  841.             'spaceUsed':function(){
  842.                 return '*** NOT IMPLEMENTED ***';
  843.             },
  844.        
  845.             'spaceRemaining':function(){
  846.                 return '*** NOT IMPLEMENTED ***';
  847.             },
  848.        
  849.             'keys':function(){
  850.                 var result=[];
  851.  
  852.                 var cache=(myself._useLocalStorage)?localStorage:myself._cache;
  853.  
  854.                 for(var key in cache){
  855.                     if(cache.hasOwnProperty(key)){
  856.                         result.push(key);
  857.                     }
  858.                 }
  859.            
  860.                 return result;
  861.             }
  862.         };
  863.     } // CacheProvider::constructor
  864.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  865.     function fnCheckBlacklist(){
  866.         if(win.game_data.world=='zz2'){
  867.             //if([15287,16555,22835].indexOf(parseInt(win.game_data.player.id,10))>=0){
  868.             if([16467].indexOf(parseInt(win.game_data.player.id,10))<0){
  869.                 alert('Hi '+win.game_data.player.name+'!\n\nYour scripts have been disabled by dalesmckay\nSend him a mail if you wish to help with testing');
  870.                 return false;
  871.             }
  872.         }
  873.        
  874.         return true;
  875.     } // fnCheckBlacklist
  876.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  877.    
  878.     // Always run this first!
  879.     fnEnsureBrowserCompatibility();
  880.  
  881.     var win=(window.main||self);
  882.    
  883.     if(!fnCheckBlacklist()){
  884.         return;
  885.     }
  886.  
  887.     fnPrint('<span style="color:red;font-weight:bold;">Provide the following info when asking for help:</span><br/>(also send a support ticket to Jon Dawson aka Morthy)<hr>');
  888.  
  889.     var debugEnabled=false;
  890.     var cache=new CacheProvider();
  891.     var buildingConfig;
  892.     var unitConfig;
  893.     var worldConfig;
  894.     var gameVersion=win.game_data.version.match(/[\d|\.]+/g);
  895.     gameVersion=(gameVersion?parseFloat(gameVersion[1]):-1);
  896.  
  897.     if(!win.game_data.mode){
  898.         var vmode=win.$('#overview_menu td[class="selected"] a').attr('href');
  899.         vmode=vmode?vmode.match(/mode\=(\w*)/i):null;
  900.         win.game_data.mode=vmode?vmode[1]:null;
  901.     }
  902.  
  903.     fnCheckFrameworkVersion(); 
  904.     fnLoadWorldConfig();
  905.     fnLoadUnitConfig();
  906.     fnLoadBuildingConfig();
  907.     fnAppendToJQueryNamespace();
  908. })((window.main||self).jQuery);
  909. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  910. /*
  911.     Author  : Dale McKay
  912.     Email   : dalesmckay@gmail.com
  913.     Purpose : To help locate the best villages for farming.
  914.     Credit  :
  915.     Todo    :
  916.         * Add spinner when downloading DAT files.
  917.         * Checkbox to ignore your own villages.
  918.         * Checkbox to ignore your own Tribe.
  919.         * Generate a farming script.
  920.         * Make the DIV draggable.
  921.         * Filter by bounding area (coord TL/BR).
  922.         * Allow multiple coords for the radius.
  923.         * Add a clear/reset button.
  924.         * Add a spinner when Finding Farms.
  925.         * Add checkbox to enable/disable each filter option.
  926.     Notes   :
  927.    
  928.  
  929.     ######################
  930.     Client Launcher (live):
  931.     ######################
  932.    
  933. javascript:
  934.     var debugEnabled=true;
  935.     var branch='http://dl.dropbox.com/u/25377948/twscripts/';
  936.     (window.main||self).$.getScript(branch+'jquery.tw.farmfinder.js',function(){$.twFarmFinder(branch,debugEnabled);});
  937.     void(0);
  938.  
  939. ____________________________________________________________
  940.  
  941. Copyright (C) 2011 Dale McKay, all rights reserved
  942. version 1.0, 14 July 2011
  943.  
  944. This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software.
  945.  
  946. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  947. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  948. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  949. This notice may not be removed or altered from any source distribution.
  950. ____________________________________________________________
  951. */
  952.  
  953. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  954. // $.twFarmFinder(branch,debugEnabled)
  955. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  956. (function($){
  957.     var win=(window.main||self);
  958.  
  959.     var script={
  960.         id:'{AD48DC2A-89F2-4B3D-A9E3-E9352A763DA0}',
  961.         name:'Gerador : Lista de Aldeias',
  962.         version:1.07,
  963.         minGameVersion:7.00,
  964.         author:{
  965.             name:'dalesmckay & traduction Br por TW 100',
  966.             email:'dalesmckay@gmail.com',
  967.             url:'https://www.youtube.com/channel/UCIngQdlpQxocFDB4Vk6yERg'
  968.         },
  969.         credit:'',
  970.         runOnce:true
  971.     };
  972.  
  973.     // Replace these strings with the correct language translation.
  974.     var config={
  975.         'userMsg':{
  976.         }
  977.     };
  978.  
  979.     // ........................................................................
  980.     function fnAjax(url,method,params,type,isAsync,callback){
  981.         var payload=null;
  982.        
  983.         $.ajax({
  984.             'async':isAsync,
  985.             'url':url,
  986.             'data':params,
  987.             'dataType':type,
  988.             'type':String(method||'GET').toUpperCase(),
  989.             'error':function(req,status,err){throw(status);},
  990.             'success':function(data,status,req){if(!isAsync){payload=data;}if(typeof(callback)=='function'){callback(data,status,req);}}
  991.         });
  992.        
  993.         if(!isAsync){
  994.             if(typeof(callback)=='function'){
  995.                 callback(payload);
  996.             }
  997.  
  998.             return payload;
  999.         }
  1000.     } // fnAjax
  1001.     // ........................................................................
  1002.     function fnExecute(branch,debugEnabled){try{
  1003.         var villagesDAT=null;
  1004.         var playersDAT=null;
  1005.         var tribesDAT=null;
  1006.         var resultCoords=[];
  1007.         var detail={};
  1008.        
  1009.            
  1010.         // ........................................................................
  1011.         function fnBuildPlayerIDList(playerNames){
  1012.             var playerIDList=null;
  1013.            
  1014.             if(playerNames&&(playerNames.length>0)){
  1015.                 playerIDList=[];
  1016.                
  1017.                 $.each(playerNames,function(i,e){
  1018.                     var name=e.toLowerCase();
  1019.                    
  1020.                     if(playersDAT[name]){
  1021.                         playerIDList.push(playersDAT[name].id);
  1022.                     }
  1023.                 });
  1024.             }
  1025.            
  1026.             return playerIDList;
  1027.         } // fnBuildPlayerIDList
  1028.         // ........................................................................
  1029.         function fnBuildTribeIDList(tribeTags){
  1030.             var tribeIDList=null;
  1031.            
  1032.             if(tribeTags&&(tribeTags.length>0)){
  1033.                 tribeIDList=[];
  1034.  
  1035.                 $.each(tribeTags,function(i,e){
  1036.                     var tag=e.toLowerCase();
  1037.                
  1038.                     if(tribesDAT[tag]){
  1039.                         tribeIDList.push(tribesDAT[tag].id);
  1040.                     }
  1041.                 });
  1042.             }
  1043.            
  1044.             return tribeIDList;
  1045.         } //fnBuildTribeIDList
  1046.         // ........................................................................
  1047.         function fnFindPlayer(playerID){
  1048.             var player=null;
  1049.            
  1050.             $.each(playersDAT,function(i,e){
  1051.                 if(e.id==playerID){
  1052.                     player=e;
  1053.                     return true;
  1054.                 }
  1055.             });
  1056.            
  1057.             return player;
  1058.         } //fnFindPlayer
  1059.         // ........................................................................
  1060.         function fnFindTribe(tribeID){
  1061.             var tribe=null;
  1062.            
  1063.             $.each(tribesDAT,function(i,e){
  1064.                 if(e.id==tribeID){
  1065.                     tribe=e;
  1066.                     return true;
  1067.                 }
  1068.             });
  1069.            
  1070.             return tribe;
  1071.         } //fnFindTribe
  1072.         // ........................................................................
  1073.         function Point(x,y){return {'x':x,'y':y};}
  1074.         // ........................................................................
  1075.         function Rect(top,left,bottom,right){return {'top':top,'left':left,'bottom':bottom,'right':right};}
  1076.         // ........................................................................
  1077.         function pointInRect(point,rect){return(point.x>=rect.left&&point.x<=rect.right&&point.y>=rect.top&&point.y<=rect.bottom);}
  1078.         // ........................................................................
  1079.         function fnIsInsideRegion(coord,mapRegion){
  1080.             var tempCoord1=twUtil.extractCoord(coord);
  1081.             if(!tempCoord1){
  1082.                 return false;
  1083.             }
  1084.            
  1085.             var tempCoord2=twUtil.extractCoord(mapRegion.topLeft);
  1086.             if(!tempCoord2){
  1087.                 return false;
  1088.             }
  1089.            
  1090.             var tempCoord3=twUtil.extractCoord(mapRegion.bottomRight);
  1091.             if(!tempCoord3){
  1092.                 return false;
  1093.             }
  1094.            
  1095.             tempCoord1=tempCoord1.split('|');
  1096.             tempCoord2=tempCoord2.split('|');
  1097.             tempCoord3=tempCoord3.split('|');
  1098.            
  1099.             // ##################################################################
  1100.             // HACK: not sure why I need to reverse the x/y co-ordinates here ???          
  1101.             // ##################################################################
  1102.             var point=Point(tempCoord1[1],tempCoord1[0]);
  1103.             // ##################################################################
  1104.  
  1105.             var rect=Rect(tempCoord2[0],tempCoord2[1],tempCoord3[0],tempCoord3[1]);
  1106.            
  1107.             return pointInRect(point,rect);
  1108.         } // fnIsInsideRegion
  1109.         // ........................................................................
  1110.         function fnFindFarms(){
  1111.             twUtil.debug('<span style="color:gray;">CALL: fnFindFarms()...</span>');
  1112.            
  1113.             var alertMsg='';
  1114.             if(!(villagesDAT&&$.trim(JSON.stringify(villagesDAT)))){
  1115.                 alertMsg+='Vous devez mettre à jours les données des villages';
  1116.             }
  1117.             if(!(playersDAT&&$.trim(JSON.stringify(playersDAT)))){
  1118.                 alertMsg+='Vous devez mettre à jours les données des villages';
  1119.             }
  1120.             if(!(tribesDAT&&$.trim(JSON.stringify(tribesDAT)))){
  1121.                 alertMsg+='ous devez mettre à jours les données des tribus';
  1122.             }
  1123.             if(alertMsg){
  1124.                 alert(alertMsg);
  1125.  
  1126.                 return;
  1127.             }
  1128.            
  1129.            
  1130.             var curConfig=fnCurrentConfig();
  1131.            
  1132.             //NOTE: these fields are not part of the std config (we don't want to save it)
  1133.             var srcCoord=twUtil.extractCoord((curConfig.radius>0)?$.trim($('#dsmRadiusCentre').val()):'')||win.game_data.village.coord;
  1134.             var mapRegion={
  1135.                 topLeft:twUtil.extractCoord($.trim($('#dsmMRTopLeft').val()))||'000|000',
  1136.                 bottomRight:twUtil.extractCoord($.trim($('#dsmMRBottomRight').val()))||'999|999',
  1137.             };
  1138.            
  1139.             var hasPlayerFilter=!!$.trim($('#dsmPlayers').val());
  1140.             var hasTribeFilter=!!$.trim($('#dsmTribes').val());
  1141.                    
  1142.             // Build PlayerID List.
  1143.             // TODO...
  1144.             var playerIDs=fnBuildPlayerIDList(curConfig.players);
  1145.            
  1146.             //Build TribeID List.
  1147.             // TODO...
  1148.             var tribeIDs=fnBuildTribeIDList(curConfig.tribes);
  1149.            
  1150.             // Reset the co-ordinates.
  1151.             resultCoords=[];
  1152.            
  1153.             $.each(villagesDAT,function(i,e){
  1154.                 var player=null;
  1155.                 var tribe=null;
  1156.                 // Ignore your own villages.
  1157.                 if(e.ownerID==win.game_data.player.id){
  1158.                     // TODO: allow your own villages.
  1159.                     return true;
  1160.                 }
  1161.  
  1162.                 // Min Points Filter.
  1163.                 if((curConfig.minPoints>=0)&&(e.points<curConfig.minPoints)){
  1164.                     return true;
  1165.                 }
  1166.                
  1167.                 // Max Points Filter.
  1168.                 if((curConfig.maxPoints>=0)&&(e.points>curConfig.maxPoints)){
  1169.                     return true;
  1170.                 }
  1171.                
  1172.                 // Radius Filter.
  1173.                 if((curConfig.radius>0)&&srcCoord&&(twUtil.fields(srcCoord,e.coord)>curConfig.radius)){
  1174.                     return true;
  1175.                 }
  1176.                
  1177.                 // Map Region Filter.
  1178.                 if(!fnIsInsideRegion(e.coord,mapRegion)){
  1179.                     return true;
  1180.                 }
  1181.                
  1182.                 // Continent Filter.
  1183.                 if(curConfig.continents&&(curConfig.continents.length>0)&&(curConfig.continents.indexOf(e.continent)<0)){
  1184.                     return true;
  1185.                 }
  1186.  
  1187.                 // Barb Filter.
  1188.                 if(curConfig.barbsOnly){
  1189.                     if(!e.ownerID){
  1190.                         resultCoords.push(e.coord);
  1191.                         detail[e.coord]={village:e,player:null,tribe:null};
  1192.                         return true;
  1193.                     }
  1194.                 }
  1195.                 else{
  1196.                     player=fnFindPlayer(e.ownerID);
  1197.                     tribe=player?fnFindTribe(player.tribeID):null;
  1198.                    
  1199.                     // Player Filter.
  1200.                     if(hasPlayerFilter&&playerIDs&&(playerIDs.indexOf(e.ownerID)>=0)){
  1201.                         resultCoords.push(e.coord);
  1202.                         detail[e.coord]={village:e,player:player,tribe:tribe};
  1203.                         return true;
  1204.                     }
  1205.                    
  1206.                     // Tribe Filter.
  1207.                     if(hasTribeFilter&&tribeIDs){
  1208.                         if(player&&player.tribeID&&(tribeIDs.indexOf(player.tribeID)>=0)){                 
  1209.                             resultCoords.push(e.coord);
  1210.                             detail[e.coord]={village:e,player:player,tribe:tribe};
  1211.                             return true;
  1212.                         }
  1213.                     }
  1214.                    
  1215.                     if(!hasPlayerFilter&&!hasTribeFilter){
  1216.                         resultCoords.push(e.coord);
  1217.                         detail[e.coord]={village:e,player:player,tribe:tribe};
  1218.                         return true;
  1219.                     }
  1220.                 }              
  1221.             });
  1222.            
  1223.             // Sort the co-ordinates.
  1224.             resultCoords=resultCoords.sort(function(a,b){return twUtil.fields(srcCoord,a)-twUtil.fields(srcCoord,b);});
  1225.  
  1226.             fnDisplayOutput();
  1227.             $('#dsmCoordCount').text('('+resultCoords.length+')');
  1228.         } // fnFindFarms
  1229.         // ........................................................................
  1230.         function fnCurrentConfig(){
  1231.             return{
  1232.                 barbsOnly:$('#dsmBarbOnly').is(':checked'),
  1233.                 continents:$.map(($('#dsmContinents').val()||'').match(/\d+/g)||[],function(e){return twUtil.int(e);}),
  1234.                 minPoints:twUtil.int($('#dsmMinPoints').val()||'-1',10),
  1235.                 maxPoints:twUtil.int($('#dsmMaxPoints').val()||'-1',10),
  1236.                 radius:$.trim($('#dsmRadius').val())||'-1',
  1237.                 players:($.trim($('#dsmPlayers').val())||'').split(','),
  1238.                 tribes:($.trim($('#dsmTribes').val())||'').split(','),
  1239.                 bbEncoded:$('#dsmBBEncoded').is(':checked'),
  1240.                 format:$.trim($('#dsmFormat').val())||'{coord}'
  1241.             };
  1242.         } // fnCurrentConfig
  1243.         // ........................................................................
  1244.         function fnLoadConfig(){
  1245.             var curConfig=twCache.fetch(script.id+'.config')||{
  1246.                 barbsOnly:false,
  1247.                 continents:undefined,
  1248.                 minPoints:-1,
  1249.                 maxPoints:-1,
  1250.                 radius:25,
  1251.                 players:undefined,
  1252.                 tribes:undefined,
  1253.                 bbEncoded:false,
  1254.                 format:'{coord}'
  1255.             };
  1256.            
  1257.             if(curConfig.players=='*** Coming Soon ***'){
  1258.                 curConfig.players=undefined;
  1259.             }
  1260.            
  1261.             if(curConfig.tribes=='*** Coming Soon ***'){
  1262.                 curConfig.tribes=undefined;
  1263.             }
  1264.            
  1265.             $('#dsmBarbOnly').attr('checked',curConfig.barbsOnly);
  1266.             $('#dsmContinents').val((curConfig.continents||[]).join(','));
  1267.             $('#dsmMRTopLeft').val('000|000');
  1268.             $('#dsmMRBottomRight').val('999|999');
  1269.             $('#dsmMinPoints').val((curConfig.minPoints>=0)?curConfig.minPoints:'');
  1270.             $('#dsmMaxPoints').val((curConfig.maxPoints>=0)?curConfig.maxPoints:'');
  1271.             $('#dsmBBEncoded').attr('checked',curConfig.bbEncoded);
  1272.             $('#dsmRadius').val((parseFloat(curConfig.radius||'0.0')>0.0)?curConfig.radius:'');
  1273.             $('#dsmRadiusCentre').val(win.game_data.village.coord);
  1274.             $('#dsmPlayers').val((curConfig.players||[]).join(','));
  1275.             $('#dsmTribes').val((curConfig.tribes||[]).join(','));
  1276.             $('#dsmFormat').val(curConfig.format||'{coord}');
  1277.         } // fnLoadConfig
  1278.         // ........................................................................
  1279.         function fnSaveConfig(){
  1280.             twCache.store(script.id+'.config',fnCurrentConfig());
  1281.         } // fnSaveConfig
  1282.         // ........................................................................
  1283.         function fnDisplayOutput(){
  1284.             var isBBEncoded=$('#dsmBBEncoded').is(':checked');
  1285.            
  1286.             var format=$.trim($('#dsmFormat').val());
  1287.             if(format){
  1288.                 var output='';
  1289.            
  1290.                 $.each(resultCoords,function(i,e){
  1291.                     var village=detail[e].village;
  1292.                     var player=detail[e].player;
  1293.                     var tribe=detail[e].tribe;
  1294.                    
  1295.                     if(player&&!player.id){
  1296.                         player=null;
  1297.                     }
  1298.                    
  1299.                     if(tribe&&!tribe.id){
  1300.                         tribe=null;
  1301.                     }
  1302.                    
  1303.                     twUtil.debug(JSON.stringify(player)+'<br/>'+JSON.stringify(tribe)+'<br/><br/>');
  1304.                    
  1305.                     output+=format
  1306.                         .replace(/\{coord\}/ig,isBBEncoded?'[coord]'+e+'[/coord]':e)
  1307.                         .replace(/\{points\}/ig,village.points)
  1308.                         .replace(/\{name\}/ig,village.name)
  1309.                         .replace(/\{player\}/ig,player?(isBBEncoded?'[player]'+player.name+'[/player]':player.name):'')
  1310.                         .replace(/\{tribe\_name\}/ig,tribe?tribe.name:'')
  1311.                         .replace(/\{tribe\}/ig,tribe?(isBBEncoded?'[ally]'+tribe.tag+'[/ally]':tribe.tag):'')
  1312.                         .replace(/\{continent\}/ig,village.continent)
  1313.                                                 .replace(/\{id\}/ig,village.id)
  1314.                     +'\n';
  1315.                 });
  1316.            
  1317.                 $('#dsmOutput').val(output);
  1318.             }
  1319.             else{
  1320.                 $('#dsmOutput').val((isBBEncoded?'[coord]':'')+resultCoords.join(isBBEncoded?'[/coord]\n[coord]':' ')+(isBBEncoded?'[/coord]\n':''));
  1321.             }          
  1322.         } // fnDisplayOutput
  1323.         // ........................................................................
  1324.         function fnCheckVillagesDAT(){
  1325.             var ageMS=undefined;
  1326.            
  1327.             var cacheVal=twCache.fetch('villagesDAT');
  1328.             if(cacheVal&&$.trim(JSON.stringify(cacheVal))){
  1329.                 villagesDAT=cacheVal.data;
  1330.                 ageMS=(new Date()).getTime()-cacheVal.lastRefresh;
  1331.             }
  1332.            
  1333.             if(ageMS!=undefined){
  1334.                 $('#dsmVillagesDATAge').text(twUtil.formatMS2(ageMS,true));
  1335.                 if(Math.floor(ageMS/(1000*60*60))>=1){
  1336.                     $('#dsmRefreshVillagesDAT').show();
  1337.                 }
  1338.                 else{
  1339.                     $('#dsmRefreshVillagesDAT').hide();
  1340.                 }
  1341.             }
  1342.             else{
  1343.                 $('#dsmVillagesDATAge').text('*** AUCUNE DONNEE ***');
  1344.                 $('#dsmRefreshVillagesDAT').show();
  1345.             }
  1346.         } // fnCheckVillagesDAT
  1347.         // ........................................................................
  1348.         function fnCheckPlayersDAT(){
  1349.             var ageMS=undefined;
  1350.            
  1351.             var cacheVal=twCache.fetch('playersDAT');
  1352.             if(cacheVal&&$.trim(JSON.stringify(cacheVal))){
  1353.                 playersDAT=cacheVal.data;
  1354.                 ageMS=(new Date()).getTime()-cacheVal.lastRefresh;
  1355.             }
  1356.            
  1357.             if(ageMS!=undefined){
  1358.                 $('#dsmPlayersDATAge').text(twUtil.formatMS2(ageMS,true));
  1359.                 if(Math.floor(ageMS/(1000*60*60))>=1){
  1360.                     $('#dsmRefreshPlayersDAT').show();
  1361.                 }
  1362.                 else{
  1363.                     $('#dsmRefreshPlayersDAT').hide();
  1364.                 }
  1365.             }
  1366.             else{
  1367.                 $('#dsmPlayersDATAge').text('*** AUCUNE DONNEE ***');
  1368.                 $('#dsmRefreshPlayersDAT').show();
  1369.             }
  1370.         } // fnCheckPlayersDAT
  1371.         // ........................................................................
  1372.         function fnCheckTribesDAT(){
  1373.             var ageMS=undefined;
  1374.            
  1375.             var cacheVal=twCache.fetch('tribesDAT');
  1376.             if(cacheVal&&$.trim(JSON.stringify(cacheVal))){
  1377.                 tribesDAT=cacheVal.data;
  1378.                 ageMS=(new Date()).getTime()-cacheVal.lastRefresh;
  1379.             }
  1380.            
  1381.             if(ageMS!=undefined){
  1382.                 $('#dsmTribesDATAge').text(twUtil.formatMS2(ageMS,true));
  1383.                 if(Math.floor(ageMS/(1000*60*60))>=1){
  1384.                     $('#dsmRefreshTribesDAT').show();
  1385.                 }
  1386.                 else{
  1387.                     $('#dsmRefreshTribesDAT').hide();
  1388.                 }
  1389.             }
  1390.             else{
  1391.                 $('#dsmTribesDATAge').text('*** AUCUNE DONNEE ***');
  1392.                 $('#dsmRefreshTribesDAT').show();
  1393.             }
  1394.         } // fnCheckTribesDAT
  1395.         // ........................................................................
  1396.         function fnRefreshVillagesDAT(){
  1397.             villagesDAT=twConfig.fetchVillagesDAT(1);
  1398.             fnCheckVillagesDAT();
  1399.         } // fnRefreshVillagesDAT
  1400.         // ........................................................................
  1401.         function fnRefreshPlayersDAT(){
  1402.             playersDAT=twConfig.fetchPlayersDAT(1);
  1403.             fnCheckPlayersDAT();
  1404.         } // fnRefreshPlayersDAT
  1405.         // ........................................................................
  1406.         function fnRefreshTribesDAT(){
  1407.             tribesDAT=twConfig.fetchTribesDAT(1);
  1408.             fnCheckTribesDAT();
  1409.         } // fnRefreshTribesDAT
  1410.         // ........................................................................
  1411.         function fnInjectGUIControls(){
  1412.             if($('#dsmFarmFinderPopup').length>0){
  1413.                 $('#dsmFarmFinderPopup').show();
  1414.            
  1415.                 return;
  1416.             }
  1417.        
  1418.             $('body').append('\
  1419.                 <div id="dsmFarmFinderPopup" style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:900;">\
  1420.                     <div style="background:url(/graphic/background/bg-tile.jpg);opacity:0.8;position:fixed;top:0;left:0;width:100%;height:100%;z-index:5;"></div>\
  1421. \
  1422.                     <div style="position:relative;margin:auto;padding:0;top:120px;width:702px;z-index:10;">\
  1423.                         <a href="#" onclick="$(\'#dsmFarmFinderPopup\').hide();return false;" style="position:absolute;right:-8px;top:-8px;">\
  1424.                             <img src="graphic/login_close.png" alt="Close" style="border:none;">\
  1425.                         </a>\
  1426. \
  1427.                         <div style="width:702px;height:22px;background:url(/graphic/index/sprites.png) no-repeat 0 -79px"></div>\
  1428.                         <div style="padding:10px 20px;width:662px;height:100%;min-height:80px;background:url(/graphic/index/news_background.png) repeat-y">\
  1429.                             <h1>'+script.name+' <sup><span style="font-size:small;">v'+script.version.toFixed(2)+'</span></sup><sub><span style="font-weight:bold;font-style:italic;text-decoration:none;font-size:x-small;"><a href="'+script.author.url+'" target="_blank"> by '+script.author.name+'</a></span></sub></h1>\
  1430.                             <div style="margin:auto;"><table><tr>\
  1431.                                 <td>\
  1432.                                     <table id="dsmSettings" class="vis">\
  1433.                                         <tr><th style="padding:2px 10px;">Opção</th><th style="padding:2px 10px;">Valeurs</th></tr>\
  1434.                                         <tr><td style="padding:2px 10px;"><span>Apenas Barbaras</span></td><td style="padding:2px 10px;align:center;"><input id="dsmBarbOnly" type="checkbox"/></td></tr>\
  1435.                                         <tr><td style="padding:2px 10px;"><span>Continente (s)</span></td><td style="padding:2px 10px;align:center;"><input id="dsmContinents"/></td></tr>\
  1436.                                         <tr><td style="padding:2px 10px;"><span>Região do mapa rectangular</span></td><td style="padding:2px 10px;"><span style="margin-left:0.5em;margin-right:0.5em;">Noroeste :</span><input id="dsmMRTopLeft" size="7"/><span style="margin-left:0.5em;margin-right:0.5em;">Sudeste :</span><input id="dsmMRBottomRight" size="7"/></td></tr>\
  1437.                                         <tr><td style="padding:2px 10px;"><span>Pontos min</span></td><td style="padding:2px 10px;"><input id="dsmMinPoints"/></td></tr>\
  1438.                                         <tr><td style="padding:2px 10px;"><span>Pontos máximos</span></td><td style="padding:2px 10px;"><input id="dsmMaxPoints"/></td></tr>\
  1439.                                         <tr><td style="padding:2px 10px;"><span>Região</span></td><td style="padding:2px 10px;"><input id="dsmRadius" size="3"/><span style="margin-left:0.5em;margin-right:0.5em;">Campos ao redor : </span><input id="dsmRadiusCentre" size="7"/></td></tr>\
  1440.                                         <tr><td style="padding:2px 10px;"><span id="dsmPlayersTitle">Nick Jogador</span></td><td style="padding:2px 10px;"><input id="dsmPlayers"/></td></tr>\
  1441.                                         <tr><td style="padding:2px 10px;"><span id="dsmTribesTitle">Tag da tribo</span></td><td style="padding:2px 10px;"><input id="dsmTribes"/></td></tr>\
  1442.                                         <tr><th><input id="dsmFindFarms" type="button" value="Gerar" style="width:100%;"/></th><th style="padding:2px 10px;"><a id="dsmSaveConfig" href="#" style="text-align:right;">Salvar</a></th></tr>\
  1443.                                     </table>\
  1444.                                 </td>\
  1445.                                 <td>\
  1446.                                     <table id="dsmResult" class="vis">\
  1447.                                         <tr><th style="padding:2px 10px;"><span>Lista de Aldeias</span><div style="float:right;"><span id="dsmCoordCount">(0)</span></div></th></tr>\
  1448.                                         <tr><td style="padding:2px 10px;"><label for="dsmFormat">Formato :</label><input id="dsmFormat" type="text" style="width:240px;margin-left:1em;" value="{coord}"/><span id="dsmHint"></span></td></tr>\
  1449.                                         <tr><td style="padding:2px 10px;"><textarea id="dsmOutput" cols="40" rows="17" style="overflow-x:hidden;overflow-y:auto;" onfocus="this.select();"></textarea></td></tr>\
  1450.                                         <tr><th style="padding:2px 10px;"><input id="dsmBBEncoded" type="checkbox"/><label for="dsmBBEncode">BB-Code</label></th></tr>\
  1451.                                     </table>\
  1452.                                 </td>\
  1453.                             </tr></table></div>\
  1454. \
  1455.                             <span style="font-weight:bold;">Tempo dos dados sobre as aldeias:</span>\
  1456.                             <span id="dsmVillagesDATAge" style="margin-left:1em;"></span>\
  1457.                             <a id="dsmRefreshVillagesDAT" href="#" style="margin-left:1em;display:none;">&lt;Refresh Now&gt; ...</a>\
  1458.                             <br/>\
  1459.                             <span style="font-weight:bold;">Tempo dos dados sobre os jogadores:</span>\
  1460.                             <span id="dsmPlayersDATAge" style="margin-left:1em;"></span>\
  1461.                             <a id="dsmRefreshPlayersDAT" href="#" style="margin-left:1em;display:none;">&lt;Refresh Now&gt; ...</a>\
  1462.                             <br/>\
  1463.                             <span style="font-weight:bold;">Tempo dos dados sobre as tribos:</span>\
  1464.                             <span id="dsmTribesDATAge" style="margin-left:1em;"></span>\
  1465.                             <a id="dsmRefreshTribesDAT" href="#" style="margin-left:1em;display:none;">&lt;Refresh Now&gt; ...</a>\
  1466.                             <br/>\
  1467.                             <span style="font-style:italic;color:red;">(AVISO: carregar esses dados pode levar vários minutos)</span>\
  1468.                             <br/>\
  1469.                         </div>\
  1470. \
  1471.                         <div style="width: 702px; height: 22px; background:url(/graphic/index/sprites.png) no-repeat 0 -101px;"></div>\
  1472.                     </div>\
  1473.                 </div>\
  1474.             ');
  1475.            
  1476.             // Wire up any relevant events.
  1477.             $('#dsmBarbOnly').click(function(){fnRefreshControls();});
  1478.             $('#dsmFindFarms').click(function(){fnCheckVillagesDAT();fnCheckPlayersDAT();fnCheckTribesDAT();fnFindFarms();});
  1479.             $('#dsmSaveConfig').click(function(){fnSaveConfig();});
  1480.             $('#dsmBBEncoded').click(function(){fnDisplayOutput();});
  1481.             $('#dsmRefreshVillagesDAT').click(function(){fnRefreshVillagesDAT();});
  1482.             $('#dsmRefreshPlayersDAT').click(function(){fnRefreshPlayersDAT();});
  1483.             $('#dsmRefreshTribesDAT').click(function(){fnRefreshTribesDAT();});
  1484.            
  1485.             $('#dsmHint').html('{coord} - Village Co-ordinate<br/>{points} - Village Points<br/>{name} - Village Name<br/>{player} - Village Owner<br/>{tribe} - Village Owner Tribe Tag<br/>{tribe_name} - Village Owner Tribe Name<br/>{continent} - Village Continent<br/>');
  1486.             $('#dsmHint').css({
  1487.                 display:'none',
  1488.                 position:'absolute',
  1489.                 left:$('#dsmFormat').css('right'),
  1490.                 width:'300px',
  1491.                 marginTop:'-4px',
  1492.                 border:'1px solid #c93',
  1493.                 padding:'10px 12px',
  1494.                 backgroundColor:'#ffc'
  1495.             });
  1496.  
  1497.  
  1498.             fnLoadConfig();
  1499.             fnRefreshControls();
  1500.             fnCheckVillagesDAT();
  1501.             fnCheckPlayersDAT();
  1502.             fnCheckTribesDAT();
  1503.         } // fnInjectGUIControls
  1504.         // ........................................................................
  1505.         function fnRefreshControls(){
  1506.             var state=$('#dsmBarbOnly').is(':checked')?'disabled':'';
  1507.             var color=$('#dsmBarbOnly').is(':checked')?'gray':'black';
  1508.            
  1509.             $('#dsmPlayersTitle').css({color:color});
  1510.            
  1511.             $('#dsmTribesTitle').css({color:color});
  1512.         } //fnRefreshControls
  1513.         // ........................................................................
  1514.         function fnBootStrapper(){
  1515.             if(!twConfig.hasMinVersion(script.minGameVersion)){
  1516.                 var msg='This script requires v'+script.minGameVersion.toFixed(2)+' or higher.\nYou are running: v'+twConfig.gameVersion.toFixed(2);
  1517.                 twUtil.print(msg);
  1518.                 alert(msg);
  1519.                 return;
  1520.             }
  1521.            
  1522.             fnInjectGUIControls();
  1523.            
  1524. /*
  1525.             switch(win.game_data.screen){
  1526.                 case 'report':             
  1527.                     break;
  1528.        
  1529.                 default:
  1530.                     var msg='This script must be run from a Report Detail Screen!';
  1531.                     twUtil.print(msg);
  1532.                     alert(msg);
  1533.  
  1534.                     break;
  1535.             }
  1536. */
  1537.             } // fnBootStrapper
  1538.         // ........................................................................
  1539.         function fnLoadUtils(){
  1540.             if($.twUtil){
  1541.                 twUtil=$.twUtil();
  1542.                 twConfig=$.twConfig();
  1543.                 twCache=$.twCache();
  1544.                 fnBootStrapper();
  1545.             }
  1546.             else{
  1547.                 fnAjax(branch+'jquery.tw.utils.js','GET',{},'script',true,function(){
  1548.                     twCache=$.twCache();
  1549.                     twConfig=$.twConfig();
  1550.                     twUtil=$.twUtil();
  1551.  
  1552.                     twUtil.debugEnabled(debugEnabled);
  1553.                     twConfig.printVersion(script);
  1554.                    
  1555.                     // Log the User Options.
  1556.                     twUtil.debug('branch='+branch);
  1557.                     twUtil.debug('debugEnabled='+debugEnabled);
  1558.                    
  1559.                     fnBootStrapper();
  1560.                 });
  1561.             }
  1562.         } // fnLoadUtils
  1563.         // ........................................................................
  1564.  
  1565.  
  1566.         var twUtil;
  1567.         var twConfig;
  1568.         var twCache;
  1569.         fnLoadUtils(); 
  1570.     }
  1571.     catch(objError){
  1572.         var errMsg=String(objError.message||objError||'');
  1573.         if(errMsg){
  1574.             $('body').append('<span>'+errMsg+'</span><br/>');
  1575.             alert('Error: '+errMsg);
  1576.         }
  1577.     }} // fnExecute
  1578.  
  1579.  
  1580.  
  1581.     // Append to the jQuery Namespace.
  1582.     $.extend({
  1583.         'twFarmFinder':fnExecute
  1584.     });
  1585. })((window.main||self).jQuery);
  1586. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1587. $.twFarmFinder(branch,debugEnabled);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement