Spawn TrChO

KOC All In One Throne Room & Champion Hall

// ==UserScript==
// @name        Spawn TrChO
// @namespace   Spawn
// @icon			https://images2.imgbox.com/e8/e9/CU2F5936_o.jpg
// @homepage        https://greasyfork.org/en/scripts/408041-spawn-trcho
// @description     KOC All In One Throne Room & Champion Hall
// @version     4.1.4
// @delay       2000
// @priority    -10
// @include			*.rycamelot.com/*main_src.php*
// @include			*.beta.rycamelot.com/*main_src.php*
// @include			*apps.facebook.com/kingdomsofcamelot/*
// @include			*.rockyou.com/rya/*
// @include			*koc-cdn.popreach.com*
// @resource    jqcss http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css
// @resource    champion_uniques  https://koc-cdn.popreach.com/fb/e2/src/pb/resource/champion_uniques.js
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require     https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js
// @connect			*
// @connect			greasyfork.org
// @grant       unsafeWindow
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_addStyle
// @grant       GM_xmlhttpRequest
// @grant       GM_log
// @grant       GM_registerMenuCommand
// @grant       GM_getResourceText
// @grant       GM_getResourceURL
// @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=CB2MLZCP8FPE8
// @copyright       Copyright 2013-2020 KSA CodeSphere - Non-commercial use only. No modifications permitted.
// @license			 	http://creativecommons.org/licenses/by/4.0/
// ==/UserScript==
//	*********************************************************************************************************
//	*	                In Hounour Of Mark Branscombe(TCO)& Phil Cazz (MadMaxx)                             *
//	*	                That Paved The Way For Organizers Like This Thanks Guys !!!                         *
//	*	            "Parts of this script use code created by Mark Branscombe & used with his               *
//	*                 explicit permission. We thank you for your generosity Mark Branscombe"                *
//	*	                                            							                            *
//	*                                                														*
//	*********************************************************************************************************



var STrChOVersion = '4.1.4';
GM_addStyle("._10.uiLayer._4-hy._3qw {display: none;}"); 
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
};
String.prototype.startsWith = function(starter) {
    return this.substring(0,starter.length) == starter;
};
String.prototype.endsWith = function(ender) {
    return this.substring(this.length-ender.length) == ender;
};

var ResetAll = false;
var DEBUG_TRACE = false;

var JSON;if(!JSON){JSON={};}(function(){"use strict";function f(n){return n<10?'0'+n:n;}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}if(typeof rep==='function'){value=rep.call(holder,key,value);}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value});};}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}throw new SyntaxError('JSON.parse');};}}());
var JSON2 = JSON;

var uW = unsafeWindow;
var Seed = uW.seed;
var CM = uW.cm;
var ThroneTemplates = CM.FETemplates.Throne;
var ajfx = uW.g_ajaxparams;

var IMGURL = uW.stimgUrl + "img/";
var STrChORightArrow = IMGURL + "autoAttack/across_arrow.png";
var STrChODownArrow = IMGURL + "autoAttack/down_arrow.png";
var STrChOPlus = IMGURL + "throne/modal/set_buy.png";  //https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/modal/set_buy.png

var STrChOBreakBuffer = 50000;

var Cities = {};
var Tabs = {};
var mainPop;

var dlgHeight = 600;
var dlgHeightOffset = 30;
var dlgWidth = 735;
var dlgWidthOffset = 12;
var dlgWidthMenu = 75;

var http =  window.location.protocol+"\/\/";
var gameurl=http+"rycamelot1-a.akamaihd.net/fb/e2/src/";
var URL_CASTLE_BUTTON = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAXCAYAAADk3wSdAAAACXBIWXMAAAsSAAALEgHS3X78AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAA+NJREFUeNqclc9uFEcQxn9d3TuzeG3DLiaIOAcT2wdjgeESKeIQ5ZIokXmPXCLlTSLllEeBByCEIBMrlyzkAFxZC7P2zt/+Uznseo0NkZKUNFOlUvXXX898VW2++uaeLvR6ZFkHKxZjDP/VVJWYIm3rKYsC9/G1a/zw/XdYew5QlaSzkGlgZm9jeG9zVSWlyI8//Yzb2Fin9R6J6UyhqqKq8xjOAhljPlAf2dhYx93Y2iLGSErKgwcPMMagquzu7s7yifv3788Bdnd3SSmdyZ/Up6Tc2NrCbW6u09QlqrC4uIiIAZRLl5aoqgrvPRcvLiEipJTo95epqooQAktLixhjiDGxtLRE01Rsbq7jrly5wsHoNQCDwQDnLKqRXq+HCHjvWFkZYK0lxtN8CIHLlweIOEIILCwsAMryxT6uKAoWFhYQEfr9PnneIaVAnneAnCyzrKxMNwshzvJdYowMBgOsdbStJ89zVCNFUeB+3/+Du59/hjGG5eVlut0MSOzv7xFjwFphMFjGuSmj/f0nhKBY26Hf72OMpWkasmy67vGTX3EPf3nEl1/cxRjhwoUL9Hrd2bEzYmzpdIQ8z+ag3W6O94q1GVmWE6MiIlhrca7Dw18e4YbDZ3N5iAhZluGcpdvNUPVYq2SZxVohhA6dTk6MBmM6GCN4H6nrBmMM1sJw+Az34uUrYowYo6SUAHDO4ZwDHNYmrAVjmDGClASwhKB4H+cSC0F58fIV7vDwDW3rMcYQQiDGBCjGCCJ21j1p5hVjLCKGlGbtGSMhBEIIeN9yePgGZ8VSliUiQtM01HVDltnZ4oRIQlVnJxFSOvEJ7yNN09I0DW3bUlU1VixudXWVsixQhaqq6HY7OAcpOUQUa6eA01Y0pGSIceqbJlCWBVVV0TQNZVmwurqK297eYjweI2IpioIsc4hAShnWKnDynI6UlIQQlKYJFEVBURTUdc1kMmF7ewt35/YOR0dHiFjK8hQ0xhYRUD0dGO8OkBihrj2TyRS0qiqOjyfcub2D27l1k7+e/4mIZTR6TdPUlGWPTse9w/C8TcHrumUyKRiPj3n79i2j0YidWzdxa9fX+O3xIwDG4zGqibZtEJH5yHsPcqZr7wNFUXJ8PKEsCyaTY9aur+G6eT7XZwhhJi/5V6AxRrwPM51Odd7Nc9zo4ICUprLxPlDXDarM5+SHhvQJaEqJtm3x3qM6bYDRwQFuOHyOs1NWG59e56OrV+n1FqeXiCrnyZ78K2PkTL4oS1KMDIfPcXt7T/nk2mVSShgRjo6OKMvilKHqWUGdu0ZOLISIiGFv7ynm62/v/dOn+19mDPw9AD29Ua4OIbBVAAAAAElFTkSuQmCC";
var URL_CASTLE_BUTTON_SELECT = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAXCAYAAADk3wSdAAAACXBIWXMAAAsSAAALEgHS3X78AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAABABJREFUeNqklT1vHGUQx3/Py+7e3tpOYmOBOSQc2S4cK3HSIKEUiIYAUj4GiAaJGiihBlFBPkC+AqGiIYl4cUA0XEKRpEmRWDn77nb39nn2eYbiLmc7QIEYaVajnZn/zOyO/qPeeueqdIuCNE0w2qCU4r+KiBBiwDlPVZbYl9fW+OjDDzDmOUARosxMpoaaPZXib8VFhBgDX3z1NXZzcwPnPTrEE4EigojMbTgJpJT6h/jA5uYG9tz2NiEEYhQ+uXZjHvT5+2/PwT699h3PWv3svStzwI+/+fZEPETObW9jt7Y2aCYVIs/GmyZnmT3W1dGYnU5y1Omx8Y0xGGPZ2trArq6usv/k8cnxFBRFPk84vdTFak0b4/z90fgKEPI8Rylh5YVVbFmWdLtdtNYopQHIMztLno7/6toy1mjaECmKzgxIkXdSJk0LKIqiACJlWWJ//e13Lr/+2rxy3kl4cXmRL69/z0I3o9tJONtbJrEG3wau3/iFsvaMK8dLK6d4PBhRTzx5ngORH279jL156zZvvnEZpTRKwZmlguXTC6yc6rJUZCwWKd08mYOWtWdUeobjhiRJ8CEyaQ5I0xSRwM1bt7H9/t15l9YaFrsdloqc04tdzix1WFpIKXJLmmgaF+lmgTRxGG1ogzCuGqyd7rjWin7/Lvb+g4eEEFBKyBJLllryLKHIUxa6GUtFSpEbkkSTpWB0SxSF95Fx5aY5iSWEAETuP3iIHQye4pyfV9JaYY0iMYrUKhKrSBNNYhWI4OzUZ/VUzSzHOQdEBoOnWKMNVVVN/z6AxGMaUBJREtEolIDiyC8SAUEBVVUBEaMNttfrUVUlIhBCxHtP0zica3BO4xw0JhBajW+FpmlpGkfjGpxr8M4TQmQ8HgORXq+H3dnZ5vDwEK0Nznvq2lHWNaNSk1pBgmdSW6zVtG2kblpGVctoXFNWE6pJg/Oe0WiESGBnZxt76eIuw+EQrQ114xnXNYcjTaIjsXWUnZQsNRilCCI0LlBOHINRw8GwZlzV1I1jNBoSY+DSxV3s7oXz/HnvD7Q2eO85GFZoCbhJzcGhJU8NidVYrWij4NtI7QLVpOWgdByMG7xvefToESDsXjiPXT+7zk8/3gYgxsioakACk4kmSzTZDFBriBHaKLg2MvFC2QTGk5YYhcFggDGa9bPr2E6WEWOckTGEKAyrFudnK2Vma6MgytTfBmhmwGFGj1MMoZNl2Cf7+8QYp9wpM2ARyiZSOYXVoNVUp0WhjTDDmst0+TVP9vex/f49rNGICFfPLyInzskR+59gfEBpzTH6BaXRCvr9e9i9vTu8srYy/wTP3x1E5oXUjLH/7Tgao9nbu4O68u7V55v5X6IU/DUA3uQnItzRr3oAAAAASUVORK5CYII=";
var success_image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AgNBDgX+Hd0CAAACkZJREFUWMOtl3uMHdV9x7+/c2buzJ373rvvtb3exYuNDfYaMIkgkNYCFIdScB+CVm4UIWiTIKs0FVSplAqaBiUWbYXSh1CcREkr2lRKrZgoJThYLQWMIY6pjV+7fqx37fU+7t7nPO48zvn1j12btYG0fzDSkWbmjH6f3/m9h/AxXjw+DhoZAY+PL39NH/U5jYx85ObHAadfoQBfUeLjtcAYALosUyzBFxczL4EZRFfujQ8VNLsb1PMoeHb3tVv0oYdhE/BvAhQDDAJIgBYVYGYiIkK+JA6ceF0MWKVwVfcKtaQQyf8HnABIAMayZQIwwWyASIINAdEWICawKcFSAjBYJVInWoh1a2/Y33jl4ef/+e9uOHb4xKltD+wI4baAJWFXH/F9+GXwZXhqCWyAWQIgEBgsEpBOIEIF2VJgAVCOEBNTYTAj+3IPf3f+G1/6p3/44UzhTPHJnV98tI25SwKA+oACy059GZwCsw0gDSANIhuABZIGQEtCOAFTBOKIKYohg4RYKO4e7mnmW3/2l6e+8Dt7/uLlX95Tu/eJF/Z+7zguXGDWimnJm8Zysy8LGhOADWaHOcqQsIts9g6w6ByE2bGCjOwACAYnURXaryCuXxJxZZJUWIMwYwwMrflP77++/Df//c2b3/nH9974HO94Ytcru0/i9GliZk2LQbho8Wt8LpfgaWbOEUd5ZEc3atF/H6ziraTP9qE97iCuSbACkwWkVkZk3+hqlT4l3LP/EWbY+uvJ3Y98/+1/7fP2qEOfLz385Ne/9tWjcKOIQTERxwAxAH0lDZfgYgnuAJwHRCdnNm/V5urHBU+sUtMvQM2OEderoMAHtAIMA7CyEB0DMIYegp/7dPup9x5RP9y/L2O/lr30lY2P/cnjO3e8jbZosbICYjMGQV2Bj4wsxQCDmFgSk8VAhoiLiRzcAhJfRvXF3uDk9+GPTeL0RIDDFxOMuYQIAj22wK19FawfrqARuPyNeJe958dH0HPeCf/8tkde+KM/3T6FWtVkYYIow0hyGiw16EohgqFndoOJiSBMgNJEXIyVU2pWjj6WSTd64+M/wuShi/y374Z0yFYIugF7kJAyJURi4hXXwrrAxOFjh+n4wTrK1RR23f+78lPXdwlEbo6p3SJDSmaficFQhcUEWqqaBhETWMgk4VQcJ7l0Pp8be+2lB4dvHrnZO/Yyzr0zx398XFG8iZHrIHQ6EqmUgZRhwmQLuayDt+bmMLm/jlQd+IM1a/me0aIRq/rO6dNnj3f3FWogmIZhCKYAlHQxrb7rSuk2AIJmLWfnG+lm0y/H/rmhjrL5W62Jw7ww1aRdk4rkbUCulIKdk7DTApZpwDIspMnGa+dmMfGzOrgFdIQONgyVCe1ZTtmZ4vmTr25Plz77Aqswk8vYrmkFIczqYvSPjCylIYHaYSLn5pvZpuuWUZ28rTige4TU+EUtxsJaRld/CrYjIC1C2rFgWyk4lMKrv5zG+L4auAlYvsTarR3Y17iAmysOFTMBEFa2jB058VLvYFeDhDZLliOWesWyGFAartc2kiSxDSnSbb+15uhpP7WfGfb6TbjRIJRzOQz2F9BdBCbrb6MR+jjwbgWn9tXANYB94IZPlJFeyXhvrIKTF4vYPNiDsNXq8uKplUFPfsK2zJRWaRLi6nZiRLGiSqVlhlFkmwIpt97q6x7Iov/wDJ79zpsIshoJAUoA/Wvy+Pz2h3DLiINnf/I8kspiQvV2OejfYqHuBWgjwuGLC9jQ3wnfi7NNv97ZFSe2F0RmSWmZEle3HyNRilpeIJJESdMUorHg5YbXFLD11k68qAowmDBzJsB8JcD8/zTx9SPfhkwDZrRYM2VMWPepAiinEDZiKJ1guhEgijQ8P6F6HGS11jIMI8la07X9TxhSIopiUlozEalarQ3PjRDGhDiMYQ8DN95fwvobOyAjgsWAEQCsAB0C/QNZdG1OwQ1DhGGMOFIQzGi3GW5ToR0xhCAthODF5nV18xOCiP0gUk3XB6QIqy1uNioe2LBQikw0FiKEMsLqbRnctKUMERKQAEgA8oCN9xXg6jZarQhtTyH2NQYyeXhujHo9VjDthmEYkWkaioj0td1XaGaO4kS5XhhL0wgi2JOXLjSRsIFNHR1waxG8Zgg3bGPwM2msHS2CPSDxgOs25iAGFKqVNrxqjHZdId2WuK5cRr3iYqGauFZH57QhRdswRGRIyR9QgDVzqZiNAPKI2LN6uo9NnmuGrZrHd16/Dk5LoDUfoTEfoO75WHWvhcG1GZhtQtctJiqVAM25GMGCQljTGM33omxnMDvR4LmWMX395pEJaRieachIpIwPWiDtWOjrKSaWlXJdL/Juv3v08PiMnpw6MUu92Sz/9rrNaC9oNC/FWLgQoFb3Ud4iMXCTjdCIUb8Ywp+NES5olBIHf3jHJ7k24+L8WI3D3hVv3H7r6mkhhJ9x7BBgDYCXj3oCkjiftZN83vFct+3eccvgVGH0hj0HDs4kp35xhn7/rl/nZx5+EiVagYUJH3NnfXjtCM4GRmM2RO18gGge+OR1n8a/PfU0ty62cPTAJE4E6bOPPr7tpTCIXCmFl8+lYyitL09dVyafp7+yHZlcGm0/RLXuk5WS4p5fWz/z04PnCxPvXVyfNOdpw8AK3n73Q3Td0B2oVpuYn51H24tRTHVj6033Y+dnv4DPdPXiyMuv0pv7jtHxKi9s27H1mw/8xuiR6kKrkcukXcs2I9bQRMAzz+29espl/nfUxqbkkRMXHGIurBnuzi9UWqueeXbvl8Tcpfs2rusRfUNl7h8eoKGNd6J71TqwFvCac7h44iDGDr2D6Ykanxmfo/GWWrj3wdufe+KLd/88jpNKorhRLmU9IoqZmUXvYx8cs9XMtyE683TwlXfNS7N1Z6CvlO3rKRTqzaDv6V0/2VE9PbVtZdHs6u3OUqlkIZNLIYk1Aj9GoxZiZs7HdM2PgnT25P0PfuK7Tz1+92uNZlCPE9Uo5h3fNI0YgLo8eS13wfsjWeMHmJmap5/tP2r5fphZv7Y/vWao2wFzx4t7Do2+9dbYXa1KY1RFcb9g7TBDxppjlrKWLWTHhq8feOOh7Vtev/Outefr861WnGg3n7N9y05F0Kw/DP6+C5Y23HN/j3/Zc1CMnZmxchk7fcumVamucs4xDMqFYVLw/Cg/N98qzle8YhTFZqHguEODXZU1w90LpYLTJEIrUdozDcN30qlQSpEwL0b+tab/yD+dd/Z+FT/6+SExuKJDpm3TZGbbsmTasc10PmunOss52dmRg22nWEqhACRac6SZQ9OQQS6TjiApgWbFzPqjwFea0fKH5//q97DlN7+GqXef0xk7pf0wSl5/ayy6MF1tt7zA15qtXNaW/b1FvXpllyrk0yqbsVQuk45LRScRpqGhtGKlmYhY9D72oWb/lRb48Q924oHPfWtxVuW9OPDTN1EqZumNg2N08vSMUEqLVSs6sGnDKu4qZzmfc/RAbxFSCmZmEBFfBv5fcAD4X6XxV1xnuaXKAAAAAElFTkSuQmCC";
var up_img ="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAaCAYAAACkVDyJAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AgRBjoxAQevPgAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAEWUlEQVRIx+2Vb2iVZRTAf+d53/tv2929m3d3a9NN55AMFG0RKhUF9aEEoX0I0rCS0HS0UkEpMJAUSxti/sn6VH0QpI/Wl0CyIhkhzbJ/rsScOXX/t7vt/nvf5/ThbrNlxjKDgg6c5zwHnvf83nOew3ng3y7xTd9M9Vu+++dgZVu/ntxHVny7puHLDgEo3/b9tGOYm8py65nW7KAe6H/f2wZAKDjtb2VagI3tDO5dDEBsy1ePusYceTAQCx9ntDtvWDm0ff7xW5rhJGxze4P1dXdtIhx+bFVc68rdJCqvlG8/Ww0wY2fHrStp2abTRb6vr5VFgw0mXsS+tkGZnXA0UeIstSo7AETM3weWtpwCwPP956IRpymSLKUrrdqdsgyM5plf6RIJytMzdv64qfelBhK7zt08sLT5C4bfuIvSllNLAg6vxqpipEMh9RUZyihXBjxxjdX6hIuItCZ2nVvW++JcKnaf/+vA6LNtDB+8m+iGtkqsfhSbUYxUxjXrqQjg+Up/yuNCb17qywzJYgcfjib3nK/s2TKHRGvn9IHRdSdJHV5CfF1bkbUcjZeGorHbq7U/h8h4X6sqmZzSl/Lp6M7RONPVsogzM+9zINnaGendXDt9YOqtZQDkle3RkLkv0VinPeqKg045p1YZSVv6hj0uDuTkzmqHSNA0+aprq/d0SsXezumXtHjtyRWO+s11S+ulN1gkonbqAVVQxVplcMzSM+wzmvV1QaVjRHg977KoZ2MtFfsu3hhY8tRnBbvm81rx7L76hdWRnni5qur1f6SFDLHg+4XSXh7yJeKq1sUdF5Fjyf2/FPc8P4vkwUvXA4tXf8LIO/dS8uSnAdQeSlaXzs7NrVbPyB9OI51Y1KJWyXlKX8rj6rAnc2Ki0ZDUoBy97d2r0t1cQ/LQld9nqBPrnnA4sDzWOEfHgkFBb1Bz1UkYqqhV0lnL1SGf/jFfFle6qshyO2p3AHRvqKLq8JUCsPiJE4y+dz9Fq08843t2/bx75tIfLcHaPxm2EyXV394njKQtXYMeIxmPpTUuGV+bKw9fbipMbnMtXnjlx4sckQ8al8yq6byjHuspiCAKNptHszlsOo/N5NFMDm8oTa5rABNywTWI62BcB1xDKOSSLAswOxHQtBeQH4b0zKjVpr71lT8ZgKLHj5fHI+6rax+oqnnk4XpFIRwQwi6EXAgHDCF3QmXShh0IOxBxhIgz7ruCAcaylpGMlRcWFuu8EXdBIuW8/NCRgSLZf+xn4yMtCnv7UnnO5gK0pwTHCGIERFBrwSr443dmFc37+GMZTMBBnEKGGAOOQZyCLYk4LCoP037Skhs2DI7qKrezNysVsWDu9IWRSx+e7k97KmCkEMQx1/auAWOuBXcM4rpgDSCFl0IFUQEVUOgfhYvpLDrT4PXYIhzjuF39WT+Tt292dKXfTuctgYAD45lhxlVMwR9XnXi5dWrXCjKlycw424mAJMBT9flf/vPyKztX7pN6V2XmAAAAAElFTkSuQmCC";
var up_glow="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAaCAYAAACkVDyJAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AgRBwMPzyBVGAAABfBJREFUSMe1lNtvnMUZxn/PzPftrk9ZO7HBtkzWSYhjp9RxfABKoZQLKspNpV70phf9F/q3cNmL/gNVL1ArVJFW6YGqUEqECjQnh9QHkpBkE68Pa+96v3l6YWOSEipA6ivNjGakeZ553mfeVzwiXl5d5dzYGGFphVdjEWNW6rN9TPas4RjSrvAm0GOrhPxvoQuWPpbZuNCoFyuT334UNNmjDs+NjQHwaiCErNQFHgHPWLyImRCkkGs77VIBImbRGEktYGmy61Cz/s7b6ZnhEc7Xag9hh/8me2zjBgAvrC4Ts5gLHyF5CvQ0ZgZxkuDJpT+0Zo2nJCaAGcTT2KcRQ93lvPTs8IjO12rMXrv2vwlv940ytv4Jh7OYQxqwdRI0jz0DeiIrh0OLf2xWP/hFs7r8TqsacvokjcmaQZ7HPmno7y3l+fjFy1w4cYInr138IuEzly4dHM7thEx2H+io7LNJnpN0LGT03vpwJ7v9z1b48XOH+PSj3VC/3omIHqBG0qzts7LHReqdOdIbBy6+z+KJKX6wtPQ54eiVK7wzOQnAK6srQUWqGA0D08YLQqcQA1t3O3HxT1uMDVT8k5/2a6QSff3dtlqbKQJV8IRgHpjGjKTk7u9XBwXwZq3Gd68vogNZ713gpcP9qnZVysmMCM8Zv4x5XmK82KXy0W8b6txCQ0f76c0KhmKHCysdl49nOvVi2ba3gWXEW0LnbL0r+War3Wn9rlYzQHhh39TTzunrKmdJ9AufSPYc5gwwikJl9b2tsL3UUfdw1Te3ze2NxP2tXb41mmvtWsEnH3aIpVAGRmzO2J4DT2AGyqUsn75yWbz7D+Lya68x88FFxh6rxiyGvmCfsP2s4HnglIKqjdVWdun1BoO1w97u7tJuu6DdKiiaLYb6I+U8+tpiR9XhoK5DIZP3ykVBO0hrBG0ciqF9vLDj+M3LHO3pDWWpW/CEzRzoe8B0iBpsbRb5hV/W1T/YS350UJvbBSoKinZBa2OHQuLU4yWtt8TKUtLQsaBYUi5TtmXwlkwjxLi1U650wmjK1QVlwRBmCvtp8FMKGuq0XPrwV3X1lHNXp0a51wbtu26bnbapbxRcud1mbiyjO4nFvxekXXKkQeGnZBaA09hDvcHl8FisZFj9wJPAgtAZSSOYyrXzDXVu7TI0X9MdZ0T8UM06mc3tRH29w8r9NrOj0c0b6NbVJJuK9/0E5sETQH9wcp9NDZi1PWs8DvTeudTUzbcb1L5z3HdL3cjp4Q5hg01KZq2ZuLNesNUq9NTj0dffN837DpK60R42cBZUCwSGJaZtLwATkqo7jU688pu6xidHfKf/sGx/seF6TyEJimIvtTcbBV2ZVTsUuPiWKQpHSVXbJ23mbU8H7CmbBaTTko6kjvNLr99Vb97l9slRdYIe2fX92eSEk2l3TH2jw6frHY71i1JHvvq2ZJNJOgKcBhYCaF74DPZoLKty9Y162Lja8sCzx9UslcA8OuwDMmyczHYr8Wmj4F6zYHYkU/0TWPmXggIVpFHEmbDnG+NZJfYs/7kRlv+65smXTupeXy8pgfgywv2U+kE/YXM7cWOtw+ZOh+fGMi9fhburUgjuAdWCpAkFVe9/3Iwfv3lX8wtj3BgexMWXSXsgEgfq9vw0nSLR2ErcWi+QC80N5L59Jaq5oSC7GgyDu5tFfuP39/Wzs0N+9YfHhaGSi0oG5QwqeaCcfTZ0sFYiVCJ0RdEV9/eZCECzldjcSfx8ukdHl3KvvZ/JSXkmOz+2IV6ZGuL2xi7v/WWJbCOgoL0ql8CJmEws0oGSEonU30XII8oCxAgxQAxof6y1Ar++vEO9ntS6mHOv28qAnQ6Of7u1mZ2/3FBhmSARhEJAUQcgKEAUIdsHHihB2H9cDBAEQXt3gtgOcG69ZU9J7SOBvuikH91YXQaGbEr7jevhf6KHlq8Z+vxLG1u0MqNN4V5JhbHM/6i7rx0P3JIt1MokLwL3wNmePH8zMV+J3Z3M0huYbsT/i+hBypTJPidClr553r6ynQL/B2jU9jxyr6MUAAAAAElFTkSuQmCC";
var down_img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAaCAYAAACkVDyJAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AgRBwUywRK+jwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAEi0lEQVRIx+1WXWwUVRT+zrl3drfbdne73e2Wv1WQYDQxwd9UjIiJ0ScfJDEENGp8ofwIgcpviGI0Gk2AaFIEYvwBwyMPRsJTI1FDkYithRCUtkChS7vd0t1u9292Zo4P0xYLrVQTEk38kpk7dyZzvnO+79yZC/yP/zropV0dCFcb1Hohqzp6czAMBSgGMYM0A0wgViBNADNIsftc3bgG0/icePSeIrBSECawwXDyBGuAbD0z7FXRoGflYM7afiFZKFgCwBGAxB0BgBxAGBABREDj6f45dYLcVM1YGLsAWCn4MURbdTziFRvkeXR+YNa8WAV+Mw20ZQmKCcTkBnIc923bgThuIlK2YeeLYFaj1bkKQAlICaAIVRXAwrAXbSccmMOMdE5sAgD/8pZwwO85vPzx6HOxJffKvksgD4+mKYCYNpyiCadQhlM0IcUyrEwe5d7rYK8GaTV6MGAokFLw+xXitQaaHgrL7mNFumI7h+KzVeO4KL4V3y1URN8+3DBnVs/98+BYAhC5ypbKkNIYYRlSNGFlCjATQ2CvBjSDtAJrBWiG16tRV2Pg7oghBcug8xk5k3Nk6eCqWCcDQOXLx1E8/HS7KOw8dfKKObMvBVIkt205dr2jMfmZoBUjWMmoDygRUvTTQDlTEnvn4KpYZ/3+JBgAcl8vQeUrx5E/uOQzpfnT33/sQjg7AmZgSlbCqMcuKYjADFRVMGaGNKp8Gq29FnyKmvsbZxxx7XHAEyK4503FYvlo5vRF8pumTOhETOxKEI83FjGhwsuIBRXCfiVt/RYR5ChX8g4AqNvbh77G+huEuYNPoeq1HzDy1eIyiFcnE8OXPF0J0o7IFAWOVueSejShtlojFtByMSOULUkvCMuuvRqTuuZeJFfXj7swjpEvn3THz5/oEc3ruzsShWj6OhHR1JIyoBShtlphRlBJwSK6nLYtiDyffGN2LvrxFSTXzJpg+6TIHVj0jU2q+XJrt0TMvAjxJJISmAkhPyMaUKj0KjrTbzsieNOw0B7d04OB9XNu6bNbUL3yBADAILydLTnfp05fpihZYt9kKDGhqoJRG9CYU+ORXxI2CqZzRBEdSGyKy8CG+KSNfQuy+xehuvEk0vsb8sxYlh4uZTPnExT2QMYcJSL4PK6UC+o8OH3VoqGCfdVQWJtsihciu3qmXEmTIruvAYE1p5Dd29APpmczgzlIf5q8mkQAaEUIV2vcFTGke8hBMmdDAcuSm+b2Rz+6iFRT/O8RAsBw82MIrPsZw588crJsY2umL4OKUokUQYI+Qn2NFsth6k5ZEJGm1LZ7TkQ+6MLA5rn4i+U7PdRsbPeXHedQOORbGp0dRKW2EVWWtF+zaTAvX6R3Lng98n4nUtvn3/bjNC0M7V6YV4q2DGXNTiedx/qGkFxK2ZQasVuZZAcAiDi3/wFPhyy0oQ3pPQ8CAIKbf31BMx9+xgj6WpBLlhkrMu/c13JHtgc1WzrcBLac2cWLz+bD2869BQDh97qmHYP/CXH6wweavCFaG35RvwsAKJl3bhMU2nh24nzduX/3ru0PInfZcM1Vy/MAAAAASUVORK5CYII=";
var down_glow = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAaCAYAAACkVDyJAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AgRBwUJcBlXqwAABehJREFUSMe1lklvXNcRhb9z3+uBzeasgZpFkaIkRxEUO7EUOIktwPZCSOBFkI13+QX5K/kFAbLIJousjSSADASWE5OiLEbWQJkSW2JIiaRMtjh193vvnixI04jhYRGogAIuChf31KlTVbh6b3F+VIQ0CjAvzwQyTi29Y7sGCPFSzRBT2VeBQUz6VS4vC488tTUmPAwqG8svD89C7VS4DnTZLoOkrzPU/0Nbe2BYtggp0Dv8LKYvPlkP1+43KSwTJIJQCCgRJAElARQgESENEHZjIaCwc4cgCPrfeJBdBHWWgk7+qCinQDVFyU+H64x2V3w/S3VzPZAEgXbcjhANRcTREI2znPiiTSglKA2QJDugSUCJUWLqXXCxv6Kp65H2UqB0IYbUUvaoJ5b/fneZq0N1XrsyysQchPCV1O4UxFaHuJ0RWx3cysibW2Rr24RKitJk1wOUEpQk1GoJ/RXx6zNVGvdbfnEp0+CFwqlgpVRPyoffHij98Q8LOt8qmVdOqZUZJGSIWcR5JOaRmBvnkTw3nQJCAchIJmjnXEmgVgnUq4HfT2/68YmokxdzKzgLtmcc3Rw4VStOvbvPkxPzHH66sqPd91lgJ6mgL/UiTQJ93YHh3gQr8Y3VTAfGC9d6HC01g6QpwVzeKjaP/6IvHn+jX/euPfDg+gYhfMfyETsgYk/rEKDeFTjcn1Kvplyfz3X8NOw7aseoTXAjgCeNbiEtFG23Tl8dij2nK1r950PXOp1vnwcJtNuJuyy7KoGDfQmDtYSpxdxDR+DYK46OtLAXMLcC0l2JCew7tp+HVNnZ9/Z5I9tW+cGC0+hvnzCxB1pOxVBPysHelEdrppNapy/bErnt58AdYCIQeWozLWkCmLHdrPalxfivhjx3b1H7176wpG8vaYAkEUM9CYf6ErZzufEicu5nIklU2G5KeiAxKWk6KGhdogFM7eipOWBj/9maD13uo/HxQ+3rbGGFbyipCEH01wL7exO6K4lvPys0clHUBhRtb+Gdt4Gb4EZYKlo58hrwOTBhfMv2IqI1eqXP6XCJ5cmG9yun+PrWC6LeFRjqTTk2UGZqoVDtMB4+HSzREixK3AImQTPAWlgImbehbVhG3EX6BHTb0ctpRZ3zvxnyZjtT8+4Cg2WwvyQoquWdUo4fKHNjPmcrmLHXE0KJDHvF6LbFBHAHaXkjqh3mDp1haXk9ZtHbSAtB/Bs8AczEwmuVepJfeH+A1aUN/GzNlVQYSBMx2JNyYl+Jh19EL20WnHszdaVbBdFNwwMFbkhhmqD/FHm2VVpdi8nPZ2f55Ow45fd/68HersJSRzubsyoYwPRW+0plpWjl7qbq9bIzo77UHOo2SZLy2bNcx18v++B4GmPuTcOs4DrWdZn7QLOxuVV8tLFJ+o/RUQDuKOPgdjvv66quRTQbRL/xIKYHx/LR17qrzcVcW0+bOnS8n3oaGEhKTD3J3D+a6sj5lKIT2+zqJnTD1gzyaruTZ9PjZ/zlcuLwzAy89irXRk65lRedgJeBO0ITwGdGy0lZ+dhbddqliNe2/LvL/TxaKpz3Syd/XDKmI1gR3BaawP6MEFeC3f7gxAkDvPHo8x3AhfFxLt27B8AHR49FJ6El/BSYFpowvo9Z7d6XFmNvdjO/2tKf/7TmxVahkZ+UXamHAmiCZgyTwDRiMQRtfdhcMcC7jQYfjYyxN1z/Ont2r91vVGNuaR382NLNYN2w/SjmbAyfr+YHLlTiX66/4OAPSnFoJC0wm0CD4ClJNy3NmbDx6fONYvXcRcZm7/LXEycA9j5Oe3ZgfYH5nsOMzD/OBpN0VfID7F6kAezuvO0jY2/VVCHV0UtlxwxsLyA+lTWJ9ECwtt7JsrlzZ3h1dpap3T753q/KL588CaGU1ISP2b4MXMGMS4qhxHbMqNok4M+BDxXCx5jGVifb+ujpYrw0fIhru8y+E/Cd+Xn+dvQoofGEq0mRJGm5x/aI7FcNI0iZ8AbQbauMPCc0ZemhzPpU83nx5OwPv5HEfwESfwMmXNBW3wAAAABJRU5ErkJggg==";
var gbtn_img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAKOWlDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAEjHnZZ3VFTXFofPvXd6oc0wAlKG3rvAANJ7k15FYZgZYCgDDjM0sSGiAhFFRJoiSFDEgNFQJFZEsRAUVLAHJAgoMRhFVCxvRtaLrqy89/Ly++Osb+2z97n77L3PWhcAkqcvl5cGSwGQyhPwgzyc6RGRUXTsAIABHmCAKQBMVka6X7B7CBDJy82FniFyAl8EAfB6WLwCcNPQM4BOB/+fpFnpfIHomAARm7M5GSwRF4g4JUuQLrbPipgalyxmGCVmvihBEcuJOWGRDT77LLKjmNmpPLaIxTmns1PZYu4V8bZMIUfEiK+ICzO5nCwR3xKxRoowlSviN+LYVA4zAwAUSWwXcFiJIjYRMYkfEuQi4uUA4EgJX3HcVyzgZAvEl3JJS8/hcxMSBXQdli7d1NqaQffkZKVwBALDACYrmcln013SUtOZvBwAFu/8WTLi2tJFRbY0tba0NDQzMv2qUP91829K3NtFehn4uWcQrf+L7a/80hoAYMyJarPziy2uCoDOLQDI3fti0zgAgKSobx3Xv7oPTTwviQJBuo2xcVZWlhGXwzISF/QP/U+Hv6GvvmckPu6P8tBdOfFMYYqALq4bKy0lTcinZ6QzWRy64Z+H+B8H/nUeBkGceA6fwxNFhImmjMtLELWbx+YKuGk8Opf3n5r4D8P+pMW5FonS+BFQY4yA1HUqQH7tBygKESDR+8Vd/6NvvvgwIH554SqTi3P/7zf9Z8Gl4iWDm/A5ziUohM4S8jMX98TPEqABAUgCKpAHykAd6ABDYAasgC1wBG7AG/iDEBAJVgMWSASpgA+yQB7YBApBMdgJ9oBqUAcaQTNoBcdBJzgFzoNL4Bq4AW6D+2AUTIBnYBa8BgsQBGEhMkSB5CEVSBPSh8wgBmQPuUG+UBAUCcVCCRAPEkJ50GaoGCqDqqF6qBn6HjoJnYeuQIPQXWgMmoZ+h97BCEyCqbASrAUbwwzYCfaBQ+BVcAK8Bs6FC+AdcCXcAB+FO+Dz8DX4NjwKP4PnEIAQERqiihgiDMQF8UeikHiEj6xHipAKpAFpRbqRPuQmMorMIG9RGBQFRUcZomxRnqhQFAu1BrUeVYKqRh1GdaB6UTdRY6hZ1Ec0Ga2I1kfboL3QEegEdBa6EF2BbkK3oy+ib6Mn0K8xGAwNo42xwnhiIjFJmLWYEsw+TBvmHGYQM46Zw2Kx8lh9rB3WH8vECrCF2CrsUexZ7BB2AvsGR8Sp4Mxw7rgoHA+Xj6vAHcGdwQ3hJnELeCm8Jt4G749n43PwpfhGfDf+On4Cv0CQJmgT7AghhCTCJkIloZVwkfCA8JJIJKoRrYmBRC5xI7GSeIx4mThGfEuSIemRXEjRJCFpB+kQ6RzpLuklmUzWIjuSo8gC8g5yM/kC+RH5jQRFwkjCS4ItsUGiRqJDYkjiuSReUlPSSXK1ZK5kheQJyeuSM1J4KS0pFymm1HqpGqmTUiNSc9IUaVNpf+lU6RLpI9JXpKdksDJaMm4ybJkCmYMyF2TGKQhFneJCYVE2UxopFykTVAxVm+pFTaIWU7+jDlBnZWVkl8mGyWbL1sielh2lITQtmhcthVZKO04bpr1borTEaQlnyfYlrUuGlszLLZVzlOPIFcm1yd2WeydPl3eTT5bfJd8p/1ABpaCnEKiQpbBf4aLCzFLqUtulrKVFS48vvacIK+opBimuVTyo2K84p6Ss5KGUrlSldEFpRpmm7KicpFyufEZ5WoWiYq/CVSlXOavylC5Ld6Kn0CvpvfRZVUVVT1Whar3qgOqCmrZaqFq+WpvaQ3WCOkM9Xr1cvUd9VkNFw08jT6NF454mXpOhmai5V7NPc15LWytca6tWp9aUtpy2l3audov2Ax2yjoPOGp0GnVu6GF2GbrLuPt0berCehV6iXo3edX1Y31Kfq79Pf9AAbWBtwDNoMBgxJBk6GWYathiOGdGMfI3yjTqNnhtrGEcZ7zLuM/5oYmGSYtJoct9UxtTbNN+02/R3Mz0zllmN2S1zsrm7+QbzLvMXy/SXcZbtX3bHgmLhZ7HVosfig6WVJd+y1XLaSsMq1qrWaoRBZQQwShiXrdHWztYbrE9Zv7WxtBHYHLf5zdbQNtn2iO3Ucu3lnOWNy8ft1OyYdvV2o/Z0+1j7A/ajDqoOTIcGh8eO6o5sxybHSSddpySno07PnU2c+c7tzvMuNi7rXM65Iq4erkWuA24ybqFu1W6P3NXcE9xb3Gc9LDzWepzzRHv6eO7yHPFS8mJ5NXvNelt5r/Pu9SH5BPtU+zz21fPl+3b7wX7efrv9HqzQXMFb0ekP/L38d/s/DNAOWBPwYyAmMCCwJvBJkGlQXlBfMCU4JvhI8OsQ55DSkPuhOqHC0J4wybDosOaw+XDX8LLw0QjjiHUR1yIVIrmRXVHYqLCopqi5lW4r96yciLaILoweXqW9KnvVldUKq1NWn46RjGHGnIhFx4bHHol9z/RnNjDn4rziauNmWS6svaxnbEd2OXuaY8cp40zG28WXxU8l2CXsTphOdEisSJzhunCruS+SPJPqkuaT/ZMPJX9KCU9pS8Wlxqae5Mnwknm9acpp2WmD6frphemja2zW7Fkzy/fhN2VAGasyugRU0c9Uv1BHuEU4lmmfWZP5Jiss60S2dDYvuz9HL2d7zmSue+63a1FrWWt78lTzNuWNrXNaV78eWh+3vmeD+oaCDRMbPTYe3kTYlLzpp3yT/LL8V5vDN3cXKBVsLBjf4rGlpVCikF84stV2a9021DbutoHt5turtn8sYhddLTYprih+X8IqufqN6TeV33zaEb9joNSydP9OzE7ezuFdDrsOl0mX5ZaN7/bb3VFOLy8qf7UnZs+VimUVdXsJe4V7Ryt9K7uqNKp2Vr2vTqy+XeNc01arWLu9dn4fe9/Qfsf9rXVKdcV17w5wD9yp96jvaNBqqDiIOZh58EljWGPft4xvm5sUmoqbPhziHRo9HHS4t9mqufmI4pHSFrhF2DJ9NProje9cv+tqNWytb6O1FR8Dx4THnn4f+/3wcZ/jPScYJ1p/0Pyhtp3SXtQBdeR0zHYmdo52RXYNnvQ+2dNt293+o9GPh06pnqo5LXu69AzhTMGZT2dzz86dSz83cz7h/HhPTM/9CxEXbvUG9g5c9Ll4+ZL7pQt9Tn1nL9tdPnXF5srJq4yrndcsr3X0W/S3/2TxU/uA5UDHdavrXTesb3QPLh88M+QwdP6m681Lt7xuXbu94vbgcOjwnZHokdE77DtTd1PuvriXeW/h/sYH6AdFD6UeVjxSfNTws+7PbaOWo6fHXMf6Hwc/vj/OGn/2S8Yv7ycKnpCfVEyqTDZPmU2dmnafvvF05dOJZ+nPFmYKf5X+tfa5zvMffnP8rX82YnbiBf/Fp99LXsq/PPRq2aueuYC5R69TXy/MF72Rf3P4LeNt37vwd5MLWe+x7ys/6H7o/ujz8cGn1E+f/gUDmPP8usTo0wAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wIEQMpM4gtTWsAAAd9SURBVFjDnZddbBzVFcd/987Mzn7Mrje7trNxHD5CI0ETRMqOqVpDBRJp+xIeKKKoERIIISRK6AO8IpEHVImHClEJtUE8IKoS9QGRlgKlrRSRFBppEAKcREhAPhw7NsHr9X7N7Hzs7cPO1JMlhrQr/XV1Z+45//85e+aeewVX+HMcRwNuNU3zzkwmU9c0bbsQoiqE0JRS7SiKzgdB8Innee8qpd6ybXv1SvyKKyAuG4axv1AoPJLP57cahoEQG5tFUUSv1/Nd132t1+s9a9v2h/+XAMdxhKZpDxeLxV8Xi8WKlBKlIAwDTp8+zfz8PGtrLQAsq0CtVuPaa6/FsiyEECilcF1XtVqtV/r9/hO2bX91xQIcxxkzTfOVcrm8N5PJMBgMOHnyFIfffJ13PniHZX+ZMBtSKBaQUuJ5HnhQlVVmb5hl7x17mZmZwTRNBoMBrVbrQqfTubderx/7VgGO49Sy2ezfy+XyLikl58+f57cv/pY3TryBMZXhezt3s3VqK0bOwI1cBgwwpYmMJM1Gk7lP51g6s8Ts1CyP/vxRbrrpJoQQdLvdfqvV+kW9Xn9tQwFx5MfGxsq7hIAjR47w9ItPs1xaZvsN1zGwIs54Z+iIDmQAPTYcAAHogc7WzDTjjHPh9CLyouTxnzzOz+66B9PM0O32gk6nfVe9Xn/7awIcxxG6rh8eGxvbK4Tg8F8Oc+DVA3hTHuYWk1VzFUpAAcgBxtcF0Ad6QBty3RxmK0u0GPLY7GM8eN+DmKZJp9NZc123btv256RcIIR4OJfL7VVKceTIEQ68eoDVyVUYh95YDzYxFJAHsrEALQ4hEeDHAgrgrrm4wkX6kuf/9Twlq8Q9e+8hm82O+b7/suM4P7Jte6Aln5qu6382zWxufn6eJ3/zJIvVRdgCTAITQJWhiLFYSDHORj7OSBYwY2GJOAlKKIIw4MSnJ7h5y81MTm5GSnFVEASfHzx48GMJoJTabxhGJQh8fv/y7/gi+wWMs45KjE0xyt+ASgrV2H4ClowlXvrbSzSbTaSUCCGechxHao7jaEKIP+i6Xjp58iTP/fU53JoLtZHI01HnUlFnUvWgr0eOTNVHBIRwbv4cM1tm2LJ5CqVUVSn1bwncqpTaGgQBb//zbZpWcz3NCakVI0l5PpX63MizfGp9MeWnBL7l8+YHb9LrdeNNLbxXj6LoToBer8fRk0dR42pjsmwq6iTSpAj11Jw4ah9wY1+xKOe8Q7PZpFKpoJTaI8MwrEdRxNmzZ7kYXlwnShOaMWkmlXIjlfpkTL/PpOyz69k61znHSnOFIAgYDAbTMoqi7UEQsLCwgKu7lycxRqo7/T8n0FJI14RxqSiVUcxfnMf3fYIgQA/DsNrv+7TbbUI9XDccLajLkab30dF12gj09XHNXcPzPJRS6FEUaZ7nEkURCvX1TiFGiMQGLU2l3onLIGU7UANc10VKiYwPE2QyGXSlDwtqI6jUmICRubqMXXTpPG/mhwErhQTOh2FIsVikQGG4paYRjiDtUI2QJGuiy9gF69v1ZGmSMAwRQiB1Xf8kDEPK5TIVWQGPIfrxZ5Qg5eASx1GKMBHsp5pTP+XPg03GJiqFCmEYomlaV1qW9a5SCk3TuHHqRujEDSUNL4VRUaPzZJ0bI/HRHeKWq26h3+8TRRG6rr8npZRv5fN5PwxDdn9nN2P+GLSGLZU2Q0Gd2EHaaUKSHnsjhJ0UWkPccf0d+L7PYDCgVCq9Lm3bXrUs67UwDJmcnGSmOgNNhlhLIS2omxq7I/NOvC4mZI3/+qtP1KkVa4RhiGVZvUwmc0gCVKvVZ3O5nBoMBtx+4+1MB9PwFbACNIDVGImw1gZI3ifrGzFWwFwzuf8H99PtdomiiGq1etC27YYEsG37w1qt9koURRSLRe7edTdW04IvgYsMxSSCVlLCLofkfWKzPMQjP3wEPdQJw5BqtdoolUrPkGqaVCqVJzZv3nwhiiKu3nI1+767j8JKAW1Zg6V1R3zJurAEybPlFJZALknEBcEDux/g+ur1+L6PaZpMT0/vT47pl+xrx48fv3Vubu4fKysrplKKC40LHDpxiFahhTFh0M60GRQG33wm7ELOy5HpZAiWAx76/kPsKO/A8zwMw2DXrl0v7Nmz55cbbqzHjh27e25u7lCj0TAAwijk6OmjHL94nMnpSaxxi67o0lEdfOUzQGEInbzIU5QlonbE8vwS1+Su4T77PpSrCMMwIf/TxMTEPtu2w2+8mLz//vs/PXXq1KGFhYWx+MBKKEI+WvyIj7/8GF8PGB8fp1goIqXA9Twaqyu4bZedm3cyu32Wklai3W4DUCgU2Llz5wvVavVXafJvu5pdd+bMmZc/++yzWc/zhg1PSnK5HEIXNNwGvaAHArJGlkq+gmVYrK2t0e/3k5M227Zta+zYsWP/bbfd9sf/+XLqOI70PG/f2bNnn1pYWNjR6/Wu6CataRq1Wq23bdu2g+Pj489sdC+8ottxIkQp9ePFxcV7m83mnl6vN93tdvF9f9jTdZ1cLodlWd1CofDe1NTU67lc7pBt241v8/0fLROqDglVp4YAAAAASUVORK5CYII=";
var remove_img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABo6AAAaOgG4MgkwAAAAB3RJTUUH3AgSBikNXTI9xQAABK5JREFUaN7t2F2IXHcZx/HPMzM7m81usktC1JJELSSNWEEvOilSbNGLBuldfaFe9KZUrBdKLwIKCiJK9UpBqGClvQoFi60v6I2geOGF3dHYqqmGtKWGqmvK7izZNd3dmTmPF+fM7pZEyE52t6XMDw7nzGH+L9/ze57/GyONNNJII4000khvX7WHKDO7je3HdsLMlhU2kzuT+4I7cDMauJScxc9qPI1Oi3xLgLTRwlmix7HkU8GXY8y+xiRjB6hNlY0UK3QX6C2Xz8mTwWNBu8WVWZx8M0AGDbcZTx4oeLgx7pbpD7H/I3LiVpqHRH0vkfT/S/c1ufoSy7Ni8SyvL1gKztT4bosLNwITNwIxy2TwaMF9kzcZP/IFOdmisU+ooSv1hD76UiH0KJblystcekbMtWWD55OHTvLssDBxA2E1jh8U3D99WBz/HrWZsqNZyOgJBXpUILJPbNwzCzH/tLzwK8Z4AZ9ulffdAaly4vPJd6bfqXnihyIDqzL6pQPZIwYgxdUw68B7xMJP5Yu/FXiqxudaLA7y73rVGCa5exwveHhqxvjxr8pcwirRF4OOvgFikyvxRqDIvjxwmzj8H/75N59InsGPdtyRWSRfqdd889j9cvqkyF7pRG7qqGKTE90NkM3X5v+vdeSLvxbLS87X+ECrxN8ZRyryJr40fZTJI1gkeiJ75eikVpJaxEoF06xa6mOtcqhXxqeiBBqriYOH5ZXzTkin8MsdBUnujJp9+98jG12RndKN6Fedfx4vlaG2Pt1F1dIkprCngovKlRVcZmqxnE1XOL0bIJ8ZazCxH0tEV+Qq8fc6f66zltSvLqSLDhY2vUNkd/CYE0STXOWurfZrmNC6Y2ycZgqL0oqIPzX4+EN8+166a9dXUb3OxYucPi06HYiojMohcncYR95bq1FfQV/4IzrB+27hYx/dWmXnztFsrhsUZKMC2g1HGlEQS/gXXsPYpljZiorimqPoroDgUtF1U//f1OcGHxKXLzM3x9oWQmt+/iqYPjlMaA0zj/xivOaeYw25d60ccSOCo0c5dOhaX/n/tBwl9Pnzsttd78wFskPcvsW+DZMjP+8W7llZY2/VeGaKixfL5B1euUKsloj/2Grh2hAFflxguVyFZG7P7ixjUlyZkqvl70d3HASd5MnBxB1Vlg+z1ctBPL1b9G6TnaYo6AWP7yhItWjM4LHXWbpUrkoiy3dbgknV7PdhGXez1KezQPJIi4X2ToK0NkaIdnBmjpwvIdZhrted2Et+UsbdoluTr/xOFDwXPLGrW902x/FUlw+ewIGqrkHOXCt31gFvlh4Q8S66L8tz3xKrLNT5bKtcxu+OZjfut7f567Pkq+UaqagGgCwoqnt57ZHFMVk8qMifyO4ZxcKDirM1+Xvm23zxTTlF2XT48P6Cr+HeKRoHySlMTIraQRyWjgi3lgdDK3Wu/EF2fiM6f6FIz9X4xsCJre4Mt+U4aBPMTHIq+XqNE000J2RzhsY7hJlyxu4tsfqqWO1QdPWSR4InTlbzxrAQ235A1y4n2FMFp4O7sloADnKmypFXgu8Hj7c2FvVvnePS2SEdbRtppJFGGmmkkUZ62+p/v5QIkkqA6+0AAAAASUVORK5CYII=";
var remove_glow = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABo6AAAaOgG4MgkwAAAAB3RJTUUH3AgSBioED8PWogAAElBJREFUaN6lmsuvbdl51X/jm3Ot/Tjn3Lq3Xn5QcdmSBZGCQhqmQSMOAYSUEBEgFo8GIpFA4g9IxxItKxLQoUGDSETQiwwNpPQSaKTc4KFYMgiwQ6TEclSSTbmqbt1b995zzt5rzfkNGnOdW9d5SBQsaWvvs7R19hzze40x5lJ+E/EdxIz0Orp56X6026P2Tx0Tq57slpKqZUKlqpdMaqcUp0tV1qgK96juFOHIcCkZshwWkgVAJiCQSCVGaULNqLsprdbC9KB2UO9k044ueve59ay1S3M6lJpufeRJCpJP4adXuPIdpBm1V6TrfhHl0TEuIhX1FOfeSyhqgRKpapca9AquiaqtSqeQTLaL5QIKSwUjmbCMAAKEHCgTDCS4Y5pEN2pI3Xi13WwXVrqDlqW0rtBFWfu0r2I6dK4z3EN+55RXLFmZUX9Fuq5X8fR8GfW8hmqPOlOWUC1LTMIF9aqISdJUUU0zpTVlj0lklVwtFaEiXIxlCBkZQFiywSaUhh6mA82ihWiG1bja2UxZyb6GUZQaciizR1vXlkvA9WWW/T5jvQ7eeezK6+hZv4in58uYjmvUeYmWtZp5Kmol1j710JTSVGjTpDKlNRvPCs+ZnpCr0SRUZRfbYbmgEEhOhHFiC6dEl5U2DdxsGvIisUIsklYHxURpSSFZa+9qc6yLTe+rMumXJygXF2nXqLx0P/ToGPU8QFT3GqJGuIpeA812zAm7bs1ePQvvJGYFU8hzOmZBFZ6MCxFFOGxHGkWMkKRxoixWN25CTVLLkmv2WEFLhM/qZTGuFmdQ2BHdqdK6SpeSSXGxEhU/66J9WKnL9VFHpUrt0XKqIabqqJFMBHOGdqR21Z6N9sg78A6xs7WTPGHmRHOIiijY1RA4YiQVDCgYOxNaSJ0tnUCL0Cq8YCaTZ1uTrSIoUpYklYkEzAER1evSfTqd0HqksjpKnKLOFFOniKjumrJrJ8dYPOxC3hvvLfbgPWhntJc9I3bCE9IkUZyuoAKEAI96N8KCBBrQDc14CWsBLzKL8WQxgc4yBVxMRoSVKkJQZMoarCvsbIiz67xfdc5ellW10Esoa4c5Hbvo2iH2KhyM9rYPlg6CPfYes0caINAOPAHVqCJCWEKyLYSRLZSgjt0QTdJie5V8RjqBJplJuCgUNsqUooiQEHKS7j2ZavV+7nk6r1GfrMtosZ6m6DFJOYfYtdCum/1U4wAc0hxNOQoOgh3iCOwT70PMhhkPICgKcsEEstDAYZOItN1BTdBsr7YX4CSYkCbbI0WhICJi1Jmx0p1myKg40otXryWp6VpKUkSWHkw4ZmAu4R3oAD7YPmIuBEeZg+EAHA172XujGTEbTSQ1lMVWjEL1KA2wRnAS3C2nzSJYJS3ANKLhCbYaSwshSTif11naJCXTPZKcskbPOqESVkW9ptpkYlfMLmBvsbc5Go62LySOiCPmaOsA7EF7wwyaxmI8easPjIxDwChTpfBYiNwQM7CKWEZauppRF5h4zgWQbTtEStERiZ0FdSI61aVW9WKXimIK9SmzzxZ7E3tbhwgdsC8QR6MLjUgckQ+2Dkiz8Iw9b7taNFE0I02IKBKj4t3lPGMWEpPgFVgsKqaCK1CMijSanMC2LcmMiZSyUqnu0puKe7d6zWTQDmmKjNn2DN5Z3ps8JDHqQhyFjxCXkvc2hwgOozaYjSc6k1fmZ28t9x7/+/OD299ux/auZzoq92i7z5fT1RfnD1/6qd2j6UGcCVXjGjAZJo26kFAgY2MGRXDKKamTak530Vvi3nt0HKkn//WVHyp4X6x9oiP4AvnC9hXiUnBh6wp0Zbb0MkfQwXgX8s6d3enbefn418+vfPDV0+teiHoJ82sQVyAgb2F9H9bHo+/e+/H6+OUv7d47/tj0tLwUJzpn8Bk4GW4F18ANcC301OaZ5WfAU5lnFtckN4luKdxU42KrGibbswozsMfajfaaR9DR5oA42D4IDpiDKnO/9uHhV8+fePhvzq/nB7m7/wW490V8+BE0vwblCDL0a1jfg/O34dnX4dFvtftv/5d276W/ND969RcO7xx/tD7Oa4cHbrzNHUQnWUGN9IpYHFptrSGvdaRnqWEXm9rMBJ5lZm3DDvuumMcQNAdCB5udqub+uF989yvXn3361vrg+Dp645fg4s/ieoUIYL0bfVAOML8BF5+E+38GXv2L+N1/R3z/N5ZXTv+rHT/15Yu3r35ifthv7uqCFINUItZBaVgMy9btJoWr7CJHraZW5ApMgaewZ9uT8Cxply8AGoXNjNjltQ/f/cr1Z5+8tT546dPo8/8cl/uIhvwI1Hhhho+XO2h7HV9Fb/4DfPky+r3/kPvv/dKzN3/o6qof/vT0iO4ZaNhN1oq0olwczKQm2bPkmdSUVkWqNXAlXSUqyopi0miLO6Mp8DYjmMEzZibZPfzq7SeevrU+eOl19Kd+GawNwLZQN9AdkBxA9AKY7b5e/WmIBf3u17z//r+4+fQbX7k6l/uRiFlSA0YDsub4aF0noaLIYlNt1xqRMQieq9A0SBvbTGBneQbNg6Z7tjydvp2XD//t+fXjFfr8P8J+yuCpL+76iyBeiIr+QHTc4eUv4DfeQd/9T+2lJ795fvnBX98vSH0kp2ebGWkmGS1eTCnmUExh14SotiNFBdVNT0zGk7SB+UFgEzB9+OvnV/K93L3x96AE8vt/YLf7BmCLBOtHQF4E9ML39doP4w/fRu/9q9tP3v+Z3cOY1cZwpUqabCZro0CogouggCJEqdldLG0EzUW4SBRJZQwoVVJ17ISKF+YPvnp6/f5n4OINzGOktqWSh6TFwGPgtIGZx8/TgWWLUPuojtxhCvTKZ+Dt3/HuydfWB/f/yv7kRsVMtmsExXa1VSRX2SFULEqCalHIRAQuDocdRXZ1+o7FlhDFUFQpz7623PNC3PssrusP1gWPgf8OfBs4b4A2gkQFLoDLQWyYN4HSQSfgCVw+Hrff/9XT6w9+bv+un3kjjmNThzZxRSqZGqMDR6KoKEK2bMt4KLthFRREIBejsInYKT78jeVBDTjcQzwFrWOM6XcK/I8yGmThBy9v6fUI+OCFe4C8Psd7AHbAk2+2Y0xW4rEOO4yLrEDEUMxRwGENhlwta8hSAoUGN4sNjEMoMCNsFd18a72YDzC/kD76bxV+6h/CP/kbsC78X12lwNtvwy/+Inr06Hng5gFRw4VRGLb1SVviBiiGRhsMTEZV/mhzsCShTdFJljQSQNZQCO1dT/sjlNOW898AHgl++E/CX/hJPtb1rW/BPD8P0JaBGnKSeC4sdbccS8OLGfQeCRsYE10y2mpUdzuzLZ8cqIfwtqAz/n4KfA94b+tlzxPkY1yZf+RtvZiT8h0H3u4bNLgxucVIVi3GElbgnowYDPfJm4zYNmbYU+UerZ+Y+v+G8s4Lv/7kCbzzDiwfI7UePvxDYPpH0fGdjvFYiT0+INka/ti4YbmO3Ln7ku0h57z9v5TJ0VhtN3n3+Xrq32hT+z7MbfvR1uBXfgV+7df+2F3+w9uuAfrx4x+IZQNve25kj6zesJi0xkLDsu/yyqIOySmnSQ35OTxVkUhpO7ESlLnaVz8+f/juN9rVaYHjlga20dtvj+L9/7hOo2urvqrFqfT2u8N5cWp87tgJSpKt35Kx2Wbbl9QDukJNoSbcEV2igdNn8qWf3j3qwLMtRf0DOf3/fukCbi7xCXjw13Yf9JMNGotzpp4THXUp0qJbpKRepAz7TkK6S0qhJtMxHauRammn5Yad0wPO935ievxo7KD1g2PhY12+q+zPQPsCfjQhB371b+3f89mdQd03DqAOTkzadJwZUg+i23YkdEItcMduCT2tZqsZNYmGWJBW0EqJ9eWf2723HMh374rnLsU+JgjN4D8H+svwtMMHj+Dlv717t7yiM6bbNNsN7t61IK/glklP3K00kIGiY3VQs92MV8vNsCAW41ViFRpGgVmPPzY9fenPz4++Dzz8qO/zcaKjI/hLA8QS+Pf/I5o/G6eXv7R/aLN6RGIFrZIXxCoxIiSvZjA8kw05Q12d3IAMGtckFolF9urhxy4yC/IS8lruxenVn9+/c3hTt78H/uDO130BkP+YKBjw58BfBv0kLGf82/8S9Uv1135+/87uzXgWikVoCbxKXiytIyu8WFpwrBFeAzUoDUcLq7ckm8kV5SJpwVpIL+CzdNdMfMZDZtJ9Pv7o9PhTX758+/CGzr8LfBe0/BHrf774PfB54O+D/hn0z+FHv4W/9Y9Ru1R/7e/u37n/V/fvjyxg9WBtZ8wZc3JyTmvBXiSvltaGuqxepFbD7qHoNi1FC2kRXowXpNPQJZqwK7hKFIzymrj3xflh+adX/fu/fPPp7/7n9tKHiV7ZCO7hAvQK6E8AbwA/AnwOTgVuvoYf/Sb64H/C/GacPvEL+3fu/+z+PWBxakGcBGdvHVn22ehsc5a8AOMsRSzgJtN18/VX3wx5n/Khw0WRLwQXia6QroBL2VfeSLjko80Rc0Daq6q29/P45K3zy+/969tPrt/zbgZ2B5jv4/o64v7mIjzF57fR6X2w8Mt/Z/fuy1/aP9x9Jp4RnLEWrJPlW8GNhyX0TPiZracWT4WfCT8FXQPXCt0GvtHt1197I8mdox9UdPDqC6SjIi7BVzaXwpfgS6OLULlI8oB9kLTXnedrz149PXlrffD+r96+fvvNfnxulL6QYtNrWu7/7O6DV//m/r3yapxtr+FYLFaLE/ZpKBRfG18LPQvpmTOvLT11+Jms6950HeKmhG8UOtVONtmlUNYQdRHnTQadY7jhZWj6564+MrlRmfRoDjtLPSa1+z+zOz340u7dqNtBwqB1gzJJpjnzbPu8zapxhrgYFpnTMOh8q2HM3Qhu3Dm5cCt8G8kJ+czEucDSe7a20Kt2dFa6s6/NMXRwqERsQgYK6buNxba582KhC6+2OmKY0GdVLy6poWHSEGiwWKVt5TgjcTNumFXBSnI2nCVuQ77FurF1jbhR8Xi3TzJnm3ONXJrKmoqm6K2K3jNogJwUycMNR2U7oAk0XPE7Q3kzArukhrWzaYLJwxSYgIIpRpL8XB7gwZsMg3JYDVhtlk0cn4FboduEG8QN6MbiVnAr6zQagZdMVhdWKVoRvfrcei+lTaVGpNZGD5lwR7YVMc4n7qz9zSLv29BatQ0syZPN7OHGlOenAJJSg3VvH9N2erMgJC3GK+Ik6ww62dxmcorCteXbTG6q4tZwq+CMfFpbrjVypatFV69Za09CGVKUVN6GqqRSoEcnBM4RihBJ0JxsA9QN5Rmzw5qQZ0QRrgy9HXeaTM/tdXJMaN+dIa4Si/N5ez0RvpU4WboVvpV8a5dbo3PPPIPXKXzONdpUepuuslVpyotoPdWjqawlumyx3m0gUm5CTaG0lCa77VWwOjUrPM44thMnQ8EKyyOe+XxSvuB2KTcDbhVaLC3jOJqTrfNWD7cQJ/DtqJ88kzo3xxKRPV27a+8KenXMOR1Sbe1tcacgOYBiiXCOZEqJ9J3ZOZys1dZiNj/YnoxqiGKzHYZup1b6SPXdWXS+O+gRzdaypeeSOaa5xEkeB6SKOLf0mcyzHMtescq5Bn2tqbbe7lxVqpl2PZfTeKKASXMdSjTXcHNAZFqZlnpYDbkjrbYWmdlWFUzbYxxVUIbkIWxE2RSfseyUlEn2QQC1Aqs0aEngszOWqF5sn0UuKE7Q12Yve+W6U670tiI3ec7rLFmPsSTXu+A6M5MeFysR1WUNeu9kAOGh0JLuVHPQDPM4Rs4ZqdpMpAqpsjlb4/hMiITQXcvenkNBOTQPzeSa0iqxRow0y2ApeM30srZcp+AcUbp8B2Lq1Joc9ul6yoreT/f7lMMFl7cQFa/n7nWFqVZ7TVvKUmp3GXqFVAtYBRVpSruiqBEU2SVHRAKQ4iNTBuwckclA3XK33CKiOdUNS+IVaw3n2hSrC2uNXL1G6+49yFWqzXcg4sbHmw+zfmddOT577E9cnbNcJDftwO1JzO7sJ+eiMKFkyi6y9x5d0AKvhiKP2SFcxtkf46Ga5xHZytzDUMpxhJOWurWd7qJWGM+npGhNrNGiOdQkN/fSeultqu6Z0a495cUGwqfHOb3XXc8Nc7XCtNqGx/0SsWPWrU/qscZEnTOpWXrTEP7Fq9WLrOosNQalCZtiUA5AsblPjMfM7hCRFiY2g8NKcsyUgG65Ee69lR60FnJXj66rbHPU/ux29pOM7PWUx5sPsz7s9gn/H47+ChCYwenhAAAAAElFTkSuQmCC";

var STrChOTokenText = {    20060: 'LII', 20059: 'LI',20058: 'L', 20057: 'XLIX', 20056: 'XLVIII',  20055: 'XLVII', 20054: 'XLVI',20053: 'XLV', 20052: 'XLIV',20051: 'XLIII',
                           20050: 'XLII',20049: 'XLI', 20048: 'XL', 20047: 'XXXIX', 20046: 'XXXVIII', 20045: 'XXXVII',20044: 'XXXVI', 20043: 'XXXV', 20042: 'XXXIV',20041: 'XXXIII',
                           20040: 'XXXII', 20039: 'XXXI', 20038: 'XXX',20037: 'XXIX', 20036: 'XXVIII', 20035: 'XXVII', 20034: 'XXVI',20033: 'XXV',20032: 'XXIV', 20031: 'XXIII',
                           20030: 'XXII',20029: 'XXI',20028: 'XX',20027: 'XIX',20026: 'XVIII',20025: 'XVII',20024: 'XVI',20023: 'XV',20021: 'XIV',20020: 'XIII', 20018: 'XII',20017: 'XI',
                           20016: 'X',20015: 'IX',20014: 'VII',20013: 'V',  20012: 'III'
}

var logValues = { SUCCESS: 0, ACTION: 1, SALVAGE: 2, MAXLOGS: 3 };

var STrChOFactions = ['briton', 'fey', 'druid'];

var STrChOJewelQualities = ['cracked', 'flawed', 'cloudy', 'subdued', 'bright'];

var throneCardTypes = ['chair', 'advisor', 'window', 'banner', 'table', 'trophy', 'candelabrum', 'hero', 'statue', 'pet', 'tapestry', 'pillar'];

var throneCardQualities = ['simple', 'common', 'uncommon', 'rare', 'epic', 'wondrous', 'miraculous'];
var champCardQualities = ['simple', 'common', 'uncommon', 'rare', 'epic', 'wondrous', 'unique'];

var champItemTypes = {'weapon': 1, 'chest': 2, 'helm':3, 'boots':4, 'shield': 5, 'ring': 6, 'pendant': 8, 'cloak': 9};
var champItemUniqueNames = {1: 'weapon', 2: 'chestArmor', 3: 'helm', 4: 'boots', 5: 'shield', 6: 'ring', 8: 'pendant', 9: 'cloak'};
var champItemNames = {1: 'weapon', 2: 'chest', 3: 'helm', 4: 'boots', 5: 'shield', 6: 'ring', 8: 'pendant', 9: 'cloak'};

var STrChORing1 = 6;
var STrChORing2 = 7;

var champTiers = CM.WorldSettings.getSettingAsObject("CE_EFFECTS_TIERS")

var champItemEffects = [201,202,203,204,205,206,207,208,209,1,2,3,4,5,6,7,17,18,19,20,21,22,23,24,26,27,29,31,32,34,35,36,37,39,40,41,44,45,46,47,50,51,52,53,56,57,58,61,62,125,126,127,128,129,130,131,132,133,134,113,114,115,116,117,118,119];

var champEffects = [];
for (var efx = 0; efx < champItemEffects.length; efx++ ) {
    var champEffectName = uW.g_js_strings.effects["name_" + champItemEffects[efx]];
    champEffectName = champEffectName.split(" Debuff")[0];
    if  (champEffects.indexOf(champEffectName) < 0) champEffects.push(champEffectName);
}

var STrChOQualityCount = 6;
var STrChOThroneDisplayTimer = null;
var STrChOMaxThroneQuality = 0;
var STrChOMaxThroneLevel = 0;
var STrChOMaxChampLevel = 0;
var STrChOMaxChampQuality = 0;
var STrChOMaxChampions = 0;
var STrChOMaxPresets = 28;
var STrChOMaxInventoryRows = 0;
var STrChOMaxThroneCards = 0;

var STrChOChampStatsGrid =  {
    "weapon" :     {1: {201:1,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:0,3:0,4:1,5:1,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:1,203:0,204:1,205:1,206:1,207:1,208:1,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:0,3:0,4:1,5:1,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:1,203:0,204:1,205:1,206:1,207:1,208:1,209:0,1:1,2:0,3:0,4:1,5:1,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "chest" :      {1: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:1,20:1,21:0,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:0,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:1,20:1,21:0,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:0,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:0,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:1,20:1,21:0,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "helm" :       {1: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:0,5:0,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:0,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:1,203:1,204:1,205:1,206:1,207:1,208:1,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:0,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:1,203:1,204:0,205:1,206:1,207:1,208:1,209:1,1:1,2:1,3:1,4:1,5:0,6:0,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "boots" :      {1: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:1,5:0,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:1,203:1,204:1,205:1,206:0,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:1,5:0,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:1,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:1,203:1,204:1,205:0,206:1,207:1,208:1,209:1,1:1,2:1,3:1,4:1,5:0,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "shield" :     {1: {201:0,202:1,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:1,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:1,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "ring"  :      {1: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "pendant" :    {1: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "cloak" :      {1: {201:0,202:1,203:0,204:0,205:1,206:1,207:1,208:1,209:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:1,4:0,5:0,6:0,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:0,26:1,27:1,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:1,45:0,46:1,47:1,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {201:0,202:0,203:0,204:0,205:0,206:0,207:0,208:0,209:0,1:0,2:0,3:1,4:1,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:0,36:1,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:1,57:0,58:0,59:0,60:0,61:0,62:1,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:1,127:0,128:0,129:0,130:1,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {201:0,202:1,203:1,204:1,205:1,206:1,207:1,208:1,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {201:0,202:1,203:1,204:1,205:1,206:1,207:1,208:0,209:1,1:0,2:0,3:0,4:0,5:0,6:0,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:1,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:1,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:1,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:1,126:0,127:0,128:0,129:0,130:0,131:1,132:0,133:1,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}}}


var STrChOThroneStatsGrid = {
    "chair" :      {1: {1:1,2:1,3:1,4:1,5:0,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:1,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:1,2:1,3:1,4:1,5:0,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:0,118:1,119:1,120:1,121:1,122:1,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:1,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:1,94:0,95:1,96:0,97:0,98:0,99:1,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:1,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:1,118:0,119:1,120:1,121:0,122:1,123:1,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "table" :      {1: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:1,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:1,9:1,10:1,11:1,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:1,82:0,83:0,84:0,85:1,86:0,87:0,88:0,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:1,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:0,3:0,4:0,5:1,6:0,7:1,8:1,9:1,10:1,11:1,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:1,82:0,83:0,84:0,85:0,86:0,87:1,88:1,89:0,90:1,91:1,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:1,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1,10:1,11:1,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:1,22:0,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:1,82:0,83:0,84:0,85:0,86:0,87:0,88:1,89:0,90:1,91:1,92:1,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:1,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:1,2:1,3:1,4:1,5:0,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:1,22:0,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:1,80:0,81:1,82:0,83:0,84:0,85:0,86:0,87:0,88:1,89:0,90:1,91:1,92:1,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:1,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "window" :     {1: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:1,17:1,18:1,19:1,20:1,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:1,102:1,103:1,104:1,105:1,106:1,107:1,108:1,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:1,11:0,12:0,13:0,14:1,15:0,16:1,17:1,18:1,19:1,20:1,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:1,102:1,103:1,104:1,105:1,106:1,107:1,108:1,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:1,11:0,12:0,13:1,14:1,15:1,16:1,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:1,88:1,89:1,90:1,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:1,102:1,103:1,104:1,105:1,106:1,107:1,108:1,109:0,110:0,111:0,112:0,113:1,114:0,115:1,116:0,117:0,118:0,119:0,120:1,121:0,122:1,123:1,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:0,2:0,3:0,4:0,5:0,6:0,7:1,8:0,9:0,10:1,11:0,12:0,13:1,14:1,15:1,16:1,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:1,88:1,89:1,90:1,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:1,102:1,103:1,104:1,105:1,106:1,107:1,108:1,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:1,11:0,12:0,13:1,14:1,15:1,16:1,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:0,84:0,85:1,86:1,87:1,88:1,89:1,90:1,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:1,102:1,103:1,104:1,105:1,106:1,107:1,108:1,109:0,110:0,111:0,112:0,113:0,114:1,115:0,116:1,117:1,118:0,119:1,120:0,121:1,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "banner" :     {1: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:1,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:0,29:1,30:1,31:1,32:1,33:0,34:1,35:1,36:1,37:0,38:0,39:1,40:1,41:1,42:0,43:0,44:1,45:1,46:1,47:1,48:1,49:0,50:1,51:1,52:1,53:1,54:1,55:0,56:1,57:1,58:0,59:1,60:0,61:1,62:1,63:0,64:1,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:1,12:1,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:0,29:1,30:1,31:1,32:1,33:0,34:1,35:1,36:1,37:0,38:0,39:1,40:1,41:1,42:0,43:0,44:1,45:1,46:1,47:1,48:1,49:0,50:1,51:1,52:1,53:1,54:1,55:0,56:1,57:1,58:0,59:1,60:0,61:1,62:1,63:0,64:1,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:1,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:1,29:1,30:1,31:1,32:1,33:1,34:1,35:1,36:1,37:1,38:0,39:1,40:1,41:1,42:1,43:1,44:1,45:1,46:1,47:1,48:1,49:1,50:1,51:1,52:1,53:1,54:1,55:1,56:1,57:1,58:0,59:1,60:1,61:1,62:1,63:0,64:1,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:1,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:1,29:1,30:1,31:1,32:1,33:1,34:1,35:1,36:1,37:0,38:1,39:1,40:1,41:1,42:1,43:0,44:1,45:1,46:1,47:1,48:1,49:1,50:1,51:1,52:1,53:1,54:1,55:1,56:1,57:1,58:1,59:1,60:1,61:1,62:1,63:1,64:1,65:1,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:1,12:1,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:1,29:1,30:1,31:1,32:1,33:1,34:1,35:1,36:1,37:0,38:1,39:1,40:1,41:1,42:1,43:0,44:1,45:1,46:1,47:1,48:1,49:1,50:1,51:1,52:1,53:1,54:1,55:1,56:1,57:1,58:1,59:1,60:1,61:1,62:1,63:1,64:1,65:1,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "trophy" :     {1: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:1,17:1,18:1,19:1,20:1,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:1,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:1,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:0,29:1,30:1,31:1,32:1,33:0,34:1,35:1,36:1,37:0,38:0,39:1,40:1,41:1,42:0,43:0,44:1,45:1,46:1,47:1,48:1,49:0,50:1,51:1,52:1,53:0,54:1,55:0,56:1,57:1,58:0,59:1,60:0,61:0,62:1,63:0,64:1,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:1,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1,10:1,11:1,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:1,22:0,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:0,81:1,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:1,91:1,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "candelabrum" :{1: {1:1,2:1,3:0,4:0,5:0,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:1,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:1,79:1,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:1,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:1,36:1,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:1,45:0,46:1,47:1,48:1,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:1,57:1,58:0,59:1,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:0,3:1,4:1,5:1,6:1,7:0,8:0,9:0,10:1,11:1,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:1,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:1,92:1,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:0,2:0,3:0,4:1,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:1,36:1,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:1,45:1,46:1,47:1,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:1,57:1,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:1,70:1,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:1,92:1,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:1,2:1,3:1,4:1,5:1,6:1,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:1,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:1,92:1,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "advisor" :    {1: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:1,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:1,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:1,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:1,71:1,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:0,80:0,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:1,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:1,70:1,71:1,72:0,73:0,74:0,75:0,76:0,77:1,78:1,79:0,80:1,81:0,82:1,83:1,84:1,85:1,86:1,87:1,88:0,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:1,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:1,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:1,70:1,71:1,72:0,73:0,74:0,75:0,76:0,77:1,78:1,79:0,80:1,81:0,82:1,83:1,84:1,85:1,86:1,87:1,88:0,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:1,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:1,70:1,71:1,72:0,73:0,74:0,75:0,76:0,77:1,78:1,79:0,80:1,81:0,82:1,83:0,84:0,85:1,86:1,87:1,88:0,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:1,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "hero" :       {1: {1:0,2:1,3:1,4:1,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:1,17:1,18:1,19:0,20:0,21:0,22:0,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:1,33:0,34:0,35:0,36:0,37:0,38:0,39:1,40:0,41:0,42:1,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:1,62:0,63:1,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:1,2:0,3:0,4:0,5:1,6:1,7:0,8:1,9:1,10:0,11:0,12:0,13:0,14:0,15:0,16:1,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:1,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:1,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:1,90:1,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:1,3:0,4:1,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:1,16:1,17:1,18:1,19:0,20:0,21:1,22:0,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:1,33:0,34:0,35:0,36:0,37:0,38:0,39:1,40:0,41:0,42:1,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:1,62:0,63:1,64:0,65:0,66:0,67:0,68:1,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:1,2:0,3:0,4:0,5:0,6:1,7:0,8:1,9:1,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:1,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:1,81:0,82:1,83:1,84:1,85:1,86:1,87:0,88:0,89:1,90:1,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:0,2:1,3:1,4:1,5:1,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:1,17:1,18:1,19:0,20:0,21:1,22:0,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:1,33:0,34:0,35:0,36:0,37:0,38:0,39:1,40:1,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:1,62:0,63:0,64:0,65:1,66:0,67:0,68:1,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "statue" :     {1: {1:0,2:1,3:0,4:1,5:0,6:0,7:0,8:1,9:0,10:1,11:1,12:0,13:0,14:0,15:0,16:0,17:1,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:1,39:0,40:1,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:1,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:1,84:0,85:0,86:0,87:0,88:0,89:1,90:0,91:0,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:1,2:0,3:0,4:1,5:0,6:0,7:1,8:0,9:0,10:0,11:1,12:1,13:0,14:0,15:0,16:1,17:1,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:0,36:0,37:0,38:1,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:1,71:0,72:1,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:1,84:0,85:0,86:0,87:0,88:0,89:1,90:0,91:0,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:1,3:0,4:1,5:0,6:0,7:1,8:1,9:1,10:1,11:1,12:1,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:0,36:0,37:1,38:0,39:0,40:1,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:1,82:1,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:0,2:0,3:0,4:0,5:0,6:0,7:1,8:1,9:1,10:1,11:1,12:0,13:0,14:0,15:0,16:1,17:1,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:0,36:0,37:0,38:0,39:0,40:1,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:1,71:0,72:1,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:1,83:1,84:0,85:0,86:0,87:0,88:1,89:0,90:0,91:1,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:1,2:1,3:0,4:0,5:1,6:0,7:0,8:0,9:1,10:0,11:0,12:1,13:0,14:0,15:0,16:1,17:1,18:1,19:0,20:0,21:1,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:1,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:1,82:1,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:1,92:0,93:1,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "pet" :        {1: {1:1,2:0,3:0,4:0,5:1,6:0,7:1,8:0,9:1,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:1,19:1,20:0,21:0,22:0,23:0,24:1,25:0,26:0,27:0,28:0,29:0,30:1,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:1,45:0,46:1,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:1,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:1,3:1,4:1,5:0,6:0,7:0,8:1,9:0,10:0,11:0,12:0,13:1,14:1,15:1,16:0,17:1,18:0,19:0,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:1,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:1,2:0,3:0,4:0,5:1,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:1,19:0,20:0,21:0,22:0,23:0,24:1,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:0,36:0,37:0,38:0,39:0,40:1,41:0,42:0,43:0,44:1,45:0,46:0,47:1,48:0,49:0,50:0,51:1,52:0,53:0,54:0,55:0,56:1,57:0,58:1,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:1,78:0,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:0,2:1,3:1,4:1,5:0,6:0,7:0,8:1,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:1,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:1,36:1,37:0,38:0,39:1,40:0,41:0,42:1,43:0,44:0,45:1,46:1,47:0,48:0,49:0,50:1,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:1,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:1,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:0,21:1,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:1,36:0,37:1,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "tapestry" :   {1: {1:1,2:1,3:1,4:0,5:1,6:0,7:0,8:1,9:0,10:1,11:0,12:0,13:0,14:0,15:0,16:1,17:1,18:1,19:1,20:0,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:1,46:0,47:0,48:0,49:0,50:0,51:0,52:1,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:0,68:0,69:1,70:0,71:0,72:1,73:0,74:0,75:0,76:0,77:0,78:1,79:0,80:1,81:1,82:0,83:0,84:0,85:0,86:0,87:0,88:1,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:0,118:1,119:1,120:1,121:1,122:1,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:1,2:1,3:1,4:0,5:0,6:1,7:0,8:1,9:0,10:0,11:1,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:0,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:1,29:0,30:0,31:0,32:1,33:1,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:1,46:0,47:0,48:0,49:0,50:0,51:0,52:1,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:0,68:0,69:1,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:1,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:1,2:1,3:1,4:1,5:0,6:0,7:0,8:1,9:0,10:1,11:0,12:0,13:0,14:0,15:0,16:1,17:1,18:1,19:1,20:0,21:1,22:1,23:0,24:0,25:0,26:0,27:1,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:1,52:0,53:1,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:1,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:1,79:0,80:0,81:1,82:0,83:0,84:0,85:0,86:0,87:0,88:1,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:0,118:1,119:1,120:1,121:1,122:1,123:1,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:1,2:1,3:1,4:0,5:0,6:0,7:0,8:1,9:0,10:0,11:1,12:0,13:0,14:0,15:0,16:1,17:1,18:1,19:1,20:0,21:0,22:1,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:1,51:0,52:1,53:1,54:1,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:1,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:1,79:0,80:0,81:1,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:1,2:1,3:0,4:1,5:0,6:0,7:0,8:1,9:0,10:0,11:0,12:1,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:0,21:0,22:1,23:0,24:0,25:0,26:0,27:1,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:1,51:1,52:0,53:0,54:1,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:1,73:0,74:0,75:0,76:0,77:0,78:0,79:1,80:1,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:1,89:1,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:1,118:0,119:1,120:1,121:1,122:1,123:1,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}},
    "pillar" :     {1: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:0,118:0,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    2: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:1,25:1,26:1,27:1,28:1,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:1,57:1,58:1,59:1,60:1,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:1,120:1,121:1,122:1,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    3: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:0,118:1,119:0,120:0,121:0,122:0,123:0,124:0,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    4: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,21:0,22:0,23:0,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:1,35:1,36:1,37:1,38:1,39:0,40:0,41:0,42:0,43:0,44:1,45:1,46:1,47:1,48:1,49:1,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:0,114:0,115:0,116:0,117:0,118:0,119:1,120:1,121:1,122:1,123:0,124:1,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0},
                    5: {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:0,25:0,26:0,27:0,28:0,29:0,30:0,31:0,32:0,33:0,34:0,35:0,36:0,37:0,38:0,39:0,40:0,41:0,42:0,43:0,44:0,45:0,46:0,47:0,48:0,49:0,50:0,51:0,52:0,53:0,54:0,55:0,56:0,57:0,58:0,59:0,60:0,61:0,62:0,63:0,64:0,65:0,66:0,67:0,68:0,69:0,70:0,71:0,72:0,73:0,74:0,75:0,76:0,77:0,78:0,79:0,80:0,81:0,82:0,83:0,84:0,85:0,86:0,87:0,88:0,89:0,90:0,91:0,92:0,93:0,94:0,95:0,96:0,97:0,98:0,99:0,100:0,101:0,102:0,103:0,104:0,105:0,106:0,107:0,108:0,109:0,110:0,111:0,112:0,113:1,114:1,115:1,116:1,117:0,118:1,119:0,120:0,121:0,122:0,123:0,124:1,125:0,126:0,127:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:0,136:0,137:0,138:0,139:0,140:0,141:0,142:0,143:0,144:0}}}

var STrChOThroneUpgradeStats = {
    upgradeSuccess: {
        0: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        1: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        6: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 }
    },

    upgradeFailure: {
        0: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        1: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        6: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 }
    },

    enhanceSuccess: {
        0: { 0: 1, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        1: { 0: 1, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        6: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 }
    },

    enhanceFailure: {
        0: { 0: 1, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        1: { 0: 1, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 },
        6: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0 , 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0, 51: 0, 52: 0, 52: 0, 54: 0, 55: 0 }
    }
};

var STrChOChampUpgradeStats = {
    upgradeSuccess: {
        0: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        1: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0}
    },
    upgradeFailure: {
        0: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        1: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0}
    },
    enhanceSuccess: {
        0: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        1: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0}
    },
    enhanceFailure: {
        0: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        1: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        2: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        3: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        4: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0},
        5: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0 , 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0}
    }
};

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

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

var STrChOThroneSorter = [];
var STrChOSwapTile = null;
var STrChOMassSalvage = [];

var STrChOGlobalOptions = {
    update: true,
    updateSite: "https://greasyfork.org/en/scripts/408041-spawn-trcho ",
    firstrun: true
};

var STrChOGeneralOptions = {
    xPos : 0,
    yPos : 30,
    hidden: true,
    disableAnim : true,
    draggableThroneItems: false,
    throneSorter: false,
    showJewels: true,
    whisperToMe: false,
    sendToInbox: false,
    retryInterval : 30,
    currentTab : null,
    usedAnyCity : true,
    usedCityNum : 0,
    salvageAnyCity : true,
    salvageCityNum : 0,
    safetyOn: false,
    safetyLimit: 100000,
    buffsOff: false,
    removeMastersTokens: false,
    removeOtherTokens: false,
    removeForgedTokens: false,
    removeOtherForgedTokens: false,
    useMastersTokens: false,
    useForgedTokens: false,
    multiUpgrade: false,
    noEquippedSalvage: false,
    noMassSalvage: false,
    noForcedSalvage: false,
    throneSalvageSafety: false,
    champSalvageSafety: false,
    throneSalvageSafetyNum: 40,
    champSalvageSafetyNum: 40,
    minStones: 100000,
    overflow : "order",
    maxStones : 16000000
};

var STrChOLogData = {
    maxEntries: 100,
    successLog: [],
    actionLog: [],
    salvageLog: []
};

var STrChOThroneQueueData = {
    list : [],
    oneItem : true,
    doingRepairs : false,
    index : 0,
    dataConverted : false
};

var STrChOChampQueueData = {
    list: [],
    oneItem: true,
    doingRepairs: false,
    index: 0,
    dataConverted: false
};

var STrChOThroneUpgradeData = {
    active : false,
    useLORB : false,
    useORB : false,
    useLPS : false,
    usePS : false,
    useLT : false,
    useLLT : false,
    useSH : false,
    useKH : false,
    useGH : false,
    useMH : false,
    useAH : false,
    useWH: false,
    useDH: false,
    useEH: false,
    useQuality : 5,
    useLevel : 6,
    useAutoTokens: false,
    useAutoTokensMin: 4,
    useAutoTokensMax: 21,
    item: 0,
    overrideSpeedUp: false,
    hourglassLevelSpecific: false,
    hourglassLevel: 0,
    hourglassQualitySpecific: false,
    hourglassQuality: 0,
    useSpeedUp: 0,
    enhanceAction: false,
    enhanceItem: 0,
    enhanceMax  : STrChOMaxThroneQuality,
    repairAll : false,
    effectSelected: "none",
    buffSelected: "both",
    sortInactive: true,
    ignoreBroken: false,
    newUpgradeState: 0
};

var STrChOChampUpgradeData = {
    active : false,
    useLOM : false,
    useGOM : false,
    useJT : false,
    useST : false,
    useET : false,
    useSH : false,
    useKH : false,
    useGH : false,
    useMH : false,
    useAH : false,
    useWH: false,
    useDH: false,
    useEH: false,
    useQuality : 1,
    useLevel : 1,
    useAutoTokens: false,
    useAutoTokensMin: 3,
    useAutoTokensMax: 14,
    item: 0,
    overrideSpeedUp: false,
    hourglassLevelSpecific: false,
    hourglassLevel: 0,
    hourglassQualitySpecific: false,
    hourglassQuality: 0,
    useSpeedUp: 0,
    enhanceAction: false,
    enhanceItem: 0,
    enhanceMax  : STrChOMaxChampQuality,
    repairAll : false,
    effectSelected: "none",
    buffSelected: "both",
    sortInactive: true,
    ignoreBroken: false,
    newUpgradeState: 0
};

var STrChOThroneSalvageData = {
    active : false,
    throneSaveNum : 40,
    minQuality    : 3,
    ruleSet       : [{"type":"any","faction":"any","conditions":[{"mustHave":"true","number":"2","effect":"Range","buffType":"e","slots":[true,true,true,true,true]}]},{"type":"any","faction":"any","conditions":[{"mustHave":"true","number":"2","effect":"Troop Training Speed","buffType":"e","slots":[true,true,true,true,true]}]},{"type":"banner","faction":"any","conditions":[{"mustHave":"true","number":"2","effect":"Siege Range","buffType":"e","slots":[true,true,true,true,true]}]}],
    numSalvagedItems : 0,
    numSalvagedItems2 : 0,
    numSalvaged   : {0: 0, 1: 0, 2:0, 3:0, 4:0, 5:0, 6:0},
    upgradeFirst  : false,
    upgradeFirstQual : 2,
    upgradedToDelete : [],
    upgradeManual : false,
    upgradeAutoFind : false
};

var STrChOChampSalvageData = {
    active : false,
    champSaveNum : 40,
    minQuality    : 3,
    ruleSet       : [],
    numSalvagedItems : 0,
    numSalvagedItems2 : 0,
    numSalvaged   : {0: 0, 1: 0, 2:0, 3:0, 4:0, 5:0, 6:0},
    upgradeAutoFind : false
};

var STrChOThroneRepairData = {
    active: false,
    useSH: false,
    useKH: false,
    useGH: false,
    useMH: false,
    useAH: false,
    useWH: false,
    useDH: false,
    useEH: false,
    overrideSpeedUp: false,
    hourglassLevelSpecific: false,
    hourglassLevel: 0,
    hourglassQualitySpecific: false,
    hourglassQuality: 0,
    useSpeedUp: 0,
    index: 0,
    items: []
};

var STrChOChampRepairData = {
    active: false,
    useSH: false,
    useKH: false,
    useGH: false,
    useMH: false,
    useAH: false,
    useWH: false,
    useDH: false,
    useEH: false,
    overrideSpeedUp: false,
    hourglassLevelSpecific: false,
    hourglassLevel: 0,
    hourglassQualitySpecific: false,
    hourglassQuality: 0,
    useSpeedUp: 0,
    index: 0,
    items: []
};

var STrChOThronePresetData = {
    items: [],
    presetNames: ["undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
                  "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
                  "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined"],
    showThroneMight: true,
    showThroneName: true,
    presetColor: "#0000FF",
    tagColor: "#FFFFFF",
    activeColor: "#FFFF00",
    taggedItems: {},
    taggedItems01: {},
    taggedItems02: {},
    taggedItems03: {},
    taggedItems04: {},
    taggedItems05: {},
    taggedItems06: {},
    taggedItems07: {},
    taggedItems08: {},
    taggedItems09: {},
    taggedItems10: {},
    taggedItems11: {},
    taggedItems12: {},
    taggedItems13: {},
    taggedItems14: {},
    taggedItems15: {},
    taggedItems16: {},
    taggedItems17: {},
    taggedItems18: {},
    taggedItems19: {},
    taggedItems20: {},
    taggedItems21: {},
    taggedItems22: {},
    taggedItems23: {},
    taggedItems24: {},
    previewThrone: {}
};

var STrChOChampPresetData = {
    items: [],
    presetNames: ["undefined", "undefined", "undefined", "undefined"],
    showChampMight: true,
    showChampName: true,
    presetColor: "#0000FF",
    tagColor: "#FFFFFF",
    activeColor: "#FFFF00",
    taggedItems: {},
    taggedItems01: {},
    taggedItems02: {},
    taggedItems03: {},
    taggedItems04: {},
    previewChamp: [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ] //had to do array like this because of double ring
};

var STrChOJewelImages = {
                1: "http://i.imgur.com/SecBRT5.png",
                2: "http://i.imgur.com/dnrId1I.png",
                3: "http://i.imgur.com/fjgZUh9.png",
                4: "http://i.imgur.com/h7tMQaB.png",
                5: "http://i.imgur.com/BZSuCiN.png"

};


var HOURGLASSES_TIME = {
    minute1 : 60,
    minute15 : 900,
    hour1 : 3600,
    hour25 : 9000,
    hour8 : 28800,
    hour15: 54000,
    hour24: 86400,
    day25: 216000
};

var HOURGLASSES_TIME_MIN_THRESHOLD = {
    minute1 : 30, //30 seconds and up will use 1m speedup
    minute15 : 301, //5 minute 1 second and up will use 15m speedup
    hour1 : 2701, // 45 minutes 1 second and up will use 1hr speedup
    hour25 : 7201, // 2 hour 1 second and up will use 2.5hr speedup
    hour8 : 26101, // 7 hours 30 minutes 1 second and up will use 8hr speedup
    hour15: 50431, // 14 hours 30 minutes 1 second and up will use 15hr speedup
    hour24: 82831, // 23 hours 30 minutes 1 second and up will use 24hr speedup
    day25: 172800 //48 hours and up will use 2.5 day speedup
};

var STrChOHourGlassTDLabel = {
                    1: 'Time: 1 Min | Conditions: 30s+',
                    2: 'Time: 15 Min | Conditions: 5m & 1s+',
                    3: 'Time: 1 Hour | Conditions: 45m & 1s+',
                    4: 'Time: 2.5 Hours | Conditions: 2h & 1s+',
                    5: 'Time: 8 Hours | Conditions: 7h & 30m & 1s+',
                    6: 'Time: 15 Hours | Conditions: 14h & 30m & 1s+',
                    7: 'Time: 24 Hours | Conditions: 23h & 30m & 1s+',
                    8: 'Time: 2.5 Days | Conditions: 48h+'
};

var STrChOHourGlassName = {
                    1: "Squire's Hourglass",
                    2: "Knight's Hourglass",
                    3: "Guinevere's Hourglass",
                    4: "Morgana's Hourglass",
                    5: "Arthur's Hourglass",
                    6: "Merlin's Hourglass",
                    7: "Divine Hourglass",
                    8: "Epic Hourglass"
};

// initialise
LOADallData();

var STrChOWinManager = {
	wins : {},    // prefix : CPopup obj

	get : function (prefix){
		var t = STrChOWinManager;
		return t.wins[prefix];
	},

	add : function (prefix, pop){
		var t = STrChOWinManager;
		t.wins[prefix] = pop;
		if (uW.cpopupWins == null)
			uW.cpopupWins = {};
		uW.cpopupWins[prefix] = pop;
	},

	delete : function (prefix){
		var t = STrChOWinManager;
		delete t.wins[prefix];
		delete uW.cpopupWins[prefix];
	}
}

// creates a 'popup' div
// prefix must be a unique (short) name for the popup window
function STrChOPopup(prefix, x, y, enableDrag, onClose) {
	var pop = STrChOWinManager.get(prefix);
	if (pop) {
		pop.show(false);
		return pop;
	}
	this.BASE_ZINDEX = 111111;
	// protos ...
	this.show = show;
	this.toggleHide = toggleHide;
	this.getTopDiv = getTopDiv;
	this.getMainDiv = getMainDiv;
	this.getLayer = getLayer;
	this.setLayer = setLayer;
	this.setEnableDrag = setEnableDrag;
	this.getLocation = getLocation;
	this.setLocation = setLocation;
	this.focusMe = focusMe;
	this.unfocusMe = unfocusMe;
	this.centerMe = centerMe;
	this.destroy = destroy;
	// object vars ...
	this.div = document.createElement('div');
	this.prefix = prefix;
	this.onClose = onClose;
	var t = this;
	this.div.className = 'STrChOPopup ' + prefix + '_STrChOPopup';
	this.div.id = prefix + '_outer';
	this.div.style.background = "#fff";
	this.div.style.zIndex = this.BASE_ZINDEX // KOC modal is 100210 ?
	this.div.style.display = 'none';
	this.div.style.width = dlgWidth + 'px';
	this.div.style.height = dlgHeight + 'px';
	this.div.style.position = "absolute";
	this.div.style.top = y + 'px';
	this.div.style.left = x + 'px';
	topClass = 'STrChOPopupTop ' + prefix + '_STrChOPopupTop';
	var m = '';
    m += '<TABLE cellspacing=0 width=100% height=100%>';
    m += '<TR id="' + prefix + '_bar" class="' + topClass + '">';
    m += '<TD width=99% align=center><b>Spawn TrChO (Version ' + STrChOVersion + ')</b>';
    m += '<input type=file id=STrChOSettingsFile style="visibility:hidden; width: 0px; height: 0px;">';
    m += '</td>';
    m += '<TD id=' + prefix + '_X align=right valign=middle onmouseover="this.style.cursor=\'pointer\'" style="color:#fff; background:#000000; font-weight:bold; font-size:14px; padding:0px 5px;">X';
    m += '</td>';
    m += '</tr>';
    m += '<tr><td valign=top colspan=2><table cellspacing=0 cellpadding=0>';
    m += '<TR><TD valign=top colspan=2 id="'+ prefix +'_top"></td>';
    m += '<TD valign=top class="STrChOCPopMain ' + prefix + '_STrChOCPopMain" colspan=2 id="' + prefix + '_main"></td></tr>';

    m += '</table></td></tr>';

    m += '</table>';
	document.body.appendChild(this.div);
	this.div.innerHTML = m;
	document.getElementById(prefix + '_X').addEventListener('click', e_XClose, false);
	this.dragger = new CWinDrag(document.getElementById(prefix + '_bar'), this.div, enableDrag);
	this.div.addEventListener('mousedown', e_divClicked, false);
	STrChOWinManager.add(prefix, this);

	function e_divClicked() {
		t.focusMe();
	}

	function e_XClose() {
		t.show(false);
		if (t.onClose != null)
			t.onClose();
	}

	function focusMe() {
		t.setLayer(5);
		for (k in uW.cpopupWins) {
			if (k != t.prefix)
				uW.cpopupWins[k].unfocusMe();
		}
	}

	function unfocusMe() {
		t.setLayer(-5);
	}

	function getLocation() {
		return {
			x: parseInt(this.div.style.left),
			y: parseInt(this.div.style.top)
		};
	}

	function setLocation(loc) {
		t.div.style.left = loc.x + 'px';
		t.div.style.top = loc.y + 'px';
	}

	function destroy() {
		document.body.removeChild(t.div);
		STrChOWinManager.delete(t.prefix);
	}

	function centerMe(parent) {
		if (parent == null) {
			var coords = getClientCoords(document.body);
		} else
			var coords = getClientCoords(parent);
		var x = ((coords.width - parseInt(t.div.style.width)) / 2) + coords.x;
		var y = ((coords.height - parseInt(t.div.style.height)) / 2) + coords.y;
		if (x < 0)
			x = 0;
		if (y < 0)
			y = 0;
		t.div.style.left = x + 'px';
		t.div.style.top = y + 'px';
	}

	function setEnableDrag(tf) {
		t.dragger.setEnable(tf);
	}

	function setLayer(zi) {
		t.div.style.zIndex = '' + (this.BASE_ZINDEX + zi);
	}

	function getLayer() {
		return parseInt(t.div.style.zIndex) - this.BASE_ZINDEX;
	}

	function getTopDiv() {
		return document.getElementById(this.prefix + '_top');
	}

	function getMainDiv() {
		return document.getElementById(this.prefix + '_main');
	}

	function show(tf) {
		if (tf) {
			t.div.style.display = 'block';
			t.focusMe();
		} else {
			t.div.style.display = 'none';
		}
		return tf;
	}

	function toggleHide(t) {
		if (t.div.style.display == 'block') {
			return t.show(false);
		} else {
			return t.show(true);
		}
	}
}

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

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

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

	function CeventDown (that){
		this.handler = handler;
		var t = that;

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

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

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

	function CeventOut  (that){
		this.handler = handler;
		var t = that;

		function handler (me){
			if (me.button==0){
				t.moveHandler (me);
			}
		}
	}

	function CeventMove (that){
		this.handler = handler;
		var t = that;

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

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

var tabManager = {
	tabList : {},           // {name, obj, div}
	currentTab : null,

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

		sorter.sort (function (a,b){return a[0]-b[0]});
		var m = '';

		m += '<ul class=STrChOULMenu>';
		for (var i=0; i<sorter.length; i++) {
			var color = sorter[i][1].tabColor;
            m += '<li><input type=button id=nttc'+ sorter[i][1].name +' class="STrChOMenuButton h20 '+color+'" style="width:'+dlgWidthMenu+'px;" value="' + sorter[i][1].label + '"></LI>';
		}
		m+='</UL>';

		mainPop.getTopDiv().innerHTML = m;

		var contentDiv = document.createElement('div');
		contentDiv.id = 'STrChOMain_content';
		mainDiv.appendChild(contentDiv);

		for (k in t.tabList) {
            if (t.tabList[k].name == STrChOGeneralOptions.currentTab) t.currentTab =t.tabList[k];
			document.getElementById('nttc'+ k).addEventListener('click', this.e_clickedTab, false);
			var div = t.tabList[k].div;
			div.style.display = 'none';
			div.style.height = '100%';
			contentDiv.appendChild(div);
			try {
				t.tabList[k].obj.init(div);
			} catch (e){
				div.innerHTML = "INIT ERROR: "+ e;
			}
		}

		if (t.currentTab == null) t.currentTab = sorter[0][1];
		t.currentTab.div.style.display = 'block';
        t.setTabStyle(t.currentTab, true);
	},

	hideTab : function (){
		var t = tabManager;
		t.currentTab.obj.hide();
        STrChOGeneralOptions.hidden = true;
        //STrChOGeneralOptions.currentTab = null;
        SAVESTrChOGeneralOptions();
	},

	showTab : function (){
		var t = tabManager;
		t.currentTab.obj.show();
        STrChOGeneralOptions.hidden = false;
        //STrChOGeneralOptions.currentTab = t.currentTab.name;
        SAVESTrChOGeneralOptions();
	},

	setTabStyle : function (Tab, selected){
		var e = document.getElementById ('nttc'+ Tab.name)
		var c = Tab.tabColor?Tab.tabColor:"gray";
		if (selected){
			e.className = 'STrChOMenuButton h20 gray';
		} else {
			e.className = 'STrChOMenuButton h20 '+c;
		}
	},

	e_clickedTab : function (e){
		var t = tabManager;
		mainPop.show (true);
		if (e.target.id)
			var newTab = t.tabList[e.target.id.substring(4)];
		else
			var newTab = t.tabList[e.target.parentNode.id.substring(4)];
		if (t.currentTab.name != newTab.name){
			t.setTabStyle (t.currentTab, false);
			t.setTabStyle (newTab, true);
			t.currentTab.obj.hide ();
			t.currentTab.div.style.display = 'none';
			t.currentTab = newTab;
            STrChOGeneralOptions.currentTab = newTab.name;
			newTab.div.style.display = 'block';
		}
		newTab.obj.show();
	},

}

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

function eventHideShow() {
	if (mainPop.toggleHide(mainPop)) {
		tabManager.showTab();
	} else {
		tabManager.hideTab();
	}
}

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

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

function ScriptStartup () {
    if (uW.STrChOLoaded) return;
	var metc = getClientCoords(document.getElementById('main_engagement_tabs'));
	if (metc.width==null || metc.width==0) {
		setTimeout (ScriptStartup, 1000);
		return;
	}

    STrChOMaxThroneQuality = CM.ThronePanelController.MAX_QUALITY;
    STrChOMaxThroneLevel = CM.MAX_MASTERS_TOKEN_LEVEL;
    STrChOMaxChampLevel = CM.CHAMPION.MAX_LEVELS;
    STrChOMaxChampQuality = CM.CHAMPION.MAX_EFFECTS;
    STrChOMaxChampions = Seed.champion.champions.size();
    STrChOMaxInventoryRows = Seed.throne.rowNum;
    STrChOMaxThroneCards = STrChOMaxInventoryRows * 5;

	// initialise
//    LOADallData(); //done earlier in the script

    var styles = '';
    styles += '#itemInventory {min-height: 420px; background-color:#884422;}'; //this expands the height of the champion hall inventory space
    styles += '#itemFilter {min-height: 150px;  background-color:#884422;}';

    styles += 'tr.STrChOPopupTop td {background-color:#000000; border:1px solid #000000; height: 21px;  padding:0px; color:#C92C0C;}';
    styles += 'td {border: 0px;}';
    styles += '.STrChOCPopMain {width:'+dlgWidth+'px; height:'+(dlgHeight-dlgHeightOffset)+'px; background-color:#F7F3E6; border:1px solid #000000; -moz-box-shadow:inset 0px 0px 10px #6a6a6a; -webkit-box-shadow:inset 0px 0px 10px #6a6a6a; box-shadow:inset 0px 0px 10px #6a6a6a; font-size:12px; color:#000000;}';
    styles += '.STrChOPopup {border:5px ridge #666; opacity:1; -moz-box-shadow: 1px 1px 5px #000000; -webkit-box-shadow: 1px 1px 5px #000000; box-shadow: 1px 1px 5px #000000;}';
    styles += '.STrChOHeader {width:100%; border:0px solid; border-color:#808080; background: -moz-linear-gradient(top, #A9A9A9, #333); background: -webkit-linear-gradient(top, #A9A9A9, #333); background: linear-gradient(top, #A9A9A9, #333); height: 22px; border-bottom:0px solid #000000;font-weight:bold;font-size:12px;opacity:0.75;margin-left:0px;margin-right:0px;margin-top:1px;margin-bottom:0px;padding-top:6px;padding-right:0px; vertical-align:middle;align:center; color:#000000; text-align:center;}';
    styles += '.STrChOThroneOrganizer {position: static; overflow-x: auto; overflow-y: auto; width:100%; border:0px solid; border-color:#000000; background: -moz-linear-gradient(top, #A9A9A9, #333); background: -webkit-linear-gradient(top, #A9A9A9, #333); background: linear-gradient(top, #A9A9A9, #333); height: 16px;border-bottom:0px solid #000000;font-weight:bold;font-size:12px;opacity:0.75;margin-left:0px;margin-right:0px;margin-top:1px;margin-bottom:0px;padding-top:0px;padding-right:0px; vertical-align:middle;align:center; color:#000000; text-align:center;}';
    styles += '.STrChOChampOrganizer {position: static; overflow-x: auto; overflow-y: auto; width:100%; border:0px solid; border-color:#000000; background: -moz-linear-gradient(top, #A9A9A9, #333); background: -webkit-linear-gradient(top, #A9A9A9, #333); background: linear-gradient(top, #A9A9A9, #333); height: 16px;border-bottom:0px solid #000000;font-weight:bold;font-size:12px;opacity:0.75;margin-left:0px;margin-right:0px;margin-top:1px;margin-bottom:0px;padding-top:0px;padding-right:0px; vertical-align:middle;align:center; color:#000000; text-align:center;}';
    styles += '.STrChOThroneOrganizerSection {display:none; position:static; overflow-x:auto; overflow-y:hidden; }';
    styles += '.STrChOChampOrganizerSection {display:none; position:static; overflow-x:auto; overflow-y:hidden; }';
    styles += '.divNoWrap {white-space: nowrap; display:inline-block;}';
    styles += '.indent5 {padding-left:5px}';
    styles += '.STrChOButton {background-color:#000000; color:#ffffff;font-weight:bold;font-size:11px;-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); box-shadow: 0px 1px 3px rgba(0,0,0,0.5);}';
    styles += '.STrChOSelect {background-color:#ffffff; color:#000000;font-weight:normal;width:100px;font-size:11px;-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); box-shadow: 0px 1px 3px rgba(0,0,0,0.5);}';
    styles += '.STrChOTextbox {background-color:#ffffff; color:#000000;font-weight:normal;font-size:11px;-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); box-shadow: 0px 1px 3px rgba(0,0,0,0.5);}';
    styles += '.STrChOCheckbox {-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5); box-shadow: 0px 1px 3px rgba(0,0,0,0.5);}';
    styles += '.STrChOLinks {font-family: tahoma,verdana,arial,sans-serif; font-size: 12px; font-variant: normal; font-style: normal; font-weight: normal; color: #000000; text-decoration: none;}';
    styles += 'td.STrChOTDLinks {background-color:#FFFFCC;}';
    styles += 'hr.STrChOHRCenter {width: 80%; align:center;}';
    styles += '.STrChOLinksHeader {font-family: tahoma,verdana,arial,sans-serif; font-size: 12px; font-variant: normal; font-style: normal; font-weight: bold; color: #1a1a1a; text-decoration: none;}';
    styles += '.STrChOLinksDesc {font-family: tahoma,verdana,arial,sans-serif; font-size: 12px; font-variant: normal; font-style: italic; font-weight: bold; color: #0000FF; text-decoration: none;}';
    styles += '.STrChOULMenu {list-style-type: none;padding: 0;margin: 0;display: inline;}';
    styles += '.STrChOSectionTable {padding:0px; border-spacing: 0px;width:100%;border:0px;}';
    styles += '.STrChOReverseImage {-moz-transform: scaleX(-1); -o-transform: scaleX(-1); -webkit-transform: scaleX(-1); transform: scaleX(-1); filter: FlipH; -ms-filter: "FlipH";}';
    styles += '.STrChOSection {display:none;}';
    styles += 'table.STrChOStats tr td { background-color: #ffffff; white-space:nowrap; padding:5px; border-bottom:solid black 1px;}';
    styles += 'table.STrChOStats tr td:last-child { border-right:solid black 1px; }';
    styles += 'table.STrChOStats tr:first-child th { border-top:solid black 1px; }';
    styles += 'table.STrChOStats tr td.td0 { background-color: white; }';
    styles += 'table.STrChOStats tr td.td1 { background-color: #eeeeee; }';
    styles += 'table.STrChOStats tr td.td2 { background-color: white; }';
    styles += 'table.STrChOStats tr th {border:solid black 1px; border-top: none; background-color: #357; color: white; white-space:nowrap; padding:5px}';
    styles += 'table.STrChOStats tr:last-child td:first-child, table.STrChOStats tr:last-child th:first-child { -moz-border-radius-bottomleft:10px; -webkit-border-bottom-left-radius:10px; border-bottom-left-radius:10px} ';
    styles += 'table.STrChOStats tr:last-child td:last-child, table.STrChOStats tr:last-child th:last-child { -moz-border-radius-bottomright:10px; -webkit-border-bottom-right-radius:10px; border-bottom-right-radius:10px} ';
    styles += 'table.STrChOStats tr:first-child th:first-child { -moz-border-radius-topleft:10px; -webkit-border-top-left-radius:10px; border-top-left-radius:10px} ';
    styles += 'table.STrChOStats tr:first-child th:last-child { -moz-border-radius-topright:10px; -webkit-border-top-right-radius:10px; border-top-right-radius:10px} ';
    styles += '.STrChOMenuButton { cursor: pointer; border-width: 2px; border-style: solid; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -webkit-border-top-colors: none; -webkit-border-right-colors: none; -webkit-border-bottom-colors: none; -webkit-border-left-colors: none; border-top-colors: none; border-right-colors: none; border-bottom-colors: none; border-left-colors: none; border-image: none; border-color: #FDF4D2 #A69964 #A69964 #FDF4D2; color: #FFF; font: bold 10px Georgia; text-align: center; text-decoration: none; background-color: #C82622 !important; }';
    styles += '.STrChOMenuButton.h20 { width: 123px; height: 20px; line-height: 14px; padding: 2px 7px; }';
    styles += '.STrChOMenuButton.red { color: #FFF !important; background: -moz-linear-gradient(center top , #B600B6, #5D3A5D 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #747474, #474747 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #FF6E72, #320201 100%) repeat scroll 0% 0% transparent; }';
    styles += '.STrChOMenuButton.green { background: -moz-linear-gradient(center top , #B600B6, #5D3A5D 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #747474, #474747 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #4AB900, #3F8803 100%) repeat scroll 0% 0% transparent; }';
    styles += '.STrChOMenuButton.brown { background: -moz-linear-gradient(center top , #B600B6, #5D3A5D 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #FE6601, #B3561D 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #C58200, #976300 100%) repeat scroll 0% 0% transparent; }';
    styles += '.STrChOMenuButton.blue { background: -moz-linear-gradient(center top , #B600B6, #5D3A5D 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #B600B6, #5D3A5D 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #014DAA, #00397E 100%) repeat scroll 0% 0% transparent; }';
    styles += '#STrChOHammer { background-image: url("'+gameurl+'img/throne/modal/sm_hammer.png"); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 28px; height: 32px; margin: 2px; vertical-align: middle;}';
    styles += 'div.STrChOHammer { background-image: url("'+gameurl+'img/throne/modal/sm_hammer.png"); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 28px; height: 32px; margin: 2px; vertical-align: middle;}';
    styles += 'div.STrChOBroken { background-image: url("'+gameurl+'img/throne/modal/sm_fail_overlay.png"); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 28px; height: 32px; margin: 2px; vertical-align: middle;}';
    styles += 'div.STrChOSuccess { background-image: url('+ success_image +'); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 28px; height: 32px; margin: 2px; vertical-align: middle;}';
    styles += 'div.STrChOUpRow { display=inline;  background-image: url('+ up_img +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
    styles += 'div.STrChOUpRow:hover { display=inline;  background-image: url('+ up_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
    styles += 'div.STrChORemove { display=inline;  background-image: url('+ remove_img +'); background-repeat: no-repeat; background-color: transparent;  width: 50px; height: 50px; }';
    styles += 'div.STrChORemove:hover { display=inline;  background-image: url('+ remove_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 50px; height: 50px; }';
    styles += 'div.STrChODownRow { display=inline;  background-image: url('+ down_img +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
    styles += 'div.STrChODownRow:hover { display=inline;  background-image: url('+ down_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
    styles += 'div.STrChOGoButton { display=inline;  background-image: url('+ gbtn_img +'); background-repeat: no-repeat; background-color: transparent;  width: 32px; height: 32px; margin: 0px; }';
    styles += 'div.STrChOSaveSettings { display=inline; background-image: url("'+gameurl+'img/bonus_prestige.png"); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 20px; height: 20px; margin-left: 20px; vertical-align: middle; float:left}';
    styles += 'div.STrChOLoadSettings { display=inline; background-image: url("'+gameurl+'img/bonus_att.png"); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 20px; height: 20px; margin-left: 2px; vertical-align: middle; float:left}';

    styles += 'div.STrChOBlueBorder { border: 2px solid blue; }';
    styles += 'div.STrChOYellowBorder { outline: 2px solid yellow; outline-offset:0px; }';

    styles += '.swapBorderThrone { margin-right: -100%; margin-bottom: -100%; height: 99%; width: 99%; padding: 4%; background-image: url('+ success_image +'); background-repeat: no-repeat; background-size: 28px; display: inline-block;}';
    styles += '.tagBorderThrone { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + STrChOThronePresetData.tagColor + '; background: transparent;}';
    styles += '.presetBorderThrone { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + STrChOThronePresetData.presetColor + '; background: transparent;}';
    styles += '.activeBorderThrone { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + STrChOThronePresetData.activeColor + '; background: transparent;}';
    styles += '.tagBorderChamp { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + STrChOChampPresetData.tagColor + '; background: transparent;}';
    styles += '.presetBorderChamp { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + STrChOChampPresetData.presetColor + '; background: transparent;}';
    styles += '.activeBorderChamp { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + STrChOChampPresetData.activeColor + '; background: transparent;}';


    styles += 'div.champ_item_section ul.effects { margin: 3px 0 0 0; padding: 0; list-style: none; }';
    styles += 'div.champ_item_section ul.effects li.effect { padding:0;font-weight:bold;font-size:10px; }';
    styles += 'div.champ_item_section ul.effects li.effect.statChamp { color: #3F2300; }';
    styles += 'div.champ_item_section ul.effects li.effect.statTroop { color: #1751A5; }';
    styles += 'div.champ_item_section ul.effects li.effect.statChamp.disabled { color: #B9A48B; }';
    styles += 'div.champ_item_section ul.effects li.effect.statTroop.disabled { color: #A5B1E5; }';

    styles += 'div.STrChOCard {width: 180px; height: 200px; font:bold 8px Georiga; overflow: hidden;}';
    var icon_size = '50px 50px';
    styles += 'div.STrChOCard div.description>div{width:50px;height:50px; }';
    styles += 'div.STrChOCard div.description div.briton.advisor{background:transparent url("'+gameurl+'img/throne/icons/70/briton_advisor_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.banner{background:transparent url("'+gameurl+'img/throne/icons/70/briton_banner_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.chair{background:transparent url("'+gameurl+'img/throne/icons/70/briton_chair_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.table{background:transparent url("'+gameurl+'img/throne/icons/70/briton_table_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.window{background:transparent url("'+gameurl+'img/throne/icons/70/briton_window_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.trophy{background:transparent url("'+gameurl+'img/throne/icons/70/briton_trophy_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.hero{background:transparent url("'+gameurl+'img/throne/icons/70/briton_hero_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.statue{background:transparent url("'+gameurl+'img/throne/icons/70/briton_statue_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.candelabrum{background:transparent url("'+gameurl+'img/throne/icons/70/briton_candelabrum_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.pet{background:transparent url("'+gameurl+'img/throne/icons/70/briton_pet_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.tapestry{background:transparent url("'+gameurl+'img/throne/icons/70/briton_tapestry_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.pillar{background:transparent url("'+gameurl+'img/throne/icons/70/briton_pillar_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.weapon{background:transparent url("'+gameurl+'img/champion_hall/wondrous_weapon_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.chest{background:transparent url("'+gameurl+'img/champion_hall/wondrous_chestArmor_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.helm{background:transparent url("'+gameurl+'img/champion_hall/wondrous_helmet_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.boots{background:transparent url("'+gameurl+'img/champion_hall/wondrous_feet_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.shield{background:transparent url("'+gameurl+'img/champion_hall/wondrous_shield_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.ring{background:transparent url("'+gameurl+'img/champion_hall/wondrous_ring1_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.pendant{background:transparent url("'+gameurl+'img/champion_hall/wondrous_pendant_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.briton.cloak{background:transparent url("'+gameurl+'img/champion_hall/wondrous_cloak_briton_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.advisor{background:transparent url("'+gameurl+'img/throne/icons/70/druid_advisor_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.banner{background:transparent url("'+gameurl+'img/throne/icons/70/druid_banner_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.chair{background:transparent url("'+gameurl+'img/throne/icons/70/druid_chair_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.table{background:transparent url("'+gameurl+'img/throne/icons/70/druid_table_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.window{background:transparent url("'+gameurl+'img/throne/icons/70/druid_window_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.trophy{background:transparent url("'+gameurl+'img/throne/icons/70/druid_trophy_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.hero{background:transparent url("'+gameurl+'img/throne/icons/70/druid_hero_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.statue{background:transparent url("'+gameurl+'img/throne/icons/70/druid_statue_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.candelabrum{background:transparent url("'+gameurl+'img/throne/icons/70/druid_candelabrum_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.pet{background:transparent url("'+gameurl+'img/throne/icons/70/druid_pet_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.tapestry{background:transparent url("'+gameurl+'img/throne/icons/70/druid_tapestry_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.pillar{background:transparent url("'+gameurl+'img/throne/icons/70/druid_pillar_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.weapon{background:transparent url("'+gameurl+'img/champion_hall/wondrous_weapon_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.chest{background:transparent url("'+gameurl+'img/champion_hall/wondrous_chestArmor_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.helm{background:transparent url("'+gameurl+'img/champion_hall/wondrous_helmet_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.boots{background:transparent url("'+gameurl+'img/champion_hall/wondrous_feet_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.shield{background:transparent url("'+gameurl+'img/champion_hall/wondrous_shield_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.ring{background:transparent url("'+gameurl+'img/champion_hall/wondrous_ring1_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.pendant{background:transparent url("'+gameurl+'img/champion_hall/wondrous_pendant_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.druid.cloak{background:transparent url("'+gameurl+'img/champion_hall/wondrous_cloak_druid_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.advisor{background:transparent url("'+gameurl+'img/throne/icons/70/fey_advisor_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.banner{background:transparent url("'+gameurl+'img/throne/icons/70/fey_banner_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.chair{background:transparent url("'+gameurl+'img/throne/icons/70/fey_chair_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.table{background:transparent url("'+gameurl+'img/throne/icons/70/fey_table_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.window{background:transparent url("'+gameurl+'img/throne/icons/70/fey_window_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.trophy{background:transparent url("'+gameurl+'img/throne/icons/70/fey_trophy_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.hero{background:transparent url("'+gameurl+'img/throne/icons/70/fey_hero_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.statue{background:transparent url("'+gameurl+'img/throne/icons/70/fey_statue_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.candelabrum{background:transparent url("'+gameurl+'img/throne/icons/70/fey_candelabrum_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.pet{background:transparent url("'+gameurl+'img/throne/icons/70/fey_pet_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.tapestry{background:transparent url("'+gameurl+'img/throne/icons/70/fey_tapestry_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.pillar{background:transparent url("'+gameurl+'img/throne/icons/70/fey_pillar_normal_1_6.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.weapon{background:transparent url("'+gameurl+'img/champion_hall/wondrous_weapon_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.chest{background:transparent url("'+gameurl+'img/champion_hall/wondrous_chestArmor_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.helm{background:transparent url("'+gameurl+'img/champion_hall/wondrous_helmet_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.boots{background:transparent url("'+gameurl+'img/champion_hall/wondrous_feet_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.shield{background:transparent url("'+gameurl+'img/champion_hall/wondrous_shield_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.ring{background:transparent url("'+gameurl+'img/champion_hall/wondrous_ring1_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.pendant{background:transparent url("'+gameurl+'img/champion_hall/wondrous_pendant_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard div.description div.fey.cloak{background:transparent url("'+gameurl+'img/champion_hall/wondrous_cloak_fey_30x30.png") top left no-repeat; background-size: ' + icon_size + ';}';
    styles += 'div.STrChOCard .disabled{opacity:.5;}';
    styles += 'div.STrChOCard ul{margin:0px;padding:0;list-style:none;}';
    styles += 'div.STrChOCard li{padding:0px 0 0 0px;color:#3f2300;font-weight:bold;font-size:10px;}'; //tooltip
    styles += 'div.STrChOCard>div{float:left;border:1px solid #a56631;margin:0px;padding:0px;width:200px; height:300px; background:transparent url("'+gameurl+'img/modal/modal_med_bg_4.png") -200px 0 no-repeat;}'; //tooltip
    styles += 'div.STrChOTitle{font:bold 11px Georgia;border-bottom:1px solid #703200;padding:4px 3px 5px 8px;background:transparent url("'+gameurl+'img/throne/panel/modal/item_bg.png") -20px -100px no-repeat;}'; //tooltip
    styles += 'div.STrChOTitle span.icon{background:transparent url("'+gameurl+'img/throne/modal/equip.png") top right no-repeat;display:block;height:20px;width:20px;top:12px;right:12px;position:absolute;}';
    styles += 'div.description {overflow:hidden;border-bottom:1px solid #703200;}';
    styles += 'div.portrait {float:left; border:3px solid #deaf69;margin-right:8px;}';
    styles += 'div.description>ul{float:left;margin:3px 0 0 0;padding:0;}';
    styles += 'div.description>ul li{padding:0;font-weight:bold;font-size:10px;text-transform:capitalize;}'; //tooltip

    styles += '.STrChOCastleButton {outline:0px; margin-left:0px; margin-right:0px; width:24px; height:26px; font-size:12px; font-weight:bold; }';
    styles += '.STrChOCastleButton:hover {background-image:url("'+ URL_CASTLE_BUTTON_SELECT +'")}';
    styles += '.STrChOCastleButtonNot {background-image:url("'+ URL_CASTLE_BUTTON +'")}';
    styles += '.STrChOCastleButtonSelect {background-image:url("'+ URL_CASTLE_BUTTON_SELECT +'")}';

    styles += 'div.STrChOContextMenu {background-color: #999966; z-index: 10000000; position: absolute; height: 400px; padding: 4px 4px 4px 4px; font: bold 11px Georgia; border-width: 2px; border-style: solid; text-align: center; margin: auto;}';// overflow-y: auto; overflow-x: hidden;}';

    styles += 'div.STrChOContextMenuItem       {height: 20px; width: 140px; margin-bottom: 2px; cursor: pointer; text-decoration: none; font: bold 12px Georgia; text-align: center; border-style: solid; border-width: 2px; background-color: #B72828 !important; vertical-align: middle; color: #ffffff; border-color: transparent; padding-top: 4px;}';
    styles += 'div.STrChOContextMenuSubItem    {height: 20px; width: 140px; margin-bottom: 2px; cursor: pointer; text-decoration: none; font: bold 12px Georgia; text-align: center; border-style: solid; border-width: 2px; background-color: #B72828 !important; vertical-align: middle; color: #ffffff; border-color: transparent; padding-top: 4px;}';

    styles += 'div.STrChORed         {background: -moz-linear-gradient(center top , #FF6E72, #320201 100%) repeat scroll 0% 0% transparent;background: -webkit-linear-gradient(top , #FF6E72, #320201 100%) repeat scroll 0% 0% transparent;background: linear-gradient(center top , #FF6E72, #320201 100%) repeat scroll 0% 0% transparent;}';
    styles += 'div.STrChORed:hover   {background: -moz-linear-gradient(center top , #320201, #FF6E72 100%) repeat scroll 0% 0% transparent;background: -webkit-linear-gradient(top , #320201, #FF6E72 100%) repeat scroll 0% 0% transparent;background: linear-gradient(center top , #320201, #FF6E72 100%) repeat scroll 0% 0% transparent;}';
    styles += 'div.STrChOGreen          {background: -moz-linear-gradient(center top , #4AB900, #3F8803 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #4AB900, #3F8803 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #4AB900, #3F8803 100%) repeat scroll 0% 0% transparent; }';
    styles += 'div.STrChOGreen:hover    {background: -moz-linear-gradient(center top , #3F8803, #4AB900 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #3F8803, #4AB900 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #3F8803, #4AB900 100%) repeat scroll 0% 0% transparent; }';
    styles += 'div.STrChOBlue         {background: -moz-linear-gradient(center top , #014DAA, #00397E 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #014DAA, #00397E 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #014DAA, #00397E 100%) repeat scroll 0% 0% transparent; }';
    styles += 'div.STrChOBlue:hover   {background: -moz-linear-gradient(center top , #00397E, #014DAA 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #00397E, #014DAA 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #00397E, #014DAA 100%) repeat scroll 0% 0% transparent; }';
    styles += 'div.STrChOBrown         {background: -moz-linear-gradient(center top , #976300, #C58200 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #976300, #C58200 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #976300, #C58200 100%) repeat scroll 0% 0% transparent; }';
    styles += 'div.STrChOBrown:hover   {background: -moz-linear-gradient(center top , #C58200, #976300 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #C58200, #976300 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #C58200, #976300 100%) repeat scroll 0% 0% transparent; }';

    styles += 'div.STrChODisabled         {background: -moz-linear-gradient(center top , #5D5D5D, #171717 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #5D5D5D, #171717 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #5D5D5D, #171717 100%) repeat scroll 0% 0% transparent; }';
    styles += 'div.STrChODisabled:hover   {background: -moz-linear-gradient(center top , #5D5D5D, #171717 100%) repeat scroll 0% 0% transparent; background: -webkit-linear-gradient(top , #5D5D5D, #171717 100%) repeat scroll 0% 0% transparent; background: linear-gradient(center top , #5D5D5D, #171717 100%) repeat scroll 0% 0% transparent; }';

    styles += 'div.STrChOContextHidden  {display: none; }';
    styles += 'div.STrChOContextVisible {display: block; }';

    if (STrChOGeneralOptions.usedCityNum && STrChOGeneralOptions.usedCityNum > Seed.cities.length -1 ) STrChOGeneralOptions.usedCityNum = 0;
    if (STrChOGeneralOptions.salvageCityNum && STrChOGeneralOptions.salvageCityNum > Seed.cities.length -1 ) STrChOGeneralOptions.salvageCityNum = 0;

    installThroneHandlerFunctions();  //installHandlerFunctions

    setCities();

    //window.addEventListener('unload', onUnload, false);
    window.addEventListener('beforeunload', onUnload, false);

    CM.cheatDetector.detect = foo;

	AddMainTabLink('Spawn TrChO', eventHideShow, mouseEventTab);

    ThroneAttachTab();

    alterChampHall();

	if (!STrChOGeneralOptions.xPos) STrChOGeneralOptions.xPos=0;
    if (!STrChOGeneralOptions.yPos) STrChOGeneralOptions.yPos=30;

    //mainPop = new STrChOPopup('STrChOMain', 0, 30, true, function (){ tabManager.hideTab(); });
	mainPop = new STrChOPopup ('STrChOMain', STrChOGeneralOptions.xPos, STrChOGeneralOptions.yPos, true, function (){ tabManager.hideTab(); });
	mainPop.getMainDiv().innerHTML = '<STYLE>'+ styles +'</style>';

	tabManager.init (mainPop.getMainDiv());

    if (!STrChOGeneralOptions.hidden) eventHideShow();

    setUpgradeColor();

    STrChOThroneDisplayTimer = setInterval(ThroneUpdateTimerDisplay, 1000);

    ReplaceToolTips();

    uW.STrChOLoaded = true;



}

var foo = function() { };

/*********************************** TABS ***********************************/

Tabs.throneUpgrader = {
	tabOrder: 101,
	tabLabel: 'UPGRADER',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM UPGRADER',
    myDiv: null,
    repairId: 0,
    repairEnd: 0,
    timerH: null,
    clearTimerH: null,
    speedup: 0,
    upgradePath: {
        0: { maxLev: 2, nextQual: 2 },
        1: { maxLev: 2, nextQual: 2 },
        2: { maxLev: 3, nextQual: 4 },
        3: { maxLev: 3, nextQual: 4 },
        4: { maxLev: 4, nextQual: 5 },
        5: { maxLev: 5, nextQual: 6 }
    },

	init: function (div) {
		var t = Tabs.throneUpgrader;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '<div class=STrChOSaveSettings id=STrChOThroneUpgraderSaveSettings title="Save Upgrader Settings"></div><div class=STrChOLoadSettings id=STrChOThroneUpgraderLoadSettings title="Load Upgrader Settings"></div></div>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
		m += '<div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        if (STrChOThroneUpgradeData.active) {
            m += '<td width=33%><input id=STrChOThroneUpgradePower type=button class=STrChOButton value="Upgrader = ON"></td>';
        } else {
            m += '<td width=33%><input id=STrChOThroneUpgradePower type=button class=STrChOButton value="Upgrader = OFF"></td>';
        }
        m += '<td width=33%><div class=divNoWrap><input class=STrChOCheckbox id=STrChOThroneOneItem type=checkbox ' + (STrChOThroneQueueData.oneItem ? ' CHECKED' : '') + '/>Upgrade 1 At A Time</div></td>';
        m += '<td width=33%><div class=divNoWrap align=center id=STrChOThroneAetherDisplay></div></td>';
        m += '</tr>';
        m += '<tr><td colspan=3><hr class=STrChOHRCenter></td></tr>';
        m += '<tr><td colspan=3><div class=indent5 id=STrChOThroneUpgradeStatus><br></div></td></tr>';
        m += '<tr><td colspan=3><div class=indent5 id=STrChOThroneLastResult><br></div></td></tr>';
        m += '</table>';
        m += '</div>';
        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SPEED UPS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';
        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOThroneHourglassLevelSpecific ' + (STrChOThroneUpgradeData.hourglassLevelSpecific ? "CHECKED" : "") + '>Only use hourglass for levels ';
        m += '<select class=STrChOSelect  id=STrChOThroneHourglassLevel>';
        for (i = 1; i < STrChOMaxThroneLevel; i++) m += '<option value=' + i + ' ' + (STrChOThroneUpgradeData.hourglassLevel == i ? 'SELECTED' : '') + '>' + i + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOThroneHourglassQualitySpecific ' + (STrChOThroneUpgradeData.hourglassQualitySpecific ? "CHECKED" : "") + '>Only use hourglass for qualities ';
        m += '<select class=STrChOSelect id=STrChOThroneHourglassQuality>';
        for (i = 1; i <= STrChOMaxThroneQuality-1; i++) m += '<option value=' + i + ' ' + (STrChOThroneUpgradeData.hourglassQuality == i ? 'SELECTED' : '') + '>' + throneCardQualities[i].capitalizeFirstLetter() + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[1] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseSH ' + (STrChOThroneUpgradeData.useSH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[1] + ' (<div class=divNoWrap id=STrChOThroneUseSHLabel><font' + (uW.ksoItems[1].count < 100 ? ' color=red>' : '>') + uW.ksoItems[1].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[2] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseKH ' + (STrChOThroneUpgradeData.useKH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[2] + ' (<div class=divNoWrap id=STrChOThroneUseKHLabel><font' + (uW.ksoItems[2].count < 100 ? ' color=red>' : '>') + uW.ksoItems[2].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[3] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseGH ' + (STrChOThroneUpgradeData.useGH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[3] + ' (<div class=divNoWrap id=STrChOThroneUseGHLabel><font' + (uW.ksoItems[3].count < 100 ? ' color=red>' : '>') + uW.ksoItems[3].count + '</font></div>)</div></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[4] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseMH ' + (STrChOThroneUpgradeData.useMH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[4] + ' (<div class=divNoWrap id=STrChOThroneUseMHLabel><font' + (uW.ksoItems[4].count < 100 ? ' color=red>' : '>') + uW.ksoItems[4].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[5] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseAH ' + (STrChOThroneUpgradeData.useAH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[5] + ' (<div class=divNoWrap id=STrChOThroneUseAHLabel><font' + (uW.ksoItems[5].count < 100 ? ' color=red>' : '>') + uW.ksoItems[5].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[6] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseWH ' + (STrChOThroneUpgradeData.useWH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[6] + ' (<div class=divNoWrap id=STrChOThroneUseWHLabel><font' + (uW.ksoItems[6].count < 100 ? ' color=red>' : '>') + uW.ksoItems[6].count + '</font></div>)</div></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[7] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseDH ' + (STrChOThroneUpgradeData.useDH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[7] + ' (<div class=divNoWrap id=STrChOThroneUseDHLabel><font' + (uW.ksoItems[7].count < 100 ? ' color=red>' : '>') + uW.ksoItems[7].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[8] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneUseEH ' + (STrChOThroneUpgradeData.useEH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[8] + ' (<div class=divNoWrap id=STrChOThroneUseEHLabel><font' + (uW.ksoItems[8].count < 100 ? ' color=red>' : '>') + uW.ksoItems[8].count + '</font></div>)</div></td>';
        m += '<td/>';
        m += '</tr>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOThroneOverrideSpeedUps ' + (STrChOThroneUpgradeData.overrideSpeedUp ? "CHECKED" : "") + '>Override hourglasses by using ';
        m += '<select class=STrChOSelect  id=STrChOThroneSpeedUp>';
        m += '<option value=0>None</option>';
        for (gls in STrChOHourGlassName) m += '<option value=' + gls + ' ' + (STrChOThroneUpgradeData.useSpeedUp == gls ? 'SELECTED' : '') + '>' + STrChOHourGlassName[gls] + '</option>';
        m += '</select> every time</td>';
        m += '</tr>';
        m += '</table>';
        m += '</div>';
        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;BOOST ITEMS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';
        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.useLPS ? "CHECKED" : "") + ' id=STrChOThroneUseLPS><div class=divNoWrap>Lesser Protection Stones (<div class=divNoWrap id=STrChOThroneUseLPSLabel>' + uW.ksoItems[20001].count + '</div>)</div></td>';
        m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.usePS ? "CHECKED" : "") + ' id=STrChOThroneUsePS><div class=divNoWrap>Protection Stones (<div class=divNoWrap id=STrChOThroneUsePSLabel>' + uW.ksoItems[20002].count + '</div>)</div></td>';
        m += '<td/>';
        m += '</tr>';
        m += '<tr>';
        //m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.useLORB ? "CHECKED" : "") + ' id=trUseLORB><div style="white-space:nowrap;display:inline-block;">Lesser Mystic Orb (<div style="white-space:nowrap;display:inline-block;" id=trUseLORBLabel>' + Seed.items['i20003'] + '</div>)</div></td>';
        m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.useORB ? "CHECKED" : "") + ' id=STrChOThroneUseORB><div class=divNoWrap>Mystic Orb (<div class=divNoWrap id=STrChOThroneUseORBLabel>' + uW.ksoItems[20004].count + '</div>)</div></td>';
        m += '<td/>';
        m += '<td>Quality <select class=STrChOSelect  id=STrChOThroneUseQuality>';
        for (i = 0; i <= STrChOMaxThroneQuality-1; i++) m += '<option value="' + i + '" ' + (STrChOThroneUpgradeData.useQuality == i ? 'SELECTED' : '')  + '>' + throneCardQualities[i].capitalizeFirstLetter() + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.useLLT ? "CHECKED" : "") + ' id=STrChOThroneUseLLT><div class=divNoWrap>Lesser Tokens (<div class=divNoWrap id=STrChOThroneUseLLTLabel>' + uW.ksoItems[20005].count + '</div>)</div></td>';
        m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.useLT ? "CHECKED" : "") + ' id=STrChOThroneUseLT><div class=divNoWrap>Lucky Tokens (<div class=divNoWrap id=STrChOThroneUseLTLabel>' + uW.ksoItems[20006].count + '</div>)</div></td>';
        m += '<td>Level <select class=STrChOSelect  id=STrChOThroneUseLevel>';
        for (i = 1; i <= STrChOMaxThroneLevel-1; i++) m += '<option value="' + i + '" ' + (STrChOThroneUpgradeData.useLevel == i ? 'SELECTED' : '') + '>+' + i + '</option>';
        m += '</select> & Higher</td>';
        m += '</tr>';

        m += '<tr><td colspan=3>';
        m += '<input class=STrChOCheckbox id=STrChOThroneUseAutoTokens type=checkbox ' + (STrChOThroneUpgradeData.useAutoTokens ? 'CHECKED ' : '') + '/> Use Auto Masters Upgrade When Min Level ';
        m += '<select id=STrChOThroneUseAutoTokensMin class=STrChOSelect>';
        for (var lvl = 0; lvl < STrChOMaxThroneLevel; lvl++) m += '<option value="' + lvl + '" ' + (STrChOThroneUpgradeData.useAutoTokensMin == lvl ? 'SELECTED ' : '') + '>+' + lvl + '</option>';
        m += '</select> & Max Level ';
        m += '<select id=STrChOThroneUseAutoTokensMax class=STrChOSelect>';
        for (var lvl = 0; lvl < STrChOMaxThroneLevel; lvl++) m += '<option value="' + lvl + '" ' + (STrChOThroneUpgradeData.useAutoTokensMax == lvl ? 'SELECTED ' : '') + '>+' + lvl + '</option>';
        m += '</select>';
        m += '</td></tr> ';

        m += '</table>';
        m += '</div>';
        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;UPGRADE ITEMS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';
        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        m += '<td colspan=4>Enhance All Quality <select class=STrChOSelect id=STrChOThroneEnhanceAllQuality>';
        for (i = 0; i <= STrChOMaxThroneQuality-1; i++) m += '<option value="' + i + '">' + throneCardQualities[i].capitalizeFirstLetter() + '</option>';
        m += '</select> To Quality <select class=STrChOSelect id=STrChOThroneEnhanceAllQualityTo>';
        for (i = 1; i <= STrChOMaxThroneQuality; i++) m += '<option value="' + i + '">' + throneCardQualities[i].capitalizeFirstLetter() + '</option>';
        m += '</select>&nbsp;&nbsp;<input class=STrChOButton type=button value="Add" id=STrChOThroneEnhanceAddAllQuality></td>';
        m += '</tr>';
        m += '<tr><td colspan=4>Upgrade All Cards Less To Level <select class=STrChOSelect id=STrChOThroneUpgradeAddAllLevelMaxTo>';
        for (i = 1; i <= STrChOMaxThroneLevel; i++) m += '<option value="' + i + '"> +' + i + '</option>';
        m += '</select>&nbsp;&nbsp;<input class=STrChOButton type=button value="Add" id=STrChOThroneUpgradeAddAllLevelMax></td></tr>';
        m += '<tr>';
        m += '<td colspan=4>Upgrade All Level <select class=STrChOSelect id=STrChOThroneUpgradeAllLevel>';
        for (i = 0; i <= STrChOMaxThroneLevel-1; i++) m += '<option value="' + i + '"> +' + i + '</option>';
        m += '</select> To Level <select class=STrChOSelect id=STrChOThroneUpgradeAllLevelTo>';
        for (i = 1; i <= STrChOMaxThroneLevel; i++) m += '<option value="' + i + '"> +' + i + '</option>';
        m += '</select>&nbsp;&nbsp;<input class=STrChOButton type=button value="Add" id=STrChOThroneUpgradeAddAllLevel></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td class=divNoWrap>Item: <select class=STrChOSelect style="white-space:nowrap;display:inline-block;max-width: 200px;" id=STrChOThroneUpgradeList>';
        m += '<option value="0">--Items--</option>';
        for (ThroneID in uW.kocThroneItems) {
            var throne_item = uW.kocThroneItems[ThroneID];
            m += '<option value="' + ThroneID + '">' + throne_item.name + '</option>';
        }
        m += '</select>&nbsp;';
        m += 'Action: <select class=STrChOSelect style="white-space:nowrap;display:inline-block;" id=STrChOThroneAction>';
        m += '<option value="upgrade">Upgrade</option>';
        m += '<option value="enhance">Enhance</option>';
        m += '<option value="both">Both</option>';
        m += '</select>&nbsp;';
        m += '<div class=divNoWrap id=STrChOThroneMaxDiv></div>&nbsp;';
        m += '<input class=STrChOButton id=STrChOThroneQueueAdd type=button value="Add"/>';
        m += '</td>';
        m += '</tr>';
        m += '</table>';
        m += '</div>';
        m += '<div class=STrChOHeader>UPGRADE LIST</div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td colspan=4>';
        m += '<div id=STrChOThroneQScroll style="position: static; width: 100%; height: 340px; overflow-x: auto; overflow-y: auto;">';
        m += '<div id=STrChOThroneQDiv></div>';
        m += '</div>';
        m += '</td></tr>';
        m += '<tr><td colspan=4><input class=STrChOButton style="float: left;" id=STrChOThroneClearQ type=button value="Clear Queue"></tr>';
        m += '</table>';
        m += '</div>';
        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOThroneUpgraderSaveSettings').addEventListener('click', function () {
            SaveSettingsToFile(STrChOThroneUpgradeData);
        }, false);
        document.getElementById('STrChOThroneUpgraderLoadSettings').addEventListener('click', function () {
            var loader = document.getElementById('STrChOSettingsFile');
            loader.addEventListener('change', function () {
                LoadSettingsFromFile(STrChOThroneUpgradeData, Tabs.throneUpgrader);
            }, false);
            loader.click();
        }, false);

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        document.getElementById('STrChOThroneUseAutoTokens').addEventListener('change', function () {
            STrChOThroneUpgradeData.useAutoTokens = document.getElementById('STrChOThroneUseAutoTokens').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useAutoTokens) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseAutoTokensMin').addEventListener('change', function () {
            STrChOThroneUpgradeData.useAutoTokensMin = document.getElementById('STrChOThroneUseAutoTokensMin').value;
            SAVESTrChOThroneUpgradeData();
        }, false);

        document.getElementById('STrChOThroneUseAutoTokensMax').addEventListener('change', function () {
            STrChOThroneUpgradeData.useAutoTokensMax = document.getElementById('STrChOThroneUseAutoTokensMax').value;
            SAVESTrChOThroneUpgradeData();
        }, false);


        document.getElementById('STrChOThroneUpgradePower').addEventListener('click', function () {
            t.togglePower(this);
        }, false);

        document.getElementById('STrChOThroneHourglassLevelSpecific').addEventListener('change', function () {
            STrChOThroneUpgradeData.hourglassLevelSpecific = document.getElementById('STrChOThroneHourglassLevelSpecific').checked;
            SAVESTrChOThroneUpgradeData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneHourglassQualitySpecific').addEventListener('change', function () {
            STrChOThroneUpgradeData.hourglassQualitySpecific = document.getElementById('STrChOThroneHourglassQualitySpecific').checked;
            SAVESTrChOThroneUpgradeData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneOverrideSpeedUps').addEventListener('change', function () {
            STrChOThroneUpgradeData.overrideSpeedUp = document.getElementById('STrChOThroneOverrideSpeedUps').checked;
            SAVESTrChOThroneUpgradeData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseWH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useWH = document.getElementById('STrChOThroneUseWH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useWH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseDH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useDH = document.getElementById('STrChOThroneUseDH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useDH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseEH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useEH = document.getElementById('STrChOThroneUseEH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useEH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseSH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useSH = document.getElementById('STrChOThroneUseSH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useSH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseKH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useKH = document.getElementById('STrChOThroneUseKH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useKH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseGH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useGH = document.getElementById('STrChOThroneUseGH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useGH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseMH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useMH = document.getElementById('STrChOThroneUseMH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useMH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseAH').addEventListener('change', function () {
            STrChOThroneUpgradeData.useAH = document.getElementById('STrChOThroneUseAH').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useAH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseQuality').addEventListener('change', function () {
            STrChOThroneUpgradeData.useQuality = document.getElementById('STrChOThroneUseQuality').value;
            SAVESTrChOThroneUpgradeData();
        }, false);

        document.getElementById('STrChOThroneUseLevel').addEventListener('change', function () {
            STrChOThroneUpgradeData.useLevel = document.getElementById('STrChOThroneUseLevel').value;
            SAVESTrChOThroneUpgradeData();
        }, false);

        document.getElementById('STrChOThroneSpeedUp').addEventListener('change', function () {
            STrChOThroneUpgradeData.useSpeedUp = document.getElementById('STrChOThroneSpeedUp').value;
            SAVESTrChOThroneUpgradeData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneHourglassLevel').addEventListener('change', function () {
            STrChOThroneUpgradeData.hourglassLevel = document.getElementById('STrChOThroneHourglassLevel').value;
            SAVESTrChOThroneUpgradeData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneHourglassQuality').addEventListener('change', function () {
            STrChOThroneUpgradeData.hourglassQuality = document.getElementById('STrChOThroneHourglassQuality').value;
            SAVESTrChOThroneUpgradeData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseORB').addEventListener('change', function () {
            STrChOThroneUpgradeData.useORB = document.getElementById('STrChOThroneUseORB').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useORB) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseLPS').addEventListener('change', function () {
            STrChOThroneUpgradeData.useLPS = document.getElementById('STrChOThroneUseLPS').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useLPS) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUsePS').addEventListener('change', function () {
            STrChOThroneUpgradeData.usePS = document.getElementById('STrChOThroneUsePS').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.usePS) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseLT').addEventListener('change', function () {
            STrChOThroneUpgradeData.useLT = document.getElementById('STrChOThroneUseLT').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useLT) t.doAction();
        }, false);

        document.getElementById('STrChOThroneUseLLT').addEventListener('change', function () {
            STrChOThroneUpgradeData.useLLT = document.getElementById('STrChOThroneUseLLT').checked;
            SAVESTrChOThroneUpgradeData();
            if (STrChOThroneUpgradeData.useLLT) t.doAction();
        }, false);

        document.getElementById('STrChOThroneQueueAdd').addEventListener('click', function () {
            t.addThroneQueue();
        }, false);

        document.getElementById('STrChOThroneOneItem').addEventListener('change', function () {
            STrChOThroneQueueData.oneItem = document.getElementById('STrChOThroneOneItem').checked;
            SAVESTrChOThroneQueueData();
        });

        document.getElementById('STrChOThroneClearQ').addEventListener('click', function () {
            STrChOThroneQueueData.list = [];
            SAVESTrChOThroneQueueData();
            t.buildThroneQueueDisplay();
        }, false);

        document.getElementById('STrChOThroneEnhanceAddAllQuality').addEventListener('click', function () {
            var low_level = parseInt(document.getElementById('STrChOThroneEnhanceAllQuality').value);
            var high_level = parseInt(document.getElementById('STrChOThroneEnhanceAllQualityTo').value);
            if (low_level >= high_level) return;
            for (ThroneId in uW.kocThroneItems) {
                var ThroneItem = uW.kocThroneItems[ThroneId];
                if (ThroneItem.quality == low_level) {
                    var qItem = new QueueItem();
                    qItem.item = ThroneId;
                    qItem.action = "enhance"
                    qItem.level = high_level
                    STrChOThroneQueueData.list.push(qItem);
                }
            }
            SAVESTrChOThroneQueueData();
            t.buildThroneQueueDisplay();
        }, false);

        document.getElementById('STrChOThroneUpgradeAddAllLevelMax').addEventListener('click', function () {
            var high_level = parseInt(document.getElementById('STrChOThroneUpgradeAddAllLevelMaxTo').value);
            for (ThroneId in uW.kocThroneItems) {
                var ThroneItem = uW.kocThroneItems[ThroneId];
                if (ThroneItem.level < high_level) {
                    var qItem = new QueueItem();
                    qItem.item = ThroneId;
                    qItem.action = "upgrade"
                    qItem.level = high_level
                    STrChOThroneQueueData.list.push(qItem);
                }
            }
            SAVESTrChOThroneQueueData();
            t.buildThroneQueueDisplay();
        }, false);

        document.getElementById('STrChOThroneUpgradeAddAllLevel').addEventListener('click', function () {
            var low_level = parseInt(document.getElementById('STrChOThroneUpgradeAllLevel').value);
            var high_level = parseInt(document.getElementById('STrChOThroneUpgradeAllLevelTo').value);

            if (low_level >= high_level) return;
            for (ThroneId in uW.kocThroneItems) {
                var ThroneItem = uW.kocThroneItems[ThroneId];
                if (ThroneItem.level == low_level) {
                    var qItem = new QueueItem();
                    qItem.item = ThroneId;
                    qItem.action = "upgrade"
                    qItem.level = high_level
                    STrChOThroneQueueData.list.push(qItem);
                }
            }
            SAVESTrChOThroneQueueData();
            t.buildThroneQueueDisplay();
        }, false);

        document.getElementById('STrChOThroneAction').addEventListener('change', function () {
            t.buildThroneLevelWidget();
        }, false);

        // wait for the current repair to finish before starting
        if (STrChOThroneUpgradeData.active)
            t.setStatus("Loading ....");
        else
            t.setStatus("Powered Off");

        t.startTimer();

        t.buildThroneLevelWidget();

        t.refreshAetherDisplay();

        t.buildThroneQueueDisplay();

	},

    startTimer: function () {
        var t = Tabs.throneUpgrader;
        var delay = 2 + Math.random() * 8;
        if (Seed.queue_throne != null && Seed.queue_throne.end != null) {
            var repairTimeLeft = Seed.queue_throne.end - unixTime();
            t.repairEnd = Seed.queue_throne.end;
            t.repairId = Seed.queue_throne.itemId;
            var n = new Date(t.repairEnd * 1000);

            var throne_item = uW.kocThroneItems[t.repairId];

            t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + throne_item.name);
            if (STrChOThroneUpgradeData.useSH || STrChOThroneUpgradeData.useKH || STrChOThroneUpgradeData.useGH || STrChOThroneUpgradeData.useMH || STrChOThroneUpgradeData.useAH || STrChOThroneUpgradeData.useWH || STrChOThroneUpgradeData.useDH || STrChOThroneUpgradeData.useEH || (STrChOThroneUpgradeData.overrideSpeedUp && STrChOThroneUpgradeData.useSpeedUp > 0)) {
                var throneQuality = throne_item.quality;
                var throneLevel = throne_item.level;
                var useThoseSpeedups = true;
                if (STrChOThroneUpgradeData.hourglassQualitySpecific && throneQuality < STrChOThroneUpgradeData.hourglassQuality) useThoseSpeedups = false;
                if (STrChOThroneUpgradeData.hourglassLevelSpecific && throneLevel < STrChOThroneUpgradeData.hourglassLevel) useThoseSpeedups = false;
                if (STrChOThroneUpgradeData.overrideSpeedUp) useThoseSpeedups = true;
                if (useThoseSpeedups) {
                    setTimeout(function () { t.doSpeedup(); }, 2000);
                }
            }
            setTimeout(t.clearRepair, (repairTimeLeft + 1) * 1000);
            if (repairTimeLeft > 0) delay += repairTimeLeft;
        }

        if (t.timerH == null)
            t.timerH = setTimeout(t.doAction, delay * 1000);
    },

	hide: function () {},

    refreshAetherDisplay : function () {
        document.getElementById('STrChOThroneAetherDisplay').innerHTML = displayCityAstone();
    },

	show: function () {
		var t = Tabs.throneUpgrader;
        t.startTimer();
        t.refreshAetherDisplay();
        t.buildThroneQueueDisplay();
	},

    doAction: function () {
        var t = Tabs.throneUpgrader;
        if (STrChOThroneRepairData.active) {
            t.setStatus('Waiting for repair tab to finish...');
            return;
        }
        var retryTime = STrChOGeneralOptions.retryInterval;

        try { // check if repair is done
            var ti = t.clearRepair();
            if (ti <= 0) { // repair is done
                if (STrChOThroneQueueData.oneItem || (STrChOThroneQueueData.doingRepairs == true)) {
                    for (queueItems in STrChOThroneQueueData.list) {
                        var qItem = STrChOThroneQueueData.list[queueItems];
                        if (!qItem) continue;
                        var throneItem = uW.kocThroneItems[qItem.item];

                        if ((throneItem == null) || (STrChOThroneQueueData.list[queueItems].status == "complete")) continue;

                        if (throneItem.isBroken) {
                            t.doRepair(throneItem.id);
                            clearTimeout(t.timerH);
                            t.timerH = setTimeout(t.doAction, retryTime * 1000);
                            return;
                        } else if (STrChOThroneQueueData.oneItem) {
                            break;
                        }
                    }
                }
                STrChOThroneQueueData.doingRepairs = false; // all repairs complete
                t.selectNext();  // set the index
                SAVESTrChOThroneQueueData();
                // if we reach the end of the queue, start repair cycle
                if (STrChOThroneQueueData.index < 0) {
                    t.setStatus("Reached end of queue.")
                    t.setResult("");
                    if (!STrChOThroneUpgradeData.active) t.setStatus("Powered Off");
                    STrChOThroneQueueData.doingRepairs = true;
                    SAVESTrChOThroneQueueData();
                    clearTimeout(t.timerH);
                    t.timerH = setTimeout(t.doAction, retryTime * 1000);
                    return;
                }
                // upgrade/enhance next item
                var qItem = STrChOThroneQueueData.list[STrChOThroneQueueData.index];

                if (qItem) {
                    if (qItem.action == "enhance")
                        t.doEnhance(qItem.item);
                    else
                        t.doUpgrade(+qItem.item, false);
                }
            } else {
                // come back after repair is complete
                retryTime = ti + 5;
                var n = new Date(t.repairEnd * 1000);
                t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + uW.kocThroneItems[t.repairId].name);
                if (STrChOThroneUpgradeData.useSH || STrChOThroneUpgradeData.useKH || STrChOThroneUpgradeData.useGH || STrChOThroneUpgradeData.useMH || STrChOThroneUpgradeData.useAH || STrChOThroneUpgradeData.useWH || STrChOThroneUpgradeData.useDH || STrChOThroneUpgradeData.useEH || (STrChOThroneUpgradeData.overrideSpeedUp && STrChOThroneUpgradeData.useSpeedUp > 0)) {
                    var throneItem = uW.kocThroneItems[t.repairId];
                    var trQuality = throneItem.quality;
                    var trLevel = throneItem.level;
                    var useThoseSpeedups = true;
                    if (STrChOThroneUpgradeData.hourglassQualitySpecific && trQuality < STrChOThroneUpgradeData.hourglassQuality) useThoseSpeedups = false;
                    if (STrChOThroneUpgradeData.hourglassLevelSpecific && trLevel < STrChOThroneUpgradeData.hourglassLevel) useThoseSpeedups = false;
                    if (STrChOThroneUpgradeData.overrideSpeedUp) useThoseSpeedups = true;
                    if (useThoseSpeedups) {
                        setTimeout(function () { t.doSpeedup(); }, 2000);
                    }
                    retryTime = 1;
                }
            }
            CM.ThroneView.renderInventory(uW.kocThroneItems);
        } catch (e) {
        }
        // recycle
        clearTimeout(t.timerH);
        t.timerH = setTimeout(t.doAction, retryTime * 1000);
    },

    doSpeedup: function () {
        var t = Tabs.throneUpgrader;

        var endTime = t.repairEnd;
        var startTime = unixTime();
        var secondsForRepair = endTime - startTime;
        var divId = "";

        t.speedup = 0;

        if (secondsForRepair > 0 && STrChOThroneUpgradeData.overrideSpeedUp && STrChOThroneUpgradeData.useSpeedUp > 0) {
            t.speedup = STrChOThroneUpgradeData.useSpeedUp;
        } else {
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.day25 && STrChOThroneUpgradeData.useEH && uW.ksoItems[8].count > 0) { t.speedup = 8; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour24 && STrChOThroneUpgradeData.useDH && uW.ksoItems[7].count > 0) { t.speedup = 7; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour15 && STrChOThroneUpgradeData.useWH && uW.ksoItems[6].count > 0) { t.speedup = 6; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour8 && STrChOThroneUpgradeData.useAH && uW.ksoItems[5].count > 0) { t.speedup = 5; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && STrChOThroneUpgradeData.useMH && uW.ksoItems[4].count > 0) { t.speedup = 4; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && STrChOThroneUpgradeData.useGH && uW.ksoItems[3].count > 0) { t.speedup = 3; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && STrChOThroneUpgradeData.useKH && uW.ksoItems[2].count > 0) { t.speedup = 2; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && STrChOThroneUpgradeData.useSH && uW.ksoItems[1].count > 0) { t.speedup = 1; }
        }
        switch (t.speedup) {
            case "1":
            case 1:
                secondsForRepair -= HOURGLASSES_TIME.minute1;
                divId = 'STrChOThroneUseSHLabel';
                break;
            case "2":
            case 2:
                secondsForRepair -= HOURGLASSES_TIME.minute15;
                divId = 'STrChOThroneUseKHLabel';
                break;
            case "3":
            case 3:
                secondsForRepair -= HOURGLASSES_TIME.hour1;
                divId = 'STrChOThroneUseGHLabel';
                break;
            case "4":
            case 4:
                secondsForRepair -= HOURGLASSES_TIME.hour25;
                divId = 'STrChOThroneUseMHLabel';
                break;
            case "5":
            case 5:
                secondsForRepair -= HOURGLASSES_TIME.hour8;
                divId = 'STrChOThroneUseAHLabel';
                break;
            case "6":
            case 6:
                secondsForRepair -= HOURGLASSES_TIME.hour15;
                divId = 'STrChOThroneUseWHLabel';
                break;
            case "7":
            case 7:
                secondsForRepair -= HOURGLASSES_TIME.hour24;
                divId = 'STrChOThroneUseDHLabel';
                break;
            case "8":
            case 8:
                secondsForRepair -= HOURGLASSES_TIME.day25;
                divId = 'STrChOThroneUseEHLabel';
                break;
        }

        if (t.speedup != 0) {
            t.setResult('Used ' + uW.ksoItems[t.speedup].name);
            var divCount = uW.ksoItems[t.speedup].count - 1;
            var divSpeedups = document.getElementById(divId);
            divSpeedups.innerHTML = divCount;
            uW.modal_speedup_apply("throne", t.speedup, t.repairId);

            if (secondsForRepair <= 0) {
                secondsForRepair = 0;
                endTime = startTime;
                t.clearTimerH = setTimeout(t.clearRepair, 1000);
                t.buildThroneQueueDisplay();
            } else {
                endTime = unixTime() + secondsForRepair;
                t.repairEnd = endTime;
                var n = new Date(t.repairEnd * 1000);
                var item = uW.kocThroneItems[t.repairId];
                t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + item.name);
                t.clearTimerH = setTimeout(t.clearRepair, secondsForRepair * 1000);
                t.buildThroneQueueDisplay();
            }
            t.repairEnd = endTime;
            setTimeout(function () { t.doSpeedup(); }, 1000);
        }
    },

    selectNext: function () {

        if (STrChOThroneQueueData.index >= STrChOThroneQueueData.list.length) STrChOThroneQueueData.index = 0;
        if (STrChOThroneQueueData.index < 0) STrChOThroneQueueData.index = 0;
        // for single item mode, always start from the top
        if (STrChOThroneQueueData.oneItem) STrChOThroneQueueData.index = 0;
        var l = STrChOThroneQueueData.list.length;
        for (i = STrChOThroneQueueData.index; i < l; i++) {
            var item = STrChOThroneQueueData.list[i];
            if (!item) continue;
            var throneItem = uW.kocThroneItems[item.item];
            if ((STrChOThroneQueueData.list[i].status != "complete") && (throneItem != null) && (!throneItem.isBroken)) {
                if (((item.action == "enhance") && (item.level <= throneItem.quality)) || ((item.action == "upgrade") && (item.level <= throneItem.level))) {
                    item.status = "complete";
                } else {
                    STrChOThroneQueueData.index = i;
                    return;
                }
            }
        }
        STrChOThroneQueueData.index = -1; // if we get here, the queue is complete
    },

    doEnhance: function (eItem) {
        var t = Tabs.throneUpgrader;
        try {
            if (STrChOThroneUpgradeData.active == false || eItem == 0) {
                t.setStatus("Powered Off");
                return;
            }
            var throne_item = uW.kocThroneItems[eItem];

            if (!throne_item) return;

            if (throne_item.isBroken) {
                // repair and then try again later
                t.doRepair(eItem);
                return;
            }

            var num_city = pickAetherUseCity();
            if (num_city < 0) {
                t.setStatus("Not enough aetherstones to enhance.  Minimum of " + STrChOGeneralOptions.minStones + " needed.  Waiting for more ...");
                return;
            }

            var t_city = uW.currentcityid;
            uW.currentcityid = Seed.cities[num_city][0];
            var w = CM.ThronePanelController.calcCost("enhance", throne_item, null, "stones");
            uW.currentcityid = t_city;

            if ((w.gems.use > 0) || (w.stones.total > parseInt(Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0]))) {
                t.setStatus("Not enough aetherstones to enhance.");
                return;
            }

            var qI = STrChOThroneQueueData.list[STrChOThroneQueueData.index];
            if (qI) {
                qI.triesTotal++;
                qI.triesThis++;
            }

            var buffItemId = 0;

            var useDiv = '';

            if (STrChOThroneUpgradeData.active && STrChOThroneQueueData.index != -1 && STrChOThroneUpgradeData.useQuality <= throne_item.quality) {
                if (STrChOThroneUpgradeData.useORB) {
                    if (Seed.items['i20004'] > 0) {
                        buffItemId = 20004;
                        useDiv = 'STrChOThroneUseORBLabel';
                    }
                }
                /*      if (TRupgradeData.useLORB) {
                if (Seed.items['i20003'] > 0) buffItemId = 20003;
                } */
                if (STrChOThroneUpgradeData.usePS) {
                    if (Seed.items['i20002'] > 0) {
                        buffItemId = 20002;
                        useDiv = 'STrChOThroneUsePSLabel';
                    }
                }
                if (STrChOThroneUpgradeData.useLPS) {
                    if (Seed.items['i20001'] > 0) {
                        buffItemId = 20001;
                        useDiv = 'STrChOThroneUseLPSLabel';
                    }
                }
                if (buffItemId) CM.InventoryView.removeItemFromInventory(buffItemId);
            }

            if (useDiv != '') document.getElementById(useDiv).innerHTML = uW.ksoItems[buffItemId].count;

            var params = uW.Object.clone(ajfx);
            params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
            params.action = 'upgradeQuality';
            params.throneRoomItemId = eItem;

            params.payment = "aetherstone";
            params.buffItemId = buffItemId;
            params.cityId = Seed.cities[num_city][0];

            t.setStatus("Sending enhance request");
            new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                loading: true,
                onSuccess: function (transport) {
                    try {
                        var rslt = eval("(" + transport.responseText + ")");
                        if (rslt.updateSeed) uW.update_seed(rslt.updateSeed);
                        if (rslt.ok) {
                            Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] = Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] - rslt.aetherstones;
                            if (rslt.gems > 0) {
                                ActionLog('Upgrader accidentally spent gems!  Upgrader turned off');
                                t.setStatus("Error ... shutting down");
                                STrChOThroneUpgradeData.active = false;
                                SAVESTrChOThroneUpgradeData();
                            }

                            throne_item.level = rslt.item.level;
                            throne_item.quality = rslt.item.quality
                            throne_item.status = rslt.item.status;

                            if (rslt.success) {
                                throne_item.name = throne_item.createName();
                                STrChOThroneUpgradeStats.enhanceSuccess[throne_item.quality - 1][throne_item.level]++;
                                SAVESTrChOThroneUpgradeStats();
                                t.setResult("Enhance successful.  " + addCommas(rslt.aetherstones) + " aetherstones used.");
                                t.refreshAetherDisplay();
                                t.setStatus("Attempting next action");
                                CM.sounds.play("tr_success_build");
                                // update the cost line
                                var qItem = STrChOThroneQueueData.list[STrChOThroneQueueData.index];
                                if (qItem) {
                                    var now = new Date();
                                    qItem.lastUpgrade = "Enhanced to " +  throneCardQualities[throne_item.quality] + " " + now.toDateString().substring(3, 10) + " " + now.toTimeString().substring(0, 8) + " in " + qItem.triesThis + " attempts";
                                    if (!qItem.upgrades) qItem.upgrades = [];
                                    qItem.upgrades.push(qItem.lastUpgrade);
                                    var msg = 'Enhanced ' + uW.kocThroneItems[eItem].name + ' [ ' + eItem + '] to quality ' + rslt.item.quality + " in " + qItem.triesThis + " attempts. " + qItem.triesTotal + " total attempts for this item.";
                                    if (STrChOGeneralOptions.whisperToMe) sendChat("/" + Seed.player.name + ' ' + msg);
                                    if (STrChOGeneralOptions.sendToInbox) sendComposedMail(Seed.player.name, 'THRONE: Enhance Success : ' + uW.kocThroneItems[eItem].name, msg);
                                    SuccessLog(msg);
                                    if (qItem.level <= throne_item.quality) {
                                        qItem.status = "complete";
                                        STrChOThroneUpgradeData.newUpgradeState = 2;
                                    }
                                    else {
                                        var now = new Date();
                                        qItem.status = "Partially enhanced";
                                        qItem.triesLast = qItem.triesThis;
                                        qItem.triesThis = 0;
                                        if (STrChOThroneUpgradeData.newUpgradeState != 2) STrChOThroneUpgradeData.newUpgradeState = 1;
                                    }
                                    SAVESTrChOThroneUpgradeData();
                                    setUpgradeColor();
                                }
                            }
                            else {
                                STrChOThroneUpgradeStats.enhanceFailure[throne_item.quality][throne_item.level]++;
                                SAVESTrChOThroneUpgradeStats();
                                ActionLog('Enhance failed.  Throne Room item ' + uW.kocThroneItems[eItem].name + (buffItemId > 0 ? ' - (' + Seed.items['i' + buffItemId] + ' ' + uW.itemlist['i' + buffItemId].name + ' remaining)' : ''));
                                if (rslt["break"]) {
                                    throne_item.isBroken = true;
                                    throne_item.brokenType = "quality";
                                    throne_item.name = throne_item.createName();
                                }
                                t.setResult("Enhance failed.  " + addCommas(rslt.aetherstones) + " aetherstones used");
                                t.refreshAetherDisplay();
                                var qItem = STrChOThroneQueueData.list[STrChOThroneQueueData.index];
                                if (qItem) if (qItem.status == "not started") qItem.status = "started";
                            }
                            CM.ThroneView.renderInventory(uW.kocThroneItems);
                            SAVESTrChOThroneQueueData();
                            t.buildThroneQueueDisplay();
                            clearTimeout(t.timerH);
                            t.timerH = setTimeout(t.doAction, 10 * 1000);
                        }
                        else {
                            t.setStatus("Unable to enhance at this time ... waiting for next cycle");

                        }
                    } catch (e) {

                    }
                    return;
                },
                onFailure: function (rst) {
                    t.setStatus("Unable to send enhance request.  Waiting for next cycle");
                    return;
                }
            });
        } catch (e) {

        }
        return;
    },

    doUpgrade: function (uItemId, bypass) {
        var t = Tabs.throneUpgrader;

        var throne_item = uW.kocThroneItems[uItemId];

        if (uItemId == 0 || throne_item == null) {
            t.setStatus("Item not found.");
            return;
        }

        if ((STrChOThroneUpgradeData.active == false) && (bypass != true)) {
            t.setStatus("Powered Off");
            return;
        }

        if (bypass == true && Tabs.throneSalvager.deleting != true) {
            // delete cycle has been canceled.  Don't upgrade this item
            return;
        }

        if (throne_item.isBroken) {
            // repair and then try again later
            t.doRepair(uItemId);
            return;
        }

        var num_city = pickAetherUseCity();
        if (num_city < 0) {
            t.setStatus("Not enough aetherstones to upgrade.  Minimum of " + STrChOGeneralOptions.minStones + " needed.  Waiting for more ...");
            return;
        }

        var t_city = uW.currentcityid;
        uW.currentcityid = Seed.cities[num_city][0];
        var w = CM.ThronePanelController.calcCost("upgrade", throne_item, null, "stones");
        uW.currentcityid = t_city;

        if ((w.gems.use > 0) || (w.stones.total > parseInt(Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0]))) {
            t.setStatus("Not enough aetherstones to upgrade.");
            return;
        }

        if (bypass != true) {
            var qI = STrChOThroneQueueData.list[STrChOThroneQueueData.index];
            if (qI) {
                qI.triesTotal++;
                qI.triesThis++;
            }

            t.setStatus("Sending upgrade request ...");
        }

        var buffItemId = 0;

        var useDiv = '';

        if (STrChOThroneUpgradeData.active && STrChOThroneQueueData.index != -1 && STrChOThroneUpgradeData.useLevel <= throne_item.level) {

            if (STrChOThroneUpgradeData.useLT) {
                if (Seed.items['i20006'] > 0) {
                    buffItemId = 20006;
                    useDiv = 'STrChOThroneUseLTLabel';
                }
            }

            if (STrChOThroneUpgradeData.useLLT) {
                if (Seed.items['i20005'] > 0) {
                    buffItemId = 20005;
                    useDiv = 'STrChOThroneUseLLTLabel';
                }
            }

            if (STrChOThroneUpgradeData.usePS) {
                if (Seed.items['i20002'] > 0) {
                    buffItemId = 20002;
                    useDiv = 'STrChOThroneUsePSLabel';
                }
            }

            if (STrChOThroneUpgradeData.useLPS) {
                if (Seed.items['i20001'] > 0) {
                    buffItemId = 20001;
                    useDiv = 'STrChOThroneUseLPSLabel';
                }
            }

        }

        if (STrChOThroneUpgradeData.useAutoTokens) {
            if (STrChOThroneUpgradeData.useAutoTokensMin <= STrChOThroneUpgradeData.useAutoTokensMax) {
                var throneLevel = throne_item.level;
                if (throneLevel >= STrChOThroneUpgradeData.useAutoTokensMin &&
                    throneLevel < STrChOThroneUpgradeData.useAutoTokensMax) {
                    var nextMastersID = getNextAvailableMasters(throne_item);
                    if (nextMastersID != 0) {
                        buffItemId = nextMastersID;
                        ActionLog('Using ' + uW.ksoItems[buffItemId].name + ' on item: ' + throne_item.name);
                    }
                }
            }
        }

        if (buffItemId) CM.InventoryView.removeItemFromInventory(buffItemId);

        if (useDiv != '') document.getElementById(useDiv).innerHTML = uW.ksoItems[buffItemId].count;

        var params = uW.Object.clone(ajfx);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'upgradeLevel';
        params.throneRoomItemId = uItemId;
        params.buffItemId = buffItemId;
        params.payment = "aetherstone";
        params.cityId = Seed.cities[num_city][0];


        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                try {

                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {

                        if (rslt.updateSeed) uW.update_seed(rslt.updateSeed);

                        Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] = Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] - rslt.aetherstones;

                        if (rslt.gems > 0) {
                            t.setStatus("Error .... Shutting down.");
                            ActionLog('Upgrader accidentally spent gems!  Upgrader turned off');
                            STrChOThroneUpgradeData.active = false;
                            SAVESTrChOThroneUpgradeData();
                        }

                        if (rslt.success) {
                            throne_item.level = rslt.item.level;
                            throne_item.quality = rslt.item.quality;
                            throne_item.name = throne_item.createName();

                            if (bypass != true) {
                                t.show();
                                STrChOThroneUpgradeStats.upgradeSuccess[throne_item.quality][throne_item.level - 1]++;
                                SAVESTrChOThroneUpgradeStats();
                                t.setResult("Upgrade successful.  " + addCommas(rslt.aetherstones) + " aetherstones used.");
                                t.refreshAetherDisplay();
                                t.setStatus("Attempting next upgrade");
                                CM.sounds.play("tr_success_build");

                                var qItem = STrChOThroneQueueData.list[STrChOThroneQueueData.index];
                                if (qItem) {
                                    var now = new Date();
                                    qItem.lastUpgrade = "Upgraded to +" + throne_item.level + " " + now.toDateString().substring(3, 10) + " " + now.toTimeString().substring(0, 8) + " in " + qItem.triesThis + " attempts";

                                    if (!qItem.upgrades) qItem.upgrades = [];
                                    qItem.upgrades.push(qItem.lastUpgrade);

                                    var msg = 'Upgraded ' + uW.kocThroneItems[uItemId].name + ' [' + uItemId + '] to level ' + rslt.item.level + " in " + qItem.triesThis + " attempts. " + qItem.triesTotal + " total attempts for this item.";
                                    if (STrChOGeneralOptions.whisperToMe) sendChat("/" + Seed.player.name + ' ' + msg);
                                    if (STrChOGeneralOptions.sendToInbox) sendComposedMail(Seed.player.name, 'THRONE: Upgrade Success : ' + uW.kocThroneItems[uItemId].name, msg);
                                    SuccessLog(msg);
                                    if (qItem.level <= throne_item.level) {
                                        qItem.status = "complete";
                                        STrChOThroneUpgradeData.newUpgradeState = 2;
                                    }
                                    else {
                                        var now = new Date();
                                        qItem.status = "Partially upgraded";
                                        qItem.triesLast = qItem.triesThis;
                                        qItem.triesThis = 0;
                                        if (STrChOThroneUpgradeData.newUpgradeState != 2) STrChOThroneUpgradeData.newUpgradeState = 1;
                                    }
                                    SAVESTrChOThroneUpgradeData();
                                    setUpgradeColor();
                                }
                            }
                        } else {
                            STrChOThroneUpgradeStats.upgradeFailure[throne_item.quality][throne_item.level]++;
                            SAVESTrChOThroneUpgradeStats();
                            ActionLog('Upgrade failed Throne Room item ' + uW.kocThroneItems[uItemId].name);
                            if (!params.buffItemId) {
                                throne_item.isBroken = true;
                                throne_item.brokenType = "level";
                                throne_item.name = throne_item.createName();
                                throne_item.status = rslt.item.status;
                            }
                            if (bypass != true) {
                                t.setResult("Upgrade failed.  " + addCommas(rslt.aetherstones) + " aetherstones used");
                                t.refreshAetherDisplay();
                                var qItem = STrChOThroneQueueData.list[STrChOThroneQueueData.index];
                                if (qItem.status == "not started") qItem.status = "started";
                            }
                        }
                        CM.ThroneView.renderInventory(uW.kocThroneItems);
                        SAVESTrChOThroneQueueData();
                        t.buildThroneQueueDisplay();
                        clearTimeout(t.timerH);
                        t.timerH = setTimeout(t.doAction, 10 * 1000);
                        if (rslt.heatupModifier) CM.HeatUpModel.attemptCallback(+(rslt.heatupModifier));
                        return;
                    } else {
                        if (bypass != true) {
                            t.setStatus("Upgrade request not accepted.  Waiting for next cycle.");
                        } else {
                            if (rslt.msg && rslt.msg.indexOf("Has status 2") > -1) {
                                // the object is in the locked rows.  Shutdown deleting until the next pass
                                Tabs.throneSalvager.delItems = [];
                                Tabs.throneSalvager.deleting = false;
                            }
                        }
                    }
                } catch (e) {
                }
                return;
            },
            onFailure: function (rrr) {
                t.setStatus("Unable to transmitt upgrade request.  Waiting for next cycle.");
                CM.ThroneView.renderInventory(uW.kocThroneItems);
                return;
            }
        });

        return;
    },




    doRepair: function (rItem) {
        var t = Tabs.throneUpgrader;
        var params = uW.Object.clone(ajfx);

        if (STrChOThroneUpgradeData.active == false || rItem == 0 || uW.kocThroneItems[rItem] == null) return; //repair is turned off

        var theItem = uW.kocThroneItems[rItem];

        params.action = 'timeRepair';
        params.throneRoomItemId = rItem;
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';

        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    var item = uW.kocThroneItems[rItem];
                    var startTime = unixTime();
                    var endTime = rslt.eta;
                    ActionLog('Starting repair for Throne Room item ' + item.name);
                    Seed.queue_throne.itemId = item.id;
                    Seed.queue_throne.start = startTime;
                    Seed.queue_throne.end = endTime;
                    t.repairId = item.id;
                    t.repairEnd = endTime;
                    var n = new Date(t.repairEnd * 1000);
                    t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + item.name);
                    var secondsForRepair = t.repairEnd - startTime;
                    if (secondsForRepair < 0) secondsForRepair = 0;
                    CM.ThroneView.renderInventory(uW.kocThroneItems);
                    t.clearTimerH = setTimeout(t.clearRepair, (secondsForRepair + 1) * 1000);
                    t.buildThroneQueueDisplay();
                    if (STrChOThroneUpgradeData.useSH || STrChOThroneUpgradeData.useKH || STrChOThroneUpgradeData.useGH || STrChOThroneUpgradeData.useMH || STrChOThroneUpgradeData.useAH || STrChOThroneUpgradeData.useWH || STrChOThroneUpgradeData.useDH || STrChOThroneUpgradeData.useEH || (STrChOThroneUpgradeData.overrideSpeedUp && STrChOThroneUpgradeData.useSpeedUp > 0)) {
                        var throneItem = uW.kocThroneItems[t.repairId];
                        var trQuality = throneItem.quality;
                        var trLevel = throneItem.level;
                        var useThoseSpeedups = true;
                        if (STrChOThroneUpgradeData.hourglassQualitySpecific && trQuality < STrChOThroneUpgradeData.hourglassQuality) useThoseSpeedups = false;
                        if (STrChOThroneUpgradeData.hourglassLevelSpecific && trLevel < STrChOThroneUpgradeData.hourglassLevel) useThoseSpeedups = false;
                        if (STrChOThroneUpgradeData.overrideSpeedUp) useThoseSpeedups = true;
                        if (useThoseSpeedups) {
                            setTimeout(function () { t.doSpeedup(); }, 2000);
                        }
                    }
                }
                else {
                    if (rslt.msg == "Item is not broken") {
                        uW.kocThroneItems[rItem].isBroken = false;
                        t.clearRepair();
                    }

                    // regrab the end times in case this is caused by a manual repair
                    if (Seed.queue_throne && Seed.queue_throne.end && Seed.queue_throne.itemId) {
                        t.repairEnd = Seed.queue_throne.end;
                        t.repairId = Seed.queue_throne.itemId;
                    }
                }
                return;
            },
            onFailure: function (ttt) {
                // this usually means a repair is in progress (such as a manual repair). Grab the seed data (if possible)
                if (Seed.queue_throne && Seed.queue_throne.end) {
                    t.repairEnd = Seed.queue_throne.end;
                    t.repairId = Seed.queue_throne.itemId;
                }
                return;
            }
        });
        return;
    },

    clearRepair: function () {
        var t = Tabs.throneUpgrader;
        var timeUntilDone = 0;

        if (t.repairEnd == 0) {
            return timeUntilDone;
        }
        timeUntilDone = t.repairEnd - unixTime();

        if (timeUntilDone <= 0) {
            if (t.repairId != 0 && uW.kocThroneItems[t.repairId] != null) {
                if (uW.kocThroneItems[t.repairId].isBroken == true) {
                    t.setStatus("Repair time complete.");
                }
                uW.kocThroneItems[t.repairId].isBroken = false;
                uW.kocThroneItems[t.repairId].brokenType = "";
                t.repairId = 0;
            }

        }
        CM.ThroneView.renderInventory(uW.kocThroneItems);
        return timeUntilDone;
    },

    addUpgradeItem: function (throneId) {
        var t = Tabs.throneUpgrader;
        var qItem = new QueueItem();
        qItem.item = throneId;
        qItem.action = "upgrade";
        qItem.level = STrChOMaxThroneLevel;
        STrChOThroneQueueData.list.push(qItem);
        SAVESTrChOThroneQueueData();
        document.getElementById('throneInventoryItem' + throneId).className = 'STrChOBlueBorder';
        t.buildThroneQueueDisplay();
    },

    addEnhanceItem: function (throneId) {
        var t = Tabs.throneUpgrader;
        var qItem = new QueueItem();
        qItem.item = throneId;
        qItem.action = "enhance";
        qItem.level = STrChOMaxThroneQuality;
        STrChOThroneQueueData.list.push(qItem);
        SAVESTrChOThroneQueueData();
        document.getElementById('throneInventoryItem' + throneId).className = 'STrChOYellowBorder';
        t.buildThroneQueueDisplay();
    },

    addBothThroneItem: function (throneId) {
        var t = Tabs.throneUpgrader;

        var throneItem = uW.kocThroneItems[throneId];

        if (throneItem == null || !throneItem) return;

        var qual = +throneItem.quality;
        var lev = +throneItem.level;

        if (qual >= STrChOMaxThroneQuality) return;

        var maxLev = null;
        var nextQual = null;
        var qItem = null;

        while (qual < STrChOMaxThroneQuality) {
            maxLev = t.upgradePath[qual].maxLev;
            nextQual = t.upgradePath[qual].nextQual;

            if (lev < maxLev) {
                qItem = new QueueItem();
                qItem.item = throneId;
                qItem.action = "upgrade";
                qItem.level = maxLev;
                STrChOThroneQueueData.list.push(qItem);
                document.getElementById('throneInventoryItem' + throneId).className = 'STrChOBlueBorder';
            }

            qItem = new QueueItem();
            qItem.item = throneId;
            qItem.action = "enhance";
            qItem.level = nextQual;
            STrChOThroneQueueData.list.push(qItem);
            document.getElementById('throneInventoryItem' + throneId).className = 'STrChOYellowBorder';
            lev = maxLev;
            qual = nextQual;
        }

        STrChOThroneQueueData();
        t.buildThroneQueueDisplay();
    },

    addThroneQueue: function () {
        var t = Tabs.throneUpgrader;

        var action = document.getElementById('STrChOThroneAction').value;

        if (action == "both") {
            t.addBothThroneItem(document.getElementById('STrChOThroneUpgradeList').value);
            return;
        }

        var qItem = new QueueItem();
        qItem.item = document.getElementById('STrChOThroneUpgradeList').value;
        qItem.action = document.getElementById('STrChOThroneAction').value;
        qItem.level = document.getElementById('STrChOThroneMaxLevel').value;

        if (qItem.item == 0) return;

        STrChOThroneQueueData.list.push(qItem);
        SAVESTrChOThroneQueueData();
        t.buildThroneQueueDisplay();
    },

    buildThroneLevelWidget: function () {
        var t = Tabs.throneUpgrader;
        var m;
        var STrChOThroneAction = document.getElementById('STrChOThroneAction');
        if (STrChOThroneAction.value == "enhance") {
            m = ' Max: <select class=STrChOSelect id=STrChOThroneMaxLevel>';
            for (qual = 1; qual <= STrChOMaxThroneQuality; qual++) {
                m += '<option value="' + qual + '">' + throneCardQualities[qual] + '</option>';
            }
            m += '</select>';
        } else if (STrChOThroneAction.value == "upgrade") {
            m = ' Max: <select class=STrChOSelect id=STrChOThroneMaxLevel>';
            for (lvl = 1; lvl <= STrChOMaxThroneLevel; lvl++) {
                m += '<option value="' + lvl + '"> +' + lvl + '</option>';
            }
            m += '</select>';
        } else {
            m = ' - <select class=STrChOSelect id=STrChOThroneMaxLevel></select>';
        }

        document.getElementById('STrChOThroneMaxDiv').innerHTML = m;
        if (STrChOThroneAction.value == "enhance") {
            document.getElementById('STrChOThroneMaxLevel').value = STrChOMaxThroneQuality;
        } else if (STrChOThroneAction.value == "upgrade") {
            document.getElementById('STrChOThroneMaxLevel').value = STrChOMaxThroneLevel;
        }

    },

    buildThroneQueueDisplay: function () {
        var t = Tabs.throneUpgrader;

        var STrChOThroneQDiv = document.getElementById('STrChOThroneQDiv');

        var m = '<table id=STrChOThroneQueue width=100%>';
        m += '<tr><th width=10%>Remove</th>';
        m += '<th width=5%>Order</th>';
        m += '<th width=8%>Status</th>';
        m += '<th width=25%>Item</th>';
        m += '<th width=5%>Action</th>';
        m += '<th width=5%>Max</th>';
        m += '<th width=40%>Status/Last Upgrade/Attempts</th></tr>';

        for (var queueIndex = 0; queueIndex < STrChOThroneQueueData.list.length; queueIndex++) {
            var queueItem = STrChOThroneQueueData.list[queueIndex];
            if (!queueItem) continue;
            var throneItem = uW.kocThroneItems[queueItem.item];

            var throneCardName = "Unknown / Item removed";
            var throneId = 0;

            if (throneItem) {
                throneCardName = throneItem.name;
                throneId = throneItem.id;
            }

            m += '<tr>';
            m += '<td align=center><div id=STrChOThroneQueueRemove' + queueIndex + ' class=STrChORemove></div></td>';
            m += '<td align=center><div id=STrChOThroneUpRow' + queueIndex + ' class=STrChOUpRow></div><div class=STrChODownRow  id=STrChOThroneDownRow' + queueIndex + '></div></td>';
            m += '<td align=center><div id=STrChOThroneState' + queueIndex + '></div></td>';
            m += '<td align=center class=STrChOThroneUpdaterItemName><div id=STrChOThroneUpdaterItem' + throneId + ' >' + throneCardName + '</div></td>';
            m += '<td align=center>' + queueItem.action + '</td>';
            m += '<td>';
            if (queueItem.action == "enhance") {
                m += '<div style="text-align: center;"><select class=STrChOSelect id=STrChOThroneChangeLevel' + queueIndex + ' style="width:90px; text-align: center;">';
                for (qual = 1; qual <= STrChOMaxThroneQuality; qual++) {
                    m += '<option value="' + qual + '" ' + (queueItem.level == qual ? 'selected' : '') + '>' + throneCardQualities[qual] + '</option>';
                }
                m += '</select></div>';
            } else {
                m += '<div style="text-align: center;"><select class=STrChOSelect id=STrChOThroneChangeLevel' + queueIndex + ' style="width:90px; text-align: center;">';
                for (lvl = 1; lvl <= STrChOMaxThroneLevel; lvl++) {
                    m += '<option value="' + lvl + '"  ' + (queueItem.level == lvl ? 'selected' : '') + '> +' + lvl + '</option>';
                }
                m += '</select></div>';
            }
            m += '</td>';

            m += '<td style="text-align: center; white-space: pre-wrap;">' + queueItem.status + ' / ';
            if (queueItem.lastUpgrade) m += queueItem.lastUpgrade;
            m += ' / ' + queueItem.triesThis + ' tries this level, ' + queueItem.triesTotal + ' tries total';
            m += '</td>';

            m += '</tr>';
        }
        m += '</table>';

        STrChOThroneQDiv.innerHTML = m;

        for (var queueIndex = 0; queueIndex < STrChOThroneQueueData.list.length; queueIndex++) {
            var queueItem = STrChOThroneQueueData.list[queueIndex];
            if (!queueItem) continue;
            var throneItem = uW.kocThroneItems[queueItem.item];

            if (throneItem) {
                var trId = throneItem.id;

                document.getElementById('STrChOThroneUpdaterItem' + trId).addEventListener('mouseover', function(A) {
                    A.stopPropagation();
                    var throneId = this.id.split('STrChOThroneUpdaterItem')[1];
                    var throneItem = uW.kocThroneItems[throneId];
                    var STrChOCard = document.getElementById('STrChOThroneUpdaterItem' + throneId);
                    CM.ThroneView.hoverItem(A, STrChOCard, throneItem);
                }, false);
            }

            document.getElementById('STrChOThroneQueueRemove' + queueIndex).setAttribute('v1', queueIndex);
            document.getElementById('STrChOThroneQueueRemove' + queueIndex).addEventListener('click', function () {
                var qIndex = this.getAttribute('v1');
                t.deleteQueueItem(qIndex);
            }, false);

            document.getElementById('STrChOThroneUpRow' + queueIndex).setAttribute('v1', queueIndex);
            document.getElementById('STrChOThroneUpRow' + queueIndex).addEventListener('click', function () {
                var qIndex = this.getAttribute('v1');
                t.moveUpRow(qIndex);
            }, false);

            document.getElementById('STrChOThroneDownRow' + queueIndex).setAttribute('v1', queueIndex);
            document.getElementById('STrChOThroneDownRow' + queueIndex).addEventListener('click', function () {
                var qIndex = this.getAttribute('v1');
                t.moveDownRow(qIndex);
            }, false);

            document.getElementById('STrChOThroneChangeLevel' + queueIndex).setAttribute('v1', queueIndex);
            document.getElementById('STrChOThroneChangeLevel' + queueIndex).addEventListener('change', function () {
                var qIndex = this.getAttribute('v1');
                var itemLevel = this.value;
                t.changeLevel(qIndex, itemLevel);
            }, false);

            if (!throneItem || !(throneItem.id)) {
                document.getElementById('STrChOThroneState' + queueIndex).innerHTML = '<div style="text-align:center"> ??</div>';
            } else if (queueItem.status == "complete") {
                document.getElementById('STrChOThroneState' + queueIndex).className = 'STrChOSuccess';
            } else if (throneItem.isBroken) {
                if (throneItem.id == t.repairId) {
                    document.getElementById('STrChOThroneState' + queueIndex).className = 'STrChOHammer';
                } else {
                    document.getElementById('STrChOThroneState' + queueIndex).className = 'STrChOBroken';
                }
            } else {
                document.getElementById('STrChOThroneState' + queueIndex).innerHTML = '<div class=STrChOGoButton></div>';
            }
        }
    },

    deleteQueueItem: function (index) {
        // delete an item from the queue
        var t = Tabs.throneUpgrader;
        STrChOThroneQueueData.list.splice(index, 1);
        if (index > STrChOThroneQueueData.index) STrChOThroneQueueData.index--;
        SAVESTrChOThroneQueueData();
        t.buildThroneQueueDisplay();
    },

    moveUpRow: function (index) {
        if (index < 1) return;
        var t = Tabs.throneUpgrader;
        var qItem = STrChOThroneQueueData.list.splice(index, 1);
        STrChOThroneQueueData.list.splice(index - 1, 0, qItem[0]);

        if (index == STrChOThroneQueueData.index)
            STrChOThroneQueueData.index--;
        else if (STrChOThroneQueueData.index == index - 1)
            STrChOThroneQueueData.index++;

        SAVESTrChOThroneQueueData();
        t.buildThroneQueueDisplay();
    },

    moveDownRow: function (index) {
        if (index > (STrChOThroneQueueData.list.length - 2)) return;

        var t = Tabs.throneUpgrader;
        var qItem = STrChOThroneQueueData.list.splice(index, 1);
        STrChOThroneQueueData.list.splice(index + 1, 0, qItem[0]);

        if (index == STrChOThroneQueueData.index)
            STrChOThroneQueueData.index++;
        else if (STrChOThroneQueueData.index == index + 1)
            STrChOThroneQueueData.index--;

        SAVESTrChOThroneQueueData();
        t.buildThroneQueueDisplay();

    },

    changeLevel: function (index, level) {
        var t = Tabs.throneUpgrader;

        var queueItem = STrChOThroneQueueData.list[index];
        if (!queueItem) return;

        queueItem.level = level;
        if (queueItem.status == "complete") queueItem.status = "started";
        SAVESTrChOThroneQueueData();
        t.buildThroneQueueDisplay();
    },

    setStatus: function (s) {
        document.getElementById('STrChOThroneUpgradeStatus').innerHTML = '<div>' + s + '</div>';
    },

    setResult: function (s) {
        document.getElementById('STrChOThroneLastResult').innerHTML = '<div>' + s + '</div>';
    },

    togglePower: function (obj) {
        var t = Tabs.throneUpgrader;

        if (!STrChOThroneUpgradeData.active && STrChOThroneRepairData.active) {
            alert('You must disable repair tab first');
            return;
        }

        var btn = document.getElementById('STrChOThroneUpgradePower');
        if (STrChOThroneUpgradeData.active) {
            STrChOThroneUpgradeData.active = false;
            btn.value = 'Upgrader = OFF';
            t.setStatus('Powered Off');
            t.setResult('');

        } else {
            STrChOThroneUpgradeData.active = true;
            btn.value = "Upgrader = ON";
            t.setStatus("Powered On");
            t.setResult("");
        }

        if (!STrChOThroneUpgradeData.active) {

        }

        t.updateThroneMenu();
        SAVESTrChOThroneUpgradeData();
    },

    updateThroneMenu: function () {
        if (!document.getElementById('STrChOExecuteUpgrader')) return;
        document.getElementById('STrChOExecuteUpgrader').innerHTML = 'Upgrade ' + (STrChOThroneUpgradeData.active ? 'ON' : 'OFF');
    },
}

Tabs.throneSalvager = {
	tabOrder: 102,
	tabLabel: 'SALVAGER',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM SALVAGER',
    delItems: [],
    deleting: false,
    rowNum: 0,
    timer: null,
    city: null,
    cityNum: 0,
    sTimer: null,
    delTimer: null,
    upgradeProfit: true,

	init: function (div) {
		var t = Tabs.throneSalvager;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

		m += '<div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        if (STrChOThroneSalvageData.active) {
            m += '<td width=33%><input id=STrChOThroneSalvagePower type=button class=STrChOButton value="Salvager = ON"></td>';
        } else {
            m += '<td width=33%><input id=STrChOThroneSalvagePower type=button class=STrChOButton value="Salvager = OFF"></td>';
        }
        m += '<td width=33%><div class=divNoWrap align=center>';
        m += 'Keep All: <select id=STrChOThroneSalvageQuality class=STrChOSelect>';
        for (i = 1; i <= STrChOMaxThroneQuality; i++) {
            m += '<option value="' + i + '">' + throneCardQualities[i].capitalizeFirstLetter() + '+</option>';
        }
        m += '</select>';
        m += '</div></td>';
        m += '<td width=33%><div class=divNoWrap>Keep The First <input style="text-align: center;" id=STrChOThroneSaveNum class=STrChOTextbox type=text size=3 maxlength=3 value="' + STrChOThroneSalvageData.throneSaveNum + '"/> Cards</div></td>';
        m += '</tr>';
        m += '<tr><td colspan=3><hr class=STrChOHRCenter></td></tr>';
        m += '<tr><td colspan=3><div class=indent5 id=STrChOThroneSalvageStatus></div></td></tr>';
        m += '<tr><td colspan=3><div class=indent5 id=STrChOThroneNumSalv><br></div></td></tr>';
        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader id=STrChOThroneSimpleRule onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SIMPLE RULES&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="position: static; width: 100%; height: 200px; overflow-x: hidden; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';
        m += '<table>';
        m += '<tr><td><b>Define Throne Items To Keep:</b></td>';
        m += '<td alight=left><div><span>Faction: <select id=STrChOThroneFactionType class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var fact = 0; fact < STrChOFactions.length; fact++) m += '<option value="' + STrChOFactions[fact] + '">' + STrChOFactions[fact].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td alight=left><div><span>Card Type: <select id=STrChOThroneCardType class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var tct = 0; tct < throneCardTypes.length; tct++) m += '  <option value="' + throneCardTypes[tct] + '">' + throneCardTypes[tct].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td align=right><input id=STrChOThroneAddRule type=button class=STrChOButton value="Create Rule"/></td>';
        m += '</tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '<tr><td>';
        m += '<table id=STrChOThroneConditionTable style="padding-left: 5px;">';
        m += '<tr><td align=left colspan=1><input id=STrChOThroneAddRow type=button class=STrChOButton value="Add Row"/></td>';
        m += '<td></td><td></td><td></td><td></td><td></td></tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';   //end of STrChOSection

        m += '<div class=STrChOHeader id=STrChOThroneAdvancedRule onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;ADVANCED RULES&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';
        m += '<table>';
        m += '<tr><td colspan=4><input class=STrChOButton type=button id=STrChOThroneAdvancedReset value="Reset"></tr>';
        m += '<tr>';
        m += '<td><b>Define Throne Items To Keep:</b></td>';
        m += '<td alight=left><div><span>Faction: <select id=STrChOThroneFactionTypeAdvanced class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var fact = 0; fact < STrChOFactions.length; fact++) m += '<option value="' + STrChOFactions[fact] + '">' + STrChOFactions[fact].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td alight=left><div><span>Card Type: <select id=STrChOThroneCardTypeAdvanced class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var tct = 0; tct < throneCardTypes.length; tct++) m += '  <option value="' + throneCardTypes[tct] + '">' + throneCardTypes[tct].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td align=right><input id=STrChOThroneAddRuleAdvanced type=button class=STrChOButton value="Create Rule"/></td>';
        m += '</tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '<tr><td>';
        m += '<table width=100% id=STrChOThroneConditionTableAdvanced>';
        m += '<tr>';
        m += '<td width=20%>ROW 1</td>';
        m += '<td width=20%>ROW 2</td>';
        m += '<td width=20%>ROW 3</td>';
        m += '<td width=20%>ROW 4</td>';
        m += '<td width=20%>ROW 5</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOThroneRow1Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOThroneRow2Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOThroneRow3Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOThroneRow4Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOThroneRow5Advanced class=STrChOSelect></select></div></td>';
        m += '</tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';   //end of STrChOSection

        m += '<div class=STrChOHeader id=STrChOThroneAdvancedRule onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;AUTO LOAD RULES&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';

        m += '<tr><td><b>&nbsp;Define Effect:</b><select id=STrChOThroneAutoLoadEffect class=STrChOSelect>';
        m += '<option value="0">--Select--</option>';
        for (var efx in CM.thronestats.effects) m += '<option value="' + efx + '">' + CM.thronestats.effects[efx][1] + '</option>';
        m += '</select><input type=button class=STrChOButton id=STrChOThroneAutoLoad value="Auto Load">';
        m += '</td></tr>';

        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader>&nbsp;RULES LIST&nbsp;</div>';

        m += '<div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td align=center>';
        m += 'Sort By Card Type: <select id=STrChOThroneSalvageSortCard class=STrChOSelect>';
        m += '<option value="0">--Select--</option>';
        for (tct = 0; tct < throneCardTypes.length; tct++) m += '  <option value="' + throneCardTypes[tct] + '">' + throneCardTypes[tct].capitalizeFirstLetter() + '</option>';
        m += '</select>';
        m += '</td></tr>';
        m += '<tr><td align=center>';
        m += '<b>Salvager Will Keep Items Matching These Rules <i><div class=divNoWrap id=STrChOThroneRuleCount></div></i></b>';
        m += '</td></tr>';
        m += '<tr><td align=center>';
        m += '<div align=center>';
        m += '<table align=center width=100%>';
        m += '<tr>';
        m += '<td align=left><input id=STrChOThroneButtonSaveItem type=button class=STrChOButton value="Save Rules">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        m += '<input id=STrChOThroneClearAllRules type=button class=STrChOButton value="Clear All Rules"></td>';
        m += '<td align=right>'
        m += '<input id=STrChOThroneButtonLoadItem type=button class=STrChOButton value="Load Rules">';
        m += '<input class=STrChOButton type=button id=STrChOThroneFileDrop onclick="document.getElementById(\'STrChOThroneFileLoadItem\').click()" value="Browse...">';
        m += '<input id=STrChOThroneFileLoadItem style="visibility: hidden; height:0px; width: 0px;" type=file>';
        m += '</td>';
        m += '</tr>';
        m += '</table>';
        m += '</div>';
        m += '</td></tr>';
        m += '<tr><td align=center>';
        m += '<div id=STrChOThroneRuleScroll style="position: static; width: 100%; height: ' + dlgHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<div id=STrChOThroneRuleDisplay></div>';
        m += '</div>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>'; //end of STrChOSection
        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        t.displayNumberSalvaged();

        if (STrChOThroneSalvageData.active)
            t.setStatus('Loading...');
        else
            t.setStatus('Powered Off');

        document.getElementById('STrChOThroneClearAllRules').addEventListener('click', function() {
            STrChOThroneSalvageData.ruleSet = [];
            SAVESTrChOThroneSalvageData();
            t.buildThroneRuleDisplay();
        }, false);

        document.getElementById('STrChOThroneAutoLoad').addEventListener('click', function () {
            var effectId = document.getElementById('STrChOThroneAutoLoadEffect').value;
            if (effectId == 0) return;
            for (var category in STrChOThroneStatsGrid) {
                var faction = 'any';
                var type = category;
                var conditions = [];
                for (var i = 1; i < 6; i++) {
                    if (STrChOThroneStatsGrid[category][i][effectId] == 1) {
                        var slots = [];
                        for (var slotChecker = 1; slotChecker < 6; slotChecker++) slots.push(slotChecker==i);
                        var effectName = CM.thronestats.effects[effectId][1];
                        var buffDebuff = 'b';
                        if (effectName.indexOf(" Debuff") != -1) buffDebuff = "d";
                        var effectName = effectName.split(" Debuff")[0];
                        var c = new ThroneCondition(true, 1, effectName, buffDebuff, slots);
                        conditions.push(c);
                    }
                }
                if (conditions.length > 0) {
                    var rule = new ThroneRule(type, faction, conditions, true);
                    t.addRule(rule);
                }
            }
            SAVESTrChOThroneSalvageData();
            t.buildThroneRuleDisplay();
        }, false);

        document.getElementById('STrChOThroneSalvagePower').addEventListener('click', function () {
            t.togglePower(this);
        }, false);

        t.createRow();

        t.buildThroneRuleDisplay();

        document.getElementById('STrChOThroneSalvageSortCard').addEventListener('change', function() {
            t.buildThroneRuleDisplay();
        }, false);

        document.getElementById('STrChOThroneAddRow').addEventListener('click', function () {
            t.createRow();
        }, false);

        document.getElementById('STrChOThroneSalvageQuality').addEventListener('click', function () {
            t.setSalvageQuality(this.value);
        }, false);

        document.getElementById('STrChOThroneSalvageQuality').value = STrChOThroneSalvageData.minQuality;

        document.getElementById('STrChOThroneSaveNum').addEventListener('change', function () {
            STrChOThroneSalvageData.throneSaveNum = parseInt(document.getElementById('STrChOThroneSaveNum').value);
            if (STrChOThroneSalvageData.throneSaveNum < 0) STrChOThroneSalvageData.throneSaveNum = 0;
            SAVESTrChOThroneSalvageData();
        }, false);

        document.getElementById('STrChOThroneAdvancedReset').addEventListener('click', function() {
            var cardtype = document.getElementById('STrChOThroneCardTypeAdvanced');
            cardtype.selectedIndex = 0;
            t.clearAdvancedStats();
            t.setAdvancedStatsToAny();
        }, false);

        t.setAdvancedStatsToAny();

        document.getElementById('STrChOThroneAddRuleAdvanced').addEventListener('click', function() {
            t.createAdvancedRule();
        }, false);

        document.getElementById('STrChOThroneCardTypeAdvanced').addEventListener('change', function() {
            var selectedValue = document.getElementById('STrChOThroneCardTypeAdvanced').value;
            t.clearAdvancedStats();
            if (selectedValue == 'any') {
                t.setAdvancedStatsToAny();
            } else {
                t.filterAdvancedStats(selectedValue);
            }
        }, false);

        document.getElementById('STrChOThroneAddRule').addEventListener('click', function () {
            t.createRule();
        }, false);


        document.getElementById('STrChOThroneButtonSaveItem').addEventListener('click', function () {
            var uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(STrChOThroneSalvageData.ruleSet));
            var newWindow = window.open(uriContent, 'file.txt');
        }, false);


        document.getElementById('STrChOThroneButtonLoadItem').addEventListener('click', function () {
            var fileInput = document.getElementById("STrChOThroneFileLoadItem");
            var files = fileInput.files;
            if (files.length == 0) {
                alert('Please Select A File');
                return;
            }
            var file = files[0];

            var reader = new FileReader();

            reader.onload = function (e) {
                var output = e.target.result;
                STrChOThroneSalvageData.ruleSet = JSON.parse(output);
                STrChOThroneSalvageData.active = false;
                clearInterval(Tabs.throneSalvager.sTimer);
                clearInterval(Tabs.throneSalvager.delTimer);
                Tabs.throneSalvager.deleting = false;
                SAVESTrChOThroneSalvageData();
                Tabs.throneSalvager.show();
                alert('Throne Salvage Settings Now Loaded From File');
            };
            reader.readAsText(file);

        }, false);


        if (STrChOThroneSalvageData.upgradedToDelete.length > 0) {
            // some items were left over that need to be deleted
            for (k = 0; k < STrChOThroneSalvageData.upgradedToDelete.length; k++) {
                var id = STrChOThroneSalvageData.upgradedToDelete[k];
                // if the item is not longer in the inventory, remove the id
                if (!uW.kocThroneItems[id]) {
                    STrChOThroneSalvageData.upgradedToDelete.splice(k, 1); // Remove item from array
                    SAVESTrChOThroneSalvageData();
                    k--;
                }
            }

            // resume deleting things
            if (STrChOThroneSalvageData.active) {
                t.delItems = STrChOThroneSalvageData.upgradedToDelete;
                t.deleting = true;
                t.upgradeAndDelete();
            }
            else {
                // if the salvager is Powered Off, clear the list
                STrChOThroneSalvageData.upgradedToDelete = [];
                SAVESTrChOThroneSalvageData();
            }
        }
        // this check makes sure upgrading before deleting is still profitable
        t.upgradeProfit = (5 * CM.WorldSettings.getSettingAsNumber("AETHERSTONE_SALVAGE_MULTIPLIER", 500) > CM.thronestats.upgrade[1]["Stones"]);
        t.start();

	},

    setAdvancedStatsToAny: function() {
        for (var i = 1; i < STrChOQualityCount; i++) {
            var row = document.getElementById('STrChOThroneRow' + i + 'Advanced');
            row.options.add(new Option("none","None"));
            for (eff in CM.thronestats.effects) {
                var effectName = CM.thronestats.effects[eff][1];
                row.options.add(new Option(effectName, effectName));
            }
            row.options.add(new Option("Any Infantry", "Infantry"));
            row.options.add(new Option("Any Ranged", "Ranged"));
            row.options.add(new Option("Any Horsed", "Horsed"));
            row.options.add(new Option("Any Siege", "Siege"));
            row.options.add(new Option("Any Spellcaster", "Spellcaster"));
            row.options.add(new Option("Any Tower", "Tower"));
        }
    },

    clearAdvancedStats: function() {
        for (var i = 1; i < STrChOQualityCount; i++) {
            var row = document.getElementById('STrChOThroneRow' + i + 'Advanced');
            row.innerHTML = "";
        }
    },

    filterAdvancedStats: function(cardtype) {
        var t = Tabs.throneSalvager;
        cardtype = cardtype || 'any';

        if (cardtype == 'any') {
            t.setAdvancedStatsToAny();
            return;
        }

        document.getElementById("STrChOThroneRow1Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOThroneRow2Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOThroneRow3Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOThroneRow4Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOThroneRow5Advanced").options.add(new Option("none", "none"));

        for (eff in CM.thronestats.effects) {
            var effectName = CM.thronestats.effects[eff][1];
            if (STrChOThroneStatsGrid[cardtype][1][eff]) { document.getElementById("STrChOThroneRow1Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOThroneStatsGrid[cardtype][2][eff]) { document.getElementById("STrChOThroneRow2Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOThroneStatsGrid[cardtype][3][eff]) { document.getElementById("STrChOThroneRow3Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOThroneStatsGrid[cardtype][4][eff]) { document.getElementById("STrChOThroneRow4Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOThroneStatsGrid[cardtype][5][eff]) { document.getElementById("STrChOThroneRow5Advanced").options.add(new Option(effectName, effectName)); }
        }
    },

	hide: function () {},

	show: function () {
		var t = Tabs.throneSalvager;
        t.displayNumberSalvaged();
        t.buildThroneRuleDisplay();
	},

    updateThroneMenu: function () {
        if (!document.getElementById('STrChOExecuteSalvager')) return;
        document.getElementById('STrChOExecuteSalvager').innerHTML = 'Salvager ' + (STrChOThroneSalvageData.active ? 'ON' : 'OFF');
    },

    forceSalvage: function (throneId) {
        throneId = throneId || false;
        if (!throneId) return;
        var throneItem = uW.kocThroneItems[throneId];
        if (!throneItem) return;
        if (throneItem.jewel) {
            if (throneItem.jewel.valid) {
                var city_num = pickAetherSalvageCity();
                if (city_num == -1) city_num = 0;
                var city_id = Seed.cities[city_num][0];
                Tabs.STrChOJewels.removeJewel(city_id, throneId);
            }
        }
        SalvageThroneItem(throneId);
        CM.ThroneView.renderInventory(uW.kocThroneItems);
    },

    doDelete: function (id) {

        var t = Tabs.throneSalvager;
        if (!STrChOThroneSalvageData.active || !t.deleting) {
            t.deleting = false;
            return;
        }

        var item = uW.kocThroneItems[id];
        if (item == null || !item) return;

        if (item) t.setStatus('Salvaging ' + item.name);

        SalvageThroneItem(id);

    },

    removeItem: function (id, cityId, numStones) {

        var throne_item = uW.kocThroneItems[id];
        if (throne_item == null || !throne_item) return;

        var c = +(Seed.resources["city" + cityId]["rec5"][0]);
        var b = Seed.throne.slotEquip;

        Seed.resources["city" + cityId]["rec5"][0] = c + numStones;
        jQuery.each(b, function (g, h) {
            a = jQuery.inArray(id, h);
            if (a > -1) {
                h.splice(a, 1)
            }
        });

        delete uW.kocThroneItems[id];
        CM.ThroneView.renderInventory(uW.kocThroneItems);
    },

    // update items to +1 before deleting
    upgradeAndDelete: function () {
        var t = Tabs.throneSalvager;

        if (!STrChOThroneSalvageData.active || t.delItems.length == 0) {
            t.deleting = false;
            return;
        }

        var id = +t.delItems[0];

        // since simple +0 can be upgrade w/ near 100% success for 1500 a-stone and then salvaged for 2150
        // upgrade all these items 1 level
        if (STrChOThroneSalvageData.upgradeFirst && t.upgradeProfit) {

            var throne_item = uW.kocThroneItems[id];
            if (throne_item) {
                if (throne_item.quality <= STrChOThroneSalvageData.upgradeFirstQual && throne_item.level == 0
                            && (STrChOThroneSalvageData.upgradedToDelete.indexOf(id) < 0)) {
                    STrChOThroneSalvageData.upgradedToDelete.push(id);
                    SAVESTrChOThroneSalvageData();
                    Tabs.throneUpgrader.doUpgrade(+id, true);
                }
            }
            else {
                //item not found
            }
        }
        // delete the item
        t.delTimer = setTimeout(function () { t.doDelete(id) }, 4000);
    },

    // returns true if the item should be saved and not salvaged
    applyRules: function (id) {
        var t = Tabs.throneSalvager;
        for (r in STrChOThroneSalvageData.ruleSet) {
            var rule = STrChOThroneSalvageData.ruleSet[r];
            if (rule.ThroneApplyRule(id)) return true;
        }
        return false;
    },

    // Create the list of items to delete.
    // If 'test' is set to true, then broken/equipted items are included.
    buildList: function (test) {
        var t = Tabs.throneSalvager;

        var countItem = 0;
        var retList = [];

        for (k in uW.kocThroneItems) {
            var throne_item = uW.kocThroneItems[k];

            if (throne_item == null || !throne_item) continue;

            countItem++;

            // ignore these things
            if (throne_item.level != 0) continue;

            if (throne_item.unique > 0) continue;

            // in test mode, include these items
            // These items are at risk if they are repaired or unequiped.
            if (test != true) {
                if (throne_item.isEquipped) continue;
                if (throne_item.isBroken) continue;
            }

            // keep the first X items
            if (countItem <= STrChOThroneSalvageData.throneSaveNum) continue;

            // keep things w/ at least minQuality
            if (throne_item.quality >= STrChOThroneSalvageData.minQuality) continue;

            // check the rules
            if (t.applyRules(throne_item.id)) { //item was found
                if (STrChOThroneSalvageData.upgradeAutoFind) {
                    var found = false;
                    for (var i = 0; i < STrChOThroneQueueData.list.length; i++) {
                        var qItem = STrChOThroneQueueData.list[i];
                        if (qItem.item != throne_item.id) continue;
                        found = true;
                        break;
                    }
                    if (!found) {
                        ActionLog('Item: ' + throne_item.name + ' found and added to auto upgrade');
                        Tabs.throneUpgrader.addUpgradeItem(throne_item.id);
                    }
                }
                continue;
            }

            // passes all tests
            retList.push(throne_item.id);
        }
        return retList;
    },

    // do the actual discard of TR items
    doSalvage: function () {
        var t = Tabs.throneSalvager;

        if (!STrChOThroneSalvageData.active) {
            t.deleting = false;
            return;
        }

        if (t.deleting == true) return;

        t.deleting = true;
        t.setStatus('Salvaging items');

        t.delItems = t.buildList(false);

        if (t.delItems.length > 0) {
            // upgrade items from +0 to +1 first
            t.upgradeAndDelete();
        } else {
            // give enough time for the last delete to finish
            setTimeout(function () {
                t.deleting = false;
                t.setStatus('No items to salvage.  Waiting for next cycle.');
            }, 3000);
        }
    },

    start: function () {
        var t = Tabs.throneSalvager;
        if (STrChOThroneSalvageData.active) {
            t.sTimer = setInterval(t.doSalvage, 1 * 60 * 1000);
        }
    },

    addRule: function (rule) {
        STrChOThroneSalvageData.ruleSet.unshift(rule);
        SAVESTrChOThroneSalvageData();
    },

    readRows: function () {
        var t = Tabs.throneSalvager;
        var table = document.getElementById('STrChOThroneConditionTable');
        var rowCount = table.rows.length;

        var cType = document.getElementById('STrChOThroneCardType').value;
        var faction = document.getElementById('STrChOThroneFactionType').value;

        var conditions = [];
        for (i = 0; i < table.rows.length; i++) {
            var row = table.rows[i];
            if (row.id) {
                var s1 = document.getElementById(row.id + "ThroneSel1");
                var s2 = document.getElementById(row.id + "ThroneSel2");
                var s3 = document.getElementById(row.id + "ThroneSel3");
                var s4 = document.getElementById(row.id + "ThroneSel4");

                var slots = [];
                for (j = 1; j <= 5; j++) {
                    var ch = document.getElementById(row.id + "ThroneSlot" + j);
                    slots.push(ch.checked);
                }

                var c = new ThroneCondition(s1.value, s2.value, s3.value, s4.value, slots);
                conditions.push(c);
            }
        }
        var rule1 = new ThroneRule(cType, faction, conditions, false);
        t.addRule(rule1);
    },

    readAdvancedRows: function () {
        var t = Tabs.throneSalvager;
        var cType = document.getElementById('STrChOThroneCardTypeAdvanced').value;
        var faction = document.getElementById('STrChOThroneFactionTypeAdvanced').value;
        var conditions = [];
        for (var i = 1; i < 6; i++) {
            var row = document.getElementById("STrChOThroneRow" + i + "Advanced");
            if (row.selectedIndex == 0) continue;
            var slots = [];
            for (var slotChecker = 1; slotChecker < 6; slotChecker++) {
                slots.push(slotChecker==i);
            }
            var effectName = row.options[row.selectedIndex].value;
            var buffDebuff = "b";
            if (effectName.indexOf(" Debuff") != -1) buffDebuff = "d";
            var effectName = effectName.split(" Debuff")[0];
            var c = new ThroneCondition(true, 1, effectName, buffDebuff, slots);
            conditions.push(c);
        }
        if ( conditions.length > 0 ) {
            var rule1 = new ThroneRule(cType, faction, conditions, true);
            t.addRule(rule1);
        }
    },

    createRule: function () {
        var t = Tabs.throneSalvager;
        t.readRows();
        t.buildThroneRuleDisplay();
    },

    createAdvancedRule: function() {
        var t = Tabs.throneSalvager;
        t.readAdvancedRows();
        t.buildThroneRuleDisplay();
    },

    setSalvageQuality: function (qual) {
        STrChOThroneSalvageData.minQuality = qual;
        SAVESTrChOThroneSalvageData();
    },

    buildThroneRuleDisplay: function () {
        var t = Tabs.throneSalvager;

        function innerThroneRuleDisplay(dataset) {
            var innerM = '';
            for (i = 0; i < dataset.length; i++) {
                var rule = dataset[i];

                innerM += '<tr>';
                innerM += '<td width=90%><div class=STrChOThroneRule>';

                innerM += (rule.advancedrule ? 'Advanced Rule<br>' : 'Simple Rule<br>');

                innerM += ' Type: ' + rule.type;
                innerM += ' Faction: ' + rule.faction;

                for (ii = 0; ii < rule.conditions.length; ii++) {
                    var condition = rule.conditions[ii];

                    if (ii == 0)
                        innerM += '<br> Item';
                    else
                        innerM += '<br> <u>and</u>';

                    if (condition.mustHave != 'false')
                        innerM += ' must have ';
                    else
                        innerM += ' must NOT have ';

                    innerM += condition.number + 'x ';
                    innerM += condition.effect + ' ';

                    if (condition.buffType == 'b')
                        innerM += 'buff ';
                    else if (condition.buffType == 'd')
                        innerM += 'debuff ';
                    else
                        innerM += 'buff or debuff ';

                    innerM += ' in slot(s): ';

                    for (j = 0; j < condition.slots.length; j++) {
                        if (condition.slots[j]) innerM += (j + 1) + " ";
                    }

                }
                innerM += '</div></td>';
                innerM += '<td width=20% align=center>';
                innerM += '<input id=STrChOThroneEditRule' + i + ' class=STrChOButton type=button value="Edit">';
                innerM += '<input id=STrChOThroneDelRule' + i + ' class=STrChOButton type=button value="X">';
                innerM += '</td>';
                innerM += '</tr>';
            }
            return innerM;
        }

        var rd = document.getElementById('STrChOThroneRuleDisplay');
        var sortType = document.getElementById('STrChOThroneSalvageSortCard').value;

        var ruleCounter = 0;

        if (sortType != "0") {
            var sortedDataSet = [];
            for (var k = 0; k < STrChOThroneSalvageData.ruleSet.length; k++) {
                if (sortType == STrChOThroneSalvageData.ruleSet[k].type) {
                    sortedDataSet.unshift(STrChOThroneSalvageData.ruleSet[k]);
                }else {
                    sortedDataSet.push(STrChOThroneSalvageData.ruleSet[k]);
                }
            }
            rd.innerHTML = '<table width=100%>' + innerThroneRuleDisplay(sortedDataSet);
            ruleCounter = sortedDataSet.length;
            for (var j = 0; j < sortedDataSet.length; j++) {
                document.getElementById('STrChOThroneDelRule' + j).v1 = j;
                document.getElementById('STrChOThroneEditRule' + j).v1 = j;
                document.getElementById('STrChOThroneDelRule' + j).addEventListener('click', function () { t.deleteRule(this.v1, sortedDataSet); }, false);
                document.getElementById('STrChOThroneEditRule' + j).addEventListener('click', function () { t.editRule(this.v1, sortedDataSet); }, false);
            }
        } else {
            ruleCounter = STrChOThroneSalvageData.ruleSet.length;
            rd.innerHTML = '<table width=100%>' + innerThroneRuleDisplay(STrChOThroneSalvageData.ruleSet);
            for (var j = 0; j < STrChOThroneSalvageData.ruleSet.length; j++) {
                document.getElementById('STrChOThroneDelRule' + j).v1 = j;
                document.getElementById('STrChOThroneEditRule' + j).v1 = j;
                document.getElementById('STrChOThroneDelRule' + j).addEventListener('click', function () { t.deleteRule(this.v1, STrChOThroneSalvageData.ruleSet); }, false);
                document.getElementById('STrChOThroneEditRule' + j).addEventListener('click', function () { t.editRule(this.v1, STrChOThroneSalvageData.ruleSet); }, false);
            }
        }

        document.getElementById('STrChOThroneRuleCount').innerHTML = '(Total Rules: ' + ruleCounter + ')';

    },

    editRule: function (ruleIndex, sortedData)
    {
        var t = Tabs.throneSalvager;
        var rule = sortedData[ruleIndex];

        var divExpander = null;

        if (rule.advancedrule)
            divExpander = document.getElementById('STrChOThroneAdvancedRule');
        else
            divExpander = document.getElementById('STrChOThroneSimpleRule');

        divExpander.click();
        if (divExpander.childNodes[0].src == STrChORightArrow) divExpander.click();

        if (rule.advancedrule) {
            document.getElementById('STrChOThroneFactionTypeAdvanced').value = rule.faction;
            document.getElementById('STrChOThroneCardTypeAdvanced').value = rule.type;
            t.clearAdvancedStats();
            if (rule.type == 'any')
                t.setAdvancedStatsToAny();
            else
                t.filterAdvancedStats(rule.type);

            for (row = 0; row < rule.conditions.length; row++) {
                var condition = rule.conditions[row];
                var slotNumber = 0;
                for (s = 0; s < condition.slots.length; s++) {
                    if (condition.slots[s]) slotNumber = s+1;
                }
                var cell = document.getElementById('STrChOThroneRow' + slotNumber + 'Advanced');
                var STrChOEffect = condition.effect;
                if (condition.buffType == 'd') STrChOEffect += ' Debuff';
                cell.value = STrChOEffect;
            }

        } else {
            document.getElementById('STrChOThroneFactionType').value = rule.faction;
            document.getElementById('STrChOThroneCardType').value = rule.type;
            var STrChOThroneConditionTable = document.getElementById('STrChOThroneConditionTable');
            while (STrChOThroneConditionTable.rows.length > 1) STrChOThroneConditionTable.deleteRow(0);
            for (row = 0; row < rule.conditions.length; row++) {
                var condition = rule.conditions[row];
                t.createRow();
                STrChOThroneConditionTable = document.getElementById('STrChOThroneConditionTable');
                STrChOThroneConditionTable.rows[row].cells[0].children[0].value = condition.mustHave;
                STrChOThroneConditionTable.rows[row].cells[1].children[0].value = condition.number;
                STrChOThroneConditionTable.rows[row].cells[2].children[0].value = condition.effect;
                STrChOThroneConditionTable.rows[row].cells[3].children[0].value = condition.buffType;
                var slotCells = STrChOThroneConditionTable.rows[row].cells[4];
                for (s = 0; s < condition.slots.length; s++) {
                    if (condition.slots[s])
                        slotCells.children[s].checked = true;
                    else
                        slotCells.children[s].checked = false;
                }
            }
        }
        t.deleteRule(ruleIndex, sortedData);
    },

    // delete a rule from the ruleset
    deleteRule: function (ruleIndex, sortedData) {
        var t = Tabs.throneSalvager;
        sortedData.splice(ruleIndex, 1);
        var newDataSet = [];
        for (var i = 0; i < STrChOThroneSalvageData.ruleSet.length; i++) {
            for (var i2 = 0; i2 < sortedData.length; i2++) {
                if (STrChOThroneSalvageData.ruleSet[i] == sortedData[i2]) {
                    newDataSet.push(STrChOThroneSalvageData.ruleSet[i]);
                    break;
                }
            }
        }
        STrChOThroneSalvageData.ruleSet = newDataSet;
        SAVESTrChOThroneSalvageData();
        t.buildThroneRuleDisplay();
    },

    removeRow: function (row) {
        var t = Tabs.throneSalvager;
        var table = document.getElementById('STrChOThroneConditionTable');

        for (i = 0; i < table.rows.length; i++) {
            if (table.rows[i] == row) {
                table.deleteRow(i);
                break;
            }
        }
    },

    createRow: function () {
        var t = Tabs.throneSalvager;
        var table = document.getElementById('STrChOThroneConditionTable');
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount - 1);
        var rowId = "r" + t.rowNum;
        t.rowNum += 1;
        row.id = rowId;

        var h = '<td> <select class=STrChOSelect id="' + rowId + 'ThroneSel1"> <option value="true"></option><option value="false">NOT</option></select></td>';
        h += '<td> <select class=STrChOSelect id="' + rowId + 'ThroneSel2">';
        h += '  <option value="1">1x</option>';
        h += '  <option value="2">2x</option>';
        h += '  <option value="3">3x</option>';
        h += '  <option value="4">4x</option>';
        h += '  <option value="5">5x</option>';
        h += '</select></td>';
        h += '<td> <select class=STrChOSelect id="' + rowId + 'ThroneSel3">';
        h += '</select></td>';
        h += '<td> <select class=STrChOSelect id="' + rowId + 'ThroneSel4">';
        h += '  <option value="e">Either</option>';
        h += '  <option value="b">Buff</option>';
        h += '  <option value="d">Debuff</option>';
        h += '</select></td>';

        h += '<td>';
        h += '  <input class=STrChOCheckbox type=checkbox value="1" checked=true id="' + rowId + 'ThroneSlot1"/>1';
        h += '  <input class=STrChOCheckbox type=checkbox value="2" checked=true id="' + rowId + 'ThroneSlot2"/>2';
        h += '  <input class=STrChOCheckbox type=checkbox value="3" checked=true id="' + rowId + 'ThroneSlot3"/>3';
        h += '  <input class=STrChOCheckbox type=checkbox value="4" checked=true id="' + rowId + 'ThroneSlot4"/>4';
        h += '  <input class=STrChOCheckbox type=checkbox value="5" checked=true id="' + rowId + 'ThroneSlot5"/>5';
        h += '</td>';

        row.innerHTML = h;

        var effects = [];

        for (e in CM.thronestats.effects) {
            var effectName = CM.thronestats.effects[e][1].split(" Debuff")[0];
            if (effects.indexOf(effectName) < 0) effects.push(effectName);
        }

        var select = document.getElementById(rowId + "ThroneSel3");
        for (index in effects) {
            select.options.add(new Option(effects[index], effects[index]));
        }

        // add in options for troops specific effects
        select.options.add(new Option("Any Infantry", "Infantry"));
        select.options.add(new Option("Any Ranged", "Ranged"));
        select.options.add(new Option("Any Horsed", "Horsed"));
        select.options.add(new Option("Any Siege", "Siege"));
        select.options.add(new Option("Any Spellcaster", "Spellcaster"));
        select.options.add(new Option("Any Tower", "Tower"));

        var c = row.insertCell(5);
        //TODO: change to javascript
        var btn = $('<input class=STrChOButton type=button value="X" />');
        $(btn).click(function () { t.removeRow(row); });
        $(c).append(btn);
    },

    togglePower: function (obj) {
        var t = Tabs.throneSalvager;
        if (STrChOThroneSalvageData.active) {
            var btn = document.getElementById('STrChOThroneSalvagePower');
            STrChOThroneSalvageData.active = false;
            btn.value = "Salvager = OFF";
            t.setStatus('Powered Off');
            clearInterval(t.sTimer);
            clearInterval(t.delTimer);
            t.delItems = [];
            STrChOThroneSalvageData.upgradedToDelete = [];
            t.deleting = false;
        } else {
            if (STrChOGeneralOptions.throneSorter) {
                if (!confirm('SORTER WARNING: You will likely experience lowered salvage rates and potentially crashing if you have both sorter and salvager enabled.  Would you like to continue?')) return;
            }
            STrChOThroneSalvageData.active = true;
            var btn = document.getElementById('STrChOThroneSalvagePower');
            btn.value = "Salvager = ON";
            t.setStatus('Loading...');
            t.doSalvage();
            t.start();
        }
        SAVESTrChOThroneSalvageData();
        t.updateThroneMenu();
    },

    // put out a status message on the trSavlStatus div
    setStatus: function (msg) {
        document.getElementById('STrChOThroneSalvageStatus').innerHTML = msg;
    },

    displayNumberSalvaged: function () {
        var since = "";
        var rate = "";
        var now = new Date();

        if (!STrChOThroneSalvageData.since) STrChOThroneSalvageData.since = now.valueOf();

        var sinceD = new Date(STrChOThroneSalvageData.since);

        since = sinceD.toDateString().substring(3, 10) + " " + sinceD.toLocaleTimeString();
        var duration = now.valueOf() - STrChOThroneSalvageData.since + 1;
        duration = duration / 1000.0;
        rate = ' (' + addCommas(Math.round(STrChOThroneSalvageData.numSalvagedItems2 / duration * 86400)) + ' per day)';

        var m = "";
        m += '<div style="text-align: center;">';
        m += addCommas(STrChOThroneSalvageData.numSalvagedItems);
        m += ' items salvaged, ';
        m += addCommas(STrChOThroneSalvageData.numSalvagedItems2);
        m += ' items since ' + since + rate;
        m += '<input id=STrChOThroneTripOdometer class=STrChOButton type=button value="<-- Reset" /></div>';

        document.getElementById('STrChOThroneNumSalv').innerHTML = m;

        document.getElementById('STrChOThroneTripOdometer').addEventListener('click', function () {
            Tabs.throneSalvager.tripOdometer();
        }, false);

    },

    tripOdometer: function () {
        STrChOThroneSalvageData.numSalvagedItems2 = 0;
        var now = new Date();
        STrChOThroneSalvageData.since = now.valueOf();
        SAVESTrChOThroneSalvageData();
        Tabs.throneSalvager.displayNumberSalvaged();
    },

}

Tabs.throneRepair = {
	tabOrder: 103,
	tabLabel: 'REPAIR',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM REPAIR',
    repairId: 0,
    repairEnd: 0,
    timerH: null,
    clearTimerH: null,

	init: function (div) {
		var t = Tabs.throneRepair;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '<div class=STrChOSaveSettings id=STrChOThroneRepairSaveSettings title="Save Repair Settings"></div><div class=STrChOLoadSettings id=STrChOThroneRepairLoadSettings title="Load Repair Settings"></div></div>';


        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
		m += '<div>';

        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        if (STrChOThroneRepairData.active) {
            m += '<td width=50%><input id=STrChOThroneRepairPower type=button class=STrChOButton value="Repair = ON"></td>';
        } else {
            m += '<td width=50%><input id=STrChOThroneRepairPower type=button class=STrChOButton value="Repair = OFF"></td>';
        }
        m += '<td width=50%><div class=divNoWrap align=center id=STrChOThroneRepairAetherDisplay></div></td>';
        m += '</tr>';
        m += '<tr><td colspan=2><hr class=STrChOHRCenter></td></tr>';
        m += '<tr><td colspan=2><div class=indent5 id=STrChOThroneRepairStatus><br></div></td></tr>';
        m += '<tr><td colspan=2><div class=indent5 id=STrChOThroneRepairLastResult><br></div></td></tr>';
        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SPEED UPS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairHourglassLevelSpecific ' + (STrChOThroneRepairData.hourglassLevelSpecific ? "CHECKED" : "") + '>Only use hourglass for levels ';
        m += '<select class=STrChOSelect  id=STrChOThroneRepairHourglassLevel>';
        for (lvl = 1; lvl < STrChOMaxThroneLevel; lvl++) m += '<option value="' + lvl + '" ' + (STrChOThroneRepairData.hourglassLevel == lvl ? 'SELECTED' : '') + '>+' + lvl + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairHourglassQualitySpecific ' + (STrChOThroneRepairData.hourglassQualitySpecific ? "CHECKED" : "") + '>Only use hourglass for qualities ';
        m += '<select class=STrChOSelect id=STrChOThroneRepairHourglassQuality>';
        for (qual = 1; qual <= STrChOMaxThroneQuality-1; qual++) m += '<option value="' + qual + '" ' + (STrChOThroneRepairData.hourglassQuality == qual ? 'SELECTED' : '') + '>' + throneCardQualities[qual].capitalizeFirstLetter() + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[1] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseSH ' + (STrChOThroneRepairData.useSH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[1] + ' (<div class=divNoWrap id=STrChOThroneRepairUseSHLabel><font' + (uW.ksoItems[1].count < 100 ? ' color=red>' : '>') + uW.ksoItems[1].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[2] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseKH ' + (STrChOThroneRepairData.useKH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[2] + ' (<div class=divNoWrap id=STrChOThroneRepairUseKHLabel><font' + (uW.ksoItems[2].count < 100 ? ' color=red>' : '>') + uW.ksoItems[2].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[3] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseGH ' + (STrChOThroneRepairData.useGH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[3] + ' (<div class=divNoWrap id=STrChOThroneRepairUseGHLabel><font' + (uW.ksoItems[3].count < 100 ? ' color=red>' : '>') + uW.ksoItems[3].count + '</font></div>)</div></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[4] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseMH ' + (STrChOThroneRepairData.useMH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[4] + ' (<div class=divNoWrap id=STrChOThroneRepairUseMHLabel><font' + (uW.ksoItems[4].count < 100 ? ' color=red>' : '>') + uW.ksoItems[4].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[5] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseAH ' + (STrChOThroneRepairData.useAH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[5] + ' (<div class=divNoWrap id=STrChOThroneRepairUseAHLabel><font' + (uW.ksoItems[5].count < 100 ? ' color=red>' : '>') + uW.ksoItems[5].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[6] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseWH ' + (STrChOThroneRepairData.useWH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[6] + ' (<div class=divNoWrap id=STrChOThroneRepairUseWHLabel><font' + (uW.ksoItems[6].count < 100 ? ' color=red>' : '>') + uW.ksoItems[6].count + '</font></div>)</div></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[7] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseDH ' + (STrChOThroneRepairData.useDH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[7] + ' (<div class=divNoWrap id=STrChOThroneRepairUseDHLabel><font' + (uW.ksoItems[7].count < 100 ? ' color=red>' : '>') + uW.ksoItems[7].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[8] + '"><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairUseEH ' + (STrChOThroneRepairData.useEH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[8] + ' (<div class=divNoWrap id=STrChOThroneRepairUseEHLabel><font' + (uW.ksoItems[8].count < 100 ? ' color=red>' : '>') + uW.ksoItems[8].count + '</font></div>)</div></td>';
        m += '<td/>';
        m += '</tr>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOThroneRepairOverrideSpeedUps ' + (STrChOThroneRepairData.overrideSpeedUp ? "CHECKED" : "") + '>Override hourglasses by using ';
        m += '<select class=STrChOSelect  id=STrChOThroneRepairSpeedUp>';
        m += '<option value=0>None</option>';
        for (gls in STrChOHourGlassName) {
            m += '<option value=' + gls + ' ' + (STrChOThroneRepairData.useSpeedUp == gls ? 'SELECTED' : '') + '>' + STrChOHourGlassName[gls] + '</option>';
        }
        m += '</select> every time</td>';
        m += '</tr>';
        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;REPAIR ITEMS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';

        m += '<tr><td>Queue By Level: <select class=STrChOSelect id=STrChOThroneRepairByLevel>';
        for (i = 1; i < STrChOMaxThroneLevel; i++) m += '<option value=' + i + '>+' + i + '</option>';
        m += '</select>&nbsp;<input id=STrChOThroneRepairByLevelAdd class=STrChOButton type=button value="Add"/></td></tr>';

        m += '<tr><td>Queue By Preset Tag: <select class=STrChOSelect id=STrChOThroneRepairPresetTagList>';
        var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);
        var presetsList = "";
        for (i = 1; i < presetSlots + 1; i++) presetsList += '<option value="' + i + '">' + i + ' (' + STrChOThronePresetData.presetNames[i] + ')</option>';
        m += presetsList;
        m += "</select>&nbsp;<input id=STrChOThroneRepairPresetTag class=STrChOButton type=button value='Add'/></td></tr>";

        m += '<tr><td><div style="max-width:90%;">Item: <select class=STrChOSelect style="white-space:nowrap;display:inline-block;max-width: 200px;" id=STrChOThroneRepairList>';
        m += '</select><input id=STrChOThroneRepairAdd type=button class=STrChOButton value="Add"/>&nbsp;<input id=STrChOThroneRepairAddAll class=STrChOButton type=button value="Add All">&nbsp;<input id=STrChOThroneRepairRefresh class=STrChOButton type=button value="Refresh List"></div></td></tr>';

        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader>&nbsp;REPAIR LIST&nbsp;</div>';

        m += '<div>';
        m += '<table class=STrChOSectionTable>';

        m += '<tr><td colspan=2>';
        m += '<div id=STrChOThroneRepairQScroll style="position: static; width: 100%; height: 350px; overflow-x: auto; overflow-y: auto;">';
        m += '<div id=STrChOThroneRepairQDiv></div>';
        m += '</div>';
        m += '</td></tr>';

        m += '<tr align=center><td><div><input style="float: left;" id=STrChOThroneRepairClear class=STrChOButton type=button value="Clear Queue"/></div></td><td><div><input style="float: right;" id=STrChOThroneRepairClearF class=STrChOButton type=button value="Clear Repaired"/></div></td></tr>';

        m += '</table>';
        m += '</div>';
        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOThroneRepairSaveSettings').addEventListener('click', function () {
            SaveSettingsToFile(STrChOThroneRepairData);
        }, false);
        document.getElementById('STrChOThroneRepairLoadSettings').addEventListener('click', function () {
            var loader = document.getElementById('STrChOSettingsFile');
            loader.addEventListener('change', function () {
                LoadSettingsFromFile(STrChOThroneRepairData, Tabs.throneRepair);
            }, false);
            loader.click();
        }, false);

        t.refreshAetherDisplay();

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        document.getElementById('STrChOThroneRepairUseWH').addEventListener('change', function () {
            STrChOThroneRepairData.useWH = document.getElementById('STrChOThroneRepairUseWH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.useWH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairUseDH').addEventListener('change', function () {
            STrChOThroneRepairData.useDH = document.getElementById('STrChOThroneRepairUseDH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairUseDH.useDH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairUseEH').addEventListener('change', function () {
            STrChOThroneRepairData.useEH = document.getElementById('STrChOThroneRepairUseEH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.useEH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairUseSH').addEventListener('change', function () {
            STrChOThroneRepairData.useSH = document.getElementById('STrChOThroneRepairUseSH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.useSH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairUseKH').addEventListener('change', function () {
            STrChOThroneRepairData.useKH = document.getElementById('STrChOThroneRepairUseKH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.useKH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairUseGH').addEventListener('change', function () {
            STrChOThroneRepairData.useGH = document.getElementById('STrChOThroneRepairUseGH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.useGH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairUseMH').addEventListener('change', function () {
            STrChOThroneRepairData.useMH = document.getElementById('STrChOThroneRepairUseMH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.useMH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairUseAH').addEventListener('change', function () {
            STrChOThroneRepairData.useAH = document.getElementById('STrChOThroneRepairUseAH').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.useAH) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairHourglassLevelSpecific').addEventListener('change', function () {
            STrChOThroneRepairData.hourglassLevelSpecific = document.getElementById('STrChOThroneRepairHourglassLevelSpecific').checked;
            SAVESTrChOThroneRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairHourglassQualitySpecific').addEventListener('change', function () {
            STrChOThroneRepairData.hourglassQualitySpecific = document.getElementById('STrChOThroneRepairHourglassQualitySpecific').checked;
            SAVESTrChOThroneRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairOverrideSpeedUps').addEventListener('change', function () {
            STrChOThroneRepairData.overrideSpeedUp = document.getElementById('STrChOThroneRepairOverrideSpeedUps').checked;
            SAVESTrChOThroneRepairData();
            if (STrChOThroneRepairData.overrideSpeedUp) t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairSpeedUp').addEventListener('change', function () {
            STrChOThroneRepairData.useSpeedUp = document.getElementById('STrChOThroneRepairSpeedUp').value;
            SAVESTrChOThroneRepairData();
        }, false);

        document.getElementById('STrChOThroneRepairHourglassLevel').addEventListener('change', function () {
            STrChOThroneRepairData.hourglassLevel = document.getElementById('STrChOThroneRepairHourglassLevel').value;
            SAVESTrChOThroneRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairHourglassQuality').addEventListener('change', function () {
            STrChOThroneRepairData.hourglassQuality = document.getElementById('STrChOThroneRepairHourglassQuality').value;
            SAVESTrChOThroneRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOThroneRepairPower').addEventListener('click', function () {
            t.togglePower(this);
        }, false);

        document.getElementById('STrChOThroneRepairByLevelAdd').addEventListener('click', function () {
            var t = Tabs.throneRepair;
            var level = document.getElementById('STrChOThroneRepairByLevel').value;
            for (trId in uW.kocThroneItems) {
                var throne_item = uW.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                if (!throne_item.isBroken) continue;
                if (throne_item.level != level) continue;
                t.addQueue(trId);
            }
        }, false);

        document.getElementById('STrChOThroneRepairPresetTag').addEventListener('click', function () {
            var t = Tabs.throneRepair;
            var presetTagNum = document.getElementById('STrChOThroneRepairPresetTagList').value;
            var presetTag = getThronePresetObject(parseInt(presetTagNum));
            for (var ptId in presetTag) {
                var throne_item = uW.kocThroneItems[ptId];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.isBroken) t.addQueue(ptId);
            }
        }, false);

        document.getElementById('STrChOThroneRepairClear').addEventListener('click', function () {
            t.deleteQueue();
        }, false);

        document.getElementById('STrChOThroneRepairClearF').addEventListener('click', function () {
            var temp = [];
            while (STrChOThroneRepairData.items.length > 0) {
                var trId = STrChOThroneRepairData.items.pop();
                var throne_item = uW.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.isBroken) temp.push(trId);
            }
            while (temp.length > 0) STrChOThroneRepairData.items.push(temp.pop());
            STrChOThroneRepairData.index = 0
            SAVESTrChOThroneRepairData();
            t.populateThroneRepairListBox();
            t.buildThroneRepairDisplay();
        }, false);

        document.getElementById('STrChOThroneRepairAdd').addEventListener('click', function () {
            t.addQueue();
        }, false);

        document.getElementById('STrChOThroneRepairAddAll').addEventListener('click', function () {
            t.addAllQueue();
        }, false);

        document.getElementById('STrChOThroneRepairRefresh').addEventListener('click', function () {
            t.populateThroneRepairListBox();
        }, false);

        if (STrChOThroneRepairData.active)
            t.setStatus('Loading...');
        else
            t.setStatus('Powered Off');

        t.refreshAetherDisplay();

        var d = 2 + Math.random() * 8;
        if (Seed.queue_throne != null && Seed.queue_throne.end != null) {
            var repairTimeLeft = Seed.queue_throne.end - unixTime();
            t.repairEnd = Seed.queue_throne.end;
            t.repairId = Seed.queue_throne.itemId;
            var n = new Date(t.repairEnd * 1000);

            t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + uW.kocThroneItems[t.repairId].name);
            if (STrChOThroneRepairData.useSH || STrChOThroneRepairData.useKH || STrChOThroneRepairData.useGH || STrChOThroneRepairData.useMH || STrChOThroneRepairData.useAH || STrChOThroneRepairData.useWH || STrChOThroneRepairData.useDH || STrChOThroneRepairData.useEH || (STrChOThroneRepairData.overrideSpeedUp && STrChOThroneRepairData.useSpeedUp > 0)) {
                var throneItem = uW.kocThroneItems[t.repairId];
                var trQuality = throneItem.quality;
                var trLevel = throneItem.level;
                var useThoseSpeedups = true;
                if (STrChOThroneRepairData.hourglassQualitySpecific && trQuality < STrChOThroneRepairData.hourglassQuality) useThoseSpeedups = false;
                if (STrChOThroneRepairData.hourglassLevelSpecific && trLevel < STrChOThroneRepairData.hourglassLevel) useThoseSpeedups = false;
                if (STrChOThroneRepairData.overrideSpeedUp) useThoseSpeedups = true;
                if (useThoseSpeedups) {
                    setTimeout(function () { t.doSpeedup(); }, 2000);
                }
            }
            setTimeout(t.clearRepair, (repairTimeLeft + 1) * 1000);
            if (repairTimeLeft > 0) d += repairTimeLeft;
        }

        t.populateThroneRepairListBox();
        t.buildThroneRepairDisplay();


        if (!STrChOThroneRepairData.active) t.setStatus("Powered Off");


        if (t.timerH == null) {
            t.timerH = setTimeout(t.doAction, d * 1000);
        }
	},

    refreshAetherDisplay : function () {
        document.getElementById('STrChOThroneRepairAetherDisplay').innerHTML = displayCityAstone();
    },

	hide: function () {},

	show: function () {
		var t = Tabs.throneRepair;
        t.refreshAetherDisplay();
        t.populateThroneRepairListBox();
        t.buildThroneRepairDisplay();
	},

    doRepair: function (rItem) {
        var t = Tabs.throneRepair;
        var params = uW.Object.clone(ajfx);

        if (STrChOThroneRepairData.active == false || rItem == 0 || uW.kocThroneItems[rItem] == null) return;

        var theItem = uW.kocThroneItems[rItem];

        params.action = 'timeRepair';
        params.throneRoomItemId = rItem;
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';

        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {

                var rslt = eval("(" + transport.responseText + ")");

                if (rslt.ok) {
                    var item = uW.kocThroneItems[rItem];
                    var startTime = unixTime();
                    var endTime = rslt.eta;
                    ActionLog('Starting repair for Throne Room item ' + item.name);
                    Seed.queue_throne.itemId = item.id;
                    Seed.queue_throne.start = startTime;
                    Seed.queue_throne.end = endTime;
                    t.repairId = item.id;
                    t.repairEnd = endTime;
                    var n = new Date(t.repairEnd * 1000);
                    t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + item.name);
                    var secondsForRepair = t.repairEnd - startTime;
                    if (secondsForRepair < 0) secondsForRepair = 0;
                    CM.ThroneView.renderInventory(uW.kocThroneItems);
                    t.clearTimerH = setTimeout(t.clearRepair, (secondsForRepair + 1) * 1000);
                    t.buildThroneRepairDisplay();
                    if (STrChOThroneRepairData.useSH || STrChOThroneRepairData.useKH || STrChOThroneRepairData.useGH || STrChOThroneRepairData.useMH || STrChOThroneRepairData.useAH || STrChOThroneRepairData.useWH || STrChOThroneRepairData.useDH || STrChOThroneRepairData.useEH || (STrChOThroneRepairData.overrideSpeedUp && STrChOThroneRepairData.useSpeedUp > 0)) {
                        var throneItem = uW.kocThroneItems[t.repairId];
                        var trQuality = throneItem.quality;
                        var trLevel = throneItem.level;
                        var useThoseSpeedups = true;
                        if (STrChOThroneRepairData.hourglassQualitySpecific && trQuality < STrChOThroneRepairData.hourglassQuality) useThoseSpeedups = false;
                        if (STrChOThroneRepairData.hourglassLevelSpecific && trLevel < STrChOThroneRepairData.hourglassLevel) useThoseSpeedups = false;
                        if (STrChOThroneRepairData.overrideSpeedUp) useThoseSpeedups = true;
                        if (useThoseSpeedups) {
                            setTimeout(function () { t.doSpeedup(); }, 2000);
                        }
                    }
                }
                else {
                    if (rslt.msg == "Item is not broken") {
                        uW.kocThroneItems[rItem].isBroken = false;
                        t.clearRepair();
                    }

                    // regrab the end times in case this is caused by a manual repair
                    if (Seed.queue_throne && Seed.queue_throne.end && Seed.queue_throne.itemId) {
                        t.repairEnd = Seed.queue_throne.end;
                        t.repairId = Seed.queue_throne.itemId;
                    }

                }
                return;
            },
            onFailure: function (ttt) {
                // this usually means a repair is in progress (such as a manual repair). Grab the seed data (if possible)
                if (Seed.queue_throne && Seed.queue_throne.end) {
                    t.repairEnd = Seed.queue_throne.end;
                    t.repairId = Seed.queue_throne.itemId;
                }

                return;
            }
        });
        return;
    },


    togglePower: function (obj) {
        var t = Tabs.throneRepair;

        var STrChOThroneRepairPower = document.getElementById('STrChOThroneRepairPower');

        if (STrChOThroneRepairData.active) {
            STrChOThroneRepairData.active = false;
            STrChOThroneRepairPower.value = "Repair = OFF";
            t.setStatus("Powered Off");
            t.setResult("");

        } else {
            STrChOThroneRepairData.active = true;
            STrChOThroneRepairPower.value = "Repair = ON";
            t.setStatus("Powered On");
            t.setResult("");
            STrChOThroneUpgradeData.active = false;
            SAVESTrChOThroneUpgradeData();
            t.doAction();
        }

        if (!STrChOThroneRepairData.active) {

        }

        SAVESTrChOThroneRepairData();
        t.updateThroneMenu();

    },

    clearRepair: function () {
        var t = Tabs.throneRepair;
        var timeUntilDone = 0;

        if (t.repairEnd == 0) {
            return timeUntilDone;
        }
        timeUntilDone = t.repairEnd - unixTime();

        if (timeUntilDone <= 0) {
            // logit("clearing repair");
            if (t.repairId != 0 && uW.kocThroneItems[t.repairId] != null) {
                if (!uW.kocThroneItems[t.repairId].isBroken) {
                    t.setStatus("Repair time complete.");
                    document.getElementById('STrChOThroneRepairState' + t.repairId).className = "STrChOSuccess";
                } else {
                    uW.kocThroneItems[t.repairId].isBroken = false;
                    uW.kocThroneItems[t.repairId].brokenType = "";
                }
                t.repairId = 0;
            }

        }
        CM.ThroneView.renderInventory(uW.kocThroneItems);
        return timeUntilDone;
    },

    setStatus: function (s) {
        document.getElementById('STrChOThroneRepairStatus').innerHTML = "<div>" + s + "</div>";
    },

    setResult: function (s) {
        document.getElementById('STrChOThroneRepairLastResult').innerHTML = "<div>" + s + "</div>";
    },

    updateThroneMenu: function () {
        if (!document.getElementById('STrChOExecuteRepair')) return;
        document.getElementById('STrChOExecuteRepair').innerHTML = 'Repair ' + (STrChOThroneRepairData.active ? 'ON' : 'OFF');
    },

    deleteRepairItem: function (index) {
        // delete an item from the queue
        var t = Tabs.throneRepair;
        STrChOThroneRepairData.items.splice(index, 1);
        SAVESTrChOThroneRepairData();
        t.populateThroneRepairListBox();
        t.buildThroneRepairDisplay();
    },

    moveRepairUpRow: function (index) {
        if (index < 1) return;
        var t = Tabs.throneRepair;
        var q = STrChOThroneRepairData.items.splice(index, 1);
        STrChOThroneRepairData.items.splice(index - 1, 0, q);

        if (index == STrChOThroneRepairData.index)
            STrChOThroneRepairData.index--;
        else if (STrChOThroneRepairData.index == index - 1)
            STrChOThroneRepairData.index++;

        SAVESTrChOThroneRepairData();
        t.buildThroneRepairDisplay();
    },

    moveRepairDownRow: function (index) {
        if (index > (STrChOThroneRepairData.items.length - 2)) return;

        var t = Tabs.throneRepair;
        var q = STrChOThroneRepairData.items.splice(index, 1);
        STrChOThroneRepairData.items.splice(index + 1, 0, q);

        if (i == STrChOThroneRepairData.index)
            STrChOThroneRepairData.index++;
        else if (STrChOThroneRepairData.index == i + 1)
            STrChOThroneRepairData.index--;

        SAVESTrChOThroneRepairData();
        t.buildThroneRepairDisplay();

    },

    buildThroneRepairDisplay: function () {
        var t = Tabs.throneRepair;

        var STrChOThroneRepairQDiv = document.getElementById('STrChOThroneRepairQDiv');

        var totalRepairTime = t.calcRepairTime();

        var item_count = STrChOThroneRepairData.items.length;

        var m = '<table>';

        if (totalRepairTime > 0) m += '<caption><b><i>Total Repair Time (' + item_count + ' items): ' + repairTimeToText(totalRepairTime) + '</i></b></caption>';

        m += '<tr>';
        m += '<th width=10%>Remove</th>';
        m += '<th width=5%>Order</th>';
        m += '<th width=8%>Status</th>';
        m += '<th width=25%>Item</th>';
        m += '</tr>';

        if (item_count > 0) {
            for (var item_index = 0; item_index < item_count; item_index++) {
                var trId = STrChOThroneRepairData.items[item_index];

                if (trId == null) {
                    t.deleteRepairItem(item_index);
                    return;
                }
                var throne_item = uW.kocThroneItems[trId];
                if (throne_item == null || !throne_item) {
                    t.deleteRepairItem(item_index);
                    return;
                }

                m += '<tr>';
                m += '<td align=center><div id=STrChOThroneRepairRemove' + trId + ' class=STrChORemove></div></td>';
                m += '<td align=center><div class=STrChOUpRow id=STrChOThroneRepairUpRow' + trId + '></div><div class=STrChODownRow  id=STrChOThroneRepairDownRow' + trId + '></div></td>';
                m += '<td align=center><div id=STrChOThroneRepairState' + trId + '></div></td>';
                m += '<td align=center class=STrChOThroneRepairItemName><div id=STrChOThroneRepairItem' + trId + ' >' + throne_item.name + '</div></td>';
                m += '</tr>';
            }

            m += '</table>';

            STrChOThroneRepairQDiv.innerHTML = m;

            for (var item_index = 0; item_index < item_count; item_index++) {

                var trId = STrChOThroneRepairData.items[item_index];

                var throne_item = uW.kocThroneItems[trId];

                if (throne_item == null || !throne_item) continue;

                document.getElementById('STrChOThroneRepairItem' + trId).addEventListener('mouseover', function(A) {
                    A.stopPropagation();
                    var throneId = this.id.split('STrChOThroneRepairItem')[1];
                    var throneItem = uW.kocThroneItems[throneId];
                    var STrChOCard = document.getElementById('STrChOThroneRepairItem' + throneId);
                    CM.ThroneView.hoverItem(A, STrChOCard, throneItem);
                }, false);

                document.getElementById('STrChOThroneRepairRemove' + trId).setAttribute('v1', item_index);
                document.getElementById('STrChOThroneRepairRemove' + trId).addEventListener('click', function () {
                    var qIndex = this.getAttribute('v1');
                    t.deleteRepairItem(qIndex);
                }, false);

                document.getElementById('STrChOThroneRepairUpRow' + trId).setAttribute('v1', item_index);
                document.getElementById('STrChOThroneRepairUpRow' + trId).addEventListener('click', function () {
                    var qIndex = this.getAttribute('v1');
                    t.moveRepairUpRow(qIndex);
                }, false);

                document.getElementById('STrChOThroneRepairDownRow' + trId).setAttribute('v1', item_index);
                document.getElementById('STrChOThroneRepairDownRow' + trId).addEventListener('click', function () {
                    var qIndex = this.getAttribute('v1');
                    t.moveRepairDownRow(qIndex);
                }, false);

                var throne_item = uW.kocThroneItems[trId];
                if (!throne_item || !(throne_item.id)) {
                    document.getElementById('STrChOThroneRepairState' + trId).innerHTML = '<div style="text-align:center"> ??</div>';
                } else if (!throne_item.isBroken) {
                    document.getElementById('STrChOThroneRepairState' + trId).className = 'STrChOSuccess';
                } else if (throne_item.isBroken) {
                    if (trId == t.repairId) {
                        document.getElementById('STrChOThroneRepairState' + trId).className = 'STrChOHammer';
                    } else {
                        document.getElementById('STrChOThroneRepairState' + trId).className = 'STrChOBroken';
                    }
                }

            }
        } else {
            m += '</table>';

            STrChOThroneRepairQDiv.innerHTML = m;
        }
    },

    populateThroneRepairListBox: function () {
        var repairList = document.getElementById('STrChOThroneRepairList');
        var m = '<option value=0>--Items--</option>';

        var item_count = STrChOThroneRepairData.items.length;

        for (trId in uW.kocThroneItems) {
            var throne_item = uW.kocThroneItems[trId];
            if (throne_item == null || !throne_item) continue;
            if (!throne_item.isBroken) continue; //item not broken, move on

            var foundIt = false;
            for (var item_index = 0; item_index < item_count; item_index++) {
                if (trId == STrChOThroneRepairData.items[item_index]) {
                    foundIt = true;
                    break;
                }
            }
            if (!foundIt) {
                var optionText = throne_item.name;
                m += '<option value="' + trId + '">' + optionText + '</option>';
            }
        }
        repairList.innerHTML = m;
    },

    deleteQueue: function () {
        var t = Tabs.throneRepair
        STrChOThroneRepairData.items = [];
        SAVESTrChOThroneRepairData();
        t.populateThroneRepairListBox();
        t.buildThroneRepairDisplay();
    },

    addAllQueue: function () {
        var t = Tabs.throneRepair;

        for (trId in uW.kocThroneItems) {
            var throne_item = uW.kocThroneItems[trId];
            if (throne_item == null || !throne_item) continue;
            if (throne_item.isBroken) {
                t.addQueue(trId);
            }
        }

    },

    selectNext: function () {

        var l = STrChOThroneRepairData.items.length;
        for (i = 0; i < l; i++) {

            var throne_item = uW.kocThroneItems[STrChOThroneRepairData.items[i]];
            if (throne_item == null || !throne_item) continue;
            if ((throne_item != null) && (throne_item.isBroken)) {
                STrChOThroneRepairData.index = i;
                SAVESTrChOThroneRepairData();
                return;
            }
        }

        // if we get here, the queue is complete
        STrChOThroneRepairData.index = -1;

        SAVESTrChOThroneRepairData();
    },

    calcRepairTime: function () {
        var t = Tabs.throneRepair
        var item_count = STrChOThroneRepairData.items.length;
        var total_time = 0;
        for (var item_index = 0; item_index < item_count; item_index++) {
            var trId = STrChOThroneRepairData.items[item_index];
            var throne_item = uW.kocThroneItems[trId];
            if (throne_item == null || !throne_item) continue;
            var item_time = CM.thronestats.repairCostUpgrade[throne_item.level].Time;
            total_time += item_time;
        }
        return total_time;
    },

    addQueue: function (iD) {
        var t = Tabs.throneRepair;

        if (iD == null) {
            var trId = document.getElementById('STrChOThroneRepairList').value;
        } else {
            var trId = iD;
        }

        if (trId == 0 || trId == null) return;

        var item_count = STrChOThroneRepairData.items.length;

        if (item_count > 0) {
            for (var item_index = 0; item_index < item_count; item_index++) {
                if (trId == STrChOThroneRepairData.items[item_index]) return;
            }
        }

        STrChOThroneRepairData.items.push(trId);
        SAVESTrChOThroneRepairData();
        t.populateThroneRepairListBox();
        t.buildThroneRepairDisplay();
    },

    doSpeedup: function () {
        var t = Tabs.throneRepair;

        var endTime = t.repairEnd;
        var startTime = unixTime();
        var secondsForRepair = endTime - startTime;
        var divId = "";

        t.speedup = 0;

        if (secondsForRepair > 0 && STrChOThroneRepairData.overrideSpeedUp && STrChOThroneRepairData.useSpeedUp > 0) {
            t.speedup = STrChOThroneRepairData.useSpeedUp;
        } else {
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.day25 && STrChOThroneRepairData.useAH && uW.ksoItems[8].count > 0) { t.speedup = 8; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour24 && STrChOThroneRepairData.useAH && uW.ksoItems[7].count > 0) { t.speedup = 7; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour15 && STrChOThroneRepairData.useAH && uW.ksoItems[6].count > 0) { t.speedup = 6; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour8 && STrChOThroneRepairData.useAH && uW.ksoItems[5].count > 0) { t.speedup = 5; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && STrChOThroneRepairData.useMH && uW.ksoItems[4].count > 0) { t.speedup = 4; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && STrChOThroneRepairData.useGH && uW.ksoItems[3].count > 0) { t.speedup = 3; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && STrChOThroneRepairData.useKH && uW.ksoItems[2].count > 0) { t.speedup = 2; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && STrChOThroneRepairData.useSH && uW.ksoItems[1].count > 0) { t.speedup = 1; }
        }

        switch (t.speedup) {
            case "1":
            case 1:
                secondsForRepair -= HOURGLASSES_TIME.minute1;
                divId = 'STrChOThroneRepairUseSHLabel';
                break;
            case "2":
            case 2:
                secondsForRepair -= HOURGLASSES_TIME.minute15;
                divId = 'STrChOThroneRepairUseKHLabel';
                break;
            case "3":
            case 3:
                secondsForRepair -= HOURGLASSES_TIME.hour1;
                divId = 'STrChOThroneRepairUseGHLabel';
                break;
            case "4":
            case 4:
                secondsForRepair -= HOURGLASSES_TIME.hour25;
                divId = 'STrChOThroneRepairUseMHLabel';
                break;
            case "5":
            case 5:
                secondsForRepair -= HOURGLASSES_TIME.hour8;
                divId = 'STrChOThroneRepairUseAHLabel';
                break;
            case "6":
            case 6:
                secondsForRepair -= HOURGLASSES_TIME.hour15;
                divId = 'STrChOThroneRepairUseWHLabel';
                break;
            case "7":
            case 7:
                secondsForRepair -= HOURGLASSES_TIME.hour24;
                divId = 'STrChOThroneRepairUseDHLabel';
                break;
            case "8":
            case 8:
                secondsForRepair -= HOURGLASSES_TIME.day25;
                divId = 'STrChOThroneRepairUseEHLabel';
                break;
        }

        if (t.speedup != 0) {
            t.setResult('Used ' + uW.ksoItems[t.speedup].name);
            var divCount = uW.ksoItems[t.speedup].count - 1;
            var divSpeedups = document.getElementById(divId);
            divSpeedups.innerHTML = divCount;
            uW.modal_speedup_apply("throne", t.speedup, t.repairId);

            if (secondsForRepair <= 0) {
                secondsForRepair = 0;
                endTime = startTime;
                t.clearTimerH = setTimeout(t.clearRepair, 1000);
            } else {
                endTime = unixTime() + secondsForRepair;
                t.repairEnd = endTime;
                var n = new Date(t.repairEnd * 1000);
                var item = uW.kocThroneItems[t.repairId];
                if (item) {
                    t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + item.name);
                    t.clearTimerH = setTimeout(t.clearRepair, secondsForRepair * 1000);
                }
            }
            t.buildThroneRepairDisplay();
            t.repairEnd = endTime;
            setTimeout(function () { t.doSpeedup(); }, 1000);
        }
    },

    doAction: function () {
        var t = Tabs.throneRepair;
        t.populateThroneRepairListBox();

        if (STrChOThroneUpgradeData.active) {
            t.setStatus('Waiting for upgrade tab to finish...');
            if (STrChOThroneRepairData.active) t.togglePower();
            return;
        }

        if (!STrChOThroneRepairData.active) {
            t.setStatus("Powered Off");
            return;
        } else {
            var retryTime = STrChOGeneralOptions.retryInterval;

            try {
                // check if repair is done
                var ti = t.clearRepair();
                if (ti <= 0) {
                    // repair is done

                    // set the index
                    t.selectNext();

                    if (STrChOThroneRepairData.index < 0) {
                        t.setStatus("Reached end of queue.")
                        t.setResult("");
                        SAVESTrChOThroneRepairData();
                    } else {
                        var throne_item = uW.kocThroneItems[STrChOThroneRepairData.items[STrChOThroneRepairData.index]];
                        if (throne_item) {
                            t.repairId = throne_item.id;
                            t.doRepair(throne_item.id);
                        }
                    }

                } else {
                    // come back after repair is complete
                    retryTime = ti + 5;
                    var n = new Date(t.repairEnd * 1000);
                    t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + uW.kocThroneItems[t.repairId].name);
                    if (STrChOThroneRepairData.useSH || STrChOThroneRepairData.useKH || STrChOThroneRepairData.useGH || STrChOThroneRepairData.useMH || STrChOThroneRepairData.useAH || STrChOThroneRepairData.useWH || STrChOThroneRepairData.useDH || STrChOThroneRepairData.useEH || (STrChOThroneRepairData.overrideSpeedUp && STrChOThroneRepairData.useSpeedUp > 0)) {
                        var throneItem = uW.kocThroneItems[t.repairId];
                        var trQuality = throneItem.quality;
                        var trLevel = throneItem.level;
                        var useThoseSpeedups = true;
                        if (STrChOThroneRepairData.hourglassQualitySpecific && trQuality < STrChOThroneRepairData.hourglassQuality) useThoseSpeedups = false;
                        if (STrChOThroneRepairData.hourglassLevelSpecific && trLevel < STrChOThroneRepairData.hourglassLevel) useThoseSpeedups = false;
                        if (STrChOThroneRepairData.overrideSpeedUp) useThoseSpeedups = true;
                        if (useThoseSpeedups) {
                            setTimeout(function () { t.doSpeedup(); }, 2000);
                        }
                        retryTime = 1;
                    }
                }
                CM.ThroneView.renderInventory(uW.kocThroneItems);
            } catch (e) {
            }
            // recycle
            clearTimeout(t.timerH);
            t.timerH = setTimeout(t.doAction, retryTime * 1000);
            t.buildThroneRepairDisplay();
        }
    },
}

Tabs.throneOrganizer = {
	tabOrder: 104,
	tabLabel: 'ORGANIZER',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM ORGANIZER',
    throneItemLists: {},
    sortEffect: "none",
    buffType: "both",
    panelId: -1,
    panelType: "upgrade",
    panelNextLevel: 2,
    switchingPresets: false,
    thronePanelOpen: false,

	init: function (div) {
		var t = Tabs.throneOrganizer;
		t.mydiv = div;

        t.sortEffect = STrChOThroneUpgradeData.effectSelected;
        t.buffType = STrChOThroneUpgradeData.buffSelected;

        var throneEffects = [];
        for (efx in CM.thronestats.effects) {
			var throneEffectName = CM.thronestats.effects[efx][1].split(" Debuff")[0];
			if (throneEffects.indexOf(throneEffectName) < 0) throneEffects.push(throneEffectName);
        }

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';

        m += 'Sort: <select class=STrChOSelect id=STrChOThroneSortEffects>';
        m += '<option value="none">--Effect--</option>';
        for (efx=0;efx<throneEffects.length;efx++) m += '<option value="' + throneEffects[efx] + '">' + throneEffects[efx] + '</option>';
        m += '</select>';
        m += '<select class=STrChOSelect id=STrChOThroneBuffType>';
        m += '<option value="both">Either</option>';
        m += '<option value="buff">Buff</option>';
        m += '<option value="debuff">Debuff</option>';
        m += '</select>';

        m += '<input id=STrChOThroneSortInactive class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.sortInactive ? ' CHECKED' : '') + '/> Include Inactive ';
        m += '<input id=STrChOThroneIgnoreBroken class=STrChOCheckbox type=checkbox ' + (STrChOThroneUpgradeData.ignoreBroken ? ' CHECKED' : '') + '/> Ignore Broken';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';

        m += '<div id=STrChOThroneOrganizerScroll style="position: static; width: ' + (dlgWidth -  (dlgWidthOffset + dlgWidthMenu)) + 'px; height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; overflow-x: hidden; overflow-y: auto;">';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;CARD FILTER&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable cellspacing=0 cellpadding=0>';

        m += '<tr><td colspan=4>';
        m += 'Filter By Effects: <select class=STrChOSelect id=STrChOThroneFilterEffects>';
        m += '<option value="none">--Effect--</option>';
        for (efx=0;efx<throneEffects.length;efx++) m += '<option value="' + throneEffects[efx] + '">' + throneEffects[efx] + '</option>';
        m += '</select>';
        m += '<select class=STrChOSelect id=STrChOThroneFilterBuffType>';
        m += '<option value="buff">Buff</option>';
        m += '<option value="debuff">Debuff</option>';
        m += '</select>';
        m += '</td></tr>';

        m += '<tr><td colspan=4><hr class=STrChOHRCenter></td></tr>';

        m += '<tr><td>Faction</td><td>Quality</td><td>Level</td><td>Jewel</td></tr>';

        m += '<tr>';

        m += '<td><div id=STrChOThroneFactionFilterRow style="float: left; width: 100px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (var fact=0;fact<STrChOFactions.length;fact++) m += '<input id=STrChOThroneFaction' + STrChOFactions[fact] + ' class=STrChOCheckbox type=checkbox  CHECKED />' + String(STrChOFactions[fact]).capitalizeFirstLetter() + '<br />';
        m += '</div></td>';

        m += '<td><div id=STrChOThroneQualityFilterRow style="float: left; width: 120px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (var qual = 0; qual < throneCardQualities.length; qual++) m += '<input id=STrChOThroneQuality' + qual + ' class=STrChOCheckbox type=checkbox  CHECKED />' + throneCardQualities[qual].capitalizeFirstLetter() + '<br />';
        m += '<input id=STrChOThroneQualityUnique class=STrChOCheckbox type=checkbox CHECKED />Uniques<br />';
        m += '</div></td>';

        m += '<td><div id=STrChOThroneLevelFilterRow style="float: left; width: 120px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (lvl = 0; lvl <= STrChOMaxThroneLevel; lvl++) {
            m += '<input id=STrChOThroneLevel' + lvl + ' class=STrChOCheckbox type=checkbox CHECKED />' + lvl + '<br /> ';
        }
        m += '</div></td>';

        m += '<td><div id=STrChOThroneJewelFilterRow style="float: left; width: 120px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        m += '<input id=STrChOThroneJewelNone class=STrChOCheckbox type=checkbox CHECKED />No Jewel<br />';

        for (var jwl = 0; jwl < STrChOJewelQualities.length; jwl++) m += '<input id=STrChOThroneJewel' + (jwl+1) + ' class=STrChOCheckbox type=checkbox CHECKED />' + STrChOJewelQualities[jwl].capitalizeFirstLetter() + '<br /> ';

        m += '</div></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td/>';
        m += '<td><input style="width:120px;" id=STrChOThroneUnselectAllQualities class=STrChOButton type=button value="Unselect All"></td>';
        m += '<td><input style="width:120px;" id=STrChOThroneUnselectAllLevels class=STrChOButton type=button value="Unselect All"></td>';
        m += '<td><input style="width:120px;" id=STrChOThroneUnselectAllJewels class=STrChOButton type=button value="Unselect All"></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td/>';
        m += '<td><input style="width:120px;" id=STrChOThroneSelectAllQualities class=STrChOButton type=button value="Select All"></td>';
        m += '<td><input style="width:120px;" id=STrChOThroneSelectAllLevels class=STrChOButton type=button value="Select All"></td>';
        m += '<td><input style="width:120px;" id=STrChOThroneSelectAllJewels class=STrChOButton type=button value="Select All"></td>';
        m += '</tr>';

        m += '</table>';
        m += '</div>';

        for (var tct = 0; tct < throneCardTypes.length; tct++) {
            m += '<div class=STrChOThroneOrganizer onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;' + throneCardTypes[tct].toUpperCase() + '&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';
            m += '<div class=STrChOThroneOrganizerSection id=STrChOThroneCardSection' + throneCardTypes[tct] + '></div>';
        }

        //m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var throneOrganizers = document.getElementsByClassName('STrChOThroneOrganizer');
        for (var throneOrg=0; throneOrg < throneOrganizers.length; throneOrg++) {
            throneOrganizers[throneOrg].addEventListener('click', function () {

                var imgs = this.childNodes;
                if (imgs[0].src == STrChODownArrow) {
                    imgs[0].src = STrChORightArrow
                    imgs[2].src = STrChORightArrow
                } else {
                    imgs[0].src = STrChODownArrow
                    imgs[2].src = STrChODownArrow
                }
                var section = this.nextSibling;
                if (section.className != 'STrChOThroneOrganizerSection') return;

                if (section.style.display == 'block')
                    section.style.display = 'none';
                else
                    section.style.display = 'block';

            }, false);
        }

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        document.getElementById('STrChOThroneSortEffects').value = STrChOThroneUpgradeData.effectSelected;
        document.getElementById('STrChOThroneBuffType').value = STrChOThroneUpgradeData.buffSelected;
        document.getElementById('STrChOThroneSortInactive').checked = STrChOThroneUpgradeData.sortInactive;
        document.getElementById('STrChOThroneIgnoreBroken').checked = STrChOThroneUpgradeData.ignoreBroken;

        document.getElementById('STrChOThroneFilterBuffType').addEventListener('change', function () {
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneFilterEffects').addEventListener('change', function () {
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneSortEffects').addEventListener('change', function () {
            t.sortEffect = this.value;
            STrChOThroneUpgradeData.effectSelected = t.sortEffect;
            SAVESTrChOThroneUpgradeData();
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneBuffType').addEventListener('change', function () {
            t.buffType = this.value;
            STrChOThroneUpgradeData.buffSelected = t.buffType;
            SAVESTrChOThroneUpgradeData();
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneSortInactive').addEventListener('click', function () {
            STrChOThroneUpgradeData.sortInactive = document.getElementById('STrChOThroneSortInactive').checked;
            SAVESTrChOThroneUpgradeData();
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneIgnoreBroken').addEventListener('click', function () {
            STrChOThroneUpgradeData.ignoreBroken = document.getElementById('STrChOThroneIgnoreBroken').checked;
            SAVESTrChOThroneUpgradeData();
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneUnselectAllQualities').addEventListener('click' , function () {
            for (var qual = 0; qual < throneCardQualities.length; qual++) document.getElementById('STrChOThroneQuality' + qual).checked = false;
            document.getElementById('STrChOThroneQualityUnique').checked = false;
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneSelectAllQualities').addEventListener('click', function () {
            for (var qual = 0; qual < throneCardQualities.length; qual++) document.getElementById('STrChOThroneQuality' + qual).checked = true;
            document.getElementById('STrChOThroneQualityUnique').checked = true;
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneQualityFilterRow').addEventListener('change', function () {
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);


        document.getElementById('STrChOThroneUnselectAllJewels').addEventListener('click' , function () {
            for (var jwl = 0 ; jwl < STrChOJewelQualities.length; jwl ++ ) document.getElementById('STrChOThroneJewel' + (jwl+1)).checked = false;
            document.getElementById('STrChOThroneJewelNone').checked = false;
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneSelectAllJewels').addEventListener('click', function () {
            for (var jwl = 0 ; jwl < STrChOJewelQualities.length; jwl ++ ) document.getElementById('STrChOThroneJewel' + (jwl+1)).checked = true;
            document.getElementById('STrChOThroneJewelNone').checked = true;
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneJewelFilterRow').addEventListener('change', function () {
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneUnselectAllLevels').addEventListener('click' , function () {
            for (lvl = 0; lvl <= STrChOMaxThroneLevel; lvl++) document.getElementById('STrChOThroneLevel' + lvl).checked = false;
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneSelectAllLevels').addEventListener('click', function () {
            for (lvl = 0; lvl <= STrChOMaxThroneLevel; lvl++) document.getElementById('STrChOThroneLevel' + lvl).checked = true;
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        document.getElementById('STrChOThroneLevelFilterRow').addEventListener('change', function () {
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);


        document.getElementById('STrChOThroneFactionFilterRow').addEventListener('change', function () {
            t.createThroneItemList();
            t.paintThroneTables();
        }, false);

        t.createThroneItemList();
        t.paintThroneTables();

	},

	hide: function () {},

    showNextThroneLevel: function () {
        var t = Tabs.throneOrganizer;
        if (t.panelId < 0) return;
        var X = uW.kocThroneItems[t.panelId];
        if (X.level == STrChOMaxThroneLevel) return;
        var V = 'next';
        var P = t.panelType;

        var level = X.level || 0;
        var quality = X.quality || 0;

        var bump = t.panelNextLevel;

        if (P == 'enhance') {
            if ((quality + bump) > 5) {
                bump = 5 - quality;
            }
        }
        else if ((level + bump) > STrChOMaxThroneLevel) {
            bump = STrChOMaxThroneLevel - level;
        }

        var R = [],
            Q, Y, S, U, N = {},
            T, W;
        if (V == 'next') {
            if (P == 'enhance') {
                quality += bump;
                document.getElementById('nextStatContainer').firstChild.innerHTML = X.createPrefix();
            } else {
                if (P == "upgrade") {
                    level += bump;
                    document.getElementById('nextStatContainer').firstChild.innerHTML = 'Level ' + level;
                }
            }
        }

        $.each(X.effects, function (Z, aa) {
            Q = +(Z.split('slot')[1]);
            Y = CM.thronestats.effects[aa.id];
            S = CM.thronestats.tiers[aa.id][aa.tier];
            if (!S) CM.thronestats.tiers[aa.id][aa.tier - 1]
            var base = S.base || 0;
            var growth = S.growth || 0;

            U = +(base) + ((level * level + level) * +(growth) / 2);

            var wholeNumber = false;
            if (Math.round(U) == U) wholeNumber = true;

            if (wholeNumber)
                U = U.toFixed(0);
            else
                U = U.toFixed(2);

            if (Q % 2 == 0) {
                T = 'even'
            } else {
                T = 'odd'
            }
            if (Q <= quality) {
                if (U > 1) {
                    R.push('<li class="' + T + '">' + Y[1] + ' +' + U + '%</li>')
                } else {
                    R.push('<li class="' + T + '">' + Y[1] + ' ' + U + '%</li>')
                }
            } else {
                R.push('<li class="disabled ' + T + '">' + Y[1] + ' + ' + U + '%</li>')
            }
        });
        if (V == 'next') {
            if (P == 'enhance') {
                quality -= bump
            } else {
                if (P == 'upgrade') {
                    level -= bump;
                }
            }
        }
        if (V === 'next') {
            if (CM.ThronePanelController.isLastLevel(X, P)) {
                var nextStatContainer = document.getElementById('nextStatContainer');
                if (nextStatContainer.children.length < 3) {
                    W = '<div id=lockedStatIcon class=lock></div>';
                    nextStatContainer.innerHTML += W;
                }
            } else {
                var elem = document.getElementById('lockedStatIcon');
                if (elem) elem.parentNode.removeChild(elem);
            }
        }
        t.panelNextLevel++;
        document.getElementById('thronePanelStat2').innerHTML = R.join('');

        var lis = document.getElementById('thronePanelStat2').getElementsByTagName('li');
        for (var i =0; i<lis.length; i++) {
            var li = lis[i];
            li.addEventListener('mouseenter', function (Z) {
                uW.Tooltip.show(Z, this.innerHTML, [-180, 5]);
            }, false);
        }
    },

    createThroneItemList: function () {
        var t = Tabs.throneOrganizer;

        for (tct = 0; tct < throneCardTypes.length; tct++) t.throneItemLists[throneCardTypes[tct]] = new Array;
        for (throneId in uW.kocThroneItems) {
            var throneItem = uW.kocThroneItems[throneId];

            // apply filters
            var faction = throneItem.faction;
            var level = throneItem.level;
            var thronetype = throneItem.type;
            var quality = throneItem.quality;
            var unique = throneItem.unique != 0;

            var jewelQuality = 0;
            var isBroken = throneItem.isBroken;

            var noJewel = document.getElementById('STrChOThroneJewelNone').checked;
            var hasJewel = (throneItem.jewel == null ? false : true);
            if (hasJewel) jewelQuality = throneItem.jewel.quality;

            if (jewelQuality > 0) {
                if (!(document.getElementById('STrChOThroneJewel' + jewelQuality).checked)) continue;
            } else {
                if (!noJewel) continue;
            }

            if (STrChOThroneUpgradeData.ignoreBroken && isBroken) continue;
            if (!(document.getElementById('STrChOThroneQualityUnique').checked) && unique) continue;
            if (!(document.getElementById('STrChOThroneQuality' + quality).checked) && !unique) continue;
            if (!(document.getElementById('STrChOThroneFaction' + faction).checked)) continue;
            if (!(document.getElementById('STrChOThroneLevel' + level).checked)) continue;

            var filterEffect = document.getElementById('STrChOThroneFilterEffects').value;
            if (filterEffect != 'none') {
                var filterBuff = document.getElementById('STrChOThroneFilterBuffType').value;
                if (filterBuff == 'debuff') filterEffect += ' Debuff';
                var foundEffect = false;
                for (e in throneItem.effects) {
                    var N = throneItem.effects[e];
                    var effect = CM.thronestats.effects[N.id][1];
                    if (effect == filterEffect) {
                        foundEffect = true;
                        break;
                    }
                }

                if (!foundEffect) continue;
            }

            if (throneItem.isEquipped)
                t.throneItemLists[thronetype].unshift(throneItem);
            else
                t.throneItemLists[thronetype].push(throneItem);

        }
        t.sortThroneOrganizerLists();

    },

    paintThroneTables: function () {
        var t = Tabs.throneOrganizer;
        for (tct in t.throneItemLists) {
			var m = '<table><tr>';
			var divCards = document.getElementById('STrChOThroneCardSection' + tct);
			divCards.innerHTML = "<div></div>";
			for (idx = 0; idx < t.throneItemLists[tct].length; idx++) {
				var throneItem = t.throneItemLists[tct][idx];
				m += '<td><div class=STrChOThroneCard id=STrChOThroneCard' + throneItem.id + '>';
				m += BuildThroneCard(throneItem);
				m += '</div></td>';
			}
			m += '</tr></table>';
			divCards.innerHTML = '<div>' + m + '</div>';
        }
        var STrChOCards = document.getElementsByClassName('STrChOThroneCard');
        for (idx = 0; idx < STrChOCards.length; idx++) {
            STrChOCards[idx].addEventListener('click', function (A) {
                A.stopPropagation();
                var throneId = this.id.split('STrChOThroneCard')[1];
                var throneItem = uW.kocThroneItems[throneId];
                CardContextMenu(this, throneItem, true);
            }, false);
        }
        Tabs.thronePresets.paintTags();
    },

	show: function () {
		var t = Tabs.throneOrganizer;
        t.createThroneItemList();
        t.paintThroneTables();
	},

    sortThroneOrganizerLists: function () {
        var t = Tabs.throneOrganizer;
        STrChOThroneUpgradeData.sortInactive = document.getElementById('STrChOThroneSortInactive').checked;
        for (tct in t.throneItemLists) {
			t.throneItemLists[tct].sort(function (item1, item2) {
				return t.sortThroneOrganizerValue(item2) - t.sortThroneOrganizerValue(item1);
			});
        }
    },

    sortThroneOrganizerValue: function (item) {
        var t = Tabs.throneOrganizer;
        var retValue = 0.0;
        for (e in item.effects) {
            try {
                var N = item.effects[e];
                var effect = CM.thronestats.effects[N.id][1];

                var tier = CM.thronestats.tiers[N.id][N.tier];
                if (!tier) CM.thronestats.tiers[N.id][N.tier - 1]

                var B = +(e.split("slot")[1]);
                var base = tier.base || 0;
                var level = item.level || 0;
                var growth = tier.growth || 0;
                var quality = item.quality || 0;

                if (B > quality && !STrChOThroneUpgradeData.sortInactive) {
                    return +retValue;
                }

                var percent = +(base + ((level * level + level) * growth * 0.5));
                if ((effect == (t.sortEffect + " Debuff")) && (t.buffType != "buff")) {
                    retValue -= percent;
                }
                else if (effect == t.sortEffect && t.buffType != "debuff") {
                    retValue += percent;
                }
            } catch (e) {

            }

        }
        return +retValue;
    },

    unequipItem: function (I, preset) {
        var t = Tabs.throneOrganizer;
        if (!I) return;
        uW.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "throneRoom\\ThroneRoomServiceAjax",
            action: "unequipItem",
            itemId: I.id,
            presetId: preset
        }, function (u) {
            if (u.ok === true) {
                CM.ThroneView.clickItemUnequip(I);
            } else {
                CM.ModalManager.alert({
                    button_text: uW.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        uW.Modal.hideModalAll();
                        CM.ModalManager.close()
                    }
                })
            }
        }, function (u) {
        });
    },

    equipItem: function (I, preset) {
        if (!I) return;
        uW.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "throneRoom\\ThroneRoomServiceAjax",
            action: "equipItem",
            itemId: I.id,
            presetId: preset
        }, function (u) {
            if (u.ok === true) {
                CM.ThroneView.clickItemEquip(I);
            } else {
                CM.ModalManager.alert({
                    button_text: uW.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        uW.Modal.hideModalAll();
                        CM.ModalManager.close()
                    }
                })
            }
        }, function (u) {
        })
    },

}
Tabs.throneSorter = {
	tabOrder: 105,
	tabLabel: 'SORTER',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM SORTER',
    STrChOLocalSwapFile: null,
    STrChOLocalSwapPresets: [],

	init: function (div) {
		var t = Tabs.throneSorter;
		t.mydiv = div;
	},


	hide: function () {},

	show: function () {
		var t = Tabs.throneSorter;

        t.STrChOLocalSwapFile = null;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div style="margin-top: 5px;">';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';
        if (STrChOGeneralOptions.throneSorter) {
            m += '<input type=button class=STrChOButton id=STrChOThroneSorterPower value="Sorter = ON">';
        } else {
            m += '<input type=button class=STrChOButton id=STrChOThroneSorterPower value="Sorter = OFF">';
        }
        m += '</td></tr>';
        m += '<tr><td colspan=3><b><font color=red>WARNINGS!</font></b></td></tr>';
        m += '<tr><td colspan=3>Sorter tab and throne panel will not sync until the other is redrawn by closing/reopening it.</td></tr>';
        m += '<tr><td colspan=3>Salvaging with throne sorter on, WILL decrease the rate of salvaging</td></tr>';
        m += '<tr><td colspan=3><hr class=STrChOHRCenter></td></tr>';
        m += '<tr><td class=indent5 colspan=3>&nbsp;';
        m += '<input id=STrChOSorterDefaults type=button class=STrChOButton value="Restore Default Order">';
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
        m += '<input id=STrChOSorterExport type=button class=STrChOButton value="Export">&nbsp;&nbsp;&nbsp;&nbsp;';
        m += '<input id=STrChOSorterImport type=button class=STrChOButton value="Import">&nbsp;';
        m += '<input id=STrChOSorterImportTrigger type=button class=STrChOButton value="Browse..."  onclick="document.getElementById(\'STrChOSorterImportLoadItem\').click()">';
        m += '<input hidden id=STrChOSorterImportLoadItem type=file>';
        m += '</td></tr>';
        m += '<tr><td colspan=3></td></tr>';
        m += '<tr>';

        m += '<td width=230px align=center style="vertical-align: top; text-align: middle;">';

        m += '<table width=100%>';
        m += '<tr><td align=center>';
        m += 'Slot: <select id=STrChOThroneSorterPreset class=STrChOSelect><option value="0">--Select--</option>';
        var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);
        for (var i = 1; i < presetSlots + 1; i++) {
            m += '<option value="' + i + '">' + i + ':' + STrChOThronePresetData.presetNames[i] + '</option>';
        }
        m += '</select><input type=button class=STrChOButton value="Select" id=STrChOThroneSorterPresetGo>';
        m += '</td></tr>';
        m += '<tr><td align=center>';
        m += '<b>SELECTED CARD:</b><br><div id=STrChOThroneSortCard></div>';
        m += '</td></tr>';
        m += '</table>';
        m += '</td>';


        m += '<td width=180px>';
        m += '<div id=STrChOThroneSorterInventoryList style="height: 405px; width: 180px; overflow-y: auto;">';

        if (STrChOThroneSorter.length == 0) resetThroneSorter();
        var row = 0;

        for (var idx = 0; idx < STrChOThroneSorter.length; idx++) {
            if (idx % 5 == 0) {
                row++;
                m += '<div id=STrChOThroneSorterInventoryRow' + row + ' class="active">';
            }

            var throneId = STrChOThroneSorter[idx];
            var throneItem = uW.kocThroneItems[throneId];
            if (!throneItem) continue;
            var className = '';
            className += throneItem.type + ' ';
            className += throneItem.faction + ' ';
            className += 'quality' + throneItem.quality;
            if (throneItem.unique > 0) className += ' unique' + throneItem.unique;

            img = getThroneImage(throneItem);

            if (t.STrChOLocalSwapFile == throneId) img = success_image;

            m += '<img id=STrChOThroneSorterInventoryIcon' + throneId + ' class=STrChOThroneSorterItem src="' + img + '" style="height: 30px; width: 30px;">';

            if (idx == STrChOThroneSorter.length-1 && idx % 5 != 4) m += '</div>';
            if (idx % 5 == 4) m += '</div>';
        }
        m += '</div>';
        m += '</td>';


        m += '<td width=230px align=center style="vertical-align: top; text-align: middle;">';
        m += '<b>HOVER CARD:</b><br><div id=STrChOThroneSortCardHover></div>';
        m += '</td>';

        m += '</tr>';
        m += '</table>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        t.displaySelectCard();

        document.getElementById('STrChOThroneSorterPresetGo').addEventListener('click', function() {
            if (!STrChOGeneralOptions.throneSorter) return;
            if (t.STrChOLocalSwapFile != null) return;
            var STrChOThroneSorterPreset = document.getElementById('STrChOThroneSorterPreset');
            if (STrChOThroneSorterPreset.value == 0) return;
            var STrChOThroneSorterPresetGo = document.getElementById('STrChOThroneSorterPresetGo');
            var STrChOThroneSortCard = document.getElementById('STrChOThroneSortCard');
            if (STrChOThroneSorterPresetGo.value == 'Select') {

                var equipped_items = Seed.throne.slotEquip[STrChOThroneSorterPreset.value];
                STrChOThroneSortCard.innerHTML = equipped_items.length + ' Cards Selected<br>From Slot ' + STrChOThroneSorterPreset.value;
                for (var ei = 0; ei < equipped_items.length; ei++) {
                    var throneId = parseInt(equipped_items[ei]);
                    t.STrChOLocalSwapPresets.push(throneId);
                    document.getElementById('STrChOThroneSorterInventoryIcon' + throneId).src = success_image;
                }
                STrChOThroneSorterPreset.disabled = true;
                STrChOThroneSorterPresetGo.value = 'Unselect';
            } else {
                STrChOThroneSortCard.innerHTML = 'No Card(s) Selected';
                for (var ei = 0; ei < t.STrChOLocalSwapPresets.length; ei++) {
                    var throneId = t.STrChOLocalSwapPresets[ei];
                    document.getElementById('STrChOThroneSorterInventoryIcon' + throneId).src = getThroneImage(uW.kocThroneItems[throneId]);
                }
                t.STrChOLocalSwapPresets = [];
                STrChOThroneSorterPresetGo.value = 'Select';
                STrChOThroneSorterPreset.disabled = false;
            }
        }, false);

        document.getElementById('STrChOThroneSorterPower').addEventListener('click', function () {
            t.togglePower(this);
        }, false);

        var STrChOThroneSorterItems = document.getElementsByClassName('STrChOThroneSorterItem');

        for (var idx = 0; idx < STrChOThroneSorterItems.length; idx++) {
            var STrChOThroneSorterItem = STrChOThroneSorterItems[idx];
            STrChOThroneSorterItem.addEventListener('mouseover', function(A) {
                A.stopPropagation();
                var throneId = this.id.split('STrChOThroneSorterInventoryIcon')[1];
                var throneItem = uW.kocThroneItems[throneId];
                document.getElementById('STrChOThroneSortCardHover').innerHTML = howManyThroneSlots(throneId) + '<br>' + BuildThroneCard(throneItem);
            }, false);

            STrChOThroneSorterItem.addEventListener('mouseout', function(A) {
                A.stopPropagation();
                var throneId = this.id.split('STrChOThroneSorterInventoryIcon')[1];
                var throneItem = uW.kocThroneItems[throneId];
                document.getElementById('STrChOThroneSortCardHover').innerHTML = '';
            }, false);


            STrChOThroneSorterItem.addEventListener('contextmenu', function(A) {
                A.preventDefault();
                if (!STrChOGeneralOptions.throneSorter) return;
                if (t.STrChOLocalSwapPresets.length > 0) {
                    var thisThroneId = parseInt(this.id.split('STrChOThroneSorterInventoryIcon')[1]);
                    var foundIndex = 0;
                    var tempSwapper = [];
                    for (var i = 0; i < STrChOThroneSorter.length; i++) {
                        var throneId = parseInt(STrChOThroneSorter[i]);
                        if (thisThroneId == throneId) {
                            foundIndex = i;
                            break;
                        }
                        if (t.STrChOLocalSwapPresets.indexOf(throneId) == -1) {  //not found in local swap list
                            tempSwapper.unshift(throneId);
                        }

                    }
                    for (var i = 0; i < t.STrChOLocalSwapPresets.length; i++ ) {
                        tempSwapper.unshift(parseInt(t.STrChOLocalSwapPresets[i]));
                    }
                    for (var i = foundIndex; i < STrChOThroneSorter.length; i++) {
                        var throneId = parseInt(STrChOThroneSorter[i]);
                        if (t.STrChOLocalSwapPresets.indexOf(throneId) == -1) { //not found in swap list
                            tempSwapper.unshift(throneId);
                        }
                    }
                    t.STrChOLocalSwapPresets = [];
                    STrChOThroneSorter = [];
                    while (tempSwapper.length > 0) STrChOThroneSorter.push(tempSwapper.pop());
                    SAVESTrChOThroneSorter();
                    t.show();
                    return;
                }

                var throneId = this.id.split('STrChOThroneSorterInventoryIcon')[1];
                var throneItem = uW.kocThroneItems[throneId];
                if (!throneItem || throneItem == null) {
                    if (t.STrChOLocalSwapFile == throneId) $(this).remove();
                    t.STrChOLocalSwapFile = null;
                    setThroneSorter(true);
                    SAVESTrChOThroneSorter();
                    t.show();
                    return;
                }
                if (t.STrChOLocalSwapFile == null) {
                    t.STrChOLocalSwapFile = throneId;
                    this.src = success_image;
                    t.displaySelectCard();
                } else {
                    if (t.STrChOLocalSwapFile == throneId) {
                        t.STrChOLocalSwapFile = null;
                        this.src = getThroneImage(throneItem);
                        t.displaySelectCard();
                        return;
                    }

                    var img = document.getElementById('STrChOThroneSorterInventoryIcon' + t.STrChOLocalSwapFile);
                    img.src = getThroneImage(uW.kocThroneItems[t.STrChOLocalSwapFile]);


                    var fromTile = document.getElementById('STrChOThroneSorterInventoryIcon' + t.STrChOLocalSwapFile);
                    var fromTilePosition = 0;
                    var child = fromTile;
                    while( (child = child.previousSibling) != null ) fromTilePosition++;

                    var toTile = document.getElementById('STrChOThroneSorterInventoryIcon' + throneId);
                    var toTilePosition = 0;
                    child = this;
                    while( (child = child.previousSibling) != null ) toTilePosition++;

                    var fromParent = fromTile.parentElement;
                    var toParent = toTile.parentElement;

                    var fromDelete = fromParent.children[fromTilePosition];
                    var toDelete = toParent.children[toTilePosition];

                    if (fromParent != toParent) { //simple swap
                        $(fromDelete).remove();
                        $(toDelete).remove();
                        fromParent.insertBefore(toTile, fromParent.childNodes[fromTilePosition]);
                        toParent.insertBefore(fromTile, toParent.childNodes[toTilePosition]);
                    } else { //little more tricky
                        var newRow = [];
                        for (var idx = 0; idx < fromParent.children.length; idx++) {
                            if (idx == fromTilePosition) {
                                newRow.unshift(toTile);
                            } else if (idx == toTilePosition) {
                                newRow.unshift(fromTile);
                            } else {
                                newRow.unshift(fromParent.children[idx]);
                            }
                        }
                        while (fromParent.hasChildNodes()) fromParent.removeChild(fromParent.lastChild);
                        while (newRow.length > 0) fromParent.appendChild(newRow.pop());
                    }
                    t.STrChOLocalSwapFile = null;
                    t.displaySelectCard();
                    setThroneSorter(true);
                    SAVESTrChOThroneSorter();
                    t.show();
                }
            }, false);
        }

        document.getElementById('STrChOSorterDefaults').addEventListener('click', function () {
            resetThroneSorter();
            t.STrChOLocalSwapFile = null;
            var cmContainerOpen = (document.getElementsByClassName('cmModalContainer').length == 1 ? true : false);
            if (cmContainerOpen) {
                var titlebar = document.getElementsByClassName('primarytitlebar')[0];
                var closebutton = titlebar.children[2];
                closebutton.click();
                setTimeout(function () { CM.ThroneView.openThrone(); }, 100);
            }
            t.show();
        }, false);

        document.getElementById('STrChOSorterExport').addEventListener('click', function () {
            if (STrChOThroneSorter.length == 0) return;
            uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(STrChOThroneSorter));
            newWindow = window.open(uriContent, 'file.txt');
        }, false);

        document.getElementById('STrChOSorterImport').addEventListener('click', function () {
            var fileInput = document.getElementById("STrChOSorterImportLoadItem");
            var files = fileInput.files;
            if (files.length==0) {
                alert('Please Select A File');
                return;
            }
            var file = files[0];

            var reader = new FileReader();

            reader.onload = function (e) {
				var output = e.target.result;
				STrChOThroneSorter = JSON.parse(output);
                SAVESTrChOThroneSorter();
                t.show();
                alert('Throne Sorted Order Now Loaded From File');
            };
            reader.readAsText(file);
        }, false);


    },

    togglePower: function (obj) {
        var t = Tabs.throneSorter;

        var STrChOThroneSorterPower = document.getElementById('STrChOThroneSorterPower');

        if (STrChOGeneralOptions.throneSorter) {
            STrChOGeneralOptions.throneSorter = false;
            STrChOThroneSorterPower.value = "Sorter = OFF";
        } else {
            if (STrChOThroneSalvageData.active) {
                if (!confirm('SORTER WARNING: You will likely experience lowered salvage rates and potentially crashing if you have both sorter and salvager enabled.  Would you like to continue?')) return;
            }
            STrChOGeneralOptions.throneSorter = true;
            STrChOThroneSorterPower.value = "Sorter = ON";
        }
        SAVESTrChOThroneSorter();

        var cmContainerOpen = (document.getElementsByClassName('cmModalContainer').length == 1 ? true : false);
        if (cmContainerOpen) {
            var titlebar = document.getElementsByClassName('primarytitlebar')[0];
            var closebutton = titlebar.children[2];
            closebutton.click();
            setTimeout(function () { CM.ThroneView.openThrone(); }, 100);
        }

        t.updateThroneMenu();

    },

    updateThroneMenu: function () {
        if (!document.getElementById('STrChOExecuteSorter')) return;
        document.getElementById('STrChOExecuteSorter').innerHTML = 'Sorter ' + (STrChOGeneralOptions.throneSorter ? 'ON' : 'OFF');
    },


    displaySelectCard: function () {
        var t = Tabs.throneSorter;
        if (t.STrChOLocalSwapFile == null) {
            document.getElementById('STrChOThroneSortCard').innerHTML = "No Card(s) Selected";
        } else {
            var throneItem = uW.kocThroneItems[t.STrChOLocalSwapFile];
            document.getElementById('STrChOThroneSortCard').innerHTML = howManyThroneSlots(t.STrChOLocalSwapFile) + '<br>' + BuildThroneCard(throneItem);
        }
    },

}

Tabs.throneEnhStats = {
	tabOrder: 106,
	tabLabel: 'ENH&nbsp;STATS',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM ENHANCEMENT STATS',

	init: function (div) {
		var t = Tabs.throneEnhStats;
		t.mydiv = div;
        t.buildThroneEnhStatsDisplay();
	},

	hide: function () {},

	buildThroneEnhStatsDisplay: function () {

        var t = Tabs.throneEnhStats;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

//        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - (dlgWidthOffset*2.5)) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

        m += '<table class=STrChOStats align=center cellspacing=0>';

        m += '<tr valign=top align=center><th colspan=' + (STrChOMaxThroneQuality + 2) + '>Enhancing Numbers  (successes/failures)</th></tr>';

        m += '<tr valign=top align=center><th></th>';
        for (qual = 0; qual <= STrChOMaxThroneQuality; qual++) m += '<td style="font-weight: bold;" class="td' + (qual % 2 + 1) + '"  >' + throneCardQualities[qual].capitalizeFirstLetter() + '&nbsp;</td>';
        m += '</tr>';

        var st = [0, 0, 0, 0, 0, 0, 0];
        var ft = [0, 0, 0, 0, 0, 0, 0];

        for (lvl = 0; lvl <= STrChOMaxThroneLevel; lvl++) {
            m += '<tr valign=top align=center>';
            m += '<th>';
            if (lvl != 0) m += '+';
            m += lvl + '</th>';
            for (qual = 0; qual < (STrChOMaxThroneQuality+1); qual++) {
                if (STrChOThroneUpgradeStats.enhanceSuccess[qual][lvl] == null) STrChOThroneUpgradeStats.enhanceSuccess[qual][lvl] = 0;
                if (STrChOThroneUpgradeStats.enhanceFailure[qual][lvl] == null) STrChOThroneUpgradeStats.enhanceFailure[qual][lvl] = 0;
                st[qual] += STrChOThroneUpgradeStats.enhanceSuccess[qual][lvl];
                ft[qual] += STrChOThroneUpgradeStats.enhanceFailure[qual][lvl];
                m += '<td class="td' + (qual % 2) + '"  >' + STrChOThroneUpgradeStats.enhanceSuccess[qual][lvl] + ' / ' + STrChOThroneUpgradeStats.enhanceFailure[qual][lvl] + '</td>';
            }
            m += '</tr>';
        }

        m += '<tr valign=top align=center><th> Totals: </th>';
        for (qual = 0; qual < (STrChOMaxThroneQuality+1); qual++) m += '<td style="font-weight: bold;" class="td' + (qual % 2) + '" >' + st[qual] + ' / ' + ft[qual] + '</td>';
        m += '</tr>';

        m += '<TR valign=top align=center><th> Percents: </th>';
        for (qual = 0; qual < (STrChOMaxThroneQuality+1); qual++) {
            m += '<td style="font-weight: bold;" class="td' + (qual % 2) + '" >';
            if ((st[qual] + ft[qual]) == 0)
                m += "--";
            else {
                var perc = (100 * st[qual] / (st[qual] + ft[qual]));
                m += perc.toFixed(2) + '%';
            }
            m += '</td>';
        }
        m += '</tr>';

        m += '</table>';
        m += '</div>';

        m += '<center><input type=button class=STrChOButton value="Clear Stats" id=STrChOThroneEnhStatsClear></center>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOThroneEnhStatsClear').addEventListener('click', function () {

            var t = Tabs.throneEnhStats;
            for (lvl = 0; lvl <= STrChOMaxThroneLevel; lvl++) {
                for (qual = 0; qual < (STrChOMaxThroneQuality+1); qual++) {
                    STrChOThroneUpgradeStats.enhanceSuccess[qual][lvl] = null;
                    STrChOThroneUpgradeStats.enhanceFailure[qual][lvl] = null;
                }
            }
            SAVESTrChOThroneUpgradeStats();
            t.buildThroneEnhStatsDisplay();

        }, false);

    },

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

Tabs.throneUpgStats = {
	tabOrder: 107,
	tabLabel: 'UPG&nbsp;STATS',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM UPGRADE STATS',

	init: function (div) {
		var t = Tabs.throneUpgStats;
		t.mydiv = div;
        t.buildThroneUpgStatsDisplay();
	},

	hide: function () {},

	buildThroneUpgStatsDisplay: function () {

		var t = Tabs.throneUpgStats;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - (dlgWidthOffset*2.5)) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table class=STrChOStats align=center cellspacing=0>';

        m += '<tr valign=top align=center><th colspan=' + (STrChOMaxThroneLevel+2) + '>Upgrading Numbers  (successes/failures)</TH></TR>';

        m += '<tr valign=top align=center><th></th>';
        for (lvl = 0; lvl < STrChOMaxThroneLevel; lvl++) m += '<td style="font-weight: bold;" class="td' + (lvl % 2) + '"  >&nbsp;+' + (lvl + 1) + '&nbsp;</td>';
        m += '</tr>';

        var st = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0];  //TODO: change when game changes max throne level (currently 52)
        var ft = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0];

        for (qual = 0; qual <= STrChOMaxThroneQuality; qual++) {
            m += '<tr valign=top align=center><th>' + throneCardQualities[qual].capitalizeFirstLetter() + '</th>';
            for (lvl = 0; lvl < STrChOMaxThroneLevel; lvl++) {
                if (STrChOThroneUpgradeStats.upgradeSuccess[qual][lvl] == null || isNaN(STrChOThroneUpgradeStats.upgradeSuccess[qual][lvl])) STrChOThroneUpgradeStats.upgradeSuccess[qual][lvl] = 0;
                if (STrChOThroneUpgradeStats.upgradeFailure[qual][lvl] == null || isNaN(STrChOThroneUpgradeStats.upgradeFailure[qual][lvl])) STrChOThroneUpgradeStats.upgradeFailure[qual][lvl] = 0;
                st[lvl] += STrChOThroneUpgradeStats.upgradeSuccess[qual][lvl];
                ft[lvl] += STrChOThroneUpgradeStats.upgradeFailure[qual][lvl];

                m += '<td class="td' + (lvl % 2) + '"  >';
                m += STrChOThroneUpgradeStats.upgradeSuccess[qual][lvl] + ' / ' + STrChOThroneUpgradeStats.upgradeFailure[qual][lvl];
                m += '</td>';
            }
            m += '</tr>';
        }

        m += '<tr valign=top align=center><th> Totals: </th>';
        for (lvl = 0; lvl < STrChOMaxThroneLevel; lvl++) m += '<td style="font-weight: bold;" class="td' + (lvl % 2) + '"  >' + st[lvl] + " / " + ft[lvl] + '</td>';
        m += '</tr>';

        m += '<tr valign=top align=center><th> Percents: </th>';
        for (lvl = 0; lvl < STrChOMaxThroneLevel; lvl++) {
            m += '<td style="font-weight: bold;" class="td' + (lvl % 2) + '"  >';
            if ((st[lvl] + ft[lvl]) == 0)
                m += '--';
            else {
                var perc = (100 * st[lvl] / (st[lvl] + ft[lvl]));
                m += perc.toFixed(2) + '%';
            }
            m += '</td>';
        }
        m += '</tr>';

        m += '</table>';
        m += '</div>';

        m += '<center><input type=button class=STrChOButton value="Clear Stats" id=STrChOThroneUpgStatsClear></center>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOThroneUpgStatsClear').addEventListener('click', function () {
            var t = Tabs.throneUpgStats;
            for (lvl = 0; lvl <= STrChOMaxThroneLevel; lvl++) {
                for (qual = 0; qual < (STrChOMaxThroneQuality+1); qual++) {
                    STrChOThroneUpgradeStats.upgradeSuccess[qual][lvl] = null;
                    STrChOThroneUpgradeStats.upgradeFailure[qual][lvl] = null;
                }
            }
            SAVESTrChOThroneUpgradeStats();
            t.buildThroneUpgStatsDisplay()
        }, false);

    },

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

Tabs.thronePresets = {
	tabOrder: 108,
	tabLabel: 'PRESETS',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM PRESETS',
    broke_count: 0,
    broke_items: 0,
    delay: 1000,

	init: function (div) {
		var t = Tabs.thronePresets;
		t.mydiv = div;
        //t.show();
	},

	hide: function () {},

    refreshBrokeMightDisplay: function () {
        document.getElementById('STrChOThroneMightBroke').innerHTML = getThroneBrokeMight();
    },

	show: function () {
		var t = Tabs.thronePresets;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '<div class=STrChOSaveSettings id=STrChOThronePresetsSaveSettings title="Save Presets Settings"></div><div class=STrChOLoadSettings id=STrChOThronePresetsLoadSettings title="Load Presets Settings"></div></div>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table>';
        m += '<tr><td width=100%>Preset Color: <select class=STrChOSelect id=STrChOThronePresetColor>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (STrChOThronePresetData.presetColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;General Color: <select class=STrChOSelect id=STrChOThroneTagColor>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (STrChOThronePresetData.tagColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;Active Color: <select class=STrChOSelect id=STrChOThroneActiveColor>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (STrChOThronePresetData.activeColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>(Requires Refresh)</td></tr>';
        m += '<tr><td>';
        m += '<input type=button class=STrChOButton id=STrChOThroneClearTags value="Clear All Tags">&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton id=STrChOThroneClearAllPresetTags value="Clear All Preset Tags">&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton id=STrChOThroneSaveAllPresetTags value="Save All Preset Tags">&nbsp;&nbsp;';
        //m += '<input type=button id=trExportPresetTags value="Export Preset Tags">';
        m += '</td></tr>';
        m += '<tr><td>';
        m += '<input type=checkbox class=STrChOCheckbox id=STrChOThroneShowMight ' + (STrChOThronePresetData.showThroneMight ? 'CHECKED' : '') + '/>Show Might on Posts';
        m += '&nbsp;&nbsp;&nbsp;<input type=checkbox class=STrChOCheckbox id=STrChOThroneShowName ' + (STrChOThronePresetData.showThroneName ? 'CHECKED' : '') + '/>Show Preset Name on Posts';
        m += '</td></tr>';
        m += '</table>';


        m += '<div class=STrChOHeader id=STrChOThronePresetNaming onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;PRESET NAMING&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);
        var presetsList = "";
        for (i = 1; i < presetSlots + 1; i++) {
            presetsList += '<option value="' + i + '">' + i + '</option>';
        }
        for (i = 1; i < presetSlots + 1; i++) {
            m += '<tr>';
            m += '<td><input class="STrChOThronePresetSlotPost STrChOButton" type=button id=STrChOThronePreset' + i + ' value="Post Slot"></td>';
            m += '<td><input class="STrChOThronePresetTagPost STrChOButton" type=button id=STrChOThronePreset' + i + ' value="Post Tag"></td>';
            m += '<td>&nbsp;<b>Preset ' + i + ': </b></td>';
            m += '<td><input class=STrChOThronePresetNameEntry type=text size=15 id=STrChOThronePresetName' + i + ' value="' + STrChOThronePresetData.presetNames[i] + '"></td>';
            m += '<td><input class="STrChOThronePresetCopyTo STrChOButton" type=button id=STrChOThronePreset' + i + ' value="Copy To"><select class=STrChOSelect id=STrChOThronePresetCopyToWhat' + i + '>' + presetsList + '</select></td>';
            m += '<td><input class="STrChOThronePresetSave STrChOButton" type=button id=STrChOThronePreset' + i + ' value="Save"></td>';

            if (getThronePresetTagCount(i) != 0) {
                m += '<td><input class="STrChOThronePresetClear STrChOButton" type=button id=STrChOThronePreset' + i + ' value="Clear"></td>';
                m += '<td><input class="STrChOThronePresetExcel STrChOButton" type=button id=STrChOThronePreset' + i + ' value="Excel"></td>';
            } else {
                m += '<td/><td/>';
            }
            m += '</tr>';
        }
        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;THRONE ROOM BREAKING&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td><div id=STrChOThroneMightBroke>You have 0 throne room might broken</div></td></tr>';
        m += '<tr><td><input type=checkbox checked class=STrChOCheckbox id=STrChOThroneExcludePresets>Exclude Tagged Presets</td></tr>';
        m += '<tr><td><input type=checkbox checked class=STrChOCheckbox id=STrChOThroneExcludeTags>Exclude Regular Tagged</td></tr>';
        m += '<tr><td>Break Items Level <select class=STrChOSelect id=STrChOThroneBreakLevelLow>';
        for (lvl = 1; lvl < STrChOMaxThroneLevel; lvl++) {
            m += '<option value=' + lvl + '>+' + lvl + '</option>';
        }
        m += '</select> or Higher</td></tr>';
        m += '<tr><td>Break Items Level <select class=STrChOSelect id=STrChOThroneBreakLevelHigh>';
        for (lvl = 1; lvl < STrChOMaxThroneLevel; lvl++) {
            m += '<option value=' + lvl + (lvl == STrChOMaxThroneLevel - 1 ? ' SELECTED' : '') + '>+' + lvl + '</option>';
        }
        m += '</select> or Lower</td></tr>';

        m += '<tr><td><input type=button class=STrChOButton id=STrChOThroneBreakAll value="Break Now"><font color=red><i>(all options above will reset after refresh)</i></font></td></tr>';
        m += '<tr><td><div id=STrChOThroneBreakCounter></div></td></tr>';
        m += '<tr><td><hr></td></tr>';
        m += '<tr><td>Break Equiped Throne Room Only<select class=STrChOSelect id=STrChOThronePresetEquipBreak>' + presetsList + '</select><input type=button class=STrChOButton id=STrChOThronePresetEquipBreakNow value="Break Now"></td></tr>';
        m += '<tr><td>Break Tagged Preset Only<select class=STrChOSelect id=STrChOThronePresetTaggedBreak>' + presetsList + '</select><input type=button class=STrChOButton id=STrChOThronePresetTaggedBreakNow value="Break Now"></td></tr>';
        m += '<tr><td>Break <input type=number class=STrChOText id=STrChOThroneMightBreak oncontextmenu="return false;"> Throne Might <input type=button class=STrChOButton id=STrChOThroneMightBreakNow value="Break Now"></td></tr>';
        m += '</table>';
        m += '</div>';
        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOThronePresetsSaveSettings').addEventListener('click', function () {
            SaveSettingsToFile(STrChOThronePresetData);
        }, false);
        document.getElementById('STrChOThronePresetsLoadSettings').addEventListener('click', function () {
            var loader = document.getElementById('STrChOSettingsFile');
            loader.addEventListener('change', function () {
                LoadSettingsFromFile(STrChOThronePresetData, Tabs.thronePresets);
            }, false);
            loader.click();
        }, false);

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        t.refreshBrokeMightDisplay();

        document.getElementById('STrChOThroneShowMight').addEventListener('change', function () {
            STrChOThronePresetData.showThroneMight = document.getElementById('STrChOThroneShowMight').checked;
            SAVESTrChOThronePresetData();
        }, false);

        document.getElementById('STrChOThroneShowName').addEventListener('change', function () {
            STrChOThronePresetData.showThroneName = document.getElementById('STrChOThroneShowName').checked;
            SAVESTrChOThronePresetData();
        }, false);

        document.getElementById('STrChOThroneSaveAllPresetTags').addEventListener('click', function () {
            for (i = 1; i < presetSlots + 1; i++) {
                t.addPresetTags(i);
            }
            t.show();
            document.getElementById('STrChOThronePresetNaming').click();
        }, false);

        document.getElementById('STrChOThroneClearTags').addEventListener('click', function () {
            t.clearAllTagItems();
        }, false);

        document.getElementById('STrChOThroneClearAllPresetTags').addEventListener('click', function () {
            t.clearAllPresetTagItems();
            t.show();
            document.getElementById('STrChOThronePresetNaming').click();
        }, false);

        document.getElementById('STrChOThroneActiveColor').addEventListener('change', function () {
            STrChOThronePresetData.activeColor = document.getElementById('STrChOThroneActiveColor').value;
            SAVESTrChOThronePresetData();
        }, false);

        document.getElementById('STrChOThronePresetColor').addEventListener('change', function () {
            STrChOThronePresetData.PresetColor = document.getElementById('STrChOThronePresetColor').value;
            SAVESTrChOThronePresetData();
        }, false);

        document.getElementById('STrChOThroneTagColor').addEventListener('change', function () {
            STrChOThronePresetData.tagColor = document.getElementById('STrChOThroneTagColor').value;
            SAVESTrChOThronePresetData();
        }, false);

        document.getElementById('STrChOThroneMightBreak').addEventListener('keydown', function (e) {
            // Allow: backspace, delete, tab, escape, enter and .
            if (e.keyCode == 46 || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 27 || e.keyCode == 13 || e.keyCode == 110 || e.keyCode == 190 ||
            // Allow: Ctrl+A
                (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39) ||
            // Allow: F5
                (e.keyCode == 116))
            {
                // let it happen, don't do anything
                return;
            }

            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105) || e.keyCode == 190 || e.keyCode == 110 )
            {
                e.preventDefault();
            }
        }, false);



        document.getElementById('STrChOThroneMightBreak').addEventListener('keyup', function (e) {
            document.getElementById('STrChOThroneMightBreak').value = document.getElementById('STrChOThroneMightBreak').value.replace('.','');
            document.getElementById('STrChOThroneMightBreak').value = document.getElementById('STrChOThroneMightBreak').value.replace(',','');
        }, false);


        function BreakIt( cardsToBreak ) {
            var t = Tabs.thronePresets;

            if (!cardsToBreak || cardsToBreak == null) return;

            if (cardsToBreak.length == 0) {
                alert('No throne items to break');
                return;
            }

            t.broke_count = cardsToBreak.length;

            //t.setBreakStatus();

            t.broke_items = 0;

            //var items_broke = 0;  //this will be the counter for the # of throne items broke

            for (var i = 0; i < cardsToBreak.length; i++) {  //loop through all the throne items to be broke

                var citytobreakfrom = 0;  //start at the first city {the index is 0-based}

                var throne_item = uW.kocThroneItems[cardsToBreak[i]];  //get the next throne item in the collection

                var curr_level = throne_item.level;  //get the current level of the throne item

                var throne_id = throne_item.id;  //get the throne item id

                //var curr_might = throne_item

                if (curr_level == STrChOMaxThroneLevel) continue;  //if for some reason a card at the max level makes it through the list then continue to the next in the list

                var cost_to_upgrade = CM.thronestats.upgrade[curr_level + 1].Stones;  //get the cost of stones to upgrade to the next level

                while (citytobreakfrom < 8) {  //loop through all the 8 cities checking for astone to upgrade for the break feature

                    stones_in_city = parseInt(Seed.resources["city" + Seed.cities[citytobreakfrom][0]]["rec5"][0]);  //get the astone count for the city

                    if (cost_to_upgrade + STrChOBreakBuffer <= stones_in_city) break;  //if you have the astone in the city then stop searching cities and do the upgrade

                    citytobreakfrom = citytobreakfrom + 1;  //search to the next city in the loop

                }

                if (citytobreakfrom == 8) continue;  //if you make it to 8, then you've exhausted all the cities astone search for this throne item, move to the next one

                var params = uW.Object.clone(ajfx);
                params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
                params.action = 'upgradeLevel';
                params.throneRoomItemId = throne_id;
                params.buffItemId = 0;
                params.payment = "aetherstone";
                params.cityId = Seed.cities[citytobreakfrom][0];

                //items_broke = items_broke + 1;
                t.broke_items += 1;

                Seed.resources["city" + Seed.cities[citytobreakfrom][0]]["rec5"][0] = Seed.resources["city" + Seed.cities[citytobreakfrom][0]]["rec5"][0] - cost_to_upgrade;

                new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
                    method: "post",
                    parameters: params,
                    loading: true,
                    onSuccess: function (transport) {
                        try {
                            var rslt = eval("(" + transport.responseText + ")");
                            if (rslt.ok) {
                                if (rslt.updateSeed) uW.update_seed(rslt.updateSeed);
                            }

                            if (rslt.gems > 0) {
                                alert("UNEXPECTED ERROR: 'BREAK TR' accidentally spent gems.... Stopping now!");
                                ActionLog('BREAK TR accidentally spent gems!  Stopping now!');
                                RefreshCamelot();
                                return;
                            }

                            //if (rslt.success) i--;

                        } catch (e) {
                        }
                    },
                    onFailure: function (rrr) {
                        CM.ThroneView.renderInventory(uW.kocThroneItems);
                    }
                });

            }

            CM.ThroneView.renderInventory(uW.kocThroneItems);
            if (t.broke_items == 0) {
                alert('No Items broken. (NOTE: check astone levels if items should have been broke)');
            } else {
                alert('Breaking TR complete.  ' + t.broke_items + ' Throne items were broken.  Page will now refresh.');
                RefreshCamelot();
            }
        }

        document.getElementById('STrChOThroneBreakAll').addEventListener('click', function () {
            if (!confirm('You cannot undo this action, are you sure you want to break your throne room?')) return;
            var excludePresets = document.getElementById('STrChOThroneExcludePresets').checked;
            var excludeTags = document.getElementById('STrChOThroneExcludeTags').checked;
            var breakLevelLow = document.getElementById('STrChOThroneBreakLevelLow').value;
            var breakLevelHigh = document.getElementById('STrChOThroneBreakLevelHigh').value;
            var allTaggedPresets = [];
            if (excludePresets) {
                for (i = 1; i < presetSlots + 1; i++) {
                    if (getThronePresetTagCount(i) != 0) {
                        var thisPreset = getThronePresetObject(i);
                        for (throneId in thisPreset) {
                            var throne_item = uW.kocThroneItems[throneId];
                            if (throne_item == null || !throne_item) continue;
                            if (throne_item.level == STrChOMaxThroneLevel) continue;
                            if (throne_item.level < breakLevelLow || throne_item.level > breakLevelHigh) continue;
                            allTaggedPresets.push(throneId);
                        }
                    }
                }
            }
            var throneToBreak = [];
            for (trId in uW.kocThroneItems) {
                var throne_item = uW.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.isBroken) continue;
                if (excludeTags && STrChOThronePresetData.taggedItems[trId]) continue;
                if (allTaggedPresets.indexOf(trId) != -1) continue;
                if (throne_item.level == STrChOMaxThroneLevel) continue;
                if (throne_item.level < breakLevelLow || throne_item.level > breakLevelHigh) continue;

                throneToBreak.push(trId);
            }
            delete allTaggedPresets;

            BreakIt(throneToBreak);

        }, false);


        document.getElementById('STrChOThroneMightBreakNow').addEventListener('click', function () {
            document.getElementById('STrChOThroneMightBreak').value = document.getElementById('STrChOThroneMightBreak').value.replace('.','');
            document.getElementById('STrChOThroneMightBreak').value = document.getElementById('STrChOThroneMightBreak').value.replace(',','');
            var mightReach = document.getElementById('STrChOThroneMightBreak').value;
            if (!isNumeric(mightReach)) return;
            if (!confirm('You cannot undo this action, are you sure you want to break?')) return;
            var throneToBreak = [];
            var mightTally = 0;
            for (var throneId in uW.kocThroneItems) {
                if (mightTally >= mightReach) break;
                var throne_item = uW.kocThroneItems[throneId];
                var throne_might = CM.ThroneView.getMightBonus(throne_item);
                mightTally += throne_might;
                throneToBreak.push(throneId);
            };
            BreakIt(throneToBreak);
        }, false);

        document.getElementById('STrChOThronePresetEquipBreakNow').addEventListener('click', function () {
            if (!confirm('You cannot undo this action, are you sure you want to break?')) return;
            var throneToBreak = [];
            var equipped_items = Seed.throne.slotEquip[Seed.throne.activeSlot];
            for (ei = 0; ei < equipped_items.length; ei++) { throneToBreak.push(equipped_items[ei]); }
            BreakIt(throneToBreak);
        }, false);

        document.getElementById('STrChOThronePresetTaggedBreakNow').addEventListener('click', function () {
            if (!confirm('You cannot undo this action, are you sure you want to break?')) return;
            var throneToBreak = [];
            var STrChOThronePresetTaggedBreak = document.getElementById('STrChOThronePresetTaggedBreak').value;
            var thronePreset = getThronePresetObject(parseInt(STrChOThronePresetTaggedBreak));
            for (var throneId in thronePreset) throneToBreak.push(throneId);
            BreakIt(throneToBreak);
        }, false);

        function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }


        // read the preset names and descriptions
        var STrChOThronePresetNameEntry = document.getElementsByClassName('STrChOThronePresetNameEntry');
        for (var elem=0; elem<STrChOThronePresetNameEntry.length;elem++) {
            STrChOThronePresetNameEntry[elem].addEventListener('change', function () {
                var id = this.id;
                var num = id.split('STrChOThronePresetName')[1];
                var presetName = this.value;
                if (presetName == "") {
                    presetName = "undefined";
                    this.value = presetName;
                }
                STrChOThronePresetData.presetNames[num] = presetName;
                SAVESTrChOThronePresetData();
            }, false);
            STrChOThronePresetNameEntry[elem].addEventListener('blur', function () {
                var id = this.id;
                var num = id.split('STrChOThronePresetName')[1];
                var presetName = this.value;
                if (presetName == "") {
                    presetName = "undefined";
                    this.value = presetName;
                    STrChOThronePresetData.presetNames[num] = presetName;
                    SAVESTrChOThronePresetData();
                }
            }, false);
        }

        var STrChOThronePresetTagPost = document.getElementsByClassName('STrChOThronePresetTagPost');
        for (var elem=0; elem<STrChOThronePresetTagPost.length;elem++) {
            STrChOThronePresetTagPost[elem].addEventListener('click', function () {
                var id = this.id;
                var num = id.split('STrChOThronePreset')[1];
                postThronePreset(num);
            }, false);
        }

        var STrChOThronePresetSlotPost = document.getElementsByClassName('STrChOThronePresetSlotPost');
        for (var elem=0; elem<STrChOThronePresetSlotPost.length;elem++) {
            STrChOThronePresetSlotPost[elem].addEventListener('click', function () {
                var id = this.id;
                var num = id.split('STrChOThronePreset')[1];
                postThroneSlot(num);
            }, false);
        }

        var STrChOThronePresetCopyTo = document.getElementsByClassName('STrChOThronePresetCopyTo');
        for (var elem=0; elem<STrChOThronePresetCopyTo.length;elem++) {
            STrChOThronePresetCopyTo[elem].addEventListener('click', function () {
                var id = this.id;
                var sourceNum = id.split("STrChOThronePreset")[1];
                var destNum = document.getElementById("STrChOThronePresetCopyToWhat" + sourceNum).value;
                var copyName = document.getElementById("STrChOThronePresetName" + sourceNum).value;
                t.copyPresetTags(sourceNum, destNum, copyName);
                t.show();
                document.getElementById('STrChOThronePresetNaming').click();
            }, false);
        }

        var STrChOThronePresetClear = document.getElementsByClassName('STrChOThronePresetClear');
        for (var elem=0; elem<STrChOThronePresetClear.length;elem++) {
            STrChOThronePresetClear[elem].addEventListener('click', function () {
                var id = this.id;
                var num = id.split("STrChOThronePreset")[1];
                t.clearPresetTags(num);
                t.show();
                document.getElementById('STrChOThronePresetNaming').click();
            }, false);
        }

        var STrChOThronePresetExcel = document.getElementsByClassName('STrChOThronePresetExcel');
        for (var elem=0; elem<STrChOThronePresetExcel.length;elem++) {
            STrChOThronePresetExcel[elem].addEventListener('click', function () {
                var id = this.id;
                var num = id.split("STrChOThronePreset")[1];
                ExportThronePresetToExcel(num);
            }, false);
        }

        var STrChOThronePresetSave = document.getElementsByClassName('STrChOThronePresetSave');
        for (var elem=0; elem<STrChOThronePresetSave.length;elem++) {
            STrChOThronePresetSave[elem].addEventListener('click', function () {
                var id = this.id;
                var num = id.split("STrChOThronePreset")[1];
                t.addPresetTags(num);
                t.show();
                document.getElementById('STrChOThronePresetNaming').click();
            }, false);
        }

  	},

    paintTags: function () {

        var equipped_items = Seed.throne.slotEquip[Seed.throne.activeSlot];

        for (ei = 0; ei < equipped_items.length; ei++) {
            var throneId = equipped_items[ei];
            $("#throneInventoryItem" + throneId).children(".activeBorderThrone").remove(); //remove any tag first before applying the tag to avoid doubling, trippling up on the borders, etc
            $("#throneInventoryItem" + throneId).prepend("<div class='activeBorderThrone'></div>");
        }

        for (p in STrChOThronePresetData.taggedItems) {
            $("#throneInventoryItem" + p).children(".tagBorderThrone").remove(); //remove any tag first before applying the tag to avoid doubling, trippling up on the borders, etc
            $("div#throneInventoryItem" + p).prepend("<div class='tagBorderThrone'></div>");
        }

        for (idx = 1; idx < (STrChOMaxPresets+1); idx++) {
            var preset = getThronePresetObject(idx);
            if (getObjectCollectionCount(preset) > 0) {
                for (p in preset) {
                    $("#throneInventoryItem" + p).children(".presetBorderThrone").remove(); //remove any tag first before applying the tag to avoid doubling, trippling up on the borders, etc
                    $("#throneInventoryItem" + p).prepend("<div class='presetBorderThrone'></div>");
                }
            }
        }

        if (STrChOGeneralOptions.showJewels) {
            for (trId in uW.kocThroneItems) {
                var throne_item = uW.kocThroneItems[trId];
                if (!throne_item.jewel) continue;
                if (throne_item.jewel.valid && !throne_item.isBroken) {
                    $("#throneInventoryItem" + throne_item.id).children(".jewelIcon").remove();
                    $("div#throneInventoryItem" + throne_item.id).append("<div class='jewelIcon'><img style='float:right;' src='" + STrChOJewelImages[throne_item.jewel.quality] + "'></div>");
                }
            }
        }

        $("#advisorContainer").click(function () { ThroneMenuPopup('advisorContainer'); });
        $("#heroContainer").click(function () { ThroneMenuPopup('heroContainer'); });
        $("#chairContainer").click(function () { ThroneMenuPopup('chairContainer'); });
        $("#candelabrumContainer").click(function () { ThroneMenuPopup('candelabrumContainer'); });
        $("#tableContainer").click(function () { ThroneMenuPopup('tableContainer'); });
        $("#windowContainer").click(function () { ThroneMenuPopup('windowContainer'); });
        $("#bannerContainer").click(function () { ThroneMenuPopup('bannerContainer'); });
        $("#trophyContainer").click(function () { ThroneMenuPopup('trophyContainer'); });
        $("#statueContainer").click(function () { ThroneMenuPopup('statueContainer'); });
        $("#petContainer").click(function () { ThroneMenuPopup('petContainer'); });
        $("#tapestryContainer").click(function () { ThroneMenuPopup('tapestryContainer'); });
        $("#pillarContainer").click(function () { ThroneMenuPopup('pillarContainer'); });

        function ThroneMenuPopup(displayContainer) {
            var throneType = displayContainer.split('Container')[0];
            for (var trId in uW.kocThroneItems) {
                var throne_item = uW.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.type == throneType && throne_item.isEquipped) {
                    var thisDiv = document.getElementById(displayContainer);
                    CardContextMenu(thisDiv, throne_item, false);
                    break;
                }
            }
        };


    },

    unequipAllItems: function (presetIndex) {

        if (Seed.throne.activeSlot != presetIndex) {
            Seed.throne.activeSlot = presetIndex;
        }

        var t = Tabs.throneOrganizer;

        if (t.switchingPresets) {
            alert("still unequipping");
            return;
        }

        if (!confirm('Are you sure you want to unequip all items?')) return;

        var c = 0;
        t.switchingPresets = true;

        // grab the list of items equipped in the slot about to be switched to
        var delay = 7;

        var equipped_items = Seed.throne.slotEquip[presetIndex];

        var counter = equipped_items.length;

        var items = [];

        for (i = 0; i < counter; i++) items.push(equipped_items[i]);

        while (counter > 0) {
            var throne_item = uW.kocThroneItems[items.pop()];

            var goUnequip = function (I2, s) {
                return function () {
                    Tabs.throneOrganizer.unequipItem(I2, s);
                };
            }

            setTimeout(goUnequip(throne_item, presetIndex), c * delay * 1000); // have to wait at least 5 seconds between switches
            c++;
            counter--;
        }

        setTimeout(function () {
            t.switchingPresets = false;
            alert("all throne items unequipped")
        }, c * delay * 1000 + 1000);

    },

    equipPresetTags: function (presetIndex) {

        if (Seed.throne.activeSlot != presetIndex) {
            Seed.throne.activeSlot = presetIndex;
        }

        var t = Tabs.throneOrganizer;

        var preset = getThronePresetObject(presetIndex);

        if (t.switchingPresets) {
            alert("still equipping");
            return;
        }

        if (getObjectCollectionCount(preset) == 0) {
            alert("preset is empty");
            return;
        }

        var c = 0;
        t.switchingPresets = true;

        var delay = 7;

        var types_equiped = [];

        for (p in preset) {

            // only equip the items not already equipped
            var throne_item = uW.kocThroneItems[p];

            types_equiped.push(throne_item.type);

            if (!throne_item.isEquipped) {

                var goEquip = function (I2, s) {
                    return function () {
                        Tabs.throneOrganizer.equipItem(I2, s);
                    };
                }

                setTimeout(goEquip(throne_item, presetIndex), c * delay * 1000); // have to wait at least 5 seconds between switches
                c++;
            }

        }

        var equipped_items = Seed.throne.slotEquip[presetIndex];

        var counter = equipped_items.length;

        var items_to_unequip = [];

        for (i = 0; i < counter; i++) {
            var throne_item = uW.kocThroneItems[equipped_items[i]];
            var idx = types_equiped.indexOf(throne_item.type);
            if (idx == -1) { //item in equipped items is not found among the types that were equipped, so unequip it

                var goUnequip = function (I2, s) {
                    return function () {
                        Tabs.throneOrganizer.unequipItem(I2, s);
                    };
                }

                setTimeout(goUnequip(throne_item, presetIndex), c * delay * 1000); // have to wait at least 5 seconds between switches
                c++;

            }
        }

        setTimeout(function () {
            t.switchingPresets = false;
            alert("preset #" + presetIndex + " loaded from tagged preset")
        }, (c * (delay * 1000)) + 1000);

    },

    copyPresetTags: function (sourcePresetNumber, destinationPresetNumber, presetName) {
        var pSource = getThronePresetObject(parseInt(sourcePresetNumber));
        var pDestination = getThronePresetObject(parseInt(destinationPresetNumber));
        for (var p in pDestination) delete pDestination[p];
        for (var p in pSource) pDestination[p] = true;
        STrChOThronePresetData.presetNames[destinationPresetNumber] = presetName + " (copy)";
        SAVESTrChOThronePresetData();
    },


    addPresetTags: function (presetIndex) {  //presetIndex should be passed in as base 0 to index into the presetTaggedItems array
        var t = Tabs.thronePresets;

        var preset = getThronePresetObject(parseInt(presetIndex));

        var equipped_items = Seed.throne.slotEquip[parseInt(presetIndex)];

        for (var p in preset) delete preset[p];

        for (ei = 0; ei < equipped_items.length; ei++) {
            var throneId = equipped_items[ei];
            preset[throneId] = true;
            $("#throneInventoryItem" + throneId).prepend("<div class='presetBorderThrone'></div>");
            SAVESTrChOThronePresetData();
        }

        t.paintTags();

    },

    clearPresetTags: function (presetIndex) {
        var preset = getThronePresetObject(parseInt(presetIndex));
        for (var p in preset) {
            delete preset[p];
            $("#throneInventoryItem" + p).children(".presetBorderThrone").remove();
            SAVESTrChOThronePresetData();
        }
    },

    removeTagItem: function (itemId) {
        if (STrChOThronePresetData.taggedItems[itemId]) {
            delete STrChOThronePresetData.taggedItems[itemId];
            $("#throneInventoryItem" + itemId).children(".tagBorderThrone").remove();
            SAVESTrChOThronePresetData();
        }
    },

    addTagItem: function (itemId) {
        STrChOThronePresetData.taggedItems[itemId] = true;
        $("#throneInventoryItem" + itemId).prepend("<div class='tagBorderThrone'></div>");
        SAVESTrChOThronePresetData();
    },

    addAllTagItems: function() {
        var t = Tabs.thronePresets;
        t.clearAllTagItems();
        for (trId in uW.kocThroneItems) {
            STrChOThronePresetData.taggedItems[trId] = true;
            $("#throneInventoryItem" + trId).prepend("<div class='tagBorderThrone'></div>");
        }
        SAVESTrChOThronePresetData();
    },

    clearAllTagItems: function () {
        var taggedReverse = [];
        for (k in STrChOThronePresetData.taggedItems) taggedReverse.push(k);
        var len = taggedReverse.length;
        while (len--) {
            var trID = taggedReverse[len];
            delete STrChOThronePresetData.taggedItems[trID];
            $("#throneInventoryItem" + trID).children(".tagBorderThrone").remove();
            SAVESTrChOThronePresetData();
        }
    },

    clearAllPresetTagItems: function () {
        if (!confirm('Are you sure you want to clear all preset tag items?')) return;
        var presetCount = getObjectCollectionCount(Seed.throne.slotEquip) + 1;
        for (i = 1; i < presetCount; i++) {
            document.getElementById('STrChOThronePresetName' + i).value = "undefined";
            STrChOThronePresetData.presetNames[i] = "undefined";
            var preset = getThronePresetObject(i);
            for (var p in preset) {
                delete preset[p];
                $("#throneInventoryItem" + p).children(".presetBorderThrone").remove();
                SAVESTrChOThronePresetData();
            }
        }
    },

    setBreakStatus: function() {
        var t = Tabs.thronePresets;
        var remaining = t.broke_count - t.broke_items;
        var m =  "Items Remaining: " + remaining;
        m += "<br>Time Remaining: " + (remaining * (t.delay/1000)) + " Seconds";
        document.getElementById('STrChOThroneBreakCounter').innerHTML = m;
    },


}

Tabs.thronePreview = {
	tabOrder: 109,
	tabLabel: 'PREVIEW',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM PREVIEW',
    equipingPreview: false,

	init: function (div) {
		var t = Tabs.thronePreview;
		t.mydiv = div;
	},

	hide: function () {},

	show: function () {
		var t = Tabs.thronePreview;

        var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);

        var presetsTagList = "";

        for (i = 1; i < presetSlots + 1; i++) {
            presetsTagList += '<option value="' + i + '">' + i + ' (' + STrChOThronePresetData.presetNames[i] + ')</option>';
        }


		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

        m += '<table>';
        m += '<tr>';
        m += '<td colspan=3>';
        m += '<input type=button class=STrChOButton value="Reset" id=STrChOThronePreviewReset>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton value="Post Stats to Chat" id=STrChOThronePreviewPost>&nbsp;';
        m += '<input type=button class=STrChOButton value="Export to Excel" id=STrChOThronePreviewExcel>&nbsp;';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Export To Text" id=STrChOThronePreviewExport>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton value="Load Text Export" id=STrChOThronePreviewExportLoad>';
        m += '<input type=button class=STrChOButton value="Browse..." id=STrChOThronePreviewExportLoadItemTrigger onclick="document.getElementById(\'STrChOThronePreviewExportLoadItem\').click()">';
        m += '<input hidden id=STrChOThronePreviewExportLoadItem type=file>';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Equip To" id=STrChOThronePreviewEquip><b>&nbsp;Slot&nbsp;</b><select class=STrChOSelect style="width:25%;" id=STrChOThronePreviewEquipValue>' + presetsTagList + '</select>&nbsp;&nbsp;<font color="black"><b>(5 sec/card load)</b></font>';
        m += '<br>';
        m += '<font color=red><b><i>NOTE: Server will update new slot design, but a refresh will be required to update client side</i></b></font>';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Load From" id=STrChOThronePreviewLoadPreset><b>&nbsp;Slot&nbsp;</b><select class=STrChOSelect style="width:25%;" id=STrChOThronePreviewLoadPresetValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Copy To" id=STrChOThronePreviewCopyTo><b>&nbsp;Preset Tag&nbsp;</b><select class=STrChOSelect style="width:25%;" id=STrChOThronePreviewCopyToValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Load From" id=STrChOThronePreviewLoadPresetTag><b>&nbsp;Preset Tag&nbsp;</b><select class=STrChOSelect style="width:25%;" id=STrChOThronePreviewLoadPresetTagValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Auto Build By Effect" id=STrChOThronePreviewAutoBuild><b>&nbsp;Effect&nbsp;</b><select class=STrChOSelect style="width:25%;" id=STrChOThronePreviewAutoBuildEffect>';
        m += '<option value="0">--Effects--</option>';
        for (efx in CM.thronestats.effects) m += '<option value="' + efx + '">' + CM.thronestats.effects[efx][1] + '</option>';
        m += '</select>&nbsp;&nbsp;';
        m += '</td>';
        m += '</tr>';
        m += '</table>';



        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;PREVIEW STATS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="position: static; width: 100%; height: 380px; overflow-x: auto; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';
        m += '<div id=STrChOThronePreviewDetails></div>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;PREVIEW CARDS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="position: static; width: 100%; height: 380px; overflow-x: auto; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';

        m += '<tr>';
        for (idx = 0; idx < throneCardTypes.length; idx++) {
            if (idx % 3 == 0) m += '</tr><tr>';
            m += '<td width=33% valign=top>';
            m += '<div id=STrChOThroneHover' + throneCardTypes[idx] + '>';
            m += '<table>';
            m += '<tr><td><b>' + throneCardTypes[idx].toUpperCase() + '<b></td></tr>';
            m += '<tr><td><select class=STrChOSelect id=STrChOThronePreviewValue' + throneCardTypes[idx] + ' style="white-space:nowrap;display:inline-block;max-width: 150px;">';
            m += '<option value=0>--Items--</option>';
            m += '</select></td></tr>';
            m += '<tr><td><div id=STrChOThronePreviewCard' + throneCardTypes[idx] + '></div></td></tr>';
            m += '</table>';
            m += '</div>';
            m += '</td>';
        }
        m += '</tr>';

        m += '</table>';
        m += '</div>';


        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        for (throneId in uW.kocThroneItems) {
            var throneItem = uW.kocThroneItems[throneId];
            var throneType = throneItem.type;
            var elemSelect = document.getElementById('STrChOThronePreviewValue' + throneType);
            elemSelect.options.add(new Option(throneItem.name, throneId));
            if (STrChOThronePresetData.previewThrone[throneId]) {
                elemSelect.value = throneId;
                var throneCard = BuildThroneCard(throneItem);
                document.getElementById('STrChOThronePreviewCard' + throneType).innerHTML = throneCard;
            }
        }

        for (idx = 0; idx < throneCardTypes.length; idx++) {

            document.getElementById('STrChOThronePreviewCard' + throneCardTypes[idx]).addEventListener('click', function(A) {
                A.stopPropagation();
                var throneType = this.id.split('STrChOThronePreviewCard')[1];
                var STrChOPreviewValue = document.getElementById('STrChOThronePreviewValue' + throneType);
                var throneId = STrChOPreviewValue.value;
                var throneItem = uW.kocThroneItems[throneId];
                if (!throneItem || throneItem ==0) return;
                CardContextMenu(this, throneItem, true);
            }, false);

            document.getElementById('STrChOThronePreviewValue' + throneCardTypes[idx]).addEventListener('change', function() {
                var throne_Type = this.id.split('STrChOThronePreviewValue')[1];
                var trId = this.value;
                t.loadThronePreviewCard(trId, throne_Type);
            }, false);

            document.getElementById('STrChOThronePreviewValue' + throneCardTypes[idx]).addEventListener('keyup', function() {
                var throne_Type = this.id.split('STrChOThronePreviewValue')[1];
                var trId = this.value;
                t.loadThronePreviewCard(trId, throne_Type);
            }, false);

        }

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        document.getElementById('STrChOThronePreviewDetails').innerHTML = t.getPreviewThroneDetails();

        document.getElementById('STrChOThronePreviewExcel').addEventListener('click', function() {
            ExportThroneToExcel(true);
        }, false);

        document.getElementById('STrChOThronePreviewPost').addEventListener('click', function () {
            t.postPreviewThroneDetails();
        }, false);

        document.getElementById('STrChOThronePreviewReset').addEventListener('click', function () {
            t.resetPreview();
        }, false);

        document.getElementById('STrChOThronePreviewExportLoad').addEventListener('click', function () {
            var fileInput = document.getElementById("STrChOThronePreviewExportLoadItem");
            var files = fileInput.files;
            if (files.length==0) {
                alert('Please Select A File');
                return;
            }
            var file = files[0];

            var reader = new FileReader();

            reader.onload = function (e) {
				var output = e.target.result;
				STrChOThronePresetData.previewThrone = JSON.parse(output);
                SAVESTrChOThronePresetData();
                t.show();
                alert('Preview Throne Now Loaded From File');
            };
            reader.readAsText(file);
        }, false);

        document.getElementById('STrChOThronePreviewExport').addEventListener('click', function() {
            uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(STrChOThronePresetData.previewThrone));
            newWindow = window.open(uriContent, 'file.txt');
        }, false);

        document.getElementById('STrChOThronePreviewCopyTo').addEventListener('click', function () {
            var presetNum = document.getElementById('STrChOThronePreviewCopyToValue').value;
            var presetTag = getThronePresetObject(parseInt(presetNum));
            for (var p in presetTag) delete presetTag[p];
            for (var p in STrChOThronePresetData.previewThrone) presetTag[p] = true;
            STrChOThronePresetData.presetNames[presetNum] = "PREVIEW";
            document.getElementById('STrChOThronePresetName' + presetNum).value = "PREVIEW";
            SAVESTrChOThronePresetData();
            t.show();
        }, false);

        document.getElementById('STrChOThronePreviewLoadPreset').addEventListener('click', function () {
            var presetIndex = document.getElementById('STrChOThronePreviewLoadPresetValue').value;
            var equipped_items = Seed.throne.slotEquip[presetIndex];
            var counter = equipped_items.length;
            t.resetPreview();
            for (var ei = 0; ei < counter; ei++) {
                var throne_item = uW.kocThroneItems[equipped_items[ei]];
                if (throne_item == null || !throne_item) continue;
                STrChOThronePresetData.previewThrone[throne_item.id] = true;
            }
            SAVESTrChOThronePresetData();
            t.show();

        }, false);

        document.getElementById('STrChOThronePreviewAutoBuild').addEventListener('click', function () {
            var EffectId = document.getElementById('STrChOThronePreviewAutoBuildEffect').value;

            if (EffectId == 0) return;

            var EffectName = CM.thronestats.effects[EffectId][1];
            var isBuff = true;
            if (EffectName.indexOf(" Debuff") != -1) isBuff = false;


            function eCard() {
                this.id = 0;
                this.type = '';
                this.total  = 0;
            }

            var EffectedCards = [];

            for (tct = 0; tct < throneCardTypes.length; tct++) EffectedCards[throneCardTypes[tct]] = new Array;

            for (var throneId in uW.kocThroneItems) {
                var throneItem = uW.kocThroneItems[throneId];
                var totalEffects = 0;
                for (var effect in throneItem.effects) {
                    var fx = throneItem.effects[effect];
                    if (fx.id == EffectId) {
                        var tier = CM.thronestats.tiers[fx.id][fx.tier];
                        if (!tier) CM.thronestats.tiers[fx.id][fx.tier - 1]
                        var base = tier.base || 0;
                        var level = throneItem.level || 0;
                        var growth = tier.growth || 0;
                        var percent = +(base + ((level * level + level) * growth * 0.5));
                        totalEffects += percent;
                    }
                }
                if (totalEffects != 0) {
                    var thisCard = new eCard();
                    thisCard.id = throneId;
                    thisCard.total = totalEffects;
                    thisCard.type = throneItem.type;
                    if (EffectedCards[thisCard.type].length > 0) {
                        if (isBuff && EffectedCards[thisCard.type][0].total > thisCard.total) continue;
                        if (!isBuff && EffectedCards[thisCard.type][0].total < thisCard.total) continue;
                        EffectedCards[thisCard.type][0] = thisCard;
                    } else {
                        EffectedCards[thisCard.type].push(thisCard);
                    }

                }
            }
            t.resetPreview();
            for (tct = 0; tct < throneCardTypes.length; tct++) {
                if (EffectedCards[throneCardTypes[tct]].length > 0) {
                    var thisCard = EffectedCards[throneCardTypes[tct]][0];
                    t.loadThronePreviewCard(thisCard.id, thisCard.type);
                }
            }
            SAVESTrChOThronePresetData();
        }, false);

        document.getElementById('STrChOThronePreviewLoadPresetTag').addEventListener('click', function () {
            var presetNum = document.getElementById('STrChOThronePreviewLoadPresetTagValue').value;
            var presetTag = getThronePresetObject(parseInt(presetNum));
            t.resetPreview();
            for (var p in presetTag) STrChOThronePresetData.previewThrone[p] = true;
            SAVESTrChOThronePresetData();
            t.show();

        }, false);

        document.getElementById('STrChOThronePreviewEquip').addEventListener('click', function () {
            var t = Tabs.thronePreview;

            var presetIndex = document.getElementById('STrChOThronePreviewEquipValue').value;

            if (t.equipingPreview) {
                alert("still equipping");
                return;
            }

            if (getObjectCollectionCount(STrChOThronePresetData.previewThrone) == 0) return;

            var c = 0;
            t.equipingPreview = true;

            var delay = 7;

            var types_equiped = [];

            var goEquip = function (I2, s) {
                return function () {
                    Tabs.throneOrganizer.equipItem(I2, s);
                };
            }

            for (var trId in STrChOThronePresetData.previewThrone) {
                var throne_item = uW.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                setTimeout(goEquip(throne_item, presetIndex), c * delay * 1000); // have to wait at least 5 seconds between switches

                c++;

            }
            setTimeout(function () {
                t.equipingPreview = false;
                alert("equipping to slot " + presetIndex + " from PREVIEW complete")
            }, (c * (delay * 1000)) + 1000);

        }, false);
	},

    loadThronePreviewCard: function(throneId, throneType) {
        var t = Tabs.thronePreview;
        var throneCard = '';
        if (throneId != 0) {
            var throneItem = uW.kocThroneItems[throneId];
            if (!throneItem || throneItem ==0) {
                throneCard = '';
            } else {
                throneCard = BuildThroneCard(throneItem);
            }
        }
        document.getElementById('STrChOThronePreviewCard' + throneType).innerHTML = throneCard;

        document.getElementById('STrChOThronePreviewValue' + throneType).value = throneId;

        for (pId in STrChOThronePresetData.previewThrone) {
            var throne_item = uW.kocThroneItems[pId];
            if (throne_item == null || !throne_item) continue;
            if (throne_item.type == throneType) {
                delete STrChOThronePresetData.previewThrone[pId];
                break;
            }
        }

        if (throneId != 0) STrChOThronePresetData.previewThrone[throneId] = true

        SAVESTrChOThronePresetData();

        document.getElementById('STrChOThronePreviewDetails').innerHTML = t.getPreviewThroneDetails();
    },

    getPreviewThroneDetails: function () {
        var t = Tabs.thronePreview;
        var previewPreset = [];
        for (var trId in STrChOThronePresetData.previewThrone) previewPreset.push(trId);

        var stringPreviewThrone = GenerateThronePresetEffectsString(previewPreset, true);
        if (stringPreviewThrone == "") {
            stringPreviewThrone = "No Stats To Preview";
        } else {
            stringPreviewThrone = "<b>PREVIEW STATS:</b>\n" + stringPreviewThrone;
        }
        return stringPreviewThrone;
    },

    postPreviewThroneDetails: function () {
        var t = Tabs.thronePreview;
        var previewPreset = [];
        for (var trId in STrChOThronePresetData.previewThrone) previewPreset.push(trId);

        var stringPreviewThrone = GenerateThronePresetEffectsString(previewPreset, true);
        if (stringPreviewThrone == "") {
            return;
        } else {
            var table = stringPreviewThrone.split("</div><div>");
            stringPreviewThrone = table.join("||");
            stringPreviewThrone = stringPreviewThrone.replace("<div>", ":::. |TR PREVIEW STATS:||");
            stringPreviewThrone = stringPreviewThrone.replace("</div>", "");
            sendChat(stringPreviewThrone);
        }
        return;

    },

    resetPreview: function () {
        var t = Tabs.thronePreview;

        for (trId in STrChOThronePresetData.previewThrone) delete STrChOThronePresetData.previewThrone[trId];
        SAVESTrChOThronePresetData();

        for (idx = 0; idx < throneCardTypes.length; idx++) {
            document.getElementById('STrChOThronePreviewCard' + throneCardTypes[idx]).innerHTML = "";
            document.getElementById('STrChOThronePreviewValue' + throneCardTypes[idx]).value = 0;
        }

        document.getElementById('STrChOThronePreviewDetails').innerHTML = t.getPreviewThroneDetails();
    },

}

Tabs.throneCompare = {
	tabOrder: 110,
	tabLabel: 'COMPARE',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM COMPARE',

	init: function (div) {
		var t = Tabs.throneCompare;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div>';
        m += '<center>';
        m += '<table>';

        m += '<tr>';
        m += '<td align=center><b>CARD 1</b></td>';
        m += '<td align=center><b>CARD 2</b></td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td>';
        m += '<b>Item Type:</b><select class=STrChOSelect id=STrChOThroneCompareType1 style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var i = 0; i < throneCardTypes.length; i++) m += '<option value="' + throneCardTypes[i] + '">' + throneCardTypes[i].capitalizeFirstLetter() + '</option>';
        m += '</select>';
        m += '</td>';
        m += '<td>';
        m += '<b>Item Type:</b><select class=STrChOSelect id=STrChOThroneCompareType2 style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var i = 0; i < throneCardTypes.length; i++) m += '<option value="' + throneCardTypes[i] + '">' + throneCardTypes[i].capitalizeFirstLetter() + '</option>';
        m += '</select>';
        m += '</td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td>';
        m += '<b>Throne Item:</b><br/><select class=STrChOSelect id=STrChOThroneCompareId1 style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (var throneId in uW.kocThroneItems) m += '<option value="' + throneId + '">' + uW.kocThroneItems[throneId].name + ' </option>';
        m += '</select>';
        m += '</td>';
        m += '<td>';
        m += '<b>Throne Item:</b><br/><select class=STrChOSelect id=STrChOThroneCompareId2 style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (var throneId in uW.kocThroneItems) m += '<option value="' + throneId + '">' + uW.kocThroneItems[throneId].name + ' </option>';
        m += '</select>';
        m += '</td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td>';
        m += '<div id=STrChOThroneCompareCard1></div>';
        m += '</td>';
        m += '<td>';
        m += '<div id=STrChOThroneCompareCard2></div>';
        m += '</td>';
        m += '</tr>';

        m += '</table>';
        m += '</center>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOThroneCompareId1').addEventListener('change', function () { t.loadCard(this, 'STrChOThroneCompareCard1'); }, false);

        document.getElementById('STrChOThroneCompareId2').addEventListener('change', function () { t.loadCard(this, 'STrChOThroneCompareCard2'); }, false);

        document.getElementById('STrChOThroneCompareId1').addEventListener('keyup', function () { t.loadCard(this, 'STrChOThroneCompareCard1'); }, false);

        document.getElementById('STrChOThroneCompareId2').addEventListener('keyup', function () { t.loadCard(this, 'STrChOThroneCompareCard2'); }, false);

        document.getElementById('STrChOThroneCompareType1').addEventListener('change', function () { t.filterItems(this, 'STrChOThroneCompareId1', 'STrChOThroneCompareCard1'); }, false);

        document.getElementById('STrChOThroneCompareType2').addEventListener('change', function () { t.filterItems(this, 'STrChOThroneCompareId2', 'STrChOThroneCompareCard2'); }, false);

        document.getElementById('STrChOThroneCompareType1').addEventListener('keyup', function () { t.filterItems(this, 'STrChOThroneCompareId1', 'STrChOThroneCompareCard1'); }, false);

        document.getElementById('STrChOThroneCompareType2').addEventListener('keyup', function () { t.filterItems(this, 'STrChOThroneCompareId2', 'STrChOThroneCompareCard2'); }, false);

    },

    sendToCompare: function (Id) {
        var t = Tabs.throneCompare;
        var throneItem = uW.kocThroneItems[Id];
        var card1 = document.getElementById('STrChOThroneCompareId1');
        var card2 = document.getElementById('STrChOThroneCompareId2');
        var obj = '';
        if (card1.value == 0)
            obj = '1';
        else if (card2.value == 0)
            obj = '2';
        else
            obj = '1';

        document.getElementById('STrChOThroneCompareType' + obj).value = throneItem.type;
        t.filterItems(document.getElementById('STrChOThroneCompareType' + obj), ('STrChOThroneCompareId' + obj), ('STrChOThroneCompareCard' + obj));
        document.getElementById('STrChOThroneCompareId' + obj).value = Id;
        t.loadCard(document.getElementById('STrChOThroneCompareId' + obj), ('STrChOThroneCompareCard' + obj));
    },

    loadCard: function (objectItem, objectName) {
        var div = document.getElementById(objectName);
        if (objectItem.value == 0)
            div.innerHTML = '';
        else
            div.innerHTML = BuildThroneCard(uW.kocThroneItems[objectItem.value]);
    },

    filterItems: function (objectItem, objectIdName, objectName) {
        document.getElementById(objectName).innerHTML = '';
        var select = document.getElementById(objectIdName);
        select.value = 0;
        var m = '<option value="0">--Items--</option>';
        if (objectItem.value == 0) {
            for (var throneId in uW.kocThroneItems) {
                m += '<option value="' + throneId + '">' + uW.kocThroneItems[throneId].name + '</option>';
            }
        } else {
            for (var throneId in uW.kocThroneItems) {
                if (uW.kocThroneItems[throneId].type == objectItem.value)
                    m += '<option value="' + throneId + '">' + uW.kocThroneItems[throneId].name + '</option>';
            }
        }
        select.innerHTML = m;
    },


	hide: function () {},

	show: function () {},
}

Tabs.throneUniques = {
	tabOrder: 111,
	tabLabel: 'UNIQUES',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM UNIQUES',
    UniqueItems : null,
    selectedCard: 0,
    selectedType: 0,
    selectedLevel: 1,

	init: function (div) {
		var t = Tabs.throneUniques;
		t.mydiv = div;

        t.UniqueItems = CM.WorldSettings.getSettingAsObject("TR_UNIQUE_ITEMS");
        for (k in t.UniqueItems) {
            var throne_item = t.UniqueItems[k];
            if (parseInt(throne_item.Id) < 29000) delete t.UniqueItems[k];
            if (parseInt(throne_item.Id) == 30262 || parseInt(throne_item.Id) == 30264 || parseInt(throne_item.Id) == 30266) { throne_item.Name = throne_item.Name + ' ('+uW.g_js_strings.commonstr[CM.CHAMPION.getFactionClasses(throne_item.Faction)].toLowerCase()+')';};
            if (parseInt(throne_item.Id) == 30261 || parseInt(throne_item.Id) == 30263 || parseInt(throne_item.Id) == 30265) { throne_item.Name = throne_item.Name + ' ('+uW.g_js_strings.commonstr[CM.CHAMPION.getFactionClasses(throne_item.Faction)].toLowerCase()+')';};
            if (parseInt(throne_item.Id) == 30230 || parseInt(throne_item.Id) == 30240 || parseInt(throne_item.Id) == 30250) { throne_item.Name = throne_item.Name + ' ('+uW.g_js_strings.commonstr[CM.CHAMPION.getFactionClasses(throne_item.Faction)].toLowerCase()+')';};
            if (parseInt(throne_item.Id) == 30231 || parseInt(throne_item.Id) == 30241 || parseInt(throne_item.Id) == 30251) { throne_item.Name = throne_item.Name + ' ('+uW.g_js_strings.commonstr[CM.CHAMPION.getFactionClasses(throne_item.Faction)].toLowerCase()+')';};
        }

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

        m += '<center><table>';
        m += '<tr><td><div style="max-width:100%;"><b>Item Type:</b><select class=STrChOSelect id=STrChOThroneUniqueType style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var i = 0; i < throneCardTypes.length; i++) m += '<option value="' + throneCardTypes[i] + '">' + throneCardTypes[i].capitalizeFirstLetter() + '</option>';
        m += '</select></div></td></tr>';

        m += '<tr><td><div style="max-width:100%;"><b>Throne Item:</b><br/><select class=STrChOSelect id=STrChOThroneUnique style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (k in t.UniqueItems) {
            var throne_item = t.UniqueItems[k];
            if (throne_item == null || !throne_item) continue;
            m += '<option value="' + k + '">' + throne_item.Name + ' </option>';
        }
        m += '</select></div></td></tr>';

        m += '<tr><td><div style="max-width:100%;"><b>Level:</b><select class=STrChOSelect id=STrChOThroneUniqueLevel style="width: 40%;">';
        m += '<option value="1" selected>+1</option>';
        for (lvl = 2; lvl < STrChOMaxThroneLevel + 1; lvl++) m += '<option value="' + lvl + '">+' + lvl + '</option>';
        m += '</select></div></td></tr>';

        m += '<tr><td><div id=STrChOThroneUniqueCard></div></td></tr>';

        m += '</table>';

        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOThroneUniqueType').addEventListener('change', function () {
            t.selectedType = document.getElementById('STrChOThroneUniqueType').value;
            t.selectedCard = 0;
            t.FilterUniques();
            document.getElementById('STrChOThroneUniqueCard').innerHTML = '';
        }, false);

        document.getElementById('STrChOThroneUnique').addEventListener('change', function () {
            t.selectedCard = document.getElementById('STrChOThroneUnique').value;
            if (t.selectedCard != 0) t.SwitchUnique();
        }, false);

        document.getElementById('STrChOThroneUniqueLevel').addEventListener('change', function () {
            t.selectedLevel = document.getElementById('STrChOThroneUniqueLevel').value;
            if (t.selectedCard != 0) t.SwitchUnique();
        }, false);

	},

	hide: function () {},

	show: function () {},

    FilterUniques: function (cardType) {
        var t = Tabs.throneUniques;
        var throneList = document.getElementById('STrChOThroneUnique');
        throneList.options.length = 0;
        var throneOption = document.createElement('option');
        throneOption.text = '--Items--';
        throneOption.value = 0;
        throneList.add(throneOption);
        for (k in t.UniqueItems) {
            var throne_item = t.UniqueItems[k];
            if (throne_item == null || !throne_item) continue;
            if (throneCardTypes[throne_item.Type-1] == t.selectedType || t.selectedType == 0) {
                var throneOption = document.createElement('option');
                throneOption.text = throne_item.Name;
                throneOption.value = k;
                throneList.add(throneOption);
            }
        }
    },

    SwitchUnique: function () {
        var t = Tabs.throneUniques;
        var div = document.getElementById('STrChOThroneUniqueCard');
        var m = ConvertUniqueAndBuildThroneCard(t.selectedCard, t.selectedLevel);
        m += t.GetUniqueInventory(t.selectedCard);
        div.innerHTML = m;
        var STrChOThroneUseUnique = document.getElementById('STrChOThroneUseUnique');
        if (!STrChOThroneUseUnique) return;
        STrChOThroneUseUnique.addEventListener('click', function() {
            var uniqueId = this.getAttribute('uid');
            var uniqueCount = parseInt(document.getElementById('STrChOThroneUniqueCount').innerHTML);
            uniqueCount--;
            document.getElementById('STrChOThroneUniqueCount').innerHTML = uniqueCount;
            CM.ItemController.use(uniqueId);
        }, false);
    },


    GetUniqueInventory: function (uniqueId) {
        var m = '<br><b>Throne Room</b><br>';
        var throneitems = {};
        for (throneId in uW.kocThroneItems) {
            var throneItem = uW.kocThroneItems[throneId];
            if (throneItem.unique == uniqueId) {
                if (throneitems[throneItem.level]) {
                    throneitems[throneItem.level]++;
                } else {
                    throneitems[throneItem.level] = 1;
                }
            }
        }
        var gotitem = false;
        for (lvl in throneitems) {
            gotitem = true;
            m += 'You have ' + throneitems[lvl] + ' at level ' + lvl + '<br>';
        }
        if (!gotitem) m += 'You have none in your throne room.<br>';

        m += '<br><b>Inventory</b><br>';
        var inventory = Seed.items['i' + uniqueId];
        m += 'You have <div class=divNoWrap id=STrChOThroneUniqueCount>' + (inventory ? inventory : '0') + '</div> in your inventory.';
        if ((inventory?inventory:0) != 0) m += '<br><b><a id=STrChOThroneUseUnique uid="' + uniqueId + '">Add To Throne Room</a></b>';
        return m;
    },

}

Tabs.throneCaps = {
	tabOrder: 112,
	tabLabel: 'CAPS',
	tabColor: 'red',
    tabHeader: 'THRONE ROOM CAPS',

	init: function (div) {
		var t = Tabs.throneCaps;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div class=indent5>';
        m += '<table cellpadding=0 cellspacing=0 width=100% align=center>';
        m += '<tr><td width=50% align=left><b>Boost</b></td><td width=25% align=left><b>Max</b></td><td width=25% align=left><b>Min</b></td></tr>';
        m += '</table>';
        m += '</div>';

        m += '<div class=indent5 style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

        m += '<table cellpadding=0 cellspacing=0 width=100% align=center>';
        for (var boost in CM.thronestats.boosts) {
            var cap = CM.thronestats.boosts[boost];
            m += '<tr class=trTabLined>';
            m += '<td width=50%>' + cap.BoostName + '</td>';
            m += '<td width=25%>' + cap.Max + ((cap.CapType == "percent") ? '%' : '') + '</td>';
            m += '<td width=25%>' + ((cap.Min == "none") ? 'None' : cap.Min + '%') + '</td>';
            m += '</tr>';
        }
        m += '</table>';
        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

	},

	hide: function () {},

	show: function () {},
}

Tabs.champUpgrader = {
	tabOrder: 200,
	tabLabel: 'UPGRADER',
	tabColor: 'brown',
  tabHeader: 'CHAMP HALL UPGRADER',
  myDiv: null,
  repairId: 0,
  repairEnd: 0,
  timerH: null,
  clearTimerH: null,
  speedup: 0,
  upgradePath: {
    0: { maxLev: 2, nextQual: 2 },
    1: { maxLev: 2, nextQual: 2 },
    2: { maxLev: 3, nextQual: 4 },
    3: { maxLev: 3, nextQual: 4 },
    4: { maxLev: 4, nextQual: 5 }
  },

	init: function (div) {
		var t = Tabs.champUpgrader;
		t.mydiv = div;
		var m = '<div class=STrChOHeader>' + t.tabHeader + '<div class=STrChOSaveSettings id=STrChOChampUpgraderSaveSettings title="Save Upgrader Settings"></div><div class=STrChOLoadSettings id=STrChOChampUpgraderLoadSettings title="Load Upgrader Settings"></div></div>';

    m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

		m += '<div>';
    m += '<table class=STrChOSectionTable>';
    m += '<tr>';

    if (STrChOChampUpgradeData.active) {
        m += '<td width=33%><input id=STrChOChampUpgradePower type=button class=STrChOButton value="Upgrader = ON"></td>';
    } else {
        m += '<td width=33%><input id=STrChOChampUpgradePower type=button class=STrChOButton value="Upgrader = OFF"></td>';
    }
    m += '<td width=33%><div class=divNoWrap><input class=STrChOCheckbox id=STrChOChampOneItem type=checkbox ' + (STrChOChampQueueData.oneItem ? ' CHECKED' : '') + '/>Upgrade 1 At A Time</div></td>';
    m += '<td width=33%><div class=divNoWrap align=center id=STrChOChampAetherDisplay></div></td>';
    m += '</tr>';
    m += '<tr><td colspan=3><hr class=STrChOHRCenter></td></tr>';
    m += '<tr><td colspan=3><div class=indent5 id=STrChOChampUpgradeStatus><br></div></td></tr>';
    m += '<tr><td colspan=3><div class=indent5 id=STrChOChampLastResult><br></div></td></tr>';
    m += '</table>';
    m += '</div>';

    m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SPEED UPS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

    m += '<div class=STrChOSection>';
    m += '<table class=STrChOSectionTable>';
    m += '<tr>';
    m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOChampHourglassLevelSpecific ' + (STrChOChampUpgradeData.hourglassLevelSpecific ? "CHECKED" : "") + '>Only use hourglass for levels ';
    m += '<select class=STrChOSelect  id=STrChOChampHourglassLevel>';
    for (i = 1; i < STrChOMaxChampLevel; i++) m += '<option value=' + i + ' ' + (STrChOChampUpgradeData.hourglassLevel == i ? 'SELECTED' : '') + '>' + i + '</option>';
    m += '</select> and higher</td>';
    m += '</tr>';
    m += '<tr>';
    m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOChampHourglassQualitySpecific ' + (STrChOChampUpgradeData.hourglassQualitySpecific ? "CHECKED" : "") + '>Only use hourglass for qualities ';
    m += '<select class=STrChOSelect id=STrChOChampHourglassQuality>';
    for (i = 1; i <= STrChOMaxChampQuality-1; i++) {
        m += '<option value=' + i + ' ' + (STrChOChampUpgradeData.hourglassQuality == i ? 'SELECTED' : '') + '>' + champCardQualities[i].capitalizeFirstLetter() + '</option>';
    }
    m += '</select> and higher</td>';
    m += '</tr>';
    m += '<tr>';
    m += '<td title="' + STrChOHourGlassTDLabel[1] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseSH ' + (STrChOChampUpgradeData.useSH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[1] + ' (<div class=divNoWrap id=STrChOChampUseSHLabel><font' + (uW.ksoItems[1].count < 100 ? ' color=red>' : '>') + uW.ksoItems[1].count + '</font></div>)</div></td>';
    m += '<td title="' + STrChOHourGlassTDLabel[2] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseKH ' + (STrChOChampUpgradeData.useKH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[2] + ' (<div class=divNoWrap id=STrChOChampUseKHLabel><font' + (uW.ksoItems[2].count < 100 ? ' color=red>' : '>') + uW.ksoItems[2].count + '</font></div>)</div></td>';
    m += '<td title="' + STrChOHourGlassTDLabel[3] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseGH ' + (STrChOChampUpgradeData.useGH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[3] + ' (<div class=divNoWrap id=STrChOChampUseGHLabel><font' + (uW.ksoItems[3].count < 100 ? ' color=red>' : '>') + uW.ksoItems[3].count + '</font></div>)</div></td>';
    m += '</tr>';
    m += '<tr>';
    m += '<td title="' + STrChOHourGlassTDLabel[4] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseMH ' + (STrChOChampUpgradeData.useMH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[4] + ' (<div class=divNoWrap id=STrChOChampUseMHLabel><font' + (uW.ksoItems[4].count < 100 ? ' color=red>' : '>') + uW.ksoItems[4].count + '</font></div>)</div></td>';
    m += '<td title="' + STrChOHourGlassTDLabel[5] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseAH ' + (STrChOChampUpgradeData.useAH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[5] + ' (<div class=divNoWrap id=STrChOChampUseAHLabel><font' + (uW.ksoItems[5].count < 100 ? ' color=red>' : '>') + uW.ksoItems[5].count + '</font></div>)</div></td>';
    m += '<td title="' + STrChOHourGlassTDLabel[6] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseWH ' + (STrChOChampUpgradeData.useWH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[6] + ' (<div class=divNoWrap id=STrChOChampUseWHLabel><font' + (uW.ksoItems[6].count < 100 ? ' color=red>' : '>') + uW.ksoItems[6].count + '</font></div>)</div></td>';
    m += '</tr>';
    m += '<tr>';
    m += '<td title="' + STrChOHourGlassTDLabel[7] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseDH ' + (STrChOChampUpgradeData.useDH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[7] + ' (<div class=divNoWrap id=STrChOChampUseDHLabel><font' + (uW.ksoItems[7].count < 100 ? ' color=red>' : '>') + uW.ksoItems[7].count + '</font></div>)</div></td>';
    m += '<td title="' + STrChOHourGlassTDLabel[8] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampUseEH ' + (STrChOChampUpgradeData.useEH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[8] + ' (<div class=divNoWrap id=STrChOChampUseEHLabel><font' + (uW.ksoItems[8].count < 100 ? ' color=red>' : '>') + uW.ksoItems[8].count + '</font></div>)</div></td>';
    m += '<td/>';
    m += '</tr>';
    m += '<tr>';
    m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOChampOverrideSpeedUps ' + (STrChOChampUpgradeData.overrideSpeedUp ? "CHECKED" : "") + '>Override hourglasses by using ';
    m += '<select class=STrChOSelect  id=STrChOChampSpeedUp>';
    m += '<option value=0>None</option>';
    for (gls in STrChOHourGlassName) {
        m += '<option value=' + gls + ' ' + (STrChOChampUpgradeData.useSpeedUp == gls ? 'SELECTED' : '') + '>' + STrChOHourGlassName[gls] + '</option>';
    }
    m += '</select> every time</td>';
    m += '</tr>';
    m += '</table>';
    m += '</div>';

    m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;BOOST ITEMS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

    m += '<div class=STrChOSection>';
    m += '<table class=STrChOSectionTable>';
    m += '<tr>';
    m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOChampUpgradeData.useLOM ? "CHECKED" : "") + ' id=STrChOChampUseLOM><div class=divNoWrap>Lesser Orb of Metallurgy (<div class=divNoWrap id=STrChOChampUseLOMLabel>' + uW.ksoItems[21001].count + '</div>)</div></td>';
    m += '<td><input class=STrChOCheckbox type=checkbox ' + (STrChOChampUpgradeData.useGOM ? "CHECKED" : "") + ' id=STrChOChampUseGOM><div class=divNoWrap>Greater Orb of Metallurgy (<div class=divNoWrap id=STrChOChampUseGOMLabel>' + uW.ksoItems[21002].count + '</div>)</div></td>';
    m += '<td>Quality <select class=STrChOSelect  id=STrChOChampUseQuality>';
    for (i = 0; i <= STrChOMaxChampQuality-1; i++) {
        m += '<option value="' + i + '" ' + (STrChOChampUpgradeData.useQuality == i ? 'SELECTED' : '')  + '>' + champCardQualities[i].capitalizeFirstLetter() + '</option>';
    }
    m += '</select> and higher</td>';
    m += '</tr>';

    m += '<tr>';
    m += "<td><input class=STrChOCheckbox type=checkbox " + (STrChOChampUpgradeData.useJT ? "CHECKED" : "") + " id=STrChOChampUseJT><div style='white-space:nowrap;display:inline-block;'>Journeyman Smith's Token (<div style='white-space:nowrap;display:inline-block;' id=STrChOChampUseJTLabel>" + uW.ksoItems[21051].count + "</div>)</div></td>";
    m += "<td><input class=STrChOCheckbox type=checkbox " + (STrChOChampUpgradeData.useST ? "CHECKED" : "") + " id=STrChOChampUseST><div style='white-space:nowrap;display:inline-block;'>Smith's Token (<div style='white-space:nowrap;display:inline-block;' id=STrChOChampUseSTLabel>" + uW.ksoItems[21052].count + "</div>)</div></td>";
    m += '<td>Level <select id="STrChOChampUseLevel">';
    for (i = 1; i <= STrChOMaxChampLevel-1; i++) {
        m += '<option value="' + i + '" ' + (STrChOChampUpgradeData.useLevel == i ? 'SELECTED' : '') + '> +' + i + '</option>';
    }
    m += '</select> and higher</td>';
    m += '</tr>';
    m += '<tr>';
    m += "<td><input class=STrChOCheckbox type=checkbox " + (STrChOChampUpgradeData.useET ? "CHECKED" : "") + " id=STrChOChampUseET><div style='white-space:nowrap;display:inline-block;'>Expert Smith's Token (<div style='white-space:nowrap;display:inline-block;' id=STrChOChampUseETLabel>" + uW.ksoItems[21058].count + "</div>)</div></td>";
    m += "<td/>";
    m += "<td/>";
    m += "</tr>";

    m += '<tr><td colspan=3>';
    m += '<input class=STrChOCheckbox id=STrChOChampUseAutoTokens type=checkbox ' + (STrChOChampUpgradeData.useAutoTokens ? 'CHECKED ' : '') + '/> Use Auto Forged Upgrade When Min Level ';
    m += '<select id=STrChOChampUseAutoTokensMin class=STrChOSelect>';
    for (var lvl = 0; lvl < STrChOMaxChampLevel; lvl++) m += '<option value="' + lvl + '" ' + (STrChOChampUpgradeData.useAutoTokensMin == lvl ? 'SELECTED ' : '') + '>+' + lvl + '</option>';
    m += '</select> & Max Level ';
    m += '<select id=STrChOChampUseAutoTokensMax class=STrChOSelect>';
    for (var lvl = 0; lvl < STrChOMaxChampLevel; lvl++) m += '<option value="' + lvl + '" ' + (STrChOChampUpgradeData.useAutoTokensMax == lvl ? 'SELECTED ' : '') + '>+' + lvl + '</option>';
    m += '</select>';

    m += '</table>';
    m += '</div>';

    m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;UPGRADE ITEMS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

    m += '<div class=STrChOSection>';
    m += '<table class=STrChOSectionTable>';
    m += '<tr>';
    m += '<td colspan=4>Enhance All Quality <select class=STrChOSelect id=STrChOChampEnhanceAllQuality>';
    for (i = 0; i <= STrChOMaxChampQuality-1; i++) {
        m += '<option value="' + i + '">' + champCardQualities[i].capitalizeFirstLetter() + '</option>';
    }
    m += '</select> To Quality <select class=STrChOSelect id=STrChOChampEnhanceAllQualityTo>';
    for (i = 1; i <= STrChOMaxChampQuality; i++) {
        m += '<option value="' + i + '">' + champCardQualities[i].capitalizeFirstLetter() + '</option>';
    }
    m += '</select>&nbsp;&nbsp;<input class=STrChOButton type=button value="Add" id=STrChOChampEnhanceAddAllQuality></td>';
    m += '</tr>';

    m += '<tr><td colspan=4>Upgrade All Cards Less To Level <select class=STrChOSelect id=STrChOChampUpgradeAddAllLevelMaxTo>';
    for (i = 1; i <= STrChOMaxChampLevel; i++) {
        m += '<option value="' + i + '"> +' + i + '</option>';
    }
    m += '</select>&nbsp;&nbsp;<input class=STrChOButton type=button value="Add" id=STrChOChampUpgradeAddAllLevelMax></td></tr>';

    m += '<tr>';
    m += '<td colspan=4>Upgrade All Level <select class=STrChOSelect id=STrChOChampUpgradeAllLevel>';
    for (i = 0; i <= STrChOMaxChampLevel-1; i++) {
        m += '<option value="' + i + '"> +' + i + '</option>';
    }
    m += '</select> To Level <select class=STrChOSelect id=STrChOChampUpgradeAllLevelTo>';
    for (i = 1; i <= STrChOMaxChampLevel; i++) {
        m += '<option value="' + i + '"> +' + i + '</option>';
    }
    m += '</select>&nbsp;&nbsp;<input class=STrChOButton type=button value="Add" id=STrChOChampUpgradeAddAllLevel></td>';
    m += '</tr>';
    m += '<tr>';
    m += '<td class=divNoWrap>Item: <select class=STrChOSelect style="white-space:nowrap;display:inline-block;max-width: 200px;" id=STrChOChampUpgradeList>';
    m += '<option value="0">--Items--</option>';
    for (ChampID in uW.kocChampionItems) {
        var champItem = uW.kocChampionItems[ChampID];
        m += '<option value="' + ChampID + '">' + champItem.name + '</option>';
    }
    m += '</select>&nbsp;';
    m += 'Action: <select class=STrChOSelect style="white-space:nowrap;display:inline-block;" id=STrChOChampAction>';
    m += '<option value="upgrade">Upgrade</option>';
    m += '<option value="enhance">Enhance</option>';
    m += '<option value="both">Both</option>';
    m += '</select>&nbsp;';
    m += '<div class=divNoWrap id=STrChOChampMaxDiv></div>&nbsp;';
    m += '<input class=STrChOButton id=STrChOChampQueueAdd type=button value="Add"/>';
    m += '</td>';
    m += '</tr>';
    m += '</table>';
    m += '</div>';

    m += '<div class=STrChOHeader>UPGRADE LIST</div>';
    m += '<table class=STrChOSectionTable>';
    m += '<tr><td colspan=4>';
    m += '<div id=STrChOChampQScroll style="position: static; width: 100%; height: 340px; overflow-x: auto; overflow-y: auto;">';
    m += '<div id=STrChOChampQDiv></div>';
    m += '</div>';
    m += '</td></tr>';
    m += '<tr><td colspan=4><input class=STrChOButton style="float: left;" id=STrChOChampClearQ type=button value="Clear Queue"></tr>';
    m += '</table>';
    m += '</div>';

    m += '</div>';

    t.mydiv.innerHTML = '<div>' + m + '</div>';

    document.getElementById('STrChOChampUpgraderSaveSettings').addEventListener('click', function () {
        SaveSettingsToFile(STrChOChampUpgradeData);
    }, false);

    document.getElementById('STrChOChampUpgraderLoadSettings').addEventListener('click', function () {
        var loader = document.getElementById('STrChOSettingsFile');
        loader.addEventListener('change', function () {
            LoadSettingsFromFile(STrChOChampUpgradeData, Tabs.champUpgrader);
        }, false);
        loader.click();
    }, false);

    t.refreshAetherDisplay();

    var header = document.getElementsByClassName('STrChOHeader');
    for (var head=0;head<header.length;head++) {
        header[head].addEventListener('click', sectionOpener, false);
    }

    document.getElementById('STrChOChampUpgradePower').addEventListener('click', function () {
        t.togglePower(this);
        t.show();
    }, false);

    document.getElementById('STrChOChampUseAutoTokens').addEventListener('change', function () {
        STrChOChampUpgradeData.useAutoTokens = document.getElementById('STrChOChampUseAutoTokens').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useAutoTokens) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseAutoTokensMin').addEventListener('change', function () {
        STrChOChampUpgradeData.useAutoTokensMin = document.getElementById('STrChOChampUseAutoTokensMin').value;
        SAVESTrChOChampUpgradeData();
    }, false);

    document.getElementById('STrChOChampUseAutoTokensMax').addEventListener('change', function () {
        STrChOChampUpgradeData.useAutoTokensMax = document.getElementById('STrChOChampUseAutoTokensMax').value;
        SAVESTrChOChampUpgradeData();
    }, false);

    document.getElementById('STrChOChampHourglassLevelSpecific').addEventListener('change', function () {
        STrChOChampUpgradeData.hourglassLevelSpecific = document.getElementById('STrChOChampHourglassLevelSpecific').checked;
        SAVESTrChOChampUpgradeData();
        t.doAction();
    }, false);

    document.getElementById('STrChOChampHourglassQualitySpecific').addEventListener('change', function () {
        STrChOChampUpgradeData.hourglassQualitySpecific = document.getElementById('STrChOChampHourglassQualitySpecific').checked;
        SAVESTrChOChampUpgradeData();
        t.doAction();
    }, false);

    document.getElementById('STrChOChampOverrideSpeedUps').addEventListener('change', function () {
        STrChOChampUpgradeData.overrideSpeedUp = document.getElementById('STrChOChampOverrideSpeedUps').checked;
        SAVESTrChOChampUpgradeData();
        t.doAction();
    }, false);

    document.getElementById('STrChOChampUseWH').addEventListener('change', function () {
        STrChOChampUpgradeData.useWH = document.getElementById('STrChOChampUseWH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useWH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseDH').addEventListener('change', function () {
        STrChOChampUpgradeData.useDH = document.getElementById('STrChOChampUseDH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useDH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseEH').addEventListener('change', function () {
        STrChOChampUpgradeData.useEH = document.getElementById('STrChOChampUseEH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useEH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseSH').addEventListener('change', function () {
        STrChOChampUpgradeData.useSH = document.getElementById('STrChOChampUseSH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useSH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseKH').addEventListener('change', function () {
        STrChOChampUpgradeData.useKH = document.getElementById('STrChOChampUseKH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useKH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseGH').addEventListener('change', function () {
        STrChOChampUpgradeData.useGH = document.getElementById('STrChOChampUseGH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useGH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseMH').addEventListener('change', function () {
        STrChOChampUpgradeData.useMH = document.getElementById('STrChOChampUseMH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useMH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseAH').addEventListener('change', function () {
        STrChOChampUpgradeData.useAH = document.getElementById('STrChOChampUseAH').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useAH) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseQuality').addEventListener('change', function () {
        STrChOChampUpgradeData.useQuality = document.getElementById('STrChOChampUseQuality').value;
        SAVESTrChOChampUpgradeData();
    }, false);

    document.getElementById('STrChOChampUseLevel').addEventListener('change', function () {
        STrChOChampUpgradeData.useLevel = document.getElementById('STrChOChampUseLevel').value;
        SAVESTrChOChampUpgradeData();
    }, false);

    document.getElementById('STrChOChampSpeedUp').addEventListener('change', function () {
        STrChOChampUpgradeData.useSpeedUp = document.getElementById('STrChOChampSpeedUp').value;
        SAVESTrChOChampUpgradeData();
        t.doAction();
    }, false);

    document.getElementById('STrChOChampHourglassLevel').addEventListener('change', function () {
        STrChOChampUpgradeData.hourglassLevel = document.getElementById('STrChOChampHourglassLevel').value;
        SAVESTrChOChampUpgradeData();
        t.doAction();
    }, false);

    document.getElementById('STrChOChampHourglassQuality').addEventListener('change', function () {
        STrChOChampUpgradeData.hourglassQuality = document.getElementById('STrChOChampHourglassQuality').value;
        SAVESTrChOChampUpgradeData();
        t.doAction();
    }, false);

    document.getElementById('STrChOChampUseLOM').addEventListener('change', function () {
        STrChOChampUpgradeData.useLOM = document.getElementById('STrChOChampUseLOM').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useLOM) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseGOM').addEventListener('change', function () {
        STrChOChampUpgradeData.useGOM = document.getElementById('STrChOChampUseGOM').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useGOM) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseET').addEventListener('change', function () {
        STrChOChampUpgradeData.useET = document.getElementById('STrChOChampUseET').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useET) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseJT').addEventListener('change', function () {
        STrChOChampUpgradeData.useJT = document.getElementById('STrChOChampUseJT').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useJT) t.doAction();
    }, false);

    document.getElementById('STrChOChampUseST').addEventListener('change', function () {
        STrChOChampUpgradeData.useST = document.getElementById('STrChOChampUseST').checked;
        SAVESTrChOChampUpgradeData();
        if (STrChOChampUpgradeData.useST) t.doAction();
    }, false);

    document.getElementById('STrChOChampQueueAdd').addEventListener('click', function () {
        t.addChampQueue();
    }, false);

    document.getElementById('STrChOChampOneItem').addEventListener('change', function () {
        STrChOChampQueueData.oneItem = document.getElementById('STrChOChampOneItem').checked;
        SAVESTrChOChampQueueData();
    });

    document.getElementById('STrChOChampClearQ').addEventListener('click', function () {
        STrChOChampQueueData.list = [];
        SAVESTrChOChampQueueData();
        t.buildChampQueueDisplay();
    }, false);

    document.getElementById('STrChOChampEnhanceAddAllQuality').addEventListener('click', function () {
        var low_level = parseInt(document.getElementById('STrChOChampEnhanceAllQuality').value);
        var high_level = parseInt(document.getElementById('STrChOChampEnhanceAllQualityTo').value);
        if (low_level >= high_level) return;
        for (ChampId in uW.kocChampionItems) {
            var ChampItem = uW.kocChampionItems[ChampId];
            if (ChampItem.rarity == low_level) {
                var qItem = new QueueItem();
                qItem.item = ChampId;
                qItem.action = "enhance"
                qItem.level = high_level
                STrChOChampQueueData.list.push(qItem);
            }
        }
        SAVESTrChOChampQueueData();
        t.buildChampQueueDisplay();
    }, false);

    document.getElementById('STrChOChampUpgradeAddAllLevelMax').addEventListener('click', function () {
        var high_level = parseInt(document.getElementById('STrChOChampUpgradeAddAllLevelMaxTo').value);
        for (ChampId in uW.kocChampionItems) {
            var ChampItem = uW.kocChampionItems[ChampId];
            if (ChampItem.level < high_level) {
                var qItem = new QueueItem();
                qItem.item = ChampId;
                qItem.action = "upgrade"
                qItem.level = high_level
                STrChOChampQueueData.list.push(qItem);
            }
        }
        SAVESTrChOChampQueueData();
        t.buildChampQueueDisplay();
    }, false);

    document.getElementById('STrChOChampUpgradeAddAllLevel').addEventListener('click', function () {
        var low_level = parseInt(document.getElementById('STrChOChampUpgradeAllLevel').value);
        var high_level = parseInt(document.getElementById('STrChOChampUpgradeAllLevelTo').value);

        if (low_level >= high_level) return;
        for (ChampId in uW.kocChampionItems) {
            var ChampItem = uW.kocChampionItems[ChampId];
            if (ChampItem.level == low_level) {
                var qItem = new QueueItem();
                qItem.item = ChampId;
                qItem.action = "upgrade"
                qItem.level = high_level
                STrChOChampQueueData.list.push(qItem);
            }
        }
        SAVESTrChOChampQueueData();
        t.buildChampQueueDisplay();
    }, false);

    if (STrChOChampUpgradeData.active)
        t.setStatus("Loading ....");
    else
        t.setStatus("Powered Off");

    t.startTimer();

    t.buildChampLevelWidget();
    t.buildChampQueueDisplay();

    document.getElementById('STrChOChampAction').addEventListener('change', function () {
        t.buildChampLevelWidget();
    }, false);

    Tabs.champPresets.paintTags();


  },

  startTimer: function () {
    var t = Tabs.champUpgrader;
    var delay = 2 + Math.random() * 8;
    if (Seed.queue_champion == null) {
        for (champId in uW.kocChampionItems) {
            var champItem = uW.kocChampionItems[champId];
            if (champItem.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE || champItem.status == CM.CHAMPION.STATUS_REPAIRING_UPGRADE) {
                Seed.queue_champion = {};
                Seed.queue_champion.start = parseInt(champItem.start);
                Seed.queue_champion.end = parseInt(champItem.eta);
                Seed.queue_champion.itemId = champItem.equipmentId;
                break;
            }
        }
    }

    if (Seed.queue_champion != null && Seed.queue_champion.end != null) {
        var repairTimeLeft = Seed.queue_champion.end - unixTime();
        t.repairEnd = Seed.queue_champion.end;
        t.repairId = Seed.queue_champion.itemId;
        var n = new Date(t.repairEnd * 1000);

        t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + uW.kocChampionItems[t.repairId].name);

        if (STrChOChampUpgradeData.useAH || STrChOChampUpgradeData.useGH || STrChOChampUpgradeData.useKH || STrChOChampUpgradeData.useMH || STrChOChampUpgradeData.useSH || STrChOChampUpgradeData.useWH || STrChOChampUpgradeData.useDH || STrChOChampUpgradeData.useEH || (STrChOChampUpgradeData.overrideSpeedUp && STrChOChampUpgradeData.useSpeedUp > 0)) {
            var champItem = uW.kocChampionItems[t.repairId];
            var STrChOChampQuality = champItem.rarity;
            var STrChOChampLevel = champItem.level;
            var useThoseSpeedups = true;
            if (STrChOChampUpgradeData.hourglassQualitySpecific && STrChOChampQuality < STrChOChampUpgradeData.hourglassQuality) useThoseSpeedups = false;
            if (STrChOChampUpgradeData.hourglassLevelSpecific && STrChOChampLevel < STrChOChampUpgradeData.hourglassLevel) useThoseSpeedups = false;
            if (STrChOChampUpgradeData.overrideSpeedUp) useThoseSpeedups = true;
            if (useThoseSpeedups) {
                t.doingSpeedup = true;
                setTimeout(function () { t.doSpeedup(); }, 2000);
            }
        }

        setTimeout(t.clearRepair, (repairTimeLeft + 1) * 5000);
        if (repairTimeLeft > 0) delay += repairTimeLeft;
    }

    if (t.timerH == null)
        t.timerH = setTimeout(t.doAction, delay * 1000);


  },

	hide: function () {},

  refreshAetherDisplay : function () {
      document.getElementById('STrChOChampAetherDisplay').innerHTML = displayCityAstone();
  },


	show: function () {
		var t = Tabs.champUpgrader;
        t.startTimer();
        t.refreshAetherDisplay();
        t.buildChampQueueDisplay();
	},

  doAction: function () {
    var t = Tabs.champUpgrader;
    if (STrChOChampRepairData.active) {
        t.setStatus('Waiting for repair tab to finish...');
        return;
    }

    var retryTime = STrChOGeneralOptions.retryInterval;

    try {
        // check if repair is done
        var ti = t.clearRepair();
        if (ti <= 0) {
            // repair is done
            if (STrChOChampQueueData.oneItem || (STrChOChampQueueData.doingRepairs == true)) {
                for (queueItems in STrChOChampQueueData.list) {
                    var qItem = STrChOChampQueueData.list[queueItems];
                    if (!qItem) continue;

                    var champItem = uW.kocChampionItems[qItem.item];

                    if ((champItem == null) || (STrChOChampQueueData.list[queueItems].status == "complete")) continue;

                    if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                        t.doRepair(champItem.equipmentId);
                        clearTimeout(t.timerH);
                        t.timerH = setTimeout(t.doAction, retryTime * 1000);
                        return;
                    } else if (STrChOChampQueueData.oneItem) {
                        break;
                    }
                }
                //}
            }

            // all repairs complete
            STrChOChampQueueData.doingRepairs = false;
            // set the index
            t.selectNext();
            SAVESTrChOChampQueueData();

            // if we reach the end of the queue, start repair cycle
            if (STrChOChampQueueData.index < 0) {
                t.setStatus("Reached end of queue.")
                t.setResult("");
                if (!STrChOChampUpgradeData.active) t.setStatus("Powered Off");
                STrChOChampQueueData.doingRepairs = true;
                SAVESTrChOChampQueueData();
                clearTimeout(t.timerH);
                t.timerH = setTimeout(t.doAction, retryTime * 1000);
                return;
            }
            // upgrade/enhance next item
            var qItem = STrChOChampQueueData.list[STrChOChampQueueData.index];

            if (qItem) {
                if (qItem.action == "enhance")
                    t.doEnhance(qItem.item);
                else
                    t.doUpgrade(+qItem.item, false);
            }
        } else {
            // come back after repair is complete
            retryTime = ti + 5;
            var n = new Date(t.repairEnd * 1000);
            t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + uW.kocChampionItems[t.repairId].name);
            if (STrChOChampUpgradeData.useSH || STrChOChampUpgradeData.useKH || STrChOChampUpgradeData.useGH || STrChOChampUpgradeData.useMH || STrChOChampUpgradeData.useAH || STrChOChampUpgradeData.useWH || STrChOChampUpgradeData.useDH || STrChOChampUpgradeData.useEH || (STrChOChampUpgradeData.overrideSpeedUp && STrChOChampUpgradeData.useSpeedUp > 0)) {
                var champItem = uW.kocChampionItems[t.repairId];
                var STrChOChampQuality = champItem.rarity;
                var STrChOChampLevel = champItem.level;
                var useThoseSpeedups = true;
                if (STrChOChampUpgradeData.hourglassQualitySpecific && STrChOChampQuality < STrChOChampUpgradeData.hourglassQuality) useThoseSpeedups = false;
                if (STrChOChampUpgradeData.hourglassLevelSpecific && STrChOChampLevel < STrChOChampUpgradeData.hourglassLevel) useThoseSpeedups = false;
                if (STrChOChampUpgradeData.overrideSpeedUp) useThoseSpeedups = true;
                if (useThoseSpeedups) {
                    t.doingSpeedup = true;
                    setTimeout(function () { t.doSpeedup(); }, 2000);
                }
                retryTime = 1;
            }
        }
        //CM.ChampView.renderInventory(uW.kocChampionItems);
    } catch (e) {
    }
    // recycle
    clearTimeout(t.timerH);
    t.timerH = setTimeout(t.doAction, retryTime * 1000);
  },

  doSpeedup: function () {
    var t = Tabs.champUpgrader;

    var endTime = t.repairEnd;
    var startTime = unixTime();
    var secondsForRepair = endTime - startTime;
    var divId = "";

    t.speedup = 0;

    if (secondsForRepair > 0 && STrChOChampUpgradeData.overrideSpeedUp && STrChOChampUpgradeData.useSpeedUp > 0) {

        t.speedup = STrChOChampUpgradeData.useSpeedUp;

    } else {

        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.day25 && STrChOChampUpgradeData.useEH && uW.ksoItems[8].count > 0) { t.speedup = 8; }
        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour24 && STrChOChampUpgradeData.useDH && uW.ksoItems[7].count > 0) { t.speedup = 7; }
        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour15 && STrChOChampUpgradeData.useWH && uW.ksoItems[6].count > 0) { t.speedup = 6; }
        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour8 && STrChOChampUpgradeData.useAH && uW.ksoItems[5].count > 0) { t.speedup = 5; }
        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && STrChOChampUpgradeData.useMH && uW.ksoItems[4].count > 0) { t.speedup = 4; }
        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && STrChOChampUpgradeData.useGH && uW.ksoItems[3].count > 0) { t.speedup = 3; }
        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && STrChOChampUpgradeData.useKH && uW.ksoItems[2].count > 0) { t.speedup = 2; }
        if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && STrChOChampUpgradeData.useSH && uW.ksoItems[1].count > 0) { t.speedup = 1; }
    }

    switch (t.speedup) {
        case "1":
        case 1:
            secondsForRepair -= HOURGLASSES_TIME.minute1;
            divId = 'STrChOChampUseSHLabel';
            break;
        case "2":
        case 2:
            secondsForRepair -= HOURGLASSES_TIME.minute15;
            divId = 'STrChOChampUseKHLabel';
            break;
        case "3":
        case 3:
            secondsForRepair -= HOURGLASSES_TIME.hour1;
            divId = 'STrChOChampUseGHLabel';
            break;
        case "4":
        case 4:
            secondsForRepair -= HOURGLASSES_TIME.hour25;
            divId = 'STrChOChampUseMHLabel';
            break;
        case "5":
        case 5:
            secondsForRepair -= HOURGLASSES_TIME.hour8;
            divId = 'STrChOChampUseAHLabel';
            break;
        case "6":
        case 6:
            secondsForRepair -= HOURGLASSES_TIME.hour15;
            divId = 'STrChOChampUseWHLabel';
            break;
        case "7":
        case 7:
            secondsForRepair -= HOURGLASSES_TIME.hour24;
            divId = 'STrChOChampUseDHLabel';
            break;
        case "8":
        case 8:
            secondsForRepair -= HOURGLASSES_TIME.day25;
            divId = 'STrChOChampUseEHLabel';
            break;
    }

    if (t.speedup != 0) {
        t.setResult('Used ' + uW.ksoItems[t.speedup].name);
        var divCount = uW.ksoItems[t.speedup].count - 1;
        var divSpeedups = document.getElementById(divId);
        divSpeedups.innerHTML = divCount;
        uW.modal_speedup_apply("champion", t.speedup, t.repairId);

        if (secondsForRepair <= 0) {
            secondsForRepair = 0;
            endTime = startTime;
            t.clearTimerH = setTimeout(t.clearRepair, 1000);
            t.buildChampQueueDisplay();
        } else {
            endTime = unixTime() + secondsForRepair;
            t.repairEnd = endTime;
            var n = new Date(t.repairEnd * 1000);
            var item = uW.kocChampionItems[t.repairId];
            t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + item.name);
            t.clearTimerH = setTimeout(t.clearRepair, secondsForRepair * 1000);
            t.buildChampQueueDisplay();
        }
        t.repairEnd = endTime;
        setTimeout(function () { t.doSpeedup(); }, 1000);
    }
  },

  selectNext: function () {

      if (STrChOChampQueueData.index >= STrChOChampQueueData.list.length) STrChOChampQueueData.index = 0;
      if (STrChOChampQueueData.index < 0) STrChOChampQueueData.index = 0;

      // for single item mode, always start from the top
      if (STrChOChampQueueData.oneItem) STrChOChampQueueData.index = 0;

      var l = STrChOChampQueueData.list.length;
      for (i = STrChOChampQueueData.index; i < l; i++) {
          var item = STrChOChampQueueData.list[i];
          if (!item) continue;
          var champItem = uW.kocChampionItems[item.item];
          if ((STrChOChampQueueData.list[i].status != "complete")
                      && (champItem != null)
                      && !(champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE || champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE)) {
              if (((item.action == "enhance") && (item.level <= champItem.rarity))
                          || ((item.action == "upgrade") && (item.level <= champItem.level))) {
                  item.status = "complete";
              } else {
                  STrChOChampQueueData.index = i;
                  return;
              }
          }
      }

      // if we get here, the queue is complete
      STrChOChampQueueData.index = -1;
  },

  doEnhance: function (eItemId) {
      var t = Tabs.champUpgrader;
      try {
          if (STrChOChampUpgradeData.active == false || eItemId == 0) {
              t.setStatus("Powered Off");
              return;
          }
          var champItem = uW.kocChampionItems[eItemId];

          if (!champItem) return;

          if (champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE || champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE) {
              // repair and then try again later
              t.doRepair(eItemId);
              return;
          }

          var num_city = pickAetherUseCity();
          if (num_city < 0) {
              t.setStatus("Not enough aetherstones to enhance.  Minimum of " + STrChOGeneralOptions.minStones + " needed.  Waiting for more ...");
              return;
          }

          var z = CM.WorldSettings.getSettingAsObject("CE_ENHANCE_AETHERSTONE_MAP");
          var w = z[parseInt(champItem.rarity) + 1].Aetherstones;

          if (w > parseInt(Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0])) {
              t.setStatus("Not enough aetherstones to enhance.");
              return;
          }

          var qI = STrChOChampQueueData.list[STrChOChampQueueData.index];
          if (qI) {

              qI.triesTotal++;
              qI.triesThis++;
          }

          var chanceItem = 0;

          var useDiv = '';

          if (STrChOChampUpgradeData.active && STrChOChampQueueData.index != -1 && STrChOChampUpgradeData.useQuality <= champItem.rarity) {

              if (STrChOChampUpgradeData.useLOM) {
                  if (Seed.items['i21001'] > 0) {
                      chanceItem = 21001;
                      useDiv = 'STrChOChampUseLOMLabel';
                  }
              }

              if (STrChOChampUpgradeData.useGOM) {
                  if (Seed.items['i21002'] > 0) {
                      chanceItem = 21002;
                      useDiv = 'STrChOChampUseGOMLabel';
                  }
              }
              //if (buffItemId) CM.InventoryView.removeItemFromInventory(buffItemId);

          }

          if (useDiv != '') document.getElementById(useDiv).innerHTML = uW.ksoItems[chanceItem].count;

          var params = uW.Object.clone(ajfx);
          params.action = '4';
          params.cityId = Seed.cities[num_city][0];
          params.eid = eItemId;
          params.chanceItem = chanceItem;
          params.aetherstones = w;
          params.gems = 0;

          t.setStatus("Sending enhance request");
          new AjaxRequest(uW.g_ajaxpath + 'ajax/ceEquipmentManagerAjax.php' + uW.g_ajaxsuffix, {
              method: "post",
              parameters: params,
              loading: true,
              onSuccess: function (transport) {
                  try {
                      var rslt = eval("(" + transport.responseText + ")");
                      if (rslt.ok) {
                          Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] = Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] - rslt.aetherstones;
                          if (rslt.gems > 0) {
                              ActionLog('Upgrader accidentally spent gems!  Upgrader turned off');
                              t.setStatus("Error ... shutting down");
                              STrChOChampUpgradeData.active = false;
                              SAVESTrChOChampUpgradeData();
                          }

                          if (rslt.itemConsumed.itemId != "0") uW.ksoItems[rslt.itemConsumed.itemId].subtract()

                          Seed.player.might += rslt.mightGain;
                          document.getElementById('topnav_might').innerHTML = Seed.player.might;

                          if (champItem.rarity != parseInt(rslt.rarity)) {
                              STrChOChampUpgradeStats.enhanceSuccess[champItem.rarity][champItem.level]++;
                              SAVESTrChOChampUpgradeStats();
                              champItem.rarity = rslt.rarity;
                              champItem.name = champItem.createName();
                              t.show();
                              t.setResult("Enhance successful.  " + addCommas(rslt.aetherstones) + " aetherstones used.");
                              t.refreshAetherDisplay();
                              t.setStatus("Attempting next action");
                              CM.sounds.play("ch_success_build");
                              // update the cost line
                              var qItem = STrChOChampQueueData.list[STrChOChampQueueData.index];
                              if (qItem) {
                                  var now = new Date();

                                  qItem.lastUpgrade = "Enhanced to " + champCardQualities[champItem.rarity] + " " + now.toDateString().substring(3, 10) + " " + now.toTimeString().substring(0, 8) + " in " + qItem.triesThis + " attempts";
                                  if (!qItem.upgrades) qItem.upgrades = [];
                                  qItem.upgrades.push(qItem.lastUpgrade);

                                  var msg = 'Enhanced ' + uW.kocChampionItems[eItemId].name + ' [ ' + eItemId + '] to quality ' + rslt.rarity + " in " + qItem.triesThis + " attempts. " + qItem.triesTotal + " total attempts for this item.";
                                  if (STrChOGeneralOptions.whisperToMe) sendChat("/" + Seed.player.name + ' ' + msg);
                                  if (STrChOGeneralOptions.sendToInbox) sendComposedMail(Seed.player.name, 'CHAMPION: Enhance Success: ' + uW.kocChampionItems[eItemId].name, msg);
                                  SuccessLog(msg);

                                  if (qItem.level <= champItem.rarity) {
                                      qItem.status = "complete";
                                      STrChOChampUpgradeData.newUpgradeState = 2;
                                  }
                                  else {
                                      var now = new Date();
                                      qItem.status = "Partially enhanced";
                                      qItem.triesLast = qItem.triesThis;
                                      qItem.triesThis = 0;
                                      if (STrChOChampUpgradeData.newUpgradeState != 2) STrChOChampUpgradeData.newUpgradeState = 1;
                                  }
                                  SAVESTrChOChampUpgradeData();
                                  setUpgradeColor();
                              }
                              SAVESTrChOChampQueueData();
                              t.buildChampQueueDisplay();
                              clearTimeout(Tabs.champUpgrader.timerH);
                              t.timerH = setTimeout(t.doAction, 10 * 1000);
                          }
                          else {
                              STrChOChampUpgradeStats.enhanceFailure[champItem.rarity][champItem.level]++;
                              SAVESTrChOChampUpgradeStats();
                              ActionLog('Enhance failed Champion item ' + uW.kocChampionItems[eItemId].name);
                              if (rslt.broken == "yes") {
                                  champItem.status = CM.CHAMPION.STATUS_BROKEN_ENHANCE;
                              }

                              champItem.name = champItem.createName();
                              t.setResult("Enhance failed.  " + addCommas(rslt.aetherstones) + " aetherstones used");
                              t.refreshAetherDisplay();
                              var qItem = STrChOChampQueueData.list[STrChOChampQueueData.index];
                              if (qItem) if (qItem.status == "not started") qItem.status = "started";
                              SAVESTrChOChampQueueData();
                              t.buildChampQueueDisplay();
                              clearTimeout(t.timerH);
                              t.timerH = setTimeout(t.doAction, 10 * 1000);
                          }
                      }
                      else {
                          if (rslt.feedback)
                              t.setStatus(rslt.feedback);
                          else
                              t.setStatus("Unable to enhance at this time ... waiting for next cycle");

                      }
                  } catch (e) {
                  }
                  return;
              },
              onFailure: function (rst) {
                  t.setStatus("Unable to send enhance request.  Waiting for next cycle");
                  return;
              }
          });
      } catch (e) {


      }
      return;
  },

  doUpgrade: function (uItemId, bypass) {

      var t = Tabs.champUpgrader;

      var champItem = uW.kocChampionItems[uItemId];

      if (uItemId == 0 || champItem == null) {
          t.setStatus("Item not found.");
          return;
      }

      if ((STrChOChampUpgradeData.active == false) && (bypass != true)) {
          t.setStatus("Powered Off");
          return;
      }

      if (bypass == true && t.deleting != true) {
          // delete cycle has been canceled.  Don't upgrade this item
          return;
      }

      if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
          // repair and then try again later
          t.doRepair(uItemId);
          return;
      }

      if (champItem.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE || champItem.status == CM.CHAMPION.STATUS_REPAIRING_UPGRADE) {
          t.setStatus("Item is still being repaired");
          return;
      }

      var num_city = pickAetherUseCity();
      if (num_city < 0) {
          t.setStatus("Not enough aetherstones to upgrade.  Minimum of " + STrChOGeneralOptions.minStones + " needed.  Waiting for more ...");
          return;
      }

      var z = CM.WorldSettings.getSettingAsObject("CE_UPGRADE_AETHERSTONE_MAP");
      var w = z[parseInt(champItem.level) + 1].Aetherstones;


      if (w > Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0]) {
          t.setStatus("Not enough aetherstones to upgrade.");
          return;
      }

      if (bypass != true) {
          var qI = STrChOChampQueueData.list[STrChOChampQueueData.index];
          if (qI) {
              qI.triesTotal++;
              qI.triesThis++;
          }

          t.setStatus("Sending upgrade request ...");
      }

      var chanceItem = 0;

      var useDiv = '';

      if (STrChOChampUpgradeData.active && STrChOChampQueueData.index != -1 && STrChOChampUpgradeData.useLevel <= champItem.level) {

          if (STrChOChampUpgradeData.useET) {
              if (Seed.items['i21058'] > 0) {
                  chanceItem = 21058;
                  useDiv = 'STrChOChampUseETLabel';
              }
          }

          if (STrChOChampUpgradeData.useST) {
              if (Seed.items['i21052'] > 0) {
                  chanceItem = 21052;
                  useDiv = 'STrChOChampUseSTLabel';
              }
          }

          if (STrChOChampUpgradeData.useJT) {
              if (Seed.items['i21051'] > 0) {
                  chanceItem = 21051;
                  useDiv = 'STrChOChampUseJTLabel';
              }
          }
      }

      if (STrChOChampUpgradeData.useAutoTokens) {
          if (STrChOChampUpgradeData.useAutoTokensMin <= STrChOChampUpgradeData.useAutoTokensMax) {
              var champLevel = champItem.level;
              if (champLevel >= STrChOChampUpgradeData.useAutoTokensMin &&
                  champLevel < STrChOChampUpgradeData.useAutoTokensMax) {
                  var nextForgedID = getNextAvailableForged(champItem);
                  if (nextForgedID != 0) {
                      chanceItem = nextForgedID;
                      ActionLog('Using ' + uW.ksoItems[chanceItem].name + ' on item: ' + champItem.name);
                  }
              }
          }
      }

      if (useDiv != '') document.getElementById(useDiv).innerHTML = uW.ksoItems[chanceItem].count;

      var params = uW.Object.clone(ajfx);

      params.action = '5';
      params.cityId = Seed.cities[num_city][0];
      params.eid = uItemId;
      params.chanceItem = chanceItem;
      params.aetherstones = w;
      params.gems = 0;


      new AjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
          method: "post",
          parameters: params,
          loading: true,
          onSuccess: function (transport) {
              try {
                  var rslt = eval("(" + transport.responseText + ")");
                  if (rslt.ok) {

                      Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] = Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0] - parseInt(rslt.aetherstones);
                      if (rslt.gems > 0) {
                          t.setStatus("Error .... Shutting down.");
                          ActionLog('Upgrader accidentally spent gems!  Upgrader turned off');
                          STrChOChampUpgradeData.active = false;
                          SAVESTrChOChampUpgradeData();
                      }

                      if (rslt.itemConsumed.itemId != "0") uW.ksoItems[rslt.itemConsumed.itemId].subtract()

                      Seed.player.might += rslt.mightGain;
                      document.getElementById('topnav_might').innerHTML = Seed.player.might;

                      if (parseInt(rslt.level) != champItem.level) {
                          STrChOChampUpgradeStats.upgradeSuccess[champItem.rarity][champItem.level]++;
                          SAVESTrChOChampUpgradeStats();
                          champItem.level = rslt.level;
                          champItem.name = champItem.createName();

                          if (bypass != true) {
                              t.show();

                              t.setResult("Upgrade successful.  " + addCommas(rslt.aetherstones) + " aetherstones used.");
                              t.refreshAetherDisplay();
                              t.setStatus("Attempting next upgrade");
                              CM.sounds.play("ch_success_build");

                              var qItem = STrChOChampQueueData.list[STrChOChampQueueData.index];
                              if (qItem) {
                                  var now = new Date();
                                  qItem.lastUpgrade = "Upgraded to +" + champItem.level + " " + now.toDateString().substring(3, 10) + " " + now.toTimeString().substring(0, 8) + " in " + qItem.triesThis + " attempts";

                                  if (!qItem.upgrades) qItem.upgrades = [];
                                  qItem.upgrades.push(qItem.lastUpgrade);

                                  var msg = 'Upgraded ' + uW.kocChampionItems[uItemId].name + ' [' + uItemId + '] to level ' + rslt.level + " in " + qItem.triesThis + " attempts. " + qItem.triesTotal + " total attempts for this item.";
                                  if (STrChOGeneralOptions.whisperToMe) sendChat("/" + Seed.player.name + ' ' + msg);
                                  if (STrChOGeneralOptions.sendToInbox) sendComposedMail(Seed.player.name, 'CHAMPION: Upgrade Success : ' + uW.kocChampionItems[uItemId].name, msg);
                                  SuccessLog(msg);
                                  if (qItem.level <= champItem.level) {
                                      qItem.status = "complete";
                                      STrChOChampUpgradeData.newUpgradeState = 2;
                                  }
                                  else {
                                      var now = new Date();
                                      qItem.status = "Partially upgraded";
                                      qItem.triesLast = qItem.triesThis;
                                      qItem.triesThis = 0;
                                      if (STrChOChampUpgradeData.newUpgradeState != 2) STrChOChampUpgradeData.newUpgradeState = 1;
                                  }
                                  SAVESTrChOChampUpgradeData();
                                  setUpgradeColor();
                              }
                              SAVESTrChOChampQueueData();
                              t.buildChampQueueDisplay();
                              clearTimeout(t.timerH);
                              t.timerH = setTimeout(t.doAction, 10 * 1000);

                          }
                      }
                      else {
                          STrChOChampUpgradeStats.upgradeFailure[champItem.rarity][champItem.level]++;
                          SAVESTrChOChampUpgradeStats();
                          ActionLog('Upgrade failed Champion item ' + uW.kocChampionItems[uItemId].name);
                          if (rslt.broken == "yes") champItem.status = CM.CHAMPION.STATUS_BROKEN_UPGRADE;
                          champItem.name = champItem.createName();
                          if (bypass != true) {
                              if (rslt.feedback) {
                                  t.setResult(rslt.feedback);
                              } else {
                                  t.setResult("Upgrade failed.  " + addCommas(rslt.aetherstones) + " aetherstones used");
                                  t.refreshAetherDisplay();
                              }
                              var qItem = STrChOChampQueueData.list[STrChOChampQueueData.index];
                              if (qItem.status == "not started") qItem.status = "started";
                              SAVESTrChOChampQueueData();
                              t.buildChampQueueDisplay();
                              clearTimeout(t.timerH);
                              t.timerH = setTimeout(t.doAction, 10 * 1000);
                          }
                      }
                      return;
                  }
                  else {
                      if (bypass != true) {
                          t.setResult(rslt.feedback);
                      }
                  }
              } catch (e) {
              }
              return;
          },
          onFailure: function (rrr) {
              t.setStatus("Unable to transmitt upgrade request.  Waiting for next cycle.");
              return;
          }
      });

      return;
  },

  doRepair: function (rItemId) {
      var t = Tabs.champUpgrader;
      var params = uW.Object.clone(ajfx);

      if (!STrChOChampUpgradeData.active || rItemId == 0 || uW.kocChampionItems[rItemId] == null) {
          t.setStatus("Powered Off");
          return; //repair is turned off
      }

      var theItem = uW.kocChampionItems[rItemId];

      params.action = "6";
      params.eid = rItemId;
      params.cityId = uW.currentcityid;
      params.gems = 0;

      new AjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
          method: "post",
          parameters: params,
          loading: true,
          onSuccess: function (transport) {
              var rslt = eval("(" + transport.responseText + ")");
              if (rslt.ok) {
                  var item = uW.kocChampionItems[rslt.equipmentId];
                  ActionLog('Starting repair for Champion item ' + item.name);
                  if (!Seed.queue_champion) Seed.queue_champion = {};
                  Seed.queue_champion.itemId = rslt.equipmentId;
                  Seed.queue_champion.start = parseInt(rslt.start);
                  Seed.queue_champion.end = parseInt(rslt.eta);
                  t.repairId = parseInt(rslt.equipmentId);
                  t.repairEnd = rslt.eta;
                  var n = new Date(t.repairEnd * 1000);
                  t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + item.name);
                  var x = rslt.eta - unixTime();
                  t.clearTimerH = setTimeout(t.clearRepair, (x + 1) * 1000);
                  if (item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE)
                      item.status = CM.CHAMPION.STATUS_REPAIRING_ENHANCE;
                  else
                      item.status = CM.CHAMPION.STATUS_REPAIRING_UPGRADE;
                  t.buildChampQueueDisplay();
              }
              else {
                  // regrab the end times in case this is caused by a manual repair
                  if (Seed.queue_champion && Seed.queue_champion.end && Seed.queue_champion.itemId) {
                      t.repairEnd = Seed.queue_champion.end;
                      t.repairId = Seed.queue_champion.itemId;
                  }

                  if (feedback.index("There is one equipment in repairing queue") > 0) {
                      // item is still be repaired.
                      return;
                  }


                  if (rslt.feedback) {
                      t.setStatus(rslt.feedback);
                      uW.kocChampionItems[rItemId].status = CM.CHAMPION.STATUS_INACTIVE;
                      t.clearRepair();
                  }

              }
              return;
          },
          onFailure: function (ttt) {
              // this usually means a repair is in progress (such as a manual repair). Grab the seed data (if possible)
              if (Seed.queue_champion && Seed.queue_champion.end) {
                  t.repairEnd = Seed.queue_champion.end;
                  t.repairId = Seed.queue_champion.itemId;
              }
              return;
          }
      });
      return;
  },

  clearRepair: function () {
      //logit("clear repair");
      var t = Tabs.champUpgrader;
      var timeUntilDone = 0;

      if (t.repairEnd == 0) {
          return timeUntilDone;
      }
      timeUntilDone = t.repairEnd - unixTime();

      if (timeUntilDone <= 0) {
          if (t.repairId != 0 && uW.kocChampionItems[t.repairId] != null) {
              if (uW.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_INACTIVE
                             || uW.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_ACTIVE) {
                  t.setStatus("Repair time complete.");
              }
              uW.kocChampionItems[t.repairId].status = CM.CHAMPION.STATUS_INACTIVE;
              t.repairId = 0;
              t.show();
          }

      }
      return timeUntilDone;
  },

  addUpgradeItem: function (champId) {
      var t = Tabs.champUpgrader;
      var qItem = new QueueItem();
      qItem.item = champId;
      qItem.action = "upgrade";
      qItem.level = STrChOMaxChampLevel;
      STrChOChampQueueData.list.push(qItem);
      SAVESTrChOChampQueueData();
      //document.getElementById('champInventoryItem' + champId).className = 'STrChOBlueBorder';
      t.buildChampQueueDisplay();
  },

  addEnhanceItem: function (champId) {
      var t = Tabs.champUpgrader;
      var qItem = new QueueItem();
      qItem.item = champId;
      qItem.action = "enhance";
      qItem.level = STrChOMaxChampQuality;
      STrChOChampQueueData.list.push(qItem);
      SAVESTrChOChampQueueData();
      //document.getElementById('champInventoryItem' + champId).className = 'STrChOYellowBorder';
      t.buildChampQueueDisplay();
  },

  addBothChampItem: function (champId) {
      var t = Tabs.champUpgrader;

      var champItem = uW.kocChampionItems[champId];

      if (champItem == null || !champItem) return;

      var qual = +champItem.rarity;
      var lev = +champItem.level;

      if (qual >= STrChOMaxChampQuality) return;

      var maxLev = null;
      var nextQual = null;
      var qItem = null;

      while (qual < STrChOMaxChampQuality) {
          maxLev = t.upgradePath[qual].maxLev;
          nextQual = t.upgradePath[qual].nextQual;

          if (lev < maxLev) {
              qItem = new QueueItem();
              qItem.item = champId;
              qItem.action = "upgrade";
              qItem.level = maxLev;
              STrChOChampQueueData.list.push(qItem);
              //document.getElementById('champInventoryItem' + champId).className = 'STrChOBlueBorder';
          }

          qItem = new QueueItem();
          qItem.item = champId;
          qItem.action = "enhance";
          qItem.level = nextQual;
          STrChOChampQueueData.list.push(qItem);
          //document.getElementById('champInventoryItem' + champId).className = 'STrChOYellowBorder';
          lev = maxLev;
          qual = nextQual;
      }

      SAVESTrChOChampQueueData();
      t.buildChampQueueDisplay();
  },

  addChampQueue: function () {
      var t = Tabs.champUpgrader;
      var action = document.getElementById('STrChOChampAction').value;
      if (action == "both") {
          t.addBothChampItem(document.getElementById('STrChOChampUpgradeList').value);
          return;
      }
      var qItem = new QueueItem();
      qItem.item = document.getElementById('STrChOChampUpgradeList').value;
      qItem.action = document.getElementById('STrChOChampAction').value;
      qItem.level = document.getElementById('STrChOChampMaxLevel').value;
      if (qItem.item == 0) return;
      STrChOChampQueueData.list.push(qItem);
      SAVESTrChOChampQueueData();
      t.buildChampQueueDisplay();
  },

  buildChampLevelWidget: function () {
      var t = Tabs.champUpgrader;
      var m;
      var STrChOChampAction = document.getElementById('STrChOChampAction');
      if (STrChOChampAction.value == "enhance") {
          m = ' Max: <select class=STrChOSelect id=STrChOChampMaxLevel>';
          for (qual = 1; qual <= STrChOMaxChampQuality; qual++) {
              m += '<option value="' + qual + '">' + champCardQualities[qual] + '</option>';
          }
          m += '</select>';
      } else if (STrChOChampAction.value == "upgrade") {
          m = ' Max: <select class=STrChOSelect id=STrChOChampMaxLevel>';
          for (lvl = 1; lvl <= STrChOMaxChampLevel; lvl++) {
              m += '<option value="' + lvl + '"> +' + lvl + '</option>';
          }
          m += '</select>';
      } else {
          m = ' - <select class=STrChOSelect id=STrChOChampMaxLevel></select>';
      }

      document.getElementById('STrChOChampMaxDiv').innerHTML = m;
      if (STrChOChampAction.value == "enhance") {
          document.getElementById('STrChOChampMaxLevel').value = STrChOMaxChampQuality;
      } else if (STrChOChampAction.value == "upgrade") {
          document.getElementById('STrChOChampMaxLevel').value = STrChOMaxChampLevel;
      }

  },

  buildChampQueueDisplay: function () {
      var t = Tabs.champUpgrader;

      var STrChOChampQDiv = document.getElementById('STrChOChampQDiv');

      var m = '<table id=STrChOChampQueue width=100%>';
      m += '<tr><th width=10%>Remove</th>';
      m += '<th width=5%>Order</th>';
      m += '<th width=8%>Status</th>';
      m += '<th width=25%>Item</th>';
      m += '<th width=5%>Action</th>';
      m += '<th width=5%>Max</th>';
      m += '<th width=40%>Status/Last Upgrade/Attempts</th></tr>';

      for (var queueIndex = 0; queueIndex < STrChOChampQueueData.list.length; queueIndex++) {
          var queueItem = STrChOChampQueueData.list[queueIndex];
          if (!queueItem) continue;
          var champItem = uW.kocChampionItems[queueItem.item];

          var champCardName = "Unknown / Item removed";
          var champId = 0;

          if (champItem) {
              champCardName = champItem.name;
              champId = champItem.id;
          }

          m += '<tr>';
          m += '<td align=center><div id=STrChOChampQueueRemove' + queueIndex + ' class=STrChORemove></div></td>';
          m += '<td align=center><div id=STrChOChampUpRow' + queueIndex + ' class=STrChOUpRow></div><div class=STrChODownRow  id=STrChOChampDownRow' + queueIndex + '></div></td>';
          m += '<td align=center><div id=STrChOChampState' + queueIndex + '></div></td>';
          m += '<td align=center class=STrChOChampUpdaterItemName><div id=STrChOChampUpdaterItem' + champId + ' >' + champCardName + '</div></td>';
          m += '<td align=center>' + queueItem.action + '</td>';
          m += '<td>';
          if (queueItem.action == "enhance") {
              m += '<div style="text-align: center;"><select class=STrChOSelect id=STrChOChampChangeLevel' + queueIndex + ' style="width:90px; text-align: center;">';
              for (qual = 1; qual <= STrChOMaxChampQuality; qual++) {
                  m += '<option value="' + qual + '" ' + (queueItem.level == qual ? 'selected' : '') + '>' + champCardQualities[qual] + '</option>';
              }
              m += '</select></div>';
          } else {
              m += '<div style="text-align: center;"><select class=STrChOSelect id=STrChOChampChangeLevel' + queueIndex + ' style="width:90px; text-align: center;">';
              for (lvl = 1; lvl <= STrChOMaxChampLevel; lvl++) {
                  m += '<option value="' + lvl + '"  ' + (queueItem.level == lvl ? 'selected' : '') + '> +' + lvl + '</option>';
              }
              m += '</select></div>';
          }
          m += '</td>';

          m += '<td style="text-align: center; white-space: pre-wrap;">' + queueItem.status + ' / ';
          if (queueItem.lastUpgrade) m += queueItem.lastUpgrade;
          m += ' / ' + queueItem.triesThis + ' tries this level, ' + queueItem.triesTotal + ' tries total';
          m += '</td>';

          m += '</tr>';
      }
      m += '</table>';

      STrChOChampQDiv.innerHTML = m;

      for (var queueIndex = 0; queueIndex < STrChOChampQueueData.list.length; queueIndex++) {
          var queueItem = STrChOChampQueueData.list[queueIndex];
          if (!queueItem) continue;
          var champItem = uW.kocChampionItems[queueItem.item];

          document.getElementById('STrChOChampQueueRemove' + queueIndex).setAttribute('v1', queueIndex);
          document.getElementById('STrChOChampQueueRemove' + queueIndex).addEventListener('click', function () {
              var qIndex = this.getAttribute('v1');
              t.deleteQueueItem(qIndex);
          }, false);

          document.getElementById('STrChOChampUpRow' + queueIndex).setAttribute('v1', queueIndex);
          document.getElementById('STrChOChampUpRow' + queueIndex).addEventListener('click', function () {
              var qIndex = this.getAttribute('v1');
              t.moveUpRow(qIndex);
          }, false);

          document.getElementById('STrChOChampDownRow' + queueIndex).setAttribute('v1', queueIndex);
          document.getElementById('STrChOChampDownRow' + queueIndex).addEventListener('click', function () {
              var qIndex = this.getAttribute('v1');
              t.moveDownRow(qIndex);
          }, false);

          document.getElementById('STrChOChampChangeLevel' + queueIndex).setAttribute('v1', queueIndex);
          document.getElementById('STrChOChampChangeLevel' + queueIndex).addEventListener('change', function () {
              var qIndex = this.getAttribute('v1');
              var itemLevel = this.value;
              t.changeLevel(qIndex, itemLevel);
          }, false);

          if (!champItem || !(champItem.equipmentId)) {
              document.getElementById('STrChOChampState' + queueIndex).innerHTML = '<div style="text-align:center"> ??</div>';

          } else if (queueItem.status == "complete") {
              document.getElementById('STrChOChampState' + queueIndex).className = 'STrChOSuccess';

          } else if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
              document.getElementById('STrChOChampState' + queueIndex).className = 'STrChOBroken';

          } else if (champItem.status == CM.CHAMPION.STATUS_REPAIRING_UPGRADE || champItem.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE) {
              document.getElementById('STrChOChampState' + queueIndex).className = 'STrChOHammer';
          } else {
              document.getElementById('STrChOChampState' + queueIndex).innerHTML = '<div class=STrChOGoButton></div>';
          }

      }
  },

  deleteQueueItem: function (index) {
      // delete an item from the queue
      var t = Tabs.champUpgrader;
      STrChOChampQueueData.list.splice(index, 1);
      if (index > STrChOChampQueueData.index) STrChOChampQueueData.index--;
      SAVESTrChOChampQueueData();
      t.buildChampQueueDisplay();
  },

  moveUpRow: function (index) {
      if (index < 1) return;
      var t = Tabs.champUpgrader;
      var qItem = STrChOChampQueueData.list.splice(index, 1);
      STrChOChampQueueData.list.splice(index - 1, 0, qItem[0]);

      if (index == STrChOChampQueueData.index)
          STrChOChampQueueData.index--;
      else if (STrChOChampQueueData.index == index - 1)
          STrChOChampQueueData.index++;

      SAVESTrChOChampQueueData();
      t.buildChampQueueDisplay();
  },

  moveDownRow: function (index) {
      if (index > (STrChOChampQueueData.list.length - 2)) return;

      var t = Tabs.champUpgrader;
      var qItem = STrChOChampQueueData.list.splice(index, 1);
      STrChOChampQueueData.list.splice(index + 1, 0, qItem[0]);

      if (index == STrChOChampQueueData.index)
          STrChOChampQueueData.index++;
      else if (STrChOChampQueueData.index == index + 1)
          STrChOChampQueueData.index--;

      SAVESTrChOChampQueueData();
      t.buildChampQueueDisplay();

  },

  changeLevel: function (index, level) {
      var t = Tabs.champUpgrader;

      var queueItem = STrChOChampQueueData.list[index];
      if (!queueItem) return;

      queueItem.level = level;
      if (queueItem.status == "complete") queueItem.status = "started";
      SAVESTrChOChampQueueData();
      t.buildChampQueueDisplay();
  },

  setStatus: function (s) {
      document.getElementById('STrChOChampUpgradeStatus').innerHTML = '<div>' + s + '</div>';
  },

  setResult: function (s) {
      document.getElementById('STrChOChampLastResult').innerHTML = '<div>' + s + '</div>';
  },

  togglePower: function (obj) {
      var t = Tabs.champUpgrader;

      if (!STrChOChampUpgradeData.active && STrChOChampRepairData.active) {
          alert('You must disable repair tab first');
          return;
      }

      var btn = document.getElementById('STrChOChampUpgradePower');
      if (STrChOChampUpgradeData.active) {
          STrChOChampUpgradeData.active = false;
          btn.value = 'Upgrader = OFF';
          t.setStatus('Powered Off');
          t.setResult('');

      } else {
          STrChOChampUpgradeData.active = true;
          btn.value = "Upgrader = ON";
          t.setStatus("Powered On");
          t.setResult("");
      }

      if (!STrChOChampUpgradeData.active) {

      }

      SAVESTrChOChampUpgradeData();
  },

}

Tabs.champSalvager = {
	tabOrder: 201,
	tabLabel: 'SALVAGER',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL SALVAGER',
    timer    : null,
    city     : null,
    cityNum  : 0,
    delItems        : [],
    rowNum   : 0,
    sTimer : null,
    delTimer : null,
    upgradeProfit: true,

	init: function (div) {
		var t = Tabs.champSalvager;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

		m += '<div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        if (STrChOChampSalvageData.active) {
            m += '<td width=33%><input id=STrChOChampSalvagerPower type=button class=STrChOButton value="Salvager = ON"></td>';
        } else {
            m += '<td width=33%><input id=STrChOChampSalvagerPower type=button class=STrChOButton value="Salvager = OFF"></td>';
        }
        m += '<td width=33%><div class=divNoWrap align=center>';
        m += 'Keep All: <select id=STrChOChampSalvageQuality class=STrChOSelect>';
        for (i = 1; i <= STrChOMaxChampQuality; i++) m += '<option value="' + i + '" ' + (STrChOChampSalvageData.minQuality == i ? 'SELECTED' : '') + '>' + throneCardQualities[i].capitalizeFirstLetter() + '+</option>';
        m += '</select>';
        m += '</div></td>';
        m += '<td width=33%><div class=divNoWrap>Keep First <input style="text-align: center;" id=STrChOChampSaveNum class=STrChOTextbox type=text size=3 maxlength=3 value="' + STrChOChampSalvageData.champSaveNum + '"/> Items</div></td>';
        m += '</tr>';
        m += '<tr><td colspan=3><hr class=STrChOHRCenter></td></tr>';
        m += '<tr><td colspan=3><div class=indent5 id=STrChOChampSalvageStatus></div></td></tr>';
        m += '<tr><td colspan=3><div class=indent5 id=STrChOChampNumSalv><br></div></td></tr>';
        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader id=STrChOChampSimpleRule onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SIMPLE RULES&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="position: static; width: 100%; height: 200px; overflow-x: hidden; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';
        m += '<table>';
        m += '<tr><td><b>Define Champ Items To Keep:</b></td>';
        m += '<td alight=left><div><span>Faction: <select id=STrChOChampFactionType class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var fact = 0; fact < STrChOFactions.length; fact++) m += '<option value="' + STrChOFactions[fact] + '">' + STrChOFactions[fact].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td alight=left><div><span>Card Type: <select id=STrChOChampCardType class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var ct in champItemNames) m += '  <option value="' + champItemNames[ct] + '">' + champItemNames[ct].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td align=right><input id=STrChOChampAddRule type=button class=STrChOButton value="Create Rule"/></td>';
        m += '</tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '<tr><td>';
        m += '<table id=STrChOChampConditionTable style="padding-left: 5px;">';
        m += '<tr><td align=left colspan=1><input id=STrChOChampAddRow type=button class=STrChOButton value="Add Row"/></td>';
        m += '<td></td><td></td><td></td><td></td><td></td></tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';   //end of STrChOSection

        m += '<div class=STrChOHeader id=STrChOChampAdvancedRule onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;ADVANCED RULES&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';
        m += '<table>';
        m += '<tr><td colspan=4><input class=STrChOButton type=button id=STrChOChampAdvancedReset value="Reset"></tr>';
        m += '<tr>';
        m += '<td><b>Define Champ Items To Keep:</b></td>';
        m += '<td alight=left><div><span>Faction: <select id=STrChOChampFactionTypeAdvanced class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var fact = 0; fact < STrChOFactions.length; fact++) m += '<option value="' + STrChOFactions[fact] + '">' + STrChOFactions[fact].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td alight=left><div><span>Card Type: <select id=STrChOChampCardTypeAdvanced class=STrChOSelect>';
        m += '  <option value="any">Any</option>';
        for (var ct in champItemNames) m += '  <option value="' + champItemNames[ct] + '">' + champItemNames[ct].capitalizeFirstLetter() + '</option>';
        m += '</select></span></div></td>';
        m += '<td align=right><input id=STrChOChampAddRuleAdvanced type=button class=STrChOButton value="Create Rule"/></td>';
        m += '</tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '<tr><td>';
        m += '<table width=100% id=STrChOChampConditionTableAdvanced>';
        m += '<tr>';
        m += '<td width=20%>ROW 1</td>';
        m += '<td width=20%>ROW 2</td>';
        m += '<td width=20%>ROW 3</td>';
        m += '<td width=20%>ROW 4</td>';
        m += '<td width=20%>ROW 5</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOChampRow1Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOChampRow2Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOChampRow3Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOChampRow4Advanced class=STrChOSelect></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id=STrChOChampRow5Advanced class=STrChOSelect></select></div></td>';
        m += '</tr>';
        m += '</table>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';   //end of STrChOSection

        m += '<div class=STrChOHeader>&nbsp;RULES LIST&nbsp;</div>';

        m += '<div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td align=center>';
        m += 'Sort By Card Type: <select id=STrChOChampSalvageSortCard class=STrChOSelect>';
        m += '<option value="0">--Select--</option>';
        for (var ct in champItemNames) m += '  <option value="' + champItemNames[ct] + '">' + champItemNames[ct].capitalizeFirstLetter() + '</option>';
        m += '</select>';
        m += '</td></tr>';
        m += '<tr><td align=center>';
        m += '<b>Salvager Will Keep Items Matching These Rules</b>';
        m += '</td></tr>';
        m += '<tr><td align=center>';
        m += '<div align=center>';
        m += '<table align=center width=100%>';
        m += '<tr>';
        m += '<td align=left><input id=STrChOChampButtonSaveItem type=button class=STrChOButton value="Save Rules">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        m += '<input id=STrChOChampClearAllRules type=button class=STrChOButton value="Clear All Rules"></td>';
        m += '<td align=right>'
        m += '<input id=STrChOChampButtonLoadItem type=button class=STrChOButton value="Load Rules">';
        m += '<input class=STrChOButton type=button id=STrChOChampFileDrop onclick="document.getElementById(\'STrChOChampFileLoadItem\').click()" value="Browse...">';
        m += '<input id=STrChOChampFileLoadItem style="visibility: hidden; height:0px; width: 0px;" type=file>';
        m += '</td>';
        m += '</tr>';
        m += '</table>';
        m += '</div>';
        m += '</td></tr>';
        m += '<tr><td align=center>';
        m += '<div id=STrChOChampRuleScroll style="position: static; width: 100%; height: ' + dlgHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<div id=STrChOChampRuleDisplay></div>';
        m += '</div>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>'; //end of STrChOSection
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        if (STrChOChampSalvageData.active)
            t.setStatus('Loading...');
        else
            t.setStatus('Powered Off');

        t.displayNumberSalvaged();

        document.getElementById('STrChOChampClearAllRules').addEventListener('click', function() {
            STrChOChampSalvageData.ruleSet = [];
            SAVESTrChOChampSalvageData();
            t.buildChampRuleDisplay();
        }, false);


        document.getElementById('STrChOChampAdvancedReset').addEventListener('click', function () {
            var cardtype = document.getElementById('STrChOChampCardTypeAdvanced');
            cardtype.selectedIndex = 0;
            t.clearAdvancedStats();
            t.setAdvancedStatsToAny();
        }, false);

        t.setAdvancedStatsToAny();

        document.getElementById('STrChOChampAddRuleAdvanced').addEventListener('click', function() {
            t.createAdvancedRule();
        }, false);

        document.getElementById('STrChOChampCardTypeAdvanced').addEventListener('change', function() {
            var selectedValue = document.getElementById('STrChOChampCardTypeAdvanced').value;
            t.clearAdvancedStats();
            if (selectedValue == "any") {
                t.setAdvancedStatsToAny();
            } else {
                t.filterAdvancedStats(selectedValue);
            }
        }, false);

        document.getElementById('STrChOChampSalvagerPower').addEventListener('click', function() {
            t.togglePower(this);
        } , false);

        t.createRow();
        t.buildChampRuleDisplay();

        document.getElementById('STrChOChampSalvageSortCard').addEventListener('change', function() {
            t.buildChampRuleDisplay();
        }, false);

        document.getElementById('STrChOChampButtonSaveItem').addEventListener('click', function() {
            uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(STrChOChampSalvageData.ruleSet));
            newWindow = window.open(uriContent, 'file.txt');
        }, false);

        document.getElementById('STrChOChampButtonLoadItem').addEventListener('click', function() {
            var fileInput = document.getElementById("STrChOChampFileLoadItem");
            var files = fileInput.files;
            if (files.length==0) {
                alert('Please Select A File');
                return;
            }
            var file = files[0];

            var reader = new FileReader();

            reader.onload = function (e) {
				var output = e.target.result;
				STrChOChampSalvageData.ruleSet = JSON.parse(output);
                STrChOChampSalvageData.active = false;
                clearInterval(t.sTimer);
                clearInterval(t.delTimer);
                t.deleting = false;
                SAVESTrChOChampSalvageData();
                t.show();
                alert('Champ Salvage Settings Now Loaded From File');
            };
            reader.readAsText(file);
        }, false);

        document.getElementById('STrChOChampSaveNum').addEventListener('change', function () {
            STrChOChampSalvageData.champSaveNum = parseInt(document.getElementById('STrChOChampSaveNum').value);
            if (STrChOChampSalvageData.champSaveNum < 0) STrChOChampSalvageData.champSaveNum = 0;
            SAVESTrChOChampSalvageData();
        }, false);

        document.getElementById('STrChOChampSalvageQuality').addEventListener('click', function() {
            t.setSalvageLevel(this.value);
        }, false);

        document.getElementById('STrChOChampAddRow').addEventListener('click', function() {
            t.createRow();
        }, false);

        document.getElementById('STrChOChampAddRule').addEventListener('click', function() {
            t.createRule();
        }, false);

        t.upgradeProfit = (5*CM.WorldSettings.getSettingAsNumber("AETHERSTONE_SALVAGE_MULTIPLIER", 500) > CM.thronestats.upgrade[1]["Stones"]);
        t.start();

	},

    setAdvancedStatsToAny: function() {
        for (var r = 1; r < STrChOQualityCount; r++) {
            var row = document.getElementById('STrChOChampRow' + r + 'Advanced');
            row.options.add(new Option("none","none"));
            for (i = 0; i < champItemEffects.length; i++) {
                var effectName = uW.g_js_strings.effects["name_" + champItemEffects[i]];
                row.options.add(new Option(effectName, effectName));
            }
        }
    },

    clearAdvancedStats: function() {
        for (var i = 1; i < STrChOQualityCount; i++) {
            var row = document.getElementById('STrChOChampRow' + i + 'Advanced');
            row.innerHTML = "";
        }
    },

    filterAdvancedStats: function(cardtype) {
        var t = Tabs.champSalvager;

        cardtype = cardtype || "any";

        if (cardtype == "any") {
            t.setAdvancedStatsToAny();
            return;
        }

        document.getElementById("STrChOChampRow1Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOChampRow2Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOChampRow3Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOChampRow4Advanced").options.add(new Option("none", "none"));
        document.getElementById("STrChOChampRow5Advanced").options.add(new Option("none", "none"));

        for (i = 0; i < champItemEffects.length; i++) {
            var effectName = uW.g_js_strings.effects["name_" + champItemEffects[i]];
            var eff = champItemEffects[i];
            if (STrChOChampStatsGrid[cardtype][1][eff]) { document.getElementById("STrChOChampRow1Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOChampStatsGrid[cardtype][2][eff]) { document.getElementById("STrChOChampRow2Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOChampStatsGrid[cardtype][3][eff]) { document.getElementById("STrChOChampRow3Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOChampStatsGrid[cardtype][4][eff]) { document.getElementById("STrChOChampRow4Advanced").options.add(new Option(effectName, effectName)); }
            if (STrChOChampStatsGrid[cardtype][5][eff]) { document.getElementById("STrChOChampRow5Advanced").options.add(new Option(effectName, effectName)); }
        }

    },

	hide: function () {},

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

    tripOdometer : function() {
        var t = Tabs.champSalvager;
        STrChOChampSalvageData.numSalvagedItems2 = 0;
        var now = new Date();
        STrChOChampSalvageData.since = now.valueOf();
        SAVESTrChOChampSalvageData();
        t.show();
    },

    displayNumberSalvaged : function () {
        var t = Tabs.champSalvager;

        var since = "";
        var rate = "";
        var now = new Date();

        if (!STrChOChampSalvageData.since) STrChOChampSalvageData.since = now.valueOf();

        var sinceD = new Date(STrChOChampSalvageData.since);

        since = sinceD.toDateString().substring(3,10) + " " + sinceD.toLocaleTimeString();
        var duration = now.valueOf() - STrChOChampSalvageData.since +1;
        duration = duration / 1000.0;
        rate = " (" + addCommas(Math.round(STrChOChampSalvageData.numSalvagedItems2 / duration * 86400)) + " per day)";

        var m = '<div style="text-align: center;">' + addCommas(STrChOChampSalvageData.numSalvagedItems);
        m += ' items salvaged, ' + addCommas(STrChOChampSalvageData.numSalvagedItems2);
        m += ' items since ' + since + rate + ' <input id=STrChOChampTripOdometer class=STrChOButton type=button value="Reset" /></div>';
        document.getElementById('STrChOChampNumSalv').innerHTML = m;

        document.getElementById('STrChOChampTripOdometer').addEventListener('click', function () {
            t.tripOdometer();
        }, false);

    },


    createRow : function() {
        var t = Tabs.champSalvager;
        var table = document.getElementById('STrChOChampConditionTable');
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount-1);
        var rowId = "r" + t.rowNum;
        t.rowNum++;
        row.id = rowId;

        var h  = "<td> <select class=STrChOSelect id='" + rowId + "ChampsSel1'> <option value='true'> </option> <option value='false'>NOT</option></select></td>";
        h += "<td> <select class=STrChOSelect id='" + rowId + "ChampsSel2'>";
        h += "  <option value='1'>1x</option>";
        h += "  <option value='2'>2x</option>";
        h += "  <option value='3'>3x</option>";
        h += "  <option value='4'>4x</option>";
        h += "  <option value='5'>5x</option>";
        h += "</select></td>";
        h += "<td> <select class=STrChOSelect id='" + rowId + "ChampsSel3'>";
        h += "</select></td>";
        h += "<td> <select class=STrChOSelect id='" + rowId + "ChampsSel4'>";
        h += "  <option value='e'>Either</option>";
        h += "  <option value='b'>Buff</option>";
        h += "  <option value='d'>Debuff</option>";
        h += "</select></td>";

        h += "<td> Slots: ";
        h += "  <input class=STrChOCheckbox type=checkbox value='1' checked=true id='" + rowId + "ChampsSlot1'/>1";
        h += "  <input class=STrChOCheckbox type=checkbox value='2' checked=true id='" + rowId + "ChampsSlot2'/>2";
        h += "  <input class=STrChOCheckbox type=checkbox value='3' checked=true id='" + rowId + "ChampsSlot3'/>3";
        h += "  <input class=STrChOCheckbox type=checkbox value='4' checked=true id='" + rowId + "ChampsSlot4'/>4";
        h += "  <input class=STrChOCheckbox type=checkbox value='5' checked=true id='" + rowId + "ChampsSlot5'/>5";
        h += "</td>";

        row.innerHTML = h;

        var effects = [];

        for (i = 0; i < champItemEffects.length; i++) {
            var effectName = uW.g_js_strings.effects["name_" + champItemEffects[i]];
            effectName = effectName.split(" Debuff")[0];
            if  (effects.indexOf(effectName) < 0) effects.push(effectName);
        }

        var select = document.getElementById(rowId + "ChampsSel3");
        for (index in effects) {
            select.options.add(new Option(effects[index], effects[index]));
        }

        var c = row.insertCell(5);
        //TODO
//        var btn = document.createElement("BUTTON");
//        btn.className = 'STrChOButton';
//        btn.value = 'X';
//        btn.addEventListener('click', function () { t.removeRow(row); }, false);
//        c.append(btn);
        var btn = $("<input class=STrChOButton type=button value='X'/>");
        $(btn).click( function () { t.removeRow(row);});
        $(c).append( btn );

    },

    setSalvageLevel : function(level) {
        STrChOChampSalvageData.minQuality = level;
        SAVESTrChOChampSalvageData();
    },

    createAdvancedRule: function() {
        var t = Tabs.champSalvager;
        t.readAdvancedRows();
        t.buildChampRuleDisplay();
    },

    createRule : function() {
        var t = Tabs.champSalvager;
        t.readRows();
        t.buildChampRuleDisplay();
    },

    buildChampRuleDisplay : function () {
        var t = Tabs.champSalvager;

        function innerRuleDisplay(dataset) {
            var innerM = "";
            for (i = 0; i < dataset.length; i++)
            {
                var rule = dataset[i];

                innerM += '<tr>';
                innerM += "<td width=90%><div class='STrChOChampRule'>";

                innerM += (rule.advancedrule ? 'Advanced Rule:<br>' : 'Simple Rule:<br>');

                innerM += " Type: " + rule.type;
                innerM += " Faction: " + rule.faction;

                for (ii = 0; ii < rule.conditions.length; ii++)
                {
                    var condition = rule.conditions[ii];

                    if (ii ==0 )
                        innerM += "<br> Item";
                    else
                        innerM += "<br> <u>and</u>";

                    if (condition.mustHave != "false")
                        innerM += " must have ";
                    else
                        innerM += " must NOT have ";

                    innerM += condition.number + "x ";
                    innerM += condition.effect + " ";

                    if (condition.buffType == "b")
                        innerM += "buff ";
                    else if (condition.buffType == "d")
                        innerM += "debuff ";
                    else
                        innerM += "buff or debuff ";

                    innerM += " in slot(s): ";

                    for (j = 0; j < condition.slots.length; j++)
                    {
                        if (condition.slots[j] ) innerM += (j+1) + " ";
                    }

                }
                innerM += '</div></td>';
                innerM += '<td width=20% align=center>';
                innerM += '<input id=STrChOChampEditRule' + i + ' type=button class=STrChOButton value="Edit"><br>';
                innerM += '<input id=STrChOChampDelRule' + i + ' type=button class=STrChOButton value="X">';
                innerM += '</td>';
                innerM += '</tr>';
            }
            return innerM;
        }

        var rd = document.getElementById('STrChOChampRuleDisplay');
        var sortType = document.getElementById('STrChOChampSalvageSortCard').value;

        if (sortType != "0") {
            var sortedDataSet = [];
            for (var k = 0; k < STrChOChampSalvageData.ruleSet.length; k++) {
                if (sortType == STrChOChampSalvageData.ruleSet[k].type) {
                    sortedDataSet.unshift(STrChOChampSalvageData.ruleSet[k]);
                }else {
                    sortedDataSet.push(STrChOChampSalvageData.ruleSet[k]);
                }
            }
            rd.innerHTML = '<table width=100%>' + innerRuleDisplay(sortedDataSet);
            for (var j=0; j < sortedDataSet.length; j++)
            {
                document.getElementById('STrChOChampDelRule' +j).v1 = j;
                document.getElementById('STrChOChampEditRule' +j).v1 = j;
                document.getElementById('STrChOChampDelRule' +j).addEventListener ('click', function() { t.deleteRule(this.v1, sortedDataSet);}, false);
                document.getElementById('STrChOChampEditRule' +j).addEventListener ('click', function() { t.editRule(this.v1, sortedDataSet);}, false);
            }
        } else {
            rd.innerHTML = '<TABLE  width=100%>' + innerRuleDisplay(STrChOChampSalvageData.ruleSet);
            for (var j=0; j < STrChOChampSalvageData.ruleSet.length; j++)
            {
                document.getElementById('STrChOChampDelRule' +j).v1 = j;
                document.getElementById('STrChOChampEditRule' +j).v1 = j;
                document.getElementById('STrChOChampDelRule' +j).addEventListener ('click', function() { t.deleteRule(this.v1, STrChOChampSalvageData.ruleSet);}, false);
                document.getElementById('STrChOChampEditRule' +j).addEventListener ('click', function() { t.editRule(this.v1, STrChOChampSalvageData.ruleSet);}, false);
            }
        }


    },

    editRule : function(ruleIndex, sortedData)
    {
        var t = Tabs.champSalvager;
        var rule = sortedData[ruleIndex];

        var divExpander = null;

        if (rule.advancedrule)
            divExpander = document.getElementById('STrChOChampAdvancedRule');
        else
            divExpander = document.getElementById('STrChOChampSimpleRule');

        divExpander.click();
        if (divExpander.childNodes[0].src == STrChORightArrow) divExpander.click();

        if (rule.advancedrule) {
            document.getElementById('STrChOChampFactionTypeAdvanced').value = rule.faction;
            document.getElementById('STrChOChampCardTypeAdvanced').value = rule.type;
            t.clearAdvancedStats();
            if (rule.type == 'any')
                t.setAdvancedStatsToAny();
            else
                t.filterAdvancedStats(rule.type);

            for (row = 0; row < rule.conditions.length; row++) {
                var condition = rule.conditions[row];
                var slotNumber = 0;
                for (s = 0; s < condition.slots.length; s++) {
                    if (condition.slots[s]) slotNumber = s+1;
                }
                var cell = document.getElementById('STrChOChampRow' + slotNumber + 'Advanced');
                var STrChOEffect = condition.effect;
                if (condition.buffType == 'd') STrChOEffect += ' Debuff';
                cell.value = STrChOEffect;
            }

        } else {
            document.getElementById('STrChOChampFactionType').value = rule.faction;
            document.getElementById('STrChOChampCardType').value = rule.type;
            var STrChOChampConditionTable = document.getElementById('STrChOChampConditionTable');
            while (STrChOChampConditionTable.rows.length > 1) STrChOChampConditionTable.deleteRow(0);
            for (row = 0; row < rule.conditions.length; row++) {
                var condition = rule.conditions[row];
                t.createRow();
                STrChOChampConditionTable = document.getElementById('STrChOChampConditionTable');
                STrChOChampConditionTable.rows[row].cells[0].children[0].value = condition.mustHave;
                STrChOChampConditionTable.rows[row].cells[1].children[0].value = condition.number;
                STrChOChampConditionTable.rows[row].cells[2].children[0].value = condition.effect;
                STrChOChampConditionTable.rows[row].cells[3].children[0].value = condition.buffType;
                var slotCells = STrChOChampConditionTable.rows[row].cells[4];
                for (s = 0; s < condition.slots.length; s++) {
                    if (condition.slots[s])
                        slotCells.children[s].checked = true;
                    else
                        slotCells.children[s].checked = false;
                }
            }
        }
        t.deleteRule(ruleIndex, sortedData);
    },

    // delete a rule from the ruleset
    deleteRule : function(ruleIndex, sortedData)
    {
        var t = Tabs.champSalvager;
        sortedData.splice(ruleIndex,1);
        var newDataSet = [];
        for (var i = 0; i < STrChOChampSalvageData.ruleSet.length; i++) {
            for (var i2 = 0; i2 < sortedData.length; i2++) {
                if (STrChOChampSalvageData.ruleSet[i] == sortedData[i2]) {
                    newDataSet.push(STrChOChampSalvageData.ruleSet[i]);
                    break;
                }
            }
        }
        STrChOChampSalvageData.ruleSet = newDataSet;
        SAVESTrChOChampSalvageData();
        t.buildChampRuleDisplay();
    },

    togglePower: function(obj){
        var t = Tabs.champSalvager;

        if (STrChOChampSalvageData.active) {
            var btn = document.getElementById('STrChOChampSalvagerPower');
            STrChOChampSalvageData.active = false;
            btn.value = "Salvager = OFF";
            clearInterval(t.sTimer);
            clearInterval(t.delTimer);
            t.delItems = [];
            t.deleting = false;
        } else {
            STrChOChampSalvageData.active = true;
            var btn = document.getElementById('STrChOChampSalvagerPower');
            btn.value = "Salvager = ON";
            t.doSalvage();
            t.start();
        }
        SAVESTrChOChampSalvageData();
    },

    readAdvancedRows: function () {
        var t = Tabs.champSalvager;
        var cType = document.getElementById('STrChOChampCardTypeAdvanced').value;
        var faction = document.getElementById('STrChOChampFactionTypeAdvanced').value;
        var row1 = document.getElementById("STrChOChampRow1Advanced");
        var row2 = document.getElementById("STrChOChampRow2Advanced");
        var row3 = document.getElementById("STrChOChampRow3Advanced");
        var row4 = document.getElementById("STrChOChampRow4Advanced");
        var row5 = document.getElementById("STrChOChampRow5Advanced");
        var conditions = [];
        for (var i = 1; i < STrChOQualityCount; i++) {
            var row = document.getElementById("STrChOChampRow" + i + "Advanced");
            if (row.selectedIndex == 0) continue;
            var slots = [];
            for (var slotChecker = 1; slotChecker < STrChOQualityCount; slotChecker++) {
                slots.push(slotChecker==i);
            }
            var effectName = row.options[row.selectedIndex].value;
            var buffDebuff = "b";
            if (effectName.indexOf(" Debuff") != -1) buffDebuff = "d";
            var effectName = effectName.split(" Debuff")[0];
            var c = new ChampCondition(true, 1, effectName, buffDebuff, slots);
            conditions.push(c);
        }
        if ( conditions.length > 0 ) {
            var rule1 = new ChampRule(cType, faction, conditions, true);
            t.addRule(rule1);
        }
    },

    readRows : function()
    {
        var t = Tabs.champSalvager;
        var table = document.getElementById('STrChOChampConditionTable');
        var rowCount = table.rows.length;

        var cType = document.getElementById('STrChOChampCardType').value;
        var faction = document.getElementById('STrChOChampFactionType').value;

        var conditions = [];
        for (i=0; i < table.rows.length; i++)
        {
            var row = table.rows[i];
            if (row.id)
            {
                var s1 = document.getElementById(row.id + "ChampsSel1");
                var s2 = document.getElementById(row.id + "ChampsSel2");
                var s3 = document.getElementById(row.id + "ChampsSel3");
                var s4 = document.getElementById(row.id + "ChampsSel4");

                var slots = [];
                for (j =1; j <= 5; j++)
                {
                    var ch = document.getElementById(row.id + "ChampsSlot" + j);
                    slots.push(ch.checked);
                }

                var c = new ChampCondition(s1.value, s2.value, s3.value, s4.value, slots );
                conditions.push(c);
            }
        }
        var rule1 = new ChampRule(cType, faction, conditions, false);
        t.addRule(rule1);
    },

    removeRow : function(row)
    {
        var table = document.getElementById('STrChOChampConditionTable');

        for (i=0; i < table.rows.length  ; i++ )
        {
            if (table.rows[i] == row)
            {
                table.deleteRow(i);
                break;
            }
        }
    },

    // add a new rule
    addRule : function(rule) {
        STrChOChampSalvageData.ruleSet.unshift(rule);
        SAVESTrChOChampSalvageData();
    },


    start : function() {
        var t = Tabs.champSalvager;
        if(STrChOChampSalvageData.active) t.sTimer = setInterval(t.doSalvage, 1*60*1000);
    },

        // do the actual discard of champion items
    doSalvage : function() {
        var t = Tabs.champSalvager;

        if(!STrChOChampSalvageData.active) {
            t.deleting = false;
            return;
        }

        if (t.deleting == true) return;

        t.deleting = true;
        t.setStatus('Salvaging items');

        t.delItems = t.buildList(false);


        if (t.delItems.length > 0) {
            // upgrade items from +0 to +1 first
            t.upgradeAndDelete();
        } else {
            // give enough time for the last delete to finish
            setTimeout( function () {
                t.deleting = false;
                t.setStatus('No items to salvage.  Waiting for next cycle.');
            }, 3000);
        }
    },

    // Create the list of items to delete.
    // If 'test' is set to true, then broken/equipted items are included.
    buildList : function(test){
        var t = Tabs.champSalvager;

        var champSaveNum = STrChOChampSalvageData.champSaveNum;
        var countItem = 0;
        var retList = [];

        for (k in uW.kocChampionItems) {
            var champ_item = uW.kocChampionItems[k];
            countItem++;
            if (champ_item.level !=0) continue; // ignore these things
            if (champ_item.unique > 0) continue;
            // in test mode, include these items
            // These items are at risk if they are repaired or unequiped.
            if (test != true)
                if (champ_item.equippedTo) continue;
            // keep the first X items
            if ( countItem <= champSaveNum) continue;
            // keep things w/ at least minQuality
            if (champ_item.rarity >= STrChOChampSalvageData.minQuality) continue;
            // check the rules
            if (t.applyRules(champ_item.equipmentId)) {
                if (STrChOChampSalvageData.upgradeAutoFind) {
                    var found = false;
                    for (var i = 0; i < STrChOChampQueueData.list.length; i++) {
                        var qItem = STrChOChampQueueData.list[i];
                        if (qItem.item != champ_item.equipmentId) continue;
                        found = true;
                        break;
                    }
                    if (!found) {
                        ActionLog('Item: ' + champ_item.name + ' found and added to auto upgrade');
                        Tabs.champUpgrader.addUpgradeItem(champ_item.equipmentId);
                    }
                }
                continue;
            }

            // passes all tests
            retList.push(champ_item.equipmentId);
        }
        return retList;
    },

    // put out a status message on the chSavlStatus div
    setStatus : function(msg) { document.getElementById('STrChOChampSalvageStatus').innerHTML = msg; },

    // returns true if the item should be saved and not salvaged
    applyRules : function(id) {
        var t = Tabs.champSalvager;
        for (r in STrChOChampSalvageData.ruleSet) {
            var rule = STrChOChampSalvageData.ruleSet[r];
            if ( rule.ChampApplyRule(id)) return true;
        }
        return false;
    },

    upgradeAndDelete : function () {  // update items to +1 before deleting
        var t = Tabs.champSalvager;
        if(!STrChOChampSalvageData.active || t.delItems.length == 0) {
            t.deleting = false;
            return;
        }
        var id = +t.delItems[0];
        t.delTimer = setTimeout( function () {t.doDelete(id)}, 4000);  // delete the item
    },

    removeItem : function (id, cityId, numStones) {
        var item = uW.kocChampionItems[id];
        if (!item) return;
        var c = +(Seed.resources["city" + cityId]["rec5"][0]);
        delete uW.kocChampionItems[id];
    },

    doDelete : function(id) {

        var t = Tabs.champSalvager;
        if(!STrChOChampSalvageData.active || !t.deleting) {
            t.deleting = false;
            return;
        }

        var item = uW.kocChampionItems[id];
        if (item) t.setStatus('Salvaging ' + item.name);

        SalvageChampItem(id);
    },

}

Tabs.champRepair = {
	tabOrder: 202,
	tabLabel: 'REPAIR',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL REPAIR',
    repairId: 0,
    repairEnd: 0,
    timerH: null,
    clearTimerH: null,

	init: function (div) {
		var t = Tabs.champRepair;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '<div class=STrChOSaveSettings id=STrChOChampRepairSaveSettings title="Save Repair Settings"></div><div class=STrChOLoadSettings id=STrChOChampRepairLoadSettings title="Load Repair Settings"></div></div>';


        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
		m += '<div>';

        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        if (STrChOChampRepairData.active) {
            m += '<td width=50%><input id=STrChOChampRepairPower type=button class=STrChOButton value="Repair = ON"></td>';
        } else {
            m += '<td width=50%><input id=STrChOChampRepairPower type=button class=STrChOButton value="Repair = OFF"></td>';
        }
        m += '<td width=50%><div class=divNoWrap align=center id=STrChOChampRepairAetherDisplay></div></td>';
        m += '</tr>';
        m += '<tr><td colspan=2><hr class=STrChOHRCenter></td></tr>';
        m += '<tr><td colspan=2><div class=indent5 id=STrChOChampRepairStatus><br></div></td></tr>';
        m += '<tr><td colspan=2><div class=indent5 id=STrChOChampRepairLastResult><br></div></td></tr>';
        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SPEED UPS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairHourglassLevelSpecific ' + (STrChOChampRepairData.hourglassLevelSpecific ? "CHECKED" : "") + '>Only use hourglass for levels ';
        m += '<select class=STrChOSelect  id=STrChOChampRepairHourglassLevel>';
        for (lvl = 1; lvl < STrChOMaxChampLevel; lvl++) m += '<option value="' + lvl + '" ' + (STrChOChampRepairData.hourglassLevel == lvl ? 'SELECTED' : '') + '>+' + lvl + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairHourglassQualitySpecific ' + (STrChOChampRepairData.hourglassQualitySpecific ? "CHECKED" : "") + '>Only use hourglass for qualities ';
        m += '<select class=STrChOSelect id=STrChOChampRepairHourglassQuality>';
        for (qual = 1; qual <= STrChOMaxChampQuality-1; qual++) m += '<option value="' + qual + '" ' + (STrChOChampRepairData.hourglassQuality == qual ? 'SELECTED' : '') + '>' + champCardQualities[qual].capitalizeFirstLetter() + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[1] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseSH ' + (STrChOChampRepairData.useSH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[1] + ' (<div class=divNoWrap id=STrChOChampRepairUseSHLabel><font' + (uW.ksoItems[1].count < 100 ? ' color=red>' : '>') + uW.ksoItems[1].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[2] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseKH ' + (STrChOChampRepairData.useKH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[2] + ' (<div class=divNoWrap id=STrChOChampRepairUseKHLabel><font' + (uW.ksoItems[2].count < 100 ? ' color=red>' : '>') + uW.ksoItems[2].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[3] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseGH ' + (STrChOChampRepairData.useGH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[3] + ' (<div class=divNoWrap id=STrChOChampRepairUseGHLabel><font' + (uW.ksoItems[3].count < 100 ? ' color=red>' : '>') + uW.ksoItems[3].count + '</font></div>)</div></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[4] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseMH ' + (STrChOChampRepairData.useMH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[4] + ' (<div class=divNoWrap id=STrChOChampRepairUseMHLabel><font' + (uW.ksoItems[4].count < 100 ? ' color=red>' : '>') + uW.ksoItems[4].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[5] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseAH ' + (STrChOChampRepairData.useAH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[5] + ' (<div class=divNoWrap id=STrChOChampRepairUseAHLabel><font' + (uW.ksoItems[5].count < 100 ? ' color=red>' : '>') + uW.ksoItems[5].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[6] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseWH ' + (STrChOChampRepairData.useWH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[6] + ' (<div class=divNoWrap id=STrChOChampRepairUseWHLabel><font' + (uW.ksoItems[6].count < 100 ? ' color=red>' : '>') + uW.ksoItems[6].count + '</font></div>)</div></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td title="' + STrChOHourGlassTDLabel[7] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseDH ' + (STrChOChampRepairData.useDH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[7] + ' (<div class=divNoWrap id=STrChOChampRepairUseDHLabel><font' + (uW.ksoItems[7].count < 100 ? ' color=red>' : '>') + uW.ksoItems[7].count + '</font></div>)</div></td>';
        m += '<td title="' + STrChOHourGlassTDLabel[8] + '"><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairUseEH ' + (STrChOChampRepairData.useEH ? 'CHECKED' : '') + '><div class=divNoWrap>' + STrChOHourGlassName[8] + ' (<div class=divNoWrap id=STrChOChampRepairUseEHLabel><font' + (uW.ksoItems[8].count < 100 ? ' color=red>' : '>') + uW.ksoItems[8].count + '</font></div>)</div></td>';
        m += '<td/>';
        m += '</tr>';
        m += '<tr>';
        m += '<td colspan=3><input class=STrChOCheckbox type=checkbox id=STrChOChampRepairOverrideSpeedUps ' + (STrChOChampRepairData.overrideSpeedUp ? "CHECKED" : "") + '>Override hourglasses by using ';
        m += '<select class=STrChOSelect  id=STrChOChampRepairSpeedUp>';
        m += '<option value=0>None</option>';
        for (gls in STrChOHourGlassName) {
            m += '<option value=' + gls + ' ' + (STrChOChampRepairData.useSpeedUp == gls ? 'SELECTED' : '') + '>' + STrChOHourGlassName[gls] + '</option>';
        }
        m += '</select> every time</td>';
        m += '</tr>';
        m += '</table>';
        m += '</div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;REPAIR ITEMS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';

        m += '<tr><td>Queue By Level: <select class=STrChOSelect id=STrChOChampRepairByLevel>';
        for (i = 1; i < STrChOMaxChampLevel; i++) m += '<option value=' + i + '>+' + i + '</option>';
        m += '</select>&nbsp;<input id=STrChOChampRepairByLevelAdd class=STrChOButton type=button value="Add"/></td></tr>';


        m += '<tr><td>Queue By Preset Tag: <select class=STrChOSelect id=STrChOChampRepairPresetTagList>';
        var presetsList = "";
        if (STrChOMaxChampions != 0)  {
            for (var i = 1; i < STrChOMaxChampions + 1; i++) {
                presetsList += '<option value="' + i + '">' + i + ' (' + STrChOChampPresetData.presetNames[i-1] + ')</option>';
            }
        }
        m += presetsList;
        m += "</select>&nbsp;<input id=STrChOChampRepairPresetTag class=STrChOButton type=button value='Add'/></td></tr>";

        m += '<tr><td><div style="max-width:90%;">Item: <select class=STrChOSelect style="white-space:nowrap;display:inline-block;max-width: 200px;" id=STrChOChampRepairList>';
        m += '</select><input id=STrChOChampRepairAdd type=button class=STrChOButton value="Add"/>&nbsp;<input id=STrChOChampRepairAddAll class=STrChOButton type=button value="Add All">&nbsp;<input id=STrChOChampRepairRefresh class=STrChOButton type=button value="Refresh List"></div></td></tr>';

        m += '</table>';
        m += '</div>';


        m += '<div class=STrChOHeader>&nbsp;REPAIR LIST&nbsp;</div>';

        m += '<div>';
        m += '<table class=STrChOSectionTable>';

        m += '<tr><td colspan=2>';
        m += '<div id=STrChOChampRepairQScroll style="position: static; width: 100%; height: 350px; overflow-x: auto; overflow-y: auto;">';
        m += '<div id=STrChOChampRepairQDiv></div>';
        m += '</div>';
        m += '</td></tr>';

        m += '<tr align=center><td><div><input style="float: left;" id=STrChOChampRepairClear class=STrChOButton type=button value="Clear Queue"/></div></td><td><div><input style="float: right;" id=STrChOChampRepairClearF class=STrChOButton type=button value="Clear Repaired"/></div></td></tr>';

        m += '</table>';
        m += '</div>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOChampRepairSaveSettings').addEventListener('click', function () {
            SaveSettingsToFile(STrChOChampRepairData);
        }, false);
        document.getElementById('STrChOChampRepairLoadSettings').addEventListener('click', function () {
            var loader = document.getElementById('STrChOSettingsFile');
            loader.addEventListener('change', function () {
                LoadSettingsFromFile(STrChOChampRepairData, Tabs.champRepair);
            }, false);
            loader.click();
        }, false);

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        t.refreshAetherDisplay();

        document.getElementById('STrChOChampRepairUseWH').addEventListener('change', function () {
            STrChOChampRepairData.useWH = document.getElementById('STrChOChampRepairUseWH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.useWH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairUseDH').addEventListener('change', function () {
            STrChOChampRepairData.useDH = document.getElementById('STrChOChampRepairUseDH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairUseDH.useDH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairUseEH').addEventListener('change', function () {
            STrChOChampRepairData.useEH = document.getElementById('STrChOChampRepairUseEH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.useEH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairUseSH').addEventListener('change', function () {
            STrChOChampRepairData.useSH = document.getElementById('STrChOChampRepairUseSH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.useSH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairUseKH').addEventListener('change', function () {
            STrChOChampRepairData.useKH = document.getElementById('STrChOChampRepairUseKH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.useKH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairUseGH').addEventListener('change', function () {
            STrChOChampRepairData.useGH = document.getElementById('STrChOChampRepairUseGH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.useGH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairUseMH').addEventListener('change', function () {
            STrChOChampRepairData.useMH = document.getElementById('STrChOChampRepairUseMH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.useMH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairUseAH').addEventListener('change', function () {
            STrChOChampRepairData.useAH = document.getElementById('STrChOChampRepairUseAH').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.useAH) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairHourglassLevelSpecific').addEventListener('change', function () {
            STrChOChampRepairData.hourglassLevelSpecific = document.getElementById('STrChOChampRepairHourglassLevelSpecific').checked;
            SAVESTrChOChampRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairHourglassQualitySpecific').addEventListener('change', function () {
            STrChOChampRepairData.hourglassQualitySpecific = document.getElementById('STrChOChampRepairHourglassQualitySpecific').checked;
            SAVESTrChOChampRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairOverrideSpeedUps').addEventListener('change', function () {
            STrChOChampRepairData.overrideSpeedUp = document.getElementById('STrChOChampRepairOverrideSpeedUps').checked;
            SAVESTrChOChampRepairData();
            if (STrChOChampRepairData.overrideSpeedUp) t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairSpeedUp').addEventListener('change', function () {
            STrChOChampRepairData.useSpeedUp = document.getElementById('STrChOChampRepairSpeedUp').value;
            SAVESTrChOChampRepairData();
        }, false);

        document.getElementById('STrChOChampRepairHourglassLevel').addEventListener('change', function () {
            STrChOChampRepairData.hourglassLevel = document.getElementById('STrChOChampRepairHourglassLevel').value;
            SAVESTrChOChampRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairHourglassQuality').addEventListener('change', function () {
            STrChOChampRepairData.hourglassQuality = document.getElementById('STrChOChampRepairHourglassQuality').value;
            SAVESTrChOChampRepairData();
            t.doAction();
        }, false);

        document.getElementById('STrChOChampRepairPower').addEventListener('click', function () {
            t.togglePower(this);
        }, false);

        document.getElementById('STrChOChampRepairByLevelAdd').addEventListener('click', function () {
            var t = Tabs.champRepair;
            var level = document.getElementById('STrChOChampRepairByLevel').value;
            for (chId in uW.kocChampionItems) {
                var champItem = uW.kocChampionItems[chId];
                if (champItem == null || !champItem) continue;
                if (!(champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE)) continue;
                if (champItem.level != level) continue;
                t.addQueue(chId);
            }
        }, false);

        document.getElementById('STrChOChampRepairPresetTag').addEventListener('click', function () {
            var t = Tabs.champRepair;
            var presetTagNum = document.getElementById('STrChOChampRepairPresetTagList').value;
            var presetTag = getChampPresetObject(parseInt(presetTagNum));
            for (var ptId in presetTag) {
                var champItem = uW.kocChampionItems[ptId];
                if (champItem == null || !champItem) continue;
                if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) t.addQueue(ptId);
            }
        }, false);

        document.getElementById('STrChOChampRepairClear').addEventListener('click', function () {
            t.deleteQueue();
        }, false);

        document.getElementById('STrChOChampRepairClearF').addEventListener('click', function () {
            var temp = [];
            while (STrChOChampRepairData.items.length > 0) {
                var chId = STrChOChampRepairData.items.pop();
                var champItem = uW.kocChampionItems[chId];
                if (champItem == null || !champItem) continue;
                if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) temp.push(chId);
            }
            while (temp.length > 0) STrChOChampRepairData.items.push(temp.pop());
            STrChOChampRepairData.index = 0
            SAVESTrChOChampRepairData();
            t.populateChampRepairListBox();
            t.buildChampRepairDisplay();
        }, false);

        document.getElementById('STrChOChampRepairAdd').addEventListener('click', function () {
            t.addQueue();
        }, false);

        document.getElementById('STrChOChampRepairAddAll').addEventListener('click', function () {
            t.addAllQueue();
        }, false);

        document.getElementById('STrChOChampRepairRefresh').addEventListener('click', function () {
            t.populateChampRepairListBox();
        }, false);

        if (STrChOChampRepairData.active)
            t.setStatus('Loading...');
        else
            t.setStatus('Powered Off');

        var d = 2 + Math.random() * 8;

        if (Seed.queue_champion == null) {
            for (chId in uW.kocChampionItems) {
                var champItem = uW.kocChampionItems[chId];
                if (champItem.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE || champItem.status == CM.CHAMPION.STATUS_REPAIRING_UPGRADE) {
                    Seed.queue_champion = {};
                    Seed.queue_champion.start = parseInt(champItem.start);
                    Seed.queue_champion.end = parseInt(champItem.eta);
                    Seed.queue_champion.itemId = champItem.equipmentId;
                    break;
                }
            }
        }

        if (Seed.queue_champion != null && Seed.queue_champion.end != null) {
            var repairTimeLeft = Seed.queue_champion.end - unixTime();
            t.repairEnd = Seed.queue_champion.end;
            t.repairId = Seed.queue_champion.itemId;
            var n = new Date(t.repairEnd * 1000);

            t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + uW.kocChampionItems[t.repairId].name);

            if (STrChOChampRepairData.useAH || STrChOChampRepairData.useGH || STrChOChampRepairData.useKH || STrChOChampRepairData.useMH || STrChOChampRepairData.useSH || STrChOChampRepairData.useWH || STrChOChampRepairData.useDH || STrChOChampRepairData.useEH || (STrChOChampRepairData.overrideSpeedUp && STrChOChampRepairData.useSpeedUp > 0)) {
                var champItem = uW.kocChampionItems[t.repairId];
                var chQuality = champItem.rarity;
                var chLevel = champItem.level;
                var useThoseSpeedups = true;
                if (STrChOChampRepairData.hourglassQualitySpecific && chQuality < STrChOChampRepairData.hourglassQuality) useThoseSpeedups = false;
                if (STrChOChampRepairData.hourglassLevelSpecific && chLevel < STrChOChampRepairData.hourglassLevel) useThoseSpeedups = false;
                if (STrChOChampRepairData.overrideSpeedUp) useThoseSpeedups = true;
                if (useThoseSpeedups) {
                    t.doingSpeedup = true;
                    setTimeout(function () { t.doSpeedup(); }, 2000);
                }
            }

            setTimeout(t.clearRepair, (repairTimeLeft + 1) * 5000);
            if (repairTimeLeft > 0) d += repairTimeLeft;
        }

        t.populateChampRepairListBox();
        t.buildChampRepairDisplay();


        if (t.timerH == null) t.timerH = setTimeout(t.doAction, d * 1000);

    },

	hide: function () {},

    refreshAetherDisplay : function () {
        document.getElementById('STrChOChampRepairAetherDisplay').innerHTML = displayCityAstone();
    },

	show: function () {
		var t = Tabs.champRepair;
        t.refreshAetherDisplay();
        t.populateChampRepairListBox();
        t.buildChampRepairDisplay();
	},

    deleteQueue: function () {
        var t = Tabs.champRepair
        STrChOChampRepairData.items = [];
        SAVESTrChOChampRepairData();
        t.populateChampRepairListBox();
        t.buildChampRepairDisplay();
    },

    doSpeedup: function () {
        var t = Tabs.champRepair;

        var endTime = t.repairEnd;
        var startTime = unixTime();
        var secondsForRepair = endTime - startTime;
        var divId = "";

        t.speedup = 0;

        if (secondsForRepair > 0 && STrChOChampRepairData.overrideSpeedUp && STrChOChampRepairData.useSpeedUp > 0) {
            t.speedup = STrChOChampRepairData.useSpeedUp;
        } else {
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.day25 && STrChOChampRepairData.useAH && uW.ksoItems[8].count > 0) { t.speedup = 8; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour24 && STrChOChampRepairData.useAH && uW.ksoItems[7].count > 0) { t.speedup = 7; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour15 && STrChOChampRepairData.useAH && uW.ksoItems[6].count > 0) { t.speedup = 6; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour8 && STrChOChampRepairData.useAH && uW.ksoItems[5].count > 0) { t.speedup = 5; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && STrChOChampRepairData.useMH && uW.ksoItems[4].count > 0) { t.speedup = 4; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && STrChOChampRepairData.useGH && uW.ksoItems[3].count > 0) { t.speedup = 3; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && STrChOChampRepairData.useKH && uW.ksoItems[2].count > 0) { t.speedup = 2; }
            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && STrChOChampRepairData.useSH && uW.ksoItems[1].count > 0) { t.speedup = 1; }
        }

        switch (t.speedup) {
            case "1":
            case 1:
                secondsForRepair -= HOURGLASSES_TIME.minute1;
                divId = 'STrChOChampRepairUseSHLabel';
                break;
            case "2":
            case 2:
                secondsForRepair -= HOURGLASSES_TIME.minute15;
                divId = 'STrChOChampRepairUseKHLabel';
                break;
            case "3":
            case 3:
                secondsForRepair -= HOURGLASSES_TIME.hour1;
                divId = 'STrChOChampRepairUseGHLabel';
                break;
            case "4":
            case 4:
                secondsForRepair -= HOURGLASSES_TIME.hour25;
                divId = 'STrChOChampRepairUseMHLabel';
                break;
            case "5":
            case 5:
                secondsForRepair -= HOURGLASSES_TIME.hour8;
                divId = 'STrChOChampRepairUseAHLabel';
                break;
            case "6":
            case 6:
                secondsForRepair -= HOURGLASSES_TIME.hour15;
                divId = 'STrChOChampRepairUseWHLabel';
                break;
            case "7":
            case 7:
                secondsForRepair -= HOURGLASSES_TIME.hour24;
                divId = 'STrChOChampRepairUseDHLabel';
                break;
            case "8":
            case 8:
                secondsForRepair -= HOURGLASSES_TIME.day25;
                divId = 'STrChOChampRepairUseEHLabel';
                break;
        }

        if (t.speedup != 0) {
            t.setResult('Used ' + uW.ksoItems[t.speedup].name);
            var divCount = uW.ksoItems[t.speedup].count - 1;
            var divSpeedups = document.getElementById(divId);
            divSpeedups.innerHTML = divCount;
            uW.modal_speedup_apply("champion", t.speedup, t.repairId);

            if (secondsForRepair <= 0) {
                secondsForRepair = 0;
                endTime = startTime;
                t.clearTimerH = setTimeout(t.clearRepair, 1000);
            } else {
                endTime = unixTime() + secondsForRepair;
                t.repairEnd = endTime;
                var n = new Date(t.repairEnd * 1000);
                var champItem = uW.kocChampionItems[t.repairId];
                if (champItem) {
                    t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + champItem.name);
                    t.clearTimerH = setTimeout(t.clearRepair, secondsForRepair * 1000);
                }
            }
            t.buildChampRepairDisplay();
            t.repairEnd = endTime;
            setTimeout(function () { t.doSpeedup(); }, 1000);
        }
    },

    selectNext: function () {

        var l = STrChOChampRepairData.items.length;
        for (i = 0; i < l; i++) {

            var champItem = uW.kocChampionItems[STrChOChampRepairData.items[i]];
            if (champItem == null || !champItem) continue;
            if ((champItem != null) && (champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE || champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE)) {
                STrChOChampRepairData.index = i;
                SAVESTrChOChampRepairData();
                return;
            }
        }

        // if we get here, the queue is complete
        STrChOChampRepairData.index = -1;

        SAVESTrChOChampRepairData();
    },

    doAction: function () {
        var t = Tabs.champRepair;
        t.populateChampRepairListBox();

        if (STrChOChampUpgradeData.active) {
            t.setStatus('Waiting for upgrade tab to finish...');
            if (STrChOChampRepairData.active) t.togglePower();
            return;
        }

        if (!STrChOChampRepairData.active) {
            t.setStatus("Powered Off");
            return;
        } else {
            var retryTime = STrChOGeneralOptions.retryInterval;

            try {  // check if repair is done
                var ti = t.clearRepair();
                if (ti <= 0) {  // repair is done

                    t.selectNext();

                    if (STrChOChampRepairData.index < 0) {
                        t.setStatus("Reached end of queue.")
                        t.setResult("");
                        SAVESTrChOChampRepairData();
                    } else {
                        var champItem = uW.kocChampionItems[STrChOChampRepairData.items[STrChOChampRepairData.index]];
                        if (champItem) {
                            t.repairId = champItem.equipmentId;
                            t.doRepair(champItem.equipmentId);
                        }
                    }

                } else {  // come back after repair is complete
                    retryTime = ti + 5;
                    var n = new Date(t.repairEnd * 1000);
                    t.setStatus("Waiting until " + n.toLocaleTimeString() + " for repair to complete.  Item: " + uW.kocChampionItems[t.repairId].name);
                    if (STrChOChampRepairData.useSH || STrChOChampRepairData.useKH || STrChOChampRepairData.useGH || STrChOChampRepairData.useMH || STrChOChampRepairData.useAH || STrChOChampRepairData.useWH || STrChOChampRepairData.useDH || STrChOChampRepairData.useEH || (STrChOChampRepairData.overrideSpeedUp && STrChOChampRepairData.useSpeedUp > 0)) {
                        var champItem = uW.kocChampionItems[t.repairId];
                        var STrChOChampQuality = champItem.rarity;
                        var STrChOChampLevel = champItem.level;
                        var useThoseSpeedups = true;
                        if (STrChOChampRepairData.hourglassQualitySpecific && STrChOChampQuality < STrChOChampRepairData.hourglassQuality) useThoseSpeedups = false;
                        if (STrChOChampRepairData.hourglassLevelSpecific && STrChOChampLevel < STrChOChampRepairData.hourglassLevel) useThoseSpeedups = false;
                        if (STrChOChampRepairData.overrideSpeedUp) useThoseSpeedups = true;
                        if (useThoseSpeedups) {
                            t.doingSpeedup = true;
                            setTimeout(function () { t.doSpeedup(); }, 2000);
                        }
                        retryTime = 1;
                    }
                }
            } catch (e) {
            }
            // recycle
            clearTimeout(t.timerH);
            t.timerH = setTimeout(t.doAction, retryTime * 1000);
            t.buildChampRepairDisplay();
        }
    },

    addQueue: function (Id) {
        var t = Tabs.champRepair;

        if (Id == null) {
            var chId = document.getElementById('STrChOChampRepairList').value;
        } else {
            var chId = Id;
        }

        if (chId == 0) return;

        var item_count = STrChOChampRepairData.items.length;

        if (item_count > 0) {
            for (var item_index = 0; item_index < item_count; item_index++) {
                if (chId == STrChOChampRepairData.items[item_index]) return;
            }
        }

        STrChOChampRepairData.items.push(chId);
        SAVESTrChOChampRepairData();
        t.populateChampRepairListBox();
        t.buildChampRepairDisplay();
    },

    addAllQueue: function () {
        var t = Tabs.champRepair;

        for (chId in uW.kocChampionItems) {
            var champItem = uW.kocChampionItems[chId];
            if (champItem == null || !champItem) continue;
            if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                t.addQueue(chId);
            }
        }

    },

    populateChampRepairListBox: function () {
        var repairList = document.getElementById('STrChOChampRepairList');
        var m = '<option value=0>--Items--</option>';

        var item_count = STrChOChampRepairData.items.length;

        for (chId in uW.kocChampionItems) {
            var champItem = uW.kocChampionItems[chId];
            if (champItem == null || !champItem) continue;
            if (champItem.status != CM.CHAMPION.STATUS_BROKEN_ENHANCE && champItem.status != CM.CHAMPION.STATUS_BROKEN_UPGRADE) continue; //item not broken, move on

            var foundIt = false;
            for (var item_index = 0; item_index < item_count; item_index++) {
                if (chId == STrChOChampRepairData.items[item_index]) {
                    foundIt = true;
                    break;
                }
            }
            if (!foundIt) {
                var optionText = champItem.name;
                m += '<option value="' + chId + '">' + optionText + '</option>';
            }
        }
        repairList.innerHTML = m;
    },

    deleteRepairItem: function (index) {  // delete an item from the queue
        var t = Tabs.champRepair;
        STrChOChampRepairData.items.splice(index, 1);
        SAVESTrChOChampRepairData();
        t.populateChampRepairListBox();
        t.buildChampRepairDisplay();
    },

    moveRepairUpRow: function (index) {
        if (index < 1) return;
        var t = Tabs.champRepair;
        var q = STrChOChampRepairData.items.splice(index, 1);
        STrChOChampRepairData.items.splice(index - 1, 0, q);

        if (index == STrChOChampRepairData.index)
            STrChOChampRepairData.index--;
        else if (STrChOChampRepairData.index == index - 1)
            STrChOChampRepairData.index++;

        SAVESTrChOChampRepairData();
        t.buildChampRepairDisplay();
    },

    moveRepairDownRow: function (index) {
        if (index > (STrChOChampRepairData.items.length - 2)) return;

        var t = Tabs.champRepair;
        var q = STrChOChampRepairData.items.splice(index, 1);
        STrChOChampRepairData.items.splice(index + 1, 0, q);

        if (i == STrChOChampRepairData.index)
            STrChOChampRepairData.index++;
        else if (STrChOChampRepairData.index == i + 1)
            STrChOChampRepairData.index--;

        SAVESTrChOChampRepairData();
        t.buildChampRepairDisplay();

    },

    setStatus: function (s) { document.getElementById('STrChOChampRepairStatus').innerHTML = "<div>" + s + "</div>"; },

    setResult: function (s) { document.getElementById('STrChOChampRepairLastResult').innerHTML = "<div>" + s + "</div>"; },

    togglePower: function (obj) {
        var t = Tabs.champRepair;

        var STrChOChampRepairPower = document.getElementById('STrChOChampRepairPower');

        if (STrChOChampRepairData.active) {
            STrChOChampRepairData.active = false;
            STrChOChampRepairPower.value = "Repair = OFF";
            t.setStatus("Powered Off");
            t.setResult("");
        } else {
            STrChOChampRepairData.active = true;
            STrChOChampRepairPower.value = "Repair = ON";
            t.setStatus("Power On");
            t.setResult("");
            STrChOChampUpgradeData.active = false;
            SAVESTrChOChampUpgradeData();
            t.doAction();
        }
        if (!STrChOChampRepairData.active) {

        }
        SAVESTrChOChampRepairData();
    },

    clearRepair: function () {
        var t = Tabs.champRepair;
        var timeUntilDone = 0;

        if (t.repairEnd == 0) {
            return timeUntilDone;
        }
        timeUntilDone = t.repairEnd - unixTime();

        if (timeUntilDone <= 0) {
            if (t.repairId != 0 && uW.kocChampionItems[t.repairId] != null) {
                if (uW.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_INACTIVE
                               || uW.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_ACTIVE) {
                    t.setStatus("Repair time complete.");
                    document.getElementById('STrChOChampRepairState' + t.repairId).className = 'STrChOSuccess';
                } else {
                }
                t.repairId = 0;
            }

        }
        return timeUntilDone;
    },

    doRepair: function (rItemId) {
        var t = Tabs.champRepair;
        var params = uW.Object.clone(ajfx);

        if (STrChOChampRepairData.active == false || rItemId == 0 || uW.kocChampionItems[rItemId] == null) return;

        var theItem = uW.kocChampionItems[rItemId];

        params.action = "6";
        params.eid = rItemId;
        params.cityId = uW.currentcityid;
        params.gems = 0;

        new AjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    var item = uW.kocChampionItems[rslt.equipmentId];
                    ActionLog('Starting repair for Champion item ' + item.name);
                    if (!Seed.queue_champion) Seed.queue_champion = {};
                    Seed.queue_champion.itemId = rslt.equipmentId;
                    Seed.queue_champion.start = parseInt(rslt.start);
                    Seed.queue_champion.end = parseInt(rslt.eta);
                    t.repairId = parseInt(rslt.equipmentId);
                    t.repairEnd = rslt.eta;
                    var n = new Date(t.repairEnd * 1000);
                    t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + item.name);
                    var x = rslt.eta - unixTime();
                    t.clearTimerH = setTimeout(t.clearRepair, (x + 1) * 1000);
                    if (item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE)
                        item.status = CM.CHAMPION.STATUS_REPAIRING_ENHANCE;
                    else
                        item.status = CM.CHAMPION.STATUS_REPAIRING_UPGRADE;

                    t.buildChampRepairDisplay();
                }
                else {
                    // regrab the end times in case this is caused by a manual repair
                    if (Seed.queue_champion && Seed.queue_champion.end && Seed.queue_champion.itemId) {
                        t.repairEnd = Seed.queue_champion.end;
                        t.repairId = Seed.queue_champion.itemId;
                    }

                    if (feedback.index("There is one equipment in repairing queue") > 0) return; // item is still be repaired

                    if (rslt.feedback) {
                        t.setStatus(rslt.feedback);
                        uW.kocChampionItems[rItemId].status = CM.CHAMPION.STATUS_INACTIVE;
                        t.clearRepair();
                    }

                }
                return;
            },
            onFailure: function (ttt) {  // this usually means a repair is in progress (such as a manualrepair). Grab the seed data (if possible)
                if (Seed.queue_champion && Seed.queue_champion.end) {
                    t.repairEnd = Seed.queue_champion.end;
                    t.repairId = Seed.queue_champion.itemId;
                }
                return;
            }
        });
        return;
    },

    buildChampRepairDisplay: function () {
        var t = Tabs.champRepair;

        STrChOChampRepairQDiv = document.getElementById('STrChOChampRepairQDiv');

        var m = '<table id=STrChOChampRepair width=100% class=trTabPad>';

        var item_count = STrChOChampRepairData.items.length;

        //TODO
        //var totalRepairTime = t.calcRepairTime();
        //if (totalRepairTime > 0) $("#trRepair").append("<caption><b><i>Total Repair Time (" + item_count + " items): " + repairTimeToText(totalRepairTime) + "</i></b></caption>");

        m += '<tr><th width=10%>Remove</th><th width=5%>Reorder</th><th width=8%>Status</th><th width=25%>Item</th></tr>';

        if (item_count > 0) {
            for (var item_index = 0; item_index < item_count; item_index++) {
                var chId = STrChOChampRepairData.items[item_index];

                if (chId == null) {
                    t.deleteRepairItem(item_index);
                    return;
                }
                var champItem = uW.kocChampionItems[chId];
                if (champItem == null || !champItem) {
                    t.deleteRepairItem(item_index);
                    return;
                }

                m += '<tr>';
                m += '<td align=center><div class=STrChORemove id=STrChOChampRepairRemove' + chId + '></div></td>';
                m += '<td align=center><div class=STrChOUpRow id=STrChOChampRepairUpRow' + chId + '></div><div class=STrChODownRow  id=STrChOChampRepairDownRow' + chId + '></div></td>';
                m += '<td align=center><div id=STrChOChampRepairState' + chId + '></div></td>';
                m += '<td align=center><div id=STrChOChampRepairItem' + chId + '>' + champItem.name + '</div></td>';
                m += '</tr>';
            }
            m += '</table>';

            STrChOChampRepairQDiv.innerHTML = m;

            for (var item_index = 0; item_index < item_count; item_index++) {

                var chId = STrChOChampRepairData.items[item_index];

                var champItem = uW.kocChampionItems[chId];

                if (champItem == null || !champItem) continue;

                document.getElementById('STrChOChampRepairRemove' + chId).setAttribute('v1', item_index);
                document.getElementById('STrChOChampRepairRemove' + chId).addEventListener('click', function () {
                    var qIndex = this.getAttribute('v1');
                    t.deleteRepairItem(qIndex);
                }, false);

                document.getElementById('STrChOChampRepairUpRow' + chId).setAttribute('v1', item_index);
                document.getElementById('STrChOChampRepairUpRow' + chId).addEventListener('click', function () {
                    var qIndex = this.getAttribute('v1');
                    t.moveRepairUpRow(qIndex);
                }, false);

                document.getElementById('STrChOChampRepairDownRow' + chId).setAttribute('v1', item_index);
                document.getElementById('STrChOChampRepairDownRow' + chId).addEventListener('click', function () {
                    var qIndex = this.getAttribute('v1');
                    t.moveRepairDownRow(qIndex);
                }, false);

                var champItem = uW.kocChampionItems[chId];

                if (!champItem || !(champItem.equipmentId)) {
                    document.getElementById('STrChOChampRepairState' + chId).innerHTML = '<div style="text-align:center"> ??</div>';

                } else if (champItem.status == CM.CHAMPION.STATUS_ACTIVE) {
                    document.getElementById('STrChOChampRepairState' + chId).className = 'STrChOSuccess';

                } else if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                    document.getElementById('STrChOChampRepairState' + chId).className = 'STrChOBroken';

                } else if (champItem.status == CM.CHAMPION.STATUS_REPAIRING_UPGRADE || champItem.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE) {
                    document.getElementById('STrChOChampRepairState' + chId).className = 'STrChOHammer';
                } else {
                    document.getElementById('STrChOChampRepairState' + chId).innerHTML = '<div class=STrChOGoButton></div>';
                }
            }
        } else {
            m += '</table>';
            STrChOChampRepairQDiv.innerHTML = m;
        }
    },

}

Tabs.champOrganizer = {
	tabOrder: 203,
	tabLabel: 'ORGANIZER',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL ORGANIZER',
    champItemLists: [],
    sortEffect: "none",
    buffType: "both",
    panelId: -1,
    panelType: "upgrade",
    panelNextLevel: 2,
    switchingPresets: false,

	init: function (div) {
		var t = Tabs.champOrganizer;
		t.mydiv = div;

        t.sortEffect = STrChOChampUpgradeData.effectSelected;
        t.buffType = STrChOChampUpgradeData.buffSelected;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td align=center><b>You Have <i><div class=divNoWrap id=STrChOCountChampCards></div></i> Champ Cards</b></td></tr>';
        m += '<tr><td>';

        m += 'Sort: <select class=STrChOSelect id=STrChOChampSortEffects>';
        m += '<option value="none">--Effect--</option>';
        for (efx in champEffects) m += '<option value="' + champEffects[efx] + '">' + champEffects[efx] + '</option>';
        m += '</select>';
        m += '<select class=STrChOSelect id=STrChOChampBuffType>';
        m += '<option value="both">Either</option>';
        m += '<option value="buff">Buff</option>';
        m += '<option value="debuff">Debuff</option>';
        m += '</select>';

        m += '<input id=STrChOChampSortInactive class=STrChOCheckbox type=checkbox ' + (STrChOChampUpgradeData.sortInactive ? ' CHECKED' : '') + '/> Include Inactive ';
        m += '<input id=STrChOChampIgnoreBroken class=STrChOCheckbox type=checkbox ' + (STrChOChampUpgradeData.ignoreBroken ? ' CHECKED' : '') + '/> Ignore Broken';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';

        m += '<div id=STrChOChampOrganizerScroll style="position: static; width: ' + (dlgWidth -  (dlgWidthOffset + dlgWidthMenu)) + 'px; height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; overflow-x: hidden; overflow-y: auto;">';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;CARD FILTER&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable cellspacing=0 cellpadding=0>';

        m += '<tr><td colspan=3>';
        m += 'Filter By Effects: <select class=STrChOSelect id=STrChOChampFilterEffects>';
        m += '<option value="none">--Effect--</option>';
        for (efx in champEffects) m += '<option value="' + champEffects[efx] + '">' + champEffects[efx] + '</option>';
        m += '</select>';
        m += '<select class=STrChOSelect id=STrChOChampFilterBuffType>';
        m += '<option value="buff">Buff</option>';
        m += '<option value="debuff">Debuff</option>';
        m += '</select>';
        m += '</td></tr>';

        m += '<tr><td colspan=3><hr class=STrChOHRCenter></td></tr>';

        m += '<tr><td>Faction</td><td>Quality</td><td>Level</td></tr>';

        m += '<tr>';

        m += '<td><div id=STrChOChampFactionFilterRow style="float: left; width: 100px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (var fact = 0; fact < STrChOFactions.length; fact++) m += '<input id=STrChOChampFaction' + STrChOFactions[fact] + ' class=STrChOCheckbox type=checkbox  CHECKED />' + STrChOFactions[fact].capitalizeFirstLetter() + '<br />';

        m += '</div></td>';

        m += '<td><div id=STrChOChampQualityFilterRow style="float: left; width: 120px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (var qual = 0; qual < champCardQualities.length; qual++) m += '<input id=STrChOChampQuality' + qual + ' class=STrChOCheckbox type=checkbox  CHECKED />' + champCardQualities[qual].capitalizeFirstLetter() + '<br />';
        m += '</div></td>';

        m += '<td><div id=STrChOChampLevelFilterRow style="float: left; width: 120px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (lvl = 0; lvl <= STrChOMaxChampLevel; lvl++) {
            m += '<input id=STrChOChampLevel' + lvl + ' class=STrChOCheckbox type=checkbox CHECKED />' + lvl + '<br /> ';
        }
        m += '</div></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td/>';
        m += '<td><input style="width:120px;" id=STrChOChampUnselectAllQualities class=STrChOButton type=button value="Unselect All"></td>';
        m += '<td><input style="width:120px;" id=STrChOChampUnselectAllLevels class=STrChOButton type=button value="Unselect All"></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td/>';
        m += '<td><input style="width:120px;" id=STrChOChampSelectAllQualities class=STrChOButton type=button value="Select All"></td>';
        m += '<td><input style="width:120px;" id=STrChOChampSelectAllLevels class=STrChOButton type=button value="Select All"></td>';
        m += '</tr>';

        m += '</table>';
        m += '</div>';

        for (champItemCardType in champItemNames) {
            m += '<div class=STrChOChampOrganizer onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;' + champItemNames[champItemCardType].toUpperCase() + '&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';
            m += '<div class=STrChOChampOrganizerSection id=STrChOChampCardSection' + champItemNames[champItemCardType] + '></div>';
        }

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var champOrganizers = document.getElementsByClassName('STrChOChampOrganizer');
        for (var champOrg=0; champOrg < champOrganizers.length; champOrg++) {
            champOrganizers[champOrg].addEventListener('click', function () {

                var imgs = this.childNodes;
                if (imgs[0].src == STrChODownArrow) {
                    imgs[0].src = STrChORightArrow
                    imgs[2].src = STrChORightArrow
                } else {
                    imgs[0].src = STrChODownArrow
                    imgs[2].src = STrChODownArrow
                }
                var section = this.nextSibling;
                if (section.className != 'STrChOChampOrganizerSection') return;

                if (section.style.display == 'block')
                    section.style.display = 'none';
                else
                    section.style.display = 'block';

            }, false);
        }

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        document.getElementById('STrChOChampSortEffects').value = STrChOChampUpgradeData.effectSelected;
        document.getElementById('STrChOChampBuffType').value = STrChOChampUpgradeData.buffSelected;
        document.getElementById('STrChOChampSortInactive').checked = STrChOChampUpgradeData.sortInactive;
        document.getElementById('STrChOChampIgnoreBroken').checked = STrChOChampUpgradeData.ignoreBroken;

        document.getElementById('STrChOChampFilterBuffType').addEventListener('change', function () {
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampFilterEffects').addEventListener('change', function () {
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampSortEffects').addEventListener('change', function () {
            t.sortEffect = this.value;
            STrChOChampUpgradeData.effectSelected = t.sortEffect;
            SAVESTrChOChampUpgradeData();
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampBuffType').addEventListener('change', function () {
            t.buffType = this.value;
            STrChOChampUpgradeData.buffSelected = t.buffType;
            SAVESTrChOChampUpgradeData();
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampSortInactive').addEventListener('click', function () {
            STrChOChampUpgradeData.sortInactive = document.getElementById('STrChOChampSortInactive').checked;
            SAVESTrChOChampUpgradeData();
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampIgnoreBroken').addEventListener('click', function () {
            STrChOChampUpgradeData.ignoreBroken = document.getElementById('STrChOChampIgnoreBroken').checked;
            SAVESTrChOChampUpgradeData();
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampUnselectAllQualities').addEventListener('click' , function () {
            for (var qual = 0; qual < champCardQualities.length; qual++) document.getElementById('STrChOChampQuality' + qual).checked = false;
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampSelectAllQualities').addEventListener('click', function () {
            for (var qual = 0; qual < champCardQualities.length; qual++) document.getElementById('STrChOChampQuality' + qual).checked = true;
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampQualityFilterRow').addEventListener('change', function () {
            t.createChampItemList();
            t.paintChampTables();
        }, false);


        document.getElementById('STrChOChampUnselectAllLevels').addEventListener('click' , function () {
            for (lvl = 0; lvl <= STrChOMaxChampLevel; lvl++) document.getElementById('STrChOChampLevel' + lvl).checked = false;
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampSelectAllLevels').addEventListener('click', function () {
            for (lvl = 0; lvl <= STrChOMaxChampLevel; lvl++) document.getElementById('STrChOChampLevel' + lvl).checked = true;
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        document.getElementById('STrChOChampLevelFilterRow').addEventListener('change', function () {
            t.createChampItemList();
            t.paintChampTables();
        }, false);


        document.getElementById('STrChOChampFactionFilterRow').addEventListener('change', function () {
            t.createChampItemList();
            t.paintChampTables();
        }, false);

        t.createChampItemList();
        t.paintChampTables();
	},

	hide: function () {
    },

    createChampItemList: function () {
        var t = Tabs.champOrganizer;

        for (var champItemTypeValue in champItemNames) t.champItemLists[champItemTypeValue] = new Array;

        for (champId in uW.kocChampionItems) {
            var champItem = uW.kocChampionItems[champId];

            // apply filters
            var faction = STrChOFactions[champItem.faction -1];
            var level = champItem.level;
            var champtype = champItem.type;
            var quality = champItem.rarity;
            var isBroken = champItem.status;

            if (STrChOChampUpgradeData.ignoreBroken && (isBroken == CM.CHAMPION.STATUS_BROKEN_UPGRADE || isBroken == CM.CHAMPION.STATUS_BROKEN_ENHANCE)) continue;
            if (!document.getElementById('STrChOChampQuality' + quality)) continue;
            if (!document.getElementById('STrChOChampQuality' + quality).checked) continue;
            if (!document.getElementById('STrChOChampFaction' + faction)) continue;
            if (!document.getElementById('STrChOChampFaction' + faction).checked) continue;
            if (!document.getElementById('STrChOChampLevel' + level)) continue;
            if (!document.getElementById('STrChOChampLevel' + level).checked) continue;

            var filterEffect = document.getElementById('STrChOChampFilterEffects').value;
            if (filterEffect != 'none') {
                var filterBuff = document.getElementById('STrChOChampFilterBuffType').value;
                if (filterBuff == 'debuff') filterEffect += ' Debuff';
                var foundEffect = false;
                for (e in champItem.effects) {
                    var N = champItem.effects[e];
                    var effect = uW.g_js_strings.effects["name_" + N.id];
                    if (effect == filterEffect) {
                        foundEffect = true;
                        break;
                    }
                }
                if (!foundEffect) continue;
            }

            if (champItem.equippedTo > 0)
                t.champItemLists[champtype].unshift(champItem);
            else
                t.champItemLists[champtype].push(champItem);
        }
        t.sortChampOrganizerLists();
    },

    sortChampOrganizerLists: function () {
        var t = Tabs.champOrganizer;
        STrChOChampUpgradeData.sortInactive = document.getElementById('STrChOChampSortInactive') == null ? false : document.getElementById('STrChOChampSortInactive').checked;
        for (i = 0; i < t.champItemLists.length; i++) {
            if (!t.champItemLists[i]) continue;
            t.champItemLists[i].sort(function (item1, item2) {
                return t.sortChampOrganizerValue(item2) - t.sortChampOrganizerValue(item1);
            });
        }
    },

    sortChampOrganizerValue: function (item) {
        var t = Tabs.champOrganizer;
        var retValue = 0.0;
        for (e in item.effects) {
            try {
                var N = item.effects[e];
                var id = item.effects[e].id;
                var effect = "";
                var quality = item.rarity;

                effect = uW.g_js_strings.effects["name_" + id];

                var S = champTiers;
                var P = id + "," + N.tier;
                var tier = S[P];

                var base = tier.Base || 0;
                var growth = tier.Growth || 0;
                var level = item.level || 0;

                // slot number
                var B = +e;

                if (B > quality && !STrChOChampUpgradeData.sortInactive) {
                    return +retValue;
                }

                var percent = +(base + ((level * level + level) * growth * 0.5));
                if ((effect == (t.sortEffect + " Debuff")) && (t.sortType != "buff")) {
                    retValue -= percent;
                }
                else if (effect == t.sortEffect && t.sortType != "debuff") {
                    retValue += percent;
                }
            } catch (e) {
            }

        }
        return +retValue;
    },

    paintChampTables: function () {
        var t = Tabs.champOrganizer;
        for (champItemTypeValue in t.champItemLists) {
            var m = '<table><tr>';
            var divCards = document.getElementById('STrChOChampCardSection' + champItemNames[champItemTypeValue]);
            if (!divCards) continue;
            divCards.innerHTML = "<div></div>";
            for (idx = 0; idx < t.champItemLists[champItemTypeValue].length; idx++) {
                var champItem = t.champItemLists[champItemTypeValue][idx];
                m += '<td><div class=STrChOChampCard id=STrChOChampCard' + champItem.equipmentId + '>';
                m += BuildChampCard(champItem);
                m += '</div></td>';
            }
            m += '</tr></table>';
            divCards.innerHTML = '<div>' + m + '</div>';
        }
        var STrChOCards = document.getElementsByClassName('STrChOChampCard');
        for (idx = 0; idx < STrChOCards.length; idx++) {
            STrChOCards[idx].addEventListener('click', function (A) {
                A.stopPropagation();
                var champId = this.id.split('STrChOChampCard')[1];
                var champItem = uW.kocChampionItems[champId];
                var STrChOCard = document.getElementById('STrChOChampCard' + champId);
                CardContextMenu(this, champItem, true);
            },false);
        }
    },

	show: function () {
        var t= Tabs.champOrganizer;
        if (document.getElementById('STrChOCountChampCards') != null) document.getElementById('STrChOCountChampCards').innerHTML = countHowManyChampCards();
        t.createChampItemList();
        t.paintChampTables();
	},



    showNextChampLevel: function () {
        var t = Tabs.champOrganizer;

        if (t.panelNextLevel + 1 > STrChOMaxChampLevel) return;

        var elemStatTitle = document.getElementsByClassName('upgEnhStatsTitle')[1];
        t.panelNextLevel++;
        elemStatTitle.innerHTML = "Level " + t.panelNextLevel + (t.panelNextLevel == STrChOMaxChampLevel ? "" : " (<i>Next</i>)");

        var elemStatBody = document.getElementById('upgEnhStatsBodyTarget');

        var elemStatItems = elemStatBody.getElementsByTagName("li");

        var champ_item = uW.kocChampionItems[t.panelId];

        for (var elemIndex = 0; elemIndex < elemStatItems.length; ++elemIndex) {
            var elemItem = elemStatItems[elemIndex];
            var slotNumber = elemIndex + 1;
            var effectLine = champ_item.effects[slotNumber];
            var effect = CM.ChampionManager.getEffect(effectLine, t.panelNextLevel);
            elemItem.innerHTML = effect.name + " " + effect.amount;
        }
    },


}

Tabs.champEnhStats = {
	tabOrder: 204,
	tabLabel: 'ENH&nbsp;STATS',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL ENHANCEMENT STATS',

	init: function (div) {
		var t = Tabs.champEnhStats;
		t.mydiv = div;
        t.buildChampEnhStatsDisplay();
	},

	hide: function () {},

	buildChampEnhStatsDisplay: function () {

        var t = Tabs.champEnhStats;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - (dlgWidthOffset*2.5)) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table class=STrChOStats align=center cellspacing=0>';

        m += '<tr valign=top align=center><th colspan=' + (STrChOMaxChampQuality + 2) + '>Enhancing Numbers  (successes/failures)</th></tr>';

        m += '<tr valign=top align=center><th></th>';
        for (qual = 0; qual <= STrChOMaxChampQuality; qual++) m += '<td style="font-weight: bold;" class="td' + (qual % 2 + 1) + '"  >' + champCardQualities[qual].capitalizeFirstLetter() + '&nbsp;</td>';
        m += '</tr>';

        var st = [0, 0, 0, 0, 0, 0];
        var ft = [0, 0, 0, 0, 0, 0];

        for (lvl = 0; lvl <= STrChOMaxChampLevel; lvl++) {
            m += '<tr valign=top align=center>';
            m += '<th>';
            if (lvl != 0) m += '+';
            m += lvl + '</th>';
            for (qual = 0; qual < (STrChOMaxChampQuality+1); qual++) {
                if (STrChOChampUpgradeStats.enhanceSuccess[qual][lvl] == null) STrChOChampUpgradeStats.enhanceSuccess[qual][lvl] = 0;
                if (STrChOChampUpgradeStats.enhanceFailure[qual][lvl] == null) STrChOChampUpgradeStats.enhanceFailure[qual][lvl] = 0;
                st[qual] += STrChOChampUpgradeStats.enhanceSuccess[qual][lvl];
                ft[qual] += STrChOChampUpgradeStats.enhanceFailure[qual][lvl];
                m += '<td class="td' + (qual % 2) + '"  >' + STrChOChampUpgradeStats.enhanceSuccess[qual][lvl] + ' / ' + STrChOChampUpgradeStats.enhanceFailure[qual][lvl] + '</td>';
            }
            m += '</tr>';
        }

        m += '<tr valign=top align=center><th> Totals: </th>';
        for (qual = 0; qual < (STrChOMaxChampQuality+1); qual++) m += '<td style="font-weight: bold;" class="td' + (qual % 2) + '" >' + st[qual] + ' / ' + ft[qual] + '</td>';
        m += '</tr>';

        m += '<tr valign=top align=center><th> Percents: </th>';
        for (qual = 0; qual < (STrChOMaxChampQuality+1); qual++) {
            m += '<td style="font-weight: bold;" class="td' + (qual % 2) + '" >';
            if ((st[qual] + ft[qual]) == 0)
                m += "--";
            else {
                var perc = (100 * st[qual] / (st[qual] + ft[qual]));
                m += perc.toFixed(2) + '%';
            }
            m += '</td>';
        }
        m += '</tr>';

        m += '</table>';
        m += '</div>';

        m += '<center><input type=button class=STrChOButton value="Clear Stats" id=STrChOChampEnhStatsClear></center>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOChampEnhStatsClear').addEventListener('click', function () {

            var t = Tabs.champEnhStats;
            for (lvl = 0; lvl <= STrChOMaxChampLevel; lvl++) {
                for (qual = 0; qual < (STrChOMaxChampQuality+1); qual++) {
                    STrChOChampUpgradeStats.enhanceSuccess[qual][lvl] = null;
                    STrChOChampUpgradeStats.enhanceFailure[qual][lvl] = null;
                }
            }
            SAVESTrChOChampUpgradeStats();
            t.buildChampEnhStatsDisplay();

        }, false);

    },

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

}

Tabs.champUpgStats = {
	tabOrder: 205,
	tabLabel: 'UPG&nbsp;STATS',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL UPGRADE STATS',

	init: function (div) {
		var t = Tabs.champUpgStats;
		t.mydiv = div;
        t.buildChampUpgStatsDisplay();
	},

	hide: function () {},

	buildChampUpgStatsDisplay: function () {

		var t = Tabs.champUpgStats;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - (dlgWidthOffset*2.5)) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table class=STrChOStats align=center cellspacing=0>';

        m += '<tr valign=top align=center><th colspan=' + (STrChOMaxChampLevel+2) + '>Upgrading Numbers  (successes/failures)</TH></TR>';

        m += '<tr valign=top align=center><th></th>';
        for (lvl = 0; lvl < STrChOMaxChampLevel; lvl++) m += '<td style="font-weight: bold;" class="td' + (lvl % 2) + '"  >&nbsp;+' + (lvl + 1) + '&nbsp;</td>';
        m += '</tr>';

        var st = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ];  //TODO: increase when game increases max champ levels (currently 45)
        var ft = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ];

        for (qual = 0; qual <= STrChOMaxChampQuality; qual++) {
            m += '<tr valign=top align=center><th>' + champCardQualities[qual].capitalizeFirstLetter() + '</th>';
            for (lvl = 0; lvl < STrChOMaxChampLevel; lvl++) {
                if (STrChOChampUpgradeStats.upgradeSuccess[qual][lvl] == null || isNaN(STrChOChampUpgradeStats.upgradeSuccess[qual][lvl])) STrChOChampUpgradeStats.upgradeSuccess[qual][lvl] = 0;
                if (STrChOChampUpgradeStats.upgradeFailure[qual][lvl] == null || isNaN(STrChOChampUpgradeStats.upgradeFailure[qual][lvl])) STrChOChampUpgradeStats.upgradeFailure[qual][lvl] = 0;
                st[lvl] += STrChOChampUpgradeStats.upgradeSuccess[qual][lvl];
                ft[lvl] += STrChOChampUpgradeStats.upgradeFailure[qual][lvl];

                m += '<td class="td' + (lvl % 2) + '"  >';
                m += STrChOChampUpgradeStats.upgradeSuccess[qual][lvl] + ' / ' + STrChOChampUpgradeStats.upgradeFailure[qual][lvl];
                m += '</td>';
            }
            m += '</tr>';
        }

        m += '<tr valign=top align=center><th> Totals: </th>';
        for (lvl = 0; lvl < STrChOMaxChampLevel; lvl++) m += '<td style="font-weight: bold;" class="td' + (lvl % 2) + '"  >' + st[lvl] + " / " + ft[lvl] + '</td>';
        m += '</tr>';

        m += '<tr valign=top align=center><th> Percents: </th>';
        for (lvl = 0; lvl < STrChOMaxChampLevel; lvl++) {
            m += '<td style="font-weight: bold;" class="td' + (lvl % 2) + '"  >';
            if ((st[lvl] + ft[lvl]) == 0)
                m += '--';
            else {
                var perc = (100 * st[lvl] / (st[lvl] + ft[lvl]));
                m += perc.toFixed(2) + '%';
            }
            m += '</td>';
        }
        m += '</tr>';

        m += '</table>';
        m += '</div>';

        m += '<center><input type=button class=STrChOButton value="Clear Stats" id=STrChOChampUpgStatsClear></center>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOChampUpgStatsClear').addEventListener('click', function () {
            var t = Tabs.champUpgStats;
            for (lvl = 0; lvl <= STrChOMaxChampLevel; lvl++) {
                for (qual = 0; qual < (STrChOMaxChampQuality+1); qual++) {
                    STrChOChampUpgradeStats.upgradeSuccess[qual][lvl] = null;
                    STrChOChampUpgradeStats.upgradeFailure[qual][lvl] = null;
                }
            }
            SAVESTrChOChampUpgradeStats();
            t.buildChampUpgStatsDisplay()
        }, false);

    },

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

Tabs.champPresets = {
	tabOrder: 206,
	tabLabel: 'PRESETS',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL PRESETS',
    broke_items: 0,
    broke_count: 0,
    delay: 2000,

	init: function (div) {
		var t = Tabs.champPresets;
		t.mydiv = div;



	},

	hide: function () {},

    refreshBrokeMightDisplay: function () {
        document.getElementById('STrChOChampMightBroke').innerHTML = getChampBrokeMight();
    },

	show: function () {
		var t = Tabs.champPresets;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '<div class=STrChOSaveSettings id=STrChOChampPresetsSaveSettings title="Save Presets Settings"></div><div class=STrChOLoadSettings id=STrChOChampPresetsLoadSettings title="Load Presets Settings"></div></div>';

        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table>';
        m += '<tr><td width=100%>Preset Color: <select class=STrChOSelect id=STrChOChampPresetColor>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (STrChOChampPresetData.presetColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;General Color: <select class=STrChOSelect id=STrChOChampTagColor>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (STrChOChampPresetData.tagColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;Active Color: <select class=STrChOSelect id=STrChOChampActiveColor>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (STrChOChampPresetData.activeColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>(Requires Refresh)</td></tr>';
        m += '<tr><td>';
        m += '<input type=button class=STrChOButton id=STrChOChampClearTags value="Clear All Tags">&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton id=STrChOChampClearAllPresetTags value="Clear All Preset Tags">&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton id=STrChOChampSaveAllPresetTags value="Save All Preset Tags">&nbsp;&nbsp;';
        //m += '<input type=button id=trExportPresetTags value="Export Preset Tags">';
        m += '</td></tr>';
        m += '<tr><td>';
        m += '<input type=checkbox class=STrChOCheckbox id=STrChOChampShowMight ' + (STrChOChampPresetData.showChampMight ? 'CHECKED' : '') + '/>Show Might on Posts';
        m += '&nbsp;&nbsp;&nbsp;<input type=checkbox class=STrChOCheckbox id=STrChOChampShowName ' + (STrChOChampPresetData.showChampName ? 'CHECKED' : '') + '/>Show Preset Name on Posts';
        m += '</td></tr>';
        m += '</table>';


        m += '<div class=STrChOHeader id=STrChOChampPresetNaming onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;PRESET NAMING&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        if (STrChOMaxChampions == 0) {
            m += '<tr><td>No Champions</td></tr>';
        } else {
            var presetsList = "";
            for (var i = 1; i < STrChOMaxChampions + 1; i++) {
                presetsList += '<option value="' + i + '">' + i + '</option>';
            }

            for (var i = 1; i < STrChOMaxChampions+1; i++) {
                var thisChampion = Seed.champion.champions[i-1];
                m += '<tr>';
                m += '<td><input class="STrChOChampPresetSlotPost STrChOButton" type=button id=STrChOChampPreset' + i + ' value="Post Slot"></td>';
                m += '<td><input class="STrChOChampPresetTagPost STrChOButton" type=button id=STrChOChampPreset' + i + ' value="Post Tag"></td>';
                if (thisChampion.name == "") {
                    m += '<td><b>Champ ' + i + ':</b></td>';
                } else {
                    m += '<td><b>' + thisChampion.name + ':</b></td>';
                }

                m += '<td><input class="STrChOChampPresetNameEntry STrChOTextbox" type=text size=15 id=STrChOChampPresetName' + i + ' value="' + STrChOChampPresetData.presetNames[i-1] + '"></td>';
                m += '<td><input class="STrChOChampPresetCopyTo STrChOButton" type=button id=STrChOChampPreset' + i + ' value="Copy To"><select class=STrChOSelect id=STrChOChampPresetCopyToWhat' + i + '>' + presetsList + '</select></td>';
                m += '<td><input class="STrChOChampPresetSave STrChOButton" type=button id=STrChOChampPreset' + i + ' value="Save"></td>';

                if (getChampPresetTagCount(i) != 0) {
                    m += '<td><input class="STrChOChampPresetClear STrChOButton" type=button id=STrChOChampPreset' + i + ' value="Clear"></td>';
                    m += '<td><input class="STrChOChampPresetExcel STrChOButton" type=button id=STrChOChampPreset' + i + ' value="Excel"></td>';
                } else {
                    m += '<td/><td/>';
                }
                m += '</tr>';

            }
        }
        m += '</table>';
        m += '</div>';

        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;CHAMP HALL BREAKING&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td><div id=STrChOChampMightBroke>You have 0 champ hall might broken</div></td></tr>';
        m += '<tr><td><input type=checkbox checked class=STrChOCheckbox id=STrChOChampExcludePresets>Exclude Tagged Presets</td></tr>';
        m += '<tr><td><input type=checkbox checked class=STrChOCheckbox id=STrChOChampExcludeTags>Exclude Regular Tagged</td></tr>';
        m += '<tr><td>Break Items Level <select class=STrChOSelect id=STrChOChampBreakLevelLow>';
        for (lvl = 1; lvl < STrChOMaxChampLevel; lvl++) {
            m += '<option value=' + lvl + '>+' + lvl + '</option>';
        }
        m += '</select> or Higher</td></tr>';
        m += '<tr><td>Break Items Level <select class=STrChOSelect id=STrChOChampBreakLevelHigh>';
        for (lvl = 1; lvl < STrChOMaxChampLevel; lvl++) {
            m += '<option value=' + lvl + (lvl == STrChOMaxChampLevel - 1 ? ' SELECTED' : '') + '>+' + lvl + '</option>';
        }
        m += '</select> or Lower</td></tr>';

        m += '<tr><td><input type=button class=STrChOButton id=STrChOChampBreakAll value="Break Now"><font color=red><i>(all options above will reset after refresh)</i></font></td></tr>';
        m += '<tr><td><div id=STrChOChampBreakCounter></div></td></tr>';
//        m += '<tr><td><hr></td></tr>';
//        m += '<tr><td>Break Equiped Throne Room Only<select class=STrChOSelect id=STrChOThronePresetEquipBreak>' + presetsList + '</select><input type=button class=STrChOButton id=STrChOThronePresetEquipBreakNow value="Break Now"></td></tr>';
//        m += '<tr><td>Break Tagged Preset Only<select class=STrChOSelect id=STrChOThronePresetTaggedBreak>' + presetsList + '</select><input type=button class=STrChOButton id=STrChOThronePresetTaggedBreakNow value="Break Now"></td></tr>';
//        m += '<tr><td>Break <input type=number class=STrChOText id=STrChOThroneMightBreak oncontextmenu="return false;"> Throne Might <input type=button class=STrChOButton id=STrChOThroneMightBreakNow value="Break Now"></td></tr>';
        m += '</table>';
        m += '</div>';
        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOChampPresetsSaveSettings').addEventListener('click', function () {
            SaveSettingsToFile(STrChOChampPresetData);
        }, false);
        document.getElementById('STrChOChampPresetsLoadSettings').addEventListener('click', function () {
            var loader = document.getElementById('STrChOSettingsFile');
            loader.addEventListener('change', function () {
                LoadSettingsFromFile(STrChOChampPresetData, Tabs.champPresets);
            }, false);
            loader.click();
        }, false);

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        t.refreshBrokeMightDisplay();

        document.getElementById('STrChOChampShowMight').addEventListener('change', function () {
            STrChOChampPresetData.showChampMight = document.getElementById('STrChOChampShowMight').checked;
            SAVESTrChOChampPresetData();
        }, false);

        document.getElementById('STrChOChampShowName').addEventListener('change', function () {
            STrChOChampPresetData.showChampName = document.getElementById('STrChOChampShowName').checked;
            SAVESTrChOChampPresetData();
        }, false);

        document.getElementById('STrChOChampBreakAll').addEventListener('click', function () {
            if (!confirm('You cannot undo this action, are you sure you want to break your champ hall?')) return;
            var excludePresets = document.getElementById('STrChOChampExcludePresets').checked;
            var excludeTags = document.getElementById('STrChOChampExcludeTags').checked;
            var breakLevelLow = document.getElementById('STrChOChampBreakLevelLow').value;
            var breakLevelHigh = document.getElementById('STrChOChampBreakLevelHigh').value;
            var allTaggedPresets = [];
            if (excludePresets) {
                for (i = 1; i < STrChOMaxChampions + 1; i++) {
                    if (getChampPresetTagCount(i) != 0) {
                        var thisPreset = getChampPresetObject(i);
                        for (var champId in thisPreset) {
                            var champ_item = uW.kocChampionItems[champId];
                            if (champ_item == null || !champ_item) continue;
                            if (champ_item.level == STrChOMaxChampLevel) continue;
                            if (champ_item.level < breakLevelLow || champ_item.level > breakLevelHigh) continue;
                            allTaggedPresets.push(champId);
                        }
                    }
                }
            }

            var champToBreak = [];
            for (chId in uW.kocChampionItems) {
                var champ_item = uW.kocChampionItems[chId];
                if (champ_item == null || !champ_item) continue;
                if (champ_item.status != 1) continue;//card broken?
                if (excludeTags && STrChOChampPresetData.taggedItems[chId]) continue;
                if (allTaggedPresets.indexOf(chId) != -1) continue;
                if (champ_item.level == STrChOMaxChampLevel) continue;
                if (champ_item.level < breakLevelLow || champ_item.level > breakLevelHigh) continue;

                champToBreak.push(chId);
            }
            delete allTaggedPresets;

            if (champToBreak.length == 0) {
                alert('No champ items to break');
                return;
            }

            t.broke_count = champToBreak.length;

            t.setBreakStatus();

            t.broke_items = 0;

            for (var i = 0; i < champToBreak.length; i++) {  //loop through all the champ items to be broke

                var citytobreakfrom = 0;  //start at the first city {the index is 0-based}

                var champ_item = uW.kocChampionItems[champToBreak[i]];  //get the next champ item in the collection

                var curr_level = champ_item.level;  //get the current level of the champ item

                var champ_id = champ_item.equipmentId;  //get the champ item id

                if (curr_level == STrChOMaxChampLevel) continue;  //if for some reason a card at the max level makes it through the list then continue to the next in the list

                var z = CM.WorldSettings.getSettingAsObject("CE_UPGRADE_AETHERSTONE_MAP");

                var cost_to_upgrade = z[curr_level + 1].Aetherstones;  //get the cost of stones to upgrade to the next level

                while (citytobreakfrom < 8) {  //loop through all the 8 cities checking for astone to upgrade for the break feature

                    stones_in_city = parseInt(Seed.resources["city" + Seed.cities[citytobreakfrom][0]]["rec5"][0]);  //get the astone count for the city

                    if (cost_to_upgrade + STrChOBreakBuffer <= stones_in_city) break;  //if you have the astone in the city then stop searching cities and do the upgrade

                    citytobreakfrom = citytobreakfrom + 1;  //search to the next city in the loop

                }

                if (citytobreakfrom == 8) continue;  //if you make it to 8, then you've exhausted all the cities astone search for this champ item, move to the next one

                var city = Seed.cities[citytobreakfrom][0];

                setTimeout(
                    (function(cy, id, uc) {
                        return function () {
                            upgradeIt(cy, id, uc);
                        }
                    }) (city, champ_id, cost_to_upgrade), (i+1) * t.delay);

            }

            setTimeout(function() {
                var t = Tabs.champPresets;
                if (t.broke_items == 0) {
                    alert('No Items broken.');
                } else {
                    alert('Breaking CH complete.  ' + t.broke_items + ' Champ items were broken.  Page will now refresh.');
                    RefreshCamelot();
                }
            }, champToBreak.length * t.delay + t.delay);

        }, false);

        document.getElementById('STrChOChampClearAllPresetTags').addEventListener('click', function () {
            t.clearAllPresetTagItems();
            t.show();
            document.getElementById('STrChOChampPresetNaming').click();
        }, false);

        document.getElementById('STrChOChampSaveAllPresetTags').addEventListener('click', function () {
            for (i = 1; i < STrChOMaxChampions + 1; i++) {
                t.addPresetTags(i);
            }
            t.show();
            document.getElementById('STrChOChampPresetNaming').click();
        }, false);

        document.getElementById('STrChOChampClearTags').addEventListener('click', function () {
            t.removeAllTagItems();
        }, false);

        document.getElementById('STrChOChampActiveColor').addEventListener('change', function () {
            STrChOChampPresetData.activeColor = document.getElementById('STrChOChampActiveColor').value;
            SAVESTrChOChampPresetData();
        }, false);

        document.getElementById('STrChOChampPresetColor').addEventListener('change', function () {
            STrChOChampPresetData.presetColor = document.getElementById('STrChOChampPresetColor').value;
            SAVESTrChOChampPresetData();
        }, false);

        document.getElementById('STrChOChampTagColor').addEventListener('change', function () {
            STrChOChampPresetData.tagColor = document.getElementById('STrChOChampTagColor').value;
            SAVESTrChOChampPresetData();
        }, false);


        var STrChOChampPresetSave = document.getElementsByClassName('STrChOChampPresetSave');
        for (var idx=0;idx<STrChOChampPresetSave.length;idx++) {
            STrChOChampPresetSave[idx].addEventListener('click', function() {
                var id = this.id;
                var num = id.split("STrChOChampPreset")[1];
                t.addPresetTags(num);
                t.show();
                document.getElementById('STrChOChampPresetNaming').click();
            }, false);
        }

        var STrChOChampPresetSlotPost = document.getElementsByClassName('STrChOChampPresetSlotPost');
        for (var idx=0; idx<STrChOChampPresetSlotPost.length; idx++) {
            STrChOChampPresetSlotPost[idx].addEventListener('click', function() {
                var id = this.id;
                var num = id.split('STrChOChampPreset')[1];
                postChampSlot(num);
            }, false);
        }

        var STrChOChampPresetTagPost = document.getElementsByClassName('STrChOChampPresetTagPost');
        for (var idx=0; idx<STrChOChampPresetTagPost.length; idx++) {
            STrChOChampPresetTagPost[idx].addEventListener('click', function () {
                var id = this.id;
                var num = id.split('STrChOChampPreset')[1];
                postChampPreset(num);
            }, false);
        }

        var STrChOChampPresetClear = document.getElementsByClassName('STrChOChampPresetClear');
        for (var idx=0; idx<STrChOChampPresetClear.length; idx++) {
            STrChOChampPresetClear[idx].addEventListener('click', function () {
                var id = this.id;
                var num = id.split('STrChOChampPreset')[1];
                t.clearPresetTags(num);
                t.show();
                document.getElementById('STrChOChampPresetNaming').click();
            }, false);
        }

        var STrChOChampPresetExcel = document.getElementsByClassName('STrChOChampPresetExcel');
        for (var idx=0; idx<STrChOChampPresetExcel.length; idx++) {
            STrChOChampPresetExcel[idx].addEventListener('click', function () {
                var id = this.id;
                var num = id.split('STrChOChampPreset')[1];
                ExportChampPresetToExcel(num);
            }, false);
        }

        var STrChOChampPresetCopyTo = document.getElementsByClassName('STrChOChampPresetCopyTo');
        for (var idx=0; idx<STrChOChampPresetCopyTo.length; idx++) {
            STrChOChampPresetCopyTo[idx].addEventListener('click', function () {
                var id = this.id;
                var sourceNum = id.split('STrChOChampPreset')[1];
                var destNum = document.getElementById('STrChOChampPresetCopyToWhat' + sourceNum).value;
                var copyName = document.getElementById('STrChOChampPresetName' + sourceNum).value;
                t.copyPresetTags(sourceNum, destNum, copyName);
                t.show();
                document.getElementById('STrChOChampPresetNaming').click();
            }, false);
        }

        var STrChOChampPresetNameEntry = document.getElementsByClassName('STrChOChampPresetNameEntry');
        for (var idx=0; idx<STrChOChampPresetNameEntry.length; idx++) {
            STrChOChampPresetNameEntry[idx].addEventListener('change', function () {
                var id = this.id;
                var num = id.split('STrChOChampPresetName')[1];
                var presetName = this.value;
                if (presetName == "") {
                    presetName = "undefined";
                    document.getElementById(id).value = presetName;
                }
                STrChOChampPresetData.presetNames[num-1] = presetName;
                SAVESTrChOChampPresetData();
            }, false);

            STrChOChampPresetNameEntry[idx].addEventListener('blur', function () {
                var id = this.id;
                var num = id.split('STrChOChampPresetName')[1];
                var presetName = this.value;
                if (presetName == "") {
                    presetName = "undefined";
                    document.getElementById(id).value = presetName;
                    STrChOChampPresetData.presetNames[num-1] = presetName;
                    SAVESTrChOChampPresetData();
                }
            }, false);
        }
	},

    setBreakStatus: function() {
        var t = Tabs.champPresets;
        var remaining = t.broke_count - t.broke_items;
        var m =  "Items Remaining: " + remaining;
        m += "<br>Time Remaining: " + (remaining * (t.delay/1000)) + " Seconds";
        document.getElementById('STrChOChampBreakCounter').innerHTML = m;
    },

    unequipAllItems: function (presetIndex) {
        var t = Tabs.champPresets;

        if (!confirm('Are you sure you want to unequip all items?')) return;

        var championID = uW.seed.champion.champions[presetIndex-1].championId;// = 11007

        var equipped_items = [];


        for (chId in uW.kocChampionItems) {
            if (uW.kocChampionItems[chId].equippedTo != championID) continue;
            equipped_items.push(chId);
        }

        var el = equipped_items.length;

        if ( el == 0 ) return;

        function unequipLoop(counter, id) {
            setTimeout(function() { t.unequipItem(id); }, (counter + 1) * 2000);
        }

        for (ei = 0; ei < el; ei++) {
            var chId = equipped_items[ei];
            unequipLoop(ei, chId);
        }

        setTimeout(function () { alert("all champ items unequipped") }, el * 2000 + 2000);
    },

    unequipItem: function(chId) {
        var t = Tabs.champPresets;
        CM.ChampionManager.unequipItem(chId);
        t.paintTags();
    },

    equipItem: function(chId) {
        CM.ChampionManager.equipItem(chId);
    },

    clearPresetTags: function (presetIndex) {
        var t = Tabs.champPresets;
        var preset = getChampPresetObject(parseInt(presetIndex));
        for (var p in preset) delete preset[p];
        SAVESTrChOChampPresetData();
        t.paintTags();
    },

    clearAllPresetTagItems: function () {
        var t = Tabs.champPresets;
        if (!confirm('Are you sure you want to clear all preset tag items?')) return;
        for (i = 1; i < STrChOMaxChampions + 1; i++) t.clearPresetTags(i);
    },

    equipPresetTags: function (presetIndex) {
        var t = Tabs.champPresets;

        var equipLoop = function (id) { return function() { t.equipItem(id); }; }
        var unequipLoop = function (id) { return function() { t.unequipItem(id) };  }

        var c = 1;

        var championID = Seed.champion.champions[presetIndex-1].championId;// = 11007
        var equipped_items = [];
        for (chId in uW.kocChampionItems) {
            if (uW.kocChampionItems[chId].equippedTo != championID) continue;
            equipped_items.push(chId);
        }
        var el = equipped_items.length;
        if (el > 0) {
            for (ei = 0; ei < el; ei++) {
                var chId = equipped_items[ei];
                setTimeout(unequipLoop(chId), c * 2000);
                c += 1;
            }
        }

        var preset = getChampPresetObject(parseInt(presetIndex));
        for (var p in preset) {
            setTimeout(equipLoop(p), c * 2000);
            c += 1;
        }

        setTimeout(function () { alert("all champ items equipped") }, c * 2000 + 2000);
    },

    copyPresetTags: function (sourcePresetNumber, destinationPresetNumber, presetName) {
        var pSource = getChampPresetObject(parseInt(sourcePresetNumber));
        var pDestination = getChampPresetObject(parseInt(destinationPresetNumber));
        for (var p in pDestination) delete pDestination[p];
        for (var p in pSource) pDestination[p] = true;
        STrChOChampPresetData.presetNames[destinationPresetNumber-1] = presetName + " (copy)";
        SAVESTrChOChampPresetData();
    },

    addPresetTags: function (presetIndex) {  //presetIndex should be passed in as base 1 to index into the presetTaggedItems array
        var t = Tabs.champPresets;

        var preset = getChampPresetObject(parseInt(presetIndex));

        var championID = Seed.champion.champions[presetIndex-1].championId;// = 11007

        var equipped_items = [];

        for (chId in uW.kocChampionItems) {
            if (uW.kocChampionItems[chId].equippedTo != championID) continue;
            equipped_items.push(chId);
        }

        if ( equipped_items.length == 0 ) return;

        for (var p in preset) delete preset[p];

        for (ei = 0; ei < equipped_items.length; ei++) {
            var chId = equipped_items[ei];
            preset[chId] = true;
            SAVESTrChOChampPresetData();
        }

        t.paintTags();

    },

    paintTags: function () {
        for (ii in uW.kocChampionItems) {
            $("div#" + ii + ".champItem").children(".ioverlay").children(".tagBorderChamp").remove();
            $("div#" + ii + ".champItem").children(".ioverlay").children(".presetBorderChamp").remove();
            $("div#" + ii + ".champItem").children(".ioverlay").children(".activeBorderChamp").remove();
            if ( STrChOChampPresetData.taggedItems[ii] ) {
                $("div#" + ii + ".champItem").children(".ioverlay").prepend("<div class='tagBorderChamp'></div>");
            }
            $("div#" + ii + ".equipSelected ").children(".ioverlay").prepend("<div class='activeBorderChamp'></div>");
            if ( STrChOChampPresetData.taggedItems01[ii] || STrChOChampPresetData.taggedItems02[ii] || STrChOChampPresetData.taggedItems03[ii] || STrChOChampPresetData.taggedItems04[ii] ) {
                $("div#" + ii + ".champItem").children(".ioverlay").prepend("<div class='presetBorderChamp'></div>");
            }
        }

        $("#itemInvetory div").removeClass('STrChOBlueBorder');
        $("#itemInvetory div").removeClass('STrChOYellowBorder');

        for (ii in STrChOChampQueueData.list) {
            var list_item = STrChOChampQueueData.list[ii];
            if (!list_item) continue;
            if (list_item.status != "complete") {
                var id = list_item.item;
                if (list_item.action == "upgrade") $("div#" + id + ".champItem").addClass('STrChOBlueBorder');
                if (list_item.action == "enhance") $("div#" + id + ".champItem").addClass('STrChOYellowBorder');
            }

        }

    },

    removeAllTagItems: function () {
        var t = Tabs.champPresets;
        var taggedReverse = [];
        for (k in STrChOChampPresetData.taggedItems) taggedReverse.push(k);
        var len = taggedReverse.length;
        while (len--) {
            var chID = taggedReverse[len];
            delete STrChOChampPresetData.taggedItems[chID];
        }
        SAVESTrChOChampPresetData();
        t.paintTags();
    },

    removeTagItem: function (itemId) {
        var t = Tabs.champPresets;
        if (STrChOChampPresetData.taggedItems[itemId]) {
            delete STrChOChampPresetData.taggedItems[itemId];
            SAVESTrChOChampPresetData();
        }
        t.paintTags();
    },

    addAllTagItems: function () {
        var t = Tabs.champPresets;
        t.removeAllTagItems();
        for (chId in uW.kocChampionItems) {
            STrChOChampPresetData.taggedItems[chId] = true;
        }
        SAVESTrChOChampPresetData();
        t.paintTags();
    },

    addTagItem: function (itemId) {
        var t = Tabs.champPresets;
        STrChOChampPresetData.taggedItems[itemId] = true;
        SAVESTrChOChampPresetData();
        t.paintTags();
    },


}

Tabs.champPreview = {
	tabOrder: 207,
	tabLabel: 'PREVIEW',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL PREVIEW',
    champItemNamesForPreview: {1: 'weapon', 2: 'chest', 3: 'helm', 4: 'boots', 5: 'shield', 6: 'ring1', 7: 'ring2', 8: 'pendant', 9: 'cloak'},
    champItemTypesForPreview: {'weapon': 1, 'chest': 2, 'helm':3, 'boots':4, 'shield': 5, 'ring1': 6, 'ring2': 7, 'pendant': 8, 'cloak': 9},
    lastRing1: 0,
    lastRing2: 0,

	init: function (div) {
		var t = Tabs.champPreview;
		t.mydiv = div;
	},

	hide: function () {},

	show: function () {
		var t = Tabs.champPreview;

        var presetsTagList = "";
        if (STrChOMaxChampions != 0)  {
            for (var i = 1; i < STrChOMaxChampions + 1; i++) {
                presetsTagList += '<option value="' + i + '">' + i + ' (' + STrChOChampPresetData.presetNames[i-1] + ')</option>';
            }
        }

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

        m += '<table>';
        m += '<tr>';
        m += '<td colspan=3>';
        m += '<input type=button class=STrChOButton value="Reset" id=STrChOChampPreviewReset>&nbsp;&nbsp;||&nbsp;&nbsp;';
//        m += '<input type=button value="Equip Now" id=chPreviewEquip><font color=black><b>(5 sec per card to load)</b></font>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton value="Post Stats to Chat" id=STrChOChampPreviewPost>&nbsp;';
        m += '<input type=button class=STrChOButton value="Export to Excel" id=STrChOChampPreviewExcel>&nbsp;';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Export To Text" id=STrChOChampPreviewExport>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton value="Load Text Export" id=STrChOChampPreviewExportLoad>';
        m += '<input type=button class=STrChOButton value="Browse..." id=STrChOChampPreviewExportLoadItemTrigger onclick="document.getElementById(\'STrChOChampPreviewExportLoadItem\').click()">';
        m += '<input hidden id=STrChOChampPreviewExportLoadItem type=file>';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Load Champ Preset" id=STrChOChampPreviewLoadPreset>&nbsp;<select class=STrChOSelect style="width:25%;" id=STrChOChampPreviewLoadPresetValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Copy To" id=STrChOChampPreviewCopyTo><b>&nbsp;Preset Tag&nbsp;</b><select class=STrChOSelect style="width:25%;" id=STrChOChampPreviewCopyToValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button class=STrChOButton value="Load Champ From" id=STrChOChampPreviewLoadPresetTag><b>&nbsp;Preset Tag&nbsp;</b><select class=STrChOSelect style="width:25%;" id=STrChOChampPreviewLoadPresetTagValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '</td>';
        m += '</tr>';
        m += '</tr>';
        m += '</table>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;PREVIEW STATS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="position: static; width: 100%; height: 380px; overflow-x: auto; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td>';
        m += '<div id=STrChOChampPreviewDetails></div>';
        m += '</td></tr>';
        m += '</table>';
        m += '</div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;PREVIEW CARDS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="position: static; width: 100%; height: 380px; overflow-x: auto; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';

        m += '<tr>';

        var idx = 0;
        for (var itemIdx in t.champItemNamesForPreview) {
            if (idx % 3 == 0) m += '</tr><tr>';
            m += '<td width=33% valign=top>';
            m += '<table>';
            m += '<tr><td><b>' + t.champItemNamesForPreview[itemIdx].toUpperCase() + '<b></td></tr>';
            m += '<tr><td>';
            m += '<select class=STrChOSelect id=STrChOChampPreviewValue' + t.champItemNamesForPreview[itemIdx] + ' style="white-space:nowrap;display:inline-block;max-width: 150px;"></select>';
            m += '</td></tr>';
            m += '<tr><td><div id=STrChOChampPreviewCard' + t.champItemNamesForPreview[itemIdx] + '></div></td></tr>';
            m += '</table>';
            m += '</td>';
            idx += 1;
        }
        m += '</tr>';


        m += '</table>';
        m += '</div>';

        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }
        t.buildChampPreviewValueDisplay();

        for (var idx in t.champItemNamesForPreview) {

            document.getElementById('STrChOChampPreviewCard' + t.champItemNamesForPreview[idx]).addEventListener('click', function(A) {
                A.stopPropagation();
                var champType = this.id.split('STrChOChampPreviewCard')[1];
                var STrChOPreviewValue = document.getElementById('STrChOChampPreviewValue' + champType);
                var champId = STrChOPreviewValue.value;
                if (champId == 0) return;
                var champItem = uW.kocChampionItems[champId];
                if (!champItem || champItem ==0) return;
                CardContextMenu(this, champItem, true);
            }, false);

            document.getElementById('STrChOChampPreviewValue' + t.champItemNamesForPreview[idx]).addEventListener('change', function(A) {
                var champ_Type = this.id.split('STrChOChampPreviewValue')[1];
                var chId = this.value;
                t.loadChampPreviewCard(chId, champ_Type);
            }, false);

            document.getElementById('STrChOChampPreviewValue' + t.champItemNamesForPreview[idx]).addEventListener('keyup', function(A) {
                var champ_Type = this.id.split('STrChOChampPreviewValue')[1];
                var chId = this.value;
                t.loadChampPreviewCard(chId, champ_Type);
            }, false);

        }

        document.getElementById('STrChOChampPreviewDetails').innerHTML = t.getPreviewChampDetails();

        document.getElementById('STrChOChampPreviewReset').addEventListener('click', function () {
            t.resetPreview();
            t.buildChampPreviewValueDisplay();
        }, false);

        document.getElementById('STrChOChampPreviewExcel').addEventListener('click', function() {
            if (STrChOChampPresetData.previewChamp.length > 0 )
                ExportChampToExcel(true);
            else
                alert('Nothing To Export');
        }, false);

        document.getElementById('STrChOChampPreviewPost').addEventListener('click', function () {
            if (STrChOChampPresetData.previewChamp.length == 0) return;
            t.postPreviewChampDetails();
        }, false);

        document.getElementById('STrChOChampPreviewExport').addEventListener('click', function() {
            uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(STrChOChampPresetData.previewChamp));
            newWindow = window.open(uriContent, 'file.txt');
        }, false);

        document.getElementById('STrChOChampPreviewExportLoad').addEventListener('click', function () {
            var fileInput = document.getElementById("STrChOChampPreviewExportLoadItem");
            var files = fileInput.files;
            if (files.length==0) {
                alert('Please Select A File');
                return;
            }
            var file = files[0];

            var reader = new FileReader();

            reader.onload = function (e) {
				var output = e.target.result;
				STrChOChampPresetData.previewChamp = JSON.parse(output);
                SAVESTrChOChampPresetData();
                t.show();
                alert('Preview Champ Now Loaded From File');
            };
            reader.readAsText(file);
        }, false);

        document.getElementById('STrChOChampPreviewLoadPresetTag').addEventListener('click', function () {
            var presetNum = document.getElementById('STrChOChampPreviewLoadPresetTagValue').value;
            var presetTag = getChampPresetObject(parseInt(presetNum));
            t.resetPreview();
            for (var p in presetTag) t.loadChampPreviewCard(p)//STrChOChampPresetData.previewChamp[p] = true;
        }, false);

        document.getElementById('STrChOChampPreviewCopyTo').addEventListener('click', function () {
            var presetNum = document.getElementById('STrChOChampPreviewCopyToValue').value;
            var presetTag = getChampPresetObject(parseInt(presetNum));
            for (var p in presetTag) delete presetTag[p];
            for (var idx = 0; idx < STrChOChampPresetData.previewChamp.length; idx++) {
                presetTag[STrChOChampPresetData.previewChamp[idx]] = true;
            }
            STrChOChampPresetData.presetNames[presetNum] = "PREVIEW";
            document.getElementById('STrChOChampPresetName' + presetNum).value = "PREVIEW";
            SAVESTrChOChampPresetData();
            t.show();
        }, false);

        document.getElementById('STrChOChampPreviewLoadPreset').addEventListener('click', function () {
            var t = Tabs.champPreview;

            var presetIndex = document.getElementById('STrChOChampPreviewLoadPresetValue').value;

            var championID = Seed.champion.champions[presetIndex-1].championId;// = 11007
            var equipped_items = [];
            for (chId in uW.kocChampionItems) {
                if (uW.kocChampionItems[chId].equippedTo != championID) continue;
                equipped_items.push(chId);
            }
            var el = equipped_items.length;

            if (el > 0) {
                for (ei = 0; ei < el; ei++) {
                    var chId = equipped_items[ei];
                    champItem = uW.kocChampionItems[chId];
                    t.loadChampPreviewCard(chId);
                }
            }
        }, false);

	},

    buildChampPreviewValueDisplay: function () {
        var t = Tabs.champPreview;
        var elemSelect = null;

        for (var champType in t.champItemNamesForPreview) { //fill the default selection "--Items--"
            elemSelect = document.getElementById('STrChOChampPreviewValue' + t.champItemNamesForPreview[champType]);
            elemSelect.innerHTML = '';
            elemSelect.options.add(new Option('--Items--', '0'));
        }

        for (var champId in uW.kocChampionItems) { //fill with all the champ cards
            var champItem = uW.kocChampionItems[champId];
            if (champItem.type == 6) {
                elemSelect = document.getElementById('STrChOChampPreviewValuering1');
                elemSelect.options.add(new Option(champItem.name, champId));
                elemSelect = document.getElementById('STrChOChampPreviewValuering2');
                elemSelect.options.add(new Option(champItem.name, champId));
            } else {
                elemSelect = document.getElementById('STrChOChampPreviewValue' + t.champItemNamesForPreview[champItem.type]);
                elemSelect.options.add(new Option(champItem.name, champId));
            }
        }

        for (var idx = 0; idx < STrChOChampPresetData.previewChamp.length; idx++) {  //select and display the champion cards in the preview preset
            if (STrChOChampPresetData.previewChamp[idx] != 0) {
                var champItem = uW.kocChampionItems[STrChOChampPresetData.previewChamp[idx]];
                if (champItem == null || !champItem) {
                    STrChOChampPresetData.previewChamp[idx] = 0;
                    SAVESTrChOChampPresetData();
                    continue;
                }
                if (idx == STrChORing1) t.lastRing1 = STrChOChampPresetData.previewChamp[idx];
                if (idx == STrChORing2) t.lastRing2 = STrChOChampPresetData.previewChamp[idx];
                var champCard = BuildChampCard(champItem);
                document.getElementById('STrChOChampPreviewValue' + t.champItemNamesForPreview[idx]).value = STrChOChampPresetData.previewChamp[idx];
                document.getElementById('STrChOChampPreviewCard' + t.champItemNamesForPreview[idx]).innerHTML = champCard;
            }
        }
    },

    postPreviewChampDetails: function () {
        var t = Tabs.champPreview;
        var previewPreset = [];
        for (var idx = 0; idx < STrChOChampPresetData.previewChamp.length; idx++) {
            if (STrChOChampPresetData.previewChamp[idx] != 0) previewPreset.push(STrChOChampPresetData.previewChamp[idx]);
        }

        var stringPreviewChamp = GenerateChampPresetEffectsString(previewPreset, true);
        if (stringPreviewChamp == "") {
            return;
        } else {
            var table = stringPreviewChamp.split("</div><div>");
            stringPreviewChamp = table.join("||");
            stringPreviewChamp = stringPreviewChamp.replace("<div>", ":::. |CHAMP PREVIEW STATS:||");
            stringPreviewChamp = stringPreviewChamp.replace("</div>", "");
            stringPreviewChamp = stringPreviewChamp.replace("<b>","").replace("<i>","").replace("</i>","").replace("</b>","").replace("<b>","").replace("<i>","").replace("</i>","").replace("</b>","");
            sendChat(stringPreviewChamp);
        }
        return;

    },

    resetPreview: function () {
        var t = Tabs.champPreview;

        for (var idx = 0; idx < STrChOChampPresetData.previewChamp.length; idx++) STrChOChampPresetData.previewChamp[idx] = 0;
        SAVESTrChOChampPresetData();

        for (var champType in t.champItemNamesForPreview) {
            document.getElementById('STrChOChampPreviewValue' + t.champItemNamesForPreview[champType]).value = 0;
            document.getElementById('STrChOChampPreviewCard' + t.champItemNamesForPreview[champType]).innerHTML = '';
        }

        document.getElementById('STrChOChampPreviewDetails').innerHTML = t.getPreviewChampDetails();
    },

    clearChampPreviewCard: function(champId) {
        var t = Tabs.champPreview;
        for (var idx = 0; idx < STrChOChampPresetData.previewChamp.length; idx++)
            if (STrChOChampPresetData.previewChamp[idx] == champId) {
                STrChOChampPresetData.previewChamp[idx] = 0;
                SAVESTrChOChampPresetData();
                for (var item in t.champItemTypesForPreview) {
                    if (document.getElementById('STrChOChampPreviewValue' + item).value == champId) {
                        document.getElementById('STrChOChampPreviewValue' + item).value = 0;
                        document.getElementById('STrChOChampPreviewCard' + item).innerHTML = '';
                        if (item == 'ring1') t.lastRing1 = 0;
                        if (item == 'ring2') t.lastRing2 = 0;

                        if (item == 'ring1' || item == 'ring2') {
                            var elemSelect = document.getElementById('STrChOChampPreviewValuering1');
                            for (var i = 0; i < elemSelect.length; i++)
                                if (elemSelect.options[i].value == champId) $(elemSelect).remove(i);
                            elemSelect = document.getElementById('STrChOChampPreviewValuering2');
                            for (var i = 0; i < elemSelect.length; i++)
                                if (elemSelect.options[i].value == champId) $(elemSelect).remove(i);
                        } else {
                            var elemSelect = document.getElementById('STrChOChampPreviewValue' + item);
                            for (var i = 0; i < elemSelect.length; i++)
                                if (elemSelect.options[i].value == champId) $(elemSelect).remove(i);
                        }
                        return;
                    }
                }
                return;
            }

    },

    loadChampPreviewCard: function(champId, champTypeName) {
        var t = Tabs.champPreview;
        if (typeof(champTypeName) == 'undefined') champTypeName = '';
        if (champId == 0 && champTypeName == "") return;

        var t = Tabs.champPreview;
        var champCard = '';
        if (champId == 0) {
            document.getElementById('STrChOChampPreviewCard' + champTypeName).innerHTML = champCard;
            document.getElementById('STrChOChampPreviewValue' + champTypeName).value = champId;
            STrChOChampPresetData.previewChamp[t.champItemTypesForPreview[champTypeName]] = champId;
        } else { //champ id is NOT 0, so load the champ
            var champItem = uW.kocChampionItems[champId];
            if (!champItem || champItem ==0) return;
            champCard = BuildChampCard(champItem);

            if (champTypeName != "") { //champ type name is known
                if (champTypeName == 'ring1') {
                    if (document.getElementById('STrChOChampPreviewValuering2').value == champId) {
                        document.getElementById('STrChOChampPreviewValuering1').value = t.lastRing1;
                    } else {
                        document.getElementById('STrChOChampPreviewCardring1').innerHTML = champCard;
                        document.getElementById('STrChOChampPreviewValuering1').value = champId;
                        STrChOChampPresetData.previewChamp[t.champItemTypesForPreview[champTypeName]] = champId;
                        t.lastRing1 = champId;
                    }
                } else if (champTypeName == 'ring2') {
                    if (document.getElementById('STrChOChampPreviewValuering1').value == champId) {
                        document.getElementById('STrChOChampPreviewValuering2').value = t.lastRing2;
                    } else {
                        document.getElementById('STrChOChampPreviewCardring2').innerHTML = champCard;
                        document.getElementById('STrChOChampPreviewValuering2').value = champId;
                        STrChOChampPresetData.previewChamp[t.champItemTypesForPreview[champTypeName]] = champId;
                        t.lastRing2 = champId;
                    }
                } else {
                    document.getElementById('STrChOChampPreviewCard' + champTypeName).innerHTML = champCard;
                    document.getElementById('STrChOChampPreviewValue' + champTypeName).value = champId;
                    STrChOChampPresetData.previewChamp[t.champItemTypesForPreview[champTypeName]] = champId;
                }
            } else { //champ type name is not known so we get it from the champ.type
                if (champItem.type != 6) { //champ is not a ring
                    champTypeName = t.champItemNamesForPreview[champItem.type];
                    document.getElementById('STrChOChampPreviewCard' + champTypeName).innerHTML = champCard;
                    document.getElementById('STrChOChampPreviewValue' + champTypeName).value = champId;
                    STrChOChampPresetData.previewChamp[t.champItemTypesForPreview[champTypeName]] = champId;
                } else { //most of the time this is coming from the "Send to Preview" option from the context menu
                    if (document.getElementById('STrChOChampPreviewValuering1').value == champId) return;
                    if (document.getElementById('STrChOChampPreviewValuering2').value == champId) return;

                    if (document.getElementById('STrChOChampPreviewValuering1').value == 0) { //if ring1 is empty load it here
                        document.getElementById('STrChOChampPreviewValuering1').value = champId;
                        document.getElementById('STrChOChampPreviewCardring1').innerHTML = champCard;
                        STrChOChampPresetData.previewChamp[t.champItemTypesForPreview['ring1']] = champId;
                        t.lastRing1 = champId;
                    } else if (document.getElementById('STrChOChampPreviewValuering2').value == 0) { //if ring1 was full and ring2 is empty load it here
                        document.getElementById('STrChOChampPreviewValuering2').value = champId;
                        document.getElementById('STrChOChampPreviewCardring2').innerHTML = champCard;
                        STrChOChampPresetData.previewChamp[t.champItemTypesForPreview['ring2']] = champId;
                        t.lastRing2 = champId;
                    } else {  //if both ring1 and ring2 are full, overwrite ring1
                        document.getElementById('STrChOChampPreviewValuering1').value = champId;
                        document.getElementById('STrChOChampPreviewCardring1').innerHTML = champCard;
                        STrChOChampPresetData.previewChamp[t.champItemTypesForPreview['ring1']] = champId;
                        t.lastRing1 = champId;
                    }
                }
            }
        }
        SAVESTrChOChampPresetData();
        document.getElementById('STrChOChampPreviewDetails').innerHTML = t.getPreviewChampDetails();
    },

    getPreviewChampDetails: function () {
        var t = Tabs.champPreview;
        var previewPreset = [];
        for (var idx = 0; idx < STrChOChampPresetData.previewChamp.length; idx++)
            if (STrChOChampPresetData.previewChamp[idx] != 0) previewPreset.push(STrChOChampPresetData.previewChamp[idx]);

        var stringPreviewChamp = GenerateChampPresetEffectsString(previewPreset, true);//GenerateThronePresetEffectsString(previewPreset);
        if (stringPreviewChamp == "") {
            stringPreviewChamp = "No Stats To Preview";
        } else {
            stringPreviewChamp = "<b>PREVIEW STATS:</b>\n" + stringPreviewChamp;
        }
        return stringPreviewChamp;
    },
}

Tabs.champCompare = {
	tabOrder: 208,
	tabLabel: 'COMPARE',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL COMPARE',

	init: function (div) {
		var t = Tabs.champCompare;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div>';
        m += '<center>';
        m += '<table>';

        m += '<tr>';
        m += '<td align=center><b>CARD 1</b></td>';
        m += '<td align=center><b>CARD 2</b></td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td>';
        m += '<b>Item Type:</b><select class=STrChOSelect id=STrChOChampCompareType1 style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var champType in champItemNames) m += '<option value="' + champType + '">' + champItemNames[champType].capitalizeFirstLetter() + '</option>';
        m += '</select>';
        m += '</td>';
        m += '<td>';
        m += '<b>Item Type:</b><select class=STrChOSelect id=STrChOChampCompareType2 style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var champType in champItemNames) m += '<option value="' + champType + '">' + champItemNames[champType].capitalizeFirstLetter() + '</option>';
        m += '</select>';
        m += '</td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td>';
        m += '<b>Champ Item:</b><br/><select class=STrChOSelect id=STrChOChampCompareId1 style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (var champId in uW.kocChampionItems) m += '<option value="' + champId + '">' + uW.kocChampionItems[champId].name + ' </option>';
        m += '</select>';
        m += '</td>';
        m += '<td>';
        m += '<b>Champ Item:</b><br/><select class=STrChOSelect id=STrChOChampCompareId2 style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (var champId in uW.kocChampionItems) m += '<option value="' + champId + '">' + uW.kocChampionItems[champId].name + ' </option>';
        m += '</select>';
        m += '</td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td>';
        m += '<div id=STrChOChampCompareCard1></div>';
        m += '</td>';
        m += '<td>';
        m += '<div id=STrChOChampCompareCard2></div>';
        m += '</td>';
        m += '</tr>';

        m += '</table>';
        m += '</center>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOChampCompareId1').addEventListener('change', function () { t.loadCard(this, 'STrChOChampCompareCard1'); }, false);

        document.getElementById('STrChOChampCompareId2').addEventListener('change', function () { t.loadCard(this, 'STrChOChampCompareCard2'); }, false);

        document.getElementById('STrChOChampCompareId1').addEventListener('keyup', function () { t.loadCard(this, 'STrChOChampCompareCard1'); }, false);

        document.getElementById('STrChOChampCompareId2').addEventListener('keyup', function () { t.loadCard(this, 'STrChOChampCompareCard2'); }, false);

        document.getElementById('STrChOChampCompareType1').addEventListener('change', function () { t.filterItems(this, 'STrChOChampCompareId1', 'STrChOChampCompareCard1'); }, false);

        document.getElementById('STrChOChampCompareType2').addEventListener('change', function () { t.filterItems(this, 'STrChOChampCompareId2', 'STrChOChampCompareCard2'); }, false);

        document.getElementById('STrChOChampCompareType1').addEventListener('keyup', function () { t.filterItems(this, 'STrChOChampCompareId1', 'STrChOChampCompareCard1'); }, false);

        document.getElementById('STrChOChampCompareType2').addEventListener('keyup', function () { t.filterItems(this, 'STrChOChampCompareId2', 'STrChOChampCompareCard2'); }, false);

    },

    sendToCompare: function (Id) {
        var t = Tabs.champCompare;
        var champItem = uW.kocChampionItems[Id];
        var card1 = document.getElementById('STrChOChampCompareId1');
        var card2 = document.getElementById('STrChOChampCompareId2');
        var obj = '';
        if (card1.value == 0)
            obj = '1';
        else if (card2.value == 0)
            obj = '2';
        else
            obj = '1';

        document.getElementById('STrChOChampCompareType' + obj).value = champItem.type;
        t.filterItems(document.getElementById('STrChOChampCompareType' + obj), ('STrChOChampCompareId' + obj), ('STrChOChampCompareCard' + obj));
        document.getElementById('STrChOChampCompareId' + obj).value = Id;
        t.loadCard(document.getElementById('STrChOChampCompareId' + obj), ('STrChOChampCompareCard' + obj));
    },

    loadCard: function (objectItem, objectName) {
        var div = document.getElementById(objectName);
        if (objectItem.value == 0)
            div.innerHTML = '';
        else
            div.innerHTML = BuildChampCard(uW.kocChampionItems[objectItem.value]);
    },

    filterItems: function (objectItem, objectIdName, objectName) {
        document.getElementById(objectName).innerHTML = '';
        var select = document.getElementById(objectIdName);
        select.value = 0;
        var m = '<option value="0">--Items--</option>';
        if (objectItem.value == 0) {
            for (var champId in uW.kocChampionItems) {
                m += '<option value="' + champId + '">' + uW.kocChampionItems[champId].name + '</option>';
            }
        } else {
            for (var champId in uW.kocChampionItems) {
                if (uW.kocChampionItems[champId].type == objectItem.value)
                    m += '<option value="' + champId + '">' + uW.kocChampionItems[champId].name + '</option>';
            }
        }
        select.innerHTML = m;
    },


	hide: function () {},

	show: function () {},
}

Tabs.champUniques = {
	tabOrder: 209,
	tabLabel: 'UNIQUES',
	tabColor: 'brown',
    tabHeader: 'CHAMP HALL UNIQUES',
    UniqueItems : null,
    selectedCard: 0,
    selectedType: 0,
    selectedLevel: 1,

	init: function (div) {
		var t = Tabs.champUniques;
		t.mydiv = div;

        var UniqueItems = {};
        eval(GM_getResourceText("champion_uniques"));
        t.UniqueItems = UniqueItems;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*2.5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

        m += '<center><table>';
        m += '<tr><td><div style="max-width:100%;"><b>Item Type:</b><select class=STrChOSelect id=STrChOChampUniqueType style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var champType in champItemNames) m += '<option value="' + champType + '">' + champItemNames[champType].capitalizeFirstLetter() + '</option>';
        m += '</select></div></td></tr>';

        m += '<tr><td><div style="max-width:100%;"><b>Champ Item:</b><br/><select class=STrChOSelect id=STrChOChampUnique style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (Id in t.UniqueItems) {
            var champItem = t.UniqueItems[Id];
            if (champItem == null || !champItem) continue;
            m += '<option value="' + Id + '">' + champItem.Name + ' </option>';
        }
        m += '</select></div></td></tr>';

        m += '<tr><td><div style="max-width:100%;"><b>Level:</b><select class=STrChOSelect id=STrChOChampUniqueLevel style="width: 40%;">';
        m += '<option value="1" selected>+1</option>';
        for (lvl = 2; lvl < STrChOMaxChampLevel + 1; lvl++) m += '<option value="' + lvl + '">+' + lvl + '</option>';
        m += '</select></div></td></tr>';

        m += '<tr><td><div id=STrChOChampUniqueCard></div></td></tr>';

        m += '</table>';

        m += '</div>';
		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOChampUniqueType').addEventListener('change', function () {
            t.selectedType = document.getElementById('STrChOChampUniqueType').value;
            t.selectedCard = 0;
            t.FilterUniques();
            document.getElementById('STrChOChampUniqueCard').innerHTML = '';
        }, false);

        document.getElementById('STrChOChampUnique').addEventListener('change', function () {
            t.selectedCard = document.getElementById('STrChOChampUnique').value;
            if (t.selectedCard != 0) t.SwitchUnique();
        }, false);

        document.getElementById('STrChOChampUniqueLevel').addEventListener('change', function () {
            t.selectedLevel = document.getElementById('STrChOChampUniqueLevel').value;
            if (t.selectedCard != 0) t.SwitchUnique();
        }, false);

	},

	hide: function () {},

	show: function () {},

    FilterUniques: function (cardType) {
        var t = Tabs.champUniques;
        var champList = document.getElementById('STrChOChampUnique');
        champList.options.length = 0;
        var champOption = document.createElement('option');
        champOption.text = '--Items--';
        champOption.value = 0;
        champList.add(champOption);
        for (Id in t.UniqueItems) {
            var champItem = t.UniqueItems[Id];
            if (champItem == null || !champItem) continue;
            if (champItem.Type == t.selectedType || t.selectedType == 0) {
                var champOption = document.createElement('option');
                champOption.text = champItem.Name;
                champOption.value = Id;
                champList.add(champOption);
            }
        }
    },

    SwitchUnique: function () {
        var t = Tabs.champUniques;
        var div = document.getElementById('STrChOChampUniqueCard');
        var m = ConvertUniqueAndBuildChampCard(t.selectedCard, t.selectedLevel);
        m += t.GetUniqueInventory(t.selectedCard);
        div.innerHTML = m;
        var STrChOChampUseUnique = document.getElementById('STrChOChampUseUnique');
        if (!STrChOChampUseUnique) return;
        STrChOChampUseUnique.addEventListener('click', function() {
            var uniqueId = this.getAttribute('uid');
            var uniqueCount = parseInt(document.getElementById('STrChOChampUniqueCount').innerHTML);
            uniqueCount--;
            document.getElementById('STrChOChampUniqueCount').innerHTML = uniqueCount;
            CM.ItemController.use(uniqueId);
        }, false);
    },


    GetUniqueInventory: function (uniqueId) {
        var m = '<br><b>Champ Hall</b><br>';
        var champitems = {};
        for (champId in uW.kocChampionItems) {
            var champItem = uW.kocChampionItems[champId];
            if (champItem.unique == uniqueId) {
                if (champitems[champItem.level]) {
                    champitems[champItem.level]++;
                } else {
                    champitems[champItem.level] = 1;
                }
            }
        }
        var gotitem = false;
        for (lvl in champitems) {
            gotitem = true;
            m += 'You have '+champitems[lvl]+' at level '+lvl+'<br>';
        }
        if (!gotitem) m += 'You have none in your throne room.<br>';

        m += '<br><b>Inventory</b><br>';
        var inventory = Seed.items['i'+uniqueId];
        m += 'You have <div class=divNoWrap id=STrChOChampUniqueCount>'+(inventory?inventory:'0')+'</div> in your inventory.';
        if ((inventory?inventory:0) != 0) m += '<br><b><a id=STrChOChampUseUnique uid="' + uniqueId + '">Add To Champ Hall</a></b>';
        return m;
    },

}

Tabs.STrChOLog = {
	tabOrder: 300,
	tabLabel: 'LOGS',
	tabColor: 'blue',
    tabHeader: 'LOGGING RECORDS',

	init: function (div) {
		var t = Tabs.STrChOLog;
		t.mydiv = div;
       //t.buildLogDisplay();
	},

	hide: function () {},

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

	buildLogDisplay: function () {
		var t = Tabs.STrChOLog;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div style="margin-top: 5px; margin-bottom: 5px;">';
        m += '&nbsp;&nbsp;Max Log Entries Per Section <input type=textbox class=STrChOTextbox id=STrChOLogMaxEntries value="' + STrChOLogData.maxEntries + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        m += '<input type=button class=STrChOButton id=STrChOLogClear value="Clear All Logs">';
        m += '</div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SUCCESS LOG&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="height: ' + (dlgHeight - 140) + 'px; width: ' + (dlgWidth - dlgWidthMenu - dlgWidthOffset) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table class=STrChOSectionTable id=STrChOSuccessLog>';
        if (STrChOLogData.successLog.length == 0) {
            m += '<tr><td>NO LOG DATA</td></tr>';
        } else {
            m += '<tr><td><input id=STrChOClearSuccessLog type=button class=STrChOButton value="Clear Success Log"></td></tr>';
            for (logIndex=0; logIndex < STrChOLogData.successLog.length; logIndex++) {
                var logVar = STrChOLogData.successLog[logIndex];
                var logDate = logVar.split(",")[0];
                var logMsg = logVar.split(",")[1];
                m += '<tr>';
                m += '<td width=20%>' + logDate + '</td>';
                m += '<td width=80%>' + logMsg + '</td>';
                m += '</tr>';
            }
        }
        m += '</table>';
        m += '</div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;ACTION LOG&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="height: ' + (dlgHeight - 140) + 'px; width: ' + (dlgWidth - dlgWidthMenu - dlgWidthOffset) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table class=STrChOSectionTable id=STrChOActionLog>';
        if (STrChOLogData.actionLog.length == 0) {
            m += '<tr><td>NO LOG DATA</td></tr>';
        } else {
            m += '<tr><td><input id=STrChOClearActionLog type=button class=STrChOButton value="Clear Action Log"></td></tr>';
            for (logIndex=0; logIndex < STrChOLogData.actionLog.length; logIndex++) {
                var logVar = STrChOLogData.actionLog[logIndex];
                var logDate = logVar.split(",")[0];
                var logMsg = logVar.split(",")[1];
                m += '<tr>';
                m += '<td width=20%>' + logDate + '</td>';
                m += '<td width=80%>' + logMsg + '</td>';
                m += '</tr>';
            }
        }
        m += '</table>';
        m += '</div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SALVAGE LOG&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="height: ' + (dlgHeight - 140) + 'px; width: ' + (dlgWidth - dlgWidthMenu - dlgWidthOffset) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';
        m += '<table class=STrChOSectionTable id=STrChOSalvageLog>';
        if (STrChOLogData.salvageLog.length == 0) {
            m += '<tr><td>NO LOG DATA</td></tr>';
        } else {
            m += '<tr><td><input id=STrChOClearSalvageLog type=button class=STrChOButton value="Clear Salvage Log"></td></tr>';
            for (logIndex=0; logIndex < STrChOLogData.salvageLog.length; logIndex++) {
                var logVar = STrChOLogData.salvageLog[logIndex];
                var logDate = logVar.split(",")[0];
                var logMsg = logVar.split(",")[1];
                m += '<tr>';
                m += '<td width=20%>' + logDate + '</td>';
                m += '<td width=80%>' + logMsg + '</td>';
                m += '</tr>';
            }
        }
        m += '</table>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        if (document.getElementById('STrChOClearActionLog')) {
            document.getElementById('STrChOClearActionLog').addEventListener('click', function () {
                STrChOLogData.actionLog = [];
                SAVESTrChOLogData();
                t.buildLogDisplay();
            }, false);
        }

        if (document.getElementById('STrChOClearSuccessLog')) {
            document.getElementById('STrChOClearSuccessLog').addEventListener('click', function () {
                STrChOLogData.successLog = [];
                SAVESTrChOLogData();
                t.buildLogDisplay();
            }, false);
        }

        if (document.getElementById('STrChOClearSalvageLog')) {
            document.getElementById('STrChOClearSalvageLog').addEventListener('click', function () {
                STrChOLogData.salvageLog = [];
                SAVESTrChOLogData();
                t.buildLogDisplay();
            }, false);
        }

        document.getElementById('STrChOLogMaxEntries').addEventListener('change', function () {
            STrChOLogData.maxEntries = parseInt(document.getElementById('STrChOLogMaxEntries').value);
            SAVESTrChOLogData();
            t.buildLogDisplay();
        }, false);

        document.getElementById('STrChOLogClear').addEventListener('click', function () {
            STrChOLogData.actionLog = [];
            STrChOLogData.salvageLog = [];
            STrChOLogData.successLog = [];
            SAVESTrChOLogData();
            t.buildLogDisplay();
        }, false);

	},

    removeLogEntry: function (logValue) {
        if (logValue == logValues.SUCCESS) {
            while (STrChOLogData.successLog.length >= STrChOLogData.maxEntries) STrChOLogData.successLog.pop();
        } else if (logValue == logValues.SALVAGE) {
            while (STrChOLogData.salvageLog.length >= STrChOLogData.maxEntries) STrChOLogData.salvageLog.pop();
        } else if (logValue == logValues.ACTION) {
            while (STrChOLogData.actionLog.length >= STrChOLogData.maxEntries) STrChOLogData.actionLog.pop();
        } else return;
    },

    addLogEntry: function (logValue, msg) {
        var t = Tabs.STrChOLog;
        if (logValue == logValues.SUCCESS) {
            if (STrChOLogData.successLog.length >= STrChOLogData.maxEntries) t.removeLogEntry(logValue);
            STrChOLogData.successLog.unshift(t.createTimeStamp() + "," + msg);
        } else if (logValue == logValues.SALVAGE) {
            if (STrChOLogData.salvageLog.length >= STrChOLogData.maxEntries) t.removeLogEntry(logValue);
            STrChOLogData.salvageLog.unshift(t.createTimeStamp() + "," + msg);
        } else if (logValue == logValues.ACTION) {
            if (STrChOLogData.actionLog.length >= STrChOLogData.maxEntries) t.removeLogEntry(logValue);
            STrChOLogData.actionLog.unshift(t.createTimeStamp() + "," + msg);
        } else return;
        SAVESTrChOLogData();
    },

    createTimeStamp: function () {
        var d = new Date();
        var ts = d.toDateString().substring(3,10) + " " + d.toTimeString().substring(0,8);
        return ts;
    },

}

Tabs.STrChOOptions = {
	tabOrder: 301,
	tabLabel: 'OPTIONS',
	tabColor: 'blue',
    tabHeader: 'STrChO OPTIONS',

	init: function (div) {
		var t = Tabs.STrChOOptions;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '<div class=STrChOSaveSettings id=STrChOOptionsSaveSettings title="Save Options Settings"></div><div class=STrChOLoadSettings id=STrChOOptionsLoadSettings title="Load Options Settings"></div></div>';


        m += '<table class=STrChOSectionTable>';
        m += '<tr><td width=100%><input class=STrChOCheckbox id=STrChODisableAnim type=checkbox ' + (STrChOGeneralOptions.disableAnim ? 'CHECKED ' : '') + '/> Disable Failure Animation (Big Red X) </td></tr>';
        m += '<tr><td><input class=STrChOCheckbox id=STrChODraggableThroneItems type=checkbox ' + (STrChOGeneralOptions.draggableThroneItems ? 'CHECKED ' : '') + '/> Enable Draggable Throne Room Items </td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOShowJewels type=checkbox ' + (STrChOGeneralOptions.showJewels ? 'CHECKED ' : '') + '/> Show Jewels Icon In Throne Room Inventory </td></tr> ';
        m += '</table>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;SALVAGER OPTIONS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';

        m += '<tr><td><b>Put Aetherstones: </b><div style="display: inline;" id=STrChOSalvageCity></div></td></tr>';
        m += '<tr><td><div style="white-space: pre;" ><input class=STrChOCheckbox id=STrChOSalvageAnyCity type=checkbox ' + (STrChOGeneralOptions.salvageAnyCity ? ' CHECKED' : '') + '> When Full, Put Aetherstones In Any City.</td></tr>';
        m += '<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Maximum Number Of Aetherstones: <input class=STrChOTextbox id=STrChOMaxStones type=text size=7 maxlength=7 value="' + STrChOGeneralOptions.maxStones + '"></div></td></tr>';
        m += '<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Overflow Method: <select class=STrChOSelect id=STrChOOverflow><option value="order" ' + (STrChOGeneralOptions.overflow=='order' ? 'SELECTED' : '') + '>City Order</option><option value="lowest" ' + (STrChOGeneralOptions.overflow=='lowest' ? 'SELECTED' : '') + '>Lowest City</option>  </select></td></tr>';
        m += '<tr><td><div>Load Throne Room Salvager Settings From Domain Number: <input class=STrChOTextbox id=STrChOThroneLoadDomain type=text size=3 maxlength=3 /><input class=STrChOButton id=STrChOThroneLoadDomainRules type=button value="Load"></div></td></tr>';
        m += '<tr><td><div>Load Champ Hall Salvager Settings From Domain Number: <input class=STrChOTextbox id=STrChOChampLoadDomain type=text size=3 maxlength=3 /><input class=STrChOButton id=STrChOChampLoadDomainRules type=button value="Load"></div></td></tr>';
        m += '<tr><td><div style="white-space: pre;" ><input class=STrChOCheckbox id=STrChOThroneSalvageUpgradeFirst type=checkbox ' + (STrChOThroneSalvageData.upgradeFirst ? ' CHECKED' : '') + '> Upgrade Items To +1 Before Deleting.</td></tr>';
        m += '<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Maximum Quality: <select class=STrChOSelect id=STrChOThroneUpgradeFirstQual>';
        for (qual = 0; qual < throneCardQualities.length; qual++) m += '<option value="' + qual + '" ' + (STrChOThroneSalvageData.upgradeFirstQual == qual ? 'SELECTED' : '') + '>' + throneCardQualities[qual].capitalizeFirstLetter() + '</option>';
        m += '</select> (Throne Room Only)</td></tr>';
        m += '<tr><td><div style="white-space: pre;" ><input class=STrChOCheckbox id=STrChOThroneSalvageUpgradeManual type=checkbox ' + (STrChOThroneSalvageData.upgradeManual ? ' CHECKED' : '') + '/> Upgrade Items To +1 On Manual Delete. (Throne Room Only)</td></tr>';
        m += '<tr><td><div style="white-space: pre;" ><input class=STrChOCheckbox id=STrChOThroneSalvageUpgradeAutoFind type=checkbox ' + (STrChOThroneSalvageData.upgradeAutoFind ? ' CHECKED' : '') + '/> Add Items To Throne Upgrader Automatically When A Rule Is Matched</td></tr>';
        m += '<tr><td><div style="white-space: pre;" ><input class=STrChOCheckbox id=STrChOChampSalvageUpgradeAutoFind type=checkbox ' + (STrChOChampSalvageData.upgradeAutoFind ? ' CHECKED' : '') + '/> Add Items To Champ Upgrader Automatically When A Rule Is Matched</td></tr>';

        m += '</table>';
        m += '</div>';



        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;ENHANCE/UPGRADE OPTIONS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="width: 100%; height: 360px; overflow-x: hidden; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';
        m += '<tr><td><b>Use Aetherstones: </b><div style="display: inline;" id=STrChOUseCity></div></td></tr>';
        m += '<tr><td width=25%>Retry interval (seconds): <input class=STrChOTextbox id=STrChORetryInterval type=text size=3 maxlength=3 value="' + STrChOGeneralOptions.retryInterval + '"/></td></tr>';
        m += '<tr><td><div style="white-space: pre;"><input class=STrChOCheckbox id=STrChOUseAnyCity type=checkbox ' + (STrChOGeneralOptions.useAnyCity ? ' CHECKED' : '') + '/> When Full, Use Aetherstones From Any City.</td></tr>';
        m += '<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Minimum Number Of Aetherstones: <input class=STrChOTextbox id=STrChOMinStones type=text size=7 maxlength=7 value="' + STrChOGeneralOptions.minStones + '"/> </div></td></tr>';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOWhisperCheck type=checkbox ' + (STrChOGeneralOptions.whisperToMe ? 'CHECKED ' : '') + '/> Whisper Myself Successful Upgrades/Enhancements</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOSendInbox type=checkbox ' + (STrChOGeneralOptions.sendToInbox ? 'CHECKED ' : '') + '/> Send To Inbox Successful Upgrades/Enhancements</td></tr>';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOSafetyCheck type=checkbox ' + (STrChOGeneralOptions.safetyOn ? 'CHECKED ' : '') + '/> Disable Manual Upgrades If Less Than <input class=STrChOTextbox type=text id=STrChOSafetyLimit size=10 maxlength=10 value="' + STrChOGeneralOptions.safetyLimit + '"> Aetherstone</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOBuffsCheck type=checkbox ' + (STrChOGeneralOptions.buffsOff ? 'CHECKED ' : '') + '/> Prevent Automatic Upgrade Token Selection (Throne Room Only)</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOMastersTokenCheck type=checkbox ' + (STrChOGeneralOptions.removeMastersTokens ? 'CHECKED ' : '') + '/> Remove Master & Lucky Tokens From Upgrade Panel (Throne Room Only)</td></tr>';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOOtherTokenCheck type=checkbox ' + (STrChOGeneralOptions.removeOtherTokens ? 'CHECKED ' : '') + '/> Remove All Other Tokens From Upgrade Panel (Not LLT Or Stones) (Throne Room Only)</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOUseMastersToken type=checkbox ' + (STrChOGeneralOptions.useMastersTokens ? 'CHECKED ' : '') + '/> Use Next Masters On Manual Upgrade (Overrides Above 2 Options If Checked, Throne Room Only) </td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOForgedTokenCheck type=checkbox ' + (STrChOGeneralOptions.removeForgedTokens ? 'CHECKED ' : '') + '/> Remove Forged Tokens From Upgrade Panel (Champ Hall Only)</td></tr>';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOOtherForgedTokenCheck type=checkbox ' + (STrChOGeneralOptions.removeOtherForgedTokens ? 'CHECKED ' : '') + '/> Remove All Other Tokens From Upgrade Panel (Champ Hall Only)</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOUseForgedToken type=checkbox ' + (STrChOGeneralOptions.useForgedTokens ? 'CHECKED ' : '') + '/> Use Next Forged On Manual Upgrade (Overrides Above 2 Options If Checked, Champ Hall Only) </td></tr> ';

        //m += '<tr><td><input class=STrChOCheckbox id=STrChOMultiUpgrade type=checkbox ' + (STrChOGeneralOptions.multiUpgrade ? 'CHECKED ' : '') + '/> Add Button For Combined Upgrade/Enhancement (Throne Room Only)</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChONoEquippedSalvage type=checkbox ' + (STrChOGeneralOptions.noEquippedSalvage ? 'CHECKED ' : '') + '/> Remove Salvage Button When Item Is Equipped In Any Slot</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChONoMassSalvage type=checkbox ' + (STrChOGeneralOptions.noMassSalvage ? 'CHECKED ' : '') + '/> Remove Mass Salvage Button</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChONoForcedSalvage type=checkbox ' + (STrChOGeneralOptions.noForcedSalvage ? 'CHECKED ' : '') + '/> Remove Forced Salvage Button (Throne Room Only)</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOThroneSalvageSafety type=checkbox ' + (STrChOGeneralOptions.throneSalvageSafety ? 'CHECKED ' : '') + '/> Remove Salvage Button For 1st <input class=STrChOTextbox id=STrChOThroneSafetyNum type=text size=3 maxlength=3 value="' + STrChOGeneralOptions.throneSalvageSafetyNum + '"> Throne Room Items</td></tr> ';
        m += '<tr><td><input class=STrChOCheckbox id=STrChOChampSalvageSafety type=checkbox ' + (STrChOGeneralOptions.champSalvageSafety ? 'CHECKED ' : '') + '/> Remove Salvage Button For 1st <input class=STrChOTextbox id=STrChOChampSafetyNum type=text size=3 maxlength=3 value="' + STrChOGeneralOptions.champSalvageSafetyNum + '"> Champion Items</td></tr> ';
        m += '</table>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOOptionsSaveSettings').addEventListener('click', function () {
            SaveSettingsToFile(STrChOGeneralOptions);
        }, false);
        document.getElementById('STrChOOptionsLoadSettings').addEventListener('click', function () {
            var loader = document.getElementById('STrChOSettingsFile');
            loader.addEventListener('change', function () {
                LoadSettingsFromFile(STrChOGeneralOptions, Tabs.STrChOOptions);
            }, false);
            loader.click();
        }, false);

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        new CdispCityPicker('salcitysel', document.getElementById('STrChOSalvageCity'), true, t.SalvageCityButton, STrChOGeneralOptions.salvageCityNum);
        new CdispCityPicker('upcitysel', document.getElementById('STrChOUseCity'), true, t.UsedCityButton, STrChOGeneralOptions.usedCityNum);

        document.getElementById('STrChOSendInbox').addEventListener('change', function () {
            STrChOGeneralOptions.sendToInbox = document.getElementById('STrChOSendInbox').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOShowJewels').addEventListener('change', function () {
            STrChOGeneralOptions.showJewels = document.getElementById('STrChOShowJewels').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOMinStones').addEventListener('change', function () {
            STrChOGeneralOptions.minStones = document.getElementById('STrChOMinStones').value;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOOverflow').addEventListener('change', function () {
            STrChOGeneralOptions.overflow = document.getElementById('STrChOOverflow').value;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOMaxStones').addEventListener('change', function () {
            STrChOGeneralOptions.maxStones = document.getElementById('STrChOMaxStones').value;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOUseAnyCity').addEventListener('change', function () {
            STrChOGeneralOptions.useAnyCity = document.getElementById('STrChOUseAnyCity').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOThroneSalvageUpgradeFirst').addEventListener('change', function () {
            STrChOThroneSalvageData.upgradeFirst = document.getElementById('STrChOThroneSalvageUpgradeFirst').checked;
            SAVESTrChOThroneSalvageData();
        }, false);

        document.getElementById('STrChOThroneUpgradeFirstQual').addEventListener('change', function () {
            STrChOThroneSalvageData.upgradeFirstQual = document.getElementById('STrChOThroneUpgradeFirstQual').value;
            SAVESTrChOThroneSalvageData();
        }, false);

        document.getElementById('STrChOThroneSalvageUpgradeManual').addEventListener('change', function () {
            STrChOThroneSalvageData.upgradeManual = document.getElementById('STrChOThroneSalvageUpgradeManual').checked;
            SAVESTrChOThroneSalvageData();
        }, false);

        document.getElementById('STrChOThroneSalvageUpgradeAutoFind').addEventListener('change', function () {
            STrChOThroneSalvageData.upgradeAutoFind = document.getElementById('STrChOThroneSalvageUpgradeAutoFind').checked;
            SAVESTrChOThroneSalvageData();
        }, false);

        document.getElementById('STrChOChampSalvageUpgradeAutoFind').addEventListener('change', function () {
            STrChOChampSalvageData.upgradeAutoFind = document.getElementById('STrChOChampSalvageUpgradeAutoFind').checked;
            SAVESTrChOChampSalvageData();
        }, false);

        document.getElementById('STrChOSalvageAnyCity').addEventListener('change', function () {
            STrChOGeneralOptions.salvageAnyCity = document.getElementById('STrChOSalvageAnyCity').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChORetryInterval').addEventListener('change', function () {
            STrChOGeneralOptions.retryInterval = parseInt(document.getElementById('STrChORetryInterval').value);
            if (STrChOGeneralOptions.retryInterval < 15) STrChOGeneralOptions.retryInterval = 15;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOThroneSafetyNum').addEventListener('change', function () {
            STrChOGeneralOptions.throneSalvageSafetyNum = parseInt(document.getElementById('STrChOThroneSafetyNum').value);
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOChampSafetyNum').addEventListener('change', function () {
            STrChOGeneralOptions.champSalvageSafetyNum = parseInt(document.getElementById('STrChOChampSafetyNum').value);
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOBuffsCheck').addEventListener('change', function () {
            STrChOGeneralOptions.buffsOff = document.getElementById('STrChOBuffsCheck').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOSafetyLimit').addEventListener('change', function () {
            STrChOGeneralOptions.safetyLimit = parseInt(document.getElementById('STrChOSafetyLimit').value);
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChODisableAnim').addEventListener('change', function () {
            STrChOGeneralOptions.disableAnim = document.getElementById('STrChODisableAnim').checked;
            disableAnimation(STrChOGeneralOptions.disableAnim);
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChODraggableThroneItems').addEventListener('change', function () {
            STrChOGeneralOptions.draggableThroneItems = document.getElementById('STrChODraggableThroneItems').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOWhisperCheck').addEventListener('change', function () {
            STrChOGeneralOptions.whisperToMe = document.getElementById('STrChOWhisperCheck').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOSafetyCheck').addEventListener('change', function () {
            STrChOGeneralOptions.safetyOn = document.getElementById('STrChOSafetyCheck').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOMastersTokenCheck').addEventListener('change', function () {
            STrChOGeneralOptions.removeMastersTokens = document.getElementById('STrChOMastersTokenCheck').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOOtherTokenCheck').addEventListener('change', function () {
            STrChOGeneralOptions.removeOtherTokens = document.getElementById('STrChOOtherTokenCheck').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOUseMastersToken').addEventListener('change', function () {
            STrChOGeneralOptions.useMastersTokens = document.getElementById('STrChOUseMastersToken').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOForgedTokenCheck').addEventListener('change', function () {
            STrChOGeneralOptions.removeForgedTokens = document.getElementById('STrChOForgedTokenCheck').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOOtherForgedTokenCheck').addEventListener('change', function () {
            STrChOGeneralOptions.removeOtherForgedTokens = document.getElementById('STrChOOtherForgedTokenCheck').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOUseForgedToken').addEventListener('change', function () {
            STrChOGeneralOptions.useForgedTokens = document.getElementById('STrChOUseForgedToken').checked;
            SAVESTrChOGeneralOptions();
        }, false);


//        document.getElementById('STrChOMultiUpgrade').addEventListener('change', function () {
//            STrChOGeneralOptions.multiUpgrade = document.getElementById('STrChOMultiUpgrade').checked;
//            SAVESTrChOGeneralOptions();
//        }, false);

        document.getElementById('STrChONoForcedSalvage').addEventListener('change', function () {
            STrChOGeneralOptions.noForcedSalvage = document.getElementById('STrChONoForcedSalvage').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChONoEquippedSalvage').addEventListener('change', function () {
            STrChOGeneralOptions.noEquippedSalvage = document.getElementById('STrChONoEquippedSalvage').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChONoMassSalvage').addEventListener('change', function () {
            STrChOGeneralOptions.noMassSalvage = document.getElementById('STrChONoMassSalvage').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOThroneSalvageSafety').addEventListener('change', function () {
            STrChOGeneralOptions.throneSalvageSafety = document.getElementById('STrChOThroneSalvageSafety').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOChampSalvageSafety').addEventListener('change', function () {
            STrChOGeneralOptions.champSalvageSafety = document.getElementById('STrChOChampSalvageSafety').checked;
            SAVESTrChOGeneralOptions();
        }, false);

        document.getElementById('STrChOThroneLoadDomainRules').addEventListener('click', function () {
            var d = document.getElementById('STrChOThroneLoadDomain').value;
            if (d != null) ThroneLoadDomainSalvageData(d);
        }, false);

        document.getElementById('STrChOChampLoadDomainRules').addEventListener('click', function () {
            var d = document.getElementById('STrChOChampLoadDomain').value;
            if (d != null) ChampLoadDomainSalvageData(d);
        }, false);

        disableAnimation(STrChOGeneralOptions.disableAnim);
	},

	hide: function () {},

	show: function () {},

    SalvageCityButton: function (city, x, y) {
        STrChOGeneralOptions.salvageCityNum = city.idx;
        SAVESTrChOGeneralOptions();
    },

    UsedCityButton: function (city, x, y) {
        STrChOGeneralOptions.usedCityNum = city.idx;
        SAVESTrChOGeneralOptions();
    },
}

Tabs.STrChOJewels = {
	tabOrder: 302,
	tabLabel: 'JEWELS',
	tabColor: 'blue',
    tabHeader: 'JEWEL ORGANIZER',
    jewelEffects: [],
    totalInventroy: 0,
    inventoryList: [],

	init: function (div) {
		var t = Tabs.STrChOJewels;
		t.mydiv = div;
	},

	hide: function () {},

	show: function () {
		var t = Tabs.STrChOJewels;

        t.buildJewelList();

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<table class=STrChOSectionTable>';

        m += '<tr><td><b>Effects</b></td><td><b>Quality</b></td></tr>';

        m += '<tr>';
        m += '<td><div id=STrChOJewelEffectFilterRow style="float: left; width: 250px; border:2px solid #ccc; height: 110px; overflow-y: scroll; background-color: white;">';
        for (fx=0;fx<t.jewelEffects.length;fx++) {
            var effect = t.jewelEffects[fx];
            effect = effect.split(' ').join('');
            effect = effect.split('.').join('');
            m += '<input class=STrChOCheckbox id=STrChOJewelEffect' + effect + ' type=checkbox  CHECKED />' + t.jewelEffects[fx] + '<br />';

        }
        m += '</div></td>';

        m += '<td><div id=STrChOJewelQualityFilterRow style="float: left; width: 120px; border:2px solid #ccc; height: 110px; overflow-y: scroll; background-color: white;">';
        for (jwl=0;jwl<STrChOJewelQualities.length;jwl++) {
            m += '<input class=STrChOCheckbox id=STrChOJewelQuality' + String(STrChOJewelQualities[jwl]).capitalizeFirstLetter() + ' type=checkbox  CHECKED />' + String(STrChOJewelQualities[jwl]).capitalizeFirstLetter() + '<br />';
        }
        m += '</div></td>';
        m += '</tr>';

        m += '<tr><td><input style="width:120px;" class=STrChOButton type=button id=STrChOJewelEffectsUnselectAll value="Unselect All"></td>';
        m += '<td><input style="width:120px;" class=STrChOButton type=button id=STrChOJewelQualitiesUnselectAll value="Unselect All"></td></tr>';
        m += '<tr><td><input style="width:120px;" class=STrChOButton type=button id=STrChOJewelEffectsSelectAll value="Select All"></td>';
        m += '<td><input style="width:120px;" class=STrChOButton type=button id=STrChOJewelQualitiesSelectAll value="Select All"></td></tr>';

        m += '<tr><td colspan=2 align=center><div class=divNoWrap id=STrChOJewelBuffFilterRow><input id=STrChOJewelBuff' + true + ' type=checkbox  CHECKED />Buff&nbsp;&nbsp;<input id=STrChOJewelBuff' + false + ' type=checkbox  CHECKED />Debuff</div></td></tr>';


        m += '</table></div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;JEWEL INVENTORY&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';

        m += '<table cellpadding=0 cellspacing=0 width=100%>';
        m += '<thead>';
        m += '<tr>';
        m += '<th align=left width=60%>Effect</th>';
        m += '<th align=left width=10%>Quality</th>';
        m += '<th align=left width=10%>Type</th>';
        m += '<th align=center width=10%>Amount</th>';
        m += '<th align=center width=10%>In Stock</th>';
        m += '</tr>';
        m += '</thead>';
        m += '</table>';

        m += '<div style="position: static; width: 100%; height: 225px; overflow-x: hidden; overflow-y: auto;">';

        m += '<table id=STrChOJewelInventory cellpadding=0 cellspacing=0 width=100%>';

        m += '<tbody>';
        m += '</tbody>';
        m += '</table>';

        m += '</div>';
        m += '<hr/>';
        m += '<input class=STrChOButton id=STrChOJewelRefresh type=button value="Refresh"/>&nbsp;<i>(new jewels found may take a couple seconds to add to total)</i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Total:</b><div class=divNoWrap id=STrChOJewelTotal></div>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

        t.buildInventory();

        document.getElementById('STrChOJewelEffectFilterRow').addEventListener('change', function () {
            t.buildInventory();
        }, false);

        document.getElementById('STrChOJewelQualityFilterRow').addEventListener('change', function () {
            t.buildInventory();
        }, false);

        document.getElementById('STrChOJewelBuffFilterRow').addEventListener('change', function () {
            t.buildInventory();
        }, false);

        document.getElementById('STrChOJewelRefresh').addEventListener('click', function () {
            t.buildJewelList();
            t.buildInventory();
        }, false);

        document.getElementById('STrChOJewelQualitiesUnselectAll').addEventListener('click', function () {
            for (qly=0;qly<=STrChOJewelQualities.length;qly++) {
                var quality = STrChOJewelQualities[qly];
                var ch = document.getElementById("STrChOJewelQuality" + quality.capitalizeFirstLetter());
                ch.checked = false;
            }
            t.buildInventory();
        }, false);

        document.getElementById('STrChOJewelQualitiesSelectAll').addEventListener('click', function () {
            for (qly=0;qly<=STrChOJewelQualities.length;qly++) {
                var quality = STrChOJewelQualities[qly];
                var ch = document.getElementById("STrChOJewelQuality" + quality.capitalizeFirstLetter());
                ch.checked = true;
            }
            t.buildInventory();
        }, false);

        document.getElementById('STrChOJewelEffectsUnselectAll').addEventListener('click', function () {
            for (ef=0;ef<t.jewelEffects.length;ef++) {
                var effect = t.jewelEffects[ef];
                effect = effect.split(' ').join('');
                effect = effect.split('.').join('');
                var ch = document.getElementById("STrChOJewelEffect" + effect);
                ch.checked = false;
            }
            t.buildInventory();
        }, false);

        document.getElementById('STrChOJewelEffectsSelectAll').addEventListener('click', function () {
            for (ef=0;ef<t.jewelEffects.length;ef++) {
                var effect = t.jewelEffects[ef];
                effect = effect.split(' ').join('');
                effect = effect.split('.').join('');
                var ch = document.getElementById("STrChOJewelEffect" + effect);
                ch.checked = true;
            }
            t.buildInventory();
        }, false);

	},

    addJewel: function (jewel_id, jewel_quality, throne_item_id) {
        var params = uW.Object.clone(ajfx);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'addJewel';
        params.itemId = throne_item_id;
        params.quality = jewel_quality;
        params.effectId = jewel_id;

        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                try {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                    }
                    else {
                        return 'Error Adding Jewel';
                    }
                } catch (e) {
                }
                return;
            },
            onFailure: function (rst) {
                return;
            }
        });
        CM.ThronePanelView.removeSpinny();
    },

    removeJewel: function (city_id, throne_item_id) {
        var params = uW.Object.clone(ajfx);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'removeJewel';
        params.cityId = city_id;
        params.itemId = throne_item_id;

        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                try {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                        var astone_gain = rslt.aetherstones * -1;
                        Seed.resources["city" + rslt.cityId]["rec5"][0] += astone_gain;
                    } else {
                        return 'Error Removing Jewel';
                    }
                } catch (e) {
                }
                return;
            },
            onFailure: function (rst) {
                return;
            }
        });
        CM.ThronePanelView.removeSpinny();
    },

    buildInventory: function () {
        var t = Tabs.STrChOJewels;
        var inv = "";

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

            var jewel_item = t.inventoryList[i];
            var qlty = CM.thronestats.jewelGrowthLimit[jewel_item.quality];
            var amt = CM.ThroneController.getEffectAmount(jewel_item, qlty);
            var name = CM.ThroneController.jewelName(jewel_item);
            var buffed = true;
            if (name.indexOf("Debuff") > 0) buffed = false;
            var effect = CM.ThroneController.getEffectName(jewel_item.id);
            var qty = CM.ThroneController.getJewelQuantity(jewel_item);
            var qualityName = CM.ThroneController.jewelQualityName(jewel_item.quality);
            var tmpEffect = CM.ThroneController.getEffectName(jewel_item.id);
            tmpEffect = tmpEffect.split(' ').join('');
            tmpEffect = tmpEffect.split('.').join('');
            if (!(document.getElementById('STrChOJewelEffect' + tmpEffect).checked)) continue;
            if (!(document.getElementById('STrChOJewelQuality' + qualityName).checked)) continue;
            if (!(document.getElementById('STrChOJewelBuff' + buffed).checked)) continue;

            inv += '<tr><td width=62%>' + effect + '</td>';
            inv += '<td width=10%>' + qualityName + '</td>';
            inv += '<td width=10%>' + (buffed ? 'Buff ' : 'Debuff') + '</td>';
            inv += '<td align=center width=10%>' + amt + '%</td>';
            inv += '<td align=right width=8%>' + qty + '</td></tr>';

        }

        var jwl_inv = document.getElementById('STrChOJewelInventory').tBodies[0];
        jwl_inv.innerHTML = inv;

        var jwl_total = document.getElementById('STrChOJewelTotal');
        jwl_total.innerHTML = t.totalInventroy;

    },

    buildJewelList: function () {
        var t = Tabs.STrChOJewels;
        t.inventoryList = [];
        t.totalInventroy = 0;
        for (var jwl=0;jwl<uW.kocJewelItems.length;jwl++) {
            var jewel_item = uW.kocJewelItems[jwl];
            var qlty = CM.thronestats.jewelGrowthLimit[jewel_item.quality];
            var amt = CM.ThroneController.getEffectAmount(jewel_item, qlty);
            var effect = CM.ThroneController.getEffectName(jewel_item.id);
            if (amt == 0) break;
            if (t.jewelEffects.indexOf(effect) < 0) t.jewelEffects.push(effect);
            var jewel_quantity = CM.ThroneController.getJewelQuantity(jewel_item);
            t.totalInventroy += jewel_quantity;
            t.inventoryList.push(jewel_item);
        }
    },
}

Tabs.STrChONews = {
	tabOrder: 303,
	tabLabel: 'NEWS',
	tabColor: 'blue',
    tabHeader: 'BREAKING NEWS',

	init: function (div) {
		var t = Tabs.STrChONews;
		t.mydiv = div;
		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<table cellpadding=0 cellspacing=0 width=100% height=35px>';
        m += '<tr><td align=center>';
       // m += '<a href="https://www.facebook.com/tco4koc" target="_BLANK" style="font-family: tahoma,verdana,arial,sans-serif; font-size: 11px; font-variant: normal; font-style: normal; font-weight: normal; color: #3B5998; text-decoration: none;" title="KoC Throne &amp; Champ Organizer by Ne0"><img src="https://www.facebookbrand.com/img/assets/asset.find.us.on.facebook.lg.png" style="border: 0px;" /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        //m += '<iframe src="//www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Ftco4koc&amp;width&amp;layout=standard&amp;action=like&amp;show_faces=false&amp;share=true&amp;height=15" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:15px;" allowTransparency="true"></iframe>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        m += '</td></tr>';
         m += '<tr></tr><tr><td align=center><b>In Hounour Of<br><br>Mark Branscombe (TCO)<br><br>Phil Cazz (MadMaxx)<br><br>That Paved The Way For Organizers Like This Thanks Guys !!! </b></td></tr>';
        m += '</table>';
        m += '<div style="height: ' + (dlgHeight - (dlgHeightOffset*5)) + 'px; width: ' + (dlgWidth - dlgWidthMenu) + 'px; margin-top:5px; margin-bottom:5px; overflow-x: auto; overflow-y: auto; position: static;">';

        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;WHATS NEW&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection style="position: static; width: 100%; overflow-x: auto; overflow-y: auto;">';
        m += '<table class=STrChOSectionTable>';
        m += NewsItemRow('<b>2020</b>');
        m += NewsItemRow('Spawn STrChO (Throne And Champ Organizer)');
        m += '</table>';
        m += '</div>';

        m += '</table>';
        m += '</div>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

	},

	hide: function () {},

	show: function () {
	},
}

Tabs.STrChOLinks = {
	tabOrder: 304,
	tabLabel: 'LINKS',
	tabColor: 'blue',
    tabHeader: 'MY FAVORITE LINKS',

	init: function (div) {
		var t = Tabs.STrChOLinks;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

		m += '<div>';

        m += '<table class=STrChOSectionTable>';//cellpadding=0 cellspacing=0 width=100%>';

        m += '<tr><td align=center><div id=STrChOLink1 class=STrChOLinksClass style="cursor:pointer;"><font class=STrChOLinksHeader>STrChO (Throne And Champ Organizer)</td></tr>';
        m += '<tr><td align=center class=STrChOTDLinks><div id=STrChOLink1data class=STrChOLinkData style="display:none;">';
        m += '<a target="_blank" href="https://greasyfork.org/en/scripts/408041-spawn-trcho "><font class=STrChOLinks>https://greasyfork.org/en/scripts/408041-spawn-trcho </a><br>';
        m += '<font class=STrChOLinksDesc>An advanced organizer that upgrades and salvages KOC throne room and champion items, with many extra features</font>';
        m += '</div></td></tr>';

        m += '<tr><td align=center><div id=STrChOLink2 class=STrChOLinksClass style="cursor:pointer;"><font class=STrChOLinksHeader>Demon Spawn koc bot</td></tr>';
        m += '<tr><td align=center class=STrChOTDLinks><div id=STrChOLink2data class=STrChOLinkData style="display:none;">';
        m += '<a target="_blank" href="https://greasyfork.org/en/scripts/407074-demon-spawn-koc-bot"><font class=STrChOLinks>https://greasyfork.org/en/scripts/407074-demon-spawn-koc-bot</a><br>';
        m += '<font class=STrChOLinksDesc>A powerful bot that automates features for KOC</font>';
        m += '</div></td></tr>';

		m += '<tr><td align=center><div id=STrChOLink3 class=STrChOLinksClass style="cursor:pointer;"><font class=STrChOLinksHeader>Tampermonkey</td></tr>';
        m += '<tr><td align=center class=STrChOTDLinks><div id=STrChOLink3data class=STrChOLinkData style="display:none;">';
        m += '<a target="_blank" href="https://www.tampermonkey.net/"><font class=STrChOLinks>https://www.tampermonkey.net/</a><br>';
        m += '<font class=STrChOLinksDesc> A extension that allows users to install scripts that make on-the-fly changes to web page content after or before the page is loaded in the browser</font>';
        m += '</div></td></tr>';

        m += '<tr><td align=center><div id=STrChOLink4 class=STrChOLinksClass style="cursor:pointer;"><font class=STrChOLinksHeader>Throne Room Spreadsheet</td></tr>';
        m += '<tr><td align=center class=STrChOTDLinks><div id=STrChOLink4data class=STrChOLinkData style="display:none;">';
        m += '<a target="_blank" href="https://docs.google.com/spreadsheets/d/1gs02x8aURak1D4MGTBzrYc5_ZDAg6cB_Kq2xiRU6kfE/edit?pli=1#gid=0"><font class=STrChOLinks>https://docs.google.com/spreadsheets/d/1gs02x8aURak1D4MGTBzrYc5_ZDAg6cB_Kq2xiRU6kfE/edit?pli=1#gid=0</a><br>';
        m += '<font class=STrChOLinksDesc>Great spreadsheet to view what stats are available on throne cards, and some other throne/champ related items</font>';
        m += '</div></td></tr>';

        m += '<tr><td align=center><div id=STrChOLink5 class=STrChOLinksClass style="cursor:pointer;"><font class=STrChOLinksHeader>Google Translator for Firefox</td></tr>';
        m += '<tr><td align=center class=STrChOTDLinks><div id=STrChOLink5data class=STrChOLinkData style="display:none;">';
        m += '<a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/google-translator-for-firefox/"><font class=STrChOLinks>https://addons.mozilla.org/en-US/firefox/addon/google-translator-for-firefox/</a><br>';
        m += '<font class=STrChOLinksDesc>With this addon you can translate any text to your own language</font>';
	    m += '</div></td></tr>';

        m += '<tr><td align=center><div id=STrChOLink6 class=STrChOLinksClass style="cursor:pointer;"><font class=STrChOLinksHeader>Tab Reloader for Chrome</td></tr>';
        m += '<tr><td align=center class=STrChOTDLinks><div id=STrChOLink6data class=STrChOLinkData style="display:none;">';
        m += '<a target="_blank" href="https://chrome.google.com/webstore/detail/tab-reloader-page-auto-re/dejobinhdiimklegodgbmbifijpppopn?hl=en"><font class=STrChOLinks>https://chrome.google.com/webstore/detail/tab-reloader-page-auto-re/dejobinhdiimklegodgbmbifijpppopn?hl=en</a><br>';
        m += '<font class=STrChOLinksDesc>Reloads web pages every so many seconds or minutes</font>';
        m += '</div></td></tr>';

        m += '<tr><td align=center><div id=STrChOLink7 class=STrChOLinksClass style="cursor:pointer;"><font class=STrChOLinksHeader>Tab Reloader for Firefox</td></tr>';
        m += '<tr><td align=center class=STrChOTDLinks><div id=STrChOLink7data class=STrChOLinkData style="display:none;">';
        m += '<a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/tab-reloader/?src=search"><font class=STrChOLinks>https://addons.mozilla.org/en-US/firefox/addon/tab-reloader/?src=search</a><br>';
        m += '<font class=STrChOLinksDesc>Reloads web pages every so many seconds or minutes</font>';
        m += '</div></td></tr>';


	   m += '</table>';

        m += '</div>';


        m += '<div class=STrChOHeader onmouseover="this.style.cursor=\'pointer\'"><img src="'+STrChORightArrow+'"/>&nbsp;TUTORIAL LINKS&nbsp;<img class=STrChOReverseImage src="'+STrChORightArrow+'"/></div>';

        m += '<div class=STrChOSection>';
        m += '<table class=STrChOSectionTable>';

        m += '<tr><td align=center>';
        m += '<a target="_blank" href="http://www.youtube.com/embed/fXlHAzszico?rel=0&autoplay=1"><font class=STrChOLinks>Preview/Preset/Repair Tabs Tutorial</font></a>';
        m += '</td></tr>';

        m += '<tr><td align=center>';
        m += '<a target="_blank" href="http://www.youtube.com/embed/-maykvcbk4o?rel=0&autoplay=1"><font class=STrChOLinks>Throne Organizer-Preview Tutorial</font></a>';
        m += '</td></tr>';

        m += '</table>';
        m += '</div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        var STrChOLinkClick = function() {
            var id = this.getAttribute("id");
            var linkNumber = id.split("STrChOLink")[1];
            var divLinkName = 'STrChOLink' + linkNumber + 'data';
            var divLink = document.getElementById(divLinkName);
            var hidden = (divLink.style.display == "none");
            var links = document.getElementsByClassName("STrChOLinkData");
            for (i = 1; i < links.length + 1; i++) {
                document.getElementById('STrChOLink' + i + 'data').style.display = "none";
            }
            if (hidden) {
                divLink.style.display = "block";
            } else {
                divLink.style.display = "none";
            }
        };

        var STrChOLinksClass = document.getElementsByClassName("STrChOLinksClass");

        for(var i = 0; i < STrChOLinksClass.length; i++){
            STrChOLinksClass[i].addEventListener('click', STrChOLinkClick, false);
        };

        var header = document.getElementsByClassName('STrChOHeader');
        for (var head=0;head<header.length;head++) {
            header[head].addEventListener('click', sectionOpener, false);
        }

	},

	hide: function () {},

	show: function () {},
}

Tabs.STrChODonate = {
	tabOrder: 305,
	tabLabel: 'DONATE',
	tabColor: 'blue',
    tabHeader: 'DONATIONS',

	init: function (div) {
		var t = Tabs.STrChODonate;
		t.mydiv = div;

		var m = '<div class=STrChOHeader>' + t.tabHeader + '</div>';

        m += '<div class=indent5><b>';
        m +='Hi there, thanks for taking the time to consider donating. I never ask for handouts, although a thank you is nice. And sometimes a monetary thank you is nicer.';
        m +='Because it lets me continue working on the KoC script. You may or may not spend a few dollars on gems in support of the game you love. Maybe you can send a ';
        m +='little our way and support the coders who make your life a bit easier by automating it? If you would like to donate, please press the donate button';
        m +='below and I will be a very happy coder! All donations are processed through PayPal on my behalf. Thanks again for your support, without people like you, I would lose interest in this game';
        m += '</b></div>';

        m += '<div align=center><table><tr><td width=100% align=center>';
        m += '<a id=STrChOPayPalLink><img onmouseover="this.style.cursor=\'pointer\'" id=STrChOPayPalImage /></a>';
        m += '</td></tr></table></div>';

		t.mydiv.innerHTML = '<div>' + m + '</div>';

        document.getElementById('STrChOPayPalLink').setAttribute('href', 'https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=CB2MLZCP8FPE8');
        document.getElementById('STrChOPayPalLink').setAttribute('target', '_blank');
        document.getElementById('STrChOPayPalImage').setAttribute('src', 'https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif');
        document.getElementById('STrChOPayPalImage').setAttribute('alt', 'donate');

	},

	hide: function () {},

	show: function () {},
}

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

function QueueItem() {  //class definition for upgrade queue items
    this.item   = 0;
    this.action = "upgrade";
    this.level  = 1;
    this.status = "not started";
    this.triesTotal = 0;
    this.triesThis = 0;
    this.triesLast = 0;
    this.lastUpgrade = "none";
    this.upgrades = [];
}

function ThroneRule(type, faction, conditions, advancedrule) { //class definition for rules and conditions
    this.type = type;
    this.faction = faction;
    this.advancedrule = advancedrule;
    if (conditions)
        this.conditions = conditions;
    else
        this.conditions = [];

    this.ThroneAddCondition = ThroneAddCondition;
    this.ThroneApplyRule    = ThroneApplyRule;
}

function ThroneCloneRule(rule) {
    this.type = rule.type;
    this.faction = rule.faction;
    this.advancedrule = rule.advancedrule;
    this.conditions = [];
    if (rule.conditions) this.conditions = rule.conditions;

    this.ThroneAddCondition = ThroneAddCondition;
    this.ThroneApplyRule    = ThroneApplyRule;
}

function ThroneAddCondition(c) {
    this.conditions.push(c);
}

function ThroneApplyRule(id) {
    var ThroneItem = uW.kocThroneItems[id];

    if (this.type != 'any' && (this.type != ThroneItem.type)) return false;
    if (this.faction != 'any' && (this.faction != ThroneItem.faction)) return false;
    for (r in this.conditions) {
        if (!this.conditions[r].ThroneCheckCondition(id)) return false;
    }
    return true;
}

function ThroneCondition(mustHave, number, effect, buffType, slots ) {
    this.mustHave = mustHave;
    this.number   = number;
    this.effect   = effect;
    this.buffType = buffType;
    this.slots    = slots;

    this.ThroneCheckCondition = ThroneCheckCondition;
}

function ThroneCheckCondition(id) {
    var numberFound  = 0;
    var effectsFound = false;
    // get card
    var ThroneItem = uW.kocThroneItems[id];

    if (!ThroneItem) return false;

    // for loop for stat
    // count up occurances
    for (i in ThroneItem.effects) {
        var CardEffect = CM.thronestats.effects[ThroneItem.effects[i].id][1];
        var slotid = i.split("slot")[1];

        if (!this.slots[slotid-1]) continue;

        var eff = this.effect + " ";

        if (CardEffect.indexOf(" Debuff") < 0) CardEffect += " ";

        if (!CardEffect.startsWith(eff)) continue;

        // special rule for Chance to Find Items
        if ( (CardEffect == "Chance to Find Items ") && (CardEffect != eff ) ) continue;

        // If we do not care about buff/debuff then we are done
        if (this.buffType == "e") {
            numberFound++;
        } else {
            // Does the description end with a Debuff
            if (CardEffect.endsWith(" Debuff")) {
                // Are we looking for a debuff
                if (this.buffType == "d") numberFound++;
            } else {
                if (this.buffType == "b") numberFound++;
            }
        }
    }

    if ( numberFound >= this.number) effectsFound = true;

    if (this.mustHave != "false")
        return effectsFound;
    else
        return (!effectsFound);
}

function ChampRule(type, faction, conditions, advancedrule) {  //class definition for rules and conditions
    this.type = type;
    this.faction = faction;
    this.advancedrule = advancedrule;
    if (conditions)
        this.conditions = conditions;
    else
        this.conditions = [];

    this.ChampAddCondition = ChampAddCondition;
    this.ChampApplyRule    = ChampApplyRule;
}

function ChampCloneRule(rule) {
    this.type = rule.type;
    this.faction = rule.faction;
    this.advancedrule = rule.advancedrule;
    this.conditions = [];
    if (rule.conditions) this.conditions = rule.conditions;

    this.ChampAddCondition = ChampAddCondition;
    this.ChampApplyRule    = ChampApplyRule;
}

function ChampAddCondition(c) {
    this.conditions.push(c);
}

function ChampApplyRule(id) {
    var champItem = uW.kocChampionItems[id];

    if (this.type != "any" && (champItemTypes[this.type] != champItem.type)) return false;
    if (this.faction != "any" && (this.faction != champItem.faction)) return false;
    for (r in this.conditions)
    {
        if (!this.conditions[r].ChampCheckCondition(id)) return false;
    }
    return true;
}

function ChampCondition(mustHave, number, effect, buffType, slots ) {
    this.mustHave = mustHave;
    this.number   = number;
    this.effect   = effect;
    this.buffType = buffType;
    this.slots    = slots;

    this.ChampCheckCondition = ChampCheckCondition;
}

function ChampCheckCondition(id) {
    var numberFound  = 0;
    var effectsFound = false;
    // get card
    var champItem = uW.kocChampionItems[id];

    if (!champItem) return false;

    // for loop for stat
    // count up occurances
    for (i in champItem.effects) {
        var id = champItem.effects[i].id;
        var card_effect = "";


        card_effect = uW.g_js_strings.effects["name_" + id];

        var slotid = +i;
        if (!this.slots[slotid-1]) continue;

        var eff = this.effect + " ";

        if (card_effect.indexOf(" Debuff") < 0) card_effect += " ";

        if (!card_effect.startsWith(eff)) continue;

        // If we do not care about buff/debuff then we are done
        if (this.buffType == "e") {
            numberFound++;
        } else {
            // Does the description end with a Debuff
            if (card_effect.endsWith(" Debuff")) {
                // Are we looking for a debuff
                if (this.buffType == "d")
                {
                    numberFound++;
                }
            } else {
                if (this.buffType == "b")
                {
                    numberFound++;
                }
            }
        }
    }

    if ( numberFound >= this.number) {
        effectsFound = true;
    }

    if (this.mustHave != "false")
        return effectsFound;
    else
        return (!effectsFound);
}

function ReplaceToolTips() {

    var TToldF = CM.ThroneView.boostsTooltip;

    var ThroneToolTip = function (L, E, K) {
        var J = new Array();
        var slot = L.innerHTML;

        slot = slot.replace("<span>","").replace("</span>","").trim();

        if (L.id == "maparea_boosts_throneroom") slot = Seed.throne.activeSlot;

        J.push("<div id='boosts_tooltip'><b>Throne Room:</b><br/>");
        J.push("<b><i>(" + STrChOThronePresetData.presetNames[slot] + ")</i></b>");
        J.push("<br/>");

        var equipped_items = Seed.throne.slotEquip[slot];

        if (equipped_items.length > 0) {
            J.push(GenerateThronePresetEffectsString(equipped_items, true));
        } else {
            J.push("<div>This Preset has no Items equipped</div>");
        }

        J.push("</div>");
        if (L.id == "maparea_boosts_throneroom") {
            uW.showTooltip(J.join(""), L, E, K)
        } else {
            uW.Tooltip.show(E, J.join(""), [10, 10], null)
        }
    }

    CM.ThroneView.boostsTooltip = ThroneToolTip;
}
function alterChampHall() {

    function addNewHover() {
		$(".Champion div[hover_id]").unbind("hover").hover(function () {
			if ($(this).hasClass("edit_container") && $(this).attr("champion_idx")) {
				$(".mini_tooltip").remove();
				$(".tooltip").remove();
				var champSlot = $(this).attr("champion_idx");
				var topVal = parseInt(champSlot) * 100 + 47;
				var leftVal = 150;

				champSlot++;
				var champId = getChampID(champSlot);
				var D = [];
				for (var chId in uW.kocChampionItems) if (uW.kocChampionItems[chId].equippedTo == champId) D.push(chId);
				var champStats = GenerateChampPresetEffectsString(D, false);
				champStats = champStats.split('||').join('<br>');
				D = [];
				D.push("Champ Hall Slot #" + champSlot);
				D.push(getChampName(champSlot));
				if (STrChOChampPresetData.showChampName) D.push("(" + STrChOChampPresetData.presetNames[champSlot-1] + ")");
				if (STrChOChampPresetData.showChampMight) D.push(getChampMight());
				D.push(champStats);

				var champText = D.join('<br>');

				$(".Champion").append('<div class="tooltip" style="pointer-events: none;  left: ' + leftVal + "px; top: " + topVal + 'px;">' + champText + "</div>");
				$(this).append('<div class="mini_tooltip"></div>')
				this.addEventListener('mouseout', function () {
					$(".mini_tooltip").remove();
					$(".tooltip").remove();
				});
			}
		});
	}

    function addPostChamp() {
        var button_sizes = '38px';
        var assign_button = document.getElementsByClassName('assign_city')[0];
        assign_button.style.width = button_sizes;
        assign_button.className += ' divNoWrap';
        assign_button.parentElement.className += ' divNoWrap';

        if (!document.getElementById('STrChOHideShow')) {
            var STrChO_button = document.createElement('div');
            STrChO_button.className = 'buttonv2 brown divNoWrap';
            STrChO_button.innerHTML = 'STrChO';
            STrChO_button.id = 'STrChOHideShow';
            STrChO_button.style.width = button_sizes;
            assign_button.parentElement.appendChild(STrChO_button);
            STrChO_button.addEventListener('click', function () {
                eventHideShow();
            }, false);
        }
        if (!document.getElementById('STrChOPostChamp')) {
            var post_button = document.createElement('div');
            post_button.className = 'buttonv2 red divNoWrap';
            post_button.innerHTML = 'POST';
            post_button.id = 'STrChOPostChamp';
            post_button.style.width = button_sizes;
            assign_button.parentElement.appendChild(post_button);
            post_button.addEventListener('click', function () {
                var champDiv = document.getElementsByClassName('name active')[0];
                var champClass = champDiv.className;
                var champIndex = parseInt(champClass.replace(' name active', '').replace('name', ''));
                postChampSlot(champIndex+1);
            }, false);
        }
    }

    function addMenus() {

        $(".champItem").click(function (A) {
            CardContextMenu(this, uW.kocChampionItems[this.id], false);
        });
    }

    function addBorders() {

        Tabs.champPresets.paintTags();

        var dv = document.getElementById('STrChOChampMight')

        if (!dv) {

            var modContainers = document.getElementsByClassName("cmModalContainer Champion");
            if (modContainers == null || !modContainers) return;

            var modContainer = modContainers[0];
            if (modContainer == null || !modContainer) return;

            var elem = modContainer.getElementsByClassName("primarytitlebar")[0];
            dv = document.createElement('div');
            dv.id = "STrChOChampMight";
            dv.style.whiteSpace='nowrap';
            dv.style.position='absolute';
            dv.style.overflow='visible';
            dv.style.top = '15px';
            dv.style.left = '435px';
            dv.style.zIndex=2005;
            elem.insertBefore(dv, elem.childNodes[1].nextSibling);
        }

        dv.innerHTML = getChampMight();

    }

    var oldOpen = CM.ChampionModalController.open;
    CM.ChampionModalController.open = function (j) {
        oldOpen(j);
        addBorders();
        addPostChamp();
		addNewHover();
    }

    var rfi = CM.ChampionModalView.renderFilteredItems;
    CM.ChampionModalView.renderFilteredItems = function () {
        rfi();
        addMenus();
        addBorders();
    }

    var rdr = CM.ChampionModalView.render;
    CM.ChampionModalView.render = function (ab,aa) {
        rdr(ab,aa);
        addMenus();
        addBorders();
        addPostChamp();
		addNewHover();
    }

    var oldUpgEnh = CM.ChampionModalView.renderUpgEnh;
    CM.ChampionModalView.renderUpgEnh = function (ag, aa) {
        oldUpgEnh(ag, aa);
        var NextClick = document.getElementById('upgEnhStatsTarget');
        var t = Tabs.champOrganizer;
        t.panelId = ag;  //this is the champ item ID
        t.panelNextLevel = uW.kocChampionItems[ag].level + 1;
        NextClick.removeEventListener("click", t.showNextChampLevel);
        var Locked = document.getElementById('chLockedStatIcon');
        if (Locked != null) return;
        NextClick.addEventListener("click", t.showNextChampLevel);

        var champUpgTab = document.getElementById('champUpgTab');
        if (!champUpgTab) return;

        var clearForgedTokens = function () {
            // remove options for tokens

            var removeItems =  [
                                  uW.ksoItems[21093].name,   //45s
                                  uW.ksoItems[21092].name,   //44s
                                  uW.ksoItems[21091].name,   //43s
                                  uW.ksoItems[21090].name,   //42s
                                  uW.ksoItems[21089].name,   //41s
                                  uW.ksoItems[21088].name,   //40s
                                  uW.ksoItems[21087].name,   //39s
                                  uW.ksoItems[21086].name,   //38s
                                  uW.ksoItems[21085].name,   //37s
                                  uW.ksoItems[21084].name,   //36s
                                  uW.ksoItems[21083].name,   //35s
                                  uW.ksoItems[21082].name,   //34s
                                  uW.ksoItems[21081].name,   //33s
                                  uW.ksoItems[21080].name,   //32s
                                  uW.ksoItems[21079].name,   //31s
                                  uW.ksoItems[21078].name,   //30s
                                  uW.ksoItems[21077].name,   //29s
                                  uW.ksoItems[21076].name,   //28s
                                  uW.ksoItems[21075].name,   //27s
                                  uW.ksoItems[21074].name,   //26s
                                  uW.ksoItems[21073].name,   //25s
                                  uW.ksoItems[21072].name,   //24s
                                  uW.ksoItems[21071].name,   //23s
                                  uW.ksoItems[21070].name,   //22s
                                  uW.ksoItems[21069].name,   //21s
                                  uW.ksoItems[21068].name,   //20s
                                  uW.ksoItems[21067].name,   //19s
                                  uW.ksoItems[21066].name,   //18s
                                  uW.ksoItems[21065].name,   //17s
                                  uW.ksoItems[21064].name,   //16s
                                  uW.ksoItems[21063].name,   //15s
                                  uW.ksoItems[21062].name,   //14s
                                  uW.ksoItems[21061].name,   //13s
                                  uW.ksoItems[21060].name,   //12s
                                  uW.ksoItems[21059].name,   //11s
                                  uW.ksoItems[21055].name,   //10s
                                  uW.ksoItems[21054].name,   //9s
                                  uW.ksoItems[21057].name,   //8s
                                  uW.ksoItems[21053].name,   //7s
                                  uW.ksoItems[21056].name   //6s
                                ];

            $(document.querySelector("#upgEnhBuffSelect")).children("option").each(function () {
                if ($.inArray($(this).text(), removeItems) > -1) $(this).remove();
            });
        }

        var clearOtherForgedTokens = function () {
            // remove options for tokens
            var removeItems =  [uW.ksoItems[21051].name, // Journeyman Smith's Token
                                uW.ksoItems[21052].name, // Smith's Token
                                uW.ksoItems[21058].name  // Expert Smith's Token
                                ];

            $(document.querySelector("#upgEnhBuffSelect")).children("option").each(function () {
                if ($.inArray($(this).text(), removeItems) > -1) $(this).remove();
            });

        }

        if (champUpgTab.className == 'upgEnhTab active') {
            if (STrChOGeneralOptions.useForgedTokens) autoSelectForged();
            if (STrChOGeneralOptions.removeForgedTokens && !STrChOGeneralOptions.useForgedTokens) clearForgedTokens();
            if (STrChOGeneralOptions.removeOtherForgedTokens && !STrChOGeneralOptions.useForgedTokens) clearOtherForgedTokens();
        }
    }

};

var ThroneOldRenderMenu = CM.ContextualMenuThrone.renderMenu;

function installThroneHandlerFunctions() {

    // add some new functionality here ...
    var oldThroneRenderPanel = CM.ThronePanelView.renderPanel;
    var newThroneRenderPanel = function (v1, v2) {
        oldThroneRenderPanel(v1, v2);

        // save off this data ...
        Tabs.throneOrganizer.panelId = v2.id;
        Tabs.throneOrganizer.panelType = v1;
        Tabs.throneOrganizer.panelNextLevel = 2;

        var clearMasterTokens = function () {
            // remove options for tokens
            var removeItems =  [uW.ksoItems[20012].name, // +3 master
                                uW.ksoItems[20013].name, // +5 master
                                uW.ksoItems[20014].name, // +7
                                uW.ksoItems[20015].name, // +9
                                uW.ksoItems[20016].name, // +10
                                uW.ksoItems[20017].name, // +11
                                uW.ksoItems[20018].name, // +12
                                uW.ksoItems[20020].name, // +13
                                uW.ksoItems[20021].name, // +14
                                uW.ksoItems[20023].name, // +15
                                uW.ksoItems[20024].name, // +16
                                uW.ksoItems[20025].name, // +17
                                uW.ksoItems[20026].name, // +18
                                uW.ksoItems[20027].name, // +19
                                uW.ksoItems[20028].name, // +20
                                uW.ksoItems[20029].name, // +21
                                uW.ksoItems[20030].name, // +22
                                uW.ksoItems[20031].name, // +23
                                uW.ksoItems[20032].name, // +24
                                uW.ksoItems[20033].name, // +25
                                uW.ksoItems[20034].name, // +26
                                uW.ksoItems[20035].name, // +27
                                uW.ksoItems[20036].name, // +28
                                uW.ksoItems[20037].name, // +29
                                uW.ksoItems[20038].name, // +30
                                uW.ksoItems[20039].name,  // +31
								uW.ksoItems[20040].name, // +32 master
                                uW.ksoItems[20041].name, // +33master
                                uW.ksoItems[20042].name, // +34
                                uW.ksoItems[20043].name, // +35
                                uW.ksoItems[20044].name, // +36
                                uW.ksoItems[20045].name, // +37
                                uW.ksoItems[20046].name, // +38
                                uW.ksoItems[20047].name, // +39
                                uW.ksoItems[20048].name, // +40
                                uW.ksoItems[20049].name, // +41
                                uW.ksoItems[20050].name, // +42
                                uW.ksoItems[20051].name, // +43
                                uW.ksoItems[20052].name, // +44
                                uW.ksoItems[20053].name, // +45
                                uW.ksoItems[20054].name, // +46
                                uW.ksoItems[20055].name, // +47
                                uW.ksoItems[20056].name, // +48
                                uW.ksoItems[20057].name, // +49
                                uW.ksoItems[20058].name, // +50
                                uW.ksoItems[20059].name, // +51
                                uW.ksoItems[20060].name // +52

                                ];

            $(document.querySelector("#buffDropDown")).children("option").each(function () {
                if ($.inArray($(this).text(), removeItems) > -1) $(this).remove();
            });
            $(document.querySelector("#thronePanelBuffIcon")).removeClass().addClass('icon').addClass('i0');
            if (!STrChOGeneralOptions.useMastersTokens) $(document.querySelector("#thronePanelBuffPrice")).children("span.items").html('');
        }
        var clearOtherTokens = function () {
            // remove options for tokens
            var removeItems =  [uW.ksoItems[20006].name, // lucky token
                                uW.ksoItems[20007].name, // common master
                                uW.ksoItems[20008].name, // uncommon
                                uW.ksoItems[20009].name, // rare
                                uW.ksoItems[20010].name, // epic
                                uW.ksoItems[20011].name, // wondrous
                                uW.ksoItems[20019].name, // super lucky token
                                uW.ksoItems[20022].name, // apprentice token
                                uW.ksoItems[20101].name, //Fortune's Token +19
                                uW.ksoItems[20102].name, //Opportunity's Token +19
                                uW.ksoItems[20103].name, //Prospector's Token +19
                                uW.ksoItems[20104].name, //Fortune's Token +20
                                uW.ksoItems[20105].name, //Opportunity's Token +20
                                uW.ksoItems[20106].name, //Prospector's Token +20
                                uW.ksoItems[20107].name, //Fortune's Token +21
                                uW.ksoItems[20108].name, //Opportunity's Token +21
                                uW.ksoItems[20109].name, //Prospector's Token +21
                                uW.ksoItems[20110].name, //Fortune's Token +22
                                uW.ksoItems[20111].name, //Opportunity's Token +22
                                uW.ksoItems[20112].name, //Prospector's Token +22
                                uW.ksoItems[20113].name, //Fortune's Token +23
                                uW.ksoItems[20114].name, //Opportunity's Token +23
                                uW.ksoItems[20115].name, //Prospector's Token +23
                                uW.ksoItems[20116].name, //Fortune's Token +24
                                uW.ksoItems[20117].name, //Opportunity's Token +24
                                uW.ksoItems[20118].name, //Prospector's Token +24
                                uW.ksoItems[20119].name, //Fortune's Token +25
                                uW.ksoItems[20120].name, //Opportunity's Token +25
                                uW.ksoItems[20121].name, //Prospector's Token +25
                                uW.ksoItems[20122].name, //Fortune's Token +26
                                uW.ksoItems[20123].name, //Opportunity's Token +26
                                uW.ksoItems[20124].name, //Prospector's Token +26
                                uW.ksoItems[20125].name, //Fortune's Token +27
                                uW.ksoItems[20126].name, //Opportunity's Token +27
                                uW.ksoItems[20127].name, //Prospector's Token +27
                                uW.ksoItems[20128].name, //Fortune's Token +28
                                uW.ksoItems[20129].name, //Opportunity's Token +28
                                uW.ksoItems[20130].name, //Prospector's Token +28
                                uW.ksoItems[20131].name, //Fortune's Token +29
                                uW.ksoItems[20132].name, //Opportunity's Token +29
                                uW.ksoItems[20133].name, //Prospector's Token +29
                                uW.ksoItems[20134].name, //Fortune's Token +30
                                uW.ksoItems[20135].name, //Opportunity's Token +30
                                uW.ksoItems[20136].name,  //Prospector's Token +30
                                uW.ksoItems[20137].name, //Fortune's Token +31
                                uW.ksoItems[20138].name, //Opportunity's Token +31
                                uW.ksoItems[20139].name, //Prospector's Token +31
                                uW.ksoItems[20140].name, //Fortune's Token +32
                                uW.ksoItems[20141].name, //Opportunity's Token +32
                                uW.ksoItems[20142].name, //Prospector's Token +32
                                uW.ksoItems[20143].name, //Fortune's Token +33
                                uW.ksoItems[20144].name, //Opportunity's Token +33
                                uW.ksoItems[20145].name, //Prospector's Token +33
                                uW.ksoItems[20146].name, //Fortune's Token +34
                                uW.ksoItems[20147].name, //Opportunity's Token +34
                                uW.ksoItems[20148].name, //Prospector's Token +34
                                uW.ksoItems[20149].name, //Fortune's Token +35
                                uW.ksoItems[20150].name, //Opportunity's Token +35
                                uW.ksoItems[20151].name, //Prospector's Token +35
                                uW.ksoItems[20152].name, //Fortune's Token +36
                                uW.ksoItems[20153].name, //Opportunity's Token +36
                                uW.ksoItems[20154].name, //Prospector's Token +36
                                uW.ksoItems[20155].name, //Fortune's Token +37
                                uW.ksoItems[20156].name, //Opportunity's Token +37
                                uW.ksoItems[20157].name, //Prospector's Token +37
                                uW.ksoItems[20158].name, //Fortune's Token +38
                                uW.ksoItems[20159].name, //Opportunity's Token +38
                                uW.ksoItems[20160].name, //Prospector's Token +38
                                uW.ksoItems[20161].name, //Fortune's Token +39
                                uW.ksoItems[20162].name, //Opportunity's Token +39
                                uW.ksoItems[20163].name, //Prospector's Token +39
                                uW.ksoItems[20164].name, //Fortune's Token +40
                                uW.ksoItems[20165].name, //Opportunity's Token +40
                                uW.ksoItems[20166].name, //Prospector's Token +40
                                uW.ksoItems[20167].name, //Fortune's Token +41
                                uW.ksoItems[20168].name, //Opportunity's Token +41
                                uW.ksoItems[20169].name,  //Prospector's Token +41
								uW.ksoItems[20170].name, //Fortune's Token +42
                                uW.ksoItems[20171].name, //Opportunity's Token +42
                                uW.ksoItems[20172].name, //Prospector's Token +42
                                uW.ksoItems[20173].name, //Fortune's Token +43
                                uW.ksoItems[20174].name, //Opportunity's Token +43
                                uW.ksoItems[20175].name, //Prospector's Token +43
                                uW.ksoItems[20176].name, //Fortune's Token +44
                                uW.ksoItems[20177].name, //Opportunity's Token +44
                                uW.ksoItems[20178].name, //Prospector's Token +44
                                uW.ksoItems[20179].name, //Fortune's Token +45
                                uW.ksoItems[20180].name, //Opportunity's Token +45
                                uW.ksoItems[20181].name, //Prospector's Token +45
                                uW.ksoItems[20182].name, //Fortune's Token +46
                                uW.ksoItems[20183].name, //Opportunity's Token +46
                                uW.ksoItems[20184].name, //Prospector's Token +46
                                uW.ksoItems[20185].name, //Fortune's Token +47
                                uW.ksoItems[20186].name, //Opportunity's Token +47
                                uW.ksoItems[20187].name, //Prospector's Token +47
                                uW.ksoItems[20188].name, //Fortune's Token +48
                                uW.ksoItems[20189].name, //Opportunity's Token +48
                                uW.ksoItems[20190].name, //Prospector's Token +48
                                uW.ksoItems[20191].name, //Fortune's Token +49
                                uW.ksoItems[20192].name, //Opportunity's Token +49
                                uW.ksoItems[20193].name, //Prospector's Token +49
                                uW.ksoItems[20194].name, //Fortune's Token +50
                                uW.ksoItems[20195].name, //Opportunity's Token +50
                                uW.ksoItems[20196].name, //Prospector's Token +50
                                uW.ksoItems[20197].name, //Fortune's Token +51
                                uW.ksoItems[20198].name, //Opportunity's Token +51
                                uW.ksoItems[20199].name //Prospector's Token +51

                                ];

            $(document.querySelector("#buffDropDown")).children("option").each(function () {
                if ($.inArray($(this).text(), removeItems) > -1) $(this).remove();
            });
            $(document.querySelector("#thronePanelBuffIcon")).removeClass().addClass('icon').addClass('i0');
            if (!STrChOGeneralOptions.useMastersTokens) $(document.querySelector("#thronePanelBuffPrice")).children("span.items").html('');

        }

        var doUpdradeChecks = function () {
            if (STrChOGeneralOptions.useMastersTokens) autoSelectMasters(); //v2.id is the throneItemID
            if (!STrChOGeneralOptions.useMastersTokens && STrChOGeneralOptions.removeMastersTokens) clearMasterTokens();
            if (!STrChOGeneralOptions.useMastersTokens && STrChOGeneralOptions.removeOtherTokens) clearOtherTokens();
            if (!STrChOGeneralOptions.useMastersTokens && STrChOGeneralOptions.buffsOff) unselectToken();
            if (STrChOGeneralOptions.safetyOn) throneSafetyCheck();
        }

        var doEnhanceChecks = function () {
            if (!STrChOGeneralOptions.useMastersTokens && STrChOGeneralOptions.buffsOff) unselectToken();
            if (STrChOGeneralOptions.safetyOn) throneSafetyCheck();
        }

        var addTabButtonChecks = function () {
            // register some callbacks when the buttons are pushed

            var pc = document.querySelector('#thronePanelContainer');
            $(pc).find("div.navigation ul").children("li.upgrade").click(function() {
                doUpdradeChecks();
                addTabButtonChecks();
            });

            $(pc).find("div.navigation ul").children("li.enhance").click(function() {
                doEnhanceChecks();
                addTabButtonChecks();
            });

            $(pc).find("div.navigation ul").children("li.jewel").click(function() {
                addTabButtonChecks();
            });
        }

        if (v1 == "upgrade") doUpdradeChecks();
        if (v1 == "enhance") doEnhanceChecks();

        addTabButtonChecks();
    }
    // hook up to the new function
    CM.ThronePanelView.renderPanel = newThroneRenderPanel;


	var oldAddJewel = CM.ThroneController.addJewel; //fixes the issue with adding/removing jewels and having it get stuck with the spinney
	var newAddJewel = function (aj, ai) {
		oldAddJewel(aj, ai);
		CM.ThronePanelView.removeSpinny();
	}
	CM.ThroneController.addJewel = newAddJewel;


	var oldRemoveJewel = CM.ThroneController.removeJewel;
	var newRemoveJewel = function (ak, ai) {
		oldRemoveJewel(ak, ai);
		CM.ThronePanelView.removeSpinny();
	}
	CM.ThroneController.removeJewel = newRemoveJewel;

    // override the salvageItem function to allow upgrade to +1 first
    var oldSalvageItem = CM.ThroneController.salvageItem;
    var newSalvageItem = function (item) {
        if ( STrChOThroneSalvageData.upgradeManual )
        {
            if (item && item.quality <= STrChOThroneSalvageData.upgradeFirstQual && item.level==0 )
            {
                var status = Tabs.throneSalvager.deleting;
                Tabs.throneSalvager.deleting = true;
                Tabs.throneUpgrader.doUpgrade(item.id,true);
                Tabs.throneSalvager.deleting = status;
            }
        }
        oldSalvageItem(item);
    };
    CM.ThroneController.salvageItem = newSalvageItem;


    var oldRenderInventory = CM.ThroneView.renderInventory;
    var newRenderInventory = function(l) {
        oldRenderInventory(l);

        $("ul#throneInventoryList > li > div").removeClass('STrChOBlueBorder');
        $("ul#throneInventoryList > li > div").removeClass('STrChOYellowBorder');
        for (ii in STrChOThroneQueueData.list) {
            var list_item = STrChOThroneQueueData.list[ii];
            if (!list_item) continue;
            if (list_item.status != "complete") {
                var id = list_item.item;

                if (list_item.action == "upgrade") $("div#throneInventoryItem" + id).addClass('STrChOBlueBorder');
                if (list_item.action == "enhance") $("div#throneInventoryItem" + id).addClass('STrChOYellowBorder');
            }
        }
        Tabs.thronePresets.paintTags();

    }
    CM.ThroneView.renderInventory = newRenderInventory;

    var oldOpenThrone = CM.ThroneView.openThrone;
    var newOpenThrone = function (F) {
        oldOpenThrone(F);

        STrChOSwapTile = null;

        if (STrChOGeneralOptions.draggableThroneItems) {
            $("#advisorContainer").draggable();
            $("#heroContainer").draggable();
            $("#chairContainer").draggable();
            $("#candelabrumContainer").draggable();
            $("#tableContainer").draggable();
            $("#windowContainer").draggable();
            $("#bannerContainer").draggable();
            $("#trophyContainer").draggable();
            $("#statueContainer").draggable();
            $("#petContainer").draggable();
            $("#tapestryContainer").draggable();
            $("#pillarContainer").draggable();
        }

        Tabs.throneSalvager.updateThroneMenu();
        Tabs.throneUpgrader.updateThroneMenu();
        Tabs.throneRepair.updateThroneMenu();
        Tabs.throneSorter.updateThroneMenu();

        $("ul#throneInventoryList > li > div").removeClass('STrChOBlueBorder');
        $("ul#throneInventoryList > li > div").removeClass('STrChOYellowBorder');

        for (ii in STrChOThroneQueueData.list) {
            var list_item = STrChOThroneQueueData.list[ii];
            if (!list_item) continue;
            if (list_item.status != "complete") {
                var id = list_item.item;
                if (list_item.action == "upgrade") $("div#throneInventoryItem" + id).addClass('STrChOBlueBorder');
                if (list_item.action == "enhance") $("div#throneInventoryItem" + id).addClass('STrChOYellowBorder');
            }
        }

        Tabs.thronePresets.paintTags();

        //these next few lines expands the throne inventory list
        var h = 564;
        var el1 = document.getElementById('throneStatList');
        if (el1) { h=h-el1.clientHeight; }
        $("ul#throneInventoryList").css('height', h+'px');
        $("div#throneInventoryContainer").css('height', h+'px');

        if (STrChOGeneralOptions.throneSorter) {
            if (STrChOThroneSorter.length == 0) resetThroneSorter();
            sortThroneSorter(false);
        }
    }
    CM.ThroneView.openThrone = newOpenThrone;

    CM.ContextualMenuThrone.renderMenu = CardContextMenu;

}

function STrChOThroneSorterEventListener(obj) {
    var throneId = obj.id.split('throneInventoryItem')[1];
    var throneItem = uW.kocThroneItems[throneId];
    if (STrChOSwapTile == null) { //this means i haven't clicked the first tile to swap yet, so set it and wait for the second to swap with
        STrChOSwapTile = throneId
        $(obj).prepend("<div class='swapBorderThrone'></div>");
    } else {
        if (throneId == STrChOSwapTile) {
            $('#throneInventoryItem' + STrChOSwapTile).children(".swapBorderThrone").remove();
            STrChOSwapTile = null;
            return;
        }
        $('#throneInventoryItem' + STrChOSwapTile).children(".swapBorderThrone").remove();

        var fromTile = document.getElementById('throneInventoryItem' + STrChOSwapTile);
        var fromTilePosition = 0;
        var child = fromTile;
        while( (child = child.previousSibling) != null ) fromTilePosition++;

        var toTile = document.getElementById('throneInventoryItem' + throneId);
        var toTilePosition = 0;
        child = obj;
        while( (child = child.previousSibling) != null ) toTilePosition++;

        var fromParent = fromTile.parentElement;
        var toParent = toTile.parentElement;

        var fromDelete = fromParent.children[fromTilePosition];
        var toDelete = toParent.children[toTilePosition];

        if (fromParent != toParent) { //simple swap
            $(fromDelete).remove();
            $(toDelete).remove();
            fromParent.insertBefore(toTile, fromParent.childNodes[fromTilePosition]);
            toParent.insertBefore(fromTile, toParent.childNodes[toTilePosition]);
        } else { //little more tricky
            var newRow = [];
            for (var idx = 0; idx < fromParent.children.length; idx++) {
                if (idx == fromTilePosition) {
                    newRow.unshift(toTile);
                } else if (idx == toTilePosition) {
                    newRow.unshift(fromTile);
                } else {
                    newRow.unshift(fromParent.children[idx]);
                }
            }
            while (fromParent.hasChildNodes()) fromParent.removeChild(fromParent.lastChild);
            while (newRow.length > 0) fromParent.appendChild(newRow.pop());
        }
        STrChOSwapTile = null;
        setThroneSorter(false);
        SAVESTrChOThroneSorter();
    }

}

function resetThroneSorter() {
    STrChOThroneSorter = [];
    counter = 0;
    for (var throneId in uW.kocThroneItems) {
        STrChOThroneSorter.push(throneId);
        counter++;
        if (counter == STrChOMaxThroneCards) break;
    }
    SAVESTrChOThroneSorter();
}

function sortThroneSorter(fromOrganizer) {  //you should never really call this function from the sorter tab because it won't do anything
    if (STrChOThroneSorter.length == 0) resetThroneSorter();
    var reorder = [];
    if (!fromOrganizer) {
        //store all the TILES in the sorter array and remove them from inventory
        for (var idx = 0; idx < STrChOThroneSorter.length; idx++) {
            var throneTile = document.getElementById('throneInventoryItem' + STrChOThroneSorter[idx]);
            if (!throneTile) continue;
            reorder.unshift(throneTile);
            $(throneTile).remove();
        }
        //check for any remaining TILES and store them temp and remove from inventory
        var throneInventoryList = document.getElementById('throneInventoryList');
        var throneRows = throneInventoryList.getElementsByClassName('active');
        for (var row = 0; row < throneRows.length; row++) {
            var throneRow = throneRows[row];
            if (throneRow.children.length > 0) {
                for (var c = 0; c < throneRow.children.length; c++) {
                    var throneTile = throneRow.children[c];
                    if (!throneTile) continue;
                    reorder.unshift(throneTile);
                }
                while (throneRow.firstChild) throneRow.removeChild(throneRow.firstChild);
            }
        }
        //by now, ALL TILES should be in the reorder array, time to put them back up on the display
        var throneInventoryList = document.getElementById('throneInventoryList');
        var throneRows = throneInventoryList.getElementsByClassName('active');
        for (var row = 0; row < throneRows.length; row++) {
            var throneRow = throneRows[row];
            for (var c = 0; c < 5; c++) {
                var throneTile = reorder.pop();
                if (!throneTile) continue;
                throneTile.addEventListener('contextmenu', function(evt) {
                    evt.preventDefault();
                    STrChOThroneSorterEventListener(this);
                }, false);
                throneRow.appendChild(throneTile);
            }
        }
        setThroneSorter(fromOrganizer);
    }
}

function setThroneSorter(fromOrganizer) {
    if (STrChOThroneSorter.length == 0) resetThroneSorter();
    var reorder = [];
    var notIn = [];

    if (fromOrganizer) {
        var STrChOThroneSorterInventoryList = document.getElementById('STrChOThroneSorterInventoryList');
        var throneRows = STrChOThroneSorterInventoryList.getElementsByClassName('active');
        for (var row = 0; row < throneRows.length; row++) {
            var throneRow = throneRows[row];
            if (throneRow.children.length > 0) {
                for (var col = 0; col < throneRow.children.length; col++) {
                    var throneDiv = throneRow.children[col];
                    if (!throneDiv) continue;
                    var cellId = throneDiv.id;
                    var throneId = cellId.split('STrChOThroneSorterInventoryIcon')[1];
                    if (STrChOThroneSorter.indexOf(throneId) == -1) {
                        notIn.unshift(throneId);
                    } else {
                        reorder.unshift(throneId);
                    }
                }
            }
        }
    } else {
        var throneInventoryList = document.getElementById('throneInventoryList');
        var throneRows = throneInventoryList.getElementsByClassName('active');
        for (var row = 0; row < throneRows.length; row++) {
            var throneRow = throneRows[row];
            if (throneRow.children.length > 0) {
                for (var col = 0; col < throneRow.children.length; col++) {
                    var cellId = throneRow.children[col].id;
                    var throneId = cellId.split('throneInventoryItem')[1];
                    if (STrChOThroneSorter.indexOf(throneId) == -1) {
                        notIn.unshift(throneId);
                    } else {
                        reorder.unshift(throneId);
                    }
                }
            }
        }
    }
    STrChOThroneSorter = [];
    while (reorder.length > 0) STrChOThroneSorter.push(reorder.pop());
    while (notIn.length > 0) STrChOThroneSorter.push(notIn.pop());
}

function isUndefined(obj) {
    if (typeof(obj) == 'undefined')
        return true;
    else
        return false;
}

function indexOfChampCard(Id) {
    var counter = 0;
    for (var champId in uW.kocChampionItems) {
        counter += 1;
        if (champId == Id) return counter;
    }
    return counter;
}

function indexOfThroneCard(Id) {
    var counter = 0;
    for (var throneId in uW.kocThroneItems) {
        counter += 1;
        if (throneId == Id) return counter;
    }
    return counter;
}

function countHowManyThroneCards() {
    var counter = 0;
    for (var throneId in uW.kocThroneItems) counter ++;
    return counter;
}

function countHowManyChampCards() {
    var counter = 0;
    for (var champId in uW.kocChampionItems) counter++;
    return counter;
}

function countHowManyThroneSlots(Id) {
    var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);
    var counter = 0;
    for (var slot = 1; slot < presetSlots + 1; slot++) {
        var throneItems = Seed.throne.slotEquip[slot];
        for (itemIdx = 0; itemIdx < throneItems.length; itemIdx++)
            if (Id == throneItems[itemIdx]) counter++;
    }
    return counter;
}

function howManyThroneSlots(Id) {
    var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);
    var presetSlotsFound = [];
    var presetSlotMsg = '';
    for (var slot = 1; slot < presetSlots + 1; slot++) {
        var throneItems = Seed.throne.slotEquip[slot];
        for (itemIdx = 0; itemIdx < throneItems.length; itemIdx++) {
            if (Id == throneItems[itemIdx]) {
                if (presetSlotsFound.length % 8 == 0) {
                    presetSlotsFound.push('<br>' + slot);
                } else {
                    presetSlotsFound.push(slot);
                }
            }
        }
    }
    if (presetSlotsFound.length > 0) {
        presetSlotMsg = 'Card Found In The<br>Following Preset Slots:' + presetSlotsFound.join(', ');
    } else {
        presetSlotMsg = 'Not In Any Presets';
    }
    return presetSlotMsg;
}

function whichChampSlot(Id) {
    var presetSlotMsg = '';
    var champItem = uW.kocChampionItems[Id];
    var championId = champItem.equippedTo;
    for (var i = 1; i < STrChOMaxChampions+1; i++) {
        var thisChampion = Seed.champion.champions[i-1];
        if (thisChampion.championId == championId) {
            presetSlotMsg = 'Item Equipped To<br> Champ In Slot ' + i + '<br>Name: ' + thisChampion.name;
            break;
        }
    }
    return presetSlotMsg;
}

var CardContextMenu = function (tileDiv, theItem, fromOrganizer) {

    if (typeof(fromOrganizer) == 'undefined') fromOrganizer = false;

    if (theItem == null) {
        ThroneOldRenderMenu(tileDiv, theItem);
        return;
    }

    var lastMenuItem = null;

    var throneItem = theItem;
    var champItem = theItem;

    var isThrone = (typeof(champItem.equipmentId) == 'undefined');
    var hasJewel = false;

    var cmContainerOpen = (document.getElementsByClassName('cmModalContainer').length == 1 ? true : false);

    var itemIndex = 0;
    var isBroken = false;
    var isRepairing = false;
    var isRepairAll = false;
    var itemId = null;
    var itemLevel = 0;

    var presetSlot = 1;
    var championId = Seed.champion.champions[presetSlot-1].championId;
    var presetTagCount = 0;
    var howManyMessage = '';
    var inPresets = false;

    if (isThrone) {
        if (!fromOrganizer) ThroneOldRenderMenu(tileDiv, theItem);
        if (throneItem.jewel) {
            if (throneItem.jewel.valid) hasJewel = true;
        }
        //hasJewel = throneItem.jewel.valid;
        isBroken = throneItem.isBroken
        presetSlot = Seed.throne.activeSlot;
        isRepairAll = isAnyThroneBroke();
        presetTagCount = getThronePresetTagCount(presetSlot);
        itemId = throneItem.id;
        itemIndex = indexOfThroneCard(itemId);
        itemLevel = throneItem.level;
        howManyMessage = howManyThroneSlots(itemId);
        if (countHowManyThroneSlots(itemId) > 0) inPresets = true;
    } else {
        isBroken = (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE);
        isRepairing = (champItem.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE || champItem.status == CM.CHAMPION.STATUS_REPAIRING_UPGRADE);
        if (!fromOrganizer) {
            for (i = 0; i < STrChOMaxChampions; i++) {
                var champClass = $(".champion_states").children(".name" + i).attr('class');
                if ( champClass.indexOf("active") == -1) continue;
                presetSlot = i + 1;
                break;
            }
        }
        isRepairAll = isAnyChampBroke();
        presetTagCount = getChampPresetTagCount(presetSlot);
        itemId = champItem.equipmentId;
        itemIndex = indexOfChampCard(itemId);
        itemLevel = champItem.level;
        howManyMessage = whichChampSlot(itemId);
        if (howManyMessage != '') {
            inPresets = true;
        } else {
            howManyMessage = 'Not Equipped';
        }
    }

    if (!fromOrganizer) {
        uW.removeTooltip();
        uW.Tooltip.hide();
    }

    function ContextMenuExpandCollapse(menuItem, isExpanding) {
        var menuSubItemClass = menuItem.id + "_SubItem";
        var SubItems = document.getElementsByClassName(menuSubItemClass);
        for (var idx = 0; idx < SubItems.length; idx++) {
            var menuSubItem = SubItems[idx];
            if (isExpanding)
                menuSubItem.className = menuSubItem.className.replace('STrChOContextHidden', 'STrChOContextVisible');
            else
                menuSubItem.className = menuSubItem.className.replace('STrChOContextVisible', 'STrChOContextHidden');
        }
    }

    var STrChOContextMenu = document.getElementById("contextMenu");
    if (STrChOContextMenu) {
        while (STrChOContextMenu.hasChildNodes()) STrChOContextMenu.removeChild(STrChOContextMenu.lastChild);
    } else {
        STrChOContextMenu = document.createElement('div');
        STrChOContextMenu.addEventListener('mouseleave', function () {
            $(this).remove();
        }, false);
    }

    if (isThrone)
        STrChOContextMenu.innerHTML = throneItem.type.capitalizeFirstLetter() + '+' + itemLevel;  //throneItem.name.replace(/ /g, '<br>');
    else
        STrChOContextMenu.innerHTML = champItemNames[champItem.type].capitalizeFirstLetter() + '+' + itemLevel; //champItem.name.replace(/ /g, '<br>');

    STrChOContextMenu.className = 'STrChOContextMenu';

    var STrChOContextMenuUpgrading = document.createElement('div');
    STrChOContextMenuUpgrading.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuUpgrading.innerHTML = 'UPGRADING';
    STrChOContextMenuUpgrading.id = 'STrChOContextMenuUpgrading';
    STrChOContextMenuUpgrading.addEventListener('click', function(A) {
        A.stopPropagation();
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuUpgrading);

    var STrChOContextMenuUpgrading_AutoUpg = document.createElement('div');
    STrChOContextMenuUpgrading_AutoUpg.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuUpgrading_SubItem';
    STrChOContextMenuUpgrading_AutoUpg.innerHTML = 'Auto Upgrade';
    if ( (isThrone && throneItem.level < STrChOMaxThroneLevel) || (!isThrone && champItem.level < STrChOMaxChampLevel) ) {
        STrChOContextMenuUpgrading_AutoUpg.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone)
                Tabs.throneUpgrader.addUpgradeItem(itemId);
            else
                Tabs.champUpgrader.addUpgradeItem(itemId);
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuUpgrading_AutoUpg.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuUpgrading_AutoUpg);

    var STrChOContextMenuUpgrading_Upgrade = document.createElement('div');
    STrChOContextMenuUpgrading_Upgrade.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuUpgrading_SubItem';
    STrChOContextMenuUpgrading_Upgrade.innerHTML = 'Upgrade';
    if ( ( (isThrone && throneItem.level < STrChOMaxThroneLevel) || (!isThrone && champItem.level < STrChOMaxChampLevel) ) && !isBroken ) {
        STrChOContextMenuUpgrading_Upgrade.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone) {
                if (!cmContainerOpen) CM.ThroneView.openThrone();
                CM.ThronePanelView.renderPanel("upgrade", throneItem)
            } else {
                if (!cmContainerOpen) CM.ChampionModalController.open();
                CM.ChampionModalView.upgEnhSlideIn(itemId, "upg");
            }
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuUpgrading_Upgrade.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuUpgrading_Upgrade);

    var STrChOContextMenuEnhancing = document.createElement('div');
    STrChOContextMenuEnhancing.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuEnhancing.innerHTML = 'ENHANCING';
    STrChOContextMenuEnhancing.id = 'STrChOContextMenuEnhancing';
    STrChOContextMenuEnhancing.addEventListener('click', function(A) {
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        A.stopPropagation();
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuEnhancing);


    var STrChOContextMenuEnhancing_AutoEnh = document.createElement('div');
    STrChOContextMenuEnhancing_AutoEnh.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuEnhancing_SubItem';
    STrChOContextMenuEnhancing_AutoEnh.innerHTML = 'Auto Enhance';
    if ( (isThrone && throneItem.quality < STrChOMaxThroneQuality) || (!isThrone && champItem.rarity < STrChOMaxChampQuality) ) {
        STrChOContextMenuEnhancing_AutoEnh.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone)
                Tabs.throneUpgrader.addEnhanceItem(itemId);
            else
                Tabs.champUpgrader.addEnhanceItem(itemId);
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuEnhancing_AutoEnh.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuEnhancing_AutoEnh);

    var STrChOContextMenuEnhancing_Enhance = document.createElement('div');
    STrChOContextMenuEnhancing_Enhance.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuEnhancing_SubItem';
    STrChOContextMenuEnhancing_Enhance.innerHTML = 'Enhance';
    if (!fromOrganizer) {
        if ( ( (isThrone && throneItem.quality < STrChOMaxThroneQuality) || (!isThrone && champItem.rarity < STrChOMaxChampQuality) ) && !isBroken ) {
            STrChOContextMenuEnhancing_Enhance.addEventListener('click', function(A) {
                A.stopPropagation();
                if (isThrone) {
                    if (!cmContainerOpen) CM.ThroneView.openThrone();
                    CM.ThronePanelView.renderPanel("enhance", throneItem)
                } else {
                    if (!cmContainerOpen) CM.ChampionModalController.open();
                    CM.ChampionModalView.upgEnhSlideIn(itemId, "enh");
                }
                $(STrChOContextMenu).remove();
            }, false);
        } else {
            STrChOContextMenuEnhancing_Enhance.className += ' STrChODisabled';
        }
    } else {
        STrChOContextMenuEnhancing_Enhance.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuEnhancing_Enhance);

    var STrChOContextMenuEnhancing_Jewel = document.createElement('div');
    STrChOContextMenuEnhancing_Jewel.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuEnhancing_SubItem';
    STrChOContextMenuEnhancing_Jewel.innerHTML = 'Jewel';
    if (isThrone && !isBroken) {
        STrChOContextMenuEnhancing_Jewel.addEventListener('click', function(A) {
            A.stopPropagation();
            if (!cmContainerOpen) CM.ThroneView.openThrone();
            CM.ThronePanelView.renderPanel("jewel", throneItem)
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuEnhancing_Jewel.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuEnhancing_Jewel);

    var STrChOContextMenuEquipping = document.createElement('div');
    STrChOContextMenuEquipping.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuEquipping.innerHTML = 'EQUIPPING';
    STrChOContextMenuEquipping.id = 'STrChOContextMenuEquipping';
    STrChOContextMenuEquipping.addEventListener('click', function(A) {
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        A.stopPropagation();
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuEquipping);

    var STrChOContextMenuEquipping_Equip = document.createElement('div');
    STrChOContextMenuEquipping_Equip.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOGreen STrChOContextMenuEquipping_SubItem';
    STrChOContextMenuEquipping_Equip.innerHTML = 'Equip';
    if (!isBroken) {
        if ( (!throneItem.isEquipped && isThrone) || (!isThrone && champItem.equippedTo != championId) ) {
            STrChOContextMenuEquipping_Equip.addEventListener('click', function(A) {
                A.stopPropagation();
                if (isThrone)
                    CM.ThroneController.equipItem(throneItem);
                else
                    Tabs.champPresets.equipItem(itemId);
                    //CM.ChampionManager.equipItem(chId);
                $(STrChOContextMenu).remove();
            }, false);
        } else {
            STrChOContextMenuEquipping_Equip.className += ' STrChODisabled';
        }
    } else {
        STrChOContextMenuEquipping_Equip.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuEquipping_Equip);

    var STrChOContextMenuEquipping_Unequip = document.createElement('div');
    STrChOContextMenuEquipping_Unequip.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOGreen STrChOContextMenuEquipping_SubItem';
    STrChOContextMenuEquipping_Unequip.innerHTML = 'Unequip';
    if (!isBroken) {
        if ( (throneItem.isEquipped && isThrone) || (!isThrone && champItem.equippedTo != 0) ) {
            STrChOContextMenuEquipping_Unequip.addEventListener('click', function(A) {
                A.stopPropagation();
                if (isThrone)
                    CM.ThroneController.unequipItem(throneItem);
                else
                    Tabs.champPresets.unequipItem(itemId);
                    //CM.ChampionManager.unequipItem(itemId);
                $(STrChOContextMenu).remove();
            }, false);
        } else {
            STrChOContextMenuEquipping_Unequip.className += ' STrChODisabled';
        }
    } else {
        STrChOContextMenuEquipping_Unequip.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuEquipping_Unequip);


    var STrChOContextMenuEquipping_UnequipAll = document.createElement('div');
    STrChOContextMenuEquipping_UnequipAll.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOGreen STrChOContextMenuEquipping_SubItem';
    STrChOContextMenuEquipping_UnequipAll.innerHTML = 'Unequip All';
    STrChOContextMenuEquipping_UnequipAll.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone)
            Tabs.thronePresets.unequipAllItems(presetSlot);
        else
            Tabs.champPresets.unequipAllItems(presetSlot);
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuEquipping_UnequipAll);


    var STrChOContextMenuRepair = document.createElement('div');
    STrChOContextMenuRepair.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuRepair.innerHTML = 'REPAIR';
    STrChOContextMenuRepair.id = 'STrChOContextMenuRepair';
    STrChOContextMenuRepair.addEventListener('click', function(A) {
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        A.stopPropagation();
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuRepair);


    var STrChOContextMenuRepair_Repair = document.createElement('div');
    STrChOContextMenuRepair_Repair.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuRepair_SubItem';
    STrChOContextMenuRepair_Repair.innerHTML = 'Repair Card';
    if (isBroken || (isRepairing && !isThrone) ) {
        STrChOContextMenuRepair_Repair.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone)
                CM.ThronePanelView.renderBroken(throneItem);
            else
                CM.ChampionPanelView.renderBroken(champItem);
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuRepair_Repair.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuRepair_Repair);


    var STrChOContextMenuRepair_AutoRepair = document.createElement('div');
    STrChOContextMenuRepair_AutoRepair.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuRepair_SubItem';
    STrChOContextMenuRepair_AutoRepair.innerHTML = 'Auto Repair';
    if (isBroken) {
        STrChOContextMenuRepair_AutoRepair.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone) {
                Tabs.throneRepair.addQueue(itemId);
                Tabs.throneRepair.buildThroneRepairDisplay();
            } else {
                Tabs.champRepair.addQueue(itemId);
                Tabs.champRepair.buildChampRepairDisplay();
            }
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuRepair_AutoRepair.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuRepair_AutoRepair);


    var STrChOContextMenuRepair_AutoRepairAll = document.createElement('div');
    STrChOContextMenuRepair_AutoRepairAll.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuRepair_SubItem';
    STrChOContextMenuRepair_AutoRepairAll.innerHTML = 'Auto Repair All';
    if (isRepairAll) {
        STrChOContextMenuRepair_AutoRepairAll.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone) {
                Tabs.throneRepair.addAllQueue();
                Tabs.throneRepair.buildThroneRepairDisplay();
            } else {
                Tabs.champRepair.addAllQueue();
                Tabs.champRepair.buildChampRepairDisplay();
            }
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuRepair_AutoRepairAll.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuRepair_AutoRepairAll);

    var STrChOContextMenuSalvaging = document.createElement('div');
    STrChOContextMenuSalvaging.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuSalvaging.innerHTML = 'SALVAGING';
    STrChOContextMenuSalvaging.id = 'STrChOContextMenuSalvaging';
    STrChOContextMenuSalvaging.addEventListener('click', function(A) {
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        A.stopPropagation();
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuSalvaging);

    var STrChOContextMenuSalvaging_Salvage = document.createElement('div');
    STrChOContextMenuSalvaging_Salvage.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuSalvaging_SubItem';
    STrChOContextMenuSalvaging_Salvage.innerHTML = 'Salvage';
    if (!isBroken) {
        if (!(inPresets && STrChOGeneralOptions.noEquippedSalvage)) {
            if (((!STrChOGeneralOptions.throneSalvageSafety) || (STrChOGeneralOptions.throneSalvageSafety && itemIndex > STrChOGeneralOptions.throneSalvageSafetyNum)) ||
            ((!STrChOGeneralOptions.champSalvageSafety) || (STrChOGeneralOptions.champSalvageSafety && itemIndex > STrChOGeneralOptions.champSalvageSafetyNum))) {
                if (!isThrone || (isThrone && !hasJewel)) {
                    STrChOContextMenuSalvaging_Salvage.addEventListener('click', function(A) {
                        A.stopPropagation();
                        if (confirm('Are you sure you want to salvage this item?')) {
                            if (isThrone) {
                                SalvageThroneItem(itemId);
                            } else {
                                SalvageChampItem(itemId);
                                if (cmContainerOpen) CM.ChampionModalController.open()
                                Tabs.champPreview.clearChampPreviewCard(itemId);
                                Tabs.champOrganizer.paintChampTables();
                            }
                        }
                        $(STrChOContextMenu).remove();
                    }, false);
                } else {
                    STrChOContextMenuSalvaging_Salvage.className += ' STrChODisabled';
                }
            } else {
                STrChOContextMenuSalvaging_Salvage.className += ' STrChODisabled';
            }
        } else {
            STrChOContextMenuSalvaging_Salvage.className += ' STrChODisabled';
        }
    } else {
        STrChOContextMenuSalvaging_Salvage.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuSalvaging_Salvage);


    var STrChOContextMenuSalvaging_Forced = document.createElement('div');
    STrChOContextMenuSalvaging_Forced.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuSalvaging_SubItem';
    STrChOContextMenuSalvaging_Forced.innerHTML = 'Forced Salvage';
    if (!isBroken && isThrone && hasJewel && !STrChOGeneralOptions.noForcedSalvage) {
        if (!(inPresets && STrChOGeneralOptions.noEquippedSalvage)) {
            STrChOContextMenuSalvaging_Forced.addEventListener('click', function(A) {
                A.stopPropagation();
                if (confirm('Are you sure you want to forced salvage this item?')) Tabs.throneSalvager.forceSalvage(itemId);
                $(STrChOContextMenu).remove();
            }, false);
        } else {
            STrChOContextMenuSalvaging_Forced.className += ' STrChODisabled';
        }
    } else {
        STrChOContextMenuSalvaging_Forced.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuSalvaging_Forced);


    var STrChOContextMenuSalvaging_Mass = document.createElement('div');
    STrChOContextMenuSalvaging_Mass.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOBlue STrChOContextMenuSalvaging_SubItem';
    STrChOContextMenuSalvaging_Mass.innerHTML = 'Mass Salvage';
    if (!STrChOGeneralOptions.noMassSalvage) {
        STrChOContextMenuSalvaging_Mass.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone)
                CM.ThroneView.renderMassSalvage();
            else
                CM.ChampionModalView.renderMassSalvage();
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuSalvaging_Mass.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuSalvaging_Mass);

    var STrChOContextMenuStats = document.createElement('div');
    STrChOContextMenuStats.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuStats.innerHTML = 'STATS';
    STrChOContextMenuStats.id = 'STrChOContextMenuStats';
    STrChOContextMenuStats.addEventListener('click', function(A) {
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        A.stopPropagation();
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuStats);


    var STrChOContextMenuStats_Copy = document.createElement('div');
    STrChOContextMenuStats_Copy.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuStats_SubItem';
    STrChOContextMenuStats_Copy.innerHTML = 'Copy Stats';
    STrChOContextMenuStats_Copy.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone) {
            var displayText = getThroneItemStats(itemId, "    ");
            if (displayText != "") window.prompt("Copy to clipboard: Ctrl+C", displayText);
        } else {
            var displayText = getChampItemStats(itemId, "    ");
            if (displayText != "") window.prompt("Copy to clipboard: Ctrl+C", displayText);
        }
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuStats_Copy);


    var STrChOContextMenuStats_Post = document.createElement('div');
    STrChOContextMenuStats_Post.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuStats_SubItem';
    STrChOContextMenuStats_Post.innerHTML = 'Post Stats';
    STrChOContextMenuStats_Post.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone)
            sendChat(getThroneItemStats(itemId, '||'));
        else
            sendChat(getChampItemStats(itemId, '||'));
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuStats_Post);


    var STrChOContextMenuStats_Export = document.createElement('div');
    STrChOContextMenuStats_Export.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuStats_SubItem';
    STrChOContextMenuStats_Export.innerHTML = 'Export Cards';
    STrChOContextMenuStats_Export.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone)
            ExportThroneToExcel(false);
        else
            ExportChampToExcel(false);
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuStats_Export);

    var STrChOContextMenuStats_Compare = document.createElement('div');
    STrChOContextMenuStats_Compare.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuStats_SubItem';
    STrChOContextMenuStats_Compare.innerHTML = 'Send To Compare';
    STrChOContextMenuStats_Compare.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone)
            Tabs.throneCompare.sendToCompare(itemId);
        else
            Tabs.champCompare.sendToCompare(itemId);
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuStats_Compare);


    var STrChOContextMenuPresets = document.createElement('div');
    STrChOContextMenuPresets.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuPresets.innerHTML = 'PRESETS';
    STrChOContextMenuPresets.id = 'STrChOContextMenuPresets';
    STrChOContextMenuPresets.addEventListener('click', function(A) {
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        A.stopPropagation();
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuPresets);


    var STrChOContextMenuPresets_EquipPreset = document.createElement('div');
    STrChOContextMenuPresets_EquipPreset.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuPresets_SubItem';
    STrChOContextMenuPresets_EquipPreset.innerHTML = 'Equip Tag #' + presetSlot;
    if (presetTagCount != 0) {
        STrChOContextMenuPresets_EquipPreset.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone)
                Tabs.thronePresets.equipPresetTags(presetSlot);
            else
                Tabs.champPresets.equipPresetTags(presetSlot);
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuPresets_EquipPreset.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuPresets_EquipPreset);


    var STrChOContextMenuPresets_ClearPreset = document.createElement('div');
    STrChOContextMenuPresets_ClearPreset.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuPresets_SubItem';
    STrChOContextMenuPresets_ClearPreset.innerHTML = 'Clear Tag #' + presetSlot;
    if (presetTagCount != 0) {
        STrChOContextMenuPresets_ClearPreset.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone) {
                Tabs.thronePresets.clearPresetTags(presetSlot);
                Tabs.thronePresets.paintTags();
            } else {
                Tabs.champPresets.clearPresetTags(presetSlot);
                Tabs.champPresets.paintTags();
            }
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuPresets_ClearPreset.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuPresets_ClearPreset);


    var STrChOContextMenuPresets_SavePreset = document.createElement('div');
    STrChOContextMenuPresets_SavePreset.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuPresets_SubItem';
    STrChOContextMenuPresets_SavePreset.innerHTML = 'Save Tag #' + presetSlot;
    STrChOContextMenuPresets_SavePreset.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone) {
            Tabs.thronePresets.addPresetTags(presetSlot);
            Tabs.thronePresets.paintTags();
        } else {
            Tabs.champPresets.addPresetTags(presetSlot);
            Tabs.champPresets.paintTags();
        }
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuPresets_SavePreset);


    var STrChOContextMenuPresets_LoadToPreview = document.createElement('div');
    STrChOContextMenuPresets_LoadToPreview.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChORed STrChOContextMenuPresets_SubItem';
    STrChOContextMenuPresets_LoadToPreview.innerHTML = 'Send To Preview';
    STrChOContextMenuPresets_LoadToPreview.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone) {
            Tabs.thronePreview.loadThronePreviewCard(itemId, throneItem.type);
            //Tabs.thronePreview.buildThronePreviewValueDisplay();
        } else {
            Tabs.champPreview.loadChampPreviewCard(itemId);
            Tabs.champPreview.buildChampPreviewValueDisplay();
        }
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuPresets_LoadToPreview);


    var STrChOContextMenuTagging = document.createElement('div');
    STrChOContextMenuTagging.className = 'STrChOContextMenuItem STrChOBrown';
    STrChOContextMenuTagging.innerHTML = 'TAGGING';
    STrChOContextMenuTagging.id = 'STrChOContextMenuTagging';
    STrChOContextMenuTagging.addEventListener('click', function(A) {
        if (lastMenuItem == this) {
            ContextMenuExpandCollapse(this, false);
            lastMenuItem = null;
            return;
        }
        A.stopPropagation();
        if (lastMenuItem == null) lastMenuItem = this;
        if (lastMenuItem.id != this.id) ContextMenuExpandCollapse(lastMenuItem, false);
        ContextMenuExpandCollapse(this, true);
        lastMenuItem = this;
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuTagging);


    var STrChOContextMenuTagging_TagItem = document.createElement('div');
    STrChOContextMenuTagging_TagItem.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOGreen STrChOContextMenuTagging_SubItem';
    STrChOContextMenuTagging_TagItem.innerHTML = 'Tag Item';
    if ( (!STrChOThronePresetData.taggedItems[itemId] && isThrone) || (!STrChOChampPresetData.taggedItems[itemId] && !isThrone) ) {
        STrChOContextMenuTagging_TagItem.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone) {
                Tabs.thronePresets.addTagItem(itemId);
                Tabs.thronePresets.paintTags();
            } else {
                Tabs.champPresets.addTagItem(itemId);
                Tabs.champPresets.paintTags();
            }
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuTagging_TagItem.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuTagging_TagItem);


    var STrChOContextMenuTagging_RemoveTag = document.createElement('div');
    STrChOContextMenuTagging_RemoveTag.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOGreen STrChOContextMenuTagging_SubItem';
    STrChOContextMenuTagging_RemoveTag.innerHTML = 'Remove Tag';
    if ( (STrChOThronePresetData.taggedItems[itemId] && isThrone) || (STrChOChampPresetData.taggedItems[itemId] && !isThrone) ) {
        STrChOContextMenuTagging_RemoveTag.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone) {
                Tabs.thronePresets.removeTagItem(itemId);
                Tabs.thronePresets.paintTags();
            } else {
                Tabs.champPresets.removeTagItem(itemId);
                Tabs.champPresets.paintTags();
            }
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuTagging_RemoveTag.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuTagging_RemoveTag);


    var STrChOContextMenuTagging_TagItemAll = document.createElement('div');
    STrChOContextMenuTagging_TagItemAll.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOGreen STrChOContextMenuTagging_SubItem';
    STrChOContextMenuTagging_TagItemAll.innerHTML = 'Tag All';
    STrChOContextMenuTagging_TagItemAll.addEventListener('click', function(A) {
        A.stopPropagation();
        if (isThrone) {
            Tabs.thronePresets.addAllTagItems();
            Tabs.thronePresets.paintTags();
        } else {
            Tabs.champPresets.addAllTagItems();
            Tabs.champPresets.paintTags();
        }
        $(STrChOContextMenu).remove();
    }, false);
    STrChOContextMenu.appendChild(STrChOContextMenuTagging_TagItemAll);


    var STrChOContextMenuTagging_RemoveTagAll = document.createElement('div');
    STrChOContextMenuTagging_RemoveTagAll.className = 'STrChOContextMenuSubItem STrChOContextHidden STrChOGreen STrChOContextMenuTagging_SubItem';
    STrChOContextMenuTagging_RemoveTagAll.innerHTML = 'Remove All Tags';
    if ( (isThrone && getObjectCollectionCount(STrChOThronePresetData.taggedItems) > 0) ||
         (!isThrone && getObjectCollectionCount(STrChOChampPresetData.taggedItems) > 0) ) {
        STrChOContextMenuTagging_RemoveTagAll.addEventListener('click', function(A) {
            A.stopPropagation();
            if (isThrone) {
                Tabs.thronePresets.clearAllTagItems();
                Tabs.thronePresets.paintTags();
            } else {
                Tabs.champPresets.removeAllTagItems();
                Tabs.champPresets.paintTags();
            }
            $(STrChOContextMenu).remove();
        }, false);
    } else {
        STrChOContextMenuTagging_RemoveTagAll.className += ' STrChODisabled';
    }
    STrChOContextMenu.appendChild(STrChOContextMenuTagging_RemoveTagAll);

    var STrChOContextMenuCardInfo = document.createElement('div');
    STrChOContextMenuCardInfo.innerHTML = howManyMessage;

    STrChOContextMenu.appendChild(STrChOContextMenuCardInfo);

    if (fromOrganizer) tileDiv.insertBefore(STrChOContextMenu,  tileDiv.firstChild);

}

var sectionOpener = function() {
    var imgs = this.childNodes;
    if (imgs[0].src == STrChODownArrow) {
        imgs[0].src = STrChORightArrow
        imgs[2].src = STrChORightArrow
    } else {
        imgs[0].src = STrChODownArrow
        imgs[2].src = STrChODownArrow
    }
    var section = this.nextSibling;
    if (section.className != "STrChOSection") return;
    var sections = document.getElementsByClassName('STrChOSection');
    for (var sect=0;sect<sections.length;sect++) {
        if (section != sections[sect]) {
            sections[sect].style.display = "none";
            var nextImgs = sections[sect].previousSibling.childNodes;
            nextImgs[0].src = STrChORightArrow
            nextImgs[2].src = STrChORightArrow
        }
    }
    if (section.style.display == "block") {
        section.style.display = "none";
    } else {
        section.style.display = "block";
    }
};

//onClick (city{name, id, x, y}, x, y) city may be null!
function CdispCityPicker (id, span, dispName, notify, selbut){
    function CcityButHandler (t) {
        var that = t;

        function clickedCityBut (e){
            if (that.selected != null)
                that.selected.className = "STrChOCastleButton STrChOCastleButtonNot";
            that.city = Cities.cities[e.target.id.substr(that.prefixLen)];
            if (that.dispName)
                document.getElementById(that.id+'cname').innerHTML = that.city.name;
            e.target.className = "STrChOCastleButton STrChOCastleButtonSelect";
            that.selected = e.target;
            if (that.coordBoxX){
                that.coordBoxX.value = that.city.x;
                that.coordBoxY.value = that.city.y;
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent('change', true, true ); // event (type,bubbling,cancelable)
                that.coordBoxX.dispatchEvent(evt);
                that.coordBoxY.dispatchEvent(evt);
                that.coordBoxX.style.backgroundColor = '#ffffff';
                that.coordBoxY.style.backgroundColor = '#ffffff';
            }
            if (that.notify != null)
                that.notify(that.city, that.city.x, that.city.y);
        }

        this.clickedCityBut = clickedCityBut;
    }

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

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

    this.selectBut = selectBut;
    this.bindToXYboxes = bindToXYboxes;
    this.coordBoxX = null;
    this.coordBoxY = null;
    this.id = id;
    this.dispName = dispName;
    this.prefixLen = id.length+1;
    this.notify = notify;
    this.selected = null;
    this.city = null;
    var m = '';
    for (var i=0; i < Cities.cities.length; i++)
        m += '<input class="STrChOCastleButton STrChOCastleButtonNot" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=button />';
    if (dispName)
        m += ' &nbsp; <span style="display:inline-block; width:85px; font-weight:bold;" id='+ id +'cname' +'></span>';
    span.innerHTML = m;
    var handler = new CcityButHandler(this);
    for (var i=0; i < Cities.cities.length; i++)
        document.getElementById (id+'_'+i).addEventListener('click', handler.clickedCityBut, false);
    if (selbut != null)
        this.selectBut(selbut);
};

function upgradeIt(citynum, chId, cost) {
    var t = Tabs.champPresets;
    var params = uW.Object.clone(ajfx);
    params.action = '5';
    params.cityId = citynum;
    params.eid = chId;
    params.chanceItem = 0;
    params.aetherstones = cost;
    params.gems = 0;
	new AjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
		method: "post",
		parameters: params,
		loading: true,
		onSuccess: function (transport) {
            try {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
                    t.broke_items += 1;
                    t.setBreakStatus();
                    Seed.resources["city" + citynum]["rec5"][0] = Seed.resources["city" + citynum]["rec5"][0] - parseInt(rslt.aetherstones);
					if (rslt.updateSeed) uW.update_seed(rslt.updateSeed);
				}
				if (rslt.gems > 0) {
                	alert("UNEXPECTED ERROR: 'BREAK CH' accidentally spent gems.... Refreshing to stop the feature now!");
                    ActionLog('BREAK CH accidentally spent gems!  Stopping now!');
                    RefreshCamelot();
                    return false;
                }
	        } catch (e) {
	        }
		},
		onFailure: function (rrr) {
		}
	});
    return true;
}

function repairTimeToText(total_time) {
    var secondsInMinutes = 60;
    var secondsInHours = 3600;
    var secondsInDays = 43200;

    var totalDays = 0;
    var totalHours = 0;
    var totalMinutes = 0;

    if (total_time > secondsInDays) {
        totalDays = (total_time - (total_time % secondsInDays)) / secondsInDays;
        total_time = total_time % secondsInDays;
    }
    if (total_time > secondsInHours) {
        totalHours = (total_time - (total_time % secondsInHours)) / secondsInHours;
        total_time = total_time % secondsInHours;
    }
    if (total_time > secondsInMinutes) {
        totalMinutes = (total_time - (total_time % secondsInMinutes)) / secondsInMinutes;
        total_time = total_time % secondsInMinutes;
    }
    var totalSeconds = total_time;

    return (totalDays + " Days " + totalHours + " Hours " + totalMinutes + " Minutes " + totalSeconds + " Seconds");
};

function ExportChampPresetToExcel(presetNumber) {
    var headers = [ "ID", "NAME", "FACTION", "QUALITY", "TYPE", "LEVEL", "MIGHT", "ROW 1", "ROW 2", "ROW 3", "ROW 4", "ROW 5"];
    var ExcelTable = document.createElement('table');
    var ExcelBody = document.createElement('tbody');
    var ExcelRow = document.createElement('tr');
    var ExcelColumn = "";
    for (i = 0; i < headers.length; i++) {
        ExcelColumn = document.createElement('th');
        ExcelColumn.appendChild(document.createTextNode(headers[i]));
        ExcelRow.appendChild(ExcelColumn);
    }
    ExcelBody.appendChild(ExcelRow);

    var columns = [];

    var preset = getChampPresetObject(parseInt(presetNumber));

    for (chId in preset) {
        var champ_item = uW.kocChampionItems[chId];
        if (!champ_item) continue;
        columns = [];
        columns.push(chId);
        columns.push(champ_item.name);
        columns.push(CM.CHAMPION.getFactionClasses(champ_item.faction));
        if (champ_item.unique) {
            columns.push("unique");
        } else {
            columns.push(CM.CHAMPION.getRarityClasses(champ_item.rarity));
        }
        columns.push(CM.CHAMPION.getEquipmentNames(champ_item.type));
        columns.push(champ_item.level);
        columns.push(champ_item.might);
        for (var slotNumber = 1; slotNumber < STrChOMaxChampQuality + 1; slotNumber++) {
            var effectLine = champ_item.effects[slotNumber];
            var effect = CM.ChampionManager.getEffect(effectLine, champ_item.level);
            columns.push(effect.amount + " " + effect.name);
        }
        columns.reverse();
        ExcelRow = document.createElement('tr');
        while (columns.length > 0) {
            ExcelColumn = document.createElement('td');
            ExcelColumn.appendChild(document.createTextNode(columns.pop()));
            ExcelRow.appendChild(ExcelColumn);
        }
        ExcelBody.appendChild(ExcelRow);
    }
    ExcelTable.appendChild(ExcelBody);

    window.open('data:application/vnd.ms-excel,' + encodeURIComponent(ExcelTable.outerHTML));
}

function ExportChampToExcel(preview) {
    var headers = [ "ID", "NAME", "FACTION", "QUALITY", "TYPE", "LEVEL", "MIGHT", "ROW 1", "ROW 2", "ROW 3", "ROW 4", "ROW 5"];
    var ExcelTable = document.createElement('table');
    var ExcelBody = document.createElement('tbody');
    var ExcelRow = document.createElement('tr');
    var ExcelColumn = "";
    for (i = 0; i < headers.length; i++) {
        ExcelColumn = document.createElement('th');
        ExcelColumn.appendChild(document.createTextNode(headers[i]));
        ExcelRow.appendChild(ExcelColumn);
    }
    ExcelBody.appendChild(ExcelRow);

    var columns = [];

    for (chId in uW.kocChampionItems) {
        if (preview && STrChOChampPresetData.previewChamp.indexOf(chId) == -1 ) continue;
        var champ_item = uW.kocChampionItems[chId];
        if (!champ_item) continue;
        columns = [];
        columns.push(chId);
        columns.push(champ_item.name);
        columns.push(CM.CHAMPION.getFactionClasses(champ_item.faction));
        if (champ_item.unique) {
            columns.push("unique");
        } else {
            columns.push(CM.CHAMPION.getRarityClasses(champ_item.rarity));
        }
        columns.push(CM.CHAMPION.getEquipmentNames(champ_item.type));
        columns.push(champ_item.level);
        columns.push(champ_item.might);
        for (var slotNumber = 1; slotNumber < STrChOMaxChampQuality + 1; slotNumber++) {
            var effectLine = champ_item.effects[slotNumber];
            var effect = CM.ChampionManager.getEffect(effectLine, champ_item.level);
            columns.push(effect.amount + " " + effect.name);
        }
        columns.reverse();
        ExcelRow = document.createElement('tr');
        while (columns.length > 0) {
            ExcelColumn = document.createElement('td');
            ExcelColumn.appendChild(document.createTextNode(columns.pop()));
            ExcelRow.appendChild(ExcelColumn);
        }
        ExcelBody.appendChild(ExcelRow);
    }
    ExcelTable.appendChild(ExcelBody);

    window.open('data:application/vnd.ms-excel,' + encodeURIComponent(ExcelTable.outerHTML));
};

function ExportThronePresetToExcel(presetNumber) {
    var headers = [ "ID", "NAME", "FACTION", "QUALITY", "TYPE", "LEVEL", "MIGHT", "JEWEL", "ROW 1", "ROW 2", "ROW 3", "ROW 4", "ROW 5", "ROW 6"];
    var ExcelTable = document.createElement('table');
    var ExcelBody = document.createElement('tbody');
    var ExcelRow = document.createElement('tr');
    var ExcelColumn = "";
    for (i = 0; i < headers.length; i++) {
        ExcelColumn = document.createElement('th');
        ExcelColumn.appendChild(document.createTextNode(headers[i]));
        ExcelRow.appendChild(ExcelColumn);
    }
    ExcelBody.appendChild(ExcelRow);

    var columns = [];

    var preset = getThronePresetObject(parseInt(presetNumber));

    for (trId in preset) {
        var throne_item = uW.kocThroneItems[trId];
        if (!throne_item) continue;
        columns = [];
        columns.push(trId);
        columns.push(throne_item.name);
        columns.push(throne_item.faction);
        columns.push(throne_item.quality);
        columns.push(throne_item.type);
        columns.push(throne_item.level);
        columns.push(CM.ThroneView.getMightBonus(throne_item));
        if (throne_item.jewel.valid) {
            var jewel_item = throne_item.jewel;
            var qlty = CM.thronestats.jewelGrowthLimit[jewel_item.quality];
            var amt = CM.ThroneController.getEffectAmount(jewel_item, qlty);
            var jewelName = CM.ThroneController.jewelName(jewel_item);
            if (amt == 0) jewelName = "none";
            columns.push(jewelName);
        } else {
            columns.push("none");
        }
        for (var O in throne_item["effects"]) {
            var slotNumber = +(O.split("slot")[1]);
            var id = throne_item["effects"]["slot" + slotNumber]["id"];
            var tier = parseInt(throne_item["effects"]["slot" + slotNumber]["tier"]);
            var level = throne_item.level;
            p = CM.thronestats.tiers[id][tier];
            var effectName = CM.thronestats["effects"][id]["1"];
            while (!p && (tier > 0)) { tier--; p = CM.thronestats.tiers[id][tier]; }
            if (!p) continue; // can't find stats for tier

            if (slotNumber == 6) {
                JewelQuality = throne_item["effects"]["slot" + slotNumber].quality;
                GrowthLimit = CM.thronestats.jewelGrowthLimit[JewelQuality];
                if (GrowthLimit <= level) level = GrowthLimit
            }
            var Current = p.base + ((level * level + level) * p.growth * 0.5);
            columns.push(Current + "% " + effectName);
        }

        columns.reverse();
        ExcelRow = document.createElement('tr');
        while (columns.length > 0) {
            ExcelColumn = document.createElement('td');
            ExcelColumn.appendChild(document.createTextNode(columns.pop()));
            ExcelRow.appendChild(ExcelColumn);
        }
        ExcelBody.appendChild(ExcelRow);
    }
    ExcelTable.appendChild(ExcelBody);

    window.open('data:application/vnd.ms-excel,' + encodeURIComponent(ExcelTable.outerHTML));
};

function getThroneMight() {
    var totMight = 0;
    for (trId in uW.kocThroneItems) {
        var throne_item = uW.kocThroneItems[trId];
        if (throne_item == null || !throne_item) continue;
        totMight += CM.ThroneView.getMightBonus(throne_item);
    }
    return addCommas(totMight);
};

function postThroneSlot( slot ) {
    var throneStats = GenerateThronePresetEffectsString(Seed.throne.slotEquip[slot], false);
    var D = [];
    D.push("Throne Room Slot #" + slot);
    if (STrChOThronePresetData.showThroneName) D.push("(" + STrChOThronePresetData.presetNames[slot] + ")");
    if (STrChOThronePresetData.showThroneMight) D.push("TR Might: " + getThroneMight());
    D.push(throneStats);

    sendChat(":::. |" + D.join("||"));
};

function postThronePreset( presetIndex ) {
    var trP = getThronePresetObject(parseInt(presetIndex));
    var D = [];
    for (var p in trP) D.push(p);
    var throneStats = GenerateThronePresetEffectsString(D, false);
    D = [];
    D.push("Throne Room Tag #" + presetIndex);
    if (STrChOThronePresetData.showThroneName) D.push("(" + STrChOThronePresetData.presetNames[presetIndex] + ")");
    if (STrChOThronePresetData.showThroneMight) D.push("TR Might: " + getThroneMight());
    D.push(throneStats);

    sendChat(":::. |" + D.join("||"));
};

function GenerateThronePresetEffectsString(presetObject, htmlEffects ) {

    var J = new Array();

    var Effects = [];
    for (var effect in CM.thronestats.effects) Effects[effect] = 0;
    var counter = presetObject.length;
    var items = [];

    for (i = 0; i < counter; i++) items.push(presetObject[i]);

    while (items.length > 0) {
        var throne_item = uW.kocThroneItems[items.pop()];
        if (throne_item == null || !throne_item) continue;
        for (var O in throne_item["effects"]) {
            var slotNumber = +(O.split("slot")[1]);
            var id = throne_item["effects"]["slot" + slotNumber]["id"];
            var tier = parseInt(throne_item["effects"]["slot" + slotNumber]["tier"]);
            var level = throne_item.level;
            p = CM.thronestats.tiers[id][tier];
            while (!p && (tier > 0)) { tier--; p = CM.thronestats.tiers[id][tier]; }
            if (!p) continue; // can't find stats for tier

            if (slotNumber == 6) {
                JewelQuality = throne_item["effects"]["slot" + slotNumber].quality;
                GrowthLimit = CM.thronestats.jewelGrowthLimit[JewelQuality];
                if (GrowthLimit <= level) level = GrowthLimit
            }
            var Current = p.base + ((level * level + level) * p.growth * 0.5);
            if (slotNumber <= parseInt(throne_item.quality)) Effects[id] += Current;
        }
    }

    for (effect in Effects) {
        if (Effects[effect] && (Effects[effect] != 0) && CM.thronestats["effects"][effect]) {
            var effectName = CM.thronestats["effects"][effect]["1"];
            if (htmlEffects == true) {
                J.push("<div>" + (Math.round(Effects[effect] * 100) / 100) + '% ' + effectName + "</div>");
            } else {
                J.push((Math.round(Effects[effect] * 100) / 100) + '% ' + effectName);
            }
        }
    }
    if (htmlEffects == true) {
        return J.join("");
    } else {
        return J.join("||");
    }
};

function getObjectCollectionCount( objColl ) {
    var c = 0;
    for (var k in objColl) {
        c++;
    }
    return c;
};


function getChampPresetTagCount(presetIndex) {
    switch(presetIndex) {
        case 1:
            return getObjectCollectionCount(STrChOChampPresetData.taggedItems01);
            break;
        case 2:
            return getObjectCollectionCount(STrChOChampPresetData.taggedItems02);
            break;
        case 3:
            return getObjectCollectionCount(STrChOChampPresetData.taggedItems03);
            break;
        case 4:
            return getObjectCollectionCount(STrChOChampPresetData.taggedItems04);
            break;
    }
    return 0;
};

function getThronePresetTagCount(presetIndex) {
    switch(presetIndex) {
        case 1:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems01);
            break;
        case 2:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems02);
            break;
        case 3:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems03);
            break;
        case 4:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems04);
            break;
        case 5:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems05);
            break;
        case 6:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems06);
            break;
        case 7:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems07);
            break;
        case 8:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems08);
            break;
        case 9:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems09);
            break;
        case 10:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems10);
            break;
        case 11:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems11);
            break;
        case 12:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems12);
            break;
        case 13:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems13);
            break;
        case 14:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems14);
            break;
        case 15:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems15);
            break;
        case 16:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems16);
            break;
        case 17:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems17);
            break;
        case 18:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems18);
            break;
        case 19:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems19);
            break;
        case 20:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems20);
            break;
        case 21:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems21);
            break;
        case 22:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems22);
            break;
        case 23:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems23);
            break;
        case 24:
            return getObjectCollectionCount(STrChOThronePresetData.taggedItems24);
            break;
    };
    return 0;
};

function getThronePresetObject(presetIndex) {
    switch(presetIndex) {
        case 1:
            return STrChOThronePresetData.taggedItems01;
            break;
        case 2:
            return STrChOThronePresetData.taggedItems02;
            break;
        case 3:
            return STrChOThronePresetData.taggedItems03;
            break;
        case 4:
            return STrChOThronePresetData.taggedItems04;
            break;
        case 5:
            return STrChOThronePresetData.taggedItems05;
            break;
        case 6:
            return STrChOThronePresetData.taggedItems06;
            break;
        case 7:
            return STrChOThronePresetData.taggedItems07;
            break;
        case 8:
            return STrChOThronePresetData.taggedItems08;
            break;
        case 9:
            return STrChOThronePresetData.taggedItems09;
            break;
        case 10:
            return STrChOThronePresetData.taggedItems10;
            break;
        case 11:
            return STrChOThronePresetData.taggedItems11;
            break;
        case 12:
            return STrChOThronePresetData.taggedItems12;
            break;
        case 13:
            return STrChOThronePresetData.taggedItems13;
            break;
        case 14:
            return STrChOThronePresetData.taggedItems14;
            break;
        case 15:
            return STrChOThronePresetData.taggedItems15;
            break;
        case 16:
            return STrChOThronePresetData.taggedItems16;
            break;
        case 17:
            return STrChOThronePresetData.taggedItems17;
            break;
        case 18:
            return STrChOThronePresetData.taggedItems18;
            break;
        case 19:
            return STrChOThronePresetData.taggedItems19;
            break;
        case 20:
            return STrChOThronePresetData.taggedItems20;
            break;
        case 21:
            return STrChOThronePresetData.taggedItems21;
            break;
        case 22:
            return STrChOThronePresetData.taggedItems22;
            break;
        case 23:
            return STrChOThronePresetData.taggedItems23;
            break;
        case 24:
            return STrChOThronePresetData.taggedItems24;
            break;
    };
    return null;
};

function getChampPresetObject(presetIndex) {
    switch(presetIndex) {
        case 1:
            return STrChOChampPresetData.taggedItems01;
            break;
        case 2:
            return STrChOChampPresetData.taggedItems02;
            break;
        case 3:
            return STrChOChampPresetData.taggedItems03;
            break;
        case 4:
            return STrChOChampPresetData.taggedItems04;
            break;
    };
    return null;
};

function logit (msg) {
    var now = new Date();
    GM_log (getServerId() +' @ '+ now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +': '+  msg);
};

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

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

function isAnyChampBroke() {
    for (champId in uW.kocChampionItems) {
        var champItem = uW.kocChampionItems[champId];
        if (champItem == null || !champItem) return false;
        if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) return true;
    }
    return false;
}

function isAnyThroneBroke() {
    for (trId in uW.kocThroneItems) {
        var throne_item = uW.kocThroneItems[trId];
        if (throne_item == null || !throne_item) return false;
        if (throne_item.isBroken) return true;
    }
    return false;
};

function getChampItemStats(chId, separater) {

    separater = separater || "    ";

    var champ_item = uW.kocChampionItems[chId];

    var D = [];

    D.push(champ_item.name);

    D.push("Faction: " + CM.CHAMPION.getFactionClasses(champ_item.faction));
    var quality = (champ_item.unique > 0) ? "Unique" : CM.CHAMPION.getRarityClasses(champ_item.rarity);
    D.push("Quality: " + quality);
    D.push("Type: " + uW.g_js_strings.champ[CM.CHAMPION.getEquipmentNames(champ_item.type)]);
    D.push("Level: " + champ_item.level);
    D.push("Might: " + champ_item.might);

    for (var slotNumber = 1; slotNumber < STrChOMaxChampQuality + 1; slotNumber++) {
        var effectLine = champ_item.effects[slotNumber];
        var effect = CM.ChampionManager.getEffect(effectLine, champ_item.level);
        D.push("Row " + slotNumber + ": " + effect.amount + " " + effect.name);
    }

    var cText = D.join(separater);

    if (separater == "||") cText = ":::. |" + cText;

    return cText;
}

function getThroneItemStats(trId, separater) {

    separater = separater || "    ";

    var throne_item = uW.kocThroneItems[trId];

    if (throne_item == null || !throne_item) return "";

    var D = [];

    D.push(throne_item.name);
    D.push("Faction: " + throne_item.faction);
    D.push("Quality: " + throne_item.createPrefix());
    D.push("Type: " + throne_item.type);
    D.push("Level: " + throne_item.level);
    D.push("Might: " + CM.ThroneView.getMightBonus(throne_item));
    for (slot in throne_item.effects) {
        try {
            var N = throne_item.effects[slot];
            effect = CM.thronestats.effects[N.id];

            tier = CM.thronestats.tiers[N.id][N.tier];
            if (!tier) tier = CM.thronestats.tiers[N.id][N.tier - 1];

            var base = tier.base || 0;
            var level = throne_item.level || 0;
            var growth = tier.growth || 0;

            if (slot == 'slot6') {  //if it has a slot 6, it automatically has a jewel
                JewelQuality = throne_item["effects"]['slot6'].quality;
                GrowthLimit = CM.thronestats.jewelGrowthLimit[JewelQuality];
                if (GrowthLimit <= level) level = GrowthLimit
            }

            percent = +(base + ((level * level + level) * growth * 0.5));

            var wholeNumber = false;
            if (Math.round(parseFloat(percent)) == parseFloat(percent)) wholeNumber = true;

            percent = (percent > 0) ? "+" + percent : +percent;

            if (wholeNumber)
                percent = parseFloat(percent)           .toFixed(0);
            else
                percent = parseFloat(percent).toFixed(2);

            css = (slot % 2 === 0) ? "even" : "odd";
            B = +(slot.split("slot")[1]);

            effect[1] = effect[1];

            D.push("Row " + B + ": " + percent + "% " + effect[1]);
        }
        catch (e) { }

    }
    var cText = D.join(separater);
    if (separater == "||") cText = ":::. |" + cText;

    return cText;
}

function displayCityAstone() {
    var city = pickAetherUseCity();
    var m = '';
    if (city == -1) {
        m = '<div>No Aetherstone Available</div>';
    } else {
        var aether = parseInt(Seed.resources["city" + Seed.cities[city][0]]["rec5"][0]);
        m = '<div>AETHER: City #' + (city + 1) + ' = ' + addCommas(aether) + '</div>';
    }
    return m;
};

function pickAetherUseCity() {
    if (parseInt(Seed.resources["city" + Seed.cities[STrChOGeneralOptions.usedCityNum][0]]["rec5"][0]) >= STrChOGeneralOptions.minStones) return STrChOGeneralOptions.usedCityNum;
    if (STrChOGeneralOptions.usedAnyCity) {
        for (i = 0; i < Seed.cities.length; i++) {
            if (parseInt(Seed.resources["city" + Seed.cities[i][0]]["rec5"][0]) >= STrChOGeneralOptions.minStones) return i;
        }
    }
    return -1;
};

function getThroneBrokeMight() {
    var totMight = 0;
    for (trId in uW.kocThroneItems) {
        var throne_item = uW.kocThroneItems[trId];
        if (throne_item == null || !throne_item) continue;
        if (throne_item.isBroken) totMight += CM.ThroneView.getMightBonus(throne_item);
    }
    return "<b>You have " + addCommas(totMight) + " in broken throne might</b>";
};

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

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

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

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

                    oldval = newval;

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

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

                    if (!obj.watchers) obj.watchers = {};

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

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

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

            }
        });
    }

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

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

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

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


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

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

function setUpgradeColor() {
//TODO
    if (STrChOThroneUpgradeData.newUpgradeState == 0)
        $("#STrChOTab>span").css('color', '#FFFF66');
    else if (STrChOThroneUpgradeData.newUpgradeState == 1)
        $("#STrChOTab>span").css('color', 'cyan');
    else if (STrChOThroneUpgradeData.newUpgradeState == 2)
        $("#STrChOTab>span").css('color', 'red');
};

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

function sendComposedMail (sendTo, subject, msg) {
    var params = uW.Object.clone(ajfx);
    params.emailTo = sendTo;
    params.subject = subject;
    params.message = msg;
    params.requestType = "COMPOSED_MAIL";
    new AjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
        method:"post",
        parameters:params,
        onSuccess:function(message){
        },
        onFailure:function(){
        }
    })
};

function unixTime () {
    return parseInt (new Date().getTime() / 1000) + uW.g_timeoff;
};

function parseIntNan (n){
	x = parseInt(n, 10);
	if (isNaN(x))
		return 0;
	return x;
};

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

function addUrlArgs (url, args){
    if (!args) return url;
    if (url.indexOf('?') < 0)
        url += '?';
    else if (url.substr(url.length-1) != '&')
        url += '&';
    if (matTypeof(args == 'object')) return url + implodeUrlArgs (args);
    return url + args;
};

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

var withAnim = null;
if (CM && CM.ThronePanelView) withAnim = CM.ThronePanelView.statusAnim;

function noAnim(result) {
    if (result == "success") {
        var isChamp = true;
        var champUpgEnhContainer = document.getElementById('champUpgEnhContainer');
        if (!champUpgEnhContainer || champUpgEnhContainer == null) isChamp = false;
        var msg = "Manual";
        if (isChamp) {
            var attempt_type = document.getElementById('upgEnhButton');
            msg += ' ' + attempt_type.innerHTML.replace('--', '').trim() + ' successful.  Item:';
            var upgEnhTitle = document.getElementById('upgEnhTitle');
            msg += ' ' + upgEnhTitle.innerHTML;
        } else {
            var thronePanelItemRequirementsContainer = document.getElementById('thronePanelItemRequirementsContainer');
            attempt_type = thronePanelItemRequirementsContainer.getElementsByClassName('gemButtonv2')[0];
            msg += ' ' + attempt_type.innerHTML + ' successful.  Item:';
            var thronePanelName = document.getElementById('thronePanelName');
            msg += ' ' + thronePanelName.innerHTML;
        }

        SuccessLog(msg);

        //if (!OrganizerDisableSuccessCheck) {
            if (withAnim) withAnim(result);
        //} else {
        //    unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
        //}
    }
    //$("div.thronePanelItemContainer").append("<div>" + result + "</div>");
}

function autoSelectForged() {
    var ChampID = 0;
    ChampID = Tabs.champOrganizer.panelId;

    var champItem = uW.kocChampionItems[ChampID];
    var nextForgedID = getNextAvailableForged(champItem);
    if (nextForgedID != 0) {
        var selected_index = 0;

        $(document.querySelector("#upgEnhBuffSelect")).children("option").each(function () {
            if ( $(this).text() == uW.ksoItems[nextForgedID].name ) {
                selected_index = $(this).val();
                return false;
            }
        });
        $('#upgEnhBuffSelect').val(selected_index).change();
        CM.ChampionModalView.renderCosts();
        CM.ChampionUpgEnhManager.calcCosts();
        if (selected_index > 0) {
            var upgEnhCostNum = document.getElementsByClassName('upgEnhCostNum')[1];
            $(upgEnhCostNum).text(uW.ksoItems[nextForgedID].count + "/1");
            $(upgEnhCostNum).css('opacity', 1);
            var upgEnhCostIconItem = document.getElementById('upgEnhCostIconItem');
            upgEnhCostIconItem.className = 'upgEnhCostIcon i' + nextForgedID;
        }

    }
// not needed as champ have a built in safety already, unlike throne
//    if (STrChOGeneralOptions.safetyOn) {
//        setTimeout(function() {
//            safetyCheck();
//        }, 2000);
//    }
}


//var champSafetyCheck = function () {
//    var sel = document.getElementById('upgEnhCostSelect');
//    $(sel).remove(1);
//    if (champCheckAstoneLevel()) {
//        $(document.getElementById('upgEnhButton')).click(function() {
//            champCheckAstoneLevel();
//            champSafetyCheck();
//        });
//    }
//}

//var champCheckAstoneLevel = function () {
//    var stones = parseInt(Seed.resources["city" + unsafeWindow.currentcityid]["rec5"][0]);
//    if (stones < STrChOGeneralOptions.safetyLimit || isNaN(stones) ) {
//        champDisableUpgradeButton();
//        return false;
//    } else {
//        return true;
//    }
//}

//var champDisableUpgradeButton = function() {
//    var container = document.querySelector('#upgEnhBody');
//    $(container).chilren('div.gemButtonv2').remove();
//    var an = $('<a/>');
//    an.addClass('gemButtonv2 gray');
//    an.html('Low A-Stone');
//    $(container).append(an);
//}


function autoSelectMasters() {
    var ThroneID = 0;
    ThroneID = Tabs.throneOrganizer.panelId;

    var throneItem = uW.kocThroneItems[ThroneID];
    var nextMastersID = 0;
    nextMastersID = getNextAvailableMasters(throneItem);
    if (nextMastersID == 0) {
        unselectToken();
    } else {
        var selected_index = 0;
        $(document.querySelector("#buffDropDown")).children("option").each(function () {
            if ( $(this).text() == uW.ksoItems[nextMastersID].name ) {
                selected_index = $(this).val();
                return false;
            }
        });
        $('#buffDropDown').val(selected_index).change();
        if (selected_index > 0) {
            var thronePanelBuffPrice = document.getElementById('thronePanelBuffPrice');
            thronePanelBuffPrice.innerHTML = '<span class="items">' + uW.ksoItems[nextMastersID].count + '/1</span>';
            var thronePanelBuffIcon = document.getElementById('thronePanelBuffIcon');
            thronePanelBuffIcon.className = 'icon mastersToken i' + nextMastersID;
            thronePanelBuffIcon.style.backgroundImage = "url('"+gameurl+"img/items/70/masters_token_bg.png')";
            thronePanelBuffIcon.innerHTML = '<div class="mastersTokenLevel">' + STrChOTokenText[nextMastersID] + '</div>';
        }
    }
    if (STrChOGeneralOptions.safetyOn) {
        setTimeout(function() {
            throneSafetyCheck();
        }, 2000);
    }
}

var throneSafetyCheck = function () {
//    var sel = document.getElementById("costDropDown"); // remove the gem option
//    $(sel).remove(1);
    if (throneCheckAstoneLevel()) { // see if we have enough a-stone
        $(document.querySelector("#thronePanelItemRequirementsContainer")).children("a.gemButtonv2").click(function () { // every time the button is pushed, check the levels
            throneCheckAstoneLevel();
            throneSafetyCheck();
        });
    }
}

var throneCheckAstoneLevel = function () {
    // check limit
    var stones = parseInt(Seed.resources["city" + uW.currentcityid]["rec5"][0]);
    if (stones < STrChOGeneralOptions.safetyLimit || isNaN(stones) ) {
        throneDisableUpgradeButton();
        return false;
    } else {
        return true;
    }
}

var throneDisableUpgradeButton = function () {
    // change the appearance
    var container = document.querySelector('#thronePanelItemRequirementsContainer');
    $(container).children("a.gemButtonv2").remove();
	var an = $("<a/>");
    an.addClass("gemButtonv2 gray");
    an.html("Low A-Stone");
    $(container).append(an);
}

function getMastersText(ksoID) {
    switch(ksoID) {
        case 20060:
            return "LII"; //52T
        case 20059:
            return "LI";
        case 20058:
            return "L";
        case 20057:
            return "XLIX";
        case 20056:
            return "XLVIII";
        case 20055:
            return "XLVII";
        case 20054:
            return "XLVI"; //46T
        case 20053:
            return "XLV";
        case 20052:
            return "XLIV";
        case 20051:
            return "XLIII";
        case 20050:
            return "XLII";
        case 20049:
            return "XLI";
        case 20048:
            return "XL";
        case 20047:
            return "XXXIX";
        case 20046:
            return "XXXVIII";
        case 20045:
            return "XXXVII";
        case 20044:
            return "XXXVI";
        case 20043:
            return "XXXV";
        case 20042:
            return "XXXIV";
        case 20041:
            return "XXXIII";
        case 20040:
            return "XXXII"; //32t
		case 20039:
            return "XXXI";
        case 20038:
            return "XXX";
        case 20037:
            return "XXIX";
        case 20036:
            return "XXVIII";
        case 20035:
            return "XXVII";
        case 20034:
            return "XXVI";
        case 20033:
            return "XXV";
        case 20032:
            return "XXIV";
        case 20031:
            return "XXIII";
        case 20030:
            return "XXII";
        case 20029:
            return "XXI";
        case 20028:
            return "XX";
        case 20027:
            return "XIX";
        case 20026:
            return "XVIII";
        case 20025:
            return "XVII";
        case 20024:
            return "XVI";
        case 20023:
            return "XV";
        case 20021:
            return "XIV";
        case 20020:
            return "XIII";
        case 20018:
            return "XII";
        case 20017:
            return "XI";
        case 20016:
            return "X";
        case 20015:
            return "IX";
        case 20014:
            return "VII";
        case 20013:
            return "V";
        case 20012:
            return "III";
        default:
            return "";
    }
}

var buffChanged = false;

function unselectToken() {
//TODO
    // if the user manually selected a buff, leave it alone
    if (!buffChanged) {

        // set the pull down to nothing when first displayed
        $(document.querySelector("#buffDropDown")).val(0);

        // set the pull down to nothing when first displayed
        $(document.querySelector("#costDropDown")).val(0);

        // remove the icon ....
        $(document.querySelector("#thronePanelBuffIcon")).removeClass().addClass('icon').addClass('i0');
        $(document.querySelector("#thronePanelBuffPrice")).children("span.items").html('');

        // install an action to track when a buff is selected
        $(document.querySelector("#buffDropDown")).change(function () {
            buffChanged = true;
        });

        // install an action to track when a buff is selected
        $(document.querySelector("#costDropDown")).change(function () {
            buffChanged = true;
        });

        // reset once the dialog is closed
        $(".throneContainer").children("div.close").click(function () {
            buffChanged = false;
        });
    }
}

function getNextAvailableForged(champItem) {
    var curCode = 0;
    if (uW.ksoItems[21093].count > 0 && champItem.level <= 44) curCode = 21093; //45s
    if (uW.ksoItems[21092].count > 0 && champItem.level <= 43) curCode = 21092; //44s
	if (uW.ksoItems[21091].count > 0 && champItem.level <= 42) curCode = 21091; //43s
    if (uW.ksoItems[21090].count > 0 && champItem.level <= 41) curCode = 21090; //42s
    if (uW.ksoItems[21089].count > 0 && champItem.level <= 40) curCode = 21089; //41s
    if (uW.ksoItems[21088].count > 0 && champItem.level <= 39) curCode = 21088; //40s
    if (uW.ksoItems[21087].count > 0 && champItem.level <= 38) curCode = 21087; //39s
    if (uW.ksoItems[21086].count > 0 && champItem.level <= 37) curCode = 21086; //38s
    if (uW.ksoItems[21085].count > 0 && champItem.level <= 36) curCode = 21085; //37s
    if (uW.ksoItems[21084].count > 0 && champItem.level <= 35) curCode = 21084; //36s
    if (uW.ksoItems[21083].count > 0 && champItem.level <= 34) curCode = 21083; //35s
    if (uW.ksoItems[21082].count > 0 && champItem.level <= 33) curCode = 21082; //34s
    if (uW.ksoItems[21081].count > 0 && champItem.level <= 32) curCode = 21081; //33s
    if (uW.ksoItems[21080].count > 0 && champItem.level <= 31) curCode = 21080; //32s
    if (uW.ksoItems[21079].count > 0 && champItem.level <= 30) curCode = 21079; //31s
    if (uW.ksoItems[21078].count > 0 && champItem.level <= 29) curCode = 21078; //30s
    if (uW.ksoItems[21077].count > 0 && champItem.level <= 28) curCode = 21077; //29s
    if (uW.ksoItems[21076].count > 0 && champItem.level <= 27) curCode = 21076; //28s
    if (uW.ksoItems[21075].count > 0 && champItem.level <= 26) curCode = 21075; //27s
    if (uW.ksoItems[21074].count > 0 && champItem.level <= 25) curCode = 21074; //26s
    if (uW.ksoItems[21073].count > 0 && champItem.level <= 24) curCode = 21073; //25s
    if (uW.ksoItems[21072].count > 0 && champItem.level <= 23) curCode = 21072; //24s/////////////
    if (uW.ksoItems[21071].count > 0 && champItem.level <= 22) curCode = 21071; //23s
    if (uW.ksoItems[21070].count > 0 && champItem.level <= 21) curCode = 21070; //22s
    if (uW.ksoItems[21069].count > 0 && champItem.level <= 20) curCode = 21069; //21s
    if (uW.ksoItems[21068].count > 0 && champItem.level <= 19) curCode = 21068; //20s
    if (uW.ksoItems[21067].count > 0 && champItem.level <= 18) curCode = 21067; //19s
    if (uW.ksoItems[21066].count > 0 && champItem.level <= 17) curCode = 21066; //18s
    if (uW.ksoItems[21065].count > 0 && champItem.level <= 16) curCode = 21065; //17s
    if (uW.ksoItems[21064].count > 0 && champItem.level <= 15) curCode = 21064; //16s
    if (uW.ksoItems[21063].count > 0 && champItem.level <= 14) curCode = 21063; //15s
    if (uW.ksoItems[21062].count > 0 && champItem.level <= 13) curCode = 21062; //14s
    if (uW.ksoItems[21061].count > 0 && champItem.level <= 12) curCode = 21061; //13s
    if (uW.ksoItems[21060].count > 0 && champItem.level <= 11) curCode = 21060; //12s
    if (uW.ksoItems[21059].count > 0 && champItem.level <= 10) curCode = 21059; //11s
    if (uW.ksoItems[21055].count > 0 && champItem.level <= 9) curCode = 21055; //10s
    if (uW.ksoItems[21054].count > 0 && champItem.level <= 8) curCode = 21054; //9s
    if (uW.ksoItems[21057].count > 0 && champItem.level <= 7) curCode = 21057; //8s
    if (uW.ksoItems[21053].count > 0 && champItem.level <= 6) curCode = 21053; //7s
    if (uW.ksoItems[21056].count > 0 && champItem.level <= 5) curCode = 21056; //6s
    return curCode;
}

function getNextAvailableMasters(throneItem) {
    var curCode = 0;
    if (uW.ksoItems[20060].count > 0 && throneItem.level <= 51) curCode = 20060; // +52master
    if (uW.ksoItems[20059].count > 0 && throneItem.level <= 50) curCode = 20059; // +51
    if (uW.ksoItems[20058].count > 0 && throneItem.level <= 49) curCode = 20058; // +50
    if (uW.ksoItems[20059].count > 0 && throneItem.level <= 48) curCode = 20057; // +49
    if (uW.ksoItems[20056].count > 0 && throneItem.level <= 47) curCode = 20056; // +48
    if (uW.ksoItems[20055].count > 0 && throneItem.level <= 46) curCode = 20055; // +47
    if (uW.ksoItems[20054].count > 0 && throneItem.level <= 45) curCode = 20054; // +46
    if (uW.ksoItems[20053].count > 0 && throneItem.level <= 44) curCode = 20053; // +45
    if (uW.ksoItems[20052].count > 0 && throneItem.level <= 43) curCode = 20052; // +44
    if (uW.ksoItems[20051].count > 0 && throneItem.level <= 42) curCode = 20051; // +43
    if (uW.ksoItems[20050].count > 0 && throneItem.level <= 41) curCode = 20050; // +42
    if (uW.ksoItems[20049].count > 0 && throneItem.level <= 40) curCode = 20049; // +41
    if (uW.ksoItems[20048].count > 0 && throneItem.level <= 39) curCode = 20048; // +40
    if (uW.ksoItems[20047].count > 0 && throneItem.level <= 38) curCode = 20047; // +39
    if (uW.ksoItems[20046].count > 0 && throneItem.level <= 37) curCode = 20046; // +38
    if (uW.ksoItems[20045].count > 0 && throneItem.level <= 36) curCode = 20045; // +37
    if (uW.ksoItems[20044].count > 0 && throneItem.level <= 35) curCode = 20044; // +36
    if (uW.ksoItems[20043].count > 0 && throneItem.level <= 34) curCode = 20042; // +35
    if (uW.ksoItems[20042].count > 0 && throneItem.level <= 33) curCode = 20042; // +34
    if (uW.ksoItems[20041].count > 0 && throneItem.level <= 32) curCode = 20041; // +33
    if (uW.ksoItems[20040].count > 0 && throneItem.level <= 31) curCode = 20040; // +32
    if (uW.ksoItems[20039].count > 0 && throneItem.level <= 30) curCode = 20039; // +31
    if (uW.ksoItems[20038].count > 0 && throneItem.level <= 29) curCode = 20038; //30s
    if (uW.ksoItems[20037].count > 0 && throneItem.level <= 28) curCode = 20037; //29s
    if (uW.ksoItems[20036].count > 0 && throneItem.level <= 27) curCode = 20036; //28s
    if (uW.ksoItems[20035].count > 0 && throneItem.level <= 26) curCode = 20035; //27s
    if (uW.ksoItems[20034].count > 0 && throneItem.level <= 25) curCode = 20034; //26s
    if (uW.ksoItems[20033].count > 0 && throneItem.level <= 24) curCode = 20033; //25s
    if (uW.ksoItems[20032].count > 0 && throneItem.level <= 23) curCode = 20032; //24s
    if (uW.ksoItems[20031].count > 0 && throneItem.level <= 22) curCode = 20031; //23s
    if (uW.ksoItems[20030].count > 0 && throneItem.level <= 21) curCode = 20030; //22s
    if (uW.ksoItems[20029].count > 0 && throneItem.level <= 20) curCode = 20029; //21s
    if (uW.ksoItems[20028].count > 0 && throneItem.level <= 19) curCode = 20028; //20s
    if (uW.ksoItems[20027].count > 0 && throneItem.level <= 18) curCode = 20027; //19s
    if (uW.ksoItems[20026].count > 0 && throneItem.level <= 17) curCode = 20026; //18s
    if (uW.ksoItems[20025].count > 0 && throneItem.level <= 16) curCode = 20025; //17s
    if (uW.ksoItems[20024].count > 0 && throneItem.level <= 15) curCode = 20024; //16s
    if (uW.ksoItems[20023].count > 0 && throneItem.level <= 14) curCode = 20023; //15s
    if (uW.ksoItems[20021].count > 0 && throneItem.level <= 13) curCode = 20021; //14s
    if (uW.ksoItems[20020].count > 0 && throneItem.level <= 12) curCode = 20020; //13s
    if (uW.ksoItems[20018].count > 0 && throneItem.level <= 11) curCode = 20018; //12s
    if (uW.ksoItems[20017].count > 0 && throneItem.level <= 10) curCode = 20017; //11s
    if (uW.ksoItems[20016].count > 0 && throneItem.level <= 9) curCode = 20016; //10s
    if (uW.ksoItems[20015].count > 0 && throneItem.level <= 8) curCode = 20015; //9s
    if (uW.ksoItems[20015].count > 0 && throneItem.level <= 7) curCode = 20015; //9s
    if (uW.ksoItems[20014].count > 0 && throneItem.level <= 6) curCode = 20014; //7s
    if (uW.ksoItems[20014].count > 0 && throneItem.level <= 5) curCode = 20014; //7s
    if (uW.ksoItems[20013].count > 0 && throneItem.level <= 4) curCode = 20013; //5s
    if (uW.ksoItems[20013].count > 0 && throneItem.level <= 3) curCode = 20013; //5s
    if (uW.ksoItems[20012].count > 0 && throneItem.level <= 2) curCode = 20012; //3s
    if (uW.ksoItems[20012].count > 0 && throneItem.level <= 1) curCode = 20012; //3s
    return curCode;
}

function disableAnimation(disable) {
    if (disable) {
        // override the success failure animations
        CM.ThronePanelView.statusAnim = noAnim;
    } else {
        if (withAnim) CM.ThronePanelView.statusAnim = withAnim;
    }
};

function getChampName( presetIndex ) { //presetIndex is 1 based but needs to be 0 based for champ name so we will minus 1
    var thisChampion = Seed.champion.champions[presetIndex-1];
    return thisChampion.name;
};

function getChampID( presetIndex ) { //presetIndex is 1 based but needs to be 0 based for champ name so we will minus 1
    var thisChampion = Seed.champion.champions[presetIndex-1];
    return thisChampion.championId;
};

function postChampSlot ( slot ) {
    var champId = getChampID(slot);
    var D = [];
    for (var chId in uW.kocChampionItems) if (uW.kocChampionItems[chId].equippedTo == champId) D.push(chId);
    var champStats = GenerateChampPresetEffectsString(D, false);
    D = [];
    D.push("Champ Hall Slot #" + slot);
    D.push(getChampName(slot));
    if (STrChOChampPresetData.showChampName) D.push("(" + STrChOChampPresetData.presetNames[slot-1] + ")");
    if (STrChOChampPresetData.showChampMight) D.push(getChampMight());
    D.push(champStats);
    sendChat(":::. |" + D.join("||"));
};

function postChampPreset ( presetIndex ) {
    var chP = getChampPresetObject(parseInt(presetIndex));
    var D = [];
    for (var p in chP) D.push(p);
    var champStats = GenerateChampPresetEffectsString(D, false);
    D = [];
    D.push("Champ Hall Tag #" + presetIndex);
    D.push(getChampName(presetIndex));
    if (STrChOChampPresetData.showChampName) D.push("(" + STrChOChampPresetData.presetNames[presetIndex-1] + ")");
    if (STrChOChampPresetData.showChampMight) D.push(getChampMight());
    D.push(champStats);
    sendChat(":::. |" + D.join("||"));
};

function getChampMight() {
    var totMight = 0;
    for (chId in uW.kocChampionItems) {
        var champ_item = uW.kocChampionItems[chId];
        var q = champ_item.rarity;
        if (champ_item.unique != 0) q -= 1;
        var l = champ_item.level;
        totMight += CM.thronestats.mightByQuality[q].Might + CM.thronestats.mightByLevel[l].Might;
    }
    return "Approx Might: " + addCommas(totMight);
};

function GenerateChampPresetEffectsString( presetObject, htmlEffects ) {

    var ChampStats = [];
    var TroopStats = [];

    for (var eff in CM.thronestats.effects) TroopStats[eff] = 0;
    //base stats for champ with no items
    ChampStats[201] = 30;
    ChampStats[202] = 0;
    ChampStats[203] = 7;
    ChampStats[204] = 27;
    ChampStats[205] = 27;
    ChampStats[206] = 60;
    ChampStats[207] = 4;
    ChampStats[208] = 3;
    ChampStats[209] = 3;

    var counter = presetObject.length;
    var items = [];

    for (i = 0; i < counter; i++) items.push(presetObject[i]);

	var SetBonus = {};
	for (var y in items) { // calculate unique set bonuses
        var champ_item = uW.kocChampionItems[items[y]];
        if (champ_item == null || !champ_item) continue;
        for (var O in champ_item["effects"]) {
            var effectLine = champ_item["effects"][O];
            var id = effectLine["id"];
            if (id >= 300) {
				var effect = CM.ChampionManager.getEffect(effectLine, champ_item.level);
				if (!SetBonus[champ_item.set]) { SetBonus[champ_item.set] = 0; }
				SetBonus[champ_item.set] += effect.amount;
			}
        }
	}
    while (items.length > 0) {
        var champ_item = uW.kocChampionItems[items.pop()];
        if (champ_item == null || !champ_item) continue;
        for (var O in champ_item["effects"]) {
            var effectLine = champ_item["effects"][O];
            var id = effectLine["id"];
            var effect = CM.ChampionManager.getEffect(effectLine, champ_item.level);
			var bonus = 0;
			if (id<300) bonus = SetBonus[champ_item.set] || 0;
            if (id >= 200) {
                if (!ChampStats[id]) { ChampStats[id] = 0; }
                ChampStats[id] += effect.amount + (effect.amount*bonus);
            } else {
                TroopStats[id] += effect.amount;
            }
        }
    }

    var J = new Array();

    if (htmlEffects) {
        J.push("<div><b><i>CHAMP STATS</i></b></div>");
    } else {
        J.push("CHAMP STATS");
    }
    for (stat in ChampStats) {
        var effectName = uW.g_js_strings.effects["name_"+ stat];
        if (ChampStats[stat] && ChampStats[stat] != 0) {
			if (stat>= 300) {
				str = 'Inc. Bonus '+effectName.split(" equipment")[0];
				var champvalue = +((ChampStats[stat]*100).toFixed(2))+"%";
				if (htmlEffects) {
					J.push("<div>&nbsp;&nbsp;" + str + " " + champvalue + "</div>");
				} else {
					J.push("&nbsp;&nbsp;" + str + " " + champvalue);
				}
			}
			else {
				if (htmlEffects) {
					J.push("<div>&nbsp;&nbsp;" + effectName + " " + ChampStats[stat].toFixed(2) + "</div>");
				} else {
					J.push("&nbsp;&nbsp;" + effectName + " " + ChampStats[stat].toFixed(2));
				}
			}
        }
    }
    if (htmlEffects) {
        J.push("<div><b><i>TROOP STATS</i></b></div>");
    } else {
        J.push("TROOP STATS");
    }
    for (stat in TroopStats) {
        var effectName = CM.thronestats.effects[stat][1];
        if (TroopStats[stat] && TroopStats[stat] != 0) {
            if (htmlEffects) {
                J.push("<div>&nbsp;&nbsp;" + effectName + " " + (Math.round(TroopStats[stat]*100)/100) + "</div>");
            } else {
                J.push("&nbsp;&nbsp;" + effectName + " " + (Math.round(TroopStats[stat]*100)/100));
            }
        }
    }
    if (htmlEffects) {
        return J.join("");
    } else {
        return J.join("||");
    }

}

function getChampBrokeMight() {
    var totMight = 0;
    for (chId in uW.kocChampionItems) {
        var champ_item = uW.kocChampionItems[chId];
        if (champ_item.status == 1) continue;
        var q = champ_item.rarity;
        if (champ_item.unique != 0) q -= 1;
        var l = champ_item.level;
        totMight += CM.thronestats.mightByQuality[q].Might + CM.thronestats.mightByLevel[l].Might;
    }
    return "<b>You have approx " + addCommas(totMight) + " in broken champ might</b>";
};

function ChampLoadDomainSalvageData(domainId) {
    var t = Tabs.champSalvager;

    s = GM_getValue('STrChOChampSalvageData_'+ domainId + uW.tvuid);

    if (s==null) {
        alert("Unable to find data from domain: " + domainId);
        return;
    }

    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOChampSalvageData[k][kk] = opts[k][kk];
            else
                STrChOChampSalvageData[k] = opts[k];
        }
    }

    // recreate the objects w/ functions
    for (k in STrChOChampSalvageData.ruleSet)
    {
        var r = STrChOChampSalvageData.ruleSet[k];
        var rule = new ChampRule(r.type, r.faction, r.conditions, r.advancedrule);
        for (j in rule.conditions) {
            rule.conditions[j].ChampCheckCondition = ChampCheckCondition;
        }
        STrChOChampSalvageData.ruleSet[k] = rule;
    }

    // turn off
    STrChOChampSalvageData.active = false;
    clearInterval(t.sTimer);
    clearInterval(t.delTimer);
    t.deleting = false;
    SAVESTrChOChampSalvageData();
    alert('Salvage settings loaded from domain ' + domainId);
    t.buildChampRuleDisplay();
};

function ThroneLoadDomainSalvageData(domainId) {
    var t = Tabs.throneSalvager;

    s = GM_getValue ('STrChOThroneSalvageData_'+ domainId + uW.tvuid);

    if (s==null) {
        alert("Unable to find data from domain: " + domainId);
        return;
    }

    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThroneSalvageData[k][kk] = opts[k][kk];
            else
                STrChOThroneSalvageData[k] = opts[k];
        }
    }

    // recreate the objects w/ functions
    for (k in STrChOThroneSalvageData.ruleSet)
    {
        var r = STrChOThroneSalvageData.ruleSet[k];
        var rule = new ThroneRule(r.type, r.faction, r.conditions, r.advancedrule);
        for (j in rule.conditions) {
            rule.conditions[j].ThroneCheckCondition = ThroneCheckCondition;
        }
        STrChOThroneSalvageData.ruleSet[k] = rule;
    }

    // turn off
    STrChOThroneSalvageData.active = false;
    clearInterval(t.sTimer);
    clearInterval(t.delTimer);
    t.deleting = false;
    SAVESTrChOThroneSalvageData();
    alert('Salvage settings loaded from domain ' + domainId);
    t.buildThroneRuleDisplay();
};

function secondsToTime(seconds) {
    if (seconds == 0) return "Complete";
    var remainderSeconds = seconds % 60;
    seconds = seconds - remainderSeconds;
    var remainderMinutes = seconds / 60;
    return (remainderMinutes + 'm ' + remainderSeconds + 's');
};

function onUnload (){
    if (uW.STrChOLoaded) {
        if (mainPop) {
            var pos = mainPop.getLocation();
            STrChOGeneralOptions.xPos = pos.x;
            STrChOGeneralOptions.yPos = pos.y;
            //STrChOGeneralOptions.xPos = mainPop.getLocation.x;
            //STrChOGeneralOptions.yPos = mainPop.getLocation.y;
            SAVESTrChOGeneralOptions();
        }
    }
};

function RefreshCamelot() {  //This piece of code was taken from KoC Power BOT.  All credit goes to them for this piece.  Thanks guys/gals!
    var serverId = getServerId();
    var goto = window.location.protocol + '//apps.facebook.com/kingdomsofcamelot/?s=' + serverId;
    if (document.URL.match(/standalone=1/i)) {
        goto = window.location.protocol + '//www.kabam.com/games/kingdoms-of-camelot/play?s=' + serverId;
    };
    setTimeout (function (){window.top.location = goto;}, 0);
};

// emulate protoype's Ajax.Request ...
function AjaxRequest (url, opts) {  //emulate protoype's Ajax.Request ...
    var headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'X-Prototype-Version': '1.6.1',
            'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };
    var ajax = null;

    if (window.XMLHttpRequest)
        ajax=new XMLHttpRequest();
    else
        ajax=new ActiveXObject("Microsoft.XMLHTTP");

    if (opts.method==null || opts.method=='')
        method = 'GET';
    else
        method = opts.method.toUpperCase();

    if (method == 'POST'){
        headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    } else if (method == 'GET'){
        addUrlArgs (url, opts.parameters);
    }

    ajax.onreadystatechange = function(){
//      ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; states 0-4
        if (ajax.readyState==4) {
            if (ajax.status >= 200 && ajax.status < 305)
                if (opts.onSuccess) opts.onSuccess(ajax);
                else
                    if (opts.onFailure) opts.onFailure(ajax);
        } else {
            if (opts.onChange) opts.onChange (ajax);
        }
    }

    ajax.open(method, url, true);   // always async!

    for (var k in headers)
        ajax.setRequestHeader (k, headers[k]);
    if (matTypeof(opts.requestHeaders)=='object')
        for (var k in opts.requestHeaders)
            ajax.setRequestHeader (k, opts.requestHeaders[k]);

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

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

    new AjaxRequest(url, opts);
    return;

    function myRetry(){
        ++retry;
        new AjaxRequest(url, opts);
        delay = delay * 2.25;
    }
    function myFailure(){
        var o = {};
        o.ok = false;
        o.errorMsg = "AJAX Communication Failure";
        wasFailure (o);
    }
    function mySuccess (msg){
        var rslt = eval("(" + msg.responseText + ")");
        if (!rslt)
        {
            logit("Message error: " + inspect(msg,3,1));
            return;
        }
        var x;
        if (window.EmulateAjaxError){
            rslt.ok = false;
            rslt.error_code=8;
        }
        if (rslt.ok){
            if (rslt.updateSeed)
                uW.update_seed(rslt.updateSeed);
            wasSuccess (rslt);
            return;
        }
        rslt.errorMsg = uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));

        if (!noRetry && (rslt.error_code==0 || rslt.error_code==8 || rslt.error_code==1 || rslt.error_code==3)){
            dialogRetry (inspect(rslt.errorMsg), delay, function(){myRetry()}, function(){wasSuccess (rslt)}, rslt.error_code);
        } else {
            wasSuccess (rslt);
        }
    }
};

function ExportThroneToExcel(isPreview) {
    var headers = [ "ID", "NAME", "FACTION", "QUALITY", "TYPE", "LEVEL", "MIGHT", "JEWEL", "ROW 1", "ROW 2", "ROW 3", "ROW 4", "ROW 5", "ROW 6"];
    var ExcelTable = document.createElement('table');
    var ExcelBody = document.createElement('tbody');
    var ExcelRow = document.createElement('tr');
    var ExcelColumn = "";
    for (i = 0; i < headers.length; i++) {
        ExcelColumn = document.createElement('th');
        ExcelColumn.appendChild(document.createTextNode(headers[i]));
        ExcelRow.appendChild(ExcelColumn);
    }
    ExcelBody.appendChild(ExcelRow);

    var columns = [];

    for (trId in uW.kocThroneItems) {
        if (isPreview && !STrChOThronePresetData.previewThrone[trId]) continue;
        var throne_item = uW.kocThroneItems[trId];
        if (!throne_item) continue;
        columns = [];
        columns.push(trId);
        columns.push(throne_item.name);
        columns.push(throne_item.faction);
        columns.push(throne_item.quality);
        columns.push(throne_item.type);
        columns.push(throne_item.level);
        columns.push(CM.ThroneView.getMightBonus(throne_item));
        if (throne_item.jewel != null) {
            if (throne_item.jewel.valid) {
                var jewel_item = throne_item.jewel;
                var qlty = CM.thronestats.jewelGrowthLimit[jewel_item.quality];
                var amt = CM.ThroneController.getEffectAmount(jewel_item, qlty);
                var jewelName = CM.ThroneController.jewelName(jewel_item);
                if (amt == 0) jewelName = "none";
                columns.push(jewelName);
            } else {
                columns.push("none");
            }
        } else {
            columns.push("none");
        }
        for (var O in throne_item["effects"]) {
            var slotNumber = +(O.split("slot")[1]);
            var id = throne_item["effects"]["slot" + slotNumber]["id"];
            var tier = parseInt(throne_item["effects"]["slot" + slotNumber]["tier"]);
            var level = throne_item.level;
            p = CM.thronestats.tiers[id][tier];
            var effectName = CM.thronestats["effects"][id]["1"];
            while (!p && (tier > 0)) { tier--; p = CM.thronestats.tiers[id][tier]; }
            if (!p) continue; // can't find stats for tier

            if (slotNumber == 6) {
                JewelQuality = throne_item["effects"]["slot" + slotNumber].quality;
                GrowthLimit = CM.thronestats.jewelGrowthLimit[JewelQuality];
                if (GrowthLimit <= level) level = GrowthLimit
            }
            var Current = p.base + ((level * level + level) * p.growth * 0.5);
            columns.push(Current + "% " + effectName);
        }

        columns.reverse();
        ExcelRow = document.createElement('tr');
        while (columns.length > 0) {
            ExcelColumn = document.createElement('td');
            ExcelColumn.appendChild(document.createTextNode(columns.pop()));
            ExcelRow.appendChild(ExcelColumn);
        }
        ExcelBody.appendChild(ExcelRow);
    }
    ExcelTable.appendChild(ExcelBody);

    window.open('data:application/vnd.ms-excel,' + encodeURIComponent(ExcelTable.outerHTML));
}
function ConvertUniqueAndBuildChampCard (champId, lvl) {
    var t = Tabs.champUniques;
	var ChampCard = {};
	ChampCard = t.UniqueItems[champId];
	ChampCard.id = ChampCard.Id;
	ChampCard.name = ChampCard.Name;
	if (ChampCard.Faction != 0) {
		ChampCard.faction = ChampCard.Faction;
		ChampCard.type = ChampCard.Type;
	}
	else {
		ChampCard.faction = 'unknown';
		ChampCard.type = 'unknown';
		ChampCard.unknown = true;
	}
	ChampCard.unique = ChampCard.id;
	ChampCard.level = parseInt(lvl);
	ChampCard.rarity = 5;
	ChampCard.createPrefix = function () { return ""; };
	ChampCard.createSuffix = function () { return ""; };
	ChampCard.effects = {};
	var effects = eval(ChampCard.Effects);
	var slot = 0;
	for (k in effects) {
		slot++
		ChampCard.effects["slot"+slot] = {};
		ChampCard.effects["slot"+slot].id = effects[k].type;
		ChampCard.effects["slot"+slot].tier = effects[k].tier;
	}
	return BuildChampCard(ChampCard);
};

function ConvertUniqueAndBuildThroneCard(throneID, lvl) {
    var t = Tabs.throneUniques;
    var ThroneCard = {};
    ThroneCard = t.UniqueItems[throneID];
    ThroneCard.id = ThroneCard.Id;
    ThroneCard.name = ThroneCard.Name;
    ThroneCard.faction = uW.g_js_strings.commonstr[CM.CHAMPION.getFactionClasses(ThroneCard.Faction)].toLowerCase();
    ThroneCard.type = throneCardTypes[parseInt(ThroneCard.Type)-1].toLowerCase();
    ThroneCard.unique = ThroneCard.id;
    ThroneCard.level = parseInt(lvl);
    ThroneCard.quality = STrChOMaxThroneQuality;
    ThroneCard.createPrefix = function () { return ""; };
    ThroneCard.createSuffix = function () { return ""; };
    ThroneCard.effects = {};
    var effects = eval(ThroneCard.Effects);
    var slot = 0;

    for (k in effects) {
        slot++
        ThroneCard.effects["slot"+slot] = {};
        ThroneCard.effects["slot"+slot].id = effects[k].type;
        ThroneCard.effects["slot"+slot].tier = effects[k].tier;

        if (slot==6) {
            ThroneCard.effects["slot"+slot].quality = 5; // assume bright jewel
            ThroneCard.effects["slot"+slot].fromJewel = true;

            ThroneCard.jewel = {};
            ThroneCard.jewel.valid = true;
            ThroneCard.jewel.id = ThroneCard.effects["slot"+slot].id;
            ThroneCard.jewel.quality = 5; // assume bright jewel
            ThroneCard.jewel.tier = ThroneCard.effects["slot"+slot].tier;
            ThroneCard.jewel.fromJewel = true;
            ThroneCard.jewel.gift = false;
            ThroneCard.jewel.quantity = 1;
        }
    }
    return BuildThroneCard(ThroneCard);
};

function BuildChampCard(champItem) {

    var D = [];

    if (champItem == null) {
        D.push('<div>');
        D.push('</div>');
        return D.join('');
    }
    D.push('<div class=STrChOCard style="white-space: normal; padding: 0px;">');
    D.push('<div class=section style="overflow: visible;" id=idsection>');
    D.push('<div div class="champ_item_section">');

    var champName = champItem.name;
    champName = champName.replace(champItem.createPrefix(), '');
    champName = champName.replace('Chest Armor of', 'Chest Of');
    champName = champName.trim();
    D.push('<div class="STrChOTitle ' + champCardQualities[champItem.rarity] + '" title="' + champName + '" style="text-transform: capitalize;">');
    if (champItem.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champItem.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) D.push('<font color=red><b>BROKEN</b></font><br>');
    D.push(champName);
    D.push('</div>');
    D.push('<div class=description>');
    var uniquestyle = "";
	if (champItem.unique != 0) uniquestyle = "background:transparent url('" + IMGURL +"champion_hall/unique_" + champItemUniqueNames[champItem.type] + "_" + STrChOFactions[champItem.faction-1] + "_70x70_" + champItem.unique + ".png'); top left no-repeat; background-size: cover;";
    D.push('<div class="portrait ' + STrChOFactions[champItem.faction-1] + ' ' + champItemNames[champItem.type] + '" style="'+uniquestyle+'"></div>');
    D.push('<ul>');
    D.push('<li>Faction: ' + STrChOFactions[champItem.faction-1] + '</li>');
    D.push('<li>Quality: ' + champCardQualities[champItem.rarity] + '</li>');
    D.push('<li>Might: ' + (champItem.might > 0 ? champItem.might : '') + '</li>');
    D.push('</ul>');
    D.push('</div>');
    D.push('<ul class="effects">');

    for (var ef in champItem["effects"]) {
        var effectLine = champItem["effects"][ef];
        var effect = CM.ChampionManager.getEffect(effectLine, champItem.level);
        D.push('<li class="effect ' + (effect.id >= 200 ? 'statChamp' : 'statTroop') + '">' + effect.amount + ' ' + uW.g_js_strings.effects["name_" + effect.id ] + '</li>');
    }

    D.push('</ul>');
    D.push('</div>');
    D.push('</div>');
    D.push('</div>');
    D.push('</div>');
    return D.join('');
};

function BuildThroneCard(throneItem) {
    var D = [];
    var w = CM.thronestats.mightByQuality;
    var z = CM.thronestats.mightByLevel;

    if (throneItem == null) {
        D.push('<div>');
        D.push('</div>');
        return D.join('');
    }

    D.push('<div class=STrChOCard style="white-space: normal; padding: 0px;">');
    D.push('<div class=section style="overflow: visible;" id=idsection>');
    D.push('<div div class="throne_item_section">');
    var throneName = throneItem.name;
    throneName = throneName.replace(throneItem.createPrefix(), '');
    throneName = throneName.trim();
    D.push('<div class="STrChOTitle ' + throneItem.createPrefix().toLowerCase() + '" title="' + throneName + '" style="text-transform: capitalize;">');
    if (throneItem.isBroken) D.push('<font color=red><b>BROKEN</b></font><br>');
    D.push(throneName + (throneItem.unique ? ' +' + throneItem.level : ''));
    D.push('</div>');
    D.push('<div class=description>');

    var uniquestyle = '';
    if (throneItem.unique > 29000) {
        uniquestyle = "background:transparent url('"+gameurl+"img/throne/icons/70/"+throneItem.faction+"_"+throneItem.type+"_unique_"+throneItem.unique + ".png'); top left no-repeat; background-size: 70px 70px;";
        if (throneItem.unique == 30262 || throneItem.unique == 30264 || throneItem.unique == 30266) { uniquestyle = "background:transparent url('"+gameurl+"img/throne/icons/70/christmas_advisor_normal_1.png'); top left no-repeat; background-size: 70px 70px;";};
        if (throneItem.unique == 30261 || throneItem.unique == 30263 || throneItem.unique == 30265) { uniquestyle = "background:transparent url('"+gameurl+"img/throne/icons/70/christmas_candelabrum_normal_1.png'); top left no-repeat; background-size: 70px 70px;";};
        if (throneItem.unique == 30230 || throneItem.unique == 30240 || throneItem.unique == 30250) { uniquestyle = "background:transparent url('"+gameurl+"img/throne/icons/70/halloween_table_normal_1.png'); top left no-repeat; background-size: 70px 70px;";};
        if (throneItem.unique == 30231 || throneItem.unique == 30241 || throneItem.unique == 30251) { uniquestyle = "background:transparent url('"+gameurl+"img/throne/icons/70/halloween_chair_normal_1.png'); top left no-repeat; background-size: 70px 70px;";};
    }
    D.push('<div class="portrait ' + throneItem.faction + ' ' + throneItem.type + '" style="'+uniquestyle+'"></div>');
    D.push('<ul>');
    D.push('<li>Faction: ' + throneItem.faction + '</li>');
    D.push('<li>Quality: ' + throneItem.createPrefix() + '</li>');
    //D.push('<li>' + uW.g_js_strings.commonstr.type + ': ' + throneItem.type + '</li>');
    //D.push('<li>' + uW.g_js_strings.commonstr.level + ': ' + throneItem.level + '</li>');
    D.push('<li>Might: ' + CM.ThroneView.getMightBonus(throneItem) + '</li>');
    var hasJewel = false;
    if (throneItem.jewel) {
        if (throneItem.jewel.valid) hasJewel = true;
    }
    D.push('<li>Jewel: ' + (!hasJewel ? 'None' : STrChOJewelQualities[throneItem.jewel.quality-1]) + '</li>');
    D.push('</ul>');
    D.push('</div>');
    D.push('<ul>');

    for (slot in throneItem.effects) {
        try {
            var N = throneItem.effects[slot];
            effect = CM.thronestats.effects[N.id];

            tier = CM.thronestats.tiers[N.id][N.tier];
            if (!tier) tier = CM.thronestats.tiers[N.id][N.tier - 1];

            var base = tier.base || 0;
            var level = throneItem.level;
            var growth = tier.growth || 0;

            if (slot == 'slot6') {  //if it has a slot 6, it automatically has a jewel
                JewelQuality = throneItem['effects']['slot6'].quality;
                GrowthLimit = CM.thronestats.jewelGrowthLimit[JewelQuality];
                if (GrowthLimit <= level) level = GrowthLimit
            }

            percent = +(base + ((level * level + level) * growth * 0.5));

            var wholeNumber = false;
            if (Math.round(parseFloat(percent)) == parseFloat(percent)) wholeNumber = true;

            percent = (percent > 0) ? "+" + percent : +percent;

            if (wholeNumber)
                percent = parseFloat(percent).toFixed(0);
            else
                percent = parseFloat(percent).toFixed(2);

            css = (slot % 2 === 0) ? 'even' : 'odd';
            B = +(slot.split("slot")[1]);

            if (B <= throneItem.quality) {
                D.push('<li class="effect ' + css + '"> ' + percent + '% ' + effect[1] + '</li>');
            } else {
                D.push('<li class="effect disabled ' + css + '"> ' + percent + '% ' + effect[1] + '</li>');
            }
        }
        catch (e) { }

    }
    D.push('</ul>');
    D.push('</div>');
    D.push('</div>');
    D.push('</div>');
    D.push('</div>');
    return D.join('');
};

function NewsItemRow(msg) {
    var m = '<tr><td>&#149';
    m += msg;
    m += '</td></tr>';
    return m;
};

function pickAetherSalvageCity() {

    if (parseInt(Seed.resources["city" + Seed.cities[STrChOGeneralOptions.salvageCityNum][0]]["rec5"][0]) <= STrChOGeneralOptions.maxStones) return STrChOGeneralOptions.salvageCityNum;

    var ind = -1;
    var lowest = 16000000;

    if (STrChOGeneralOptions.salvageAnyCity) {
        for (i = 0; i < Seed.cities.length; i++) {
            if (STrChOGeneralOptions.overflow == "lowest") {
                // put in the city w/ the lowest number of a-stone
                if (parseInt(Seed.resources["city" + Seed.cities[i][0]]["rec5"][0]) < lowest) {
                    ind = i;
                    lowest = +Seed.resources["city" + Seed.cities[ind][0]]["rec5"][0];
                }
            } else {
                // put in the first city with low stones
                if (parseInt(Seed.resources["city" + Seed.cities[i][0]]["rec5"][0]) <= STrChOGeneralOptions.maxStones) {
                    return i;
                }
            }
        }
    }
    return ind;
};

function SalvageChampItem(id) {
    var t = Tabs.champSalvager;

    var params = uW.Object.clone(ajfx);
    var num_city = pickAetherSalvageCity();
    if ( num_city < 0)
    {
        num_city = +STrChOGeneralOptions.salvageCityNum;
        t.setStatus("All cities are (nearly) full of aetherstone");
    }

    params.action = "8";
    params.eids = id;
    params.cityId = Seed.cities[num_city][0];

    new AjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        loading: true,
        onSuccess: function (transport) {
            try {
                var rslt = eval("(" + transport.responseText + ")");
                var champ_item = uW.kocChampionItems[id];

                if(rslt.ok == true) {
                    var eid = rslt.equipmentIds[0];
                    champ_item = uW.kocChampionItems[eid];

                    if (champ_item) SalvageLog('Deleted Champion item '+ champ_item.name);
                    STrChOChampSalvageData.numSalvagedItems++;
                    STrChOChampSalvageData.numSalvagedItems2++;
                    SAVESTrChOChampSalvageData();

                    if (champ_item) {
                        STrChOChampSalvageData.numSalvaged[champ_item.rarity]++;
                        SAVESTrChOChampSalvageData();
                        t.removeItem(eid , Seed.cities[num_city][0], parseInt(rslt.aetherstones));
                    }
                    t.displayNumberSalvaged();
                }
                else
                {
                    //logit("rslt: " + inspect(rslt,3,1));
                    if (champ_item) t.setStatus('Unable to salvage item ' + champ_item.name);
                }

                var idx = t.delItems.indexOf(id);
                if (idx >=0)
                {
                    t.delItems.splice(idx,1);
                    // Remove item from array regardless
                    // of success. Catch on next refresh
                }
                if (t.delItems.length > 0) { // Check if the array is empty
                    t.upgradeAndDelete();
                } else {
                    t.deleting = false;
                    t.setStatus('Salvaging complete.  Waiting for next cycle.');
                    return;
                }
            } catch (e) {
                t.deleting = false;
            }
        },
        onFailure: function () {
            t.delIems = [];
            t.deleting = false;
            //if (uW.kocChampionItems[id] )                logit("salvage failed for item " + unsafeWindow.kocChampionItems[id].name );
            return;
        }
    });
}

function ThroneUpdateTimerDisplay () {

    if (!document.getElementById('STrChOTimerDisplay')) return;

    var t = Tabs.throneUpgrader;
    var timeUntilDone = 0;

    if (t.repairEnd != 0) timeUntilDone = t.repairEnd - unixTime();

    if (timeUntilDone > 0)
        document.getElementById('STrChOTimerDisplay').innerHTML = '<span id=STrChOHammer></span> ' + rectime(timeUntilDone);
    else
        document.getElementById('STrChOTimerDisplay').innerHTML = 'DONE';
}

function rectime(secs) {
    var min = Math.floor((secs)/60);
    var sec = Math.ceil(secs - (min * 60));

    if (sec < 10) {sec = "0" + sec;}
    return  min + ':' + sec;
}

function getThroneImage(item) {
    var img = '';
    if (item.unique == 30262 || item.unique == 30264 || item.unique == 30266) {
        img = "https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/christmas_advisor_normal_1.png";
    } else if (item.unique == 30261 || item.unique == 30263 || item.unique == 30265) {
        img = "https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/christmas_candelabrum_normal_1.png";
    } else if (item.unique == 30230 || item.unique == 30240 || item.unique == 30250) {
        img = "https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/halloween_table_normal_1.png";
    } else if (item.unique == 30231 || item.unique == 30241 || item.unique == 30251) {
        img = "https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/halloween_chair_normal_1.png";
    } else if (item.unique > 0) {
        img = "https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/30/" + item.faction + "/" + item.faction + "_" + item.type + "_unique_normal_" + item.unique + ".png";
    } else {
        img = "https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/30/" + item.faction + "/" + item.faction + "_" + item.type + "_normal_1_" + item.quality + ".png";
    }

    if (item.isBroken) img = "https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/modal/sm_fail_overlay.png";

    return img;
}

function SalvageThroneItem(id) {

    var t = Tabs.throneSalvager;

    var params = uW.Object.clone(ajfx);
    var num_city = pickAetherSalvageCity();
    if (num_city < 0) {
        num_city = +STrChOGeneralOptions.salvageCityNum;
        t.setStatus("All cities are (nearly) full of aetherstone");
    }

    params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
    params.action = 'salvage';
    params.itemId = id;
    params.cityId = Seed.cities[num_city][0];

    new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        loading: true,
        onSuccess: function (transport) {
            try {
                var rslt = eval("(" + transport.responseText + ")");
                var throne_item = uW.kocThroneItems[id];
                if (rslt.ok) {
                    if (throne_item) SalvageLog('Deleted Throne Room item ' + throne_item.name);
                    STrChOThroneSalvageData.numSalvagedItems++;
                    STrChOThroneSalvageData.numSalvagedItems2++;
                    SAVESTrChOThroneSalvageData();

                    if (throne_item) {
                        STrChOThroneSalvageData.numSalvaged[throne_item.quality]++;
                        SAVESTrChOThroneSalvageData();
                        Tabs.throneSalvager.removeItem(id, Seed.cities[num_city][0], rslt.aetherstones);
                    }

                    Tabs.throneSalvager.displayNumberSalvaged();

                    var sidx = STrChOThroneSalvageData.upgradedToDelete.indexOf(id);
                    if (sidx >= 0) {
                        STrChOThroneSalvageData.upgradedToDelete.splice(sidx, 1); // Remove item from array
                        SAVESTrChOThroneSalvageData();
                    }
                    if (STrChOGeneralOptions.throneSorter) {
                        var cmContainerOpen = (document.getElementsByClassName('cmModalContainer').length == 1 ? true : false);
                        sortThroneSorter(!cmContainerOpen);
                        setThroneSorter(!cmContainerOpen);
                        SAVESTrChOThroneSorter();
                    }
                } else {
                    if (throne_item) Tabs.throneSalvager.setStatus('Unable to salvage item ' + throne_item.name);
                    CM.ThroneView.renderInventory(uW.kocThroneItems);
                }

                var idx = t.delItems.indexOf(id);

                if (idx >= 0) t.delItems.splice(idx, 1); // Remove item from array regardless of success. Catch on next refresh

                if (t.delItems.length > 0) { // Check if the array is empty
                    t.upgradeAndDelete();
                } else {
                    t.deleting = false;
                    t.setStatus('Salvaging complete.  Waiting for next cycle.');
                    return;
                }
            } catch (e) {
                t.deleting = false;
            }
        },
        onFailure: function () {
            t.delIems = [];
            t.deleting = false;
            CM.ThroneView.renderInventory(uW.kocThroneItems);
            return;
        }
    });
};

function ThroneAttachTab() {

    uW.hideShow    = eventHideShow;
    uW.execSalvager = Tabs.throneSalvager.togglePower;
    uW.execUpgrader = Tabs.throneUpgrader.togglePower;
    uW.execRepair  = Tabs.throneRepair.togglePower;
    uW.execSorter = Tabs.throneSorter.togglePower;
    uW.clickNextThroneLevel = Tabs.throneOrganizer.showNextThroneLevel;

    var str = ThroneTemplates.mainThrone.replace(
            '<li id="throneStatTab" class="inactive"> #{stats} </li>',
            '<li id="throneStatTab" class="inactive"> #{stats} </li>' +
            '<li id="STrChOControls" class="inactive" style="font-size: 12px;" onclick="hideShow()">STrChO</li>' +
            '<li id="STrChOExecuteSorter" class="inactive" style="font-size: 10px;" onclick="execSorter()">Sorter ' + (STrChOGeneralOptions.throneSorter ? 'ON' : 'OFF') + '</li>' +
            '<li id="STrChOExecuteRepair" class="inactive" style="font-size: 10px;" onclick="execRepair()">Repair ' + (STrChOThroneRepairData.active ? 'ON' : 'OFF') + '</li>' +
            '<li id="STrChOExecuteUpgrader" class="inactive" style="font-size: 10px;" onclick="execUpgrader()">Upgrader ' + (STrChOThroneUpgradeData.active ? 'ON' : 'OFF') + '</li>' +
            '<li id="STrChOExecuteSalvager" class="inactive" style="font-size: 10px;" onclick="execSalvager()">Salvager ' + (STrChOThroneSalvageData.active ? 'ON' : 'OFF') + '</li>' +
            '<li id="STrChOTimerDisplay" class="inactive" style="font-size: 10px;">Done</li>');
    str = str.replace( '<div id="thronePanelContainer">', '<div id="thronePanelContainer" style="z-index: 101">');
    //str = str.replace( '<li id="throneInventoryTab" class="inactive"> #{inventory} </li>', '<li id="throneInventoryTab" class="inactive" style="font-size: 12px;"> #{inventory} </li>');
    ThroneTemplates.mainThrone = str;

    ThroneTemplates.throneInfo = ThroneTemplates.throneInfo.replace (
            '<div id="throneInfoContainer">',
            '<div id="throneInfoContainer" style="z-index: 100;">');

    ThroneTemplates.mainThrone = ThroneTemplates.mainThrone.replace (
            '<div id="throneInfoContainer">',
            '<div id="throneInfoContainer" style="z-index: 100;">');

    ThroneTemplates.thronePanel = ThroneTemplates.thronePanel.replace(
            '<div class="thronePanelContainer">',
            '<div class="thronePanelContainer" style="z-index: 101;">');

    ThroneTemplates.thronePanel = ThroneTemplates.thronePanel.replace(
            '<div id="nextStatContainer" class="nextStat">',
            '<div id="nextStatContainer" class="nextStat" onclick="clickNextThroneLevel()">');

    ThroneTemplates.mainThrone = ThroneTemplates.mainThrone.replace(
            '<ul id="throneStatDisplay"></ul>',
            '<div style="width: 70%; margin-left: auto; margin-right: auto;"><input class=STrChOButton type="button" value="Post to Chat" onclick="postThroneStats()"></input></div><ul id="throneStatDisplay"></ul>');

    GM_addStyle( "div#throneMainContainer div#throneInfoContainer div.infoContainer div.statContainer div.stats > ul {height: 345px }");

    function postThroneStats() { postThroneSlot(Seed.throne.activeSlot); }

    uW.postThroneStats = postThroneStats;
}

function SAVESTrChOGlobalOptions() {
    setTimeout(function () { GM_setValue('STrChOGlobalOptions_' + uW.tvuid, JSON2.stringify(STrChOGlobalOptions)); }, 0);
}
function SAVESTrChOGeneralOptions() {
    setTimeout(function () { GM_setValue('STrChOGeneralOptions_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOGeneralOptions)); }, 0);
}
function SAVESTrChOLogData() {
    setTimeout(function () { GM_setValue('STrChOLogData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOLogData)); }, 0);
}
function SAVESTrChOThroneUpgradeStats() {
    setTimeout(function () { GM_setValue('STrChOThroneUpgradeStats_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOThroneUpgradeStats)); }, 0);
}
function SAVESTrChOThroneUpgradeData() {
    setTimeout(function () { GM_setValue('STrChOThroneUpgradeData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOThroneUpgradeData)); }, 0);
}
function SAVESTrChOThroneQueueData() {
    setTimeout(function () { GM_setValue('STrChOThroneQueueData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOThroneQueueData)); }, 0);
}
function SAVESTrChOThronePresetData() {
    setTimeout(function () { GM_setValue('STrChOThronePresetData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOThronePresetData)); }, 0);
    uW.STrChOPresetNames = STrChOThronePresetData.presetNames;
}
function SAVESTrChOThroneRepairData() {
    setTimeout(function () { GM_setValue('STrChOThroneRepairData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOThroneRepairData)); }, 0);
}
function SAVESTrChOThroneSalvageData() {
    setTimeout(function () { GM_setValue('STrChOThroneSalvageData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOThroneSalvageData)); }, 0);
}
function SAVESTrChOChampUpgradeStats() {
    setTimeout(function () { GM_setValue('STrChOChampUpgradeStats_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOChampUpgradeStats)); }, 0);
}
function SAVESTrChOChampUpgradeData() {
    setTimeout(function () { GM_setValue('STrChOChampUpgradeData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOChampUpgradeData)); }, 0);
}
function SAVESTrChOChampQueueData() {
    setTimeout(function () { GM_setValue('STrChOChampQueueData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOChampQueueData)); }, 0);
}
function SAVESTrChOChampPresetData() {
    setTimeout(function () { GM_setValue('STrChOChampPresetData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOChampPresetData)); }, 0);
}
function SAVESTrChOChampRepairData() {
    setTimeout(function () { GM_setValue('STrChOChampRepairData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOChampRepairData)); }, 0);
}
function SAVESTrChOChampSalvageData() {
    setTimeout(function () { GM_setValue('STrChOChampSalvageData_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOChampSalvageData)); }, 0);
}
function SAVESTrChOThroneSorter() {
    setTimeout(function () { GM_setValue('STrChOThroneSorter_' + getServerId() + uW.tvuid, JSON2.stringify(STrChOThroneSorter)); }, 0);
}

function LOADSTrChOGlobalOptions() {
    var s = GM_getValue('STrChOGlobalOptions_' + uW.tvuid);
    if (s != null) STrChOGlobalOptions = JSON2.parse(s);
}

function LOADSTrChOGeneralOptions() {
    var s = GM_getValue('STrChOGeneralOptions_' + getServerId() + uW.tvuid);
    if (s != null) STrChOGeneralOptions = JSON2.parse(s);
}

function LOADSTrChOLogData() {
    var s = GM_getValue('STrChOLogData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOLogData[k][kk] = opts[k][kk];
            else
                STrChOLogData[k] = opts[k];
        }
    }
}

function LOADSTrChOThroneUpgradeStats() {
    var s = GM_getValue('STrChOThroneUpgradeStats_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThroneUpgradeStats[k][kk] = opts[k][kk];
            else
                STrChOThroneUpgradeStats[k] = opts[k];
        }
    }
}

function LOADSTrChOThronePresetData() {
    var s = GM_getValue('STrChOThronePresetData_'+ getServerId() + uW.tvuid);
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThronePresetData[k][kk] = opts[k][kk];
            else
                STrChOThronePresetData[k] = opts[k];
        }
    }
//    for (var i in STrChOThronePresetData.previewThrone) {
//        var throne_item = uW.kocThroneItems[i];
//        if (throne_item == null || !throne_item) delete STrChOThronePresetData.previewThrone[i];
//    }
    uW.STrChOPresetNames = STrChOThronePresetData.presetNames;
}

function LOADSTrChOThroneSalvageData() {
    var s = GM_getValue('STrChOThroneSalvageData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThroneSalvageData[k][kk] = opts[k][kk];
            else
                STrChOThroneSalvageData[k] = opts[k];
        }
    }

    for (k in STrChOThroneSalvageData.ruleSet)
    {
        var r = STrChOThroneSalvageData.ruleSet[k];
        var rule = new ThroneRule(r.type, r.faction, r.conditions, r.advancedrule);
        for (j in rule.conditions)
        {
            rule.conditions[j].ThroneCheckCondition = ThroneCheckCondition;
        }
        STrChOThroneSalvageData.ruleSet[k] = rule;
    }
}


function LOADSTrChOThroneUpgradeData() {
    var s = GM_getValue('STrChOThroneUpgradeData_' + getServerId() + uW.tvuid);

    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThroneUpgradeData[k][kk] = opts[k][kk];
            else
                STrChOThroneUpgradeData[k] = opts[k];
        }
    }
}

function LOADSTrChOThroneRepairData() {
    var s = GM_getValue('STrChOThroneRepairData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThroneRepairData[k][kk] = opts[k][kk];
            else
                STrChOThroneRepairData[k] = opts[k];
        }
    }
}

function LOADSTrChOThroneQueueData() {
    var s = GM_getValue('STrChOThroneQueueData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThroneQueueData[k][kk] = opts[k][kk];
            else
                STrChOThroneQueueData[k] = opts[k];
        }
    }
}

function LOADSTrChOChampUpgradeStats() {
    var s = GM_getValue('STrChOChampUpgradeStats_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOChampUpgradeStats[k][kk] = opts[k][kk];
            else
                STrChOChampUpgradeStats[k] = opts[k];
        }
    }
}

function LOADSTrChOChampPresetData() {
    var s = GM_getValue('STrChOChampPresetData_'+ getServerId() + uW.tvuid);
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOChampPresetData[k][kk] = opts[k][kk];
            else
                STrChOChampPresetData[k] = opts[k];
        }
    }
}

function LOADSTrChOChampSalvageData() {
    var s = GM_getValue('STrChOChampSalvageData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOChampSalvageData[k][kk] = opts[k][kk];
            else
                STrChOChampSalvageData[k] = opts[k];
        }
    }

    for (k in STrChOChampSalvageData.ruleSet) {
        var r = STrChOChampSalvageData.ruleSet[k];
        var rule = new ChampRule(r.type, r.faction, r.conditions, r.advancedrule);
        for (j in rule.conditions) rule.conditions[j].ChampCheckCondition = ChampCheckCondition;
        STrChOChampSalvageData.ruleSet[k] = rule;
    }
}


function LOADSTrChOChampUpgradeData() {
    var s = GM_getValue('STrChOChampUpgradeData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOChampUpgradeData[k][kk] = opts[k][kk];
            else
                STrChOChampUpgradeData[k] = opts[k];
        }
    }
}

function LOADSTrChOChampRepairData() {
    var s = GM_getValue('STrChOChampRepairData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOChampRepairData[k][kk] = opts[k][kk];
            else
                STrChOChampRepairData[k] = opts[k];
        }
    }
}

function LOADSTrChOChampQueueData() {
    var s = GM_getValue('STrChOChampQueueData_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOChampQueueData[k][kk] = opts[k][kk];
            else
                STrChOChampQueueData[k] = opts[k];
        }
    }
}

function LOADSTrChOThroneSorter() {
    var s = GM_getValue('STrChOThroneSorter_' + getServerId() + uW.tvuid);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    STrChOThroneSorter[k][kk] = opts[k][kk];
            else
                STrChOThroneSorter[k] = opts[k];
        }
    }
}

function LOADallData() {
    LOADSTrChOChampPresetData();
    LOADSTrChOChampQueueData();
    LOADSTrChOChampRepairData();
    LOADSTrChOChampSalvageData();
    LOADSTrChOChampUpgradeData();
    LOADSTrChOChampUpgradeStats();
    LOADSTrChOGeneralOptions();
    LOADSTrChOGlobalOptions();
    LOADSTrChOLogData();
    LOADSTrChOThronePresetData();
    LOADSTrChOThroneQueueData();
    LOADSTrChOThroneRepairData();
    LOADSTrChOThroneSalvageData();
    LOADSTrChOThroneUpgradeData();
    LOADSTrChOThroneUpgradeStats();
    LOADSTrChOThroneSorter();
}

function SAVEallData() {
    SAVESTrChOChampPresetData();
    SAVESTrChOChampQueueData();
    SAVESTrChOChampRepairData();
    SAVESTrChOChampSalvageData();
    SAVESTrChOChampUpgradeData();
    SAVESTrChOChampUpgradeStats();
    SAVESTrChOGeneralOptions();
    SAVESTrChOGlobalOptions();
    SAVESTrChOLogData();
    SAVESTrChOThronePresetData();
    SAVESTrChOThroneQueueData();
    SAVESTrChOThroneRepairData();
    SAVESTrChOThroneSalvageData();
    SAVESTrChOThroneUpgradeData();
    SAVESTrChOThroneUpgradeStats();
    SAVESTrChOThroneSorter();
}

function SaveSettingsToFile(objSettings) {
    var uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON2.stringify(objSettings));
    var newWindow = window.open(uriContent, 'file.txt');
}

function LoadSettingsFromFile(objSettings, objTab) {
    var fileInput = document.getElementById("STrChOSettingsFile");
    var files = fileInput.files;
    if (files.length == 0) {
        alert('Failed To Select A File');
        return;
    }
    var file = files[0];

    var reader = new FileReader();

    reader.onload = function (e) {
        var output = e.target.result;
        if (output != null) {
            opts = JSON2.parse(output);
            for (k in opts) {
                if (matTypeof(opts[k]) == 'object') {
                    for (kk in opts[k]) objSettings[k][kk] = opts[k][kk];
                } else {
                    objSettings[k] = opts[k];
                }
            }
            SAVEallData();
            objTab.show();
        }
    };

    reader.readAsText(file);
}

function SuccessLog(msg) {
    var t = Tabs.STrChOLog;
    msg = msg.replace(',', '\,');
    t.addLogEntry(logValues.SUCCESS, msg);
    t.show();
}

function ActionLog(msg) {
    var t = Tabs.STrChOLog;
    msg = msg.replace(',', '\,');
    t.addLogEntry(logValues.ACTION, msg);
    t.show();
}

function SalvageLog(msg) {
    var t = Tabs.STrChOLog;
    msg = msg.replace(',', '\,');
    t.addLogEntry(logValues.SALVAGE, msg);
    t.show();
}

if (document.location.toString().match('src/main_src.php')) ScriptStartup();