Hébergeur de fichiers indépendant

135994.user.js

À propos du fichier

Type de fichier
Fichier JS de 193 Ko (text/plain)
Confidentialité
Fichier public, envoyé le 14 novembre 2012 à 05:36, depuis l'adresse IP 69.156.x.x (CA)
Sécurité
Ne contient aucun Virus ou Malware connus - Dernière vérification: 18 heures
Statistiques
La présente page de téléchargement a été vue 912 fois depuis l'envoi du fichier
Page de téléchargement

Aperçu du fichier


// ==UserScript==
// @name           Chat Alliance
// @namespace      http://userscripts.org/
// @grant          GM_getValue
// @grant          GM_setValue
// @grant          GM_addStyle
// @grant          GM_registerMenuCommand
// @grant          GM_deleteValue
// @grant          GM_xmlhttpRequest
// @grant          GM_openInTab
// @downloadURL    
// @updateURL      
// @include        http://s*.ikariam.*/index.php*
// @include        http://board.*.ikariam.com*
// @include        http://*.ikariam.*/board
// @version        1.0
//
// @require        http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @require        http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js
//
// ==/UserScript==
/***********************************************************************************************************************
 * Includes
 ********************************************************************************************************************* */
//"use strict";
if (window.navigator.vendor.match(/Google/))
    var isChrome = true;
if (!isChrome){
    this.$ = this.jQuery = jQuery.noConflict(true);
}
/*! qTip2 v2.0.0 | http://craigsworks.com/projects/qtip2/ | Licensed MIT, GPL */
(function(e,t,n){(function(e){"use strict";typeof define=="function"&&define.amd?define(["jquery"],e):jQuery&&!jQuery.fn.qtip&&e(jQuery)})(function(r){function D(e){var t=function(e){return e===o||"object"!=typeof e},n=function(e){return!r.isFunction(e)&&(!e&&!e.attr||e.length<1||"object"==typeof e&&!e.jquery)};if(!e||"object"!=typeof e)return s;t(e.metadata)&&(e.metadata={type:e.metadata});if("content"in e){if(t(e.content)||e.content.jquery)e.content={text:e.content};n(e.content.text||s)&&(e.content.text=s),"title"in e.content&&(t(e.content.title)&&(e.content.title={text:e.content.title}),n(e.content.title.text||s)&&(e.content.title.text=s))}return"position"in e&&t(e.position)&&(e.position={my:e.position,at:e.position}),"show"in e&&t(e.show)&&(e.show=e.show.jquery?{target:e.show}:{event:e.show}),"hide"in e&&t(e.hide)&&(e.hide=e.hide.jquery?{target:e.hide}:{event:e.hide}),"style"in e&&t(e.style)&&(e.style={classes:e.style}),r.each(w,function(){this.sanitize&&this.sanitize(e)}),e}function P(u,a,f,l){function I(e){var t=0,n,r=a,i=e.split(".");while(r=r[i[t++]])t<i.length&&(n=r);return[n||a,i.pop()]}function q(){var e=a.style.widget;H.toggleClass("ui-helper-reset "+T,e).toggleClass(k,a.style.def&&!e),j.content&&j.content.toggleClass(T+"-content",e),j.titlebar&&j.titlebar.toggleClass(T+"-header",e),j.button&&j.button.toggleClass(x+"-icon",!e)}function R(e){j.title&&(j.titlebar.remove(),j.titlebar=j.title=j.button=o,e!==s&&m.reposition())}function U(){var e=a.content.title.button,t=typeof e=="string",n=t?e:"Close tooltip";j.button&&j.button.remove(),e.jquery?j.button=e:j.button=r("<a />",{"class":"ui-state-default ui-tooltip-close "+(a.style.widget?"":x+"-icon"),title:n,"aria-label":n}).prepend(r("<span />",{"class":"ui-icon ui-icon-close",html:"&times;"})),j.button.appendTo(j.titlebar).attr("role","button").click(function(e){return H.hasClass(N)||m.hide(e),s})}function z(){var e=y+"-title";j.titlebar&&R(),j.titlebar=r("<div />",{"class":x+"-titlebar "+(a.style.widget?"ui-widget-header":"")}).append(j.title=r("<div />",{id:e,"class":x+"-title","aria-atomic":i})).insertBefore(j.content).delegate(".ui-tooltip-close","mousedown keydown mouseup keyup mouseout",function(e){r(this).toggleClass("ui-state-active ui-state-focus",e.type.substr(-4)==="down")}).delegate(".ui-tooltip-close","mouseover mouseout",function(e){r(this).toggleClass("ui-state-hover",e.type==="mouseover")}),a.content.title.button&&U()}function W(e){var t=j.button,n=j.title;if(!m.rendered)return s;e?(n||z(),U()):t.remove()}function X(e,t){var n=j.title;if(!m.rendered||!e)return s;r.isFunction(e)&&(e=e.call(u,F.event,m));if(e===s||!e&&e!=="")return R(s);e.jquery&&e.length>0?n.empty().append(e.css({display:"block"})):n.html(e),t!==s&&m.rendered&&H[0].offsetWidth>0&&m.reposition(F.event)}function V(e,t){function o(e){function a(n){n&&(delete u[n.src],clearTimeout(m.timers.img[n.src]),r(n).unbind(B)),r.isEmptyObject(u)&&(t!==s&&m.reposition(F.event),e())}var o,u={};if((o=i.find("img[src]:not([height]):not([width])")).length===0)return a();o.each(function(e,t){if(u[t.src]!==n)return;var i=0,s=3;(function o(){if(t.height||t.width||i>s)return a(t);i+=1,m.timers.img[t.src]=setTimeout(o,700)})(),r(t).bind("error"+B+" load"+B,function(){a(this)}),u[t.src]=t})}var i=j.content;return!m.rendered||!e?s:(r.isFunction(e)&&(e=e.call(u,F.event,m)||""),e.jquery&&e.length>0?i.empty().append(e.css({display:"block"})):i.html(e),m.rendered<0?H.queue("fx",o):(P=0,o(r.noop)),m)}function J(){function h(e){if(H.hasClass(N))return s;clearTimeout(m.timers.show),clearTimeout(m.timers.hide);var t=function(){m.toggle(i,e)};a.show.delay>0?m.timers.show=setTimeout(t,a.show.delay):t()}function p(e){if(H.hasClass(N)||O||P)return s;var t=r(e.relatedTarget||e.target),i=t.closest(C)[0]===H[0],u=t[0]===o.show[0];clearTimeout(m.timers.show),clearTimeout(m.timers.hide);if(n.target==="mouse"&&i||a.hide.fixed&&/mouse(out|leave|move)/.test(e.type)&&(i||u)){try{e.preventDefault(),e.stopImmediatePropagation()}catch(f){}return}a.hide.delay>0?m.timers.hide=setTimeout(function(){m.hide(e)},a.hide.delay):m.hide(e)}function d(e){if(H.hasClass(N))return s;clearTimeout(m.timers.inactive),m.timers.inactive=setTimeout(function(){m.hide(e)},a.hide.inactive)}function v(e){m.rendered&&H[0].offsetWidth>0&&m.reposition(e)}var n=a.position,o={show:a.show.target,hide:a.hide.target,viewport:r(n.viewport),document:r(t),body:r(t.body),window:r(e)},l={show:r.trim(""+a.show.event).split(" "),hide:r.trim(""+a.hide.event).split(" ")},c=r.browser.msie&&parseInt(r.browser.version,10)===6;H.bind("mouseenter"+B+" mouseleave"+B,function(e){var t=e.type==="mouseenter";t&&m.focus(e),H.toggleClass(A,t)}),/mouse(out|leave)/i.test(a.hide.event)&&a.hide.leave==="window"&&o.window.bind("mouseout"+B+" blur"+B,function(e){!/select|option/.test(e.target.nodeName)&&!e.relatedTarget&&m.hide(e)}),a.hide.fixed?(o.hide=o.hide.add(H),H.bind("mouseover"+B,function(){H.hasClass(N)||clearTimeout(m.timers.hide)})):/mouse(over|enter)/i.test(a.show.event)&&o.hide.bind("mouseleave"+B,function(e){clearTimeout(m.timers.show)}),(""+a.hide.event).indexOf("unfocus")>-1&&n.container.closest("html").bind("mousedown"+B+" touchstart"+B,function(e){var t=r(e.target),n=m.rendered&&!H.hasClass(N)&&H[0].offsetWidth>0,i=t.parents(C).filter(H[0]).length>0;t[0]!==u[0]&&t[0]!==H[0]&&!i&&!u.has(t[0]).length&&!t.attr("disabled")&&m.hide(e)}),"number"==typeof a.hide.inactive&&(o.show.bind("qtip-"+f+"-inactive",d),r.each(b.inactiveEvents,function(e,t){o.hide.add(j.tooltip).bind(t+B+"-inactive",d)})),r.each(l.hide,function(e,t){var n=r.inArray(t,l.show),i=r(o.hide);n>-1&&i.add(o.show).length===i.length||t==="unfocus"?(o.show.bind(t+B,function(e){H[0].offsetWidth>0?p(e):h(e)}),delete l.show[n]):o.hide.bind(t+B,p)}),r.each(l.show,function(e,t){o.show.bind(t+B,h)}),"number"==typeof a.hide.distance&&o.show.add(H).bind("mousemove"+B,function(e){var t=F.origin||{},n=a.hide.distance,r=Math.abs;(r(e.pageX-t.pageX)>=n||r(e.pageY-t.pageY)>=n)&&m.hide(e)}),n.target==="mouse"&&(o.show.bind("mousemove"+B,function(e){E={pageX:e.pageX,pageY:e.pageY,type:"mousemove"}}),n.adjust.mouse&&(a.hide.event&&(H.bind("mouseleave"+B,function(e){(e.relatedTarget||e.target)!==o.show[0]&&m.hide(e)}),j.target.bind("mouseenter"+B+" mouseleave"+B,function(e){F.onTarget=e.type==="mouseenter"})),o.document.bind("mousemove"+B,function(e){m.rendered&&F.onTarget&&!H.hasClass(N)&&H[0].offsetWidth>0&&m.reposition(e||E)}))),(n.adjust.resize||o.viewport.length)&&(r.event.special.resize?o.viewport:o.window).bind("resize"+B,v),(o.viewport.length||c&&H.css("position")==="fixed")&&o.viewport.bind("scroll"+B,v)}function K(){var n=[a.show.target[0],a.hide.target[0],m.rendered&&j.tooltip[0],a.position.container[0],a.position.viewport[0],a.position.container.closest("html")[0],e,t];m.rendered?r([]).pushStack(r.grep(n,function(e){return typeof e=="object"})).unbind(B):a.show.target.unbind(B+"-create")}var m=this,g=t.body,y=x+"-"+f,O=0,P=0,H=r(),B=".qtip-"+f,j,F;m.id=f,m.rendered=s,m.destroyed=s,m.elements=j={target:u},m.timers={img:{}},m.options=a,m.checks={},m.plugins={},m.cache=F={event:{},target:r(),disabled:s,attr:l,onTarget:s,lastClass:""},m.checks.builtin={"^id$":function(e,t,n){var o=n===i?b.nextid:n,u=x+"-"+o;o!==s&&o.length>0&&!r("#"+u).length&&(H[0].id=u,j.content[0].id=u+"-content",j.title[0].id=u+"-title")},"^content.text$":function(e,t,n){V(n)},"^content.title.text$":function(e,t,n){if(!n)return R();!j.title&&n&&z(),X(n)},"^content.title.button$":function(e,t,n){W(n)},"^position.(my|at)$":function(e,t,n){"string"==typeof n&&(e[t]=new w.Corner(n))},"^position.container$":function(e,t,n){m.rendered&&H.appendTo(n)},"^show.ready$":function(){m.rendered?m.toggle(i):m.render(1)},"^style.classes$":function(e,t,n){H.attr("class",x+" qtip "+n)},"^style.width|height":function(e,t,n){H.css(t,n)},"^style.widget|content.title":q,"^events.(render|show|move|hide|focus|blur)$":function(e,t,n){H[(r.isFunction(n)?"":"un")+"bind"]("tooltip"+t,n)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){var e=a.position;H.attr("tracking",e.target==="mouse"&&e.adjust.mouse),K(),J()}},r.extend(m,{_triggerEvent:function(e,t,n){var i=r.Event("tooltip"+e);return i.originalEvent=(n?r.extend({},n):o)||F.event||o,H.trigger(i,[m].concat(t||[])),!i.isDefaultPrevented()},render:function(e){if(m.rendered)return m;var t=a.content.text,n=a.content.title.text,o=a.position;return r.attr(u[0],"aria-describedby",y),H=j.tooltip=r("<div/>",{id:y,"class":x+" qtip "+k+" "+a.style.classes+" "+x+"-pos-"+a.position.my.abbrev(),width:a.style.width||"",height:a.style.height||"",tracking:o.target==="mouse"&&o.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":s,"aria-describedby":y+"-content","aria-hidden":i}).toggleClass(N,F.disabled).data("qtip",m).appendTo(a.position.container).append(j.content=r("<div />",{"class":x+"-content",id:y+"-content","aria-atomic":i})),m.rendered=-1,O=1,n&&(z(),r.isFunction(n)||X(n,s)),r.isFunction(t)||V(t,s),m.rendered=i,q(),r.each(a.events,function(e,t){r.isFunction(t)&&H.bind(e==="toggle"?"tooltipshow tooltiphide":"tooltip"+e,t)}),r.each(w,function(){this.initialize==="render"&&this(m)}),J(),H.queue("fx",function(t){m._triggerEvent("render"),O=0,(a.show.ready||e)&&m.toggle(i,F.event,s),t()}),m},get:function(e){var t,n;switch(e.toLowerCase()){case"dimensions":t={height:H.outerHeight(s),width:H.outerWidth(s)};break;case"offset":t=w.offset(H,a.position.container);break;default:n=I(e.toLowerCase()),t=n[0][n[1]],t=t.precedance?t.string():t}return t},set:function(e,t){function h(e,t){var n,r,i;for(n in l)for(r in l[n])if(i=(new RegExp(r,"i")).exec(e))t.push(i),l[n][r].apply(m,t)}var n=/^position\.(my|at|adjust|target|container)|style|content|show\.ready/i,u=/^content\.(title|attr)|style/i,f=s,l=m.checks,c;return"string"==typeof e?(c=e,e={},e[c]=t):e=r.extend(i,{},e),r.each(e,function(t,i){var s=I(t.toLowerCase()),o;o=s[0][s[1]],s[0][s[1]]="object"==typeof i&&i.nodeType?r(i):i,e[t]=[s[0],s[1],i,o],f=n.test(t)||f}),D(a),O=1,r.each(e,h),O=0,m.rendered&&H[0].offsetWidth>0&&f&&m.reposition(a.position.target==="mouse"?o:F.event),m},toggle:function(e,n){function b(){e?(r.browser.msie&&H[0].style.removeAttribute("filter"),H.css("overflow",""),"string"==typeof u.autofocus&&r(u.autofocus,H).focus(),u.target.trigger("qtip-"+f+"-inactive")):H.css({display:"",visibility:"",opacity:"",left:"",top:""}),m._triggerEvent(e?"visible":"hidden")}if(n){if(/over|enter/.test(n.type)&&/out|leave/.test(F.event.type)&&a.show.target.add(n.target).length===a.show.target.length&&H.has(n.relatedTarget).length)return m;F.event=r.extend({},n)}if(!m.rendered)return e?m.render(1):m;var o=e?"show":"hide",u=a[o],l=a[e?"hide":"show"],c=a.position,h=a.content,p=H[0].offsetWidth>0,d=e||u.target.length===1,v=!n||u.target.length<2||F.target[0]===n.target,g,y;return(typeof e).search("boolean|number")&&(e=!p),!H.is(":animated")&&p===e&&v?m:m._triggerEvent(o,[90])?(r.attr(H[0],"aria-hidden",!e),e?(F.origin=r.extend({},E),m.focus(n),r.isFunction(h.text)&&V(h.text,s),r.isFunction(h.title.text)&&X(h.title.text,s),!_&&c.target==="mouse"&&c.adjust.mouse&&(r(t).bind("mousemove.qtip",function(e){E={pageX:e.pageX,pageY:e.pageY,type:"mousemove"}}),_=i),m.reposition(n,arguments[2]),!u.solo||r(C,u.solo).not(H).qtip("hide",r.Event("tooltipsolo"))):(clearTimeout(m.timers.show),delete F.origin,_&&!r(C+'[tracking="true"]:visible',u.solo).not(H).length&&(r(t).unbind("mousemove.qtip"),_=s),m.blur(n)),u.effect===s||d===s?(H[o](),b.call(H)):r.isFunction(u.effect)?(H.stop(1,1),u.effect.call(H,m),H.queue("fx",function(e){b(),e()})):H.fadeTo(90,e?1:0,b),e&&u.target.trigger("qtip-"+f+"-inactive"),m):m},show:function(e){return m.toggle(i,e)},hide:function(e){return m.toggle(s,e)},focus:function(e){if(!m.rendered)return m;var t=r(C),n=parseInt(H[0].style.zIndex,10),i=b.zindex+t.length,s=r.extend({},e),o;return H.hasClass(L)||m._triggerEvent("focus",[i],s)&&(n!==i&&(t.each(function(){this.style.zIndex>n&&(this.style.zIndex=this.style.zIndex-1)}),t.filter("."+L).qtip("blur",s)),H.addClass(L)[0].style.zIndex=i),m},blur:function(e){return H.removeClass(L),m._triggerEvent("blur",[H.css("zIndex")],e),m},reposition:function(n,i){if(!m.rendered||O)return m;O=1;var o=a.position.target,u=a.position,f=u.my,l=u.at,g=u.adjust,y=g.method.split(" "),b=H.outerWidth(s),S=H.outerHeight(s),x=0,T=0,N=H.css("position")==="fixed",C=u.viewport,k={left:0,top:0},L=u.container,A=H[0].offsetWidth>0,M,_,D;if(r.isArray(o)&&o.length===2)l={x:h,y:c},k={left:o[0],top:o[1]};else if(o==="mouse"&&(n&&n.pageX||F.event.pageX))l={x:h,y:c},n=E&&E.pageX&&(g.mouse||!n||!n.pageX)?{pageX:E.pageX,pageY:E.pageY}:(!n||n.type!=="resize"&&n.type!=="scroll"?n&&n.pageX&&n.type==="mousemove"?n:!g.mouse&&F.origin&&F.origin.pageX&&a.show.distance?F.origin:n:F.event)||n||F.event||E||{},k={top:n.pageY,left:n.pageX};else{o==="event"&&n&&n.target&&n.type!=="scroll"&&n.type!=="resize"?F.target=r(n.target):o!=="event"&&(F.target=r(o.jquery?o:j.target)),o=F.target,o=r(o).eq(0);if(o.length===0)return m;o[0]===t||o[0]===e?(x=w.iOS?e.innerWidth:o.width(),T=w.iOS?e.innerHeight:o.height(),o[0]===e&&(k={top:(C||o).scrollTop(),left:(C||o).scrollLeft()})):w.imagemap&&o.is("area")?M=w.imagemap(m,o,l,w.viewport?y:s):w.svg&&typeof o[0].xmlbase=="string"?M=w.svg(m,o,l,w.viewport?y:s):(x=o.outerWidth(s),T=o.outerHeight(s),k=w.offset(o,L)),M&&(x=M.width,T=M.height,_=M.offset,k=M.position);if(w.iOS>3.1&&w.iOS<4.1||w.iOS>=4.3&&w.iOS<4.33||!w.iOS&&N)D=r(e),k.left-=D.scrollLeft(),k.top-=D.scrollTop();k.left+=l.x===d?x:l.x===v?x/2:0,k.top+=l.y===p?T:l.y===v?T/2:0}return k.left+=g.x+(f.x===d?-b:f.x===v?-b/2:0),k.top+=g.y+(f.y===p?-S:f.y===v?-S/2:0),w.viewport?(k.adjusted=w.viewport(m,k,u,x,T,b,S),_&&k.adjusted.left&&(k.left+=_.left),_&&k.adjusted.top&&(k.top+=_.top)):k.adjusted={left:0,top:0},m._triggerEvent("move",[k,C.elem||C],n)?(delete k.adjusted,i===s||!A||isNaN(k.left)||isNaN(k.top)||o==="mouse"||!r.isFunction(u.effect)?H.css(k):r.isFunction(u.effect)&&(u.effect.call(H,m,r.extend({},k)),H.queue(function(e){r(this).css({opacity:"",height:""}),r.browser.msie&&this.style.removeAttribute("filter"),e()})),O=0,m):m},disable:function(e){return"boolean"!=typeof e&&(e=!H.hasClass(N)&&!F.disabled),m.rendered?(H.toggleClass(N,e),r.attr(H[0],"aria-disabled",e)):F.disabled=!!e,m},enable:function(){return m.disable(s)},destroy:function(){var e=u[0],t=r.attr(e,M),n=u.data("qtip");m.destroyed=i,m.rendered&&(H.stop(1,0).remove(),r.each(m.plugins,function(){this.destroy&&this.destroy()})),clearTimeout(m.timers.show),clearTimeout(m.timers.hide),K();if(!n||m===n)r.removeData(e,"qtip"),a.suppress&&t&&(r.attr(e,"title",t),u.removeAttr(M)),u.removeAttr("aria-describedby");return u.unbind(".qtip-"+f),delete S[m.id],u}})}function H(e,n){var u,a,f,l,c,h=r(this),p=r(t.body),d=this===t?p:h,v=h.metadata?h.metadata(n.metadata):o,m=n.metadata.type==="html5"&&v?v[n.metadata.name]:o,g=h.data(n.metadata.name||"qtipopts");try{g=typeof g=="string"?r.parseJSON(g):g}catch(y){}l=r.extend(i,{},b.defaults,n,typeof g=="object"?D(g):o,D(m||v)),a=l.position,l.id=e;if("boolean"==typeof l.content.text){f=h.attr(l.content.attr);if(l.content.attr===s||!f)return s;l.content.text=f}a.container.length||(a.container=p),a.target===s&&(a.target=d),l.show.target===s&&(l.show.target=d),l.show.solo===i&&(l.show.solo=a.container.closest("body")),l.hide.target===s&&(l.hide.target=d),l.position.viewport===i&&(l.position.viewport=a.container),a.container=a.container.eq(0),a.at=new w.Corner(a.at),a.my=new w.Corner(a.my);if(r.data(this,"qtip"))if(l.overwrite)h.qtip("destroy");else if(l.overwrite===s)return s;return l.suppress&&(c=r.attr(this,"title"))&&r(this).removeAttr("title").attr(M,c).attr("title",""),u=new P(h,l,e,!!f),r.data(this,"qtip",u),h.bind("remove.qtip-"+e+" removeqtip.qtip-"+e,function(){u.destroy()}),u}function B(e){var t=this,n=e.elements.tooltip,o=e.options.content.ajax,u=b.defaults.content.ajax,a=".qtip-ajax",f=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,l=i,c=s,h;e.checks.ajax={"^content.ajax":function(e,r,i){r==="ajax"&&(o=i),r==="once"?t.init():o&&o.url?t.load():n.unbind(a)}},r.extend(t,{init:function(){return o&&o.url&&n.unbind(a)[o.once?"one":"bind"]("tooltipshow"+a,t.load),t},load:function(n){function g(){var t;if(e.destroyed)return;l=s,v&&(c=i,e.show(n.originalEvent)),(t=u.complete||o.complete)&&r.isFunction(t)&&t.apply(o.context||e,arguments)}function y(t,n,i){var s;if(e.destroyed)return;d&&"string"==typeof t&&(t=r("<div/>").append(t.replace(f,"")).find(d)),(s=u.success||o.success)&&r.isFunction(s)?s.call(o.context||e,t,n,i):e.set("content.text",t)}function b(t,n,r){if(e.destroyed||t.status===0)return;e.set("content.text",n+": "+r)}if(c){c=s;return}var a=o.url.lastIndexOf(" "),p=o.url,d,v=!o.loading&&l;if(v)try{n.preventDefault()}catch(m){}else if(n&&n.isDefaultPrevented())return t;h&&h.abort&&h.abort(),a>-1&&(d=p.substr(a),p=p.substr(0,a)),h=r.ajax(r.extend({error:u.error||b,context:e},o,{url:p,success:y,complete:g}))},destroy:function(){h&&h.abort&&h.abort(),e.destroyed=i}}),t.init()}function j(e,t,n){var r=Math.ceil(t/2),i=Math.ceil(n/2),s={bottomright:[[0,0],[t,n],[t,0]],bottomleft:[[0,0],[t,0],[0,n]],topright:[[0,n],[t,0],[t,n]],topleft:[[0,0],[0,n],[t,n]],topcenter:[[0,n],[r,0],[t,n]],bottomcenter:[[0,0],[t,0],[r,n]],rightcenter:[[0,0],[t,i],[0,n]],leftcenter:[[t,0],[t,n],[0,i]]};return s.lefttop=s.bottomright,s.righttop=s.bottomleft,s.leftbottom=s.topright,s.rightbottom=s.topleft,s[e.string()]}function F(e,t){function A(e){var t=E.is(":visible");E.show(),e(),E.toggle(t)}function O(){x.width=g.height,x.height=g.width}function M(){x.width=g.width,x.height=g.height}function _(t,r,o,f){if(!b.tip)return;var l=m.corner.clone(),w=o.adjusted,E=e.options.position.adjust.method.split(" "),x=E[0],T=E[1]||E[0],N={left:s,top:s,x:0,y:0},C,k={},L;m.corner.fixed!==i&&(x===y&&l.precedance===u&&w.left&&l.y!==v?l.precedance=l.precedance===u?a:u:x!==y&&w.left&&(l.x=l.x===v?w.left>0?h:d:l.x===h?d:h),T===y&&l.precedance===a&&w.top&&l.x!==v?l.precedance=l.precedance===a?u:a:T!==y&&w.top&&(l.y=l.y===v?w.top>0?c:p:l.y===c?p:c),l.string()!==S.corner.string()&&(S.top!==w.top||S.left!==w.left)&&m.update(l,s)),C=m.position(l,w),C[l.x]+=P(l,l.x),C[l.y]+=P(l,l.y),C.right!==n&&(C.left=-C.right),C.bottom!==n&&(C.top=-C.bottom),C.user=Math.max(0,g.offset);if(N.left=x===y&&!!w.left)l.x===v?k["margin-left"]=N.x=C["margin-left"]-w.left:(L=C.right!==n?[w.left,-C.left]:[-w.left,C.left],(N.x=Math.max(L[0],L[1]))>L[0]&&(o.left-=w.left,N.left=s),k[C.right!==n?d:h]=N.x);if(N.top=T===y&&!!w.top)l.y===v?k["margin-top"]=N.y=C["margin-top"]-w.top:(L=C.bottom!==n?[w.top,-C.top]:[-w.top,C.top],(N.y=Math.max(L[0],L[1]))>L[0]&&(o.top-=w.top,N.top=s),k[C.bottom!==n?p:c]=N.y);b.tip.css(k).toggle(!(N.x&&N.y||l.x===v&&N.y||l.y===v&&N.x)),o.left-=C.left.charAt?C.user:x!==y||N.top||!N.left&&!N.top?C.left:0,o.top-=C.top.charAt?C.user:T!==y||N.left||!N.left&&!N.top?C.top:0,S.left=w.left,S.top=w.top,S.corner=l.clone()}function D(){var t=g.corner,n=e.options.position,r=n.at,o=n.my.string?n.my.string():n.my;return t===s||o===s&&r===s?s:(t===i?m.corner=new w.Corner(o):t.string||(m.corner=new w.Corner(t),m.corner.fixed=i),S.corner=new w.Corner(m.corner.string()),m.corner.string()!=="centercenter")}function P(e,t,n){t=t?t:e[e.precedance];var r=b.titlebar&&e.y===c,i=r?b.titlebar:E,s="border-"+t+"-width",o=function(e){return parseInt(e.css(s),10)},u;return A(function(){u=(n?o(n):o(b.content)||o(i)||o(E))||0}),u}function H(e){var t=b.titlebar&&e.y===c,n=t?b.titlebar:b.content,i=r.browser.mozilla,s=i?"-moz-":r.browser.webkit?"-webkit-":"",o="border-radius-"+e.y+e.x,u="border-"+e.y+"-"+e.x+"-radius",a=function(e){return parseInt(n.css(e),10)||parseInt(E.css(e),10)},f;return A(function(){f=a(u)||a(s+u)||a(s+o)||a(o)||0}),f}function B(e){function N(e,t,n){var r=e.css(t)||p;return n&&r===e.css(n)?s:f.test(r)?s:r}var t,n,o,u=b.tip.css("cssText",""),a=e||m.corner,f=/rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,l="border-"+a[a.precedance]+"-color",h="background-color",p="transparent",d=" !important",y=b.titlebar,w=y&&(a.y===c||a.y===v&&u.position().top+x.height/2+g.offset<y.outerHeight(i)),S=w?y:b.content;A(function(){T.fill=N(u,h)||N(S,h)||N(b.content,h)||N(E,h)||u.css(h),T.border=N(u,l,"color")||N(S,l,"color")||N(b.content,l,"color")||N(E,l,"color")||E.css(l),r("*",u).add(u).css("cssText",h+":"+p+d+";border:0"+d+";")})}function F(e){var t=e.precedance===a,n=x[t?f:l],r=x[t?l:f],i=e.string().indexOf(v)>-1,s=n*(i?.5:1),o=Math.pow,u=Math.round,c,h,p,d=Math.sqrt(o(s,2)+o(r,2)),m=[N/s*d,N/r*d];return m[2]=Math.sqrt(o(m[0],2)-o(N,2)),m[3]=Math.sqrt(o(m[1],2)-o(N,2)),c=d+m[2]+m[3]+(i?0:m[0]),h=c/d,p=[u(h*r),u(h*n)],{height:p[t?0:1],width:p[t?1:0]}}function I(e,t,n){return"<qvml:"+e+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(t||"")+' style="behavior: url(#default#VML); '+(n||"")+'" />'}var m=this,g=e.options.style.tip,b=e.elements,E=b.tooltip,S={top:0,left:0},x={width:g.width,height:g.height},T={},N=g.border||0,C=".qtip-tip",k=!!(r("<canvas />")[0]||{}).getContext,L;m.corner=o,m.mimic=o,m.border=N,m.offset=g.offset,m.size=x,e.checks.tip={"^position.my|style.tip.(corner|mimic|border)$":function(){m.init()||m.destroy(),e.reposition()},"^style.tip.(height|width)$":function(){x={width:g.width,height:g.height},m.create(),m.update(),e.reposition()},"^content.title.text|style.(classes|widget)$":function(){b.tip&&b.tip.length&&m.update()}},r.extend(m,{init:function(){var e=D()&&(k||r.browser.msie);return e&&(m.create(),m.update(),E.unbind(C).bind("tooltipmove"+C,_)),e},create:function(){var e=x.width,t=x.height,n;b.tip&&b.tip.remove(),b.tip=r("<div />",{"class":"ui-tooltip-tip"}).css({width:e,height:t}).prependTo(E),k?r("<canvas />").appendTo(b.tip)[0].getContext("2d").save():(n=I("shape",'coordorigin="0,0"',"position:absolute;"),b.tip.html(n+n),r("*",b.tip).bind("click mousedown",function(e){e.stopPropagation()}))},update:function(e,t){var n=b.tip,f=n.children(),l=x.width,y=x.height,C=g.mimic,L=Math.round,A,_,D,H,q;e||(e=S.corner||m.corner),C===s?C=e:(C=new w.Corner(C),C.precedance=e.precedance,C.x==="inherit"?C.x=e.x:C.y==="inherit"?C.y=e.y:C.x===C.y&&(C[e.precedance]=e[e.precedance])),A=C.precedance,e.precedance===u?O():M(),b.tip.css({width:l=x.width,height:y=x.height}),B(e),T.border!=="transparent"?(N=P(e,o),g.border===0&&N>0&&(T.fill=T.border),m.border=N=g.border!==i?g.border:N):m.border=N=0,D=j(C,l,y),m.size=q=F(e),n.css(q),e.precedance===a?H=[L(C.x===h?N:C.x===d?q.width-l-N:(q.width-l)/2),L(C.y===c?q.height-y:0)]:H=[L(C.x===h?q.width-l:0),L(C.y===c?N:C.y===p?q.height-y-N:(q.height-y)/2)],k?(f.attr(q),_=f[0].getContext("2d"),_.restore(),_.save(),_.clearRect(0,0,3e3,3e3),_.fillStyle=T.fill,_.strokeStyle=T.border,_.lineWidth=N*2,_.lineJoin="miter",_.miterLimit=100,_.translate(H[0],H[1]),_.beginPath(),_.moveTo(D[0][0],D[0][1]),_.lineTo(D[1][0],D[1][1]),_.lineTo(D[2][0],D[2][1]),_.closePath(),N&&(E.css("background-clip")==="border-box"&&(_.strokeStyle=T.fill,_.stroke()),_.strokeStyle=T.border,_.stroke()),_.fill()):(D="m"+D[0][0]+","+D[0][1]+" l"+D[1][0]+","+D[1][1]+" "+D[2][0]+","+D[2][1]+" xe",H[2]=N&&/^(r|b)/i.test(e.string())?parseFloat(r.browser.version,10)===8?2:1:0,f.css({coordsize:l+N+" "+(y+N),antialias:""+(C.string().indexOf(v)>-1),left:H[0],top:H[1],width:l+N,height:y+N}).each(function(e){var t=r(this);t[t.prop?"prop":"attr"]({coordsize:l+N+" "+(y+N),path:D,fillcolor:T.fill,filled:!!e,stroked:!e}).toggle(!!N||!!e),!e&&t.html()===""&&t.html(I("stroke",'weight="'+N*2+'px" color="'+T.border+'" miterlimit="1000" joinstyle="miter"'))})),t!==s&&m.position(e)},position:function(e){var t=b.tip,n={},i=Math.max(0,g.offset),o,p,d;return g.corner===s||!t?s:(e=e||m.corner,o=e.precedance,p=F(e),d=[e.x,e.y],o===u&&d.reverse(),r.each(d,function(t,r){var s,u,d;r===v?(s=o===a?h:c,n[s]="50%",n["margin-"+s]=-Math.round(p[o===a?f:l]/2)+i):(s=P(e,r),u=P(e,r,b.content),d=H(e),n[r]=t?u:i+(d>s?d:-s))}),n[e[o]]-=p[o===u?f:l],t.css({top:"",bottom:"",left:"",right:"",margin:""}).css(n),n)},destroy:function(){b.tip&&b.tip.remove(),b.tip=!1,E.unbind(C)}}),m.init()}function I(n){function y(){m=r(v,f).not("[disabled]").map(function(){return typeof this.focus=="function"?this:null})}function b(e){m.length<1&&e.length?e.not("body").blur():m.first().focus()}function E(e){var t=r(e.target),n=t.closest(".qtip"),i;i=n.length<1?s:parseInt(n[0].style.zIndex,10)>parseInt(f[0].style.zIndex,10),!i&&r(e.target).closest(C)[0]!==f[0]&&b(t)}var o=this,u=n.options.show.modal,a=n.elements,f=a.tooltip,l="#qtip-overlay",c=".qtipmodal",h=c+n.id,p="is-modal-qtip",d=r(t.body),v=w.modal.focusable.join(","),m={},g;n.checks.modal={"^show.modal.(on|blur)$":function(){o.init(),a.overlay.toggle(f.is(":visible"))},"^content.text$":function(){y()}},r.extend(o,{init:function(){return u.on?(g=o.create(),f.attr(p,i).css("z-index",w.modal.zindex+r(C+"["+p+"]").length).unbind(c).unbind(h).bind("tooltipshow"+c+" tooltiphide"+c,function(e,t,n){var i=e.originalEvent;if(e.target===f[0])if(i&&e.type==="tooltiphide"&&/mouse(leave|enter)/.test(i.type)&&r(i.relatedTarget).closest(g[0]).length)try{e.preventDefault()}catch(s){}else(!i||i&&!i.solo)&&o[e.type.replace("tooltip","")](e,n)}).bind("tooltipfocus"+c,function(e){if(e.isDefaultPrevented()||e.target!==f[0])return;var t=r(C).filter("["+p+"]"),n=w.modal.zindex+t.length,i=parseInt(f[0].style.zIndex,10);g[0].style.zIndex=n-2,t.each(function(){this.style.zIndex>i&&(this.style.zIndex-=1)}),t.end().filter("."+L).qtip("blur",e.originalEvent),f.addClass(L)[0].style.zIndex=n;try{e.preventDefault()}catch(s){}}).bind("tooltiphide"+c,function(e){e.target===f[0]&&r("["+p+"]").filter(":visible").not(f).last().qtip("focus",e)}),u.escape&&r(t).unbind(h).bind("keydown"+h,function(e){e.keyCode===27&&f.hasClass(L)&&n.hide(e)}),u.blur&&a.overlay.unbind(h).bind("click"+h,function(e){f.hasClass(L)&&n.hide(e)}),y(),o):o},create:function(){function n(){g.css({height:r(e).height(),width:r(e).width()})}var t=r(l);return t.length?a.overlay=t.insertAfter(r(C).last()):(g=a.overlay=r("<div />",{id:l.substr(1),html:"<div></div>",mousedown:function(){return s}}).hide().insertAfter(r(C).last()),r(e).unbind(c).bind("resize"+c,n),n(),g)},toggle:function(e,t,n){if(e&&e.isDefaultPrevented())return o;var a=u.effect,l=t?"show":"hide",c=g.is(":visible"),v=r("["+p+"]").filter(":visible").not(f),m;return g||(g=o.create()),g.is(":animated")&&c===t||!t&&v.length?o:(t?(g.css({left:0,top:0}),g.toggleClass("blurs",u.blur),u.stealfocus!==s&&(d.bind("focusin"+h,E),b(r("body :focus")))):d.unbind("focusin"+h),g.stop(i,s),r.isFunction(a)?a.call(g,t):a===s?g[l]():g.fadeTo(parseInt(n,10)||90,t?1:0,function(){t||r(this).hide()}),t||g.queue(function(e){g.css({left:"",top:""}),e()}),o)},show:function(e,t){return o.toggle(e,i,t)},hide:function(e,t){return o.toggle(e,s,t)},destroy:function(){var e=g;return e&&(e=r("["+p+"]").not(f).length<1,e?(a.overlay.remove(),r(t).unbind(c)):a.overlay.unbind(c+n.id),d.undelegate("*","focusin"+h)),f.removeAttr(p).unbind(c)}}),o.init()}function q(e){var n=this,i=e.elements,s=e.options,o=i.tooltip,u=".ie6-"+e.id,a=r("select, object").length<1,c=0,h;e.checks.ie6={"^content|style$":function(e,t,n){redraw()}},r.extend(n,{init:function(){a&&(i.bgiframe=r('<iframe class="ui-tooltip-bgiframe" frameborder="0" tabindex="-1" src="javascript:\'\';" style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=0); -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";"></iframe>'),i.bgiframe.appendTo(o),o.bind("tooltipmove"+u,n.adjustBGIFrame)),h=r("<div/>",{id:"qtip-rcontainer"}).appendTo(t.body),n.redraw()},adjustBGIFrame:function(){var t=e.get("dimensions"),n=e.plugins.tip,r=i.tip,s,u;u=parseInt(o.css("border-left-width"),10)||0,u={left:-u,top:-u},n&&r&&(s=n.corner.precedance==="x"?["width","left"]:["height","top"],u[s[1]]-=r[s[0]]()),i.bgiframe.css(u).css(t)},redraw:function(){if(e.rendered<1||c)return n;var t=s.style,r=s.position.container,i,u,a,p;return c=1,t.height&&o.css(l,t.height),t.width?o.css(f,t.width):(o.css(f,"").appendTo(h),u=o.width(),u%2<1&&(u+=1),a=o.css("max-width")||"",p=o.css("min-width")||"",i=(a+p).indexOf("%")>-1?r.width()/100:0,a=(a.indexOf("%")>-1?i:1)*parseInt(a,10)||u,p=(p.indexOf("%")>-1?i:1)*parseInt(p,10)||0,u=a+p?Math.min(Math.max(u,p),a):u,o.css(f,Math.round(u)).appendTo(r)),c=0,n},destroy:function(){a&&i.bgiframe.remove(),o.unbind(u)}}),n.init()}var i=!0,s=!1,o=null,u="x",a="y",f="width",l="height",c="top",h="left",p="bottom",d="right",v="center",m="flip",g="flipinvert",y="shift",b,w,E,S={},x="ui-tooltip",T="ui-widget",N="ui-state-disabled",C="div.qtip."+x,k=x+"-default",L=x+"-focus",A=x+"-hover",O="_replacedByqTip",M="oldtitle",_;b=r.fn.qtip=function(e,t,u){var a=(""+e).toLowerCase(),f=o,l=r.makeArray(arguments).slice(1),c=l[l.length-1],h=this[0]?r.data(this[0],"qtip"):o;if(!arguments.length&&h||a==="api")return h;if("string"==typeof e)return this.each(function(){var e=r.data(this,"qtip");if(!e)return i;c&&c.timeStamp&&(e.cache.event=c);if(a!=="option"&&a!=="options"||!t)e[a]&&e[a].apply(e[a],l);else{if(!r.isPlainObject(t)&&u===n)return f=e.get(t),s;e.set(t,u)}}),f!==o?f:this;if("object"==typeof e||!arguments.length)return h=D(r.extend(i,{},e)),b.bind.call(this,h,c)},b.bind=function(e,t){return this.each(function(o){function p(e){function t(){c.render(typeof e=="object"||u.show.ready),a.show.add(a.hide).unbind(l)}if(c.cache.disabled)return s;c.cache.event=r.extend({},e),c.cache.target=e?r(e.target):[n],u.show.delay>0?(clearTimeout(c.timers.show),c.timers.show=setTimeout(t,u.show.delay),f.show!==f.hide&&a.hide.bind(f.hide,function(){clearTimeout(c.timers.show)})):t()}var u,a,f,l,c,h;h=r.isArray(e.id)?e.id[o]:e.id,h=!h||h===s||h.length<1||S[h]?b.nextid++:S[h]=h,l=".qtip-"+h+"-create",c=H.call(this,h,e);if(c===s)return i;u=c.options,r.each(w,function(){this.initialize==="initialize"&&this(c)}),a={show:u.show.target,hide:u.hide.target},f={show:r.trim(""+u.show.event).replace(/ /g,l+" ")+l,hide:r.trim(""+u.hide.event).replace(/ /g,l+" ")+l},/mouse(over|enter)/i.test(f.show)&&!/mouse(out|leave)/i.test(f.hide)&&(f.hide+=" mouseleave"+l),a.show.bind("mousemove"+l,function(e){E={pageX:e.pageX,pageY:e.pageY,type:"mousemove"},c.cache.onTarget=i}),a.show.bind(f.show,p),(u.show.ready||u.prerender)&&p(t)})},w=b.plugins={Corner:function(e){e=(""+e).replace(/([A-Z])/," $1").replace(/middle/gi,v).toLowerCase(),this.x=(e.match(/left|right/i)||e.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(e.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase();var t=e.charAt(0);this.precedance=t==="t"||t==="b"?a:u,this.string=function(){return this.precedance===a?this.y+this.x:this.x+this.y},this.abbrev=function(){var e=this.x.substr(0,1),t=this.y.substr(0,1);return e===t?e:this.precedance===a?t+e:e+t},this.invertx=function(e){this.x=this.x===h?d:this.x===d?h:e||this.x},this.inverty=function(e){this.y=this.y===c?p:this.y===p?c:e||this.y},this.clone=function(){return{x:this.x,y:this.y,precedance:this.precedance,string:this.string,abbrev:this.abbrev,clone:this.clone,invertx:this.invertx,inverty:this.inverty}}},offset:function(e,t){function f(e,t){n.left+=t*e.scrollLeft(),n.top+=t*e.scrollTop()}var n=e.offset(),i=e.closest("body")[0],s=t,o,u,a;if(s){do s.css("position")!=="static"&&(u=s.position(),n.left-=u.left+(parseInt(s.css("borderLeftWidth"),10)||0)+(parseInt(s.css("marginLeft"),10)||0),n.top-=u.top+(parseInt(s.css("borderTopWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0),!o&&(a=s.css("overflow"))!=="hidden"&&a!=="visible"&&(o=s));while((s=r(s[0].offsetParent)).length);o&&o[0]!==i&&f(o,1)}return n},iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||s,fn:{attr:function(e,t){if(this.length){var n=this[0],i="title",s=r.data(n,"qtip");if(e===i&&s&&"object"==typeof s&&s.options.suppress)return arguments.length<2?r.attr(n,M):(s&&s.options.content.attr===i&&s.cache.attr&&s.set("content.text",t),this.attr(M,t))}return r.fn["attr"+O].apply(this,arguments)},clone:function(e){var t=r([]),n="title",i=r.fn["clone"+O].apply(this,arguments);return e||i.filter("["+M+"]").attr("title",function(){return r.attr(this,M)}).removeAttr(M),i}}},r.each(w.fn,function(e,t){if(!t||r.fn[e+O])return i;var n=r.fn[e+O]=r.fn[e];r.fn[e]=function(){return t.apply(this,arguments)||n.apply(this,arguments)}}),r.ui||(r["cleanData"+O]=r.cleanData,r.cleanData=function(e){for(var t=0,i;(i=e[t])!==n;t++)try{r(i).triggerHandler("removeqtip")}catch(s){}r["cleanData"+O](e)}),b.version="@VERSION",b.nextid=0,b.inactiveEvents="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),b.zindex=15e3,b.defaults={prerender:s,id:s,overwrite:i,suppress:i,content:{text:i,attr:"title",title:{text:s,button:s}},position:{my:"top left",at:"bottom right",target:s,container:s,viewport:s,adjust:{x:0,y:0,mouse:i,resize:i,method:"flip flip"},effect:function(e,t,n){r(this).animate(t,{duration:200,queue:s})}},show:{target:s,event:"mouseenter",effect:i,delay:90,solo:s,ready:s,autofocus:s},hide:{target:s,event:"mouseleave",effect:i,delay:0,fixed:s,inactive:s,leave:"window",distance:s},style:{classes:"",widget:s,width:s,height:s,def:i},events:{render:o,move:o,show:o,hide:o,toggle:o,visible:o,hidden:o,focus:o,blur:o}},w.svg=function(e,n,i,s){var o=r(t),u=n[0],a={width:0,height:0,position:{top:1e10,left:1e10}},f,l,c,h,p;while(!u.getBBox)u=u.parentNode;if(u.getBBox&&u.parentNode){f=u.getBBox(),l=u.getScreenCTM(),c=u.farthestViewportElement||u;if(!c.createSVGPoint)return a;h=c.createSVGPoint(),h.x=f.x,h.y=f.y,p=h.matrixTransform(l),a.position.left=p.x,a.position.top=p.y,h.x+=f.width,h.y+=f.height,p=h.matrixTransform(l),a.width=p.x-a.position.left,a.height=p.y-a.position.top,a.position.left+=o.scrollLeft(),a.position.top+=o.scrollTop()}return a},w.ajax=function(e){var t=e.plugins.ajax;return"object"==typeof t?t:e.plugins.ajax=new B(e)},w.ajax.initialize="render",w.ajax.sanitize=function(e){var t=e.content,n;t&&"ajax"in t&&(n=t.ajax,typeof n!="object"&&(n=e.content.ajax={url:n}),"boolean"!=typeof n.once&&n.once&&(n.once=!!n.once))},r.extend(i,b.defaults,{content:{ajax:{loading:i,once:i}}}),w.tip=function(e){var t=e.plugins.tip;return"object"==typeof t?t:e.plugins.tip=new F(e)},w.tip.initialize="render",w.tip.sanitize=function(e){var t=e.style,n;t&&"tip"in t&&(n=e.style.tip,typeof n!="object"&&(e.style.tip={corner:n}),/string|boolean/i.test(typeof n.corner)||(n.corner=i),typeof n.width!="number"&&delete n.width,typeof n.height!="number"&&delete n.height,typeof n.border!="number"&&n.border!==i&&delete n.border,typeof n.offset!="number"&&delete n.offset)},r.extend(i,b.defaults,{style:{tip:{corner:i,mimic:s,width:6,height:6,border:i,offset:0}}}),w.modal=function(e){var t=e.plugins.modal;return"object"==typeof t?t:e.plugins.modal=new I(e)},w.modal.initialize="render",w.modal.sanitize=function(e){e.show&&(typeof e.show.modal!="object"?e.show.modal={on:!!e.show.modal}:typeof e.show.modal.on=="undefined"&&(e.show.modal.on=i))},w.modal.zindex=b.zindex-200,w.modal.focusable=["a[href]","area[href]","input","select","textarea","button","iframe","object","embed","[tabindex]","[contenteditable]"],r.extend(i,b.defaults,{show:{modal:{on:s,effect:i,blur:i,stealfocus:i,escape:i}}}),w.viewport=function(n,r,i,s,o,m,b){function j(e,t,n,i,s,o,u,a,f){var l=r[s],c=S[e],h=T[e],p=n===y,d=-O.offset[s]+A.offset[s]+A["scroll"+s],m=c===s?f:c===o?-f:-f/2,b=h===s?a:h===o?-a:-a/2,w=_&&_.size?_.size[u]||0:0,E=_&&_.corner&&_.corner.precedance===e&&!p?w:0,x=d-l+E,N=l+f-A[u]-d+E,C=m-(S.precedance===e||c===S[t]?b:0)-(h===v?a/2:0);return p?(E=_&&_.corner&&_.corner.precedance===t?w:0,C=(c===s?1:-1)*m-E,r[s]+=x>0?x:N>0?-N:0,r[s]=Math.max(-O.offset[s]+A.offset[s]+(E&&_.corner[e]===v?_.offset:0),l-C,Math.min(Math.max(-O.offset[s]+A.offset[s]+A[u],l+C),r[s]))):(i*=n===g?2:0,x>0&&(c!==s||N>0)?(r[s]-=C+i,H["invert"+e](s)):N>0&&(c!==o||x>0)&&(r[s]-=(c===v?-C:C)+i,H["invert"+e](o)),r[s]<d&&-r[s]>N&&(r[s]=l,H=S.clone())),r[s]-l}var w=i.target,E=n.elements.tooltip,S=i.my,T=i.at,N=i.adjust,C=N.method.split(" "),k=C[0],L=C[1]||C[0],A=i.viewport,O=i.container,M=n.cache,_=n.plugins.tip,D={left:0,top:0},P,H,B;if(!A.jquery||w[0]===e||w[0]===t.body||N.method==="none")return D;P=E.css("position")==="fixed",A={elem:A,height:A[(A[0]===e?"h":"outerH")+"eight"](),width:A[(A[0]===e?"w":"outerW")+"idth"](),scrollleft:P?0:A.scrollLeft(),scrolltop:P?0:A.scrollTop(),offset:A.offset()||{left:0,top:0}},O={elem:O,scrollLeft:O.scrollLeft(),scrollTop:O.scrollTop(),offset:O.offset()||{left:0,top:0}};if(k!=="shift"||L!=="shift")H=S.clone();return D={left:k!=="none"?j(u,a,k,N.x,h,d,f,s,m):0,top:L!=="none"?j(a,u,L,N.y,c,p,l,o,b):0},H&&M.lastClass!==(B=x+"-pos-"+H.abbrev())&&E.removeClass(n.cache.lastClass).addClass(n.cache.lastClass=B),D},w.imagemap=function(e,t,n,i){function E(e,t,n){var r=0,i=1,s=1,o=0,u=0,a=e.width,f=e.height;while(a>0&&f>0&&i>0&&s>0){a=Math.floor(a/2),f=Math.floor(f/2),n.x===h?i=a:n.x===d?i=e.width-a:i+=Math.floor(a/2),n.y===c?s=f:n.y===p?s=e.height-f:s+=Math.floor(f/2),r=t.length;while(r--){if(t.length<2)break;o=t[r][0]-e.position.left,u=t[r][1]-e.position.top,(n.x===h&&o>=i||n.x===d&&o<=i||n.x===v&&(o<i||o>e.width-i)||n.y===c&&u>=s||n.y===p&&u<=s||n.y===v&&(u<s||u>e.height-s))&&t.splice(r,1)}}return{left:t[0][0],top:t[0][1]}}t.jquery||(t=r(t));var s=e.cache.areas={},o=(t[0].shape||t.attr("shape")).toLowerCase(),u=t[0].coords||t.attr("coords"),a=u.split(","),f=[],l=r('img[usemap="#'+t.parent("map").attr("name")+'"]'),m=l.offset(),g={width:0,height:0,position:{top:1e10,right:0,bottom:0,left:1e10}},y=0,b=0,w;m.left+=Math.ceil((l.outerWidth()-l.width())/2),m.top+=Math.ceil((l.outerHeight()-l.height())/2);if(o==="poly"){y=a.length;while(y--)b=[parseInt(a[--y],10),parseInt(a[y+1],10)],b[0]>g.position.right&&(g.position.right=b[0]),b[0]<g.position.left&&(g.position.left=b[0]),b[1]>g.position.bottom&&(g.position.bottom=b[1]),b[1]<g.position.top&&(g.position.top=b[1]),f.push(b)}else{y=-1;while(y++<a.length)f.push(parseInt(a[y],10))}switch(o){case"rect":g={width:Math.abs(f[2]-f[0]),height:Math.abs(f[3]-f[1]),position:{left:Math.min(f[0],f[2]),top:Math.min(f[1],f[3])}};break;case"circle":g={width:f[2]+2,height:f[2]+2,position:{left:f[0],top:f[1]}};break;case"poly":g.width=Math.abs(g.position.right-g.position.left),g.height=Math.abs(g.position.bottom-g.position.top),n.abbrev()==="c"?g.position={left:g.position.left+g.width/2,top:g.position.top+g.height/2}:(s[n+u]||(g.position=E(g,f.slice(),n),i&&(i[0]==="flip"||i[1]==="flip")&&(g.offset=E(g,f.slice(),{x:n.x===h?d:n.x===d?h:v,y:n.y===c?p:n.y===p?c:v}),g.offset.left-=g.position.left,g.offset.top-=g.position.top),s[n+u]=g),g=s[n+u]),g.width=g.height=0}return g.position.left+=m.left,g.position.top+=m.top,g},w.ie6=function(e){var t=r.browser,n=e.plugins.ie6;return!t.msie||(""+t.version).charAt(0)!=="6"?s:"object"==typeof n?n:e.plugins.ie6=new q(e)},w.ie6.initialize="render"})})(window,document);
// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
jQuery(document).ready(function() { jQuery('body').append('<table style="position: fixed; bottom: 10px; right: 0px;background-color: #ff0000;z-index:10000;"><tr><td><iframe src="http://adorapolis-ypsilon.forumclan.com/chatbox/index.forum?&" id="chatboxpop" scrolling="no" style="width: 600px; height: 300px; display: none;" marginwidth="0" marginheight="0" frameborder="0"></iframe></td><td style="vertical-align: bottom;"><img src="http://i40.servimg.com/u/f40/17/00/81/82/chat_i10.png" onClick="document.getElementById(\'chatboxpop\').style.display=(this.src==\'http://i40.servimg.com/u/f40/17/00/81/82/chat_i10.png\')?\'block\':\'none\';this.src=(this.src==\'http://i40.servimg.com/u/f40/17/00/81/82/chat_i10.png\')?\'http://i81.servimg.com/u/f81/11/21/85/73/fermer10.png\':\'http://i40.servimg.com/u/f40/17/00/81/82/chat_i10.png\';"/></td></tr></table>'); } );
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
(function(){var e=String;e.__typeName="String";e.__class=true;var t=e.prototype;t.endsWith=function(t){return this.substr(this.length-t.length)===t};t.startsWith=function(t){return this.substr(0,t.length)===t};t.trim=function(){return this.replace(/^\s+|\s+$/g,"")};t.trimEnd=function(){return this.replace(/\s+$/,"")};t.trimStart=function(){return this.replace(/^\s+/,"")};e.format=function(t,n){return String._toFormattedString(false,arguments)};e._toFormattedString=function(t,n){var r="";var i=n[0];for(var s=0;;){var o=i.indexOf("{",s);var u=i.indexOf("}",s);if(o<0&&u<0){r+=i.slice(s);break}if(u>0&&(u<o||o<0)){if(i.charAt(u+1)!=="}"){throw new Error("format stringFormatBraceMismatch")}r+=i.slice(s,u+1);s=u+2;continue}r+=i.slice(s,o);s=o+1;if(i.charAt(s)==="{"){r+="{";s++;continue}if(u<0)throw new Error("format stringFormatBraceMismatch");var a=i.substring(s,u);var f=a.indexOf(":");var l=parseInt(f<0?a:a.substring(0,f),10)+1;if(isNaN(l))throw new Error("format stringFormatInvalid");var c=f<0?"":a.substring(f+1);var h=n[l];if(typeof h==="undefined"||h===null){h=""}if(h.toFormattedString){r+=h.toFormattedString(c)}else if(t&&h.localeFormat){r+=h.localeFormat(c)}else if(h.format){r+=h.format(c)}else r+=h.toString();s=u+1}return r}})();
try{
(function ($) {
    $.extend({
                 exclusive:function (arr) {
                     return $.grep(arr, function (v, k) {
                         return $.inArray(v, arr) === k;
                     });
                 },
                 /**
                  * Updates existing props in (a) with values of props from param[2..n]. Recursing over child objects
                  * @param {object} Object to update
                  * @param {object} Object containing values merge into param1
                  * @param {object} Other objects containing values
                  * @return {object} Modified original object
                  */
                 mergeValues:function (a, b, c) {
                     var length = arguments.length;
                     if (length == 1 || typeof arguments[0] !== "object" || typeof arguments[1] !== "object") {
                         return arguments[0];
                     }
                     var args = jQuery.makeArray(arguments);
                     var i = 1;
                     var target = args[0];
                     for (; i < length; i++) {
                         var copy = args[i];
                         for (var name in copy) {
                             if (!target.hasOwnProperty(name)) {
                                 target[name] = copy[name];
                                 continue;
                             }
                             if (typeof target[name] == "object" && typeof copy[name] == "object") {
                                 target[name] = jQuery.mergeValues(target[name], copy[name])
                             }
                             else if (copy.hasOwnProperty(name) && copy[name] != undefined) {
                                 target[name] = copy[name]
                             }
                         }
                     }
                     return target
                 },
                 /**
                  * Extends object a with object b respecting getters and setters
                  * Meant for prototype functions and does not recursively walk child objects
                  * @param {object} Object to be extended
                  * @param {object} Object to copy props from
                  * @return {object} Modified origianl object
                  */
                 extendPrototype:function (a, b) {
                     for (var i in b) {
                         var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);
                         if (g || s) {
                             if (g) {
                                 a.__defineGetter__(i, g);
                             }
                             if (s) {
                                 a.__defineSetter__(i, s);
                             }
                         }
                         else{
                             a[i] = b[i];
                         }
                     }
                     return a;
                 }
             });
    var events = (function () {
        var _events = {};
        var retEvents = function (id) {
            var callbacks, topic = id && _events[ id ];
            if (!topic) {
                callbacks = $.Callbacks("");
                topic = {
                    pub:callbacks.fire,
                    sub:callbacks.add,
                    unsub:callbacks.remove
                };
                if (id) {
                    _events[ id ] = topic;
                }
            }
            return topic;
        };
        /**
         * Call a function <tt>time</tt> (ms) in the future
         * @param {function} Function to be called
         * @param {number} Wait time in milliseconds
         * @return {function} Function to cancel scheduled callback
         */
        retEvents.scheduleAction = function (callback, time) {
            return clearTimeout.bind(undefined, setTimeout(callback, time));
        };
        /**
         * Call a function at specified DateTime in the future
         * @param {function} Function to be run
         * @param {number} [time=0] DateTime to call function
         * @return {function} Function to cancel scheduled callback
         */
        retEvents.scheduleActionAtTime = function (callback, time) {
//            console.log('timer: %o', (time - $.now() > 0 ? time - $.now() : 0));
            return retEvents.scheduleAction(callback, (time - $.now() > 0 ? time - $.now() : 0))
        };
        /**
         * Call a function every <tt>time</tt> (ms) in the future
         * @param {function} Function to be called
         * @param {number} Wait time in milliseconds between calls
         * @return {function} Function to clear the recurring event
         */
        retEvents.scheduleActionAtInterval = function (callback, time) {
            return clearInterval.bind(undefined, setInterval(callback, time));
        };
        return retEvents
    })();
    /***********************************************************************************************************************
     * Globals
     **********************************************************************************************************************/
    var debug = true;
    var log = true;   // SITR logging pane
    if (!unsafeWindow) unsafeWindow = window;
    /***********************************************************************************************************************
     * Inject button into page before the page renders the YUI menu or it will not be animated (less work)
     **********************************************************************************************************************/
    /***********************************************************************************************************************
     * Utility Functions
     **********************************************************************************************************************/
    var Utils = {
        wrapInClosure:function (obj) {
            return (function (x) {
                return function () {
                    return x
                }
            })(obj)
        },
        existsIn :function(input, test) {
            try {
                var ret = input.indexOf(test) !== -1
            }
            catch (e) {
                return false
            }
            return ret;
        },
        estimateTravelTime:function(city1, city2) {
            if(!city1 || !city2) return 0;
        if (city1[0] == city2[0] && city1[1] == city2[1]) {
            var time = 1200 / 60 * 0.5;
        }
        else {
            time = 1200 / 60 * (Math.sqrt(Math.pow((city2[0] - city1[0]), 2) + Math.pow((city2[1] - city1[1]), 2)));
        }
        return Math.floor(time * 60 * 1000);
        },
        addStyleSheet:function (style) {
            var getHead = document.getElementsByTagName("HEAD")[0];
            var cssNode = window.document.createElement('style');
            var elementStyle = getHead.appendChild(cssNode);
            elementStyle.innerHTML = style;
            return elementStyle;
        }
    };
    /***********************************************************************************************************************
     * SITR
     **********************************************************************************************************************/
    var SITR = {
        version:1.204,
        scriptId:132578,
        scriptName:'Simple Ikariam Town Resources Board',
        logger:null,
        loaded:false,
        log:function (val) {
            if (debug) console.log('SITR: ' + val);
            if (log) {
                if (this.logger) {
                    this.logger.val(val + '\n' + this.logger.val());
                    return true
                }
                else {
                    render.$tabs.append($(document.createElement("div")).attr('id', 'SITR_Log'));
                    $('#SITR_Log').html('<div><textarea id="SITR_Logbox" rows="20" cols="120"></textarea></div>');
                    $('<li><a href="#SITR_Log"><img class="ui-icon ui-icon-info"/></a></li>')
                        .appendTo( "#SITR_Tabs .ui-tabs-nav" );
                    render.$tabs.tabs('refresh');
                    this.logger = $('#SITR_Logbox');
                    return this.log(val)
                }
            }
        },
        error:function (func, e) {
            this.log('****** Error raised in ' + func + ' ******');
            this.log(e.name + ' : ' + e.message);
            this.log(e.stack);
            this.log('****** End ******')
            if (debug){
                console.error('****** Error raised in ' + func + ' ******');
                console.error(e.name + ' : ' + e.message);
                console.error(e.stack);
                console.error('****** End ******')
            }
        },
        Init:function () {
            ikariam.Init();
            database.Init(ikariam.Host());
            render.Init();
            this.CheckForUpdates(false);
            GM_registerMenuCommand(this.scriptName + ' - Manual Update', function () {
                SITR.CheckForUpdates(true);
            });
        },
        //original snippet taken from http://userscripts.org/scripts/show/20145
        CheckForUpdates:function (forced) {
            if ((forced) || ((database.getGlobalData.LastUpdateCheck + 86400000 <= $.now()) && database.options.autoUpdates)) // Checks once a day (24 h * 60 m * 60 s * 1000 ms)
            {
                try {
                    GM_xmlhttpRequest({
                        method:'GET',
                        url:'http://userscripts.org/scripts/source/' + SITR.scriptId + '.meta.js?' + $.now(),
                        headers:{'Cache-Control':'no-cache'},
                        onload:function (resp) {
                            var remote_version, rt;
                            rt = resp.responseText;
                            database.getGlobalData.LastUpdateCheck = $.now();
                            remote_version = parseFloat(/@version\s*(.*?)\s*$/m.exec(rt)[1]);
                            if (SITR.version != -1) {
                                if (remote_version > SITR.version) {
                                    if (confirm('There is an update available for the Greasemonkey script "' + SITR.scriptName + '."\nWould you like to go to the install page now?')) {
                                        GM_openInTab('http://userscripts.org/scripts/show/' + SITR.scriptId);
                                    }
                                }
                                else
                                    if (forced)
                                        render.toast('No update is available for "' + SITR.scriptName + '."');
                            }
                            database.getGlobalData.latestVersion = remote_version;
                        }
                    });
                }
                catch (err) {
                    if (forced)
                        render.toast('An error occurred while checking for updates:\n' + err);
                }
            }
        },
        HardReset:function () {
            database = {};
            SITR.deleteVar("Options");
            SITR.deleteVar("cities");
            SITR.deleteVar("LocalStrings");
            SITR.deleteVar("globalData");
            render.toast('Data Reset, reloading the page in a few seconds');
            setTimeout(function () {
                document.location = document.getElementById('js_cityLink').children[0].href
            }, 3500);
        }
    };
    /***********************************************************************************************************************
     * database
     **********************************************************************************************************************/
    var database = {
        cities:{},
        options:{
            version:SITR.version,
            cityOrder : [],
            fullArmyTable:false,
            onTop:true,
            showOnIslandView:false,
            showOnWorldView:false,
            autoUpdates:true,
            wineWarningTime:24,
            largeFont:false,
            altBuildingList:false,
            openBuilding:-1,
            restoreRes:-1,
            window:{
                left:150,
                top:180,
                activeTab:0,
                visible:true
            },
            addOptions:function (objVals) {
                return $.mergeValues(this, objVals);
            }
        },
        _globalData : {},
        Init:function (host) {
            var prefix = host;
            prefix = prefix.replace('.ikariam.', '-');
            prefix = prefix.replace('.', '-');
            this.Prefix = prefix;
            this._globalData = new GlobalData();
            //this.options = new Options(); //TODO: create options class
            this.Load();
            ikariam.getLocalizationStrings()
            this.startMonitoringChanges()
            $(window).on("beforeunload", function () {
                setTimeout(function () {
                    database.Save();
                }, 0);
            });
        },
        addCity:function (id, a) {
            if (a) {
                return $.mergeValues(new City(id), a);
            }
            else return new City(id);
        },
        get getBuildingCounts (){
            var buildingCounts = {};
            $.each(this.cities,function(cityId, city){
                $.each(Constant.Buildings, function(key, value){
                    buildingCounts[value] = Math.max(buildingCounts[value]||0,city.getBuildingsFromName(value).length)
                })
            })
            return buildingCounts
        },
        startMonitoringChanges :function(){
            //events('cityChanged').sub(this.cityChange.bind(this));
            events('buildingsUpdated').sub(this.Save.bind(this));
            events('globalDataUpdated').sub(this.Save.bind(this));
            events('movementsUpdated').sub(this.Save.bind(this));
            events('resourcesUpdated').sub(this.Save.bind(this));
            //events('cityData').sub(this.Save.bind(this));
            events('militaryUpdated').sub(this.Save.bind(this));
        },
        Load:function () {
            var options = this.UnSerialize(SITR.getVar("Options", ""));
            if (typeof options === 'object') {
                if (!this.isDatabaseOutdated(options.version)) {
                    $.mergeValues(this.options, options)
                    var cities = this.UnSerialize(SITR.getVar("cities", ""));
                    if (typeof cities == 'object') {
                        for (var cityID in cities) {
                            (this.cities[cityID] = this.addCity(cities[cityID]._id, cities[cityID])).init()
                        }
                    }
                    var globalData = this.UnSerialize(SITR.getVar("globalData", ""));
                    if (typeof globalData == 'object') {
                        $.mergeValues(this._globalData, globalData);
                    }
                }
              this._globalData.init();
            }
        },
        Serialize:function (data) {
            if (data)
                try {
                    var ret = JSON.stringify(data)
                }
                catch (e) {
                    SITR.log('error saving')
                }
            return ret || undefined;
        },
        UnSerialize:function (data) {
            if (data)
                try {
                    var ret = JSON.parse(data)
                }
                catch (e) {
                    SITR.log('error loading')
                }
            return ret || undefined;
        },
        Save:function () {
            events.scheduleAction(function(){
                SITR.setVar("cities", database.Serialize(database.cities));
                SITR.setVar("Options", database.Serialize(database.options));
                SITR.setVar("globalData", database.Serialize(database._globalData));
            })
        },
        get getGlobalData(){return this._globalData},
        isDatabaseOutdated:function(version){
            return 1.200 > (version || 0);
        },
        getCityFromId : function(id){return this.cities[id] || null}
    };
    /***********************************************************************************************************************
     * render view
     **********************************************************************************************************************/
    
    /***********************************************************************************************************************
     * ikariam
     **********************************************************************************************************************/
    var ikariam = {
        _View:null,
        _Host:null,
        _Server:null,
        _ActionRequest:null,
        _Units:null,
        _BuildingsList:null,
        _AltBuildingsList:null,
        _Nationality:null,
        _GameVersion:null,
        _TemplateView:null,
        _currentCity:null,
        url : function(){
            return 'http://' + this.Host() + '/index.php'
        },
        Host:function () {
            if (this._Host == null) {
                this._Host = '';
                this._Host = document.location.host;
            }
            return this._Host;
        },
        Server:function (host) {
            if (this._Server == null) {
                if (host == undefined) {
                    host = this.Host();
                }
                this._Server = '';
                var parts = host.split(".");
                var idx = 0;
                if (parts[0] == 'www') {
                    idx++;
                }
                this._Server = parts[idx];
            }
            return this._Server;
        },
        Nationality:function (host) {
            if (this._Nationality == null) {
                if (host == undefined) {
                    host = this.Host();
                }
                this._Nationality = '';
                var parts = host.split(".");
                var idx = (parts[0] == 'www') ? 2 : 1;
                this._Nationality = parts[idx];
            }
            return this._Nationality;
        },
        getNextWineTick:function (precision) {
            precision = precision || 1; // 1 for Mins, 2 for mins:secs
            if (precision == 1) {
                return 60 - new Date().getMinutes();
            }
            else{
                var secs = 3600 - (new Date().getMinutes() * 60) - new Date().getSeconds();
                var ret = Math.floor(secs / 60) + database.getGlobalData.getLocalisedString('minute') + ' ';
                ret += secs - (Math.floor(secs / 60) * 60) + database.getGlobalData.getLocalisedString('second');
                return ret;
            }
        },
        GameVersion:function () {
            if (this._GameVersion == null) {
                this._GameVersion = $('.version a span').text().split("v ")[1];
            }
            return this._GameVersion
        },
        get CurrentCityId() {
            return unsafeWindow.ikariam.backgroundView.id === 'city' ?
                   ikariam._currentCity || unsafeWindow.ikariam.model.relatedCityData[unsafeWindow.ikariam.model.relatedCityData.selectedCity].id :
                   unsafeWindow.ikariam.model.relatedCityData[unsafeWindow.ikariam.model.relatedCityData.selectedCity].id
        },
        get viewIsCity(){return unsafeWindow.ikariam.backgroundView.id === 'city'},
        get getCurrentCity() {
            return database.cities[ikariam.CurrentCityId];
        },
        get CurrentTemplateView() {
            try {
                this._CurrentTemplateView = unsafeWindow.ikariam.templateView.id;
            }
            catch (e) {
                this._CurrentTemplateView = null
            }
            return this._CurrentTemplateView;
        },
        getLocalizationStrings :function() {
            var localStrings = unsafeWindow.LocalizationStrings;
            if (!localStrings){
                    $('script').each(function (index, script) {
                        var match = /LocalizationStrings = JSON.parse\('(.*)'\);/.exec(script.innerHTML);
                        if (match) {
                            localStrings = JSON.parse(match[1]);
                            return false;
                        }
                    });
            }
            var local = $.extend({}, localStrings);
            //merge ikariams time units
            $.extend(local, local.timeunits.short);
            //remove extra objects
            delete local['warnings'];
            delete local['timeunits'];
            $.each(local,function(name,value){database.getGlobalData.addLocalisedString(name.toLowerCase(),value)});
            local = null;
        },
        setupEventHandlers:function () {
            events('ajaxResponse').sub(function (response) {
                var view, html, data, template;
                var len = response.length;
                var oldCity = this._currentCity
                while (len) {
                    len--;
                    switch (response[len][0]) {
                        case 'updateGlobalData':
                            this._currentCity = parseInt(response[len][1][11].id);
                            var cityData = $.extend({}, response[len][1][11], response[len][1][10]);
                            events('updateBuildingData').pub(this.CurrentCityId, cityData.position);
                            events('updateCityData').pub(this.CurrentCityId, $.extend({}, cityData));
                            break;
                        case 'changeView':
                            view = response[len][1][0];
                            html = response[len][1][1];
                            break;
                        case 'updateTemplateData':
                            template = response[len][1];
                            if (unsafeWindow.ikariam.templateView){
                                if (unsafeWindow.ikariam.templateView.id == 'researchAdvisor'){
                                    view = unsafeWindow.ikariam.templateView.id
                                }
                            }
                            break;
                        case 'updateBackgroundData':
                            oldCity = this.CurrentCityId
                            this._currentCity = parseInt(response[len][1].id);
                            events('updateBuildingData').pub(response[len][1].id, response[len][1].position);
                            events('updateCityData').pub(response[len][1].id, $.extend(true, {}, unsafeWindow.dataSetForView, response[len][1]));
                            break;
                    }
                }
                this.parseViewData(view, html, template);
                this.RestoreTemplateBox();
                    if (oldCity !== this.CurrentCityId) {
                        events('cityChanged').pub(this.CurrentCityId)
                }
            }.bind(ikariam));
            //parse data on form submit and add it when submit success
            events('formSubmit').sub(function (form) {
                var formID = form.getAttribute('id');
                if (!ikariam[formID + 'Submitted'])return false;
                var formSubmission = (function formSubmit() {
                    var data = ikariam[formID + 'Submitted']();
                    return function formSubmitID(response) {
                        var len = response.length;
                        var feedback = 0;
                        while (len) {
                            len--;
                            if (response[len][0] == 'provideFeedback')
                                feedback = response[len][1][0].type;
                        }
                        if (feedback == 10) //success
                            ikariam[formID + 'Submitted'](data);
                        events('ajaxResponse').unsub(formSubmission);
                    }
                })();
                events('ajaxResponse').sub(formSubmission)
            }.bind(ikariam));
        },
        Init:function () {
            this.setupEventHandlers();
        },
        parseViewData:function (view, html, tData) {
            switch (view) {
                case 'finances':
                    this.parseFinances($('#finances .table01 tr').slice(2).children('td'));
                    break;
                case Constant.Buildings.TOWN_HALL:
                    this.parseTownHall(tData);
                    break;
                case 'militaryAdvisor':
                    this.parseMilitaryAdvisor(html, tData);
                    break;
                case 'cityMilitary':
                    this.parseCityMilitary();
                    this.parseMilitaryLocalization();
                    break;
                case 'researchAdvisor':
                    this.parseResearchAdvisor(tData);
                    break;
                case Constant.Buildings.PALACE:
                    this.parsePalace();
                    break;
                case Constant.Buildings.ACADEMY:
                    this.parseAcademy(tData);
                    break;
                case 'culturalPossessions_assign':
                    this.parseCulturalPossessions(html);
                    break;
                case Constant.Buildings.MUSEUM:
                    this.parseMuseum();
                    break;
                case Constant.Buildings.TAVERN:
                    this.parseTavern();
                    break;
                case 'transport':
                    //this.transportFormSubmitted();
                    break;
                case Constant.Buildings.TEMPLE:
                    this.parseTemple(tData);
                    break;
                case Constant.Buildings.BARRACKS:
                case Constant.Buildings.SHIPYARD:
                    this.parseBarracks(view, html, tData);
                    break;
                case 'deployment':
                    this.parseMilitaryTransport();
                    break;
            }
        },
        parsePalace:function () {
            var governmentType = $('.government_pic img').attr('src').slice(16, -8);
            var changed = (database.getGlobalData.getGovernmentType != governmentType);
            database.getGlobalData.governmentType = governmentType
            if (changed) events('globalDataUpdated').pub({type:'government'})
        },
        parseCulturalPossessions:function (html) {
            var allCulturalGoods = html.match(/iniValue\s:\s(\d*)/g);
            var changes = [];
            $.each(html.match(/goodscity_(\d*)/g), function (i) {
                var cityID = this.split('_')[1];
                var culturalGoods = parseInt(allCulturalGoods[i].split(' ').pop());
                var changed = (database.cities[cityID]._culturalGoods != culturalGoods);
                if (changed) {
                    database.cities[cityID]._culturalGoods = culturalGoods;
                    changes.push(cityID)
                }
            });
            if (changes.length) $.each(changes, function (idx, cityID) {events('cityData').pub(cityID, {culturalGoods:true})})
        },
        parseMuseum:function () {
            var regText = $('#val_culturalGoodsDeposit').parent().text().match(/(\d+)/g);
            if (regText.length == 2) {
            var changed = ikariam.getCurrentCity.updateCulturalGoods(regText[0])
            }
            if (changed) events('cityData').pub(ikariam.CurrentCityId, {culturalGoods:true})
        },
        parseTavern:function () {
        },
        resTransportObject:function () {
            return {id:null,
                wood:0,
                wine:0,
                marble:0,
                glass:0,
                sulfur:0,
                targetCityId:0,
                arrivalTime:0,
                originCityId:0,
                loadedTime:0,
                mission:''};
        },
        troopTransportObject:function () {
            return {id:null,
                troops:{},
                targetCityId:0,
                arrivalTime:0,
                originCityId:0,
                returnTime:0,
                mission:''};
        },
        parseBarracks:function (view, html, tData) {
            //Todo:add change logger
            var type = view == Constant.Buildings.BARRACKS ? 'army' :
                       view == Constant.Buildings.SHIPYARD ? 'fleet' : false;
            var city = ikariam.getCurrentCity;
            var currentUnits = {};
            var i = 14
            while (i--) {
                if (tData['js_barracksUnitUnitsAvailable' + (i - 1)]) {
                    currentUnits[tData['js_barracksUnitClass' + (i - 1)].class.split(' ').pop()] = parseInt(tData['js_barracksUnitUnitsAvailable' + (i - 1)].text)
                }
            }
            var changes = city.military.updateUnits(currentUnits)
            var elem = $('#unitConstructionList');
            if (elem.length) {
                var tasks = [];
                tasks.push({
                               units:parseUnits(elem.find('> .army_wrapper .army')),
                               completionTime:parseTime($('#buildCountDown').text()),
                               type:type
                           });
                elem.find('.constructionBlock').each(function () {
                    tasks.push({
                                   units:parseUnits($(this).find('> .army_wrapper .army')),
                                   completionTime:parseTime($(this).find('h4 > span').text()),
                                   type:type
                               })
                });
                changes = changes.concat(city.military.setTraining(tasks))
            }
            elem = null;
            if (changes.length) {
                events('militaryUpdated').pub(city.getId, $.exclusive(changes))
            }
            function parseUnits(element) {
                var units = {};
                element.each(function () {
                    units[Constant.unitIds[this.classList.toString().match(/(\d+)/g)]] = parseInt(this.nextElementSibling.textContent.match(/(\d+)/g))
                });
                return units;
            }
            function parseTime(timeText) {
                var completionTime = new Date();
                completionTime.setSeconds(completionTime.getSeconds() + (
                    timeText.match(/(\d+)s/) ? parseInt(timeText.match(/(\d+)s/)[1]) : 0));
                completionTime.setMinutes(completionTime.getMinutes() + (
                    timeText.match(/(\d+)m/) ? parseInt(timeText.match(/(\d+)m/)[1]) : 0));
                completionTime.setHours(completionTime.getHours() + (
                    timeText.match(/(\d+)h/) ? parseInt(timeText.match(/(\d+)h/)[1]) : 0));
                completionTime.setDate(completionTime.getDate() + (
                    timeText.match(/(\d+)D/) ? parseInt(timeText.match(/(\d+)D/)[1]) : 0));
                return completionTime.getTime();
            }
        },
        //TODO: Cleanup
        /**
         * First call without data will parse the transportform, seccond call will add the forms data to the database
         */
        transportFormSubmitted:function (data) {
            if (!data) {
                var journeyTime = $('#journeyTime').text();
                //var arrivalTime = $('#arrival').text();
                var wood = parseInt($('#textfield_wood').val());
                var wine = parseInt($('#textfield_wine').val());
                var marble = parseInt($('#textfield_marble').val());
                var glass = parseInt($('#textfield_glass').val());
                var sulfur = parseInt($('#textfield_sulfur').val());
                var targetID = $('input[name=destinationCityId]').val();
                var ships = $('#transporterCount').val();
                var arrTime = new Date();
                //TODO: Refactor and clean this up
                var regArrTime = $('#arrival').text().match(/(\d+)/g);
                if (regArrTime[0] < new Date().getHours()) {
                    arrTime.setHours(regArrTime[0] + 24)
                }
                else {
                    arrTime.setHours(regArrTime[0])
                }
                arrTime.setSeconds(regArrTime[2]);
                arrTime.setMinutes(regArrTime[1]);
                var arrivalTime = arrTime.getTime();
                arrTime.setSeconds(arrTime.getSeconds() - (journeyTime.match(/(\d+)s/) ? parseInt(journeyTime.match(/(\d+)s/)[1]) : 0));
                arrTime.setMinutes(arrTime.getMinutes() - (journeyTime.match(/(\d+)m/) ? parseInt(journeyTime.match(/(\d+)m/)[1]) : 0));
                arrTime.setHours(arrTime.getHours() - (journeyTime.match(/(\d+)h/) ? parseInt(journeyTime.match(/(\d+)h/)[1]) : 0));
                arrTime.setDate(arrTime.getDate() - (journeyTime.match(/(\d+)D/) ? parseInt(journeyTime.match(/(\d+)D/)[1]) : 0));
                var loadedTime = arrTime.getTime();
                //SITR.log(transport);
                return new Movement('XXX-' + arrTime.getTime(),
                                             this.CurrentCityId,
                                             targetID,
                                             arrivalTime,
                                             'transport',
                                             loadedTime,
                                             { wood:wood||0, wine:wine||0, marble:marble||0, glass:glass||0, sulfur:sulfur||0},
                                             undefined,
                                             ships)
            }
            else {
                database.getGlobalData.addFleetMovement(data);
                events('movementsUpdated').pub([data.getTargetCityId]);
                //events('resourcesUpdated').pub(data.getOriginCityId)
            };
        },
        parseMilitaryTransport:function (submit) {
            //$('ul.assignUnits li input.textfield')
            submit = submit || false;
            var that = this;
            if (submit) {
                var journeyTime = $('#journeyTime').text();
                var returnTime = $('#returnTime').text();
                var targetID = $('input:[name=destinationCityId]').val();
                var troops = {};
                var mission = '';
                $('ul.assignUnits li input.textfield').each(function () {
                    if (this.value !== 0) {
                        troops[this.getAttribute('name').split('_').pop()] = parseInt(this.value)
                    }
                    if (mission === '') {
                        mission = 'deploy' + this.getAttribute('name').match(/_(.*)_/)[1]
                    }
                });
                var arrTime = new Date();
                var transport = this.troopTransportObject();
                transport.id = 'XXX-' + arrTime.getTime();
                transport.targetCityId = targetID;
                transport.originCityId = this.CurrentCityId;
                transport.mission = mission;
                transport.troops = troops;
                arrTime.setSeconds(arrTime.getSeconds() + (journeyTime.match(/(\d+)s/) ? parseInt(journeyTime.match(/(\d+)s/)[1]) : 0));
                arrTime.setMinutes(arrTime.getMinutes() + (journeyTime.match(/(\d+)m/) ? parseInt(journeyTime.match(/(\d+)m/)[1]) : 0));
                arrTime.setHours(arrTime.getHours() + (journeyTime.match(/(\d+)h/) ? parseInt(journeyTime.match(/(\d+)h/)[1]) : 0));
                arrTime.setDate(arrTime.getDate() + (journeyTime.match(/(\d+)D/) ? parseInt(journeyTime.match(/(\d+)D/)[1]) : 0));
                transport.arrivalTime = arrTime.getTime();
                arrTime = new Date();
                arrTime.setSeconds(arrTime.getSeconds() + (returnTime.match(/(\d+)s/) ? parseInt(returnTime.match(/(\d+)s/)[1]) : 0));
                arrTime.setMinutes(arrTime.getMinutes() + (returnTime.match(/(\d+)m/) ? parseInt(returnTime.match(/(\d+)m/)[1]) : 0));
                arrTime.setHours(arrTime.getHours() + (returnTime.match(/(\d+)h/) ? parseInt(returnTime.match(/(\d+)h/)[1]) : 0));
                arrTime.setDate(arrTime.getDate() + (returnTime.match(/(\d+)D/) ? parseInt(returnTime.match(/(\d+)D/)[1]) : 0));
                transport.returnTime = arrTime.getTime();
                database.getGlobalData.addFleetMovement(transport);
                render.toast('Updated: Movement added');
            }
            else {
                return true
            }
        },
        parseFinances:function ($elem) {
            //todo: add change logger
            //database.getGlobalData.finance.lastUpdated = $.now();
            var updateTime = $.now()
            for (var i = 1; i < Object.keys(database.cities).length + 1; i++) {
                var city = database.cities[Object.keys(database.cities)[i - 1]];
                if (city != false) {
                    var changed = city.updateIncome(parseInt($elem[(i * 4) - 3].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join('')));
                    changed = city.updateExpenses(parseInt($elem[(i * 4) - 2].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join(''))) || changed;
                }
                if (changed) events('cityData').pub(city.getId, {finances:true});
                //database.getGlobalData.SigmaIncome = parseInt($elem[(Object.keys(database.cities).length * 4) + 1].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join(''));
                //database.getGlobalData.SigmaExpenses = -1 * parseInt($elem[(Object.keys(database.cities).length * 4) + 2].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join(''));
            }
            var $breakdown = $('#finances').find('tbody tr.bottomLine td:last-child');
            database.getGlobalData.finance.armyCost = parseInt($breakdown[0].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join(''));
            database.getGlobalData.finance.fleetCost = parseInt($breakdown[1].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join(''));
            database.getGlobalData.finance.armySupply = parseInt($breakdown[2].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join(''));
            database.getGlobalData.finance.fleetSupply = parseInt($breakdown[3].textContent.split(database.getGlobalData.getLocalisedString('thousandSeperator')).join(''));
            //events('dataUpdated').pub(false, 'finances')
        },
        parseResearchAdvisor:function (data) {
            var changes = [];
            var research = JSON.parse(data['new_js_params'] || data['load_js'].params).currResearchType;
            $.each(research, function (name, Data) {
                var id = parseInt(Data.aHref.match(/researchId=([0-9]+)/i)[1]);
                var level = name.match(/\((\d+)\)/);
                var explored = level? parseInt(level[1])-1: (Data.liClass === 'explored' ? 1 : 0)
                var changed = database.getGlobalData.updateResearchTopic(id, explored);
                if (changed) changes.push({type:'research_topic',subType:id});
                database.getGlobalData.addLocalisedString('research_' + id, name.split('(').shift())
            });
            //        if (Object.keys(database.getGlobalData.research.topics).length > 66) {
            //            database.getGlobalData.research.lastUpdate = $.now();
            //        }
            if (changes.length) events('globalDataUpdated').pub(changes);
            database.getGlobalData.addLocalisedString('researchpoints', $('li.points').text().split(':')[0]);
        },
        parseAcademy:function (data) {
            var city = ikariam.getCurrentCity;
            var changed = city.updateResearchers(parseInt(data.js_AcademySlider.slider.ini_value))
            if (changed)
            events('cityData').pub(city.getId, {research:changed})
        },
        parseTownHall:function (data) {
            var changes = {};
            var city = ikariam.getCurrentCity;
            var cultBon = parseInt(data.js_TownHallSatisfactionOverviewCultureBoniTreatyBonusValue.text) || 0;
            var priests = parseInt(data.js_TownHallPopulationGraphPriestCount.text) || 0;
            var researchers = parseInt(data.js_TownHallPopulationGraphScientistCount.text) || 0;
            changes['culturalGoods'] = city.updateCulturalGoods(cultBon / 50);
            changes['priests'] = city.updatePriests(priests);
            changes['research'] = city.updateResearchers(researchers);
            events('cityData').pub(ikariam.CurrentCityId, changes);
            //parseInt(data.js_TownHallSatisfactionOverviewWineBoniServeBonusValue.text)/60
        },
        parseTemple:function (data) {
            var priests = parseInt(data.js_TempleSlider.slider.ini_value) || 0;
            var changed = ikariam.getCurrentCity.updatePriests(priests);
            events('cityData').pub(ikariam.CurrentCityId, {priests:changed})
        },
        parseMilitaryAdvisor:function (html, data) {
            try {
                var ownMovementIds = [];
                var move;
                for (var key in data) {
                    var match = key.match(/^js_MilitaryMovementsEventRow(\d+)$/);
                    if (match && Utils.existsIn(data[key].class, 'own')) {
                        ownMovementIds.push(match[1])
                    }
                }
                var changes = database.getGlobalData.clearFleetMovements();
                if (ownMovementIds.length) {
                    $.each(ownMovementIds, function (idx, value) {
                        var transport = new Movement(value);
                        transport._id = parseInt(value);
                        transport._arrivalTime = parseInt(data['js_MilitaryMovementsEventRow' + value + 'ArrivalTime'].countdown.enddate * 1000);
                        transport._originCityId = parseInt(data['js_MilitaryMovementsEventRow' + value + 'OriginLink'].href.match(/cityId=(\d+)/)[1]);
                        transport._targetCityId = parseInt(data['js_MilitaryMovementsEventRow' + value + 'TargetLink'].href.match(/cityId=(\d+)/)[1]);
                        transport._mission = data['js_MilitaryMovementsEventRow' + value + 'MissionIcon'].class.split(' ')[1];
                        var status = data['js_MilitaryMovementsEventRow' + value + 'Mission'].class;
                        if (status) {
                            if (Utils.existsIn(status, 'arrow_right_green')) {
                                transport._loadedTime = 0;
                            }
                            else if (Utils.existsIn(status, 'arrow_left_green')) {
                                var t = transport._originCityId;
                                transport._originCityId = transport._targetCityId;
                                transport._targetCityId = t;
                            }
                        }
                        else{
                            transport._loadedTime = transport._arrivalTime;
                            if (database.getCityFromId(transport._originCityId) && database.getCityFromId(transport._targetCityId)) {
                                transport._arrivalTime += Utils.estimateTravelTime(database.getCityFromId(transport._originCityId).getCoordinates,
                                                                                   database.getCityFromId(transport._targetCityId).getCoordinates);
                            }
                        }
                        switch (transport._mission) {
                            case 'trade':
                            case 'transport':
                                $.each(data['js_MilitaryMovementsEventRow' + value + 'UnitDetails'].appendElement,
                                       function (index, item) {
                                           if (Utils.existsIn(item.class, 'wood')) {
                                               transport._resources.wood = parseInt(item.text);
                                           }
                                           else if (Utils.existsIn(item.class, 'wine')) {
                                               transport._resources.wine = parseInt(item.text);
                                           }
                                           else if (Utils.existsIn(item.class, 'marble')) {
                                               transport._resources.marble = parseInt(item.text);
                                           }
                                           else if (Utils.existsIn(item.class, 'glass')) {
                                               transport._resources.glass = parseInt(item.text);
                                           }
                                           else if (Utils.existsIn(item.class, 'sulfur')) {
                                               transport._resources.sulfur = parseInt(item.text);
                                           }
                                       });
                                break;
                            case 'deployarmy':
                            case 'deployfleet':
                                transport.military = {};
                                $.each(data['js_MilitaryMovementsEventRow' + value + 'UnitDetails'].appendElement,
                                       function (index, item) {
                                           $.each(Constant.Military, function findIsUnit(i, val) {
                                               if (Utils.existsIn(item.class, ' ' + val)) {
                                                   transport.military[val] = parseInt(item.text);
                                                   return false;
                                               }
                                           });
                                       });
                                break;
                            //TODO: other military movements
                            default:
                                return true
                        }
                        database.getGlobalData.addFleetMovement(transport);
                        changes.push(transport._targetCityId);
                    });
                }
                console.log(changes)
                if (changes.length) events('movementsUpdated').pub($.exclusive(changes))
            }
            catch (e) {
                SITR.error('parseMilitaryAdvisor', e);
            }
            finally {
            }
        },
        parseCityMilitary:function () {
            //TODO: add changes logger
            try {
                var $elemArmy = $('#tabUnits > .contentBox01h td');
                var $elemShips = $('#tabShips > .contentBox01h td');
                var city = ikariam.getCurrentCity;
                var cityArmy = {};
                cityArmy[Constant.Military.SLINGER] = parseInt($elemArmy[4].innerHTML);
                cityArmy[Constant.Military.SWORDSMAN] = parseInt($elemArmy[3].innerHTML);
                cityArmy[Constant.Military.HOPLITE] = parseInt($elemArmy[0].innerHTML);
                cityArmy[Constant.Military.MARKSMAN] = parseInt($elemArmy[6].innerHTML);
                cityArmy[Constant.Military.MORTAR] = parseInt($elemArmy[9].innerHTML);
                cityArmy[Constant.Military.CATAPULT] = parseInt($elemArmy[8].innerHTML);
                cityArmy[Constant.Military.RAM] = parseInt($elemArmy[7].innerHTML);
                cityArmy[Constant.Military.STEAM_GIANT] = parseInt($elemArmy[1].innerHTML);
                cityArmy[Constant.Military.BALLOON_BOMBADIER] = parseInt($elemArmy[11].innerHTML);
                cityArmy[Constant.Military.COOK] = parseInt($elemArmy[12].innerHTML);


Partager le fichier 135994.user.js sur le Web et les réseaux sociaux:


Télécharger le fichier 135994.user.js


Télécharger 135994.user.js