Greasy Fork is available in English.

KOC Throne Room & Champ Organizer

Organizes, upgrades and salvages KOC throne room and champion items

This script has been deleted and replaced by TCO.

// ==UserScript==
// @name           KOC Throne Room & Champ Organizer
// @version        20151001
// @namespace      mmm
// @homepage       http://www.markbranscombe.com/thronechampbot/
// @delay 2000
// @priority -10
// @include        *.kingdomsofcamelot.com/*main_src.php*
// @include        *kabam.com/kingdoms-of-camelot/play*
// @resource       jqcss http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css
// @icon  https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_chair_normal_1.png
// @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
// @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
// @description    Organizes, upgrades and salvages KOC throne room and champion items
// @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=TJ9YQ8S75HFEL
// ==/UserScript==

/*
 * Modified by Ne0 of Glessic429
 *
 * 2014-03-23 : added pets, unselect all & select all buttons, updated for lvl 17, fixed 'next' in upgrade screen, fixed 6 slot cards posting, added filter by throne type
 * 2014-04-15 : added update dropdown to choose updating by Userscripts or Google Code, removed the donate button for now
 * 2014-04-18 : removed stats tabs to reduce memory, as most found they didn't use them;
 *              added a 'compare' feature which allows the user to take 2 tr cards and pull them up side by side to compare the stats (more work will be done on this feature)
 * 2014-04-19 : added 'preset #' to the throne room post to chat display so you know which # of throne room item you're displaying
 * 2014-04-29 : integrated champion organizer functions to give users 2 for 1 organizer tool
 *              added donate button in the options tab, for those who care to donate
 * 2014-04-30 : added "remove all tags" from throne and champ organizer context menu (more tag stuff will be coming soon)
 *            : minor glitch with the update dropdown selection
 * 2014-05-01 : added level 6 (miraculous) auto-enhancing
 * 2014-05-02 : added a news section so users can see what is new in the latest update
 *            : added a throne room caps tab that retrieves caps directly from the game
 *            : added a jewel inventory so you can see how many of each type of jewel you have
 * 2014-05-03 : added preset tagging
 *            : added options for changing preset tag colors and general tag colors
 * 2014-05-04 : added the ability to equip your throne items based on the tagged items from that preset #
 *            : added the ability to unequip all your throne items in a selected preset
 * 2014-05-05 : fixed glitch where tagging would cause multiple borders around card, eventually hiding it, if it was tagged a lot
 *            : fixed code for loading champ salvager settings from another domain (thought i already did that, oops!)
 *            : added quality filter to throne organizer
 *            : changed filtering to checked list boxes in throne organizer to flow more aesthetically pleasing
 *            : option given to show or hide the local presets section in throne organizer, giving some people more viewing room if they choose
 * 2014-05-06 : enhanced and renamed the jewel inventory section to be like the other organizers with filtering (no sorting yet)
 * 2014-05-07 : fixed glitch for enhance/upgrade button which stuck in endless loop and crashed browser (only since miraculous was released)
 * 2014-05-10 : fixed glitch for upgrader scrolling through queued items
 *            : added saving/loading of throne/champ salvage rules
 *            : combined both champ/throne action log into 1 complete log
 *            : additional option given to show or hide the local presets section in the options tab
 *            : added throne preset naming, so no you will be able to define your type of throne room preset
 *            : post to chat will also post the name of your throne preset
 * 2014-05-12 : added using protection stones, orbs and tokens when enhancing/upgrading throne room items
 * 2014-05-13 : TEMPORARILY DISABLED USE TOKENS FEATURE UNTIL I CAN FIX A GLITCH I FOUND
 * 2014-05-14 : fixed NON-EXISTENT glitch, bad case of "fuzzy eyes"
 *            : added user defined upgrade/enhance levels for when using stones/tokens/orbs
 *            : updated userscripts links to include 8080 so people can access them again, but i still recommend google code
 * 2014-05-15 : added using speedups for repair times on throne items
 * 2014-05-16 : fixed updater glitch, organizer will now auto update properly 
 *            : moved preset options from general organizer options to a new presets tab for more development
 *            : switched speedups section on upgrader, so the user can select the speedups they want to use
 * 2014-05-19 : fixed the champ panel menu for removing of mass salvage and removing salvage from first ##
 *            : improved equip preset so it only equips items not already equipped and thus saving time
 *            : added more functionality to the presets section, now you can save preset tags without having the preset equipped
 *            : added posting of champ stats to chat
 * 2014-05-21 : added a jewel indicator in the throne inventory screen so you know which items have jewels
 *            : BREAK YOUR THRONE ROOM!!!!!  that is right, by popular demand, you can now break your entire throne in 1 click within seconds! You can find this new feature in the presets tab 
 * 2014-05-22 : separated back out the salvage by minimum safety option into the 2 types, throne room and champ
 *            : added send to inbox upon success upgrade/enhancement (great for those who have refresh on & whisper log off)
 * 2014-05-23 : added a check to make sure you have hourglass in your inventory before it attempts to use any
 * 2014-05-27 : added tokens and speedups to champ upgrader
 * 2014-05-31 : fixed messaging glitch when champ enhancements are successful
 *            : fixed upgrade +1 glitch where you had to have upgrader set to ON in order for it to work
 *            : fixed refresh after breaking TR so you are not prompted after the message to refresh
 *            : added jewel salvager, to remove 5 jewels at a time (per click)... this feature will improve as i have more time to think of a better interface
 * 2014-06-01 : fixed early disabling of the dropdowns in jewel salvager if you do not select a jewel
 *            : fixed prompting if you do not select a throne item to salvage with
 * 2014-06-03 : fixed break tr function so it will exclude level 17 cards that cannot be upgrade to 18 yet
 *            : enhanced the look/feel of jewel salvager, and also removed the 5 jewel cap
 * 2014-06-12 : updated champion upgrade level to 12
 *            : added a links tab for bots and other useful links
 * 2014-06-17 : removed refresh prompt for when salvaging jewels is finished, bot will just refresh once done without prompt
 *            : removed selection dropdown for type of update, now only updates using googlecode site
 *            : added descriptions to the links, giving the users more detail on what the links are for
 *            : added highlighting for active throne preset different color from rest (requested by John Barnett)
 *            : added "copy to" for throne room presets so you can copy from 1 preset to another, then you can equip it into the destination preset
 *            : fixed glitch when equiping from preset or unequiping all, jewel icon would start duplicating itself
 *            : enabled users to switch on/off the "draggable" throne items option, some people have never liked that draggable option
 * 2014-07-02 : added "fail safe" protocol to stop the breaking feature if gems are used, after hearing of some people losing gems with the break TR feature somehow by mistake
 *            : reworked the "break tr" function and removed previous authors checks for gem usage and made my own, should now be 100% secure no gem usage
 *            : created an "override hourglass" function that allows you to use any 1 type of hourglass all the time no matter what (requested by Joe Stephens)
 *            : added functionality for new throne item "Tapestry"
 *            : fixed small glitch where throne cards can be broken when using lesser protection stones (thanks Audrius Audriulaitis)
 *            : added notation to action log about remaining "boost items" if boost items are used (thanks Audrius Audriulaitis)
 *            : updated the change level when upgrading if you complete a level but want to go to another level on the same card (thanks Audrius Audriulaitis)
 * 2014-07-06 : added an astone buffer to the break tr of 50k, so you will need (50k + cost to upgrade) in your city or wont break
 *            : fixed the glitch with override hourglass feature
 *            : fixed the "equipped to" feature for preset equipping when you copied from another preset, now it will unequip the types (i.e. chair, table, etc) that were not in the source preset
 *            : added "preview tr", for setting up a throne room before you use it so enemy cannot see it, like a preview before using (requested by John Barnett)
 * 2014-07-07 : added option to turn off "showing jewels" in the throne room inventory (requested by Jason DeLeone)
 *            : fixed speedups, turns out by fixing the override i messed up normal speedups
 * 2014-07-17 : updated throne room max upgrade level to 19, which also allows 17s to be broke in the "break tr" function
 *            : added a jewel filter to the throne organizer tab
 *            : added "unique" to the filter list for throne qualities (thank you Barbarossa)
 *            : changed compare to allow 3 cards to be compared (requested by Mary Bowyer)
 *            : added a "minimum" for only breaking throne items higher than selected (requested by Audrius Audriulaitis)
 *            : enabled users to "show extra tabs", for those old schoolers who do not want bells n wistles
 *            : added throne organizer filter for ignoring broken tr items (request by Kees Raymond Vermeulen)
 *            : reversed the order that rules are added, newest rule will now display at the top
 *            : added the rest of the higher MT past +12 to the remove from tokens option when manually upgrading
 * 2014-07-19 : added ability to load a throne room item into the "preview TR" section from organizer or the throne inventory panel
 *            : added ability to load an actual throne preset into the "preview TR" section (requested by Pandora Box)
 * 2014-07-22 : added different colored jewels for the different jewel qualities (thanks Barbarossa Smith)
 * 2014-07-26 : added a "load from preset tag" in the preview tr tab, that way people can view a broken tagged tr preset
              : fixed the looping spinney during jewel attachment/removal process in the throne inventory panel
 * 2014-07-27 : enhanced the card selection in preview tr to change the preview with up/down keyboard presses making for quicker viewing without the use of a mouse (request by Dean Mason)
              : add # of stones and tokens so people can track their quantity
 * 2014-07-30 : added yes/no prompt for unequip all feature (requested by Dieter Neely and many others)
              : added a save all presets button so you can save all your presets at once
              : added throne menu options when clicking on the throne image, much like the champ room (requested by George Anadiotis)
              : added the option to make hourglasses be restricted to specific levels or qualities
              : reformated speedups section for better use of space, and put the "conditions of use" in a tooltip instead
 * 2014-07-31 : returned the aetherstone counter in the upgraders so people can know what cities they are reaping astone from and how much is left during upgrades/enhancements
              : changed the height of the champion hall inventory so you don't have to scroll through your champ items (thanks to Barbarossa Smith)
              : changed the links on the links tab to expand/contract when clicked
 * 2014-08-01 : fixed a glitch with the new aether display in upgrade tabs, now displays appropriate city to use from
              : added back the enhance/upgrade stats tab, as some users had really missed that feature, sorry i removed it
 * 2014-08-06 : fixed might display on throne cards when choose "post stats to chat" or "copy stats"
              : added enhance/upgrade stats tabs for champs
              : added options to hide/show the new stats tabs for champs
 * 2014-08-07 : fixed 6th row display on throne cards when posting to chat and on the display throughout the tr/champ bot (requested by PixieCinnamon)
              : add a "click next" to the champ items upgrade panel just like the throne room has (requested by Dieter Neely)
 * 2014-08-12 : fixed a glitch with preview tr, that sometimes it wouldn't load a card from your preset slot setup
 * 2014-08-23 : fixed a glitch with preview tr, that if you previewed a card that was recently salvaged, it would cause bot to disappear
              : added a repair tab to have enhanced functionality and more convenient options for repairing, like queing specific cards for repair (request by Rose Hodge)
 * 2014-08-25 : added the "add all" for broken items in repair tab
              : added an ETA for the total time to repair all queued items (requested by Patrick Bammens)
 * 2014-08-26 : added the "repair preset tag", allowing you to select a preset that you want to repair, providing you have it tagged beforehand
              : added the name of the preset to the dropdowns wherever there is preset tagging involved, so you know the name of the preset instead of just the #
 * 2014-08-29 : added repair tab as optional for showing/hiding
              : added "post stats to chat" for the preview tr tab (requested by Rodney Lamontagne)
              : clearing tag items will also clear the name; also added prompt if you click "clear all preset tags"
              : fixed a repair glitch that had to do with starting at the wrong repair item, AND sometimes items appearing as if fixed but not
              : fixed links so that they will open in a new tab; also added a few more links
 * 2014-09-02 : revamped preview tr and compare tr visual display to make more compact and save space, also added card hover tooltip
 * 2014-09-03 : added hover tooltip for champ card while in the champ upgrader and organizer tabs
              : added context menu for throne cards in both compare tr tabs
              : revamped throne room organizer tab to be more compact
              : revamped champ room organizer tab to be more compact
              : added more filters for champ in the organizer tab
              : revamped size of the tr/champ bot so it should now fit on a screen even if you do not use widescreen mode
 * 2014-09-04 : reduced the number of repaints to each card in preview tr, which i believe was causing so many crashes
 * 2014-09-05 : fixed the display of uniques name in the textual display of throne cards (in preview, compare and organizer tab)
              : added option to select the new textual display or the old graphical display for viewing cards
 * 2014-09-06 : fixed the preview stats loading in preview tr tab, after breaking it on my last update
              : added back the "active" highlights to equipped cards in the organizer tab, but only while using the graphic view option
 * 2014-09-07 : fixed the champion card posting to chat and copying to clipboard
 * 2014-09-10 : fixed the glitches that were causing the bot to crash while using the repair tab (lets cross our fingers!)
              : added horizontal scroll bar to upgrader and repair queue lists
 * 2014-09-11 : fixed more bugs
              : fixed problem with the images in throne room where the context menu would not work after switching thrones
 * 2014-09-13 : added contextmenu to the champ item images
              : added check to remove auto-enhance/upgrade if champ item is already at max rarity/level
              : added menu on champ organizer when you select a card, just like throne organizer (requested by Robert Jon)
 * 2014-09-17 : added the ability to take all throne items of one level to another level (requested by Ian Broadbent)
 * 2014-09-18 : added back the 11 column view of throne organizer, BUT with an option to switch to compact view
 * 2014-09-19 : added a repair throne item by level option to repair tab (requested by Peter Johnston)
 * 2014-09-23 : fixed the custom enhance/upgrade yellow buttons for champ context menu
              : added a salvage button to the custom context menu for champs
              : added the ability to take all champ items of one level to another level
              : fixed sizing issue with throne organizer when in 11 column view
 * 2014-09-24 : fixed (hopefully) the auto update
 * 2014-09-25 : added "forced salvage" to the context menu, this will salvage an item even with a jewel
              : fixed custom champ salvage button
              : added back the column view in champ organizer, just like throne organizer you now have the compact option
              : added export to excel file for throne AND champ inventory (requested by Leslie Grilley)
              : added "Any Spellcaster" to the throne room rules (requested by Onebiggoxx Baker)
 * 2014-09-26 : added a throne uniques tab (thanks to Barbarossa Smith)
              : changed tab colors (throne = green, champ = purple, bot = blue)
 * 2014-09-27 : added an "advanced rule" creater to salvage tab (requested by Jaddoo Emmanuel)
              : added the ability to take all throne/champ items from one quality to another quality (requested by Gary Cummins)
              : added a tutorial tab for the throne/champ tutorials
              : added custom color choosing for the tabs
              : added export preview throne setup to file (requested by Kenneth Tompkins)
 * 2014-10-04 : added champ preset tagging
              : added break champion hall
              : added "unequip all" to champs
              : added sort order to throne/champ salvager rules by card type (requested by Audrius Audriulaitis)
              : added more hourglasses (requested by Henriette Paagh)
              : added "no forced salvage" option to hide that feature if you want (requested by Jeffrey Donati)
              : updated advanced salvager rules to include most recent updated info from spreadsheet
              : moved the delete button for upgrader queue to the left, hopefully clearing up scrolling issues
 * 2014-10-05 : made throne/champ organizer display over all other bots (requested by Eric Wong)
              : fixed some issues with horizontal spacing at the item selection for upgraders (requested by Eric Wong)
 * 2014-10-07 : extended champ to level 14
 * 2014-10-11 : added a "below" criteria for breaking throne/champ rooms (requested by Barrie Morris)
              : added champ hall repair tab
 * 2014-10-12 : fixed some issues with unequip all, equip from preset and the copy feature for preset tags
              : added a confirmation prompt to the break throne/champ buttons in case you hit them by accident
 * 2014-10-13 : added under the break throne/champ sections how much might is broken (requested by Antwyn Collins)
              : added total champ might to the champion hall (requested by Kenneth Tompkins)
              : added total champ might to the display when posting champ stats
 * 2014-10-18 : added a useless bacon phrase button as a joke for those bacon lovers who keep asking me for bacon stuff in the script
              : script will now update new levels and qualities as kabam adds more, without a physical update from me
 * 2014-10-29 : i believe i fixed the champ might display
              : fixed the salvage routine to make cloaks work properly
              : added champ preview tab
 * 2014-11-10 : added new throne item "pillar"
              : fixed outlining of champ upgrade/enhance
 * 2014-11-16 : added advanced rules for pillar
              : added advanced rules section for champs
   2014-11-19 : added damage back to the searchable champ stats even though it is only in weapon slot 1
              : added options to show/hide preset names and might when posting to chat [find under preset tabs]
              : added posting to chat, throne slots AND preset slots for throne rooms without room being active
              : added posting to chat, champ slots AND preset slots for champ halls without hall being active
   2014-12-15 : updated the change level when upgrading if you complete a level but want to go to another level on the same champ card (thanks Audrius Audriulaitis)
              : updated advanced throne rules for new findings (thanks again Gunvald Storheil)
              : updated link to Gunvalds spreadsheet on google
              : added "any tower" to the salvage rules
   2014-12-18 : removed clearing of the name from throne presets when you click "clear" (request by  Wendy Taylor)
   2014-12-23 : fixed effects dropdown for champ organizer, where it was showing both buff and debuff for effect names
   2014-12-26 : fixed some display issues where sometimes you can only see the first 3 lines of a card
   2015-01-12 : added break individual equipped throne room (requested by Ron Moe)
              : added break individual tagged presest throne room (requested by Ron Moe)
              : added break throne room to a certain might level
              : added throne/champ preview tab export to excel (thanks Barbarossa Smith)
              : added export tagged presets to file (requested by Jaddoo Emmanuel)
   2015-01-20 : fixed glitch when deleting throne/champ rules when sorted (requested by Corinne Morris)
   2015-01-22 : fixed glitch when you click next on throne card it would only show in compact view
   2015-01-29 : kabam changed code on side bar in throne panel, had to adjust code to fix it
   2015-02-17 : made the popup menu for pendants available in champs
   2015-03-20 : fixed for missing throne uniques
              : added "clear stats" buttons to all 4 stats tabs so you can reset the stats (requested by Shadows)
   2015-05-22 : fixed the images due to kabam changing their image host
   2015-05-24 : fixed the images links on the uniques throne pictures as well
   2015-06-05 : fixed so higher master tokens would show when disabling them
              : added the 8 new throne presets to the widget
              : removed the 'Disable success animation' which i left in by mistake while testing a few releases ago
   2015-06-08 : fixed the new 8 row preset glitch that causes the last card collection row to cut off (thanks Barbarossa Smith)
   2015-06-23 : fixed preset tagging to include the new 8 rows
   2015-07-29 : made auto selecting next masters token on manual upgrade
              : added "tag all" to throne/champ inventory, this tags everything with a generic tag (requested by Sam Adams)
              : WARNING!!!: changes in game code have caused disabling the upgrade button when below threshold to not work
   2015-08-01 : fixed the disabling of upgrade button when below the safety threshold defined by user
   2015-09-05 : got rid of the useless bacon phrase, sorry, im just trying to keep things relavent for my upcoming revamp
              : added an "upgrade all to level" option, for those events that are garunteed upgrade to a certain level
              : removed selectable site to update, updates only on greaseyfork at this time
              : added the ability to remove the new "chance" upgrade tokens from the dropdown
              : updated some links and added Aderiks slideshow links
   2015-09-11 : removed greaseyfork as the main download for updates, it will now update straight from my website
              : fixed the enhancement/upgrading statistics pages, did not realize they were not pushed for higher levels
   2015-09-30 : opened context menu for champ rings
              : fixed champ organizer to read only ONE ring (to rule them all!!!  lol) instead of 2
              : post to chat reads ring instead of ring 1
              : rules for champs will search for ring, not ring 1 or ring 2
   2015-10-01 : added some missing champ effects for rule making

 */
 
var Version = '20151001';

var OrganizerPopUpTopClass = 'orgPopTop';
var OrganizerTitle= 'Throne Room & Champ Organizer (v' + Version + ')';
var OrganizerHeaderSize = '10%';
var OrganizerWindowWidth = '750px';
var OrganizerWindowWidthLarge = '1000px';
var OrganizerWindowHeight = '400px';
var OrganizerWindowHeightLarge = '600px';
var OrganizerOpacity = 1.0;
var OrganizerButtonLabel = "THRONE/CHAMP";
var OrganizerMaxTRLevel = 0;
var OrganizerMaxCHLevel = 0;
var OrganizerMaxTRQuality = 0;
var OrganizerMaxCHQuality = 0;
var OrganizerMaxChampions = 0;
var OrganizerBreakAstoneBuffer = 50000;
var OrganizerCardScale = 1;
var OrganizerTooltipCardScale = 1;
var OrganizerPlayerUID = "";
var OrganizerPresetSlots = 24;
for (var n in unsafeWindow.seed.players) { OrganizerPlayerUID = n; break; }
OrganizerPlayerUID = OrganizerPlayerUID.split("u")[1];

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

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

var HourGlassName = {
                    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"
};

var tabColorsIndex = [ "blue", "magenta", "green", "orange", "red", "yellow", "grey" ];

var tabColors = [   "http://i.imgur.com/yNacBue.png",
                    "http://i.imgur.com/aIvGGi4.png",
                    "http://i.imgur.com/vthPqAP.png",
                    "http://i.imgur.com/UpghF0A.png",
                    "http://i.imgur.com/sZA8iwD.png",
                    "http://i.imgur.com/V1rGJ9T.png",
                    "http://i.imgur.com/4yk8alP.png"
];

var champItemTypes = {"weapon": 1, "chest": 2, "helm":3, "boots":4, "shield": 5, "ring": 6, "pendant": 8, "cloak": 9};
var champItemNames = {1: "weapon", 2: "chest", 3: "helm", 4: "boots", 5: "shield", 6: "ring", 8: "pendant", 9: "cloak"};
//var champItemTypes = {"weapon": 1, "chest": 2, "helm":3, "boots":4, "shield": 5, "ring1": 6, "ring2": 7, "pendant": 8, "cloak": 9};
//var champItemNames = {1: "weapon", 2: "chest", 3: "helm", 4: "boots", 5: "shield", 6: "ring1", 7: "ring2", 8: "pendant", 9: "cloak"};

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 prefix = 'org';

var ResetAll = false;
var DEBUG_TRACE = false;

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
}

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


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

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

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

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


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

                    oldval = newval;

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

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

                    if (!obj.watchers) obj.watchers = {};

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

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

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

            }
        });
    }

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

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

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

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

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

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

var ajfx = unsafeWindow.g_ajaxparams;

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 URL_CASTLE_BUT = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAXCAYAAADk3wSdAAAACXBIWXMAAAsSAAALEgHS3X78AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48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P/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+98jG12RndKN6Fedfx4vlaG2Pt1F1dIkprCngovKlRVcZmq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1b6SPXdWXS+O+gRzdaypeeSOaa5xEkeB6SKOLf0mcyzHMtescq5Bn2tqbbe7lxVqpl2PZfTeKKASXMdSjTXcHNAZFqZlnpYDbkjrbYWmdlWFUzbYxxVUIbkIWxE2RSfseyUlEn2QQC1Aqs0aEngszOWqF5sn0UuKE7Q12Yve+W6U670tiI3ec7rLFmPsSTXu+A6M5MeFysR1WUNeu9kAOGh0JLuVHPQDPM4Rs4ZqdpMpAqpsjlb4/hMiITQXcvenkNBOTQPzeSa0iqxRow0y2ApeM30srZcp+AcUbp8B2Lq1Joc9ul6yoreT/f7lMMFl7cQFa/n7nWFqVZ7TVvKUmp3GXqFVAtYBRVpSruiqBEU2SVHRAKQ4iNTBuwckclA3XK33CKiOdUNS+IVaw3n2hSrC2uNXL1G6+49yFWqzXcg4sbHmw+zfmddOT577E9cnbNcJDftwO1JzO7sJ+eiMKFkyi6y9x5d0AKvhiKP2SFcxtkf46Ga5xHZytzDUMpxhJOWurWd7qJWGM+npGhNrNGiOdQkN/fSeultqu6Z0a495cUGwqfHOb3XXc8Nc7XCtNqGx/0SsWPWrU/qscZEnTOpWXrTEP7Fq9WLrOosNQalCZtiUA5AsblPjMfM7hCRFiY2g8NKcsyUgG65Ee69lR60FnJXj66rbHPU/ux29pOM7PWUx5sPsz7s9gn/H47+ChCYwenhAAAAAElFTkSuQmCC";

var ChampStatsGrid =  {
    "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}},
//    "ring2" :      {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 ThroneStatsGrid = {
    "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 TRupgradeStats = {
    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 },
        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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    },

    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 },
        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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    },

    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 },
        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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    },

    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 },
        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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    }
};

var CHupgradeStats = {
    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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    },
    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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    },
    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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    },
    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 },
        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 },
        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 },
        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 },
        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 },
        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 }
    }
};

var TRrepairData = {
    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 CHrepairData = {
    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 TRupgradeData = {
    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,
    item: 0,
    overrideSpeedUp: false,
    hourglassLevelSpecific: false,
    hourglassLevel: 0,
    hourglassQualitySpecific: false,
    hourglassQuality: 0,
    useSpeedUp: 0,
    enhanceAction: false,
    enhanceItem: 0,
    enhanceMax  : OrganizerMaxTRQuality,
    repairAll : false,
    trWinPos: {},
    activeTab: 1,
    sortSelected: "none",
    buffSelected: "both",
    sortInactive: true,
    ignoreBroken: false,
    newUpgradeState: 0
};


var CHupgradeData = {
    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,
    item : 0,
    overrideSpeedUp: false,
    hourglassLevelSpecific: false,
    hourglassLevel: 0,
    hourglassQualitySpecific: false,
    hourglassQuality: 0,
    useSpeedUp: 0,
    enhanceAction: false,
    enhanceItem: 0,
    enhanceMax  : OrganizerMaxCHQuality,
    repairAll : false,
    sortSelected: "none",
    buffSelected: "both",
    sortInactive: true,
    ignoreBroken: false,
    newUpgradeState: 0
};

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

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


var GlobalOptions = {
    OrganizerUpdate: false,
    OrganizerDate : 0,
    OrganizerVersion : 0,
    UpdateSite: 0  // greasyfork_name
};

var GeneralOptions = {
    currentTab : null,
    WinIsOpen: false,
    localPresetHidden: false,
    showJewels: true,
    compactView: true,
    draggableThroneItems: false,
    disableAnim : false,
  //  disableSuccessCheck : false,
    salvageAnyCity : true,
    useAnyCity : true,
    usedCityNum : 0,
    salvageCityNum : 0,
    minStones : 100000,
    overflow : "order",
    maxStones     : 1980000,
    retryInterval : 30,
    presetWidget: true,
    whisperToMe: false,
    sendToInbox: false,
    buffsOff: false,
    safetyOn: false,
    safetyLimit: 100000,
    removeMastersTokens: false,
    removeOtherTokens: false,
    useTokens: false,
    multiUpgrade: false,
    noMassSalvage: false,
    noForcedSalvage: false,
    TRsalvageSafety: false,
    CHsalvageSafety: false,
    showTabPresetsTR: true,
    showTabPresetsCH: true,
    showTabUniquesTR: true,
    showTabCompareTR: true,
    showTabPreviewTR: true,
    showTabPreviewCH: true,
    showTabLog: true,
    showTabCapsTR: true,
    showTabJewelsTR: true,
    showTabNews: true,
    showTabLinks: true,
    showTabTutorials: true,
    showTabEnhanceStatsTR: true,
    showTabUpgradeStatsTR: true,
    showTabEnhanceStatsCH: true,
    showTabUpgradeStatsCH: true,
    showTabRepairTR: true,
    showTabRepairCH: true,
    graphicalThrone: false,
    tabColorOptions: 0,
    tabColorChamp: 1,
    tabColorThrone: 2,
    TRnumSafety: 40,
    CHnumSafety: 40
};
   
var presetPosition = null;
var guardPosition = null;

var CHpresetData = {
    items : [],
    ids : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R'],
    desc : ['Preset A', 'Preset B', 'Preset C', 'Preset D', 'Preset E', 'Preset F', 'Preset G', 'Preset H', 'Preset I', 'Preset J',
            'Preset K', 'Preset L', 'Preset M', 'Preset N', 'Preset O', 'Preset P', 'Preset Q', 'Preset R'],
    num_presets: 10,
    presetNames: ["undefined", "undefined", "undefined", "undefined"],
    noTooltips : false,
    usePreset : 0,
    showCHMight: true,
    showCHName: true,
    presetColor: "#0000FF",
    tagColor: "#FFFFFF",
    activeColor: "#FFFF00",
    taggedItems: {},
    taggedItems01: {},
    taggedItems02: {},
    taggedItems03: {},
    taggedItems04: {},
    previewChamp: {}
};


var TRpresetData = {
    items: [],
    ids: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R'],
    desc: ['Preset A', 'Preset B', 'Preset C', 'Preset D', 'Preset E', 'Preset F', 'Preset G', 'Preset H', 'Preset I', 'Preset J',
                'Preset K', 'Preset L', 'Preset M', 'Preset N', 'Preset O', 'Preset P', 'Preset Q', 'Preset R'],
    num_presets: 10,
    presetNames: ["undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
                       "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined"],
    noTooltips: false,
    usePreset: 0,
    showTRMight: true,
    showTRName: 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 TRsalvageData = {
        salvageActive : 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
};

var CHsalvageData = {
        salvageActive : 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}
};

var n = new Date();
TRsalvageData.since = n.valueOf();
CHsalvageData.since = n.valueOf();

var Seed = unsafeWindow.seed;
var Tabs = {};
var uW = unsafeWindow;
var CM = unsafeWindow.cm;
var Cities = {};

var OrganizerStartupTimer = null;

var TROrganizerDisplayTimer = null;

var CHOrganizerDisplayTimer = null;

function OrganizerStartup (){

    if (!unsafeWindow.cm) return;

    if (uW.trLoaded) return;

    var metc = getClientCoords(document.getElementById('main_engagement_tabs'));
    if (metc.width==null || metc.width==0){
        OrganizerStartupTimer = setTimeout (OrganizerStartup, 1000);
        return;
    }

    OrganizerMaxTRLevel = unsafeWindow.cm.MAX_MASTERS_TOKEN_LEVEL;
    OrganizerMaxCHLevel = unsafeWindow.cm.CHAMPION.MAX_LEVELS;
    OrganizerMaxTRQuality = unsafeWindow.cm.ThronePanelController.MAX_QUALITY;
    OrganizerMaxCHQuality = unsafeWindow.cm.CHAMPION.MAX_EFFECTS;
    OrganizerMaxChampions = unsafeWindow.seed.champion.champions.size();

    uW.trLoaded = Version;

    readGeneralOptions();
    TRreadUpgradeData();
    CHreadUpgradeData();
    TRreadRepairData();
    CHreadRepairData();

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

    TRreadUpgradeStats();
    CHreadUpgradeStats();
    JLreadSalvageData();
    TRreadSalvageData();
    TRreadQueueData();
    TRreadPresetData();
    CHreadSalvageData();
    CHreadQueueData();
    CHreadPresetData();


    logit ("Throne/Champ room organizer loaded");

    installHandlerFunctions();

    var styles =  '.xtab {padding-right: 5px; border:none; background:none; white-space:nowrap;}';
        styles += '#itemInventory {min-height: 420px; background-color:#884422;}';
        styles += '.xtabBR {padding-right: 5px; border:none; background:none;}';
        styles += '.koclinks {font-family: tahoma,verdana,arial,sans-serif; font-size: 14px; font-variant: normal; font-style: normal; font-weight: normal; color: #000000; text-decoration: none;}';
        styles += '.koclinksheader {font-family: tahoma,verdana,arial,sans-serif; font-size: 14px; font-variant: normal; font-style: normal; font-weight: bold; color: #000000; text-decoration: none;}';
        styles += '.koclinksdesc {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 += '.tagBorderThrone { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + TRpresetData.tagColor + '; background: transparent;}';
        styles += '.presetBorderThrone { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + TRpresetData.presetColor + '; background: transparent;}';
        styles += '.activeBorderThrone { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + TRpresetData.activeColor + '; background: transparent;}';
        styles += '.tagBorderChamp { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + CHpresetData.tagColor + '; background: transparent;}';
        styles += '.presetBorderChamp { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + CHpresetData.presetColor + '; background: transparent;}';
        styles += '.activeBorderChamp { margin-right: -100%; margin-bottom: -100%; height: 72%; width: 72%; padding: 4%; border: 3px solid ' + CHpresetData.activeColor + '; background: transparent;}';
        //styles += 'div.activeBorder2 { position: absolute; }';
        styles += 'div.greenBorder2 {position: absolute; }';
        styles += '.semi_transparent { zoom: 1; filter: alpha(opacity=60); opacity: 0.6;}';
        styles += '.rot45 { transform: rotate(-45deg); -ms-transform: rotate(-45deg); -webkit-transform: rotate(-45deg); -o-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -moz-transform-origin: 100% 100%; z-index: 10;}';
        styles += 'div.cardOverlay { font: cracked; font-size:1.5em; position: absolute; left: 0%; top: 50%; color: red; text-align: center; text-shadow: 2px 2px 4px #000;}';
        styles += 'body table.trMainTab tbody tr td {background: transparent;}';
        styles += 'table.trTabdef { height: 0px;}';
        styles += 'body table.chMainTab tbody tr td {background: transparent;}';
        styles += 'table.chTabdef { height: 0px;}';
        styles += '.trCardDisp { display:static;}';
        styles += '.chtrTooltip { display:static;position:fixed;z-index:10000;left:10%;top:10%;}';
        styles += 'table.trTabDef thead {background: transparent;}';
        styles += 'table.orgPopMain tbody tr td,th {background: transparent;}';
        styles += 'table.trTabDef tbody tr td {background: transparent; height: 0px; }';
        styles += 'table.trTab tr td, th { border: 1px solid brown;}';
        styles += '#org_footer {height: 50px; background: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/dialog_740_r3_c1.jpg") scroll no-repeat center bottom;}';
        styles += '#org_footer { background-size: cover; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; }';
        styles += 'table.trTab tr td,th {border:none; background:none; padding: 0px}';
        styles += 'table.trTab#trDisplayTable tr th { border: 3px solid grey; font-size:1.2em; }';
        styles += 'table.trStatTab tr td { background-color: #ffffff; white-space:nowrap; padding:5px; border-bottom:solid black 1px;}';
        styles += 'table.trStatTab tr td:last-child { border-right:solid black 1px; }';
        styles += 'table.trStatTab tr:first-child th { border-top:solid black 1px; }';
        styles += 'table.trStatTab tr td.td0 { background-color: white; }';
        styles += 'table.trStatTab tr td.td1 { background-color: #eeeeee; }';
        styles += 'table.trStatTab tr td.td2 { background-color: white; }';
        styles += 'table.trStatTab tr th {border:solid black 1px; border-top: none; background-color: #357; color: white; white-space:nowrap; padding:5px}';
        styles += 'table.trStatTab tr:last-child td:first-child, table.trStatTab tr:last-child th:first-child { -moz-border-radius-bottomleft:10px; -webkit-border-bottom-left-radius:10px; border-bottom-left-radius:10px} ';
        styles += 'table.trStatTab tr:last-child td:last-child, table.trStatTab tr:last-child th:last-child { -moz-border-radius-bottomright:10px; -webkit-border-bottom-right-radius:10px; border-bottom-right-radius:10px} ';
        styles += 'table.trStatTab tr:first-child th:first-child { -moz-border-radius-topleft:10px; -webkit-border-top-left-radius:10px; border-top-left-radius:10px} ';
        styles += 'table.trStatTab tr:first-child th:last-child { -moz-border-radius-topright:10px; -webkit-border-top-right-radius:10px; border-top-right-radius:10px} ';
        styles += 'table.trTabLined tbody tr td {border-bottom:1px solid gray; padding: 2px 5px; }';
        styles += 'table.trOptions tr td,th {border:1px none none solid none; padding: 1px 3px; white-space:nowrap;} ';
        styles += 'table.trSrchResults tr td,th {border:1px none none solid none; padding: 1px 3px; white-space:nowrap;}';
        styles += 'table.trTabSome tr td,th {border:none; background:none; padding: 1px 3px; white-space:nowrap;}';
        styles += 'table.trTabPad tr td,th { padding-left: 2px; background: none;}';
        styles += 'table.trTabPad2 tr td,th { padding-left: 20px; background: none;}';
        styles += '.trDetLeft {padding:0 5px 0 0 !important; font-weight:bold; text-align:right}';
        styles += '.trStat {border:1px solid; border-color:#000000; font-weight:bold; padding-top:2px; padding-bottom:2px; text-align:center; color:#ffffff ; background-color:#357;  -moz-border-radius:5px;}';
        styles += '.trentry {padding: 7px; white-space:nowrap;}';
        styles += 'table.chTabDef thead {background: transparent;}';
        styles += 'table.chTabDef tbody tr td {background: transparent; height: 0px; }';
        styles += 'table.chTab tr td, th { border: 1px solid brown;}';
        styles += 'table.chTab tr td,th {border:none; background:none; padding: 0px}';
        styles += 'table.chTab#chDisplayTable tr th { border: 3px solid grey; font-size:1.2em; }';
        styles += 'table.chStatTab tr td { background-color: #ffffff; white-space:nowrap; padding:5px; border-bottom:solid black 1px;}';
        styles += 'table.chStatTab tr td:last-child { border-right:solid black 1px; }';
        styles += 'table.chStatTab tr:first-child th { border-top:solid black 1px; }';
        styles += 'table.chStatTab tr td.td0 { background-color: white; }';
        styles += 'table.chStatTab tr td.td1 { background-color: #eeeeee; }';
        styles += 'table.chStatTab tr td.td2 { background-color: white; }';
        styles += 'table.chStatTab tr th {border:solid black 1px; border-top: none; background-color: #357; color: white; white-space:nowrap; padding:5px}';
        styles += 'table.chStatTab tr:last-child td:first-child, table.trStatTab tr:last-child th:first-child { -moz-border-radius-bottomleft:10px; -webkit-border-bottom-left-radius:10px; border-bottom-left-radius:10px}';
        styles += 'table.chStatTab tr:last-child td:last-child, table.trStatTab tr:last-child th:last-child { -moz-border-radius-bottomright:10px; -webkit-border-bottom-right-radius:10px; border-bottom-right-radius:10px}';
        styles += 'table.chStatTab tr:first-child th:first-child { -moz-border-radius-topleft:10px; -webkit-border-top-left-radius:10px; border-top-left-radius:10px}';
        styles += 'table.chStatTab tr:first-child th:last-child { -moz-border-radius-topright:10px; -webkit-border-top-right-radius:10px; border-top-right-radius:10px}';
        styles += 'table.chTabLined tbody tr td {border-bottom:1px solid gray; padding: 2px 5px; }';
        styles += 'table.chOptions tr td,th {border:1px none none solid none; padding: 1px 3px; white-space:nowrap;}';
        styles += 'table.chSrchResults tr td,th {border:1px none none solid none; padding: 1px 3px; white-space:nowrap;}';
        styles += 'table.chTabSome tr td,th {border:none; background:none; padding: 1px 3px; white-space:nowrap;}';
        styles += 'table.chTabPad tr td,th { padding-left: 2px; background: none;}';
        styles += 'table.chTabPad2 tr td,th { padding-left: 20px; background: none;}';
        styles += '.chDetLeft {padding:0 5px 0 0 !important; font-weight:bold; text-align:right}';
        styles += '.chStat {border:1px solid; border-color:#000000; font-weight:bold; padding-top:2px; padding-bottom:2px; text-align:center; color:#ffffff ; background-color:#357;  -moz-border-radius:5px;}';
        styles += '.cchentry {padding: 7px; white-space:nowrap;}';
        styles += 'button::-moz-focus-inner, input[type="submit"]::-moz-focus-inner { border: none; }';
        styles += 'button::-moz-focus-inner, input[type="button"]::-moz-focus-inner { border: none; }';
        styles += '.castleBut {outline:0px; margin-left:0px; margin-right:0px; width:24px; height:26px; font-size:12px; font-weight:bold;}';
        styles += '.castleBut:hover {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}';
        styles += '.castleButNon {background-image:url("'+ URL_CASTLE_BUT +'")}';
        styles += '.castleButSel {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}';
        styles += 'input.trDefButOn {cursor:pointer; border:1px solid #45d183; -moz-box-shadow:inset 0px 1px 5px #3aef8b; -moz-border-radius:5px;}';
        styles += 'input.trDefButOff {cursor:pointer; border:1px solid #f61646; -moz-box-shadow:inset 0px 1px 5px #f6375f; -moz-border-radius:5px;}';
        styles += 'table.trMainTab { empty-cells: show;  }';
        styles += 'table.trMainTab tr td,th a {color:inherit }';
        styles += 'table.trMainTab tr td,th  {height:60%; empty-cells:show; padding: 0px 0px 0px 0px;  margin-top:5px; white-space:nowrap; border: 1px solid; border-style: none none solid none; -moz-border-radius:5px; }';
        styles += 'table.trMainTab tr td.spacer,th.space {padding: 0px 0px;}';
        styles += 'table.trMainTab tr th.sel,td.sel    {font-weight:bold; font-size:13px; }';
        styles += 'table.trMainTab tr th.notSel,td.notSel {font-weight:bold; font-size:13px; }';
        styles += 'tr.orgPopTop td,th { background-color:transparent; border:none; height: 21px;  padding:0px;}';
        styles += '.orgPopMain  { -moz-box-shadow:inset 0px 0px 10px #6a6a6a; -moz-border-radius-bottomright: 20px; -moz-border-radius-bottomleft: 20px;}';
        styles += '.orgPopup { border:3px ridge #666; opacity:'+ OrganizerOpacity +'; -moz-border-radius:25px; -moz-box-shadow: 1px 1px 5px #000000;}';
        styles += '.orgPopup { overflow-x: hide; overflow-y: hide; max-height: 900px; min-height: 300px; height: ' + OrganizerWindowHeight + ';  }';
        styles += '#org_top { background: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/dialog_740_r2_c1.jpg") no-repeat transparent 0% 0%; }';
        styles += '#org_top { background-size: cover; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; }';

        styles += 'div.trCard2 {width: 250px;}';
        styles += 'div.trCard2 ul{margin:0px;padding:0;list-style:none;text-align:center;}';
        styles += 'div.trCard2 li{padding:0px 0 0 0px;color:#3f2300;font-weight:bold;font-size:11px;}';
        styles += 'div.trCard2 div.trCardDetail{align:center;border:1px solid;}';

        styles += 'div.chCard2 {width: 250px;}';
        styles += 'div.chCard2 ul{margin:0px;padding:0;list-style:none;text-align:center;}';
        styles += 'div.chCard2 li{padding:0px 0 0 0px;color:#3f2300;font-weight:bold;font-size:11px;}';
        styles += 'div.chCard2 div.chCardDetail{align:center;border:1px solid;}';

        styles += 'div.trCard {width: 200px; height: 260px;}';
        styles += 'div.trCard div.description>div{width:70px;height:70px; }';
        styles += 'div.trCard div.description div.briton.advisor{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_advisor_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.banner{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_banner_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.chair{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_chair_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.table{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_table_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.window{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_window_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.trophy{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_trophy_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.hero{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_hero_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.statue{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_statue_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.candelabrum{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_candelabrum_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.pet{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_pet_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.tapestry{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_tapestry_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.briton.pillar{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/briton_pillar_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.advisor{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_advisor_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.banner{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_banner_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.chair{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_chair_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.table{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_table_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.window{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_window_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.trophy{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_trophy_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.hero{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_hero_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.statue{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_statue_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.candelabrum{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_candelabrum_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.pet{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_pet_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.tapestry{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_tapestry_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.druid.pillar{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/druid_pillar_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';  
        styles += 'div.trCard div.description div.fey.advisor{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_advisor_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.banner{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_banner_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.chair{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_chair_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.table{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_table_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.window{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_window_normal_1.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.trophy{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_trophy_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.hero{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_hero_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.statue{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_statue_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.candelabrum{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_candelabrum_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.pet{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_pet_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.tapestry{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_tapestry_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';
        styles += 'div.trCard div.description div.fey.pillar{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/fey_pillar_normal_1_5.png") top left no-repeat; background-size: 70px 70px;}';  
        styles += 'div.trCard div.description{overflow:hidden;border-bottom:1px solid #703200;padding:5px 0;}';
        styles += 'div.trCard div.description{overflow:hidden;border-bottom:1px solid #703200;}';
        styles += 'div.trCard div.description div.portrait{float:left;}';
        styles += 'div.trCard div.description div.portrait{border:3px solid #deaf69;margin-right:10px;}';
        styles += 'div.trCard div.description>ul{float:left;margin:3px 0 0 0;padding:0;}';
        styles += 'div.trCard div.description>ul li{padding:0;font-weight:bold;font-size:11px;text-transform:capitalize;}'; //tooltip
        //styles += 'div.trCard div.description>ul li{padding:0;font-weight:bold;font-size:9px;text-transform:capitalize;}';
        styles += 'div.trCard{font:bold 10px Georiga; overflow: hidden;}';
        styles += 'div.trCard>div{float:left;border:1px solid #a56631;margin:0px;padding:0px;width:200px; height:300px; background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/modal/modal_med_bg_4.png") -200px 0 no-repeat;}'; //tooltip
        //styles += 'div.trCard>div{float:left;border:1px solid #a56631;margin:0px;padding:0px;width:150px; height:200px; background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/modal/modal_med_bg_4.png") -200px 0 no-repeat;}';
        styles += 'div.trCard div.title{font:bold 14px Georgia;border-bottom:1px solid #703200;padding:4px 3px 5px 8px;background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/panel/modal/item_bg.png") -20px -100px no-repeat;}'; //tooltip
        //styles += 'div.trCard div.title{font:bold 11px Georgia;border-bottom:1px solid #703200;padding:4px 3px 5px 8px;background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/panel/modal/item_bg.png") -20px -100px no-repeat;}';
        styles += 'div.trCard div.title span.icon{background:transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/modal/equip.png") top right no-repeat;display:block;height:20px;width:20px;top:12px;right:12px;position:absolute;}';
        styles += 'div.trCard .disabled{opacity:.5;}';
        styles += 'div.trCard ul{margin:0px;padding:0;list-style:none;}';
        styles += 'div.trCard li{padding:0px 0 0 0px;color:#3f2300;font-weight:bold;font-size:13px;}'; //tooltip
        //styles += 'div.trCard li{padding:0px 0 0 0px;color:#3f2300;font-weight:bold;font-size:10px;}';
        styles += 'div.trRule {border:2px inset #c0c0c0; margin-right:10px; margin-left:10px; margin-bottom:2px; padding-left:5px; padding-bottom:5px}';
        styles += 'div.trRuleCreate {margin-right:10px; padding-right: 5px; margin-bottom:2px; padding-bottom:5px}';
        styles += 'div.trRule { background-color: #eeeeee; }';
        styles += 'input.chDefButOn {cursor:pointer; border:1px solid #45d183; -moz-box-shadow:inset 0px 1px 5px #3aef8b; -moz-border-radius:5px;}';
        styles += 'input.chDefButOff {cursor:pointer; border:1px solid #f61646; -moz-box-shadow:inset 0px 1px 5px #f6375f; -moz-border-radius:5px;}';
        styles += 'table.chMainTab { empty-cells: show;  }';
        styles += 'table.chMainTab tr td,th a {color:inherit }';
        styles += 'table.chMainTab tr td,th  {height:60%; empty-cells:show; padding: 0px 0px 0px 0px;  margin-top:5px; white-space:nowrap; border: 1px solid; border-style: none none solid none; -moz-border-radius:5px; }';
        styles += 'table.chMainTab tr td.spacer,th.space {padding: 0px 0px;}';
        styles += 'table.chMainTab tr th.sel,td.sel    {font-weight:bold; font-size:13px; }';
        styles += 'table.chMainTab tr th.notSel,td.notSel {font-weight:bold; font-size:13px; }';
        styles += 'div.chCard {width: 200px;}';
        styles += '.ChampionX .item { width: 30px; height: 30px; border: 1px solid black; display: inline-block; }';
        styles += '.ChampionX .title { position: absolute; font-size: 18px; width: 300px; text-align: center; font-weight: bold; }';
        styles += '.ChampionX .stats .name {  background: url(../img/champion_hall/champName_off.png);  width: 173px; height: 26px; position: absolute; top: 0px; left: 0px; }';
        styles += '.ChampionX .stats .name:hover {  background: url(../img/champion_hall/champName_over.png);}';
        styles += '.ChampionX .item_section { float: left;  color: #3f2300; background-color: #E7E3D6; border: 1px solid #A4753A; padding: 9px; width: 220px; font-weight: bold;  line-height: 130%; position: relative;}';
        styles += '.ChampionX .champItemHover { margin: -4px; }';
        styles += '.ChampionX .champItemHover .item_section { margin: 4px; }';
        styles += '.ChampionX .item_title .icon {  background: transparent url("../img/throne/modal/equip.png") top right no-repeat; background-size: 100% 100%; display: inline-block; height: 20px; width: 20px; top: 12px;  right: 12px;  position: absolute; }';
        styles += '.ChampionX .item_title { font-size: 11px; display: table-cell; height: 10px; vertical-align: middle; padding-right: 30px; }';
        styles += '.ChampionX .item_titleTT { font-size: 14px; display: table-cell; height: 28px; vertical-align: middle; padding-right: 30px; }';
        styles += '.ChampionX .stats_item_hover { color: #94652A; }';
        styles += '.ChampionX .champ_item_hover { width: 70px; height: 70px; float: left; margin-right: 10px;}';
        styles += '.ChampionX .champ_item_hoverTT { width: 70px; height: 70px; float: left; margin-right: 10px;}';
        styles += '.ChampionX .item_section .divider { border-bottom: 2px solid #A4753A; margin: 10px 0px 10px 0px;}';
        styles += '.ChampionX .item_section .effectsTT { margin: 3px 0; padding: 0; list-style: none; }';
        styles += '.ChampionX .item_section .effectsTT .effect { padding: 3px 0 0 5px; font-weight: bold; font-size: 14px; }';
        styles += '.ChampionX .item_section .effectsTT .effect.statChamp { color: #3F2300; }';
        styles += '.ChampionX .item_section .effectsTT .effect.statTroop { color: #1751A5; }';
        styles += '.ChampionX .item_section .effectsTT .effect.statChamp.disabled { color: #B9A48B; }';
        styles += '.ChampionX .item_section .effectsTT .effect.statTroop.disabled { color: #A5B1E5; }';

        styles += '.ChampionX .item_section .effects { margin: 3px 0; padding: 0; list-style: none; }';
        styles += '.ChampionX .item_section .effects .effect { padding: 3px 0 0 5px; font-weight: bold; font-size: 14px; }';
        styles += '.ChampionX .item_section .effects .effect.statChamp { color: #3F2300; }';
        styles += '.ChampionX .item_section .effects .effect.statTroop { color: #1751A5; }';
        styles += '.ChampionX .item_section .effects .effect.statChamp.disabled { color: #B9A48B; }';
        styles += '.ChampionX .item_section .effects .effect.statTroop.disabled { color: #A5B1E5; }';

        styles += 'div.chRule {border:2px inset #c0c0c0; margin-right:10px; margin-left:10px; margin-bottom:2px; padding-left:5px; padding-bottom:5px}';
        styles += 'div.chRuleCreate {margin-right:10px; padding-right: 5px; margin-bottom:2px; padding-bottom:5px}';
        styles += 'div.chRule { background-color: #eeeeee; }';
        styles += 'div.blueBorder { border: 2px solid blue; }';
        styles += 'div.blueBorder2 { border: 10px solid blue; }';
        styles += 'div.yellowBorder { outline: 2px solid yellow; outline-offset:0px; }';
        styles += 'div.yellowBorder2 { outline: 10px solid yellow; outline-offset:0px; }';
        styles += '#trhammer { background-image: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/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.trhammer { background-image: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/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.trbroken { background-image: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/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.trsuccess { 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.trup { display=inline;  background-image: url('+ up_img +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.trup:hover { display=inline;  background-image: url('+ up_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.trremove { display=inline;  background-image: url('+ remove_img +'); background-repeat: no-repeat; background-color: transparent;  width: 50px; height: 50px; }';
        styles += 'div.trremove:hover { display=inline;  background-image: url('+ remove_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 50px; height: 50px; }';
        styles += 'div.trdown { display=inline;  background-image: url('+ down_img +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.trdown:hover { display=inline;  background-image: url('+ down_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.trgbtn { display=inline;  background-image: url('+ gbtn_img +'); background-repeat: no-repeat; background-color: transparent;  width: 32px; height: 32px; margin: 0px; }';
        styles += 'ul#MM_throneStatList li { float: left; width: 22px; height: 22px; text-align: center; color: white; }';
        styles += 'ul#MM_throneStatList li.active { background: transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/modal/set_active.png") top left no-repeat; }';
        styles += 'ul#MM_throneStatList li.selected { background: transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/modal/set_selected.png") top left no-repeat; }';
        styles += 'ul#MM_throneStatList li.locked { background: transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/modal/set_locked.png") top left no-repeat; text-indent: -999px; }';
        styles += 'ul#MM_throneStatList li.buy { background: transparent url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/modal/set_buy.png") top left no-repeat; text-indent: -999px; }';
        styles += '#trQueue th { text-align: center; }';
        styles += 'a.loadGPreset { border-radius:5px; border-style: solid; border-width: 3px; }';
        styles += '#chhammer { background-image: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/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.chhammer { background-image: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/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.chbroken { background-image: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/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.chsuccess { 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.chup { display=inline;  background-image: url('+ up_img +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.chup:hover { display=inline;  background-image: url('+ up_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.chremove { display=inline;  background-image: url('+ remove_img +'); background-repeat: no-repeat; background-color: transparent;  width: 50px; height: 50px; }';
        styles += 'div.chremove:hover { display=inline;  background-image: url('+ remove_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 50px; height: 50px; }';
        styles += 'div.chdown { display=inline;  background-image: url('+ down_img +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.chdown:hover { display=inline;  background-image: url('+ down_glow +'); background-repeat: no-repeat; background-color: transparent;  width: 28px; height: 24px; }';
        styles += 'div.chgbtn { display=inline;  background-image: url('+ gbtn_img +'); background-repeat: no-repeat; background-color: transparent;  width: 32px; height: 32px; margin: 0px; }';
        styles += '#chQueue th { text-align: center; }';
        styles += 'a.loadChPreset { border-radius:5px; border-style: solid; border-width: 3px; }';
        styles += 'div.indent25 {padding-left:25px}';
        styles += 'li.guardbutton { border: 4px inset Peru; display: inline; float: left; width: 31px; height: 33px; text-align: center; color: white; }';
        styles += 'li.guardbutton.active { border: 4px solid blue;}';
        styles += 'li.guardbutton:hover div.tt { visibility: visible;}';
        styles += 'li.guardbutton div.tt { visibility: hidden; border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;';
        styles += 'box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1);';
        styles += 'font-family: Calibri, Tahoma, Geneva, sans-serif; font-weight: normal;';
        styles += 'position: relative; left: -30px; top: 50px;';
        styles += 'margin-left: 0; width: 200px; background-color: white; color: black;';
        styles += 'background: #FFFFAA; border: 1px solid #FFAD33; padding: 0.8em 1em;}';
        styles += '#preset_tt {margin-left: -999em; position: absolute;}';
        styles += '#preset_tt.showit { border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;';
        styles += '#preset_ch {margin-left: -999em; position: absolute;}';
        styles += '#preset_ch.showit { border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;';
        styles += 'box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1);';
        styles += 'font-family: Calibri, Tahoma, Geneva, sans-serif; font-weight: normal;';
        styles += 'position: absolute; left: 400px; top: 100px; z-index: 99;';
        styles += 'margin-left: 0; width: 200px; background-color: white; color: black;';
        styles += 'background: #FFFFAA; border: 1px solid #FFAD33; padding: 0.8em 1em;}';
        styles += '#jewelCracked {height: 50px; background: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/jewel_general_buff_cracked.jpg") scroll no-repeat center bottom;}';
        styles += '#jewelFlawed {height: 50px; background: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/jewel_general_buff_flawed.jpg") scroll no-repeat center bottom;}';
        styles += '#jewelCloudy {height: 50px; background: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/jewel_general_buff_cloudy.jpg") scroll no-repeat center bottom;}';
        styles += '#jewelSubdued {height: 50px; background: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/jewel_general_buff_subdued.jpg") scroll no-repeat center bottom;}';
        styles += '#jewelBright {height: 50px; background: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/throne/icons/70/jewel_general_buff_bright.jpg") scroll no-repeat center bottom;}';


    window.name = 'ORG';

    if (TRupgradeData.trWinPos==null ||  TRupgradeData.trWinPos.x==null || TRupgradeData.trWinPos.x=='' || isNaN(TRupgradeData.trWinPos.x)){
        var c = getClientCoords (document.getElementById('main_engagement_tabs'));
        TRupgradeData.trWinPos.x = 100;
        TRupgradeData.trWinPos.y = 100;
        TRsaveUpgradeData();
    }

    var newCSS = GM_getResourceText ("jqcss");

    GM_addStyle (newCSS);
    GM_addStyle (styles);

    // clear some styles
    var styles2 = ".orgDiag .ui-widget-content { font-size: 1.0em; background: none; border: none;}";
    styles2 += ".orgDiag.ui-widget-content { font-size: 0.95em; background: none; border: none;}";
//    styles2 += ".orgDiag .ui-tabs .ui-tabs-nav li a { font-weight: bold; font-family: georgia,arial,sans-serif; color: white; font-size: 1.0em; background: url('https://rycamelot1-a.akamaihd.net/fb/e2/src/img/tab_unselected.png') no-repeat scroll 0% 0% transparent;}";
//    styles2 += ".orgDiag .ui-tabs .ui-tabs-nav li.ui-tabs-active a {   background: url('https://rycamelot1-a.akamaihd.net/fb/e2/src/img/tab_selected.png') no-repeat scroll 0% 0% transparent;}";
    styles2 += ".orgDiag .ui-tabs .ui-tabs-nav li a { font-weight: bold; font-family: georgia,arial,sans-serif; color: white; font-size: 1.0em; background: url('" + tabColors[GeneralOptions.tabColorOptions] +"') no-repeat scroll 0% 0% transparent;}";
    styles2 += ".orgDiag .ui-tabs .ui-tabs-nav li.listCH a { font-weight: bold; font-family: georgia,arial,sans-serif; color: white; font-size: 1.0em; background: url('" + tabColors[GeneralOptions.tabColorChamp] + "') no-repeat scroll 0% 0% transparent;}";
    styles2 += ".orgDiag .ui-tabs .ui-tabs-nav li.listTR a { font-weight: bold; font-family: georgia,arial,sans-serif; color: white; font-size: 1.0em; background: url('" + tabColors[GeneralOptions.tabColorThrone] + "') no-repeat scroll 0% 0% transparent;}";
    styles2 += ".orgDiag .ui-tabs .ui-tabs-nav li.ui-tabs-active a {   background: url('http://i.imgur.com/kBSabbl.png') no-repeat scroll 0% 0% transparent;}";
    styles2 += ".orgDiag .ui-widget-content a { color: white;}";
    styles2 += ".orgDiag a.buttonDown20 span { color: white;}";
    styles2 += ".orgDiag .ui-widget {font-size: 1.0em;}";
    styles2 += ".orgDiag.ui-dialog .ui-dialog-title {margin: 0px; width: 100%;}";
    styles2 += ".orgDiag .ui-widget-header {background: none; border: none;}";
    styles2 += ".orgDiag .ui-state-deafault {background-color: none; }";
    styles2 += ".orgDiag .ui-widget .ui-widget {font-size: 0.9em;}";
    styles2 += ".orgDiag .ui-dialog-titlebar {text-shadow: 0px 1px 0px white; line-height: 24px; text-align: center; color: #5C3317; font: bold 1.3em Georiga;}";
    styles2 += '.orgDiag.ui-dialog .ui-dialog-titlebar-close { background-position: 0px 0px; background-image: url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/close_icon.png"); background-repeat: no-repeat; height: 20px; width: 20px; }';
    styles2 += ".orgDiag.ui-dialog .ui-dialog-titlebar-close { width: 20px; height: 20px;}";
    styles2 += ".orgDiag .ui-resizable-s { background: rgba(0,0,255,0.3);}";
    styles2 += ".orgDiag .ui-tabs .ui-tabs-nav { position: relative; top: 10px; left: 15px;}";
    styles2 += "table.trTable tbody tr td { background: none;}";
    styles2 += "table.chTable tbody tr td { background: none;}";

    GM_addStyle(styles2);

    $("#mainbody").append(
            "<div id='org_dialog' class='orgPopup org_orgPopup'>"
            + '<TABLE class=trTab cellspacing=0 width=' + OrganizerWindowWidth + ' height=100%>'
            + '<tbody><TR><TD colspan=2><div width=100% height=100% valign=top class="orgPopMain org_orgPopMain" id="org_main"></div></td></tr>'
            + '<tr><td colspan=2><div id=org_footer></div></td>'
            + '</tr></tbody></table></div>');

    $("#org_dialog").css({
        "overflow-y": "hidden",
        "overflow-x": "hidden",
        "padding": '0px'
    });

    var orgPop = null;

    $("#org_dialog").dialog({
        title: OrganizerTitle,
        position: [ TRupgradeData.trWinPos.x, TRupgradeData.trWinPos.y],
        draggable: true,
        height: "auto",
        maxHeight: 2000,
        minHeight: 300,
        width: "auto",
        resizable: false,
        autoOpen: GeneralOptions.WinIsOpen,
        dragStop: function( event, ui ) {
            TRupgradeData.trWinPos.x = ui.position.left;
            TRupgradeData.trWinPos.y = ui.position.top;
            TRsaveUpgradeData();
        },
        close: function( event, ui ) {
            GeneralOptions.WinIsOpen = false;
            saveGeneralOptions();
        },
        open: function( event, ui ) {
            $("#org_dialog").parent().css('z-index', 1111111 );
            if (orgPop) orgPop.focusMe();
        }
    });
    
    $("#org_dialog").css('max-height', '2000px');
    $("#org_dialog").parent().attr( {id: 'org_top', padding: '0px'});
    mainPop = $("#org_top")[0];
    $("div#tr_bar").css( {background: 'none', border: 'none'} );
    $("#org_top").addClass('orgDiag');

    var mainDiv = $("#org_top")[0];

    orgPop = new orgPopup('org');

    // block the copy/paste stuff added by sharethis
    var a = document.getElementsByTagName("body")[0];
    a.oncopy = function () { return true;}

    setCities();

    CM.cheatDetector.detect = foo;

    var OrganizerMainMenu = '<div>';
    OrganizerMainMenu += '<ul>';
    OrganizerMainMenu += '<li class="listTR"><a href="#tabs-upgradeTR" title="Throne Upgrade">Upgrade</a></li>';
    OrganizerMainMenu += '<li class="listTR"><a href="#tabs-salvageTR" title="Throne Salvage">Salvage</a></li>';
    if (GeneralOptions.showTabRepairTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-repairTR" title="Throne Repair">Repair</a></li>';
    OrganizerMainMenu += '<li class="listTR"><a href="#tabs-organizeTR" title="Throne Organizer">Organize</a></li>';
    if (GeneralOptions.showTabEnhanceStatsTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-enhancestatsTR" title="Throne Enhance Stats">Enh Stats</a></li>';
    if (GeneralOptions.showTabUpgradeStatsTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-upgradestatsTR" title="Throne Upgrade Stats">Upg Stats</a></li>';
    if (GeneralOptions.showTabPresetsTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-presetsTR" title="Throne Presets">Presets</a></li>';
    if (GeneralOptions.showTabCompareTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-compareTR" title="Throne Compare">Compare</a></li>';
    if (GeneralOptions.showTabPreviewTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-previewTR" title="Throne Preview">Preview</a></li>';
    if (GeneralOptions.showTabUniquesTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-uniqueTR" title="Throne Uniques">Uniques</a></li>';
    if (GeneralOptions.showTabCapsTR) OrganizerMainMenu += '<li class="listTR"><a href="#tabs-caps" title="Throne Caps">Caps</a></li>';
    OrganizerMainMenu += '<li class="listCH"><a href="#tabs-upgradeCH" title="Champ Upgrade">Upgrade</a></li>';
    OrganizerMainMenu += '<li class="listCH"><a href="#tabs-salvageCH" title="Champ Salvage">Salvage</a></li>';
    if (GeneralOptions.showTabRepairCH) OrganizerMainMenu += '<li class="listCH"><a href="#tabs-repairCH" title="Champ Repair">Repair</a></li>';
    OrganizerMainMenu += '<li class="listCH"><a href="#tabs-organizeCH" title="Champ Organizer">Organize</a></li>';
    if (GeneralOptions.showTabEnhanceStatsCH) OrganizerMainMenu += '<li class="listCH"><a href="#tabs-enhancestatsCH" title="Champ Enhance Stats">Enh Stats</a></li>';
    if (GeneralOptions.showTabUpgradeStatsCH) OrganizerMainMenu += '<li class="listCH"><a href="#tabs-upgradestatsCH" title="Champ Upgrade Stats">Upg Stats</a></li>';
    if (GeneralOptions.showTabPresetsCH) OrganizerMainMenu += '<li class="listCH"><a href="#tabs-presetsCH" title="Champ Presets">Presets</a></li>';
    if (GeneralOptions.showTabPreviewCH) OrganizerMainMenu += '<li class="listCH"><a href="#tabs-previewCH" title="Champ Preview">Preview</a></li>';
    if (GeneralOptions.showTabLog) OrganizerMainMenu += '<li><a href="#tabs-log" title="BOT Log">Log</a></li>';
    OrganizerMainMenu += '<li><a href="#tabs-options" title="BOT Options">Options</a></li>';
    if (GeneralOptions.showTabJewelsTR) OrganizerMainMenu += '<li><a href="#tabs-jewels" title="Jewel Organizer">Jewels</a></li>';
    if (GeneralOptions.showTabNews) OrganizerMainMenu += '<li><a href="#tabs-news" title="BOT News">News</a></li>';
    if (GeneralOptions.showTabLinks) OrganizerMainMenu += '<li><a href="#tabs-links" title="BOT Links">Links</a></li>';
    if (GeneralOptions.showTabTutorials) OrganizerMainMenu += '<li><a href="#tabs-tutorials" title="BOT Tutorials">Tutorials</a></li>';
    OrganizerMainMenu += '</ul>';
    OrganizerMainMenu += '<div id="tabs-upgradeTR">  UpgradeTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-salvageTR">  SalvageTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-repairTR" style="display: ' + (GeneralOptions.showTabRepairTR ? "block" : "none") + '">  RepairTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-organizeTR">  OrganizeTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-enhancestatsTR" style="display: ' + (GeneralOptions.showTabEnhanceStatsTR ? "block" : "none") + '">  EnhancestatsTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-upgradestatsTR" style="display: ' + (GeneralOptions.showTabUpgradeStatsTR ? "block" : "none") + '">  UpgradestatsTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-presetsTR" style="display: ' + (GeneralOptions.showTabPresetsTR ? "block" : "none") + '">  PresetsTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-compareTR" style="display: ' + (GeneralOptions.showTabCompareTR ? "block" : "none") + '">  CompareTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-previewTR" style="display: ' + (GeneralOptions.showTabPreviewTR ? "block" : "none") + '">  PreviewTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-uniqueTR" style="display: ' + (GeneralOptions.showTabUniquesTR ? "block" : "none") + '">  UniquesTR tab    </div>';
    OrganizerMainMenu += '<div id="tabs-caps" style="display: ' + (GeneralOptions.showTabCapsTR ? "block" : "none") + '">  Caps tab    </div>';
    OrganizerMainMenu += '<div id="tabs-upgradeCH">  UpgradeCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-salvageCH">  SalvageCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-repairCH" style="display: ' + (GeneralOptions.showTabRepairCH ? "block" : "none") + '">  RepairCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-organizeCH">  OrganizeCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-enhancestatsCH" style="display: ' + (GeneralOptions.showTabEnhanceStatsCH ? "block" : "none") + '">  EnhancestatsCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-upgradestatsCH" style="display: ' + (GeneralOptions.showTabUpgradeStatsCH ? "block" : "none") + '">  UpgradestatsCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-presetsCH" style="display: ' + (GeneralOptions.showTabPresetsCH ? "block" : "none") + '">  PresetsCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-previewCH" style="display: ' + (GeneralOptions.showTabPreviewCH ? "block" : "none") + '">  PreviewCH tab    </div>';
    OrganizerMainMenu += '<div id="tabs-log" style="display: ' + (GeneralOptions.showTabLog ? "block" : "none") + '">  Log tab    </div>';
    OrganizerMainMenu += '<div id="tabs-options">  Options tab    </div>';
    OrganizerMainMenu += '<div id="tabs-jewels" style="display: ' + (GeneralOptions.showTabJewelsTR ? "block" : "none") + '">  Jewels tab    </div>';
    OrganizerMainMenu += '<div id="tabs-news" style="display: ' + (GeneralOptions.showTabNews ? "block" : "none") + '">  News tab    </div>';
    OrganizerMainMenu += '<div id="tabs-links" style="display: ' + (GeneralOptions.showTabLinks ? "block" : "none") + '">  Links tab    </div>';
    OrganizerMainMenu += '<div id="tabs-tutorials" style="display: ' + (GeneralOptions.showTabTutorials ? "block" : "none") + '">  Tutorials tab    </div>';
    OrganizerMainMenu += '</div>';
    
    $("#org_main").html(OrganizerMainMenu);

    $("#org_main").tabs({ 
        heightStyle: "content",
        active: TRupgradeData.activeTab,
        beforeActivate: function( event, ui ) {
            if (ui.oldPanel && ui.oldPanel[0]) {
                tab = findTab(ui.oldPanel[0]);
                if (tab) {
                    Tabs[tab].hide();
                }
            }
            if (ui.newPanel && ui.newPanel[0]) {
                var tab = findTab(ui.newPanel[0]);
                if (tab) Tabs[tab].show();  
            }
        }
    });

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

    Tabs.OrganizerOptions.init($("#tabs-options")[0]);
    Tabs.throneUpgrader.init($("#tabs-upgradeTR")[0]);
    Tabs.throneSalvage.init($("#tabs-salvageTR")[0]);
    Tabs.throneRepair.init($("#tabs-repairTR")[0]);
    if (GeneralOptions.compactView) {
        Tabs.throneOrganizerCompact.init($("#tabs-organizeTR")[0]);
    } else {
        Tabs.throneOrganizer.init($("#tabs-organizeTR")[0]);
    }
    Tabs.throneEnhanceStats.init($("#tabs-enhancestatsTR")[0]);
    Tabs.throneUpgradeStats.init($("#tabs-upgradestatsTR")[0]);
    Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
    Tabs.throneCompare.init($("#tabs-compareTR")[0]);
    Tabs.thronePreview.init($("#tabs-previewTR")[0]);
    Tabs.throneUnique.init($("#tabs-uniqueTR")[0]);
    Tabs.champUpgrader.init($("#tabs-upgradeCH")[0]);
    Tabs.champSalvage.init($("#tabs-salvageCH")[0]);
    if (GeneralOptions.compactView) {
        Tabs.champOrganizerCompact.init($("#tabs-organizeCH")[0]);
    } else {
        Tabs.champOrganizer.init($("#tabs-organizeCH")[0]);
    }
    Tabs.champRepair.init($("#tabs-repairCH")[0]);
    Tabs.champEnhanceStats.init($("#tabs-enhancestatsCH")[0]);
    Tabs.champUpgradeStats.init($("#tabs-upgradestatsCH")[0]);
    Tabs.champPresets.init($("#tabs-presetsCH")[0]);
    Tabs.champPreview.init($("#tabs-previewCH")[0]);
    Tabs.ActionLog.init($("#tabs-log")[0]);
    Tabs.jewelOrganizer.init($("#tabs-jewels")[0]);
    Tabs.Caps.init($("#tabs-caps")[0]);
    Tabs.News.init($("#tabs-news")[0]);
    Tabs.Links.init($("#tabs-links")[0]);
    Tabs.Tutorials.init($("#tabs-tutorials")[0]);
    
    $( "#org_main" ).tabs( "refresh" ); 

    AddMainOrganizerTabLink('trtab', OrganizerButtonLabel, trHideShow, trMainTab);

    TRattachTab();

    alterChampHall();

    // create a preset list on the main display.  Wait 2 seconds for the chat-on-right to fire first.
    if (GeneralOptions.presetWidget) setTimeout(buildPresetWidget,2000);

    // set the color on the tab button
    setUpgradeColor();

    TROrganizerDisplayTimer = setInterval(TRupdateTimerDisp, 1000);

    CHOrganizerDisplayTimer = setInterval(CHupdateTimerDisp, 1000);

    ReplaceToolTips();
}

function GenerateChampPresetEffectsString( presetObject, htmlEffects ) {

    var ChampStats = [];
    var TroopStats = [];

    for (var eff in unsafeWindow.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]);

    while (items.length > 0) {
        var champ_item = unsafeWindow.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 = unsafeWindow.cm.ChampionManager.getEffect(effectLine, champ_item.level);
            if (id >= 201 && id <= 209) {
                ChampStats[id] += effect.amount;
            } 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 = unsafeWindow.g_js_strings.effects["name_"+ stat];
        if (ChampStats[stat] && ChampStats[stat] != 0) {
            if (htmlEffects) {
                J.push("<div>&nbsp;&nbsp;" + effectName + " " + ChampStats[stat] + "</div>");
            } else {
                J.push("&nbsp;&nbsp;" + effectName + " " + ChampStats[stat]);
            }
        }
    }
    if (htmlEffects) {
        J.push("<div><b><i>TROOP STATS</i></b></div>");
    } else {
        J.push("TROOP STATS");
    }
    for (stat in TroopStats) {
        var effectName = unsafeWindow.cm.thronestats.effects[stat][1];
        if (TroopStats[stat] && TroopStats[stat] != 0) {
            if (htmlEffects) {
                J.push("<div>&nbsp;&nbsp;" + effectName + " " + TroopStats[stat] + "</div>");
            } else {
                J.push("&nbsp;&nbsp;" + effectName + " " + TroopStats[stat]);
            }
        }
    }
    if (htmlEffects) {
        return J.join("");
    } else {
        return J.join("||");
    }

}

function GenerateThronePresetEffectsString( presetObject, htmlEffects ) {
    
    var J = new Array();

    var Effects = [];
    for (var effect in unsafeWindow.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 = unsafeWindow.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 = unsafeWindow.cm.thronestats.tiers[id][tier];
            while (!p && (tier > 0)) { tier--; p = unsafeWindow.cm.thronestats.tiers[id][tier]; }
            if (!p) continue; // can't find stats for tier

            if (slotNumber == 6) {
                JewelQuality = throne_item["effects"]["slot" + slotNumber].quality;
                GrowthLimit = unsafeWindow.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) && unsafeWindow.cm.thronestats["effects"][effect]) {
            var effectName = unsafeWindow.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 ReplaceToolTips() {

    var TToldF = unsafeWindow.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>(" + TRpresetData.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") {
            unsafeWindow.showTooltip(J.join(""), L, E, K)
        } else {
            unsafeWindow.Tooltip.show(E, J.join(""), [10, 10], null)
        }
    }

    unsafeWindow.cm.ThroneView.boostsTooltip = ThroneToolTip;
}

function alterChampHall() {

    function addPostChamp() {
        var ChampDivs = document.getElementsByClassName('section1 ')[0];
        var ChampStats = ChampDivs.getElementsByTagName('div')[0];
        if (ChampStats.innerHTML == "Post Champ Stats") return;
        ChampStats.className = "buttonv2 box red";
        ChampStats.innerHTML = "Post Champ Stats";
        ChampStats.position = "relative";
        ChampStats.top = "80px";
        ChampStats.width = "100px";
        ChampStats.zIndex = 10000;
        ChampStats.onclick = function () {
            var ChampName = document.getElementsByClassName('name_text')[0].getElementsByTagName('b')[0].innerHTML;
            var ChampIndex = 0;
            for (var ci = 1; ci < OrganizerMaxChampions+1; ci++) {
                var thisChampion = unsafeWindow.seed.champion.champions[ci-1];
                if (thisChampion.name == ChampName) {
                    ChampIndex = ci;
                    break;
                }
            }
            postChampSlot(ChampIndex);
        };
    }
    
    function addMenus() {

        $(".shield").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".weapon").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".chestArmor").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".helmet").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".feet").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".cloak").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".ring1").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".ring2").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });
        $(".pendant").click(function () {
            CustomChampContextMenu($(this).attr('hover_id'), $(this).offset().top, $(this).offset().left, false, true);
        });

        //        ------------------------------------------------

        $(".champItem").click(function () {
            DoChampContextMenu($(this)[0].id, false, false);
        }); 
    }

    function addBorders() {

        Tabs.champPresets.paintTags();

        var dv = document.getElementById('chMight')

        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 = "chMight";
            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();

    }

    // save link to old function
    var oldOpen = CM.ChampionModalController.open;
    
    //override
    CM.ChampionModalController.open = function (j) {
        oldOpen(j);
        //addMenus();
        addBorders();
        addPostChamp();
    }
    
    // save link to old function
    var rfi = CM.ChampionModalView.renderFilteredItems;
    // override
    CM.ChampionModalView.renderFilteredItems = function ()
    {
        // do normal stuff
        rfi();
        // new stuff
        addMenus();
        addBorders();
    }

    var rdr = CM.ChampionModalView.render;

    CM.ChampionModalView.render = function (ab,aa) 
    {
        rdr(ab,aa);
        addMenus();
        addBorders();
        addPostChamp();
    }

    var oldUpgEnh = CM.ChampionModalView.renderUpgEnh;

    CM.ChampionModalView.renderUpgEnh = function (ag, aa) {

        oldUpgEnh(ag, aa);

        var NextClick = document.getElementById('upgEnhStatsTarget');

        if (GeneralOptions.compactView) { var t = Tabs.champOrganizerCompact; } else { var t = Tabs.champOrganizer; }

        t.panelId = ag;  //this is the champ item ID
        t.panelNextLevel = unsafeWindow.kocChampionItems[ag].level + 1;

        NextClick.removeEventListener("click", t.showNext);

        var Locked = document.getElementById('chLockedStatIcon');

        if (Locked != null) return;

        NextClick.addEventListener("click", t.showNext);

    }

};

var foo = function() {
};

function setUpgradeColor() {
    if (TRupgradeData.newUpgradeState == 0)
        $("#trtab>span").css('color', '#FFFF66');
    else if (TRupgradeData.newUpgradeState == 1)
        $("#trtab>span").css('color', 'cyan');
    else if (TRupgradeData.newUpgradeState == 2)
        $("#trtab>span").css('color', 'red');
}

var presetTimer = null;
var presetFailures = 0;

function processPresetClick(btn) {  //callback handler when a preset button is presed
    // if there is a timer still running, kill it
    clearTimeout(presetTimer);
    
    // don't do anything if already the right preset
    if (btn == Seed.throne.activeSlot) {
        // redarw everything
        setPresetWidget(btn);
        unsafeWindow.cm.ThroneView.renderThrone();
        unsafeWindow.cm.ThroneView.renderStats();
        if (GeneralOptions.compactView) {
            Tabs.throneOrganizerCompact.show();
        } else {
            Tabs.throneOrganizer.show();
        }
        //return;
    }

    // send message
    unsafeWindow.AjaxCall.gPostRequest(
            "ajax/_dispatch53.php",
            {
                ctrl: "throneRoom\\ThroneRoomServiceAjax",
                action: "setPreset",
                presetId: btn
            },
            function (v) {
                if (v.ok === true) {
                    presetFailures = 0;
                    // success
                    var H = Seed.throne.slotEquip[btn];
                    Seed.throne.activeSlot = btn;

                    // set the right items as equiped
                    $.each(unsafeWindow.kocThroneItems, function (I, J) {
                        C = $.inArray(J.id, H) > -1;
                        if (C) {
                            J.isEquipped = true;
                        } else {
                            J.isEquipped = false;
                        }
                    });

                    // update the buttons
                    setPresetWidget(btn);
                    unsafeWindow.cm.ThroneView.renderThrone();
                    unsafeWindow.cm.ThroneView.renderStats();

                    // redraw the organizer tab
                    if (GeneralOptions.compactView) {
                        Tabs.throneOrganizerCompact.show();
                    } else {
                        Tabs.throneOrganizer.show();
                    }
                }
                else {
                    presetFailures++;
                    logit("Preset change failed. Error code: " + v.error_code);

                    // try again in 2 seconds
                    if (presetFailures <= 10) {
                        presetTimer = setTimeout(function () { processPresetClick(btn) }, 2000);
                    }
                    else {
                        // after 10 failures, give up
                        presetFailures = 0;
                    }
                }
            }
    );
}

function processGuardianClick(type) {  //handler when a guardian button is presed
    // callback.  only called when successful
    var cb = function(h)
    {
        // set the outline and turn the background gray
        var btn = "li.guardbutton." + type;
        $("li.guardbutton").removeClass('active');
        $(btn).css('background-color', 'darkgray');
        $(btn).addClass('active');

        // after lockout time is complete, redraw the control
        var timeLeft = h.finishTime - unixTime();
        setTimeout( function () 
                {
            h.summonFinishCallback(type, unsafeWindow.cm.guardianSummonModel.getSummonGuardian());
            $(btn).css('background-color', 'white');
            drawGuardWidget(); 
                }, (timeLeft + 1.0)* 1000);
    };
    // change guardian
    unsafeWindow.cm.guardianSummonModel.summon(type, cb)
}

function setPresetWidget(slot) {  //update the preset list buttons
    var x = ($("#MM_throneStatList .selected, #throneStatList .selected"));
    x.removeClass('selected');
    x.addClass('active');
    x.bind("mouseenter", function (I) {
        unsafeWindow.cm.ThroneView.boostsTooltip(this, I, I.target.id)
    });
    x.bind("mouseleave", function (I) {
        unsafeWindow.removeTooltip()
    });

    var s = $("#MM_throneInventoryPreset" + slot + ", #throneInventoryPreset" + slot);     
    s.removeClass('active');
    s.addClass('selected')
    s.unbind("mouseenter").unbind("mouseleave");

    $("a.loadGPreset").css('border-color', 'transparent');
    $("#trPresetNum" + slot ).css('border-color', 'green');

    document.getElementById('TRPresetList').value = slot;
    if (GeneralOptions.compactView) {
        Tabs.throneOrganizerCompact.selectPreset(slot);
    } else {
        Tabs.throneOrganizer.selectPreset(slot);
    }
}

function buildPresetWidget() {  //create a preset list on the main display
    var E = [];
    var J = Seed.throne.activeSlot;
    var F = Seed.throne.slotNum;

    for (var G = 0; G < OrganizerPresetSlots; ++G) {
        var H = G + 1;
        var I = $("<li/>");
        if (H === J) {
            I.attr("id", "MM_throneInventoryPreset" + H);
            I.addClass("selected");
            I.html(H);
            I.bind("click", {
                idx: G
            }, function (K) {
                var L = K.data.idx + 1;
                processPresetClick(L);
            });

        } else {
            if (H === (F + 1)) {
                I.attr("id", "MM_throneInventoryPreset" + H);
                I.addClass("buy");
                I.bind("click", function () {
                    unsafeWindow.cm.ContextualMenuThrone.renderMenu(this, null);
                })
            } else {
                if (H <= F) {
                    I.attr("id", "MM_throneInventoryPreset" + H);
                    I.addClass("active");
                    I.html(H);
                    I.bind("click", {
                        idx: G
                    }, function (K) {
                        var L = K.data.idx + 1;
                        processPresetClick(L);
                    });
                    I.bind("mouseenter", function (K) {
                        unsafeWindow.cm.ThroneView.boostsTooltip(this, K, K.target.id)
                    });
                    I.bind("mouseleave", function (K) {
                        unsafeWindow.removeTooltip()
                    })
                } else {
                    I.attr("id", "MM_throneInventoryPreset" + H);
                    I.addClass("locked");
                }
            }
        }
        E.push(I)
    }

    var C = $("<ul/>", {
        id: "MM_throneStatList",
        addClass: "presetList",
        style: "width: 178px; padding: 0px; margin: 0px; list-style: none; overflow: hiddden; float: left; border: 5px outset Peru; position: absolute; background: white;"
    });

    $.each(E, function (K, L) {
        C.append(L)
    });

    var aa = $("<div id='tr_presetBox'/>");
    aa.append(C);
    aa.css({
        "height": "55px",
        "width": "190px",
        "overflow": "visible",
        "position": "absolute",
        "z-index": "100000"
    })
    $("#kocContainer").append(aa);

//    //make a selector box for picking a champ
//    var C3 = $("<ul/>", {
//        id: "t_champList",
//        addClass: "presetList",
//        style: "padding: 0px; margin: 0px; list-style: none; overflow: visible; float: left; border: 4px outset Peru;"
//    });

    

    // make a selector box for picking a guardian
    var C2 = $("<ul/>", {
        id: "t_throneGuardList",
        addClass: "presetList",
        style: "padding: 0px; margin: 0px; list-style: none; overflow: visible; float: left; border: 4px outset Peru;"
    });

    var guardTypes = ["wood", "ore", "food", "stone"];
    var offsets = [" 77% 47% ", " 77% 73% ", " 77% 60% "," 77% 85% "]; // default to highest level.  

    for (g =0; g < 4; g++)
    {
        var type = guardTypes[g];

        var bb = $("<li/>").html('<div/>').css(
                {
                    'padding': '0px',
                    'background': 'url("https://rycamelot1-a.akamaihd.net/fb/e2/src/img/guardian_change_spritemap102.png") no-repeat scroll ' + offsets[g] + ' white',
                    'background-size': '350px'
                });
        bb.addClass("guardbutton").addClass(type);
        bb.append("<div class='tt'>" + unsafeWindow.g_js_strings.guardian["tooltipSummon_" + type] + "</div>");

        bb.bind("click", {
            gt: type
        }, function (K) {
            processGuardianClick(K.data.gt);
        });

        C2.append(bb);
    }

    aa = $("<div id='tr_guardBox'/>");
    aa.append(C2);
    aa.css({"height": "48px",
        "width": "164px",
        "position": "absolute",
        "overflow": "visible",
        "z-index": "100000"}
    );

    $("#kocContainer").append(aa);

    // move the chat box down
    var p = $("div.mod_comm").css('top');
    p = +p.split('px')[0] + 70;
    $("div.mod_comm").css('top', p + "px");

    var CHAT_BG_IMAGE = "data:image/gif;base64,R0lGODlhagHQAvcAAP%2F%2F5v%2F%2F1v%2F33v%2F31vf35v%2F3zvf33v%2F3xff31vf3zv%2Fv3u%2F33v%2Fv1v%2Fvzvfv1vfvzvfvxffvvffmzu%2Fmvebmvffere%2Feve%2Fete%2Fere%2Fepebevebeteberd7evd7ete%2FWpebWtd7Wtd7Wrd7WpdbWrd7Ord7OpdbOrdbOpdbFpc7FtdbFnM7FnMXFrc7FlM69rc69nM69lM69jMW9nMW9lMW9jL29nL29lM61jMW1nMW1lMW1jL21nMW1hL21lL21jMWtlLW1lL2tnL2tlL2thL2te7WthL2le72lc7WlhL2la7Wle7Wlc7Wla62le62lc7Wce7Wcc62chLWca6WcjK2cc6WchK2ca62cY6Wcc6Wca6WUhK2Ua6WUa6WUY5yUY5yMa5yMY5yMWpSMa5SMY5SMWoyMY5SEa5SEY4SEe4yEY4yEWoyEUpx7Uox7Wox7UoR7WoR7UoRzUntzY4RzSntzUntzSnNzSntrSmtrY3NrSmtjOhlrzmNaSjpjhBljxRljvRljtRlarRlapRlSnBlSlBlKjBlKhBlKexlCexlCcxlCa0o6CCE6Uhk6Yxk6WkopAEIpADopABAxQjEpEDEpCCEpMRkpMTohADEhACkhCDEZACkZACEZCCEZACEQABkQABkIABAIABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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dZ1jdYSiFd2RQGCZdcSKIETSNgT%2FwhYaT1YEyBYFDhYhEXYhD3YhIVYjI3YEkCBFOhYjyXYj%2BXYFMDYjgVZjz3ZkBXZEzDZjIXYlDVZFkBZj2UBmk0BmqVZkGWBnG1ZnkWBFViBjP1ZoR3ZkSXYFWCBo%2F3ZjhVapm1ap3Xam41apG3am12BGNiBGtiBHTjaGXCCJAABH2CEURgFYj2AwjICGmCBGVBbGqCBGYABuIWBGJjbuW1bu73ZGUhbFoABqbVbv50BwM1btw1cwSXcuIUBv01cxU3cGsharM3aHugBIpjcHtDayn1cv%2FUBzfWBHfgBzyUCz%2FVcrd2BySUCIzAC0C3d0j1dI%2FjcH1DdJYhd1k0C1P9VXda9XdpFXSOIXd693SXI3dPlXd6lXeEt3iW4Xd8V3t29XSdoXuSd3SQwXuXd3eMN3ue93uuN3SLY3uKNXtml3iUogvAN3u%2BV3uIVX%2FE93iIwgvU13fXdXvgVXid4Ai3ogi8Igy5Ygh8Agx9omT4IhU8YBVEQugDwq%2BbNAgRO4CyogirIAi3QAgZ%2B4C54YC1QYASm4ApG4Al%2BYAvuYA%2F%2BYAZWYAzuAhIm4REmYS%2FQAi8IAzEQgzB4YS%2BI4RKeYfv9Ahv%2BAjLIYR0mgxfu4TAggzIoAx8eYiJ%2B4RwO4iDeYSLO4R5mYiPeYR5u4ij%2B4SLugiLGXxrO4hKuXy3eYAxTzuAvpuAJXmAHDmEEroLmfYInaF42doIqUOM1ZmM4nmMGZmMGvuM7hmM3ZmA1xmM%2F5uM5juM1ll8n4F04jmArLoM1YIMyWGMYGIAf6NKxFQVRCAgAOw%3D%3D";
    $("div.mod_comm").css('background', 'url(' + CHAT_BG_IMAGE + ')');


    $("#tr_presetBox").draggable({stop: function( event, ui ) {
        presetPosition = $("#tr_presetBox").position();
        savePresetPosition();
    } });

    $("#tr_guardBox").draggable({stop: function( event, ui ) {
        guardPosition = $("#tr_guardBox").position();
        saveGuardPosition();
    } });

    readGuardPosition();
    if (!guardPosition)
        resetGuardWidget();
    else
    {
        $('#tr_guardBox').css({
            "left": guardPosition.left + "px",
            "top": guardPosition.top + "px"});
    }

    readPresetPosition();
    if (!presetPosition)
        resetPresetWidget();
    else
    {
        $('#tr_presetBox').css({
            "left": presetPosition.left + "px",
            "top": presetPosition.top + "px"});
    }

    drawGuardWidget();

    // hook into citysel_click();
    var cityselMod = new CalterUwFunc("citysel_click",[['cm.PrestigeCityView.render()','cm.PrestigeCityView.render();tr_cityChanged();']]);
    unsafeWindow.tr_cityChanged = drawGuardWidget;
    cityselMod.setEnable(true);

    $('#tr_presetBox').bind('mousedown', function(e) {
        if (e.which == 3) {
            resetPresetWidget();
            return false;
        }
    });

    $('#tr_guardBox').bind('mousedown', function(e) {
        if (e.which == 3) {
            resetGuardWidget();
            return false;
        }
    });
}

function drawGuardWidget() {
    // color the outline based on the current city

    $("li.guardbutton").removeClass("active");
    var cityId =  unsafeWindow.currentcityid;

    var y_offset = {
            wood: " 47% ",
            ore: " 72.5% ",
            food: " 59.5% ",
            stone: " 85% "
    };

    var x_offset = {
            plate:    20,
            junior:   134,
            teenager: 248,
            adult:    362,
            adult2:   476,
            adult3:   590
    };

    var x_by_level = {
            0: x_offset.plate,
            1: x_offset.junior,
            2: x_offset.junior,
            3: x_offset.junior,
            4: x_offset.teenager,
            5: x_offset.teenager,
            6: x_offset.adult,
            7: x_offset.adult,
            8: x_offset.adult,
            9: x_offset.adult,
            10: x_offset.adult2,
            11: x_offset.adult3,
            12: x_offset.adult3,
            13: x_offset.adult3,
            14: x_offset.adult3,
            15: x_offset.adult3
    };

    for (c in unsafeWindow.seed.guardian)
    {
        if (unsafeWindow.seed.guardian[c].cityId == cityId)
        {
            var type = unsafeWindow.seed.guardian[c].type;
            $("li.guardbutton." + type).addClass("active");

            for (t in y_offset)
            {
                var level = unsafeWindow.seed.guardian[c].cityGuardianLevels[t];
                level = level ? level : 0;
                var bg_offset =  x_by_level[level]/776*100 + "% " + y_offset[t];
                $("li.guardbutton." + t).css('background-position', bg_offset);
                if (level)
                    $("li.guardbutton." + t).css('background-color', 'white');
                else
                    $("li.guardbutton." + t).css('background-color', 'darkgray');
            }
        }
    }
}

function resetGuardWidget() {
    $("#tr_guardBox").position( {
        my: "right bottom",
        at: "right top-6",
        of: "div.mod_comm",
        collision: "fit"
    });
    delete guardPosition;
    guardPosition = null;
    saveGuardPosition();
}

function resetPresetWidget() {
    $("#tr_presetBox").position( {
        my: "left bottom",
        at: "left+3 top",
        of: "div.mod_comm",
        collision: "fit"
    });
    delete presetPosition;
    presetPosition = null;
    savePresetPosition();
}

function TRupdateTimerDisp () {

    var t = Tabs.throneUpgrader;
    var timeUntilDone = 0;

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

    if (timeUntilDone > 0)
    {
        $(document.querySelector('#trtimerdisp')).html("<span id='trhammer'></span>  " + rectime(timeUntilDone))
        .css('text-align', 'left')
        .css('width', '100px');
    }
    else
    {
        $(document.querySelector('#trtimerdisp')).html("<span id='trhammer'></span> Done").css('width', '100px');
    }
}

function CHupdateTimerDisp () {

    var t = Tabs.champUpgrader;
    var timeUntilDone = 0;

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

    if (timeUntilDone > 0)
    {
        $(document.querySelector('#chtimerdisp')).html("<span id='chhammer'></span>  " + rectime(timeUntilDone))
        .css('text-align', 'left')
        .css('width', '100px');
    }
    else
    {
        $(document.querySelector('#chtimerdisp')).html("<span id='chhammer'></span> Done").css('width', '100px');
    }
}

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;
}

var withAnim = null;
if (unsafeWindow.cm && unsafeWindow.cm.ThronePanelView) withAnim = unsafeWindow.cm.ThronePanelView.statusAnim;

function noAnim(result) {
    if (result == "success")
    {
        var item_name = $("#thronePanelName").html();
        var attempt_type = $("div.thronePanelContainer").find("li.selected").html();

        var msg = "Manual ";
        if (attempt_type)
            msg += attempt_type;
        else
            msg += "upgrade/enhance";

        msg += " successful.";

        if (item_name) msg += "  Item: " + item_name;

        if (GeneralOptions.useTokens) autoSelectMasters();

        SuccessLog(msg);

        //if (!OrganizerDisableSuccessCheck) {
            if (withAnim) withAnim(result);
        //} else {
        //    unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
        //}
    }
    $("div.thronePanelItemContainer").append("<div>" + result + "</div>");
    
}

function disableAnimation(disable) {
    if (disable) {
        // override the success failure animations
        CM.ThronePanelView.statusAnim = noAnim;
    } else {
        if (withAnim) CM.ThronePanelView.statusAnim = withAnim;
    }
}

function installHandlerFunctions() {

    var oldR = unsafeWindow.cm.ThroneView.renderInventory;
    var oldOpen = unsafeWindow.cm.ThroneView.openThrone;

	var oldAJ = unsafeWindow.cm.ThroneController.addJewel; //fixes the issue with adding/removing jewels and having it get stuck with the spinney
	var AJ2 = function (aj, ai) {
		oldAJ(aj, ai);
		unsafeWindow.cm.ThronePanelView.removeSpinny();
	}
	unsafeWindow.cm.ThroneController.addJewel = AJ2;
	
	var oldRJ = unsafeWindow.cm.ThroneController.removeJewel;
	var RJ2 = function (ak, ai) {
		oldRJ(ak, ai);
		unsafeWindow.cm.ThronePanelView.removeSpinny();
	}
	unsafeWindow.cm.ThroneController.removeJewel = RJ2;
	
	
    var ri2 = function(l) {
        oldR(l);
        $("ul#throneInventoryList > li > div").removeClass('blueBorder');
        $("ul#throneInventoryList > li > div").removeClass('yellowBorder');
        for (ii in TRqueueData.list) {
            var list_item = TRqueueData.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('blueBorder');     
                if (list_item.action == "enhance") $("div#throneInventoryItem" + id).addClass('yellowBorder');
            }

        }

        Tabs.thronePresets.paintTags();

        $('div[id^="throneInventoryItem"]').bind("contextmenu",function(e){
            e.preventDefault();
            var theId = $(this).attr("id").split("throneInventoryItem")[1];
            unsafeWindow.cm.ContextualMenuThrone.renderMenu( $(this), unsafeWindow.kocThroneItems[theId]);

            return false;
        }); 
    };

    var open2 = function (F) {
        oldOpen(F);

        $('div[id^="throneInventoryItem"]').bind("contextmenu", function (e) {
            e.preventDefault();
            var theId = $(this).attr("id").split("throneInventoryItem")[1];
            unsafeWindow.cm.ContextualMenuThrone.renderMenu($(this), unsafeWindow.kocThroneItems[theId]);

            return false;
        });

        if (GeneralOptions.draggableThroneItems) {
            // allow TR items to be dragged around
            $("#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.throneSalvage.updateTRTab();
        Tabs.throneUpgrader.updateTRTab();
        Tabs.throneRepair.updateTRTab();
        $("ul#throneInventoryList > li > div").removeClass('blueBorder');
        $("ul#throneInventoryList > li > div").removeClass('yellowBorder');
        //$("div#throneMainContainer div#heroContainer").css('left', '450px');

        for (ii in TRqueueData.list) {
            var list_item = TRqueueData.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('blueBorder');
                if (list_item.action == "enhance") $("div#throneInventoryItem" + id).addClass('yellowBorder');
            }

        }

        Tabs.thronePresets.paintTags();

        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');


        // update the other presets buttons when clicked
        $('ul#throneStatList li.active, ul#throneStatList li.selected').click(
                function () {
                    var s = $(this).attr('id').split('throneInventoryPreset')[1];
                    setPresetWidget(+s);
                });



    };

    unsafeWindow.cm.ThroneView.renderInventory = ri2;
    unsafeWindow.cm.ThroneView.openThrone = open2;

    // intercept the render menu call for our own uses

    // save the location of the old funtion
    var TRoldF = unsafeWindow.cm.ContextualMenuThrone.renderMenu;

    var TRrenderMenu2 = function (l, j) {
        // call the old one
        TRoldF(l, j);

        if (j != null) {

            Tabs.throneRepair.populateListBox();

            var idx = Seed.throne.activeSlot;

            var equipped_items = Seed.throne.slotEquip[idx];
            if (equipped_items.length > 0) {
                btn = document.createElement('a');
                $(btn).addClass("buttonv2 h20 blue")
                .html("Unequip All")
                .css('color', 'white')
                .bind("click", function () {
                    Tabs.thronePresets.unequipAllItems(idx);
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn);
            }

            if (GeneralOptions.showTabPreviewTR) {
                var btn4 = document.createElement('a');
                $(btn4).addClass("buttonv2 h20 red")
                .html("Load To Preview TR")
                .css('color', 'white')
                .bind("click", function () {
                    Tabs.thronePreview.loadCard(j.id);
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn4);
                
            }

            if (GeneralOptions.showTabPresetsTR) {

                var btn3 = document.createElement('a');
                $(btn3).addClass("buttonv2 h20 brown")
                .html("Tag All")
                .css('color', 'white')
                .bind("click", function () {
                    Tabs.thronePresets.addAllTagItems();
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn3);

                // create a button to "remove all tags"
                if (getObjectCollectionCount(TRpresetData.taggedItems) > 0) {
                    var btn4 = document.createElement('a');
                    $(btn4).addClass("buttonv2 h20 brown")
                    .html("Remove All Tags")
                    .css('color', 'white')
                    .bind("click", function () {
                        Tabs.thronePresets.clearAllTagItems();
                        $("#contextMenu").remove();
                    });
                    $("#contextMenu div.title").after(btn4);
                }

                // create a button to "tag" an item
                var btn3 = document.createElement('a');
                if (!TRpresetData.taggedItems[j.id]) {
                    $(btn3).addClass("buttonv2 h20 brown")
                    .html("Tag Item")
                    .css('color', 'white')
                    .bind("click", function () {
                        Tabs.thronePresets.addTagItem(j.id);
                        $("#contextMenu").remove();
                    });
                } else {
                    $(btn3).addClass("buttonv2 h20 brown")
                    .html("Remove Tag")
                    .css('color', 'white')
                    .bind("click", function () {
                        Tabs.thronePresets.removeTagItem(j.id);
                        $("#contextMenu").remove();
                    });
                }
                $("#contextMenu div.title").after(btn3);


            }

            // create a button to set the item to auto-enhance
            if (j.quality < OrganizerMaxTRQuality) {
                var btn2 = document.createElement('a');
                $(btn2).addClass("buttonv2 h20 green")
                .html("Auto Enhance")
                .css('color', 'yellow')
                .bind("click", function () {
                    Tabs.throneUpgrader.addEnhanceItem(j.id);
                    Tabs.throneUpgrader.repaint();
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn2);
            }

            // create a button to set the item to auto-update
            var btn = document.createElement('a');
            $(btn).addClass("buttonv2 h20 green")
            .html("Auto Upgrade")
            .css('color', 'blue')
            .bind("click", function () {
                Tabs.throneUpgrader.addUpgradeItem(j.id);
                Tabs.throneUpgrader.repaint();
                $("#contextMenu").remove();
            });
            $("#contextMenu div.title").after(btn);


            // create a button to set the item to auto-update/enhance
            if (GeneralOptions.multiUpgrade) {
                var btn = document.createElement('a');
                $(btn).addClass("buttonv2 h20 green")
                .html("Auto Upgrade/Enhance")
                .css('color', 'black')
                .bind("click", function () {
                    Tabs.throneUpgrader.addBothItem(j.id);
                    Tabs.throneUpgrader.repaint();
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn);
            }

            if (GeneralOptions.showTabPresetsTR) {
                var btn = document.createElement('a');
                $(btn).addClass("buttonv2 h20 red")
                .html("Save Preset #" + idx + " Tags")
                .css('color', 'white')
                .bind("click", function () {
                    Tabs.thronePresets.addPresetTags(idx);
                    Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn);

                var presetTagCount = getPresetTRTagCount(idx);
                if (presetTagCount != 0) {
                    btn = document.createElement('a');
                    $(btn).addClass("buttonv2 h20 red")
                    .html("Clear Preset #" + idx + " Tags")
                    .css('color', 'white')
                    .bind("click", function () {
                        Tabs.thronePresets.clearPresetTags(idx);
                        Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
                        $("#contextMenu").remove();
                    });
                    $("#contextMenu div.title").after(btn);
                    btn = document.createElement('a');
                    $(btn).addClass("buttonv2 h20 red")
                    .html("Equip Tag Preset #" + idx)
                    .css('color', 'white')
                    .bind("click", function () {
                        Tabs.thronePresets.equipPresetTags(idx);
                        $("#contextMenu").remove();
                    });
                    $("#contextMenu div.title").after(btn);
                }
            }

            if (j.isBroken) {
                var btn4 = document.createElement('a');
                $(btn4).addClass("buttonv2 h20 green")
                .html("Auto Repair")
                .css('color', 'white')
                .bind("click", function () {
                    Tabs.throneRepair.addQueue(j.id);
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn4);
            }

            if (isAnyTRBroke()) {
                var btn4 = document.createElement('a');
                $(btn4).addClass("buttonv2 h20 green")
                .html("Auto Repair All")
                .css('color', 'white')
                .bind("click", function () {
                    Tabs.throneRepair.addAllQueue();
                    $("#contextMenu").remove();
                });
                $("#contextMenu div.title").after(btn4);

            }

            // create a button to copy the stats
            btn = document.createElement('a');
            $(btn).addClass("buttonv2 h20 blue")
            .html("Copy Stats")
            .css('color', 'white')
            .bind("click", function () {
                var displayText = getThroneItemStats(j.id, "    ");
                if (displayText != "") window.prompt("Copy to clipboard: Ctrl+C", displayText);
                $("#contextMenu").remove();
            });
            $("#contextMenu div.title").after(btn);

            // create a button to post the stats
            btn = document.createElement('a');
            $(btn).addClass("buttonv2 h20 blue")
            .html("Post Stats to Chat")
            .css('color', 'white')
            .bind("click", function () {
                var displayText = getThroneItemStats(j.id, "||");
                if (displayText != "") sendChat(displayText);
                $("#contextMenu").remove();
            });
            $("#contextMenu div.title").after(btn);

            // create a button to post the stats
            btn = document.createElement('a');
            $(btn).addClass("buttonv2 h20 blue")
            .html("Export Excel")
            .css('color', 'white')
            .bind("click", function () {
                ExportThroneToExcel();
                $("#contextMenu").remove();
            });
            $("#contextMenu div.title").after(btn);

            $(".buttonv2.red").click(function () { $(".mediumModal").css('z-index', 120000); });

            if (!j.isBroken) {
                // no salvage on first x items
                if (GeneralOptions.TRsalvageSafety) {

                    var keys = unsafeWindow.Object.keys(unsafeWindow.kocThroneItems);
                    var v = "" + j.id;
                    if (keys.indexOf(v) < GeneralOptions.TRnumSafety && keys.indexOf(v) > -1) {
                        $("#contextMenu a:nth-last-child(2)").remove();
                    }

                }

                if (GeneralOptions.noMassSalvage) {
                    $("#contextMenu a").last().remove();
                }
            }
            if (!GeneralOptions.noForcedSalvage) {
                if (!j.isBroken) {
                    btn = document.createElement('a');
                    $(btn).addClass("buttonv2 h20 red")
                    .html("FORCED SALVAGE")
                    .css('color', 'white')
                    .bind("click", function () {
                        Tabs.throneSalvage.forceSalvage(j.id);
                        $("#contextMenu").remove();
                    });
                    $("#contextMenu a").last().after(btn);
                }
            }
        }

    };

    // hook up our new function
    unsafeWindow.cm.ContextualMenuThrone.renderMenu = TRrenderMenu2;

    // add some new functionality here ...
    var TRPanel = CM.ThronePanelView.renderPanel;

    var TRrenderPanel2 = function (v1, v2) {
        TRPanel(v1, v2);

        // save off this data ...
        if (GeneralOptions.compactView) {
            Tabs.throneOrganizerCompact.panelId = v2.id;
            Tabs.throneOrganizerCompact.panelType = v1;
            Tabs.throneOrganizerCompact.panelNextLevel = 2;
        } else {
            Tabs.throneOrganizer.panelId = v2.id;
            Tabs.throneOrganizer.panelType = v1;
            Tabs.throneOrganizer.panelNextLevel = 2;
        }


        var clearMasterTokens = function () {
            // remove options for tokens
            var removeItems =  [unsafeWindow.ksoItems[20012].name, // +3 master
                                unsafeWindow.ksoItems[20013].name, // +5 master
                                unsafeWindow.ksoItems[20014].name, // +7
                                unsafeWindow.ksoItems[20015].name, // +9
                                unsafeWindow.ksoItems[20016].name, // +10
                                unsafeWindow.ksoItems[20017].name, // +11
                                unsafeWindow.ksoItems[20018].name, // +12
                                unsafeWindow.ksoItems[20020].name, // +13
                                unsafeWindow.ksoItems[20021].name, // +14
                                unsafeWindow.ksoItems[20023].name, // +15
                                unsafeWindow.ksoItems[20024].name, // +16
                                unsafeWindow.ksoItems[20025].name, // +17
                                unsafeWindow.ksoItems[20026].name, // +18
                                unsafeWindow.ksoItems[20027].name, // +19
                                unsafeWindow.ksoItems[20028].name, // +20
                                unsafeWindow.ksoItems[20029].name, // +21
                                unsafeWindow.ksoItems[20030].name, // +22
                                unsafeWindow.ksoItems[20031].name // +23
                                ];

            $(document.querySelector("#buffDropDown")).children("option").each(function () {
                if ($.inArray($(this).text(), removeItems) > -1) $(this).remove();
            });
            $(document.querySelector("#thronePanelBuffIcon")).removeClass().addClass('icon').addClass('i0');
            $(document.querySelector("#thronePanelBuffPrice")).children("span.items").html('');
        }
        var clearOtherTokens = function () { 
            // remove options for tokens
            var removeItems =  [unsafeWindow.ksoItems[20006].name, // lucky token
                                unsafeWindow.ksoItems[20007].name, // common master
                                unsafeWindow.ksoItems[20008].name, // uncommon
                                unsafeWindow.ksoItems[20009].name, // rare
                                unsafeWindow.ksoItems[20010].name, // epic
                                unsafeWindow.ksoItems[20011].name, // wondrous
                                unsafeWindow.ksoItems[20019].name, // super lucky token
                                unsafeWindow.ksoItems[20022].name, // apprentice token
                                unsafeWindow.ksoItems[20101].name, //Fortune's Token +19
                                unsafeWindow.ksoItems[20102].name, //Opportunity's Token +19
                                unsafeWindow.ksoItems[20103].name, //Prospector's Token +19
                                unsafeWindow.ksoItems[20104].name, //Fortune's Token +20
                                unsafeWindow.ksoItems[20105].name, //Opportunity's Token +20
                                unsafeWindow.ksoItems[20106].name, //Prospector's Token +20
                                unsafeWindow.ksoItems[20107].name, //Fortune's Token +21
                                unsafeWindow.ksoItems[20108].name, //Opportunity's Token +21
                                unsafeWindow.ksoItems[20109].name, //Prospector's Token +21
                                unsafeWindow.ksoItems[20110].name, //Fortune's Token +22
                                unsafeWindow.ksoItems[20111].name, //Opportunity's Token +22
                                unsafeWindow.ksoItems[20112].name, //Prospector's Token +22
                                unsafeWindow.ksoItems[20113].name, //Fortune's Token +23
                                unsafeWindow.ksoItems[20114].name, //Opportunity's Token +23
                                unsafeWindow.ksoItems[20115].name //Prospector's Token +23
                                ];

            $(document.querySelector("#buffDropDown")).children("option").each(function () {
                if ($.inArray($(this).text(), removeItems) > -1) $(this).remove();
            });
            $(document.querySelector("#thronePanelBuffIcon")).removeClass().addClass('icon').addClass('i0');
            $(document.querySelector("#thronePanelBuffPrice")).children("span.items").html('');

        }

        var doUpdradeChecks = function () {
            if (GeneralOptions.useTokens) autoSelectMasters(); //v2.id is the throneItemID
            if (!GeneralOptions.useTokens && GeneralOptions.removeMastersTokens) clearMasterTokens();
            if (!GeneralOptions.useTokens && GeneralOptions.removeOtherTokens) clearOtherTokens();
            if (!GeneralOptions.useTokens && GeneralOptions.buffsOff) unselectToken();
            if (GeneralOptions.safetyOn) safetyCheck();
        }

        var doEnhanceChecks = function () {
            if (!GeneralOptions.useTokens && GeneralOptions.buffsOff) unselectToken();
            if (GeneralOptions.safetyOn) safetyCheck();
        }

        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 = TRrenderPanel2;

    // override the salvageItem function to allow upgrade to +1 first
    var salItemOrig = CM.ThroneController.salvageItem;    
    var salItemNew = function (item) {
        if ( TRsalvageData.upgradeManual )
        {
            if (item && item.quality <= TRsalvageData.upgradeFirstQual && item.level==0 )
            {
                var status = Tabs.throneSalvage.deleting;
                Tabs.throneSalvage.deleting = true;
                Tabs.throneUpgrader.doUpgrade(item.id,true);
                Tabs.throneSalvage.deleting = status;
            }  
        }
        salItemOrig(item);
    };

    CM.ThroneController.salvageItem = salItemNew;

    // watch the active slot so the TRO keeps up with changes
    //  This uses Object.watch() which is only defined on Gecko
    try {

        function updateThrone () {
            unsafeWindow.cm.ThroneView.renderThrone();
            unsafeWindow.cm.ThroneView.renderStats();
            if (GeneralOptions.compactView) {
                Tabs.throneOrganizerCompact.show();
            } else {
                Tabs.throneOrganizerCompact.show();
            }
        };

        // This function watchs the TR active slot.
        function slotWatcher(id, oldval, newval) {
            try {
                setPresetWidget(newval);
                setTimeout(updateThrone, 200);
            } catch (e) {
                logit("error in slot watcher" + e.toString());
            };
            return newval;
        };

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

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

                newval.multiWatch("activeSlot", slotWatcher);
            } catch (e) { logit("error in multiwatch handler: " + e.toString());}

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

var buffChanged = false;

var disableUpgradeButton = 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);
}

var checkAstoneLevel = function () {
    // check limit
    var stones = parseInt(Seed.resources["city" + unsafeWindow.currentcityid]["rec5"][0]);
    if (stones < GeneralOptions.safetyLimit || isNaN(stones) ) {
        disableUpgradeButton();
        return false;
    } else {
        return true;    
    }
}

var safetyCheck = function () {
    // remove the gem option
    var sel = document.getElementById("costDropDown");
    sel.remove(1);
    // see if we have enough a-stone
    if (checkAstoneLevel()) {
        $(document.querySelector("#thronePanelItemRequirementsContainer")).children("a.gemButtonv2").click(function () {
            // every time the button is pushed, check the levels
            checkAstoneLevel();
            safetyCheck();
        });
    }
}

function unselectToken() {

    // 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 onUnload (){

    TRupgradeData.activeTab = $( "#org_main" ).tabs( "option", "active"); 
    TRupgradeData.sortSelected = $("#trSortList").val();
    TRupgradeData.buffSelected = $("#trSortType").val();
    TRupgradeData.sortInactive = ($("#trSortInactive").attr('checked') == 'checked');

    if (!ResetAll) TRsaveUpgradeData();
}

function trMainTab (me){   // right-click on main button resets window
    if (me.button == 2){
        $( "#org_dialog" ).dialog( "option", "position",  
                {my: "left top",
            at: "left+15 bottom+5",
            of: "#main_engagement_tabs"});
    }
}

function TRattachTab() {

    unsafeWindow.hideShow     = trHideShow;
    unsafeWindow.execSalvage  = Tabs.throneSalvage.togglePower;
    unsafeWindow.execUpgrade = Tabs.throneUpgrader.togglePower;
    unsafeWindow.execRepair = Tabs.throneRepair.togglePower;
    if (GeneralOptions.compactView) {
        unsafeWindow.clickNextTR = Tabs.throneOrganizerCompact.showNext;
    } else {
        unsafeWindow.clickNextTR = Tabs.throneOrganizer.showNext;
    }
 
    var str = unsafeWindow.cm.FETemplates.Throne.mainThrone.replace(
            '<li id="throneStatTab" class="inactive"> #{stats} </li>',
    '<li id="throneStatTab" class="inactive"> #{stats} </li><li id="throneTest" class="inactive" onclick="hideShow()"> Controls </li><li id="trexecrepair" class="inactive" onclick="execRepair()">Repair</li><li id="trexecupgrade" class="inactive" onclick="execUpgrade()">Upgrade</li><li id="trexecsalvage" class="inactive" onclick="execSalvage()">Salvage</li><li id="trtimerdisp" class="inactive">Timer</li>');
    
    str = str.replace( '<div id="thronePanelContainer">', '<div id="thronePanelContainer" style="z-index: 101">');
    unsafeWindow.cm.FETemplates.Throne.mainThrone = str;
    
    unsafeWindow.cm.FETemplates.Throne.throneInfo = unsafeWindow.cm.FETemplates.Throne.throneInfo.replace (
            '<div id="throneInfoContainer">',
    '<div id="throneInfoContainer" style="z-index: 100;">');

    unsafeWindow.cm.FETemplates.Throne.mainThrone = unsafeWindow.cm.FETemplates.Throne.mainThrone.replace (
            '<div id="throneInfoContainer">',
    '<div id="throneInfoContainer" style="z-index: 100;">');

    unsafeWindow.cm.FETemplates.Throne.thronePanel = unsafeWindow.cm.FETemplates.Throne.thronePanel.replace(
            '<div class="thronePanelContainer">',
    '<div class="thronePanelContainer" style="z-index: 101;">');

//    unsafeWindow.cm.FETemplates.Throne.thronePanel = unsafeWindow.cm.FETemplates.Throne.thronePanel.replace(
//            '<div id="nextStatContainer" class="nextStat">',
//    '<div id="nextStatContainer" class="nextStat" onclick="clickNextTR()">');

    unsafeWindow.cm.FETemplates.Throne.mainThrone = unsafeWindow.cm.FETemplates.Throne.mainThrone.replace(
            '<ul id="throneStatDisplay"></ul>', '<div style="width: 70%; margin-left: auto; margin-right: auto;"><input type="button" value="Post to Chat" onclick="postTR()"></input></div><ul id="throneStatDisplay"></ul>');

    GM_addStyle( "div#throneMainContainer div#throneInfoContainer div.infoContainer div.statContainer div.stats > ul {height: 345px }");

    function postTR() { postThroneSlot(Seed.throne.activeSlot); }
    
    unsafeWindow.postTR = postTR;
}

function trHideShow () {
    if ($(document.querySelector("#org_dialog")).dialog("isOpen")){
        $(document.querySelector("#org_dialog")).dialog("close");
        GeneralOptions.WinIsOpen = false;
    } else {
        $(document.querySelector("#org_dialog")).dialog("open");
        GeneralOptions.WinIsOpen = true;
        // clear the color
        TRupgradeData.newUpgradeState = 0;
        setUpgradeColor();
    }
    TRsaveUpgradeData();
    saveGeneralOptions();
}

function autoSelectMasters() {
    var ThroneID = 0;
    if (GeneralOptions.compactView) {
        ThroneID = Tabs.throneOrganizerCompact.panelId;
    } else {
        ThroneID = Tabs.throneOrganizer.panelId;
    }
    var throne_item = unsafeWindow.kocThroneItems[ThroneID];
    nextMastersID = getNextAvailableMasters(throne_item);
    if (nextMastersID == 0) {
        unselectToken();
    } else {
        var selected_index = 0;
        $(document.querySelector("#buffDropDown")).children("option").each(function () {
            if ( $(this).text() == unsafeWindow.ksoItems[nextMastersID].name ) {
                selected_index = $(this).val();
                return false;
            }
        });
        $('#buffDropDown').val(selected_index).change();
        if (selected_index > 0) {
            $("#thronePanelBuffPrice span").text(unsafeWindow.ksoItems[nextMastersID].count + "/1");
            $("div.mastersTokenLevel").text(getMastersText(nextMastersID));
        }
    }
    if (GeneralOptions.safetyOn) {
        setTimeout(function() {
            safetyCheck();
        }, 2000);
    }
}

function getNextAvailableMasters(throneItem) {
    var curCode = 0;
    if (unsafeWindow.ksoItems[20031].count > 0 && throneItem.level <= 22) curCode = 20031; //23s
    if (unsafeWindow.ksoItems[20030].count > 0 && throneItem.level <= 21) curCode = 20030; //22s
    if (unsafeWindow.ksoItems[20029].count > 0 && throneItem.level <= 20) curCode = 20029; //21s
    if (unsafeWindow.ksoItems[20028].count > 0 && throneItem.level <= 19) curCode = 20028; //20s
    if (unsafeWindow.ksoItems[20027].count > 0 && throneItem.level <= 18) curCode = 20027; //19s
    if (unsafeWindow.ksoItems[20026].count > 0 && throneItem.level <= 17) curCode = 20026; //18s
    if (unsafeWindow.ksoItems[20025].count > 0 && throneItem.level <= 16) curCode = 20025; //17s
    if (unsafeWindow.ksoItems[20024].count > 0 && throneItem.level <= 15) curCode = 20024; //16s
    if (unsafeWindow.ksoItems[20023].count > 0 && throneItem.level <= 14) curCode = 20023; //15s
    if (unsafeWindow.ksoItems[20021].count > 0 && throneItem.level <= 13) curCode = 20021; //14s
    if (unsafeWindow.ksoItems[20020].count > 0 && throneItem.level <= 12) curCode = 20020; //13s
    if (unsafeWindow.ksoItems[20018].count > 0 && throneItem.level <= 11) curCode = 20018; //12s
    if (unsafeWindow.ksoItems[20017].count > 0 && throneItem.level <= 10) curCode = 20017; //11s
    if (unsafeWindow.ksoItems[20016].count > 0 && throneItem.level <= 9) curCode = 20016; //10s
    if (unsafeWindow.ksoItems[20015].count > 0 && throneItem.level <= 8) curCode = 20015; //9s
    if (unsafeWindow.ksoItems[20015].count > 0 && throneItem.level <= 7) curCode = 20015; //9s
    if (unsafeWindow.ksoItems[20014].count > 0 && throneItem.level <= 6) curCode = 20014; //7s
    if (unsafeWindow.ksoItems[20014].count > 0 && throneItem.level <= 5) curCode = 20014; //7s
    if (unsafeWindow.ksoItems[20013].count > 0 && throneItem.level <= 4) curCode = 20013; //5s
    if (unsafeWindow.ksoItems[20013].count > 0 && throneItem.level <= 3) curCode = 20013; //5s
    if (unsafeWindow.ksoItems[20012].count > 0 && throneItem.level <= 2) curCode = 20012; //3s
    if (unsafeWindow.ksoItems[20012].count > 0 && throneItem.level <= 1) curCode = 20012; //3s
    return curCode;
}

function getMastersText(ksoID) {
    switch(ksoID) {
        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 "";
    }
}

function sendChat (msg){  //Simple method, as if it were typed in thru DOM
    $(document.querySelector("#mod_comm_input")).val(msg);
    uW.Chat.sendChat ();
}

function AddMainOrganizerTabLink(tabID, buttonLabel, eventListener, mouseListener) {

    var a=document.createElement('a');
    a.className='button20';
    a.innerHTML='<span style="color: #ff6">'+ buttonLabel +'</span>';
    a.id = tabID;
    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='nowrap';
            gmTabs.style.width = '735px';
            gmTabs.lang = 'en_PT';
        }
        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 getClientCoords(e) {
    if (e==null)
        return {x:null, y:null, width:null, height:null};
        var x=0, y=0;
        ret = {x:0, y:0, width:e.clientWidth, height:e.clientHeight};
        while (e.offsetParent != null){
            ret.x += e.offsetLeft;
            ret.y += e.offsetTop;
            e = e.offsetParent;
        }
        return ret;
}

function 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 = unsafeWindow.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)
                unsafeWindow.update_seed(rslt.updateSeed);
            wasSuccess (rslt);
            return;
        }
        rslt.errorMsg = unsafeWindow.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);
        }
    }
}

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;
}

function logit (msg) {
    var now = new Date();
    GM_log (getServerId() +' @ '+ now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +': '+  msg);
}

function saveGeneralOptions () {
    setTimeout (function (){GM_setValue ('GenOptions_' + getServerId(), JSON2.stringify(GeneralOptions));}, 0);
}

function TRsaveUpgradeData() {
    var serverID = getServerId();
    setTimeout(function () { GM_setValue('UpgradeDataMM2_' + serverID, JSON2.stringify(TRupgradeData)); }, 0);
}

function TRsaveRepairData() {
    var serverID = getServerId();
    setTimeout(function () { GM_setValue('RepairDataMM2_' + serverID, JSON2.stringify(TRrepairData)); }, 0);
}

function TRsavePresetData () {
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('PresetDataMM2_'+serverID, JSON2.stringify(TRpresetData));}, 0);
}

function TRsaveQueueData () {
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('QData_'+serverID, JSON2.stringify(TRqueueData));}, 0);
}

function TRsaveSalvageData () {
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('SalvageDataMM2_'+serverID, JSON2.stringify(TRsalvageData));}, 0);
}

function TRsaveUpgradeStats() {
    var serverID = getServerId();
    setTimeout(function () { GM_setValue('UpgradeStatsTR_' + serverID, JSON2.stringify(TRupgradeStats)); }, 0);
}

function CHsaveUpgradeStats() {
    var serverID = getServerId();
    setTimeout(function () { GM_setValue('UpgradeStatsCH_' + serverID, JSON2.stringify(CHupgradeStats)); }, 0);
}

function CHsaveUpgradeData() {
    var serverID = getServerId();
    setTimeout(function () { GM_setValue('UpgradeDataCH2_' + serverID, JSON2.stringify(CHupgradeData)); }, 0);
}

function CHsaveRepairData() {
    var serverID = getServerId();
    setTimeout(function () { GM_setValue('RepairDataCH2_' + serverID, JSON2.stringify(CHrepairData)); }, 0);
}

function CHsavePresetData() {
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('PresetDataCH2_'+serverID, JSON2.stringify(CHpresetData));}, 0);
}

function CHsaveQueueData () {
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('CHQData_'+serverID, JSON2.stringify(CHqueueData));}, 0);
}

function CHsaveSalvageData () {
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('SalvageDataCH2_'+serverID, JSON2.stringify(CHsalvageData));}, 0);
}

function savePresetPosition () {
    var serverID = getServerId();
    setTimeout (function (){ GM_setValue ('PresetPosition_'+serverID, JSON2.stringify(presetPosition));}, 0);
}

function saveGuardPosition () {
    var serverID = getServerId();
    setTimeout (function (){ GM_setValue ('GuardPosition_'+serverID, JSON2.stringify(guardPosition));}, 0);
}

function readPresetPosition () {
    var serverID = getServerId();
    s = GM_getValue ('PresetPosition_'+serverID);
    if (s != null){
        presetPosition = JSON2.parse (s);
    }
}

function readGuardPosition () {
    var serverID = getServerId();
    s = GM_getValue ('GuardPosition_'+serverID);
    if (s != null){
        guardPosition = JSON2.parse (s);
    }
}

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

function readGeneralOptions () {
    s = GM_getValue ('GenOptions_' + getServerId());
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    GeneralOptions[k][kk] = opts[k][kk];
            else
                GeneralOptions[k] = opts[k];
        }
    }
}

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

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

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

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

function TRreadPresetData() {
    var serverID = getServerId();
    s = GM_getValue ('PresetDataMM2_'+serverID);
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    TRpresetData[k][kk] = opts[k][kk];
            else
                TRpresetData[k] = opts[k];
        }
    }
    for (var i in TRpresetData.previewThrone) {
        var throne_item = unsafeWindow.kocThroneItems[i];
        if (throne_item == null || !throne_item) delete TRpresetData.previewThrone[i];
    }
}

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

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

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

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

    // recreate the objects w/ functions
    for (k in TRsalvageData.ruleSet)
    {
        var r = TRsalvageData.ruleSet[k];
        var rule = new TRRule(r.type, r.faction, r.conditions);
        for (j in rule.conditions)
        {
            rule.conditions[j].TRcheckCondition = TRcheckCondition;
        }
        TRsalvageData.ruleSet[k] = rule;
    }
}

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

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


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

    // recreate the objects w/ functions
    for (k in CHsalvageData.ruleSet)
    {
        var r = CHsalvageData.ruleSet[k];
        var rule = new CHRule(r.type, r.faction, r.conditions);
        for (j in rule.conditions)
        {
            rule.conditions[j].CHcheckCondition = CHcheckCondition;
        }
        CHsalvageData.ruleSet[k] = rule;
    }
}

function CHloadSalvageData (domainId) {

    s = GM_getValue ('SalvageDataCH2_'+ domainId);

    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])
                    CHsalvageData[k][kk] = opts[k][kk];
            else
                CHsalvageData[k] = opts[k];
        }
    }

    // recreate the objects w/ functions
    for (k in CHsalvageData.ruleSet)
    {
        var r = CHsalvageData.ruleSet[k];
        var rule = new CHRule(r.type, r.faction, r.conditions);
        for (j in rule.conditions)
        {
            rule.conditions[j].CHcheckCondition = CHcheckCondition;
        }
        CHsalvageData.ruleSet[k] = rule;
    }

    // turn off
    CHsalvageData.salvageActive = false;
    clearInterval(Tabs.champSalvage.sTimer);
    clearInterval(Tabs.champSalvage.delTimer);
    Tabs.champSalvage.deleting = false;
    CHsaveSalvageData();
    alert('Salvage settings loaded from domain ' + domainId);
    Tabs.champSalvage.init(Tabs.champSalvage.myDiv);
}

function TRloadSalvageData (domainId) {

    s = GM_getValue ('SalvageDataMM2_'+ domainId);

    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])
                    TRsalvageData[k][kk] = opts[k][kk];
            else
                TRsalvageData[k] = opts[k];
        }
    }

    // recreate the objects w/ functions
    for (k in TRsalvageData.ruleSet)
    {
        var r = TRsalvageData.ruleSet[k];
        var rule = new TRRule(r.type, r.faction, r.conditions);
        for (j in rule.conditions)
        {
            rule.conditions[j].TRcheckCondition = TRcheckCondition;
        }
        TRsalvageData.ruleSet[k] = rule;
    }

    // turn off
    TRsalvageData.salvageActive = false;
    clearInterval(Tabs.throneSalvage.sTimer);
    clearInterval(Tabs.throneSalvage.delTimer);
    Tabs.throneSalvage.deleting = false;
    TRsaveSalvageData();
    alert('Salvage settings loaded from domain ' + domainId);
    Tabs.throneSalvage.init(Tabs.throneSalvage.myDiv);
}

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

function unixTime () {
    return parseInt (new Date().getTime() / 1000) + unsafeWindow.g_timeoff;
}

//***************************** UNIQUES TAB ********************************************//

Tabs.throneUnique = {
    tabOrder: 405,
    myDiv: null,
    tabLabel: 'Uniques TR',
    tabDisabled: false,
    UniqueItems : null,
    trTypes: ['chair', 'advisor', 'window', 'banner', 'table', 'trophy', 'candelabrum', 'hero', 'statue', 'pet', 'tapestry', 'pillar'], // must be in this order  
    itemTypes: { chair: 0, advisor: 1, window: 2, banner: 3, table: 4, trophy: 5, candelabrum: 6, hero: 7, statue: 8, pet: 9, tapestry: 10, pillar: 11 }, // must be in this order
    itemLists: [],
    selectedCard1: 0,
    selectedCard2: 0,
    selectedCard3: 0,
    selectedType1: 0,
    selectedType2: 0,
    selectedType3: 0,
    contextMenu: false,

    init: function (div) {
        var t = Tabs.throneUnique;
        t.myDiv = div;

        t.UniqueItems = unsafeWindow.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 + ' ('+unsafeWindow.g_js_strings.commonstr[unsafeWindow.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 + ' ('+unsafeWindow.g_js_strings.commonstr[unsafeWindow.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 + ' ('+unsafeWindow.g_js_strings.commonstr[unsafeWindow.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 + ' ('+unsafeWindow.g_js_strings.commonstr[unsafeWindow.cm.CHAMPION.getFactionClasses(throne_item.Faction)].toLowerCase()+')';};
        }
       
        for (i in t.itemTypes) {
            t.itemLists[i] = new Array;
        }
        for (k in t.UniqueItems) {
            var throne_item = t.UniqueItems[k];
            if (throne_item == null || !throne_item || !t.itemLists[t.trTypes[parseInt(throne_item.Type)-1]]) continue;
            t.itemLists[t.trTypes[parseInt(throne_item.Type)-1]].push(throne_item);
        }
       
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV class=trStat>THRONE ROOM UNIQUES</div>';
        m += '<TABLE width=100% class="trTabPad2 trTable">';
        m += '<tr width=100% align=center><td width=33%/><td width=33%/><td width=33%/></tr>';
 
        m += '<tr><td><div style="max-width:100%;"><b>Item Type:</b><select id="trUniqueType1" style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var type_index = 0; type_index < this.trTypes.length; ++type_index) {
            m += '<option value="' + this.trTypes[type_index] + '">' + this.trTypes[type_index].capitalize() + '</option>';
        }
        m += '</select></div></td>';

        m += '<td><div style="max-width:100%;"><b>Item Type:</b><select id="trUniqueType2" style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var type_index = 0; type_index < this.trTypes.length; ++type_index) {
            m += '<option value="' + this.trTypes[type_index] + '">' + this.trTypes[type_index].capitalize() + '</option>';
        }
        m += '</select></div></td>';

        m += '<td><div style="max-width:100%;"><b>Item Type:</b><select id="trUniqueType3" style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var type_index = 0; type_index < this.trTypes.length; ++type_index) {
            m += '<option value="' + this.trTypes[type_index] + '">' + this.trTypes[type_index].capitalize() + '</option>';
        }
        m += '</select></div></td></tr>';

        m += '<tr><td><div style="max-width:100%;"><b>Throne Item:</b><br/><select id="trUnique1" 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>';

        m += '<td><div style="max-width:100%;"><b>Throne Item:</b><br/><select id="trUnique2" 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>';

        m += '<td><div style="max-width:100%;"><b>Throne Item:</b><br/><select id="trUnique3" 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 id="trUniqueLevel1" style="width: 40%;">';
        m += '<option value="1" selected>1</option>';
        for (var type_index = 2; type_index < OrganizerMaxTRLevel + 1; ++type_index) {
            m += '<option value="' + type_index + '">' + type_index + '</option>';
        }
        m += '</select></div></td>';
        m += '<td><div style="max-width:100%;"><b>Level:</b><select id="trUniqueLevel2" style="width: 40%;">';
        m += '<option value="1" selected>1</option>';
        for (var type_index = 2; type_index < OrganizerMaxTRLevel + 1; ++type_index) {
            m += '<option value="' + type_index + '">' + type_index + '</option>';
        }
        m += '</select></div></td>';
        m += '<td><div style="max-width:100%;"><b>Level:</b><select id="trUniqueLevel3" style="width: 40%;">';
        m += '<option value="1" selected>1</option>';
        for (var type_index = 2; type_index < OrganizerMaxTRLevel + 1; ++type_index) {
            m += '<option value="' + type_index + '">' + type_index + '</option>';
        }
        m += '</select></div></td></tr>';

        m += '<tr>';
        m += '<td id="trUniqueItem1" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '<td id="trUniqueItem2" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '<td id="trUniqueItem3" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '</tr>';
        m += '<tr>';
        m += '<td id="trUniqueInv1" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '<td id="trUniqueInv2" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '<td id="trUniqueInv3" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '</tr>';

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

        t.myDiv.innerHTML = m;

        $("#trUniqueType1").change(function () {
            var trType = $(this).val();
            var trList = document.getElementById('trUnique1');
            var trDisplay = document.getElementById('trDisplayItem1');
            if (t.selectedCard1 == 0 || (t.selectedType1 != trType) && trType != 0) {
                trDisplay.innerHTML = '';
                t.selectedCard1 = 0;
            }
            t.selectedType1 = trType;
            $("#trUnique1").empty();
            var trOption = document.createElement('option');
            trOption.text = '--Items--';
            trOption.value = 0;
            trList.add(trOption);
            for (k in t.UniqueItems) {
                var throne_item = t.UniqueItems[k];
                if (throne_item == null || !throne_item) continue;
                if (t.trTypes[parseInt(throne_item.Type)-1] == trType || trType == 0) {
                    var trOption = document.createElement('option');
                    trOption.text = throne_item.Name;
                    trOption.value = k;
                    trList.add(trOption);
                }
            }

            if (t.selectedCard1 != 0) {
                $("#trUnique1").val(t.selectedCard1);
            }

        });

        $("#trUniqueType2").change(function () {
            var trType = $(this).val();
            var trList = document.getElementById('trUnique2');
            var trDisplay = document.getElementById('trDisplayItem2');
            if (t.selectedCard2 == 0 || (t.selectedType2 != trType) && trType != 0) {
                trDisplay.innerHTML = '';
                t.selectedCard2 = 0;
            }
            t.selectedType2 = trType;
            $("#trUnique2").empty();
            var trOption = document.createElement('option');
            trOption.text = '--Items--';
            trOption.value = 0;
            trList.add(trOption);
            for (k in t.UniqueItems) {
                var throne_item = t.UniqueItems[k];
                if (throne_item == null || !throne_item) continue;
                if (t.trTypes[parseInt(throne_item.Type)-1] == trType || trType == 0) {
                    var trOption = document.createElement('option');
                    trOption.text = throne_item.Name;
                    trOption.value = k;
                    trList.add(trOption);
                }
            }

            if (t.selectedCard2 != 0) {
                $("#trUnique2").val(t.selectedCard2);
            }

        });

        $("#trUniqueType3").change(function () {
            var trType = $(this).val();
            var trList = document.getElementById('trUnique3');
            var trDisplay = document.getElementById('trDisplayItem3');
            if (t.selectedCard3 == 0 || (t.selectedType3 != trType) && trType != 0) {
                trDisplay.innerHTML = '';
                t.selectedCard3 = 0;
            }
            t.selectedType3 = trType;
            $("#trUnique3").empty();
            var trOption = document.createElement('option');
            trOption.text = '--Items--';
            trOption.value = 0;
            trList.add(trOption);
            for (k in t.UniqueItems) {
                var throne_item = t.UniqueItems[k];
                if (throne_item == null || !throne_item) continue;
                if (t.trTypes[parseInt(throne_item.Type)-1] == trType || trType == 0) {
                    var trOption = document.createElement('option');
                    trOption.text = throne_item.Name;
                    trOption.value = k;
                    trList.add(trOption);
                }
            }

            if (t.selectedCard3 != 0) {
                $("#trUnique3").val(t.selectedCard3);
            }

        });

        $("#trUnique1").change(function () { changeUnique1(this); });

        $("#trUnique1").keyup(function (event) { changeUnique1(this); });

        function changeUnique1(thisObj) {
            var trID = $(thisObj).val();
            var trDisplay = document.getElementById('trUniqueItem1');
            var trLevel = document.getElementById('trUniqueLevel1');
            var trInv = document.getElementById('trUniqueInv1');
            t.selectedCard1 = 0;
            t.ConvertToCard(trID,trDisplay,trLevel);
            t.GetInventory(trID,trInv);
            t.selectedCard1 = trID;
            t.selectedType1 = i;
        }

        $("#trUnique2").change(function () { changeUnique2(this); });

        $("#trUnique2").keyup(function (event) { changeUnique2(this); });

        function changeUnique2(thisObj) {
            var trID = $(thisObj).val();
            var trDisplay = document.getElementById('trUniqueItem2');
            var trLevel = document.getElementById('trUniqueLevel2');
            var trInv = document.getElementById('trUniqueInv2');
            t.selectedCard2 = 0;
            t.ConvertToCard(trID,trDisplay,trLevel);
            t.GetInventory(trID,trInv);
            t.selectedCard2 = trID;
            t.selectedType2 = i;
        }

        $("#trUnique3").change(function () { changeUnique3(this); });

        $("#trUnique3").keyup(function (event) { changeUnique3(this); });

        function changeUnique3(thisObj) {
            var trID = $(thisObj).val();
            var trDisplay = document.getElementById('trUniqueItem3');
            var trLevel = document.getElementById('trUniqueLevel3');
            var trInv = document.getElementById('trUniqueInv3');
            t.selectedCard3 = 0;
            t.ConvertToCard(trID,trDisplay,trLevel);
            t.GetInventory(trID,trInv);
            t.selectedCard3 = trID;
            t.selectedType3 = i;
        }

        $("#trUniqueLevel1").keyup(function (event) { changeLevel1(); });

        $("#trUniqueLevel1").change(function () { changeLevel1(); });

        function changeLevel1() {
            if (t.selectedCard1 != 0) {
                var trID = t.selectedCard1;
                var trDisplay = document.getElementById('trUniqueItem1');
                var trLevel = document.getElementById('trUniqueLevel1');
                trDisplay.innerHTML = '';
                t.ConvertToCard(trID,trDisplay,trLevel);
            }
        }

        $("#trUniqueLevel2").keyup(function (event) { changeLevel2(); });

        $("#trUniqueLevel2").change(function () { changeLevel2(); });

        function changeLevel2() {
            if (t.selectedCard2 != 0) {
                var trID = t.selectedCard2;
                var trDisplay = document.getElementById('trUniqueItem2');
                var trLevel = document.getElementById('trUniqueLevel2');
                trDisplay.innerHTML = '';
                t.ConvertToCard(trID,trDisplay,trLevel);
            }
        }

        $("#trUniqueLevel3").keyup(function (event) { changeLevel3(); });

        $("#trUniqueLevel3").change(function () { changeLevel3(); });

        function changeLevel3() {
            if (t.selectedCard3 != 0) {
                var trID = t.selectedCard3;
                var trDisplay = document.getElementById('trUniqueItem3');
                var trLevel = document.getElementById('trUniqueLevel3');
                trDisplay.innerHTML = '';
                t.ConvertToCard(trID,trDisplay,trLevel);
            }
        }

    },

    ConvertToCard:function (trID,div,lvl) {
        var t = Tabs.throneUnique;
        div.innerHTML = '';
        var TRCard = {};
        TRCard = t.UniqueItems[trID];
        TRCard.id = TRCard.Id;
        TRCard.name = TRCard.Name;
        TRCard.faction = unsafeWindow.g_js_strings.commonstr[unsafeWindow.cm.CHAMPION.getFactionClasses(TRCard.Faction)].toLowerCase();
        TRCard.type = t.trTypes[parseInt(TRCard.Type)-1].toLowerCase();
        TRCard.unique = TRCard.id;
        TRCard.level = parseInt(lvl.value);
        TRCard.quality = OrganizerMaxTRQuality;
        TRCard.createPrefix = function () { return ""; };
        TRCard.createSuffix = function () { return ""; };
        TRCard.effects = {};
        var effects = eval(TRCard.Effects);
        var slot = 0;

        for (k in effects) {
            slot++
            TRCard.effects["slot"+slot] = {};
            TRCard.effects["slot"+slot].id = effects[k].type;
            TRCard.effects["slot"+slot].tier = effects[k].tier;
           
            if (slot==6) {
                TRCard.effects["slot"+slot].quality = 5; // assume bright jewel
                TRCard.effects["slot"+slot].fromJewel = true;
               
                TRCard.jewel = {};
                TRCard.jewel.valid = true;
                TRCard.jewel.id = TRCard.effects["slot"+slot].id;
                TRCard.jewel.quality = 5; // assume bright jewel
                TRCard.jewel.tier = TRCard.effects["slot"+slot].tier;
                TRCard.jewel.fromJewel = true;
                TRCard.jewel.gift = false;
                 TRCard.jewel.quantity = 1;
            }   
        }
        div.innerHTML = BuildThroneCardGraphical(TRCard, div, "trUniqueCardDisp");
    },

    GetInventory:function (trID,div) {
        var t = Tabs.throneUnique;
        div.innerHTML = '';
        var m = '<br><b>Throne Room</b><br>';
        var tritem = {};
        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            if (throne_item.unique == trID) {
                if (tritem[throne_item.level]) {tritem[throne_item.level]++} else {tritem[throne_item.level] = 1;}
            }
        }
        var gotitem = false;
        for (l in tritem) {
            gotitem = true;
            m += 'You have '+tritem[l]+' at level '+l+'<br>';
        }
        if (!gotitem) m += 'You have none in your throne room.<br>';
       
        m += '<br><b>Inventory</b><br>';
        var inv = unsafeWindow.seed.items['i'+trID];
        m += 'You have '+(inv?inv:'none')+' in your inventory.';
        div.innerHTML = m;
    },

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

    hide: function () {
    }
}

/** ********************************* Throne Compare Tab ****************** **/
Tabs.throneCompare = {
    tabOrder: 400,
    tabLabel: 'Compare TR',
    tabDisabled: false,
    myDiv: null,
    trTypes: ['chair', 'table', 'window', 'banner', 'advisor', 'trophy', 'candelabrum', 'hero', 'statue', 'pet', 'tapestry', 'pillar'],
    itemTypes: { chair: 0, table: 1, window: 2, banner: 3, advisor: 4, trophy: 5, candelabrum: 6, hero: 7, statue: 8, pet: 9, tapestry: 10, pillar: 11 }, 
    itemLists: [],
    selectedCard1: 0,
    selectedCard2: 0,
    selectedCard3: 0,
    selectedType1: 0,
    selectedType2: 0,
    selectedType3: 0,
    contextMenu: false,


    init: function (div) {
        var t = Tabs.throneCompare
        t.fillLists();
        t.myDiv = div;

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=trSalvage class=trStat>THRONE ROOM COMPARE</div>';
        m += '<TABLE  width=100% class="trTabPad2 trTable">';
        m += '<tr width=100% align=center><td width=33%/><td width=33%/><td width=33%/></tr>';
        //m += '<tr width=100%><td colspan=2><b>NOTE:</b> There will be some future tweaks to this section.  Look for them in upcoming releases.<br/><hr/></td></tr>';
        m += '<tr>';

        m += '<td><div style="max-width:100%;"><b>Throne Type:</b><select id="trCompareType1" style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var type_index = 0; type_index < this.trTypes.length; ++type_index) {
            m += '<option value="' + this.trTypes[type_index] + '">' + this.trTypes[type_index].capitalize() + '</option>';
        }
        m += '</select></div></td>';

        m += '<td><div style="max-width:100%;"><b>Throne Type:</b><select id="trCompareType2" style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var type_index = 0; type_index < this.trTypes.length; ++type_index) {
            m += '<option value="' + this.trTypes[type_index] + '">' + this.trTypes[type_index].capitalize() + '</option>';
        }
        m += '</select></div></td>';

        m += '<td><div style="max-width:100%;"><b>Throne Type:</b><select id="trCompareType3" style="width: 40%;">';
        m += '<option value="0">--ALL--</option>';
        for (var type_index = 0; type_index < this.trTypes.length; ++type_index) {
            m += '<option value="' + this.trTypes[type_index] + '">' + this.trTypes[type_index].capitalize() + '</option>';
        }
        m += '</select></div></td>';

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

        m += '<td><div style="max-width:100%;"><b>Throne Item:</b><br/><select id="trCompare1" style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            if (throne_item == null || !throne_item) continue;
            m += '<option value="' + k + '">' + throne_item.name + ' </option>';
        }
        m += '</select></div></td>';

        m += '<td><div style="max-width:100%;"><b>Throne Item:</b><br/><select id="trCompare2" style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            if (throne_item == null || !throne_item) continue;
            m += '<option value="' + k + '">' + throne_item.name + ' </option>';
        }
        m += '</select></div></td>';

        m += '<td><div style="max-width:100%;"><b>Throne Item:</b><br/><select id="trCompare3" style="width: 95%;">';
        m += '<option value="0">--Items--</option>';
        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            if (throne_item == null || !throne_item) continue;
            m += '<option value="' + k + '">' + throne_item.name + ' </option>';
        }
        m += '</select></div></td>';

        m += '</tr>';

        m += '<tr>';

        m += '<td id="trDisplayItem1" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '<td id="trDisplayItem2" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '<td id="trDisplayItem3" class="tdcard" style="overflow: visible;  width: auto; height: auto;"/>';
        m += '</tr>';

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

        t.myDiv.innerHTML = m;

        $("#trCompareType1").change(function () {
            var trType = $(this).val();
            var trList = document.getElementById('trCompare1');
            var trDisplay = document.getElementById('trDisplayItem1');
            if (t.selectedCard1 == 0 || (t.selectedType1 != trType) && trType != 0) {
                trDisplay.innerHTML = '';
                t.selectedCard1 = 0;
            }
            t.selectedType1 = trType;
            $("#trCompare1").empty();
            var trOption = document.createElement('option');
            trOption.text = '--Items--';
            trOption.value = 0;
            trList.add(trOption);
            for (k in unsafeWindow.kocThroneItems) {
                var throne_item = unsafeWindow.kocThroneItems[k];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.type == trType || trType == 0) {
                    var trOption = document.createElement('option');
                    trOption.text = throne_item.name;
                    trOption.value = k;
                    trList.add(trOption);
                }
            }

            if (t.selectedCard1 != 0) {
                $("#trCompare1").val(t.selectedCard1);
            }

        });

        $("#trCompareType2").change(function () {
            var trType = $(this).val();
            var trList = document.getElementById('trCompare2');
            var trDisplay = document.getElementById('trDisplayItem2');
            if (t.selectedCard2 == 0 || (t.selectedType2 != trType) && trType != 0) {
                trDisplay.innerHTML = '';
                t.selectedCard2 = 0;
            }
            t.selectedType2 = trType;
            $("#trCompare2").empty();
            var trOption = document.createElement('option');
            trOption.text = '--Items--';
            trOption.value = 0;
            trList.add(trOption);
            for (k in unsafeWindow.kocThroneItems) {
                var throne_item = unsafeWindow.kocThroneItems[k];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.type == trType || trType == 0) {
                    var trOption = document.createElement('option');
                    trOption.text = throne_item.name;
                    trOption.value = k;
                    trList.add(trOption);
                }
            }

            if (t.selectedCard2 != 0) {
                $("#trCompare2").val(t.selectedCard2);
            }

        });

        $("#trCompareType3").change(function () {
            var trType = $(this).val();
            var trList = document.getElementById('trCompare3');
            var trDisplay = document.getElementById('trDisplayItem3');
            if (t.selectedCard3 == 0 || (t.selectedType3 != trType) && trType != 0) {
                trDisplay.innerHTML = '';
                t.selectedCard3 = 0;
            }
            t.selectedType3 = trType;
            $("#trCompare3").empty();
            var trOption = document.createElement('option');
            trOption.text = '--Items--';
            trOption.value = 0;
            trList.add(trOption);
            for (k in unsafeWindow.kocThroneItems) {
                var throne_item = unsafeWindow.kocThroneItems[k];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.type == trType || trType == 0) {
                    var trOption = document.createElement('option');
                    trOption.text = throne_item.name;
                    trOption.value = k;
                    trList.add(trOption);
                }
            }

            if (t.selectedCard3 != 0) {
                $("#trCompare3").val(t.selectedCard3);
            }

        });


        $("#trCompare1").change(function () {
            var trID = $(this).val();
            var trDisplay1 = document.getElementById('trDisplayItem1');
            trDisplay1.innerHTML = '';
            t.selectedCard1 = 0;
            var ii = Math.max(t.itemLists['chair'].length, t.itemLists['table'].length, t.itemLists['window'].length, t.itemLists['banner'].length, t.itemLists['advisor'].length, t.itemLists['trophy'].length, t.itemLists['candelabrum'].length, t.itemLists['hero'].length, t.itemLists['statue'].length, t.itemLists['pet'].length, t.itemLists['tapestry'].length, t.itemLists['pillar'].length);  

            for (var k = 0; k < ii; k++) {
                for (i in t.itemTypes) {
                    var item = t.itemLists[i][k];
                    if (item != null) {
                        if (item.id == trID) {
                            if (GeneralOptions.graphicalThrone) {
                                trDisplay1.innerHTML = BuildThroneCardGraphical(unsafeWindow.kocThroneItems[trID], "trDisplayItem1", "trCompareCardDisp");
                            } else {
                                trDisplay1.innerHTML = BuildThroneCardTextual(unsafeWindow.kocThroneItems[trID], "trDisplayItem1", "trCompareCardDisp");
                            }

                            t.selectedCard1 = trID;
                            t.selectedType1 = i;
                            break;
                        }
                    }
                }
            }

        });




        $("#trCompare2").change(function () {
            var trID = $(this).val();
            var trDisplay2 = document.getElementById('trDisplayItem2');
            trDisplay2.innerHTML = '';
            t.selectedCard2 = 0;
            var ii = Math.max(t.itemLists['chair'].length, t.itemLists['table'].length, t.itemLists['window'].length, t.itemLists['banner'].length, t.itemLists['advisor'].length, t.itemLists['trophy'].length, t.itemLists['candelabrum'].length, t.itemLists['hero'].length, t.itemLists['statue'].length, t.itemLists['pet'].length, t.itemLists['tapestry'].length, t.itemLists['pillar'].length);  

            for (var k = 0; k < ii; k++) {
                for (i in t.itemTypes) {
                    var item = t.itemLists[i][k];
                    if (item != null) {
                        if (item.id == trID) {
                            if (GeneralOptions.graphicalThrone) {
                                trDisplay2.innerHTML = BuildThroneCardGraphical(unsafeWindow.kocThroneItems[trID], "trDisplayItem2", "trCompareCardDisp");
                            } else {
                                trDisplay2.innerHTML = BuildThroneCardTextual(unsafeWindow.kocThroneItems[trID], "trDisplayItem2", "trCompareCardDisp");
                            }


                            t.selectedCard2 = trID;
                            t.selectedType2 = i;
                            break;
                        }
                    }
                }
            }

        });


        $("#trCompare3").change(function () {
            var trID = $(this).val();
            var trDisplay3 = document.getElementById('trDisplayItem3');
            trDisplay3.innerHTML = '';
            t.selectedCard3 = 0;
            var ii = Math.max(t.itemLists['chair'].length, t.itemLists['table'].length, t.itemLists['window'].length, t.itemLists['banner'].length, t.itemLists['advisor'].length, t.itemLists['trophy'].length, t.itemLists['candelabrum'].length, t.itemLists['hero'].length, t.itemLists['statue'].length, t.itemLists['pet'].length, t.itemLists['tapestry'].length, t.itemLists['pillar'].length);  

            for (var k = 0; k < ii; k++) {
                for (i in t.itemTypes) {
                    var item = t.itemLists[i][k];
                    if (item != null) {
                        if (item.id == trID) {
                            if (GeneralOptions.graphicalThrone) {
                                trDisplay3.innerHTML = BuildThroneCardGraphical(unsafeWindow.kocThroneItems[trID], "trDisplayItem3", "trCompareCardDisp");
                            } else {
                                trDisplay3.innerHTML = BuildThroneCardTextual(unsafeWindow.kocThroneItems[trID], "trDisplayItem3", "trCompareCardDisp");
                            }

                            t.selectedCard3 = trID;
                            t.selectedType3 = i;
                            break;
                        }
                    }
                }
            }

        });


        $("#trDisplayItem1").click(function () {
            DoContextMenu("trDisplayItem1");
        });
        $("#trDisplayItem2").click(function () {
            DoContextMenu("trDisplayItem2");
        });
        $("#trDisplayItem3").click(function () {
            DoContextMenu("trDisplayItem3");
        });

        function DoContextMenu(tdId) {
            var t = Tabs.throneCompare;
            var td = document.getElementById(tdId);
            var divs = td.getElementsByTagName("div");
            var div = divs[0];
            var theId = $(div).attr("id").split(tdId)[1];
            unsafeWindow.cm.ContextualMenuThrone.renderMenu(div, unsafeWindow.kocThroneItems[theId]);
            t.contextMenu = true;
            document.getElementById("contextMenu").addEventListener("mouseenter", function () { t.contextMenu = false; }, false);
            div.addEventListener("mouseleave", function () {
                setTimeout(function () {
                    if (t.contextMenu) {
                        $("#contextMenu").remove();
                        t.contextMenu = false;
                    }
                }, 100);
            }, false);
        }

        if (!GeneralOptions.graphicalThrone) {
            if (TRpresetData.noTooltips != true) $("td.tdcard").on("mouseleave", "*", function (A) {
                HideThroneTooltip("chtrTooltip");
            });

            if (TRpresetData.noTooltips != true) $("td.tdcard").on("mouseenter", "*", function (A) {
                A.stopPropagation();
                var tdCard = $(this).parents("td.tdcard");
                var divCard = $(this).parents("div.trCompareCardDisp");

                var tdCard_id = tdCard.attr("id");
                var divCard_id = divCard.attr("id");

                var trId = divCard_id.split(tdCard_id)[1];

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

                ShowThroneTooltip($(this), "chtrTooltip", trId);

            });
        }
    },

    // fill the lists w/ the current TR items
    fillLists: function () {
        var t = Tabs.throneCompare;

        for (i in t.itemTypes) {
            t.itemLists[i] = new Array;
        }

        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            if (throne_item == null || !throne_item) continue;
            t.itemLists[throne_item.type].push(throne_item);
        }
    },

    show: function () {
        var t = Tabs.throneCompare;
        t.fillLists();
        //t.init();
        //t.init($("#tabs-compareTR")[0]);
    },

    hide: 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 = [];
}

/** ********************************* Champion Salvage Tab **************** **/
Tabs.champSalvage = {
        tabOrder    : 700,
        tabLabel    : 'Champ Salvager',
        tabDisabled : false,
        myDiv    : null,
        timer    : null,
        city     : null,
        cityNum  : 0,
        delItems        : [],
        rowNum   : 0,
        sTimer : null,
        delTimer : null,
        upgradeProfit: true,
        //salvageFailList: {},
        //maxFailures: 2,

        init : function (div) {
            var t = Tabs.champSalvage;
            t.myDiv = div;

            var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
            m += '<DIV  id=chSalvage class=chStat>CHAMPION SALVAGER</div>';
            m += "<div id='chInfoArea'>";
            m += '</div>';
            m += '<TABLE class="chTabDef chTable" id=chUpgrader width =100% height=0% style="padding-left: 20px;">';
            if (CHsalvageData.salvageActive == false) {
                m += '<tr><TD><div><INPUT id=chSalvagerPower type=button value="Salvager = OFF"/></div></td>';
            } else {
                m += '<tr><TD><div><INPUT id=chSalvagerPower type=button value="Salvager = ON"/></div></td>';
            }
            m += '<td> <div> Keep all: <select id="chSalvageQuality">';
            m += '<option value="1">Common</option>';
            m += '<option value="2">Uncommon</option>';
            m += '<option value="3">Rare</option>';
            m += '<option value="4">Epic</option>';
            m += '<option value="5">Wondrous</option>';
            m += '</select> and higher</div></td>';

            m += '<td align=right>Keep the first <INPUT id=chSaveNum type=text size=3 maxlength=3 value="' + CHsalvageData.champSaveNum+ '"/> items</td>';
            m += "</tr></table><hr/>";

            m += "<div id='chRulesCreateSimple' class='chRuleCreate' style='display: block;'>";

            // rules definition
            m += '<TABLE class="chTabDef chTable" width=100% class=chTabPad style="padding-left: 10px;">';
            m += '<tr><td colspan=4><input type=button id="chSwitchToAdvanced" value="SWITCH TO ADVANCED"></td></tr>';
            m += '<tr><td>  <b>Define the champion items to keep: </b> </td>';

            m += '<td alight="left"><div><span>Faction: <select id="chFactionType">';
            m += '  <option value="any">Any</option>';
            m += '  <option value="fey">Fey</option>';
            m += '  <option value="briton">Briton</option>';
            m += '  <option value="druid">Druid</option>';
            m += '</select></span></div></td>';
            m += '<td alight="left"><div><span>Item type: <select id="chCardType">';
            m += '  <option value="any">Any</option>';
            for (ct in champItemTypes) m += '<option value="' + ct + '">' + ct + '</option>';
            m += '</select></span></div></td>';
            m += '<td align="right"><INPUT id=chAddRule type=button value="Create Rule"/></td>';
            m += '</tr></table>';

            m += '<TABLE  class="chTabPad chTable" width=100% id="chConditionTable"  style="padding-left: 5px;">';
            m += '<tr><td align=left colspan=1><INPUT id=chAddRow type=button value="Add Row"/></td>';
            m += '<td></td><td></td><td></td><td></td><td></td></tr>';
            m += '</table>';
            m += '</div>';

            m += "<div id='chRulesCreateAdvanced' class='chRuleCreate' style='display:none;'>";

            // rules definition
            m += '<TABLE class="chTabDef chTable" width=100% class=chTabPad style="padding-left: 10px;">';
            m += '<tr><td colspan=3 align=left><input type=button id="chSwitchToSimple" value="SWITCH TO SIMPLE"></td><td><input type=button id="chAdvancedReset" value="Reset"></tr>';
            m += '<tr><td colspan=4><center><b><font color=red>SPECIAL THANKS TO Gunvald Storheil FOR HIS SPREADSHEET, IT INSPIRED THIS FEATURE</font></b></center></td></tr>';
            m += '<tr><td>  <b>Define the CH items to keep: </b> </td>';

            m += '<td alight="left"><div><span>Faction: <select id="chFactionTypeAdvanced">';
            m += '  <option value="any">Any</option>';
            m += '  <option value="fey">Fey</option>';
            m += '  <option value="briton">Briton</option>';
            m += '  <option value="druid">Druid</option>';
            m += '</select></span></div></td>';
            m += '<td alight="left"><div><span>Card type: <select id="chCardTypeAdvanced">';
            m += '  <option value="any">Any</option>';
            for (ct in champItemTypes) m += '<option value="' + ct + '">' + ct + '</option>';
            m += '</select></span></div></td>';
            m += '<td align="right"><INPUT id=chAddRuleAdvanced type=button value="Create Rule"/></td>';
            m += '</tr></table>';
            m += '<center><TABLE  class="chTabPad chTable" id="chConditionTableAdvanced"  style="padding-left: 5px;">';
            m += '<tr>';
            m += '<td align=center width=20%>ROW 1</td>';
            m += '<td align=center width=20%>ROW 2</td>';
            m += '<td align=center width=20%>ROW 3</td>';
            m += '<td align=center width=20%>ROW 4</td>';
            m += '<td align=center width=20%>ROW 5</td>';
            m += '</tr>';
            m += '<tr>';
            m += '<td width=20%><div><select style="max-width: 125px;" id="chRow1Advanced"></select></div></td>';
            m += '<td width=20%><div><select style="max-width: 125px;" id="chRow2Advanced"></select></div></td>';
            m += '<td width=20%><div><select style="max-width: 125px;" id="chRow3Advanced"></select></div></td>';
            m += '<td width=20%><div><select style="max-width: 125px;" id="chRow4Advanced"></select></div></td>';
            m += '<td width=20%><div><select style="max-width: 125px;" id="chRow5Advanced"></select></div></td>';
            m += '</tr>';
            m += '</table></center>';


            m += "</div>";
            
            m += '<hr/>';
            m += '<div id="chSalvStatus" style="text-align: center;" >Loading ... </div>';
            m += '<div id="chNumSalv" style="text-align: center;"></div>';
            m += '<hr/>';
            m += '<div class=chRulePane>';
            m += '<div align=center>Sort By Card Type: <select id=chSalvageSortCard>';
            m += '  <option value="0">--Select--</option>';
            for (ct in champItemTypes) m += '<option value="' + ct + '">' + ct + '</option>';
            m += '</select></div>';
            m += '<div align=center> <b> Salvager will keep items matching any of these rules </b></div>';
            m += '<div id=chRuleScroll style="position: static; width: 100%; height: '+ OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
            m += "<div id='chRuleDisplay' >";
            m += '</div></div>';
            m += '<div align=center><table align=center width=100%><tr><td width=50%><input id=chButtonSaveItem type=button value="Save Rules"></td>';
            m += '<td width=50%><input id=chButtonLoadItem type=button value="Load Rules"><input id=chFileLoadItem type=file></td></tr></table></div>';
            m += '</div>';
            t.myDiv.innerHTML = m;

            Tabs.champSalvage.displayNumberSalvaged();

            $('#chAdvancedReset').click(function() {
                var cardtype = document.getElementById('chCardTypeAdvanced');
                cardtype.selectedIndex = 0;
                clearAdvancedStats();
                setAdvancedStatsToAny();
            });

            function setAdvancedStatsToAny() {
                for (var r = 1; r < 6; r++) {
                    var row = document.getElementById('chRow' + r + 'Advanced');
                    row.options.add(new Option("none","None"));
                    for (i = 0; i < champItemEffects.length; i++) {
                        var effectName = unsafeWindow.g_js_strings.effects["name_" + champItemEffects[i]];
                        row.options.add(new Option(effectName, effectName));
                    }
                }
            }

            function clearAdvancedStats() {
                for (var i = 1; i < 6; i++) {
                    var row = document.getElementById('chRow' + i + 'Advanced');
                    row.innerHTML = "";
                }
            }

            function filterAdvancedStats(cardtype) {
                cardtype = cardtype || "any";

                if (cardtype == "any") {
                    setAdvancedStatsToAny();
                    return;
                }

                document.getElementById("chRow1Advanced").options.add(new Option("none", "none"));
                document.getElementById("chRow2Advanced").options.add(new Option("none", "none"));
                document.getElementById("chRow3Advanced").options.add(new Option("none", "none"));
                document.getElementById("chRow4Advanced").options.add(new Option("none", "none"));
                document.getElementById("chRow5Advanced").options.add(new Option("none", "none"));

                for (i = 0; i < champItemEffects.length; i++) {
                    var effectName = unsafeWindow.g_js_strings.effects["name_" + champItemEffects[i]];
                    var eff = champItemEffects[i];
                    if (ChampStatsGrid[cardtype][1][eff]) { document.getElementById("chRow1Advanced").options.add(new Option(effectName, effectName)); }
                    if (ChampStatsGrid[cardtype][2][eff]) { document.getElementById("chRow2Advanced").options.add(new Option(effectName, effectName)); }
                    if (ChampStatsGrid[cardtype][3][eff]) { document.getElementById("chRow3Advanced").options.add(new Option(effectName, effectName)); }
                    if (ChampStatsGrid[cardtype][4][eff]) { document.getElementById("chRow4Advanced").options.add(new Option(effectName, effectName)); }
                    if (ChampStatsGrid[cardtype][5][eff]) { document.getElementById("chRow5Advanced").options.add(new Option(effectName, effectName)); }
                }

            }

            setAdvancedStatsToAny();

            $('#chAddRuleAdvanced').click(function() { t.createAdvancedRule(); });

            $('#chCardTypeAdvanced').change(function() {
                var selectedValue = document.getElementById('chCardTypeAdvanced').value;
                clearAdvancedStats();
                if (selectedValue == "any") { 
                    setAdvancedStatsToAny();
                } else {
                    filterAdvancedStats(selectedValue);
                }
            });


            $('#chSwitchToAdvanced').click(function() {
                document.getElementById('chRulesCreateSimple').style.display = "none";
                document.getElementById('chRulesCreateAdvanced').style.display = "block";
            });

            $('#chSwitchToSimple').click(function() {
                document.getElementById('chRulesCreateSimple').style.display = "block";
                document.getElementById('chRulesCreateAdvanced').style.display = "none";
            });


            $('#chSalvagerPower').click(function () { t.togglePower(this); });
            //document.getElementById('chSalvagerPower').addEventListener('click', function(){t.togglePower(this);} , false);

            t.createRow();
            t.buildRuleDisplay();

            $('#chSalvageSortCard').change(function() { t.buildRuleDisplay(); });

            $('#chButtonSaveItem').click(function() {
                uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(CHsalvageData.ruleSet));
                newWindow = window.open(uriContent, 'file.txt');                
            });

            $('#chButtonLoadItem').click(function() {
                var fileInput = document.getElementById("chFileLoadItem");
                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;
				    CHsalvageData.ruleSet = JSON.parse(output);
                    CHsalvageData.salvageActive = false;
                    clearInterval(Tabs.champSalvage.sTimer);
                    clearInterval(Tabs.champSalvage.delTimer);
                    Tabs.champSalvage.deleting = false;
                    CHsaveSalvageData();
                    Tabs.champSalvage.init(Tabs.champSalvage.myDiv);
                    alert('Champ Salvage Settings Now Loaded From File');
                };
                reader.readAsText(file);
            });

            $('#chSaveNum').change(function () {
                CHsalvageData.champSaveNum = parseInt(document.getElementById('chSaveNum').value);
                if (CHsalvageData.champSaveNum < 0) CHsalvageData.champSaveNum = 0;
                CHsaveSalvageData();
            });

            $('#chSalvageQuality').click(function() { t.setSalvageLevel(this.value); });

            document.getElementById ('chSalvageQuality').value = CHsalvageData.minQuality;

            $('#chAddRow').click(function() { t.createRow(); });

            $('#chAddRule').click(function() { t.createRule(); });

//            $(document.querySelector("#chRuleScroll")).resizable({
//                minWidth: 720,
//                maxWidth: 1000,
//                minHeight: 180,
//                maxHeight: 700,
//                stop: function(event, ui) {
//                    CHupgradeData.salvageH =  ui.size.height + 'px';
//                    CHupgradeData.salvageW =  ui.size.width  + 'px';
//                    CHsaveUpgradeData();
//                }
//            });

//            $(document.querySelector("#chRuleScroll")).css('height', CHupgradeData.salvageH).css('width', CHupgradeData.salvageW);
            // 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();
        },

        tripOdometer : function() {
            CHsalvageData.numSalvagedItems2 = 0;
            var now = new Date();
            CHsalvageData.since = now.valueOf();
            CHsaveSalvageData();
            Tabs.champSalvage.init(Tabs.champSalvage.myDiv);
        },

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

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

            var sinceD = new Date(CHsalvageData.since);

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

            $(document.querySelector("#chNumSalv")).html('<div style="text-align: center;"> '+ addCommas(CHsalvageData.numSalvagedItems) + " items salvaged" 
                    + ', ' + addCommas(CHsalvageData.numSalvagedItems2) + ' items since ' + since + rate +
            ' <input id="chtripOdo" type=button value="Reset" /> </div>');

            $(document.querySelector("#chtripOdo")).click( function () {
                Tabs.champSalvage.tripOdometer();  
            });
        },


        createRow : function()
        {
            var t = Tabs.champSalvage;
            var table = document.getElementById('chConditionTable');
            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 id='" + rowId + "chsel1'> <option value='true'> </option> <option value='false'>NOT</option></select></td>";
            h += "<td> <select id='" + rowId + "chsel2'>";
            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 id='" + rowId + "chsel3'>";
            h += "</select></td>";
            h += "<td> <select id='" + rowId + "chsel4'>";
            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 type=checkbox value='1' checked=true id='" + rowId + "ch_slot1'/>1";
            h += "  <input type=checkbox value='2' checked=true id='" + rowId + "ch_slot2'/>2";
            h += "  <input type=checkbox value='3' checked=true id='" + rowId + "ch_slot3'/>3";
            h += "  <input type=checkbox value='4' checked=true id='" + rowId + "ch_slot4'/>4";
            h += "  <input type=checkbox value='5' checked=true id='" + rowId + "ch_slot5'/>5";
            h += "</td>";

            row.innerHTML = h;

            var effects = [];
            
            for (i = 0; i < champItemEffects.length; i++) {
                var effectName = unsafeWindow.g_js_strings.effects["name_" + champItemEffects[i]];
                effectName = effectName.split(" Debuff")[0];
                if  (effects.indexOf(effectName) < 0) effects.push(effectName);
            }

            /*

            for (i = 201; i <= 209 ; i ++)
            {
               var effectName = unsafeWindow.g_js_strings.effects["name_"+ i];
               if (effects.indexOf(effectName) < 0) effects.push(effectName);
            }
            
            //"1","2","3","4","5","6","7","17","18","19","20","21","22","23"
            for (i = 1; i <= 7; i ++)
            {
               var effectName = CM.thronestats.effects[i][1];
               if (effects.indexOf(effectName) < 0) effects.push(effectName);
            }


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

            var c = row.insertCell(5);
            var btn = $("<input type=button value='X'/>");
            $(btn).click( function () { t.removeRow(row);});
            $(c).append( btn );

            //t.setFullness();
        },

        setSalvageLevel : function(level)
        {
            CHsalvageData.minQuality = level;
            CHsaveSalvageData();
        },

        createAdvancedRule: function() {
            var t = Tabs.champSalvage;
            t.readAdvancedRows();
            t.buildRuleDisplay();  
        },

        createRule : function()
        {
            var t = Tabs.champSalvage;
            t.readRows();
            t.buildRuleDisplay();
        },

        buildRuleDisplay : function ()
        {
            var t = Tabs.champSalvage;

            function innerRuleDisplay(dataset) {
                var innerM = "";
                //for (i =0; i < CHsalvageData.ruleSet.length; i++)
                for (i = 0; i < dataset.length; i++)
                {
                    var rule = dataset[i];

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

                    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><INPUT id=chEditRule" + i + " type=button value='Edit' disabled/><br><INPUT id=chDelRule" + i + " type=button value='Delete' /></td>";
                    innerM += '</tr>';
                }
                return innerM;
            }

            var rd = document.getElementById('chRuleDisplay');
            var sortType = document.getElementById('chSalvageSortCard').value;

            if (sortType != "0") {
                var sortedDataSet = [];
                //var sortType = document.getElementById('chSalvageSortCard').value;
                for (var k = 0; k < CHsalvageData.ruleSet.length; k++) {
                    if (sortType == CHsalvageData.ruleSet[k].type) {
                        sortedDataSet.unshift(CHsalvageData.ruleSet[k]);
                    }else {
                        sortedDataSet.push(CHsalvageData.ruleSet[k]);
                    }
                }
                rd.innerHTML = '<TABLE  width=100% class="chTabPad chTable">' + innerRuleDisplay(sortedDataSet);
                for (var j=0; j < sortedDataSet.length; j++)
                {
                    document.getElementById('chDelRule' +j).v1 = j;
                    document.getElementById('chEditRule' +j).v1 = j;
                    document.getElementById('chDelRule' +j).addEventListener ('click', function() { t.deleteRule(this.v1, sortedDataSet);}, false);
                    document.getElementById('chEditRule' +j).addEventListener ('click', function() { t.editRule(this.v1, sortedDataSet);}, false);
                }
            } else {
                rd.innerHTML = '<TABLE  width=100% class="chTabPad chTable">' + innerRuleDisplay(CHsalvageData.ruleSet);
                for (var j=0; j < CHsalvageData.ruleSet.length; j++)
                {
                    document.getElementById('chDelRule' +j).v1 = j;
                    document.getElementById('chEditRule' +j).v1 = j;
                    document.getElementById('chDelRule' +j).addEventListener ('click', function() { t.deleteRule(this.v1, CHsalvageData.ruleSet);}, false);
                    document.getElementById('chEditRule' +j).addEventListener ('click', function() { t.editRule(this.v1, CHsalvageData.ruleSet);}, false);
                }
            }

            //rd.innerHTML = m;


        },
        editRule : function(ruleIndex, sortedData)
        {
            //alert('edit');
        },

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

        updateCHTab : function() {
            $(document.querySelector("#chexecsalvage")).html("Salvage " + (CHsalvageData.salvageActive ? "ON" : "OFF"));
        },


        togglePower: function(obj){
            var t = Tabs.champSalvage;
            
            if (CHsalvageData.salvageActive == true) {
                var btn = document.getElementById('chSalvagerPower');
                CHsalvageData.salvageActive = false;
                btn.value = "Salvager = OFF";
                clearInterval(t.sTimer);
                clearInterval(t.delTimer);
                t.delItems = [];
                t.deleting = false;
            } else {
                CHsalvageData.salvageActive = true;
                var btn = document.getElementById('chSalvagerPower');
                btn.value = "Salvager = ON";
                t.doSalvage();
                t.start();
            }
            CHsaveSalvageData();
            t.updateCHTab();
        },

        readAdvancedRows: function () {
            var t = Tabs.champSalvage;
            var cType = document.getElementById('chCardTypeAdvanced').value;
            var faction = document.getElementById('chFactionTypeAdvanced').value;
            //var c = new TRCondition(true,1,
            var row1 = document.getElementById("chRow1Advanced");
            var row2 = document.getElementById("chRow2Advanced");
            var row3 = document.getElementById("chRow3Advanced");
            var row4 = document.getElementById("chRow4Advanced");
            var row5 = document.getElementById("chRow5Advanced");
            var conditions = [];
            for (var i = 1; i < 6; i++) {
                var row = document.getElementById("chRow" + 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 CHCondition(true, 1, effectName, buffDebuff, slots);
                conditions.push(c);
            }
            if ( conditions.length > 0 ) {
                var rule1 = new CHRule(cType, faction, conditions);
                t.addRule(rule1);
            }
        },

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

            var cType = document.getElementById('chCardType').value;
            var faction = document.getElementById('chFactionType').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 + "chsel1");
                    var s2 = document.getElementById(row.id + "chsel2");
                    var s3 = document.getElementById(row.id + "chsel3");
                    var s4 = document.getElementById(row.id + "chsel4");

                    var slots = [];
                    for (j =1; j <= 5; j++)
                    {
                        var ch = document.getElementById(row.id + "ch_slot" + j);
                        slots.push(ch.checked);
                    }
                    
                    var c = new CHCondition(s1.value, s2.value, s3.value, s4.value, slots );
                    conditions.push(c);
                }
            }
            var rule1 = new CHRule(cType, faction, conditions);
            t.addRule(rule1);
        },

        removeRow : function(row)
        {
            var table = document.getElementById('chConditionTable');

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

        // add a new rule
        addRule : function(rule)
        {
            CHsalvageData.ruleSet.unshift(rule);
            CHsaveSalvageData();
        },

//        // callback for when salvage city is changed
//        e_CityButton : function (city, x, y){
//            var t = Tabs.champSalvage;
//            CHupgradeData.sCityNum = city.idx;
//            CHsaveUpgradeData();
//        },

        start : function(){
            var t = Tabs.champSalvage;
            if(CHsalvageData.salvageActive) {
                t.sTimer = setInterval(t.doSalvage, 1*60*1000);
            }
        },

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

            //t.setFullness();

            if(!CHsalvageData.salvageActive) {
                t.deleting = false;
                return;
            }

            if (t.deleting == true) {
                logit("Deleting not complete");
                return;
            }

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

            t.delItems = t.buildList(false);
            
            //logit("Items to delete: "+ t.delItems.length);
           
            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);
            }
            //t.setFullness();
        },

//        setFullness : function () {
//            // change the color on the throne button when full

//            var num_items = unsafeWindow.Object.keys(unsafeWindow.kocChampionItems).length;  
//            if (num_items > 140)
//                $("a.buttonv2.throne").css('color', 'red');
//            else 
//                $("a.buttonv2.throne").css('color', 'black');
//        },

        // 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.champSalvage;

            var champSaveNum = CHsalvageData.champSaveNum;
            var countItem = 0;
            var retList = [];

            for (k in unsafeWindow.kocChampionItems) {
                var champ_item = unsafeWindow.kocChampionItems[k];
                
                countItem++;

                // ignore these things
                if (champ_item.level !=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 >= CHsalvageData.minQuality) continue;

                // check the rules
                if (t.applyRules(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('chSalvStatus').innerHTML = msg;
        },

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

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

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

            var id = +t.delItems[0];

            // delete the item
            t.delTimer = setTimeout( function () {t.doDelete(id)}, 4000);
        },

        removeItem : function (id, cityId, numStones) {

            var item = unsafeWindow.kocChampionItems[id];
            if (!item) return;

            var c = +(Seed.resources["city" + cityId]["rec5"][0]);
            delete unsafeWindow.kocChampionItems[id];
            
            //CM.ChampionModalView.renderFilteredItems();
        },

        doDelete : function(id) {

            var t = Tabs.champSalvage;
            if(!CHsalvageData.salvageActive || !t.deleting) {
                t.deleting = false;
                return;
            }

            //logit("deleting item: " + id);
            var item = unsafeWindow.kocChampionItems[id];
            if (item) t.setStatus('Salvaging ' + item.name);

            SalvageChampItem(id);
//            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//            var num_city = pickAetherSalvageCity();
//            if ( num_city < 0)
//            {
//                num_city = +GeneralOptions.salvageCityNum;
//                logit(" cities full");
//                t.setStatus("All cities are (nearly) full of aetherstone");
//            }


//            //params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
//            
//            params.action = "8";
//            params.eids = id;
//            params.cityId = Seed.cities[num_city][0];
//            
//            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
//                method: "post",
//                parameters: params,
//                loading: true,
//                onSuccess: function (transport) {
//                    try {
//                        var rslt = eval("(" + transport.responseText + ")");
//                        var champ_item = unsafeWindow.kocChampionItems[id];
//                        
//                        if(rslt.ok == true) {
//                            var eid = rslt.equipmentIds[0];
//                            champ_item = unsafeWindow.kocChampionItems[eid];
//                            
//                            if (champ_item) SalvageLog('Deleted Champion item '+ champ_item.name);
//                            CHsalvageData.numSalvagedItems++;
//                            CHsalvageData.numSalvagedItems2++;
//                            CHsaveSalvageData();

//                            if (champ_item) {
//                                CHsalvageData.numSalvaged[champ_item.rarity]++;
//                                CHsaveSalvageData();
//                                Tabs.champSalvage.removeItem(eid , Seed.cities[num_city][0], parseInt(rslt.aetherstones));
//                            }
//                            Tabs.champSalvage.displayNumberSalvaged();
//                        }
//                        else
//                        {
//                            //logit("rslt: " + inspect(rslt,3,1));
//                            if (champ_item) Tabs.champSalvage.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 {
//                            //logit("deletes done");
//                            t.deleting = false;
//                            t.setStatus('Salvaging complete.  Waiting for next cycle.');
//                            return;
//                        }
//                    } catch (e) {
//                        logit("Delete exception: " + inspect(e,3,1));
//                        t.deleting = false;
//                    }
//                },
//                onFailure: function () {
//                    //logit("failure case");
//                    t.delIems = [];
//                    t.deleting = false;
//                    if (unsafeWindow.kocChampionItems[id] )
//                        logit("salvage failed for item " + unsafeWindow.kocChampionItems[id].name );
//                    return;
//                }
//            });

        },

        show: function(){
        },

        hide: function(){
        }
}

function CHRule(type, faction, conditions) {  //class definition for rules and conditions
    this.type = type;
    this.faction = faction;
    if (conditions)
        this.conditions = conditions;
    else
        this.conditions = [];

    this.CHaddCondition = CHaddCondition;
    this.CHapplyRule    = CHapplyRule;
}

function CHcloneRule(rule) {
    this.type = rule.type;
    this.faction = rule.faction;
    this.conditions = [];
    if (rule.conditions) this.conditions = rule.conditions;

    this.CHaddCondition = CHaddCondition;
    this.CHapplyRule    = CHapplyRule;
}

function CHaddCondition(c) {
    this.conditions.push(c);
}

function CHapplyRule(id) {
    var champ_item = unsafeWindow.kocChampionItems[id];
    
    if (this.type != "any" && (champItemTypes[this.type] != champ_item.type)) return false;
    if (this.faction != "any" && (this.faction != champ_item.faction)) return false;
    for (r in this.conditions)
    {
        if (!this.conditions[r].CHcheckCondition(id)) return false;
    }
    return true;
}

function CHCondition(mustHave, number, effect, buffType, slots ) {
    this.mustHave = mustHave;
    this.number   = number;
    this.effect   = effect;
    this.buffType = buffType;
    this.slots    = slots;

    this.CHcheckCondition = CHcheckCondition;
}

function CHcheckCondition(id) {
    var numberFound  = 0;
    var effectsFound = false;
    // get card
    var champ_item = unsafeWindow.kocChampionItems[id];

    if (!champ_item) return false;

    // for loop for stat
    // count up occurances
    for (i in champ_item.effects) {
        var id = champ_item.effects[i].id;
        var card_effect = "";
        

        card_effect = unsafeWindow.g_js_strings.effects["name_" + id];

/*
        if ( +id > 200 )
        {
            card_effect = unsafeWindow.g_js_strings.effects["name_" + id];
        }
        else
        {
            card_effect = CM.thronestats.effects[id][1];
        }
*/
        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);
}

/** ********************************* Throne Salvage Tab ****************** **/
Tabs.throneSalvage = {
    tabOrder: 200,
    tabLabel: 'Salvage TR',
    tabDisabled: false,
    myDiv: null,
    timer: null,
    city: null,
    cityNum: 0,
    cardTypes: ['chair', 'table', 'window', 'banner', 'advisor', 'trophy', 'candelabrum', 'hero', 'statue', 'pet', 'tapestry', 'pillar'],  
    delItems: [],
    rowNum: 0,
    sTimer: null,
    delTimer: null,
    upgradeProfit: true,
    //salvageFailList: {},
    //maxFailures: 2,

    init: function (div) {
        var t = Tabs.throneSalvage;
        t.myDiv = div;

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV  id=trSalvage class=trStat>THRONE ROOM SALVAGER</div>';
        m += "<div id='trInfoArea'>";
        m += '</div>';

        m += '<table class="trTabPad trTable"><tr><td width=30%/><td width=35%/><td width=35%/></tr>';
        if (TRsalvageData.salvageActive == false) {
            m += '<tr><TD><div><INPUT id=trSalvagerPower type=button value="Salvager = OFF"/></div></td>';
        } else {
            m += '<tr><TD><div><INPUT id=trSalvagerPower type=button value="Salvager = ON"/></div></td>';
        }
        m += '<td><div> Keep all: <select id="trSalvageQuality">';
        m += '<option value="1">Common</option>';
        m += '<option value="2">Uncommon</option>';
        m += '<option value="3">Rare</option>';
        m += '<option value="4">Epic</option>';
        m += '<option value="5">Wondrous</option>';
        m += '</select> and higher</div></td>';

        m += '<td align=right>Keep the first <INPUT id=trSaveNum type=text size=3 maxlength=3 value="' + TRsalvageData.throneSaveNum + '"/> items</td>';
        m += "</tr></table><hr/>";

        m += "<div id='trRulesCreateSimple' class='trRuleCreate' style='display: block;'>";

        // rules definition
        m += '<TABLE class="trTabDef trTable" width=100% class=trTabPad style="padding-left: 10px;">';
        m += '<tr><td colspan=4><input type=button id="trSwitchToAdvanced" value="SWITCH TO ADVANCED"></td></tr>';
        m += '<tr><td>  <b>Define the TR items to keep: </b> </td>';

        m += '<td alight="left"><div><span>Faction: <select id="trFactionType">';
        m += '  <option value="any">Any</option>';
        m += '  <option value="fey">Fey</option>';
        m += '  <option value="briton">Briton</option>';
        m += '  <option value="druid">Druid</option>';
        m += '</select></span></div></td>';
        m += '<td alight="left"><div><span>Card type: <select id="trCardType">';
        m += '  <option value="any">Any</option>';
        for (i = 0; i < t.cardTypes.length; i++) {
            m += '  <option value="' + t.cardTypes[i] + '">' + t.cardTypes[i].capitalize() + '</option>';
        }
        m += '</select></span></div></td>';
        m += '<td align="right"><INPUT id=trAddRule type=button value="Create Rule"/></td>';
        m += '</tr></table>';
        m += '<TABLE  class="trTabPad trTable" width=100% id="trConditionTable"  style="padding-left: 5px;">';
        m += '<tr><td align=left colspan=1><INPUT id=trAddRow type=button value="Add Row"/></td>';
        m += '<td></td><td></td><td></td><td></td><td></td></tr>';
        m += '</table>';
        m += '</div>';

        m += "<div id='trRulesCreateAdvanced' class='trRuleCreate' style='display:none;'>";

        // rules definition
        m += '<TABLE class="trTabDef trTable" width=100% class=trTabPad style="padding-left: 10px;">';
        m += '<tr><td colspan=3 align=left><input type=button id="trSwitchToSimple" value="SWITCH TO SIMPLE"></td><td><input type=button id="trAdvancedReset" value="Reset"></tr>';
        m += '<tr><td colspan=4><center><b><font color=red>SPECIAL THANKS TO Gunvald Storheil FOR HIS SPREADSHEET, IT INSPIRED THIS FEATURE</font></b></center></td></tr>';
        m += '<tr><td>  <b>Define the TR items to keep: </b> </td>';

        m += '<td alight="left"><div><span>Faction: <select id="trFactionTypeAdvanced">';
        m += '  <option value="any">Any</option>';
        m += '  <option value="fey">Fey</option>';
        m += '  <option value="briton">Briton</option>';
        m += '  <option value="druid">Druid</option>';
        m += '</select></span></div></td>';
        m += '<td alight="left"><div><span>Card type: <select id="trCardTypeAdvanced">';
        m += '  <option value="any">Any</option>';
        m += '  <option value="chair">Chair</option>';
        m += '  <option value="table">Table</option>';
        m += '  <option value="window">Window</option>';
        m += '  <option value="banner">Banner</option>';
        m += '  <option value="advisor">Advisor</option>';
        m += '  <option value="trophy">Trophy</option>';
        m += '  <option value="candelabrum">Candelabrum</option>';
        m += '  <option value="hero">Hero</option>';
        m += '  <option value="statue">Statue</option>';
        m += '  <option value="pet">Pet</option>';
        m += '  <option value="tapestry">Tapestry</option>';
        m += '  <option value="pillar">Pillar</option>';
        m += '</select></span></div></td>';
        m += '<td align="right"><INPUT id=trAddRuleAdvanced type=button value="Create Rule"/></td>';
        m += '</tr></table>';
        m += '<center><TABLE  class="trTabPad trTable" id="trConditionTableAdvanced"  style="padding-left: 5px;">';
        m += '<tr>';
        m += '<td align=center width=20%>ROW 1</td>';
        m += '<td align=center width=20%>ROW 2</td>';
        m += '<td align=center width=20%>ROW 3</td>';
        m += '<td align=center width=20%>ROW 4</td>';
        m += '<td align=center width=20%>ROW 5</td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td width=20%><div><select style="max-width: 125px;" id="trRow1Advanced"></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id="trRow2Advanced"></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id="trRow3Advanced"></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id="trRow4Advanced"></select></div></td>';
        m += '<td width=20%><div><select style="max-width: 125px;" id="trRow5Advanced"></select></div></td>';
        m += '</tr>';
        m += '</table></center>';
        m += '</div>';


        m += '<hr/>';
        m += '<div id="trSalvStatus" style="text-align: center;" >Loading ... </div>';
        m += '<div id="trNumSalv" style="text-align: center;"></div>';
        m += '<hr/>';
        m += '<div class=trRulePane>';
        m += '<div align=center>Sort By Card Type: <select id=trSalvageSortCard>';
            m += '  <option value="0">--Select--</option>';
        for (i = 0; i < t.cardTypes.length; i++) {
            m += '  <option value="' + t.cardTypes[i] + '">' + t.cardTypes[i].capitalize() + '</option>';
        }
        m += '</select></div>';
        m += '<div align=center> <b> Salvager will keep items matching any of these rules </b></div>';
        m += '<div id=trRuleScroll style="position: static; width: 100%; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += "<div id='trRuleDisplay' >";
        m += '</div></div>';
        m += '<div align=center><table align=center width=100%><tr><td width=50%><input id=trButtonSaveItem type=button value="Save Rules"></td>';
        m += '<td width=50%><input id=trButtonLoadItem type=button value="Load Rules"><input id=trFileLoadItem type=file></td></tr></table></div>';
        m += '</div>';
        t.myDiv.innerHTML = m;

        Tabs.throneSalvage.displayNumberSalvaged();

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

        t.createRow();
        t.buildRuleDisplay();

        $('#trSalvageSortCard').change(function() { t.buildRuleDisplay(); });

        $('#trAdvancedReset').click(function() {
            var cardtype = document.getElementById('trCardTypeAdvanced');
            cardtype.selectedIndex = 0;
            clearAdvancedStats();
            setAdvancedStatsToAny();
        });

        function setAdvancedStatsToAny() {
            for (var i = 1; i < 6; i++) {
                var row = document.getElementById('trRow' + i + 'Advanced');
                row.options.add(new Option("none","None"));
                for (eff in unsafeWindow.cm.thronestats.effects) {
                    var effectName = unsafeWindow.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"));
            }
        }

        function clearAdvancedStats() {
            for (var i = 1; i < 6; i++) {
                var row = document.getElementById('trRow' + i + 'Advanced');
                row.innerHTML = "";
            }
        }

        function filterAdvancedStats(cardtype) {
            cardtype = cardtype || "any";

            if (cardtype == "any") {
                setAdvancedStatsToAny();
                return;
            }

            document.getElementById("trRow1Advanced").options.add(new Option("none", "none"));
            document.getElementById("trRow2Advanced").options.add(new Option("none", "none"));
            document.getElementById("trRow3Advanced").options.add(new Option("none", "none"));
            document.getElementById("trRow4Advanced").options.add(new Option("none", "none"));
            document.getElementById("trRow5Advanced").options.add(new Option("none", "none"));

            for (eff in unsafeWindow.cm.thronestats.effects) {
                var effectName = unsafeWindow.cm.thronestats.effects[eff][1];
                if (ThroneStatsGrid[cardtype][1][eff]) { document.getElementById("trRow1Advanced").options.add(new Option(effectName, effectName)); }
                if (ThroneStatsGrid[cardtype][2][eff]) { document.getElementById("trRow2Advanced").options.add(new Option(effectName, effectName)); }
                if (ThroneStatsGrid[cardtype][3][eff]) { document.getElementById("trRow3Advanced").options.add(new Option(effectName, effectName)); }
                if (ThroneStatsGrid[cardtype][4][eff]) { document.getElementById("trRow4Advanced").options.add(new Option(effectName, effectName)); }
                if (ThroneStatsGrid[cardtype][5][eff]) { document.getElementById("trRow5Advanced").options.add(new Option(effectName, effectName)); }
            }
        }

        setAdvancedStatsToAny();

        $('#trAddRuleAdvanced').click(function() { t.createAdvancedRule(); });

        $('#trCardTypeAdvanced').change(function() {
            var selectedValue = document.getElementById('trCardTypeAdvanced').value;
            clearAdvancedStats();
            if (selectedValue == "any") { 
                setAdvancedStatsToAny();
            } else {
                filterAdvancedStats(selectedValue);
            }
        });

        $('#trSwitchToAdvanced').click(function() {
            document.getElementById('trRulesCreateSimple').style.display = "none";
            document.getElementById('trRulesCreateAdvanced').style.display = "block";
        });

        $('#trSwitchToSimple').click(function() {
            document.getElementById('trRulesCreateSimple').style.display = "block";
            document.getElementById('trRulesCreateAdvanced').style.display = "none";
        });


        document.getElementById('trButtonSaveItem').addEventListener('click', function () {
            alert("WARNING: The file you're about to save will most likely need to be renamed to a .TXT file, OR opened with NOTEPAD");
            uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(TRsalvageData.ruleSet));
            newWindow = window.open(uriContent, 'file.txt');
        }, false);


        document.getElementById('trButtonLoadItem').addEventListener('click', function () {
            var fileInput = document.getElementById("trFileLoadItem");
            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;
                TRsalvageData.ruleSet = JSON.parse(output);
                TRsalvageData.salvageActive = false;
                clearInterval(Tabs.throneSalvage.sTimer);
                clearInterval(Tabs.throneSalvage.delTimer);
                Tabs.throneSalvage.deleting = false;
                TRsaveSalvageData();
                Tabs.throneSalvage.init(Tabs.throneSalvage.myDiv);
                alert('Throne Salvage Settings Now Loaded From File');
            };
            reader.readAsText(file);

        }, false);

        document.getElementById('trSaveNum').addEventListener('change', function () {
            TRsalvageData.throneSaveNum = parseInt(document.getElementById('trSaveNum').value);
            if (TRsalvageData.throneSaveNum < 0) TRsalvageData.throneSaveNum = 0;
            TRsaveSalvageData();
        }, false);
        document.getElementById('trSalvageQuality').addEventListener('click', function () { t.setSalvageLevel(this.value); }, false);
        document.getElementById('trSalvageQuality').value = TRsalvageData.minQuality;

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

        /* removing sizing restrictions

        $(document.querySelector("#trRuleScroll")).resizable({
        minWidth: 720,
        maxWidth: 1000,
        minHeight: 180,
        maxHeight: 700,
        stop: function(event, ui) {
        TRupgradeData.salvageH =  ui.size.height + 'px';
        TRupgradeData.salvageW =  ui.size.width  + 'px';
        TRsaveUpgradeData();
        }
        });

        $(document.querySelector("#trRuleScroll")).css('height', TRupgradeData.salvageH).css('width', TRupgradeData.salvageW);
        */
        if (TRsalvageData.upgradedToDelete.length > 0) {
            // some items were left over that need to be deleted 
            logit("Found " + TRsalvageData.upgradedToDelete.length + " upgraded items that need to be deleted.");

            for (k = 0; k < TRsalvageData.upgradedToDelete.length; k++) {
                var id = TRsalvageData.upgradedToDelete[k];
                // if the item is not longer in the inventory, remove the id
                if (!unsafeWindow.kocThroneItems[id]) {
                    logit("Removing item " + id + " from salvage list.");
                    TRsalvageData.upgradedToDelete.splice(k, 1); // Remove item from array
                    TRsaveSalvageData();
                    k--;
                }
            }

            // resume deleting things
            if (TRsalvageData.salvageActive) {
                t.delItems = TRsalvageData.upgradedToDelete;
                t.deleting = true;
                t.upgradeAndDelete();
            }
            else {
                // if the salvager is powered off, clear the list
                TRsalvageData.upgradedToDelete = [];
                TRsaveSalvageData();
            }
        }

        // 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();
    },

    tripOdometer: function () {
        TRsalvageData.numSalvagedItems2 = 0;
        var now = new Date();
        TRsalvageData.since = now.valueOf();
        TRsaveSalvageData();
        Tabs.throneSalvage.init(Tabs.throneSalvage.myDiv);
    },

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

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

        var sinceD = new Date(TRsalvageData.since);

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

        $(document.querySelector("#trNumSalv")).html('<div style="text-align: center;"> ' + addCommas(TRsalvageData.numSalvagedItems) + " items salvaged"
                    + ', ' + addCommas(TRsalvageData.numSalvagedItems2) + ' items since ' + since + rate +
            ' <input id="tripOdo" type=button value="<-- Reset" /> </div>');

        $(document.querySelector("#tripOdo")).click(function () {
            Tabs.throneSalvage.tripOdometer();
        });
    },

    createRow: function () {
        var t = Tabs.throneSalvage;
        var table = document.getElementById('trConditionTable');
        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 id='" + rowId + "sel1'> <option value='true'> </option> <option value='false'>NOT</option></select></td>";
        h += "<td> <select id='" + rowId + "sel2'>";
        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 id='" + rowId + "sel3'>";
        h += "</select></td>";
        h += "<td> <select id='" + rowId + "sel4'>";
        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 += "<td>";
        h += "  <input type=checkbox value='1' checked=true id='" + rowId + "slot1'/>1";
        h += "  <input type=checkbox value='2' checked=true id='" + rowId + "slot2'/>2";
        h += "  <input type=checkbox value='3' checked=true id='" + rowId + "slot3'/>3";
        h += "  <input type=checkbox value='4' checked=true id='" + rowId + "slot4'/>4";
        h += "  <input type=checkbox value='5' checked=true id='" + rowId + "slot5'/>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 + "sel3");
        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);
        var btn = $("<input type=button value='X'/>");
        $(btn).click(function () { t.removeRow(row); });
        $(c).append(btn);

        //t.setFullness();
    },

    setSalvageLevel: function (level) {
        TRsalvageData.minQuality = level;
        TRsaveSalvageData();
    },

    createAdvancedRule: function() {
        var t = Tabs.throneSalvage;
        t.readAdvancedRows();
        t.buildRuleDisplay();  
    },

    createRule: function () {
        var t = Tabs.throneSalvage;
        t.readRows();
        t.buildRuleDisplay();
    },

    buildRuleDisplay: function () {
        var t = Tabs.throneSalvage;

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

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

                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><INPUT id=trEditRule" + i + " type=button value='Edit' disabled/><br><INPUT id=trDelRule" + i + " type=button value='Delete' /></td>";
                innerM += '</tr>';
            }
            return innerM;
        }

        var rd = document.getElementById('trRuleDisplay');
        var sortType = document.getElementById('trSalvageSortCard').value; 


        if (sortType != "0") {
            var sortedDataSet = [];
            //var sortType = document.getElementById('chSalvageSortCard').value;
            for (var k = 0; k < TRsalvageData.ruleSet.length; k++) {
                if (sortType == TRsalvageData.ruleSet[k].type) {
                    sortedDataSet.unshift(TRsalvageData.ruleSet[k]);
                }else {
                    sortedDataSet.push(TRsalvageData.ruleSet[k]);
                }
            }
            rd.innerHTML = '<TABLE  width=100% class="trTabPad trTable">' + innerRuleDisplay(sortedDataSet);
            for (var j = 0; j < sortedDataSet.length; j++) {
                document.getElementById('trDelRule' + j).v1 = j;
                document.getElementById('trEditRule' + j).v1 = j;
                document.getElementById('trDelRule' + j).addEventListener('click', function () { t.deleteRule(this.v1, sortedDataSet); }, false);
                document.getElementById('trEditRule' + j).addEventListener('click', function () { t.editRule(this.v1, sortedDataSet); }, false);
            }
        } else {
            rd.innerHTML = '<TABLE  width=100% class="trTabPad trTable">' + innerRuleDisplay(TRsalvageData.ruleSet);
            for (var j = 0; j < TRsalvageData.ruleSet.length; j++) {
                document.getElementById('trDelRule' + j).v1 = j;
                document.getElementById('trEditRule' + j).v1 = j;
                document.getElementById('trDelRule' + j).addEventListener('click', function () { t.deleteRule(this.v1, TRsalvageData.ruleSet); }, false);
                document.getElementById('trEditRule' + j).addEventListener('click', function () { t.editRule(this.v1, TRsalvageData.ruleSet); }, false);
            }
        }


    },
    editRule: function (ruleIndex, sortedData)
    {
//        var t = Tabs.throneSalvage;
//        var rule = sortedData[ruleIndex];
//        $("#trSwitchToAdvanced").click();
//        //$("#trSwitchToSimple").click();
//        alert('rule.type = ' + rule.type + ' and rule.faction = ' + rule.faction);
    },

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

    updateTRTab: function () {
        $(document.querySelector("#trexecsalvage")).html("Salvage " + (TRsalvageData.salvageActive ? "ON" : "OFF"));
    },

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

        if (TRsalvageData.salvageActive == true) {
            var btn = document.getElementById('trSalvagerPower');
            TRsalvageData.salvageActive = false;
            btn.value = "Salvager = OFF";
            clearInterval(t.sTimer);
            clearInterval(t.delTimer);
            t.delItems = [];
            TRsalvageData.upgradedToDelete = [];
            t.deleting = false;
        } else {
            TRsalvageData.salvageActive = true;
            var btn = document.getElementById('trSalvagerPower');
            btn.value = "Salvager = ON";
            t.doSalvage();
            t.start();
        }
        TRsaveSalvageData();
        t.updateTRTab();
    },

    readAdvancedRows: function () {
        var t = Tabs.throneSalvage;
        var cType = document.getElementById('trCardTypeAdvanced').value;
        var faction = document.getElementById('trFactionTypeAdvanced').value;
        //var c = new TRCondition(true,1,
        var row1 = document.getElementById("trRow1Advanced");
        var row2 = document.getElementById("trRow2Advanced");
        var row3 = document.getElementById("trRow3Advanced");
        var row4 = document.getElementById("trRow4Advanced");
        var row5 = document.getElementById("trRow5Advanced");
        var conditions = [];
        for (var i = 1; i < 6; i++) {
            var row = document.getElementById("trRow" + 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 TRCondition(true, 1, effectName, buffDebuff, slots);
            conditions.push(c);
        }
        if ( conditions.length > 0 ) {
            var rule1 = new TRRule(cType, faction, conditions);
            t.addRule(rule1);
        }
    },

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

        var cType = document.getElementById('trCardType').value;
        var faction = document.getElementById('trFactionType').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 + "sel1");
                var s2 = document.getElementById(row.id + "sel2");
                var s3 = document.getElementById(row.id + "sel3");
                var s4 = document.getElementById(row.id + "sel4");

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

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

    removeRow: function (row) {
        var table = document.getElementById('trConditionTable');

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

    // add a new rule
    addRule: function (rule) {
        TRsalvageData.ruleSet.unshift(rule);
        TRsaveSalvageData();
    },

    start: function () {
        var t = Tabs.throneSalvage;
        if (TRsalvageData.salvageActive) {
            t.sTimer = setInterval(t.doSalvage, 1 * 60 * 1000);
        }
    },

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

        //t.setFullness();

        if (!TRsalvageData.salvageActive) {
            t.deleting = false;
            return;
        }

        if (t.deleting == true) {
            logit("Deleting not complete");
            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);
        }
        //t.setFullness();
    },

    //        setFullness : function () {
    //            // change the color on the throne button when full
    //            
    //            var num_items = unsafeWindow.Object.keys(unsafeWindow.kocThroneItems).length;  
    //            if (num_items > 10)
    //                $("a.buttonv2.throne").css('color', 'red');
    //            else 
    //                $("a.buttonv2.throne").css('color', 'black');
    //        },

    // 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.throneSalvage;

        var throneSaveNum = TRsalvageData.throneSaveNum;
        var countItem = 0;
        var retList = [];

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

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

            countItem++;

            // ignore these things
            if (throne_item.level != 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 <= throneSaveNum) continue;

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

            // check the rules
            if (t.applyRules(throne_item.id)) continue;

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

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

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

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

        if (!TRsalvageData.salvageActive || 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 (TRsalvageData.upgradeFirst && t.upgradeProfit) {

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

    removeItem: function (id, cityId, numStones) {

        var throne_item = unsafeWindow.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 unsafeWindow.kocThroneItems[id];
        CM.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
    },

    doDelete: function (id) {

        var t = Tabs.throneSalvage;
        if (!TRsalvageData.salvageActive || !t.deleting) {
            t.deleting = false;
            return;
        }

        //logit("deleting item: " + id);
        var item = unsafeWindow.kocThroneItems[id];
        if (item == null || !item) return;

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

        SalvageThroneItem(id);

//        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//        var num_city = pickAetherSalvageCity();
//        if (num_city < 0) {
//            num_city = +GeneralOptions.salvageCityNum;
//            logit(" cities full");
//            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(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
//            method: "post",
//            parameters: params,
//            loading: true,
//            onSuccess: function (transport) {
//                try {
//                    var rslt = eval("(" + transport.responseText + ")");
//                    //logit("Salvage: " + inspect(rslt,3,1));
//                    var throne_item = unsafeWindow.kocThroneItems[id];
//                    if (rslt.ok) {
//                        if (throne_item) SalvageLog('Deleted Throne Room item ' + throne_item.name);
//                        TRsalvageData.numSalvagedItems++;
//                        TRsalvageData.numSalvagedItems2++;
//                        TRsaveSalvageData();


//                        if (throne_item) {
//                            TRsalvageData.numSalvaged[throne_item.quality]++;
//                            TRsaveSalvageData();
//                            Tabs.throneSalvage.removeItem(id, Seed.cities[num_city][0], rslt.aetherstones);
//                        }

//                        Tabs.throneSalvage.displayNumberSalvaged();

//                        var sidx = TRsalvageData.upgradedToDelete.indexOf(id);
//                        if (sidx >= 0) {
//                            TRsalvageData.upgradedToDelete.splice(sidx, 1); // Remove item from array
//                            TRsaveSalvageData();
//                        }
//                    }
//                    else {
//                        logit("rslt: " + inspect(rslt, 3, 1));
//                        if (throne_item) Tabs.throneSalvage.setStatus('Unable to salvage item ' + throne_item.name);

//                        // store off the object id and record the number of failures.  If it fails too many times, skip it next time.
//                        //if ( !t.salvageFailList[id] ) 
//                        //   t.salvageFailList[id] = 1;
//                        //else
//                        //   t.salvageFailList[id]++;

//                        //logit("Salvage failed.  Current number of failures of item " + id +" is " + t.salvageFailList[id]);

//                        unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.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 {
//                        //logit("deletes done");
//                        t.deleting = false;
//                        t.setStatus('Salvaging complete.  Waiting for next cycle.');
//                        return;
//                    }
//                } catch (e) {
//                    logit("Delete exception: " + inspect(e, 3, 1));
//                    t.deleting = false;
//                }
//            },
//            onFailure: function () {
//                logit("failure case");
//                t.delIems = [];
//                t.deleting = false;
//                if (unsafeWindow.kocThroneItems[id])
//                    logit("salvage failed for item " + unsafeWindow.kocThroneItems[id].name);
//                unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
//                return;
//            }
//        });

    },

    forceSalvage: function (trId) {
        if (!confirm('Are you sure you would like to Salvage the selected item?')) return;
        trId = trId || false;
        if (!trId) return;
        var throne_item = unsafeWindow.kocThroneItems[trId];
        if (!throne_item) return;
        if (throne_item.jewel) {
            var city_num = pickAetherSalvageCity();
            var city_id = Seed.cities[city_num][0];
            Tabs.jewelOrganizer.removeJewel(city_id, trId);
        }
        SalvageThroneItem(trId);
        unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
    },

    show: function () {
    },

    hide: function () {
    }
}

function TRRule(type, faction, conditions) { //class definition for rules and conditions
    this.type = type;
    this.faction = faction;
    if (conditions)
        this.conditions = conditions;
    else
        this.conditions = [];

    this.TRaddCondition = TRaddCondition;
    this.TRapplyRule    = TRapplyRule;
}

function TRcloneRule(rule) {
    this.type = rule.type;
    this.faction = rule.faction;
    this.conditions = [];
    if (rule.conditions) this.conditions = rule.conditions;

    this.TRaddCondition = TRaddCondition;
    this.TRapplyRule    = TRapplyRule;
}

function TRaddCondition(c) {
    this.conditions.push(c);
}

function TRapplyRule(id) {
    var throne_item = unsafeWindow.kocThroneItems[id];

    if (this.type != "any" && (this.type != throne_item.type)) return false;
    if (this.faction != "any" && (this.faction != throne_item.faction)) return false;
    for (r in this.conditions) {
        if (!this.conditions[r].TRcheckCondition(id)) return false;
    }
    return true;
}

function TRCondition(mustHave, number, effect, buffType, slots ) {
    this.mustHave = mustHave;
    this.number   = number;
    this.effect   = effect;
    this.buffType = buffType;
    this.slots    = slots;

    this.TRcheckCondition = TRcheckCondition;
}

function TRcheckCondition(id) {
    var numberFound  = 0;
    var effectsFound = false;
    // get card
    var throne_item = unsafeWindow.kocThroneItems[id];

    if (!throne_item) return false;

    // for loop for stat
    // count up occurances
    for (i in throne_item.effects) {
        var card_effect = CM.thronestats.effects[throne_item.effects[i].id][1];
        var slotid = i.split("slot")[1];

        if (!this.slots[slotid-1]) continue;

        var eff = this.effect + " ";

        if (card_effect.indexOf(" Debuff") < 0) card_effect += " ";

        if (!card_effect.startsWith(eff)) continue;

        // special rule for Chance to Find Items 
        if ( (card_effect == "Chance to Find Items ") && (card_effect != 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);
}


/** ********************************* Throne Repair Tab ******************* **/
Tabs.throneRepair = {
    tabOrder: 900,
    tabLabel: 'Throne Repair',
    tabDisabled: false,
    repairId: 0,
    repairEnd: 0,
    timerH: null,
    clearTimerH: null,
    myDiv: null,

    repaint: function () {
        var t = Tabs.throneRepair;
        t.init(t.myDiv);
    },

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

        t.myDiv = div;

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=chOrganizer class=chStat>THRONE ROOM REPAIR</div>';

        m += '<TABLE width=100% id=trupdtable class=trTabPad>';

        m += '<tr><td align=center colspan=2><i><b><font color=red>(NOTE: Enabling this feature disables upgrader, you cannot have both running at the same time)</font></b></i></td></tr>';

        m += '<tr>';
        if (!TRrepairData.active) {
            m += '<TD width=50%><div><INPUT id=trRepairPower type=button value="Repair = OFF"/></div></td>';
        } else {
            m += '<TD width=50%><div><INPUT id=trRepairPower type=button value="Repair = ON"/></div></td>';
        }

        m += '<td width=50%><div id=trRepairAetherDisplay>' + displayCityAstone() + '</div></td></tr>';

        m += '<tr><td colspan=2><hr></td></tr>';

        m += '<tr align="center"><td colspan=2><div id=trRepairStatus class=indent25> <br> </div></td></tr>';
        m += '<tr align="center"><td colspan=2><div id=trLastRepairResult class=indent25> <br> </div></td></tr>';


        m += '<tr><td colspan=2><DIV id=trUpgrader class=trStat>REPAIR SPEEDUPS</div></td></tr>';
        m += '<tr><td colspan=2 align=center>';
        m += '<table width=100% cellpadding=0 cellspacing=0>'
        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=trRepairHourglassLevelSpecific ' + (TRrepairData.hourglassLevelSpecific ? "CHECKED" : "") + '>Only use hourglass for levels ';
        m += '<select id=trRepairHourglassLevel>';
        for (i = 1; i < OrganizerMaxTRLevel; i++) m += '<option value=' + i + '>+' + i + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=trRepairHourglassQualitySpecific ' + (TRrepairData.hourglassQualitySpecific ? "CHECKED" : "") + '>Only use hourglass for qualities ';
        m += '<select id=trRepairHourglassQuality>';
        m += '<option value="1">Common</option>';
        m += '<option value="2">Uncommon</option>';
        m += '<option value="3">Rare</option>';
        m += '<option value="4">Epic</option>';
        m += '<option value="5">Wondrous</option>';
        m += '</select> and higher</td>';
        m += '</tr>';

        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[1] + "'><input type=checkbox id=trRepairUseSH " + (TRrepairData.useSH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[1] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseSHLabel>" + unsafeWindow.ksoItems[1].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[2] + "'><input type=checkbox id=trRepairUseKH " + (TRrepairData.useKH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[2] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseKHLabel>" + unsafeWindow.ksoItems[2].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[3] + "'><input type=checkbox id=trRepairUseGH " + (TRrepairData.useGH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[3] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseGHLabel>" + unsafeWindow.ksoItems[3].count + "</div>)</div></td>";
        m += "</tr>";
        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[4] + "'><input type=checkbox id=trRepairUseMH " + (TRrepairData.useMH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[4] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseMHLabel>" + unsafeWindow.ksoItems[4].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[5] + "'><input type=checkbox id=trRepairUseAH " + (TRrepairData.useAH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[5] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseAHLabel>" + unsafeWindow.ksoItems[5].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[6] + "'><input type=checkbox id=trRepairUseWH " + (TRrepairData.useWH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[6] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseWHLabel>" + unsafeWindow.ksoItems[6].count + "</div>)</div></td>";
        m += "</tr>";
        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[7] + "'><input type=checkbox id=trRepairUseDH " + (TRrepairData.useDH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[7] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseDHLabel>" + unsafeWindow.ksoItems[7].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[8] + "'><input type=checkbox id=trRepairUseEH " + (TRrepairData.useEH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[8] + " (<div style='white-space:nowrap;display:inline-block;' id=trRepairUseEHLabel>" + unsafeWindow.ksoItems[8].count + "</div>)</div></td>";
        m += "<td/";
        m += "</tr>";
        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=trRepairOverrideSpeedUps ' + (TRrepairData.overrideSpeedUp ? "CHECKED" : "") + '>Override hourglasses by using ';
        m += '<select id=trRepairSpeedUp>';
        m += '<option value=0>None</option>';
        m += '<option value=1>Squires Hourglass</option>';
        m += '<option value=2>Knights Hourglass</option>';
        m += '<option value=3>Guineveres Hourglass</option>';
        m += '<option value=4>Morganas Hourglass</option>';
        m += '<option value=5>Arthurs Hourglass</option>';
        m += '<option value=6>Merlins Hourglass</option>';
        m += '<option value=7>Divine Hourglass</option>';
        m += '<option value=8>Epic Hourglass</option>';
        m += '</select> every time</td>';
        m += '</tr>';

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

        m += '<tr><td colspan=2><DIV class=trStat>REPAIR LIST</div></td></tr>';

        m += '<tr><td colspan=2>';

        m += '<TABLE width=100% id=trupdtable2 class=trTabPad>';
        m += '<tr><td colspan=2><div>Queue by Level: <select id="trRepairByLevel">';
        for (i = 1; i < OrganizerMaxTRLevel; i++) m += '<option value=' + i + '>+' + i + '</option>';
        m += '</select>&nbsp;<INPUT id=trRepairByLevelAdd type=button value="Add"/></td></tr>';

        m += '<tr><td colspan=2><div>Queue by Preset Tag: <select id="trRepairPresetTagList">';
        var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);

        var presetsList = "";
        for (i = 1; i < presetSlots + 1; i++) presetsList += '<option value="' + i + '">' + i + ' (' + TRpresetData.presetNames[i] + ')</option>';

        m += presetsList;
        m += "</select>&nbsp;<INPUT id=trRepairPresetTag type=button value='Add'/></td></tr>";

        m += '<tr><td><div style="max-width:90%;">Item: <select id="trRepairList" style="width: 80%;">';
        m += '</select></div></td>';

        m += "<td><div><INPUT id=trRepairAdd type=button value='Add'/>&nbsp;<INPUT id=trRepairAddAll type=button value='Add All'>&nbsp;<INPUT id=trRepairRefresh type=button value='Refresh List'></div></td></tr>";
        m += '</table>';
        m += '</td></tr>';
        m += '<tr><td colspan=2><hr></td></tr>';

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

        m += '<tr align=center><td><div><input style="float: left;" id=trClearR type=button value="Clear Queue"/></div></td><td><div><input style="float: right;" id=trClearFR type=button value="Clear Repaired"/></div></td></tr>';
        m += '</table>';

        m += '</div>';


        t.myDiv.innerHTML = m;

        $('#trRepairByLevelAdd').click(function () {
            var t = Tabs.throneRepair;
            var level = document.getElementById('trRepairByLevel').value;
            for (trId in unsafeWindow.kocThroneItems) {
                var throne_item = unsafeWindow.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                if (!throne_item.isBroken) continue;
                if (throne_item.level != level) continue;
                t.addQueue(trId);
            }
        });

        $('#trRepairPresetTag').click(function () {
            var t = Tabs.throneRepair;
            var presetTagNum = document.getElementById('trRepairPresetTagList').value;
            var presetTag = getPresetTRObject(parseInt(presetTagNum));
            for (var ptId in presetTag) {
                var throne_item = unsafeWindow.kocThroneItems[ptId];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.isBroken) t.addQueue(ptId);
            }
        });

        $('#trClearR').click(function () { t.deleteQueue(); });

        $('#trRepairRefresh').click(function () { t.populateListBox(); });

        $('#trClearFR').click(function () {
            var temp = [];
            while (TRrepairData.items.length > 0) {
                var trId = TRrepairData.items.pop();
                var throne_item = unsafeWindow.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.isBroken) temp.push(trId);
            }
            while (temp.length > 0) TRrepairData.items.push(temp.pop());
            TRrepairData.index = 0
            TRsaveRepairData();
            t.populateListBox();
            t.buildRepairDisplay();
        });

        $('#trRepairHourglassLevelSpecific').change(function () {
            TRrepairData.hourglassLevelSpecific = document.getElementById('trRepairHourglassLevelSpecific').checked;
            TRsaveRepairData();
            t.doAction();
        });

        $('#trRepairHourglassQualitySpecific').change(function () {
            TRrepairData.hourglassQualitySpecific = document.getElementById('trRepairHourglassQualitySpecific').checked;
            TRsaveRepairData();
            t.doAction();
        });

        $('#trRepairOverrideSpeedUps').change(function () {
            TRrepairData.overrideSpeedUp = document.getElementById('trRepairOverrideSpeedUps').checked;
            TRsaveRepairData();
            if (TRrepairData.overrideSpeedUp) t.doAction();
        });


        $('#trRepairUseWH').change(function () {
            TRrepairData.useWH = document.getElementById('trRepairUseWH').checked;
            TRsaveRepairData();
            if (TRrepairData.useWH) t.doAction();
        });

        $('#trRepairUseDH').change(function () {
            TRrepairData.useDH = document.getElementById('trRepairUseDH').checked;
            TRsaveRepairData();
            if (TRrepairData.useDH) t.doAction();
        });

        $('#trRepairUseEH').change(function () {
            TRrepairData.useEH = document.getElementById('trRepairUseEH').checked;
            TRsaveRepairData();
            if (TRrepairData.useEH) t.doAction();
        });

        $('#trRepairUseSH').change(function () {
            TRrepairData.useSH = document.getElementById('trRepairUseSH').checked;
            TRsaveRepairData();
            if (TRrepairData.useSH) t.doAction();
        });

        $('#trRepairUseKH').change(function () {
            TRrepairData.useKH = document.getElementById('trRepairUseKH').checked;
            TRsaveRepairData();
            if (TRrepairData.useKH) t.doAction();
        });

        $('#trRepairUseGH').change(function () {
            TRrepairData.useGH = document.getElementById('trRepairUseGH').checked;
            TRsaveRepairData();
            if (TRrepairData.useGH) t.doAction();
        });

        $('#trRepairUseMH').change(function () {
            TRrepairData.useMH = document.getElementById('trRepairUseMH').checked;
            TRsaveRepairData();
            if (TRrepairData.useMH) t.doAction();
        });

        $('#trRepairUseAH').change(function () {
            TRrepairData.useAH = document.getElementById('trRepairUseAH').checked;
            TRsaveRepairData();
            if (TRrepairData.useAH) t.doAction();
        });

        document.getElementById('trRepairSpeedUp').value = TRrepairData.useSpeedUp;
        document.getElementById('trRepairHourglassLevel').value = TRrepairData.hourglassLevel;
        document.getElementById('trRepairHourglassQuality').value = TRrepairData.hourglassQuality;

        $('#trRepairSpeedUp').change(function () {
            TRrepairData.useSpeedUp = document.getElementById('trRepairSpeedUp').value;
            TRsaveRepairData();
        });

        $('#trRepairHourglassLevel').change(function () {
            TRrepairData.hourglassLevel = document.getElementById('trRepairHourglassLevel').value;
            TRsaveRepairData();
            t.doAction();
        });

        $('#trRepairHourglassQuality').change(function () {
            TRrepairData.hourglassQuality = document.getElementById('trRepairHourglassQuality').value;
            TRsaveRepairData();
            t.doAction();
        });

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

        t.setStatus("Loading ....");

        $("#trRDiv").html('<div><table id="trRepair" class="trTabLined" /></div>');

        $("#trRepairAdd").click(function () { t.addQueue(); });

        $("#trRepairAddAll").click(function () { t.addAllQueue(); });

        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: " + unsafeWindow.kocThroneItems[t.repairId].name);
            if (TRrepairData.useSH || TRrepairData.useKH || TRrepairData.useGH || TRrepairData.useMH || TRrepairData.useAH || TRrepairData.useWH || TRrepairData.useDH || TRrepairData.useEH || (TRrepairData.overrideSpeedUp && TRrepairData.useSpeedUp > 0)) {
                var throneItem = unsafeWindow.kocThroneItems[t.repairId];
                var trQuality = throneItem.quality;
                var trLevel = throneItem.level;
                var useThoseSpeedups = true;
                if (TRrepairData.hourglassQualitySpecific && trQuality < TRrepairData.hourglassQuality) useThoseSpeedups = false;
                if (TRrepairData.hourglassLevelSpecific && trLevel < TRrepairData.hourglassLevel) useThoseSpeedups = false;
                if (useThoseSpeedups) {
                    //t.doingSpeedup = true;
                    setTimeout(function () { t.doSpeedup(); }, 2000);
                }
            }
            setTimeout(t.clearRepair, (repairTimeLeft + 1) * 1000);
            if (repairTimeLeft > 0) d += repairTimeLeft;
        }

        t.populateListBox();
        t.buildRepairDisplay();


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


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


    },

    deleteQueue: function () {
        var t = Tabs.throneRepair
        TRrepairData.items = [];
        TRsaveRepairData();
        t.populateListBox();
        t.buildRepairDisplay();
    },

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

    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 && TRrepairData.overrideSpeedUp && TRrepairData.useSpeedUp > 0) {

            t.speedup = TRrepairData.useSpeedUp;

        } else {

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.day25 && TRrepairData.useAH && unsafeWindow.ksoItems[8].count > 0) { t.speedup = 8; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour24 && TRrepairData.useAH && unsafeWindow.ksoItems[7].count > 0) { t.speedup = 7; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour15 && TRrepairData.useAH && unsafeWindow.ksoItems[6].count > 0) { t.speedup = 6; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour8 && TRrepairData.useAH && unsafeWindow.ksoItems[5].count > 0) { t.speedup = 5; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && TRrepairData.useMH && unsafeWindow.ksoItems[4].count > 0) { t.speedup = 4; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && TRrepairData.useGH && unsafeWindow.ksoItems[3].count > 0) { t.speedup = 3; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && TRrepairData.useKH && unsafeWindow.ksoItems[2].count > 0) { t.speedup = 2; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && TRrepairData.useSH && unsafeWindow.ksoItems[1].count > 0) { t.speedup = 1; }

        }

        switch (t.speedup) {
            case "1":
            case 1:
                secondsForRepair -= HOURGLASSES_TIME.minute1;
                divId = 'trRepairUseSHLabel';
                break;
            case "2":
            case 2:
                secondsForRepair -= HOURGLASSES_TIME.minute15;
                divId = 'trRepairUseKHLabel';
                break;
            case "3":
            case 3:
                secondsForRepair -= HOURGLASSES_TIME.hour1;
                divId = 'trRepairUseGHLabel';
                break;
            case "4":
            case 4:
                secondsForRepair -= HOURGLASSES_TIME.hour25;
                divId = 'trRepairUseMHLabel';
                break;
            case "5":
            case 5:
                secondsForRepair -= HOURGLASSES_TIME.hour8;
                divId = 'trRepairUseAHLabel';
                break;
            case "6":
            case 6:
                secondsForRepair -= HOURGLASSES_TIME.hour15;
                divId = 'trRepairUseWHLabel';
                break;
            case "7":
            case 7:
                secondsForRepair -= HOURGLASSES_TIME.hour24;
                divId = 'trRepairUseDHLabel';
                break;
            case "8":
            case 8:
                secondsForRepair -= HOURGLASSES_TIME.day25;
                divId = 'trRepairUseEHLabel';
                break;
        }

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

            if (secondsForRepair <= 0) {
                secondsForRepair = 0;
                endTime = startTime;
                t.clearTimerH = setTimeout(t.clearRepair, 1000);
                //t.buildRepairDisplay();
            } else {
                endTime = unixTime() + secondsForRepair;
                t.repairEnd = endTime;
                var n = new Date(t.repairEnd * 1000);
                var item = unsafeWindow.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.buildRepairDisplay();
                }
            }
            t.buildRepairDisplay();
            t.repairEnd = endTime;
            setTimeout(function () { t.doSpeedup(); }, 1000);
        }
    },

    selectNext: function () {

        //        if (TRrepairData.items.length > 0 && TRrepairData.index == -1) TRrepairData.index = 0;
        //        if (TRrepairData.index >= TRrepairData.items.length) TRrepairData.index = 0;
        //        if (TRrepairData.index < 0) TRrepairData.index = 0;

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

            var throne_item = unsafeWindow.kocThroneItems[TRrepairData.items[i]];
            if (throne_item == null || !throne_item) continue;
            if ((throne_item != null) && (throne_item.isBroken)) {
                TRrepairData.index = i;
                TRsaveRepairData();
                return;
            }
        }

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

        TRsaveRepairData();
    },

    doAction: function () {
        var t = Tabs.throneRepair;
        t.populateListBox();
        if (TRupgradeData.active) {
            t.setStatus('Waiting for upgrade tab to finish...');
            return;
        }

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

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

                    // set the index
                    t.selectNext();

                    if (TRrepairData.index < 0) {
                        t.setStatus("Reached end of queue.")
                        t.setResult("");
                        TRsaveRepairData();
                    } else {
                        var throne_item = unsafeWindow.kocThroneItems[TRrepairData.items[TRrepairData.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: " + unsafeWindow.kocThroneItems[t.repairId].name);
                    if (TRrepairData.useSH || TRrepairData.useKH || TRrepairData.useGH || TRrepairData.useMH || TRrepairData.useAH || TRrepairData.useWH || TRrepairData.useDH || TRrepairData.useEH || (TRrepairData.overrideSpeedUp && TRrepairData.useSpeedUp > 0)) {
                        var throneItem = unsafeWindow.kocThroneItems[t.repairId];
                        var trQuality = throneItem.quality;
                        var trLevel = throneItem.level;
                        var useThoseSpeedups = true;
                        if (TRrepairData.hourglassQualitySpecific && trQuality < TRrepairData.hourglassQuality) useThoseSpeedups = false;
                        if (TRrepairData.hourglassLevelSpecific && trLevel < TRrepairData.hourglassLevel) useThoseSpeedups = false;
                        if (useThoseSpeedups) {
                            //t.doingSpeedup = true;
                            setTimeout(function () { t.doSpeedup(); }, 2000);
                        }
                        //t.doSpeedup();
                        retryTime = 1;
                    }
                }
                unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
            } catch (e) {
                logit("do action exception");
                logit("exception: " + inspect(e, 3, 1));
            }
            // recycle
            clearTimeout(t.timerH);
            t.timerH = setTimeout(t.doAction, retryTime * 1000);
            t.buildRepairDisplay();
        }
    },

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

        if (iD == null) {
            var trId = $("#trRepairList").val();
        } else {
            var trId = iD;
        }

        if (trId == 0) return;


        var item_count = TRrepairData.items.length;

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

        TRrepairData.items.push(trId);
        TRsaveRepairData();
        t.populateListBox();
        t.buildRepairDisplay();
    },

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

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

    },

    populateListBox: function () {

        var repairList = $('#trRepairList');
        repairList.empty();
        repairList.append($('<option></option>').val("0").html("--Items--"));

        var item_count = TRrepairData.items.length;

        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.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 == TRrepairData.items[item_index]) {
                    foundIt = true;
                    break;
                }
            }
            if (!foundIt) {
                var optionText = throne_item.name;
                repairList.append($('<option></option>').val(trId).html(optionText));
            }
        }
    },

    deleteRepairItem: function (index) {
        // delete an item from the queue
        var t = Tabs.throneRepair;
        //var trId = TRrepairData.items[i];
        TRrepairData.items.splice(index, 1);
        TRsaveRepairData();
        t.populateListBox();
        t.buildRepairDisplay();
    },

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

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

        TRsaveRepairData();
        t.buildRepairDisplay();
    },

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

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

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

        TRsaveRepairData();
        t.buildRepairDisplay();

    },

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

        $("#trRepair").html("<table id='trRepair' width='100%' class=trTabPad/>");
        var totalRepairTime = t.calcRepairTime();

        var item_count = TRrepairData.items.length;

        if (totalRepairTime > 0) $("#trRepair").append("<caption><b><i>Total Repair Time (" + item_count + " items): " + repairTimeToText(totalRepairTime) + "</i></b></caption>");

        $("#trRepair").append("<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 trId = TRrepairData.items[item_index];

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

                var m = "<tr>";
                m += "<td align='center'><div><div id=trRepairRemove" + trId + " class=trremove/></div></td>";
                m += "<td align='center'><div class='trup' id=trRepairUpRow" + trId + " /><div class='trdown'  id=trRepairDownRow" + trId + " /></td>";
                m += "<td align='center'><div id=trRepairState" + trId + "></div></td>";
                m += "<td align='center' class=trRepairItemName><div id=trRepairItem" + trId + " >" + throne_item.name + "</div></td>";
                m += "</tr>";
                $("#trRepair").append(m);
            }

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

                var trId = TRrepairData.items[item_index];

                var throne_item = unsafeWindow.kocThroneItems[trId];

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

                $("#trRepairItem" + trId).mouseover(function (A) {
                    var throne_id = $(this).attr("id").split("trRepairItem")[1];
                    ShowThroneTooltip($(this), "chtrTooltip", throne_id);
                });

                $("#trRepairItem" + trId).mouseout(function (A) {
                    HideThroneTooltip("chtrTooltip");
                });


                $("#trRepairRemove" + trId).attr('v1', item_index);
                $("#trRepairRemove" + trId).click(function () { t.deleteRepairItem($(this).attr('v1')); });

                $("#trRepairUpRow" + trId).attr('v1', item_index);
                $("#trRepairUpRow" + trId).click(function () { t.moveRepairUpRow(+($(this).attr('v1'))); });

                $("#trRepairDownRow" + trId).attr('v1', item_index);
                $("#trRepairDownRow" + trId).click(function () { t.moveRepairDownRow(+($(this).attr('v1'))); });

                var throne_item = unsafeWindow.kocThroneItems[trId];
                if (!throne_item || !(throne_item.id)) {
                    $("#trRepairState" + trId).html("<div style='text-align:center'> ??</div>");
                } else if (!throne_item.isBroken) {
                    $("#trRepairState" + trId).addClass('trsuccess');
                } else if (throne_item.isBroken) {
                    if (trId == t.repairId) {
                        $("#trRepairState" + trId).addClass('trhammer');
                    } else {
                        $("#trRepairState" + trId).addClass('trbroken');
                    }
                }

            }
        }

        //        if (TRpresetData.noTooltips != true) {
        //            $(".trRepairItemName").mouseover(function (td) {

        //                td.stopPropagation();
        //                var theId = $(this).attr("id").split("trRepairItem")[1];

        //                if (!theId || theId == 0) {
        //                    return;
        //                }

        //                var throne_item;
        //                if (throne_item = unsafeWindow.kocThroneItems[theId]) {
        //                    unsafeWindow.cm.ThroneView.hoverItem(td, this, throne_item);
        //                    $("#kofcNewTooltipDiv").css('position', 'absolute');
        //                    $("#kofcNewTooltipDiv").css('left', ($("#org_dialog").position().left + 200) + 'px');
        //                    $("#kofcNewTooltipDiv").css('top', td.pageY - 330 + 'px');
        //                }
        //                else {
        //                    $("#kofcNewTooltipDiv").remove();
        //                }
        //            });

        //        }


    },

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

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

    updateTRTab: function () {
        $("#trexecrepair").html("Repair " + (TRrepairData.active ? "ON" : "OFF"));
    },

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

        var btn = document.getElementById('trRepairPower');
        if (TRrepairData.active == true) {
            TRrepairData.active = false;
            btn.value = "Repair = OFF";
            t.setStatus("Powered off");
            t.setResult("");

        } else {
            TRrepairData.active = true;
            btn.value = "Repair = ON";
            t.setStatus("Power on");
            t.setResult("");
            TRupgradeData.active = true; //make the ugprader on, so when you toggle it, it will turn off
            Tabs.throneUpgrader.togglePower(this);
            t.doAction();
        }

        if (TRrepairData.active == false) {

        }

        t.updateTRTab();
        TRsaveRepairData();

    },

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

        if (TRrepairData.active == false || rItem == 0 || unsafeWindow.kocThroneItems[rItem] == null) {
            logit("repair is turned off");
            return;
        }
        var theItem = unsafeWindow.kocThroneItems[rItem];

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

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                //logit("repair success");
                //logit("tport: " + inspect(transport,3,1));
                var rslt = eval("(" + transport.responseText + ")");
                //logit("rslt: " + inspect(rslt,3,1));
                if (rslt.ok) {
                    var item = unsafeWindow.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;
                    unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
                    t.clearTimerH = setTimeout(t.clearRepair, (secondsForRepair + 1) * 1000);
                    t.buildRepairDisplay();
                    if (TRrepairData.useSH || TRrepairData.useKH || TRrepairData.useGH || TRrepairData.useMH || TRrepairData.useAH || TRrepairData.useWH || TRrepairData.useDH || TRrepairData.useEH || (TRrepairData.overrideSpeedUp && TRrepairData.useSpeedUp > 0)) {
                        var throneItem = unsafeWindow.kocThroneItems[t.repairId];
                        var trQuality = throneItem.quality;
                        var trLevel = throneItem.level;
                        var useThoseSpeedups = true;
                        if (TRrepairData.hourglassQualitySpecific && trQuality < TRrepairData.hourglassQuality) useThoseSpeedups = false;
                        if (TRrepairData.hourglassLevelSpecific && trLevel < TRrepairData.hourglassLevel) useThoseSpeedups = false;
                        if (useThoseSpeedups) {
                            //t.doingSpeedup = true;
                            setTimeout(function () { t.doSpeedup(); }, 2000);
                        }
                        //setTimeout(function () { t.doSpeedup(); }, 1000);
                    }
                }
                else {
                    logit("Repair failed");
                    if (rslt.msg == "Item is not broken") {
                        unsafeWindow.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;
                    }
                    logit("result:" + inspect(rslt, 3, 1));
                }
                return;
            },
            onFailure: function (ttt) {
                logit("repair error");
                // 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;
                }
                logit("ttt: " + inspect(ttt, 3, 1));
                return;
            }
        });
        return;
    },

    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 && unsafeWindow.kocThroneItems[t.repairId] != null) {
                if (!unsafeWindow.kocThroneItems[t.repairId].isBroken) {
                    t.setStatus("Repair time complete.");
                    $("#trRepairState" + t.repairId).removeClass('trhammer');
                    $("#trRepairState" + t.repairId).addClass('trsuccess');
                } else {
                    unsafeWindow.kocThroneItems[t.repairId].isBroken = false;
                    unsafeWindow.kocThroneItems[t.repairId].brokenType = "";
                }
                t.repairId = 0;
            }

        }
        unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
        return timeUntilDone;
    },

    show: function () {
        Tabs.throneRepair.repaint();
    },

    hide: function () {

    }

}


/** ********************************* Throne Repair Tab ******************* **/
Tabs.champRepair = {
    tabOrder: 900,
    tabLabel: 'Champ Repair',
    tabDisabled: false,
    repairId: 0,
    repairEnd: 0,
    timerH: null,
    clearTimerH: null,
    myDiv: null,

    repaint: function () {
        var t = Tabs.champRepair;
        t.init(t.myDiv);
    },

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

        t.myDiv = div;

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=chOrganizer class=chStat>CHAMP HALL REPAIR</div>';

        m += '<TABLE width=100% id=trupdtable class=trTabPad>';

        m += '<tr><td align=center colspan=2><i><b><font color=red>(NOTE: Enabling this feature disables upgrader, you cannot have both running at the same time)</font></b></i></td></tr>';

        m += '<tr>';
        if (!CHrepairData.active) {
            m += '<TD width=50%><div><INPUT id=chRepairPower type=button value="Repair = OFF"/></div></td>';
        } else {
            m += '<TD width=50%><div><INPUT id=chRepairPower type=button value="Repair = ON"/></div></td>';
        }

        m += '<td width=50%><div id=chRepairAetherDisplay>' + displayCityAstone() + '</div></td></tr>';

        m += '<tr><td colspan=2><hr></td></tr>';

        m += '<tr align="center"><td colspan=2><div id=chRepairStatus class=indent25> <br> </div></td></tr>';
        m += '<tr align="center"><td colspan=2><div id=chLastRepairResult class=indent25> <br> </div></td></tr>';


        m += '<tr><td colspan=2><DIV id=trUpgrader class=trStat>REPAIR SPEEDUPS</div></td></tr>';
        m += '<tr><td colspan=2 align=center>';
        m += '<table width=100% cellpadding=0 cellspacing=0>'
        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=chRepairHourglassLevelSpecific ' + (CHrepairData.hourglassLevelSpecific ? "CHECKED" : "") + '>Only use hourglass for levels ';
        m += '<select id=chRepairHourglassLevel>';
        for (i = 1; i < OrganizerMaxCHLevel; i++) m += '<option value=' + i + '>+' + i + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=chRepairHourglassQualitySpecific ' + (CHrepairData.hourglassQualitySpecific ? "CHECKED" : "") + '>Only use hourglass for qualities ';
        m += '<select id=chRepairHourglassQuality>';
        m += '<option value="1">Common</option>';
        m += '<option value="2">Uncommon</option>';
        m += '<option value="3">Rare</option>';
        m += '<option value="4">Epic</option>';
        m += '<option value="5">Wondrous</option>';
        m += '</select> and higher</td>';
        m += '</tr>';

        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[1] + "'><input type=checkbox id=chRepairUseSH " + (CHrepairData.useSH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[1] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseSHLabel>" + unsafeWindow.ksoItems[1].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[2] + "'><input type=checkbox id=chRepairUseKH " + (CHrepairData.useKH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[2] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseKHLabel>" + unsafeWindow.ksoItems[2].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[3] + "'><input type=checkbox id=chRepairUseGH " + (CHrepairData.useGH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[3] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseGHLabel>" + unsafeWindow.ksoItems[3].count + "</div>)</div></td>";
        m += "</tr>";
        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[4] + "'><input type=checkbox id=chRepairUseMH " + (CHrepairData.useMH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[4] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseMHLabel>" + unsafeWindow.ksoItems[4].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[5] + "'><input type=checkbox id=chRepairUseAH " + (CHrepairData.useAH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[5] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseAHLabel>" + unsafeWindow.ksoItems[5].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[6] + "'><input type=checkbox id=chRepairUseWH " + (CHrepairData.useWH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[6] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseWHLabel>" + unsafeWindow.ksoItems[6].count + "</div>)</div></td>";
        m += "</tr>";
        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[7] + "'><input type=checkbox id=chRepairUseDH " + (TRrepairData.useDH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[7] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseDHLabel>" + unsafeWindow.ksoItems[7].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[8] + "'><input type=checkbox id=chRepairUseEH " + (TRrepairData.useEH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[8] + " (<div style='white-space:nowrap;display:inline-block;' id=chRepairUseEHLabel>" + unsafeWindow.ksoItems[8].count + "</div>)</div></td>";
        m += "<td/";
        m += "</tr>";
        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=chRepairOverrideSpeedUps ' + (CHrepairData.overrideSpeedUp ? "CHECKED" : "") + '>Override hourglasses by using ';
        m += '<select id=chRepairSpeedUp>';
        m += '<option value=0>None</option>';
        m += '<option value=1>Squires Hourglass</option>';
        m += '<option value=2>Knights Hourglass</option>';
        m += '<option value=3>Guineveres Hourglass</option>';
        m += '<option value=4>Morganas Hourglass</option>';
        m += '<option value=5>Arthurs Hourglass</option>';
        m += '<option value=6>Merlins Hourglass</option>';
        m += '<option value=7>Divine Hourglass</option>';
        m += '<option value=8>Epic Hourglass</option>';
        m += '</select> every time</td>';
        m += '</tr>';

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

        m += '<tr><td colspan=2><DIV class=trStat>REPAIR LIST</div></td></tr>';

        m += '<tr><td colspan=2>';

        m += '<TABLE width=100% id=trupdtable2 class=trTabPad>';
        m += '<tr><td colspan=2><div>Queue by Level: <select id="chRepairByLevel">';
        for (i = 1; i < OrganizerMaxCHLevel; i++) m += '<option value=' + i + '>+' + i + '</option>';
        m += '</select>&nbsp;<INPUT id=chRepairByLevelAdd type=button value="Add"/></td></tr>';

        m += '<tr><td colspan=2><div>Queue by Preset Tag: <select id="chRepairPresetTagList">';
        var presetsList = "";
        if (OrganizerMaxChampions != 0)  {
            for (var i = 1; i < OrganizerMaxChampions + 1; i++) {
                presetsList += '<option value="' + i + '">' + i + ' (' + CHpresetData.presetNames[i-1] + ')</option>';
            }
        }
        m += presetsList;
        m += "</select>&nbsp;<INPUT id=chRepairPresetTag type=button value='Add'/></td></tr>";

        m += '<tr><td><div style="max-width:90%;">Item: <select id="chRepairList" style="width: 80%;">';
        m += '</select></div></td>';

        m += "<td><div><INPUT id=chRepairAdd type=button value='Add'/>&nbsp;<INPUT id=chRepairAddAll type=button value='Add All'>&nbsp;<INPUT id=chRepairRefresh type=button value='Refresh List'></div></td></tr>";
        m += '</table>';
        m += '</td></tr>';
        m += '<tr><td colspan=2><hr></td></tr>';

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

        m += '<tr align=center><td><div><input style="float: left;" id=chClearR type=button value="Clear Queue"/></div></td><td><div><input style="float: right;" id=chClearFR type=button value="Clear Repaired"/></div></td></tr>';
        m += '</table>';

        m += '</div>';


        t.myDiv.innerHTML = m;

        $('#chRepairByLevelAdd').click(function () {
            var t = Tabs.champRepair;
            var level = document.getElementById('chRepairByLevel').value;
            for (chId in unsafeWindow.kocChampionItems) {
                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (champ_item == null || !champ_item) continue;
                if (champ_item.status != CM.CHAMPION.STATUS_BROKEN_UPGRADE && champ_item.status != CM.CHAMPION.STATUS_BROKEN_ENHANCE) continue;
                if (champ_item.level != level) continue;
                t.addQueue(chId);
            }
        });

        $('#chRepairPresetTag').click(function () {
            var t = Tabs.champRepair;
            var presetTagNum = document.getElementById('chRepairPresetTagList').value;
            var presetTag = getPresetCHObject(parseInt(presetTagNum));
            for (var ptId in presetTag) {
                var champ_item = unsafeWindow.kocChampionItems[ptId];
                if (champ_item == null || !champ_item) continue;
                if (champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE) t.addQueue(ptId);
            }
        });

        $('#chClearR').click(function () { t.deleteQueue(); });

        $('#chRepairRefresh').click(function () { t.populateListBox(); });

        $('#chClearFR').click(function () {
            var temp = [];
            while (CHrepairData.items.length > 0) {
                var chId = CHrepairData.items.pop();
                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (champ_item == null || !champ_item) continue;
                if (champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) temp.push(chId);
            }
            while (temp.length > 0) CHrepairData.items.push(temp.pop());
            CHrepairData.index = 0
            CHsaveRepairData();
            t.populateListBox();
            t.buildRepairDisplay();
        });

        $('#chRepairHourglassLevelSpecific').change(function () {
            CHrepairData.hourglassLevelSpecific = document.getElementById('chRepairHourglassLevelSpecific').checked;
            CHsaveRepairData();
            t.doAction();
        });

        $('#chRepairHourglassQualitySpecific').change(function () {
            CHrepairData.hourglassQualitySpecific = document.getElementById('chRepairHourglassQualitySpecific').checked;
            CHsaveRepairData();
            t.doAction();
        });

        $('#chRepairOverrideSpeedUps').change(function () {
            CHrepairData.overrideSpeedUp = document.getElementById('chRepairOverrideSpeedUps').checked;
            CHsaveRepairData();
            if (CHrepairData.overrideSpeedUp) t.doAction();
        });


        $('#chRepairUseWH').change(function () {
            CHrepairData.useWH = document.getElementById('chRepairUseWH').checked;
            CHsaveRepairData();
            if (CHrepairData.useWH) t.doAction();
        });

        $('#chRepairUseDH').change(function () {
            CHrepairData.useDH = document.getElementById('chRepairUseDH').checked;
            CHsaveRepairData();
            if (CHrepairData.useDH) t.doAction();
        });

        $('#chRepairUseEH').change(function () {
            CHrepairData.useEH = document.getElementById('chRepairUseEH').checked;
            CHsaveRepairData();
            if (CHrepairData.useEH) t.doAction();
        });

        $('#chRepairUseSH').change(function () {
            CHrepairData.useSH = document.getElementById('chRepairUseSH').checked;
            CHsaveRepairData();
            if (CHrepairData.useSH) t.doAction();
        });

        $('#chRepairUseKH').change(function () {
            CHrepairData.useKH = document.getElementById('chRepairUseKH').checked;
            CHsaveRepairData();
            if (CHrepairData.useKH) t.doAction();
        });

        $('#chRepairUseGH').change(function () {
            CHrepairData.useGH = document.getElementById('chRepairUseGH').checked;
            CHsaveRepairData();
            if (CHrepairData.useGH) t.doAction();
        });

        $('#chRepairUseMH').change(function () {
            CHrepairData.useMH = document.getElementById('chRepairUseMH').checked;
            CHsaveRepairData();
            if (CHrepairData.useMH) t.doAction();
        });

        $('#chRepairUseAH').change(function () {
            CHrepairData.useAH = document.getElementById('chRepairUseAH').checked;
            CHsaveRepairData();
            if (CHrepairData.useAH) t.doAction();
        });

        document.getElementById('chRepairSpeedUp').value = CHrepairData.useSpeedUp;
        document.getElementById('chRepairHourglassLevel').value = CHrepairData.hourglassLevel;
        document.getElementById('chRepairHourglassQuality').value = CHrepairData.hourglassQuality;

        $('#chRepairSpeedUp').change(function () {
            CHrepairData.useSpeedUp = document.getElementById('chRepairSpeedUp').value;
            CHsaveRepairData();
        });

        $('#chRepairHourglassLevel').change(function () {
            CHrepairData.hourglassLevel = document.getElementById('chRepairHourglassLevel').value;
            CHsaveRepairData();
            t.doAction();
        });

        $('#chRepairHourglassQuality').change(function () {
            CHrepairData.hourglassQuality = document.getElementById('chRepairHourglassQuality').value;
            CHsaveRepairData();
            t.doAction();
        });

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

        t.setStatus("Loading ....");

        $("#chRDiv").html('<div><table id="chRepair" class="trTabLined" /></div>');

        $("#chRepairAdd").click(function () { t.addQueue(); });

        $("#chRepairAddAll").click(function () { t.addAllQueue(); });

        var d = 2 + Math.random() * 8;
        logit("checking repair time")

        if (Seed.queue_champion == null) {
            for (kk in unsafeWindow.kocChampionItems) {
                var K = unsafeWindow.kocChampionItems[kk];
                if ((K.status == 2) || (K.status == 3)) {
                    logit("Object is being repaired, but there's no queue");
                    Seed.queue_champion = {};
                    Seed.queue_champion.start = parseInt(K.start);
                    Seed.queue_champion.end = parseInt(K.eta);
                    Seed.queue_champion.itemId = K.equipmentId;
                    break;
                }
            }
        }

        if (Seed.queue_champion != null && Seed.queue_champion.end != null) {
            var repairTimeLeft = Seed.queue_champion.end - unixTime();
            logit("time left: " + repairTimeLeft);
            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: " + unsafeWindow.kocChampionItems[t.repairId].name);

            if (CHrepairData.useAH || CHrepairData.useGH || CHrepairData.useKH || CHrepairData.useMH || CHrepairData.useSH || CHrepairData.useWH || CHrepairData.useDH || CHrepairData.useEH || (CHrepairData.overrideSpeedUp && CHrepairData.useSpeedUp > 0)) {
                var champItem = unsafeWindow.kocChampionItems[t.repairId];
                var chQuality = champItem.rarity;
                var chLevel = champItem.level;
                var useThoseSpeedups = true;
                if (CHrepairData.hourglassQualitySpecific && chQuality < CHrepairData.hourglassQuality) useThoseSpeedups = false;
                if (CHrepairData.hourglassLevelSpecific && chLevel < CHrepairData.hourglassLevel) useThoseSpeedups = false;
                if (useThoseSpeedups) {
                    t.doingSpeedup = true;
                    setTimeout(function () { t.doSpeedup(); }, 2000);
                }
            }

            setTimeout(t.clearRepair, (repairTimeLeft + 1) * 5000);
            if (repairTimeLeft > 0) d += repairTimeLeft;
        }

        t.populateListBox();
        t.buildRepairDisplay();


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


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


    },

    deleteQueue: function () {
        var t = Tabs.champRepair
        CHrepairData.items = [];
        CHsaveRepairData();
        t.populateListBox();
        t.buildRepairDisplay();
    },

//    calcRepairTime: function () {
//        var t = Tabs.champRepair
//        var item_count = CHrepairData.items.length;
//        var total_time = 0;
//        for (var item_index = 0; item_index < item_count; item_index++) {
//            var trId = CHrepairData.items[item_index];
//            var champItem = unsafeWindow.kocChampionItems[trId];
//            if (champItem == null || !champItem) continue;
//            var item_time = unsafeWindow.cm.thronestats.repairCostUpgrade[champItem.level].Time;
//            total_time += item_time;
//        }
//        return total_time;
//    },

    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 && CHrepairData.overrideSpeedUp && CHrepairData.useSpeedUp > 0) {

            t.speedup = CHrepairData.useSpeedUp;

        } else {

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.day25 && CHrepairData.useAH && unsafeWindow.ksoItems[8].count > 0) { t.speedup = 8; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour24 && CHrepairData.useAH && unsafeWindow.ksoItems[7].count > 0) { t.speedup = 7; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour15 && CHrepairData.useAH && unsafeWindow.ksoItems[6].count > 0) { t.speedup = 6; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour8 && CHrepairData.useAH && unsafeWindow.ksoItems[5].count > 0) { t.speedup = 5; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && CHrepairData.useMH && unsafeWindow.ksoItems[4].count > 0) { t.speedup = 4; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && CHrepairData.useGH && unsafeWindow.ksoItems[3].count > 0) { t.speedup = 3; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && CHrepairData.useKH && unsafeWindow.ksoItems[2].count > 0) { t.speedup = 2; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && CHrepairData.useSH && unsafeWindow.ksoItems[1].count > 0) { t.speedup = 1; }

        }

        switch (t.speedup) {
            case "1":
            case 1:
                secondsForRepair -= HOURGLASSES_TIME.minute1;
                divId = 'chRepairUseSHLabel';
                break;
            case "2":
            case 2:
                secondsForRepair -= HOURGLASSES_TIME.minute15;
                divId = 'chRepairUseKHLabel';
                break;
            case "3":
            case 3:
                secondsForRepair -= HOURGLASSES_TIME.hour1;
                divId = 'chRepairUseGHLabel';
                break;
            case "4":
            case 4:
                secondsForRepair -= HOURGLASSES_TIME.hour25;
                divId = 'chRepairUseMHLabel';
                break;
            case "5":
            case 5:
                secondsForRepair -= HOURGLASSES_TIME.hour8;
                divId = 'chRepairUseAHLabel';
                break;
            case "6":
            case 6:
                secondsForRepair -= HOURGLASSES_TIME.hour15;
                divId = 'chRepairUseWHLabel';
                break;
            case "7":
            case 7:
                secondsForRepair -= HOURGLASSES_TIME.hour24;
                divId = 'chRepairUseDHLabel';
                break;
            case "8":
            case 8:
                secondsForRepair -= HOURGLASSES_TIME.day25;
                divId = 'chRepairUseEHLabel';
                break;
        }

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

            if (secondsForRepair <= 0) {
                secondsForRepair = 0;
                endTime = startTime;
                t.clearTimerH = setTimeout(t.clearRepair, 1000);
                //t.buildRepairDisplay();
            } else {
                endTime = unixTime() + secondsForRepair;
                t.repairEnd = endTime;
                var n = new Date(t.repairEnd * 1000);
                var item = unsafeWindow.kocChampionItems[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.buildRepairDisplay();
                }
            }
            t.buildRepairDisplay();
            t.repairEnd = endTime;
            setTimeout(function () { t.doSpeedup(); }, 1000);
        }
    },

    selectNext: function () {

        //        if (TRrepairData.items.length > 0 && TRrepairData.index == -1) TRrepairData.index = 0;
        //        if (TRrepairData.index >= TRrepairData.items.length) TRrepairData.index = 0;
        //        if (TRrepairData.index < 0) TRrepairData.index = 0;

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

            var champ_item = unsafeWindow.kocChampionItems[CHrepairData.items[i]];
            if (champ_item == null || !champ_item) continue;
            if ((champ_item != null) && (champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE)) {
                CHrepairData.index = i;
                CHsaveRepairData();
                return;
            }
        }

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

        CHsaveRepairData();
    },

    doAction: function () {
        var t = Tabs.champRepair;
        t.populateListBox();
        if (CHupgradeData.active) {
            t.setStatus('Waiting for upgrade tab to finish...');
            return;
        }

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

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

                    // set the index
                    t.selectNext();

                    if (CHrepairData.index < 0) {
                        t.setStatus("Reached end of queue.")
                        t.setResult("");
                        CHsaveRepairData();
                    } else {
                        var champ_item = unsafeWindow.kocChampionItems[CHrepairData.items[CHrepairData.index]];
                        if (champ_item) {
                            t.repairId = champ_item.equipmentId;
                            t.doRepair(champ_item.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: " + unsafeWindow.kocChampionItems[t.repairId].name);
                    if (CHrepairData.useSH || CHrepairData.useKH || CHrepairData.useGH || CHrepairData.useMH || CHrepairData.useAH || CHrepairData.useWH || CHrepairData.useDH || CHrepairData.useEH || (CHrepairData.overrideSpeedUp && CHrepairData.useSpeedUp > 0)) {
                        var champItem = unsafeWindow.kocChampionItems[t.repairId];
                        var chQuality = champItem.rarity;
                        var chLevel = champItem.level;
                        var useThoseSpeedups = true;
                        if (CHrepairData.hourglassQualitySpecific && chQuality < CHrepairData.hourglassQuality) useThoseSpeedups = false;
                        if (CHrepairData.hourglassLevelSpecific && chLevel < CHrepairData.hourglassLevel) useThoseSpeedups = false;
                        if (useThoseSpeedups) {
                            //t.doingSpeedup = true;
                            setTimeout(function () { t.doSpeedup(); }, 2000);
                        }
                        //t.doSpeedup();
                        retryTime = 1;
                    }
                }
                //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
            } catch (e) {
                logit("do action exception");
                logit("exception: " + inspect(e, 3, 1));
            }
            // recycle
            clearTimeout(t.timerH);
            t.timerH = setTimeout(t.doAction, retryTime * 1000);
            t.buildRepairDisplay();
        }
    },

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

        if (iD == null) {
            var chId = $("#chRepairList").val();
        } else {
            var chId = iD;
        }

        if (chId == 0) return;


        var item_count = CHrepairData.items.length;

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

        CHrepairData.items.push(chId);
        CHsaveRepairData();
        t.populateListBox();
        t.buildRepairDisplay();
    },

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

        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item = unsafeWindow.kocChampionItems[chId];
            if (champ_item == null || !champ_item) continue;
            if (champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                t.addQueue(chId);
            }
        }

    },

    populateListBox: function () {

        var repairList = $('#chRepairList');
        repairList.empty();
        repairList.append($('<option></option>').val("0").html("--Items--"));

        var item_count = CHrepairData.items.length;

        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item = unsafeWindow.kocChampionItems[chId];
            if (champ_item == null || !champ_item) continue;
            if (champ_item.status != CM.CHAMPION.STATUS_BROKEN_ENHANCE && champ_item.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 == CHrepairData.items[item_index]) {
                    foundIt = true;
                    break;
                }
            }
            if (!foundIt) {
                var optionText = champ_item.name;
                repairList.append($('<option></option>').val(chId).html(optionText));
            }
        }
    },

    deleteRepairItem: function (index) {
        // delete an item from the queue
        var t = Tabs.champRepair;
        //var trId = TRrepairData.items[i];
        CHrepairData.items.splice(index, 1);
        CHsaveRepairData();
        t.populateListBox();
        t.buildRepairDisplay();
    },

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

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

        CHsaveRepairData();
        t.buildRepairDisplay();
    },

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

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

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

        CHsaveRepairData();
        t.buildRepairDisplay();

    },

    buildRepairDisplay: function () {
        var t = Tabs.champRepair;

        $("#chRepair").html("<table id='chRepair' width='100%' class=trTabPad/>");
        //var totalRepairTime = t.calcRepairTime();

        var item_count = CHrepairData.items.length;

        //if (totalRepairTime > 0) $("#trRepair").append("<caption><b><i>Total Repair Time (" + item_count + " items): " + repairTimeToText(totalRepairTime) + "</i></b></caption>");

        $("#chRepair").append("<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 = CHrepairData.items[item_index];

                if (chId == null) {
                    t.deleteRepairItem(item_index);
                    return;
                }
                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (champ_item == null || !champ_item) {
                    t.deleteRepairItem(item_index);
                    return;
                }

                var m = "<tr>";
                m += "<td align='center'><div><div id=chRepairRemove" + chId + " class=trremove/></div></td>";
                m += "<td align='center'><div class='trup' id=chRepairUpRow" + chId + " /><div class='trdown'  id=chRepairDownRow" + chId + " /></td>";
                m += "<td align='center'><div id=chRepairState" + chId + "></div></td>";
                m += "<td align='center' class=chRepairItemName><div id=chRepairItem" + chId + " >" + champ_item.name + "</div></td>";
                m += "</tr>";
                $("#chRepair").append(m);
            }

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

                var chId = CHrepairData.items[item_index];

                var champ_item = unsafeWindow.kocChampionItems[chId];

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

                $("#chRepairItem" + chId).mouseover(function (A) {
                    var champ_id = $(this).attr("id").split("chRepairItem")[1];
                    ShowChampTooltip($(this), "chtrTooltip", champ_id);
                });

                $("#chRepairItem" + chId).mouseout(function (A) {
                    HideChampTooltip("chtrTooltip");
                });


                $("#chRepairRemove" + chId).attr('v1', item_index);
                $("#chRepairRemove" + chId).click(function () { t.deleteRepairItem($(this).attr('v1')); });

                $("#chRepairUpRow" + chId).attr('v1', item_index);
                $("#chRepairUpRow" + chId).click(function () { t.moveRepairUpRow(+($(this).attr('v1'))); });

                $("#chRepairDownRow" + chId).attr('v1', item_index);
                $("#chRepairDownRow" + chId).click(function () { t.moveRepairDownRow(+($(this).attr('v1'))); });

                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (!champ_item || !(champ_item.equipmentId)) {
                    $("#chRepairState" + chId).html("<div style='text-align:center'> ??</div>");
                } else if (champ_item.status == 1) {
                    $("#chRepairState" + chId).addClass('trsuccess');
                } else if (champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE) {
                    if (trId == t.repairId) {
                        $("#chRepairState" + chId).addClass('trhammer');
                    } else {
                        $("#chRepairState" + chId).addClass('trbroken');
                    }
                }

            }
        }

        //        if (TRpresetData.noTooltips != true) {
        //            $(".trRepairItemName").mouseover(function (td) {

        //                td.stopPropagation();
        //                var theId = $(this).attr("id").split("trRepairItem")[1];

        //                if (!theId || theId == 0) {
        //                    return;
        //                }

        //                var throne_item;
        //                if (throne_item = unsafeWindow.kocThroneItems[theId]) {
        //                    unsafeWindow.cm.ThroneView.hoverItem(td, this, throne_item);
        //                    $("#kofcNewTooltipDiv").css('position', 'absolute');
        //                    $("#kofcNewTooltipDiv").css('left', ($("#org_dialog").position().left + 200) + 'px');
        //                    $("#kofcNewTooltipDiv").css('top', td.pageY - 330 + 'px');
        //                }
        //                else {
        //                    $("#kofcNewTooltipDiv").remove();
        //                }
        //            });

        //        }


    },

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

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

//    updateTRTab: function () {
//        $("#trexecrepair").html("Repair " + (TRrepairData.active ? "ON" : "OFF"));
//    },

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

        var btn = document.getElementById('chRepairPower');
        if (CHrepairData.active == true) {
            CHrepairData.active = false;
            btn.value = "Repair = OFF";
            t.setStatus("Powered off");
            t.setResult("");

        } else {
            CHrepairData.active = true;
            btn.value = "Repair = ON";
            t.setStatus("Power on");
            t.setResult("");
            CHupgradeData.active = true; //make the ugprader on, so when you toggle it, it will turn off
            Tabs.champUpgrader.togglePower(this);
            t.doAction();
        }

        if (CHrepairData.active == false) {

        }

        //t.updateTRTab();
        CHsaveRepairData();

    },

    doRepair: function (rItem) {
        var t = Tabs.champRepair;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        if (CHrepairData.active == false || rItem == 0 || unsafeWindow.kocChampionItems[rItem] == null) {
            logit("repair is turned off");
            return;
        }
        var theItem = unsafeWindow.kocChampionItems[rItem];

        params.action = "6";
        params.eid = rItem;
        params.cityId = unsafeWindow.currentcityid;
        params.gems = 0;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                //logit("repair success");
                //logit("tport: " + inspect(transport,3,1));
                var rslt = eval("(" + transport.responseText + ")");

                //logit("rslt: " + inspect(rslt,3,1));
                if (rslt.ok) {
                    //logit("ok");
                    var item = unsafeWindow.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();
                    //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocChampionItems);
                    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;
                    Tabs.champRepair.buildQueueDisplay();
                    // uW.cm.ThronePanelView.clickSpeedUp(item);
                }
                else {
                    logit("Repair failed");
                    logit("result:" + inspect(rslt, 3, 1));

                    // 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);

                        unsafeWindow.kocChampionItems[rItem].status = CM.CHAMPION.STATUS_INACTIVE;
                        t.clearRepair();
                    }

                }
                return;
            },
            onFailure: function (ttt) {
                logit("repair error");
                // 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;
                }
                logit("ttt: " + inspect(ttt, 3, 1));
                return;
            }
        });
        return;
    },
    clearRepair: function () {
        var t = Tabs.champRepair;
        var timeUntilDone = 0;

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

        if (timeUntilDone <= 0) {
            // logit("clearing repair");
            if (t.repairId != 0 && unsafeWindow.kocChampionItems[t.repairId] != null) {
                if (unsafeWindow.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_INACTIVE
                               || unsafeWindow.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_ACTIVE) {
                    t.setStatus("Repair time complete.");
                    $("#chRepairState" + t.repairId).removeClass('trhammer');
                    $("#chRepairState" + t.repairId).addClass('trsuccess');
                } else {
                    //unsafeWindow.kocChampionItems[t.repairId].status = 1;
                    //unsafeWindow.kocChampionItems[t.repairId].brokenType = "";
                }
                t.repairId = 0;
            }

        }
        //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
        return timeUntilDone;
    },

    show: function () {
        Tabs.champRepair.repaint();
    },

    hide: function () {

    }

}


/** ********************************* Champ Organizer Tab ***************** **/
Tabs.champOrganizerCompact = {
    tabOrder: 800,
    tabLabel: 'Champ Organizer',
    tabDisabled: false,
    myDiv: null,
    champCards: [],
    //itemLists: [],
    //itemTypes : { weapon: 0, shield: 1, armor: 2 /*, banner: 3, advisor: 4, trophy: 5, candelabrum: 6, hero: 7*/ },
    //itemTypes: [], //unsafeWindow.cm.CHAMPION.getEquipmentNames(),
    selectedItems: [],
    panelId: -1,
    panelType: "upgrade",
    panelNextLevel: 2,
    sortEffect: "none",
    sortType: "both",
    //factions: ['briton', 'fey', 'druid'],
    qualitiesNames: ['simple', 'common', 'uncommon', 'rare', 'epic', 'wondrous'],
    qualities: [0, 1, 2, 3, 4, 5],
    switchingPresets: false,

    init: function (div) {
        //if (GeneralOptions.WinIsOpen) CM.ChampionModalController.open();

        var t = Tabs.champOrganizerCompact;


        //t.itemTypes = unsafeWindow.cm.CHAMPION.getEquipmentNames();

        // setup the lists for weapons, armor, etc.
        t.fillLists();
        t.myDiv = div;

        // setup the tab
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=chOrganizer class=chStat>CHAMPION ORGANIZER</div>';
        var effects = [];


        for (i = 0; i < champItemEffects.length; i++) {
            var effectName = unsafeWindow.g_js_strings.effects["name_" + champItemEffects[i]];
            effectName = effectName.split(" Debuff")[0];
            if  (effects.indexOf(effectName) < 0) effects.push(effectName);
        }

        // header stuff
        // preset selector
        m += '<TABLE  width=100% class="chTabPad2 chTable">';

        m += '<tr>';

        m += '<td>';
        m += '<center><b>TYPES</b></center>';
        m += '<div id=chTypeFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 95px; overflow-y: scroll; background-color: white;">';
        for (ch in champItemTypes) m += '<INPUT id=chType' + ch + ' type=checkbox  CHECKED />' + ch + '<br />';
        m += '</div>';
        m += '<br>';
        m += '<center><input id=chUnselectAllTypes type=button value="Unselect All"></center>';
        m += '<center><input id=chSelectAllTypes type=button value="Select All"></center>';
        m += '</td>';

        m += '<td>';
        m += '<center><b>QUALITIES</b></center>';
        m += '<div id=chQualityFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 95px; overflow-y: scroll; background-color: white;">';
        for (q in t.qualities) {
            m += '<INPUT id=chQuality' + t.qualities[q] + ' type=checkbox  CHECKED />' + t.qualitiesNames[q].capitalize() + '<br />';
        }
        m += '<INPUT id=chUnique type=checkbox CHECKED />Uniques<br />';
        m += '</div>';
        m += '<br>';
        m += '<center><input id=chUnselectAllQualities type=button value="Unselect All"></center>';
        m += '<center><input id=chSelectAllQualities type=button value="Select All"></center>';
        m += '</td>';

        m += '<td rowspan=2>';
        m += '<div>Sort: <select id="chSortList"><option value="none">--Effect--</option>';
        for (k in effects) {
            m += '<option value="' + effects[k] + '">' + effects[k] + '</option>';
        }
        m += "</select>&nbsp;&nbsp;<select id='chSortType'>";
        m += "  <option value='both'>Either</option>";
        m += "  <option value='buff'>Buff</option>";
        m += "  <option value='debuff'>Debuff</option>";
        m += "</select></div>";
        m += '<div id="chScrollDiv" style="position: static; width: 100%; height: 300px; overflow-x: auto; overflow-y: auto;">';
        m += '<center>';
        m += '<div id="chTableDiv" style="width: 100%;">';
        m += '<TABLE id=chDisplayTable height=0% class=chTab><tr align=center valign=top></tr></table>';
        m += '</div>';
        m += '</center>';
        m += '</div>';

        m += '<INPUT id=chSortInactive type=checkbox ' + (CHupgradeData.sortInactive ? ' CHECKED' : '') + '/> Include Inactive ';
        m += '<INPUT id=chIgnoreBroken type=checkbox ' + (CHupgradeData.ignoreBroken ? ' CHECKED' : '') + '/> Ignore Broken';
        m += '</td>';
        m += '</tr>';

        m += '<tr>';

        m += '<td>';
        m += '<center><b>LEVELS</b></center>';
        m += '<div id=chLevelFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 95px; overflow-y: scroll; background-color: white;">';
        for (level = 0; level <= OrganizerMaxCHLevel; level++) {
            m += '<INPUT id=chLevel' + level + ' type=checkbox CHECKED />' + level + '<br /> ';
        }
        m += '</div>';
        m += '<br>';
        m += '<center><input id=chUnselectAllLevels type=button value="Unselect All"></center>';
        m += '<center><input id=chSelectAllLevels type=button value="Select All"></center>';
        m += '</td>';


        m += '<td/>';  //no jewels to filter by

        m += '<td/>';

        m += '</tr>';

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

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

        t.myDiv.innerHTML = m;
        t.paintTable();

        $(document.querySelector("#chPresetNum" + Seed.throne.activeSlot)).css('border-color', 'green')

        $(document.querySelector("#chSortList")).change(function () {
            t.sortEffect = $(this).val();
            t.show();
        });

        $(document.querySelector("#chLocalPresetList")).children("option").hover(
                    function (e) {
                        var target = $(e.target);
                        var id = target.val();
                        if (id >= 0) {
                            $("#preset_ch").html('<b>' + CHpresetData.ids[id] + ':</b> ' + CHpresetData.desc[id]);
                            $("#preset_ch").addClass('showit');
                        }
                    },
                    function () {
                        $(document.querySelector("#preset_ch")).removeClass('showit');
                    }

            );

        $("#chSortType").change(function () {
            t.sortType = $(this).val();
            t.show();
        });

        $("#chSortInactive").change(function () {
            t.show();
        });

        $("#chIgnoreBroken").change(function () {
            CHupgradeData.ignoreBroken = document.getElementById('chIgnoreBroken').checked;
            CHsaveUpgradeData();
            t.show();
        });

        $("#chPresetNumber").change(function () {
            CHpresetData.usePreset = $('#chPresetNumber').val();
            CHsavePresetData();
        });

        $("#chLevelFilterRow input").change(function () {
            t.show();
        });

        $("#chQualityFilterRow input").change(function () {
            t.show();
        });

        $("#chTypeFilterRow input").change(function () {
            t.show();
        });

        $("#chUnselectAllLevels").click(function () {
            for (level = 0; level <= OrganizerMaxCHLevel; level++) {
                var ch = document.getElementById("chLevel" + level);
                ch.checked = false;
            }
            t.show();
        });

        $("#chSelectAllLevels").click(function () {
            for (level = 0; level <= OrganizerMaxCHLevel; level++) {
                var ch = document.getElementById("chLevel" + level);
                ch.checked = true;
            }
            t.show();
        });

        $("#chUnselectAllQualities").click(function () {
            for (q in t.qualities) {
                var ch = document.getElementById("chQuality" + t.qualities[q]);
                ch.checked = false;
            }
            var ch = document.getElementById("chUnique");
            ch.checked = false;
            t.show();
        });

        $("#chSelectAllQualities").click(function () {
            for (q in t.qualities) {
                var ch = document.getElementById("chQuality" + t.qualities[q]);
                ch.checked = true;
            }
            var ch = document.getElementById("chUnique");
            ch.checked = true;
            t.show();
        });

        $("#chUnselectAllTypes").click(function () {
            for (chtype in champItemTypes) {
                var ch = document.getElementById("chType" + chtype);
                ch.checked = false;
            }
            t.show();
        });

        $("#chSelectAllTypes").click(function () {
            for (chtype in champItemTypes) {
                var ch = document.getElementById("chType" + chtype);
                ch.checked = true;
            }
            t.show();
        });

        $("#chSortList").val(CHupgradeData.sortSelected);
        $("#chSortType").val(CHupgradeData.buffSelected);
        t.sortEffect = CHupgradeData.sortSelected;
        t.sortType = CHupgradeData.buffSelected;

        t.show();


    },


    showNext: function () {
        var t = Tabs.champOrganizerCompact;

        if (t.panelNextLevel + 1 > OrganizerMaxCHLevel) return;

        var elemStatTitle = document.getElementsByClassName('upgEnhStatsTitle')[1];
        t.panelNextLevel++;
        elemStatTitle.innerHTML = "Level " + t.panelNextLevel + (t.panelNextLevel == OrganizerMaxCHLevel ? "" : " (<i>Next</i>)");

        var elemStatBody = document.getElementById('upgEnhStatsBodyTarget');

        var elemStatItems = elemStatBody.getElementsByTagName("li");

        var champ_item = unsafeWindow.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 = unsafeWindow.cm.ChampionManager.getEffect(effectLine, t.panelNextLevel);
            elemItem.innerHTML = effect.name + " " + effect.amount;
        }
    },

    setSwitchStatus: function (s) {
        $("#chSwitchStatus").html(s);
    },

//    addTagItem: function (itemId) {
//        CHpresetData.taggedItems[itemId] = true;
//        $("#" + itemId).prepend("<div class='tagBorderThrone'></div>");
//        //$("td#ch_card" + itemId).find("div.chbox").append("<div class='greenBorder2' style='border: 4px solid cyan; background: none; width: 228px; height: 255px;'></div>");
//        CHsavePresetData();
//    },

//    removeTagItem: function (itemId) {
//        if (CHpresetData.taggedItems[itemId]) {
//            delete CHpresetData.taggedItems[itemId];
//            $("#" + itemId).children(".tagBorderThrone").remove();
//            //$("td#ch_card" + itemId).find("div.greenBorder2").remove();
//            CHsavePresetData();
//        }
//    },


    equipItem: function (I, preset) {
        if (!I) return;
        unsafeWindow.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "ChampionRoom\\ChampionRoomServiceAjax",
            action: "equipItem",
            itemId: I.equipmentId,

            presetId: unsafeWindow.seed.champion.activeSlot
        }, function (u) {
            logit("result: " + inspect(u, 3, 1));
            if (u.ok === true) {
                unsafeWindow.cm.ChampionView.clickItemEquip(I);
                Tabs.champOrganizerCompact.show();
            } else {
                if (I && I.name) {
                    Tabs.champOrganizerCompact.setSwitchStatus("Unable to equip item " + I.name);
                } else {
                    Tabs.champOrganizerCompact.setSwitchStatus("Unable to equip item");
                }
                logit("Unable to equip item.");
                cm.ModalManager.alert({
                    button_text: unsafeWindow.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        unsafeWindow.Modal.hideModalAll();
                        unsafeWindow.cm.ModalManager.close()
                    }
                })
            }
        }, function (u) {
            logit("equip error");
            logit("e:" + inspect(u, 3, 1));

        })
    },

    // highlight the items the salvager will target
    //        testSalvage : function() {
    //            var t = Tabs.champOrganizerCompact;
    //            var s = Tabs.champSalvage;
    //            var toDelete = s.buildList(true);

    //            $('#chDelResults').html("<div> " + toDelete.length + " item(s) targeted for deletion</div>");

    //            for (i =0; i < toDelete.length; i++)
    //            {
    //                var item = unsafeWindow.kocChampionItems[toDelete[i]];
    //                
    //                if (item.equippedTo  )
    //                {
    //                    t.selectCard(toDelete[i], "orange");
    //                }
    //                else
    //                {
    //                    t.selectCard(toDelete[i], "red");
    //                }
    //            }
    //        },

    paintTable: function () {
        // fill in the table
        var t = Tabs.champOrganizerCompact;
        var m = "";
        var tab = document.getElementById('chDisplayTable');

        var item_count = t.champCards.length;

        for (var item_index = 0; item_index < item_count; item_index++) {
            m += '<TR><TD class="chcard" style="white-space: normal; padding: 0px;" id="' + t.champCards[item_index] + '" >';
            if (GeneralOptions.graphicalThrone) {
                m += BuildChampCardGraphical(unsafeWindow.kocChampionItems[t.champCards[item_index]], "chCardItem", "chOrganizerCardDisp");
            } else {
                m += BuildChampCardTextual(unsafeWindow.kocChampionItems[t.champCards[item_index]], "chCardItem", "chOrganizerCardDisp");
            }

            m += '</TD></TR>';

        }

        tab.innerHTML = m;

        $(".chcard").click(function (e) {
            var id = $(this).attr('id');
            CustomChampContextMenu(id, e.pageY-20, e.pageX-20, true, false);
        });


        if (!GeneralOptions.graphicalThrone) {
            $(".chOrganizerCardDisp").mouseover(function (A) {
                var champ_id = $(this).attr("id").split("chCardItem")[1];
                ShowChampTooltip($(this), "chtrTooltip", champ_id);
            });

            $(".chOrganizerCardDisp").mouseout(function (A) {
                HideChampTooltip("chtrTooltip");
            });
        }
        // add yellow and blue borders

        //$("div.chbox").removeClass("blueBorder2");
        //$("div.chbox").removeClass("yellowBorder2");

        //        for (ii in CHqueueData.list) {
        //            var list_item = CHqueueData.list[ii];
        //            if (!list_item) continue;
        //            if (list_item.status != "complete") {
        //                var id = list_item.item;

        //                if (list_item.action == "upgrade") $("td#ch_card" + id).find("div.chbox").addClass("blueBorder2");
        //                if (list_item.action == "enhance") $("td#ch_card" + id).find("div.chbox").addClass("yellowBorder2");
        //            }
        //        }

    },


    // fill the lists w/ the current TR items
    fillLists: function () {
        var t = Tabs.champOrganizerCompact;

        t.champCards = [];

        for (k in unsafeWindow.kocChampionItems) {
            var champ_item = unsafeWindow.kocChampionItems[k];

            // apply filters
            var unique = champ_item.unique;
            var level = champ_item.level;
            var quality = champ_item.rarity;
            var isBroken = (champ_item.status == 1 ? false : true);
            var chType = champItemNames[champ_item.type];

            if (($('#chIgnoreBroken').is(':checked')) && isBroken) continue;
            if (!($('#chUnique').is(':checked')) && unique) continue;
            if (!($('#chQuality' + quality).is(':checked')) && !unique) continue;
            if (!($('#chLevel' + level).is(':checked'))) continue;
            if (!($('#chType' + chType).is(':checked'))) continue;

            t.champCards.push(champ_item.equipmentId);
        }
    },

    // sort the lists in the desired order
    sortLists: function () {
        var t = Tabs.champOrganizerCompact;
        CHupgradeData.sortInactive = $("#chSortInactive").is(':checked');
        t.champCards.sort(function (item1, item2) {
            return t.sortValue(item2) - t.sortValue(item1);
        });
    },

    sortValue: function (itemId) {
        var t = Tabs.champOrganizerCompact;
        var retValue = 0.0;
        var item = unsafeWindow.kocChampionItems[itemId];
        for (e in item.effects) {
            try {

                //
                var N = item.effects[e];
                var id = item.effects[e].id;
                var effect = "";
                var quality = item.rarity;

                effect = unsafeWindow.g_js_strings.effects["name_" + id];
                //base = CM.CHAMPION["CHAMP_STAT_BASE_" + id];

                var S = CM.WorldSettings.getSettingAsObject("CE_EFFECTS_TIERS");
                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 && !CHupgradeData.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) {
                logit("Exception: " + inspect(e, 3, 1));

            }

        }
        return +retValue;
    },

    show: function () {

        //if (GeneralOptions.WinIsOpen) CM.ChampionModalController.open();

        var t = Tabs.champOrganizerCompact;
        t.fillLists();
        //t.sortLists2();
        t.sortLists();
        t.paintTable();
        //t.selectPreset(document.getElementById ('chPresetList').value);
    },

    hide: function () {
    }
}

Tabs.champOrganizer = {
    tabOrder: 800,
    tabLabel: 'Champ Organizer',
    tabDisabled: false,
    myDiv: null,
    itemLists: [],
    //itemTypes : { weapon: 0, shield: 1, armor: 2 /*, banner: 3, advisor: 4, trophy: 5, candelabrum: 6, hero: 7*/ },
    //itemTypes: [], //unsafeWindow.cm.CHAMPION.getEquipmentNames(),
    selectedItems: [],
    panelId: -1,
    panelType: "upgrade",
    panelNextLevel: 2,
    sortEffect: "none",
    sortType: "both",
    factions: ['briton', 'fey', 'druid'],
    switchingPresets: false,

    init: function (div) {
        //if (GeneralOptions.WinIsOpen) CM.ChampionModalController.open();

        var t = Tabs.champOrganizer;

        //t.itemTypes = unsafeWindow.cm.CHAMPION.getEquipmentNames();
        
        // setup the lists for weapons, armor, etc.
        t.fillLists();
        t.myDiv = div;

        // setup the tab
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=chOrganizer class=chStat>CHAMPION ORGANIZER</div>';
        var effects = [];

        for (i = 0; i < champItemEffects.length; i++) {
            var effectName = unsafeWindow.g_js_strings.effects["name_" + champItemEffects[i]];
            effectName = effectName.split(" Debuff")[0];
            if  (effects.indexOf(effectName) < 0) effects.push(effectName);
        }

        m += '<TABLE  width=100% class="chTabPad2 chTable">';
        m += '<tr width=100% align=center><td width=15%/><td width=30%/><td/></tr>';
        

        m += '<tr><td colspan=4><hr/></td></tr>';
        m += '<tr id=ch_factionFilterRow><td colspan=4 align=center> Factions: ';
        for (f in t.factions) {
            var faction = t.factions[f];
            m += '<INPUT id=chFaction' + faction + ' type=checkbox  CHECKED >' + faction.capitalize() + '</input> ';
        }

        m += '</td></tr>';
        m += '<tr id=ch_levelFilterRow><td colspan=4 align=center> Levels: ';

        for (level = 0; level <= OrganizerMaxCHLevel; level++) {
            m += '<INPUT id=chLevel' + level + ' type=checkbox CHECKED >' + level + '</input> ';
        }

        m += '</td></tr>';
        m += '<tr align=center><td colspan=2><div><span>Sort: <select id="chSortList">';

        m += '<option value="none">--Effect--</option>';
        for (k in effects) {
            m += '<option value="' + effects[k] + '">' + effects[k] + '</option>';
        }
        m += '</select></span></div></td>';

        m += "<td> <select id='chSortType'>";
        m += "  <option value='both'>Either</option>";
        m += "  <option value='buff'>Buff</option>";
        m += "  <option value='debuff'>Debuff</option>";
        m += "</select></td>";

        m += '<td><INPUT id=chSortInactive type=checkbox ' + (CHupgradeData.sortInactive ? ' CHECKED' : '') + '/> Include Inactive';


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

        m += '<div id="chScrollDiv" style="position: static; width: 100%; height: ' + OrganizerWindowHeight + '; overflow-x: auto; overflow-y: auto;">';

        m += "<div id='chTableDiv' style='width: 100%;'>";
        m += '<TABLE id=chDisplayTable width=100% height=0% class=chTab>';

        m += "<tr align=center valign=top>";

        for (ct in champItemTypes) m += "<th width=10%>" + ct + "</th>";

        m += "</tr>";

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

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

        t.myDiv.innerHTML = m;
        t.paintTable();

        $(document.querySelector("#chPresetNum" + Seed.throne.activeSlot)).css('border-color', 'green')

        $(document.querySelector("#chSortList")).change(function () {
            t.sortEffect = $(this).val();
            t.show();
        });

        $(document.querySelector("#chLocalPresetList")).children("option").hover(
                    function (e) {
                        var target = $(e.target);
                        var id = target.val();
                        if (id >= 0) {
                            $("#preset_ch").html('<b>' + CHpresetData.ids[id] + ':</b> ' + CHpresetData.desc[id]);
                            $("#preset_ch").addClass('showit');
                        }
                    },
                    function () {
                        $(document.querySelector("#preset_ch")).removeClass('showit');
                    }

            );

        $("#chSortType").change(function () {
            t.sortType = $(this).val();
            t.show();
        });

        $("#chSortInactive").change(function () {
            t.show();
        });

        $("#chPresetNumber").change(function () {
            CHpresetData.usePreset = $('#chPresetNumber').val();
            CHsavePresetData();
        });


        $("#ch_factionFilterRow input").change(function () {
            t.show();
        });

        $("#ch_levelFilterRow input").change(function () {
            t.show();
        });

        $("#chSortList").val(CHupgradeData.sortSelected);
        $("#chSortType").val(CHupgradeData.buffSelected);
        t.sortEffect = CHupgradeData.sortSelected;
        t.sortType = CHupgradeData.buffSelected;

        t.show();

    },


    showNext: function () {
        var t = Tabs.champOrganizer;

        if (t.panelNextLevel + 1 > OrganizerMaxCHLevel) return;

        var elemStatTitle = document.getElementsByClassName('upgEnhStatsTitle')[1];
        t.panelNextLevel++;
        elemStatTitle.innerHTML = "Level " + t.panelNextLevel + (t.panelNextLevel == OrganizerMaxCHLevel ? "" : " (<i>Next</i>)");

        var elemStatBody = document.getElementById('upgEnhStatsBodyTarget');

        var elemStatItems = elemStatBody.getElementsByTagName("li");

        var champ_item = unsafeWindow.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 = unsafeWindow.cm.ChampionManager.getEffect(effectLine, t.panelNextLevel);
            elemItem.innerHTML = effect.name + " " + effect.amount;
        }
    },

    setSwitchStatus: function (s) {
        $("#chSwitchStatus").html(s);
    },

    equipItem: function (I, preset) {
        if (!I) return;
        unsafeWindow.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "ChampionRoom\\ChampionRoomServiceAjax",
            action: "equipItem",
            itemId: I.equipmentId,

            presetId: unsafeWindow.seed.champion.activeSlot
        }, function (u) {
            logit("result: " + inspect(u, 3, 1));
            if (u.ok === true) {
                unsafeWindow.cm.ChampionView.clickItemEquip(I);
                Tabs.champOrganizer.show();
            } else {
                if (I && I.name) {
                    Tabs.champOrganizer.setSwitchStatus("Unable to equip item " + I.name);
                } else {
                    Tabs.champOrganizer.setSwitchStatus("Unable to equip item");
                }
                logit("Unable to equip item.");
                cm.ModalManager.alert({
                    button_text: unsafeWindow.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        unsafeWindow.Modal.hideModalAll();
                        unsafeWindow.cm.ModalManager.close()
                    }
                })
            }
        }, function (u) {
            logit("equip error");
            logit("e:" + inspect(u, 3, 1));

        })
    },

    
    paintTable: function () {
        // fill in the table
        var t = Tabs.champOrganizer;
        var m = "";
        var mm;
        var tab = document.getElementById('chDisplayTable');

        var ii = 0;
        for (ct in champItemTypes) {
            var jj = t.itemLists[ct].length;
            if (jj > ii) ii = jj;
        }

        m += "<tr align=center valign=top>";

        for (i in champItemTypes) m += "<th width=10%>" + i + "</th>";

        m += "</tr>";

        for (var k = 0; k < ii; k++) {
            mm = '<TR  align=left valign=top style="height: auto;">';
            for (i in champItemTypes) {
                var item = t.itemLists[i][k];
                var id = 0;
                if (item != null) id = item.equipmentId;
                mm += '<TD class="chcard" style="overflow: visible;  width:auto; height: 150px; border: 4px solid white;" id="' + id + '" >';
                if (GeneralOptions.graphicalThrone) {
                    mm += BuildChampCardGraphical(t.itemLists[i][k], "chCardItem", "chOrganizerCardDisp");
                } else {
                    mm += BuildChampCardTextual(t.itemLists[i][k], "chCardItem", "chOrganizerCardDisp");
                }
                mm += '</TD>';
            }
            mm += '</TR>';
            m += mm;
        }
        tab.innerHTML = m;
        // repair the height/width caused by the 2d transform


        $(".chcard").click(function (e) {
            var id = $(this).attr('id');
            CustomChampContextMenu(id, e.pageY-20, e.pageX-20, true, false);
        });


        if (!GeneralOptions.graphicalThrone) {
            $(".chOrganizerCardDisp").mouseover(function (A) {
                var champ_id = $(this).attr("id").split("chCardItem")[1];
                ShowChampTooltip($(this), "chtrTooltip", champ_id);
            });

            $(".chOrganizerCardDisp").mouseout(function (A) {
                HideChampTooltip("chtrTooltip");
            });
        }
        // add the large tooltip

        // add yellow and blue borders

        $("div.chbox").removeClass("blueBorder2");
        $("div.chbox").removeClass("yellowBorder2");
        $("div.chbox").children("div.greenBorder2").remove();

        for (ii in CHqueueData.list) {
            var list_item = CHqueueData.list[ii];
            if (!list_item) continue;
            if (list_item.status != "complete") {
                var id = list_item.item;

                if (list_item.action == "upgrade") $("td#ch_card" + id).find("div.chbox").addClass("blueBorder2");
                if (list_item.action == "enhance") $("td#ch_card" + id).find("div.chbox").addClass("yellowBorder2");
            }
        }

        for (ii in CHpresetData.taggedItems) {
            $("td#ch_card" + ii).find("div.chbox").append("<div class='greenBorder2' style='border: 4px solid cyan; background: none; width: 228px; height: 255px;'></div>");

        }


    },


    // fill the lists w/ the current TR items
    fillLists: function () {
        var t = Tabs.champOrganizer;

        for (i in champItemTypes) t.itemLists[i] = new Array;

        for (k in unsafeWindow.kocChampionItems) {
            var champ_item = unsafeWindow.kocChampionItems[k];

            // apply filters
            var faction = CM.CHAMPION.getFactionClasses(champ_item.faction);
            var level = champ_item.level;

            if (!($('#chFaction' + faction).is(':checked'))) continue;
            if (!($('#chLevel' + level).is(':checked'))) continue;

            // put the equipped items first
            if (champ_item.isEquipped)
                t.itemLists[champItemNames[champ_item.type]].unshift(champ_item);
            else
                t.itemLists[champItemNames[champ_item.type]].push(champ_item);
        }
    },

    // sort the lists in the desired order
    sortLists: function () {
        var t = Tabs.champOrganizer;
        CHupgradeData.sortInactive = $("#chSortInactive").is(':checked');
        for (i in t.itemLists) {
            t.itemLists[i].sort(function (item1, item2) {
                return t.sortValue(item2) - t.sortValue(item1);
            });
        }
    },

    sortValue: 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 = unsafeWindow.g_js_strings.effects["name_" + id];
                //base = CM.CHAMPION["CHAMP_STAT_BASE_" + id];

                var S = CM.WorldSettings.getSettingAsObject("CE_EFFECTS_TIERS");
                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 && !CHupgradeData.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) {
                logit("Exception: " + inspect(e, 3, 1));

            }

        }
        return +retValue;
    },

    // clear all the highlists
    clearHighlights: function () {
        var t = Tabs.champOrganizer;

        for (k in unsafeWindow.kocChampionItems) {
            var champ_item = unsafeWindow.kocChampionItems[k];
            t.selectCard(champ_item.equipmentId, "white");
        }

    },

    // highlight a card
    selectCard: function (itemId, color) {
        var t = Tabs.champOrganizer;
        var item = unsafeWindow.kocChampionItems[itemId];

        if (item) t.selectedItems[item.type] = itemId;
        td = document.getElementById("ch_card" + itemId);
        if (td) {
            td.style.borderColor = color;
        }
    },

    clearCards: function () {
        var t = Tabs.champOrganizer;
        for (k in t.selectedItems) {
            var td = document.getElementById("ch_card" + t.selectedItems[k]);
            if (td) {
                td.style.borderColor = "white";
            }
        }
        t.selectedItems = [];
    },

    // create the card to display

    show: function () {
        //if (GeneralOptions.WinIsOpen) CM.ChampionModalController.open();

        var t = Tabs.champOrganizer;
        t.fillLists();
        t.sortLists()
        t.paintTable();
        //t.selectPreset(document.getElementById ('chPresetList').value);
    },

    hide: function () {
    }
}

/** ********************************* Throne Organizer Tab **************** **/
Tabs.throneOrganizer = {
    tabOrder: 300,
    tabLabel: 'Organize TR',
    tabDisabled: false,
    myDiv: null,
    itemLists: [],
    itemTypes: { chair: 0, table: 1, window: 2, banner: 3, advisor: 4, trophy: 5, candelabrum: 6, hero: 7, statue: 8, pet: 9, tapestry: 10, pillar: 11 },  
    selectedItems: [],
    panelId: -1,
    panelType: "upgrade",
    panelNextLevel: 2,
    sortEffect: "none",
    sortType: "both",
    throneTypes: ['chair', 'table', 'window', 'banner', 'advisor', 'trophy', 'candelabrum', 'hero', 'statue', 'pet', 'tapestry', 'pillar'], 
    factions: ['briton', 'fey', 'druid'],
    qualitiesNames: ['simple', 'common', 'uncommon', 'rare', 'epic', 'wondrous', 'miraculous'],
    qualities: [0, 1, 2, 3, 4, 5, 6],
    jewels: ['cracked', 'flawed', 'cloudy', 'subdued', 'bright'],
    jewelsQualities: [1, 2, 3, 4, 5],
    switchingPresets: false,

    init: function (div) {
        var t = Tabs.throneOrganizer;
        // setup the lists for tables, chairs, etc.
        t.fillLists();
        t.myDiv = div;
        // setup the tab
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidthLarge + '; height: ' + OrganizerWindowHeightLarge + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=trOrganizer class=trStat>THRONE ROOM ORGANIZER</div>';
        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);
        }

        // header stuff
        // preset selector
        m += '<TABLE  width=100% class="trTabPad2 trTable">';
        m += '<tr width=100% align=center><td width=15%/><td width=30%/><td/></tr>';


        m += '<tr><td colspan=4 width=100%>';
        m += '<div width=100% id=localPresets style="display: ';
        if (GeneralOptions.localPresetHidden) {
            m += 'none;';
        } else {
            m += 'block;';
        }
        m += '"><table width=100%><tr width=100% align=center><td width=15%/><td width=30%/><td/></tr>';



        m += '<tr><td><div><span>View preset: </td><td><select id="TRPresetList">';
        m += '<option value="0">--Presets--</option>';

        for (k = 1; k <= Seed.throne.slotNum; k++) {
            m += '<option value="' + k + '"> Preset:  ' + k + '</option>';
        }
        for (k = 0; k < TRpresetData.num_presets; k++) {
            if (TRpresetData.ids[k])
                m += '<option value="local' + k + '"> Local:  ' + TRpresetData.ids[k] + '</option>';
            else
                m += '<option value="local' + k + '"> Local:  ' + String.fromCharCode(65 + k) + '</option>';
        }

        m += '</select></span></div></td>';
        m += '</tr>';

        m += '<tr  width=100% ><td colspan=1><span style="width: 130px; float: left; margin-top: 4px;  margin-right: 4px;"> Switch to preset: </span>';
        m += '</td><td colspan=3 width=450px>';
        for (a = 1; a <= Seed.throne.slotNum; a++) {
            m += '<a style="font-family: serif; width: 25px;" class="button20 loadGPreset"  id=trPresetNum' + a + ' > <span> ' + a + ' </span></a>';
        }
        m += '</td></tr>';

        if (TRpresetData.num_presets > 0) {
            m += '<div id="preset_tt"> <b>: </b> </div></a>';
            m += '<tr width=100%><td colspan=1><span style="width: 130px; float: left; margin-top: 4px;  margin-right: 4px;"> Local preset: </span>';
            m += '</td><td colspan=3>';

            m += '<select id="trLocalPresetList" style="float: left;">';

            m += '<option value="-1">--Preset--</option>';
            for (a = 0; a < TRpresetData.num_presets; a++) {
                m += '<option value="' + a + '">' + TRpresetData.ids[a] + '</option>';
            }
            m += '</select>';
            m += '<a style=" font-family: serif; margin-left: 10px;" class="button20" id=trLoad><span>Load</span></a>';
            m += '<a style=" font-family: serif; margin-left: 5px;" class="buttonDown20" id=trSave><span>Save</span></a>';
            m += '<span style="float: left; margin-top: 4px;  margin-right: 4px; margin-left: 10px;">';
            if (TRpresetData.num_presets > 0) {
                m += "Switch to slot <INPUT id=trPresetNumber type=text size=2 maxlength=2 value='" + parseInt(TRpresetData.usePreset) + "' </input> when loading";
            }
            m += "</span></td></tr>";
        }

        m += '<tr align=center><td colspan=4><div id=trSwitchStatus></div></td></tr>';

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



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

        m += '<tr><td colspan=4 align=center><table cellspacing=0 cellpadding=0>';

        m += '<tr><td align=center><b>Types</td><td align=center><b>Factions</td><td align=center><b>Qualities</td><td align=center><b>Levels</td><td align=center><b>Jewels</td></tr>';
        m += '<tr>';
        m += '<td><div id=throneTypeFilterRow style="float: left; width: 150px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (tr in t.throneTypes) {
            var throne = t.throneTypes[tr];
            m += '<INPUT id=trThroneType' + throne + ' type=checkbox  CHECKED />' + throne.capitalize() + '<br />';
        }
        m += '</div></td>';

        m += '<td><div id=factionFilterRow style="float: left; width: 100px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (f in t.factions) {
            var faction = t.factions[f];
            m += '<INPUT id=trFaction' + faction + ' type=checkbox  CHECKED />' + faction.capitalize() + '<br />';
        }
        m += '</div></td>';

        m += '<td><div id=qualityFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (q in t.qualities) {
            m += '<INPUT id=trQuality' + t.qualities[q] + ' type=checkbox  CHECKED />' + t.qualitiesNames[q].capitalize() + '<br />';
        }
        m += '<INPUT id=trUnique type=checkbox CHECKED />Uniques<br />';
        m += '</div></td>';

        m += '<td><div id=levelFilterRow style="float: left; width: 100px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        for (level = 0; level <= OrganizerMaxTRLevel; level++) {
            m += '<INPUT id=trLevel' + level + ' type=checkbox CHECKED />' + level + '<br /> ';
        }
        m += '</div></td>';

        m += '<td><div id=jewelFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 105px; overflow-y: scroll; background-color: white;">';
        m += '<INPUT id=trNoJewel type=checkbox CHECKED />No Jewel<br />';
        for (j in t.jewels) {
            m += '<INPUT id=trJewel' + t.jewelsQualities[j] + ' type=checkbox CHECKED />' + t.jewels[j].capitalize() + '<br /> ';
        }
        m += '</div></td>';


        m += '</tr>';
        m += '<tr>';
        m += '<td align=center><input id=unselectAllTypes type=button value="Unselect All"></td>';
        m += '<td align=center></td>';
        m += '<td align=center><input id=unselectAllQualities type=button value="Unselect All"></td>';
        m += '<td align=center><input id=unselectAllLevels type=button value="Unselect All"></td>';
        m += '<td align=center><input id=unselectAllJewels type=button value="Unselect All"></td>';
        m += '</tr>';
        m += '<tr>';
        m += '<td align=center><input id=selectAllTypes type=button value="Select All"></td>';
        m += '<td align=center></td>';
        m += '<td align=center><input id=selectAllQualities type=button value="Select All"></td>';
        m += '<td align=center><input id=selectAllLevels type=button value="Select All"></td>';
        m += '<td align=center><input id=selectAllJewels type=button value="Select All"></td>';
        m += '</tr>';

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

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

        m += '<tr align=center><td colspan=2><div><span>Sort: <select id="trSortList">';

        m += '<option value="none">--Effect--</option>';
        for (k in effects) {
            m += '<option value="' + effects[k] + '">' + effects[k] + '</option>';
        }
        m += '</select></span></div></td>';

        m += "<td> <select id='trSortType'>";
        m += "  <option value='both'>Either</option>";
        m += "  <option value='buff'>Buff</option>";
        m += "  <option value='debuff'>Debuff</option>";
        m += "</select></td>";

        m += '<td><INPUT id=trSortInactive type=checkbox ' + (TRupgradeData.sortInactive ? ' CHECKED' : '') + '/> Include Inactive ';
        m += '<INPUT id=trIgnoreBroken type=checkbox ' + (TRupgradeData.ignoreBroken ? ' CHECKED' : '') + '/> Ignore Broken</td></tr>';

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

        m += '<div id="trScrollDiv" style="position: static; width: 100%; height: ' + OrganizerWindowHeight + '; overflow-x: auto; overflow-y: auto;">';

        var ii = Math.max(t.itemLists['chair'].length, t.itemLists['table'].length, t.itemLists['window'].length, t.itemLists['banner'].length, t.itemLists['advisor'].length, t.itemLists['trophy'].length, t.itemLists['candelabrum'].length, t.itemLists['hero'].length, t.itemLists['statue'].length, t.itemLists['pet'].length, t.itemLists['tapestry'].length, t.itemLists['pillar'].length); 

        m += "<div id='trTableDiv' style='width: 100%;'>";
        m += '<TABLE id=trDisplayTable height=0% class=trTab>';
        m += "<tr align=center valign=top>";
        for (tr in t.throneTypes) {
            var throne = t.throneTypes[tr];
            m += '<th width=' + OrganizerHeaderSize + '>' + throne.capitalize() + '</th> ';
        }
        m += "</tr>";
        m += '</table></div>';
        m += '</div>';
        m += '</div>';

        t.myDiv.innerHTML = m;
        t.paintTable();

        /* remove resize restrictions
        $(document.querySelector("#trScrollDiv")).resizable({
        minWidth: 710,
        maxWidth: 900,
        minHeight: 180,
        maxHeight: 560,
        maxHeight: 1000,
        stop: function (event, ui) {
        TRupgradeData.organizeH = ui.size.height + 'px';
        TRupgradeData.organizeW = ui.size.width + 'px';
        TRsaveUpgradeData();
        }
        });
        */
        $("#TRPresetList").click(function () { t.selectPreset($(this).val()); });
        // $("#testSalvage").click(function () { t.testSalvage(); });

        // default to highlight the active preset
        document.getElementById('TRPresetList').value = Seed.throne.activeSlot;
        t.selectPreset(Seed.throne.activeSlot);

        $("a.loadGPreset").css('border-color', 'transparent');

        $("#trPresetNum" + Seed.throne.activeSlot).css('border-color', 'green')

        $("#trSortList").change(function () {
            t.sortEffect = $(this).val();
            t.show();
        });

        $("#trLocalPresetList").children("option").hover(
                    function (e) {
                        var target = $(e.target);
                        var id = target.val();
                        if (id >= 0) {
                            $("#preset_tt").html('<b>' + TRpresetData.ids[id] + ':</b> ' + TRpresetData.desc[id]);
                            $("#preset_tt").addClass('showit');
                        }
                    },
                    function () {
                        $(document.querySelector("#preset_tt")).removeClass('showit');
                    }

            );

        $("#trSortType").change(function () {
            t.sortType = $(this).val();
            t.show();
        });

        $("#trSortInactive").change(function () {
            t.show();
        });

        $("#trIgnoreBroken").change(function () {
            TRupgradeData.ignoreBroken = document.getElementById('trIgnoreBroken').checked;
            TRsaveUpgradeData();
            t.show();
        });

        $("#trPresetNumber").change(function () {
            TRpresetData.usePreset = $('#trPresetNumber').val();
            TRsavePresetData();
        });

        $(".loadGPreset").click(function () {
            var id = $(this).attr('id');
            processPresetClick(+id.split("trPresetNum")[1]);
        });

        $(".loadPreset").click(function () {
            var id = $(this).attr('id');
            Tabs.throneOrganizer.loadLocalPreset(+id.split("trLoad")[1]);
        });

        $("#unselectAllQualities").click(function () {
            for (q in t.qualities) {
                var ch = document.getElementById("trQuality" + t.qualities[q]);
                ch.checked = false;
            }
            var ch = document.getElementById("trUnique");
            ch.checked = false;
            t.show();
        });

        $("#selectAllQualities").click(function () {
            for (q in t.qualities) {
                var ch = document.getElementById("trQuality" + t.qualities[q]);
                ch.checked = true;
            }
            var ch = document.getElementById("trUnique");
            ch.checked = true;
            t.show();
        });


        $("#unselectAllTypes").click(function () {
            for (tr in t.throneTypes) {
                var ch = document.getElementById("trThroneType" + t.throneTypes[tr]);
                ch.checked = false;
            }
            t.show();
        });

        $("#selectAllTypes").click(function () {
            for (tr in t.throneTypes) {
                var ch = document.getElementById("trThroneType" + t.throneTypes[tr]);
                ch.checked = true;
            }
            t.show();
        });

        $("#unselectAllJewels").click(function () {
            for (j in t.jewelsQualities) {
                var ch = document.getElementById("trJewel" + t.jewelsQualities[j]);
                ch.checked = false;
            }
            var ch = document.getElementById('trNoJewel');
            ch.checked = false;
            t.show();
        });

        $("#selectAllJewels").click(function () {
            for (j in t.jewelsQualities) {
                var ch = document.getElementById("trJewel" + t.jewelsQualities[j]);
                ch.checked = true;
            }
            var ch = document.getElementById('trNoJewel');
            ch.checked = true;
            t.show();
        });



        $("#unselectAllLevels").click(function () {
            for (level = 0; level <= OrganizerMaxTRLevel; level++) {
                var ch = document.getElementById("trLevel" + level);
                ch.checked = false;
            }
            t.show();
        });

        $("#selectAllLevels").click(function () {
            for (level = 0; level <= OrganizerMaxTRLevel; level++) {
                var ch = document.getElementById("trLevel" + level);
                ch.checked = true;
            }
            t.show();
        });

        $("#trLoad").click(function () {
            var preset = $('#trLocalPresetList').val();
            if (preset >= 0) Tabs.throneOrganizer.loadLocalPreset(preset);
        });

        $("#trSave").click(function () {
            var preset = $('#trLocalPresetList').val();
            if (preset >= 0) Tabs.throneOrganizer.saveLocalPreset(preset);
        });

        $("#jewelFilterRow input").change(function () {
            t.show();
        });

        $("#qualityFilterRow input").change(function () {
            t.show();
        });

        $("#throneTypeFilterRow input").change(function () {
            t.show();
        });

        $("#factionFilterRow input").change(function () {
            t.show();
        });

        $("#levelFilterRow input").change(function () {
            t.show();
        });

        $("#trSortList").val(TRupgradeData.sortSelected);
        $("#trSortType").val(TRupgradeData.buffSelected);
        t.sortEffect = TRupgradeData.sortSelected;
        t.sortType = TRupgradeData.buffSelected;

        t.show();
        //$("#trSortList").trigger("change");
    },

    setSwitchStatus: function (s) {
        $("#trSwitchStatus").html(s);
    },

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

        if (t.switchingPresets) {
            t.setSwitchStatus("Local preset switch still in prgres ....");
            return;
        }

        var items = TRpresetData.items[id];
        if (!items || items.length == 0) {
            t.setSwitchStatus("Local preset is empty");
            return;
        }

        var c = 0;
        t.switchingPresets = true;

        var slot = parseInt(TRpresetData.usePreset);

        if (!slot) slot = parseInt(Seed.throne.activeSlot);

        // make sure it is in the valid range
        if (slot < 1 || slot > Seed.throne.slotNum) slot = parseInt(Seed.throne.activeSlot);

        // grab the list of items equipped in the slot about to be switched to
        var ei = Seed.throne.slotEquip[slot];

        // see if we are already on the correct slot
        if (slot != Seed.throne.activeSlot) {
            // switch to the correct preset
            t.setSwitchStatus("Switching to slot " + slot);
            processPresetClick(slot);
            c++;
        } else {
            t.setSwitchStatus("Already in correct slot.");
        }

        var delay = 7;
        for (i in items) {
            if (!items[i]) continue;

            // only equip the items not already equipped
            if (ei.indexOf(items[i]) < 0) {
                var I = unsafeWindow.kocThroneItems[+items[i]];

                if (!I) {
                    t.setSwitchStatus("Throne Room item " + items[i] + " not found");
                    continue;
                }

                var f = function (I2, s) {
                    return function () {
                        Tabs.throneOrganizer.equipItem(I2, s);
                        Tabs.throneOrganizer.setSwitchStatus("Equipping " + I2.name);
                    };
                }
                setTimeout(f(I, slot), c * delay * 1000); // have to wait at least 5 seconds between switches
                c++;
            }
            else {
                var I = unsafeWindow.kocThroneItems[+items[i]];
                //t.setSwitchStatus("Item " + I.name + " is already equipped");
            }
        }

        setTimeout(function () {
            Tabs.throneOrganizer.show();
            t.switchingPresets = false;
            t.setSwitchStatus("Local preset " + TRpresetData.ids[id] + " loaded.")
        }, c * delay * 1000 + 1000);
    },

    saveLocalPreset: function (id) {
        var equipedItems = {};
        var ei = Seed.throne.slotEquip[Seed.throne.activeSlot];

        // convert array to an object
        for (j = 0; j < ei.length; j++) {
            equipedItems[j] = ei[j];
        }

        TRpresetData.items[id] = equipedItems;
        TRsavePresetData();
        Tabs.throneOrganizer.setSwitchStatus("Local preset " + TRpresetData.ids[id] + " saved.");
    },

    unequipItem: function (I, preset) {
        if (!I) return;
        unsafeWindow.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "throneRoom\\ThroneRoomServiceAjax",
            action: "unequipItem",
            itemId: I.id,
            presetId: preset
        }, function (u) {
            if (u.ok === true) {
                unsafeWindow.cm.ThroneView.clickItemUnequip(I);
                Tabs.throneOrganizer.show();
            } else {
                if (I && I.name) {
                    Tabs.throneOrganizer.setSwitchStatus("Unable to unequip item " + I.name);
                } else {
                    Tabs.throneOrganizer.setSwitchStatus("Unable to unequip item");
                }
                logit("Unable to unequip item.");
                cm.ModalManager.alert({
                    button_text: unsafeWindow.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        unsafeWindow.Modal.hideModalAll();
                        unsafeWindow.cm.ModalManager.close()
                    }
                })
            }
        }, function (u) {
            logit("unequip error");
            logit("e:" + inspect(u, 3, 1));

        })
    },

    equipItem: function (I, preset) {
        if (!I) return;
        unsafeWindow.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "throneRoom\\ThroneRoomServiceAjax",
            action: "equipItem",
            itemId: I.id,
            presetId: preset
        }, function (u) {
            //logit("result: "+ inspect(u,3,1));
            if (u.ok === true) {
                unsafeWindow.cm.ThroneView.clickItemEquip(I);
                Tabs.throneOrganizer.show();
            } else {
                if (I && I.name) {
                    Tabs.throneOrganizer.setSwitchStatus("Unable to equip item " + I.name);
                } else {
                    Tabs.throneOrganizer.setSwitchStatus("Unable to equip item");
                }
                logit("Unable to equip item.");
                cm.ModalManager.alert({
                    button_text: unsafeWindow.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        unsafeWindow.Modal.hideModalAll();
                        unsafeWindow.cm.ModalManager.close()
                    }
                })
            }
        }, function (u) {
            logit("equip error");
            logit("e:" + inspect(u, 3, 1));

        })
    },

    showNext: function () {
        var t = Tabs.throneOrganizer;
        if (t.panelId < 0) return;
        var X = unsafeWindow.kocThroneItems[t.panelId];
        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) > OrganizerMaxTRLevel) {
            bump = OrganizerMaxTRLevel - level;
        }

        var R = [],
            Q, Y, S, U, N = {},
            T, W;
        if (V == "next") {
            if (P == "enhance") {
                quality += bump;
                $("#nextStatContainer span").html('<span> ' + X.createPrefix() + ' </span>');
            } else {
                if (P == "upgrade") {
                    level += bump;
                    $("#nextStatContainer span").html('<span> Level ' + level + ' </span>');
                }
            }
        }
        $.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)) {
                W = $("<div/>").addClass("lock").attr("id", "lockedStatIcon");
                $("#nextStatContainer").append(W)
            } else {
                $("#lockedStatIcon").remove()
            }
        }
        t.panelNextLevel++;
        $("#thronePanelStat2").html(R.join(""));

        $("#thronePanelStat2 li").unbind("mouseenter").bind("mouseenter", function (Z) {
            unsafeWindow.Tooltip.show(Z, $(this).html(), [-180, 5])
        })
    },

    // highlight the items the salvager will target
    //    testSalvage: function () {
    //        var t = Tabs.throneOrganizer;
    //        var s = Tabs.throneSalvage;
    //        var toDelete = s.buildList(true);

    //        $('#trDelResults').html("<div> " + toDelete.length + " item(s) targeted for deletion</div>");

    //        for (i = 0; i < toDelete.length; i++) {
    //            var item = unsafeWindow.kocThroneItems[toDelete[i]];
    //            if (item.isBroken || item.isEquipped) {
    //                t.selectCard(toDelete[i], "orange");
    //            }
    //            else {
    //                t.selectCard(toDelete[i], "red");
    //            }
    //        }
    //    },

//    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>");
//            $("div#trCardItem" + throneId).find("div.trCard").append("<div class='greenBorder2' style='border: 8px solid cyan; background: none; width: 192px; height: 292;'></div>");
//        }

//        for (p in TRpresetData.taggedItems) {
//            $("#throneInventoryItem" + p).children(".tagBorderThrone").remove(); //remove any tag first before applying the tag to avoid doubling, trippling up on the borders, etc
//            $("#trCardItem" + p + " div.greenBorder2").remove();
//            $("div#throneInventoryItem" + p).prepend("<div class='tagBorderThrone'></div>");
//            $("div#trCardItem" + p).find("div.trCard").append("<div class='greenBorder2' style='border: 8px solid cyan; background: none; width: 192px; height: 292px;'></div>");
//        }

//        for (idx = 1; idx < 17; idx++) {
//            var preset = getPresetTRObject(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
//                    $("#trCardItem" + p + " div.greenBorder2").remove();
//                    $("#throneInventoryItem" + p).prepend("<div class='presetBorderThrone'></div>");
//                    $("div#trCardItem" + p).find("div.trCard").append("<div class='greenBorder2' style='border: 8px solid cyan; background: none; width: 192px; height: 292;'></div>");
//                }
//            }
//        }

//        if (GeneralOptions.showJewels) {
//            for (trId in unsafeWindow.kocThroneItems) {
//                var throne_item = unsafeWindow.kocThroneItems[trId];
//                if (throne_item.jewel && 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='" + JewelImages[throne_item.jewel.quality] + "'></div>");
//                }
//            }
//        }
//    },

    paintTable: function () {
        // fill in the table
        var t = Tabs.throneOrganizer;
        var m = "";
        var mm;
        var tab = document.getElementById('trDisplayTable');
        var ii = Math.max(t.itemLists['chair'].length, t.itemLists['table'].length, t.itemLists['window'].length, t.itemLists['banner'].length, t.itemLists['advisor'].length, t.itemLists['trophy'].length, t.itemLists['candelabrum'].length, t.itemLists['hero'].length, t.itemLists['statue'].length, t.itemLists['pet'].length, t.itemLists['tapestry'].length, t.itemLists['pillar'].length);  

        m += '<tr align=center valign=top width=100%>';
        for (tr in t.throneTypes) {
            var throne = t.throneTypes[tr];
            m += '<th width=' + OrganizerHeaderSize + '>' + throne.capitalize() + '</th>';
        }
        m += '</tr>';

        for (var k = 0; k < ii; k++) {
            mm = '<TR  align=left valign=top style="height: auto;">';
            for (i in t.itemTypes) {
                var item = t.itemLists[i][k];
                var item_num = 0;
                var id = "card";
                if (item != null) {
                    id += item.id;
                    item_num = item.id;
                }
                mm += '<TD class="tdcard" style="overflow: visible;  width:auto; height: 150px; border: 4px solid white;" id="' + id + '" >';
                if (GeneralOptions.graphicalThrone) {
                    mm += BuildThroneCardGraphical(t.itemLists[i][k], "trCardItem", "trOrganizerDisp");
                } else {
                    mm += BuildThroneCardTextual(t.itemLists[i][k], "trCardItem", "trOrganizerDisp");
                }
                //mm += t.buildCard(t.itemLists[i][k]);
                //mm += BuildThroneCard(t.itemLists[i][k], Table_Scale_TR_Organizer, "trCardItem");
                mm += '</TD>';
            }
            mm += '</TR>';
            m += mm;
        }
        tab.innerHTML = m;
        //repair the height/width caused by the 2d transform
//        var d = document.getElementById('trTableDiv');
//        var t = document.getElementById('trDisplayTable');
//        var nodes = t.getElementsByTagName('td');

//        for (n = 0; n < nodes.length; n++) {
//            var d2 = nodes[n].childNodes[0];
//            var h = d2.offsetHeight;
//            var w = d2.offsetWidth;
//            d2.style.height = (OrganizerCardScale * h) + "px";
//            d2.style.width = (OrganizerCardScale * w) + "px";
//        }
        
        $(".trOrganizerDisp").click(function (A) {
            var theId = $(this).attr("id").split("trCardItem")[1];
            unsafeWindow.cm.ContextualMenuThrone.renderMenu($(this), unsafeWindow.kocThroneItems[theId]);
            t.contextMenu = true;
            document.getElementById("contextMenu").addEventListener("mouseenter", function () { t.contextMenu = false; }, false);
        });

//        $(".trCardDisp").click(function (A) {
//            var theId = $(this).attr("id").split("trCardItem")[1];
//            unsafeWindow.cm.ContextualMenuThrone.renderMenu($(this), unsafeWindow.kocThroneItems[theId]);
//        });

        // add the large tooltip

        if (!GeneralOptions.graphicalThrone) {
            $(".trOrganizerDisp").mouseenter(function () {
                var theId = $(this).attr("id").split("trCardItem")[1];
                ShowThroneTooltip($(this), "chtrTooltip", theId);
            });


            $(".trOrganizerDisp").mouseleave(function () {
                HideThroneTooltip("chtrTooltip");
                setTimeout(function () {
                    if (t.contextMenu) {
                        $("#contextMenu").remove();
                        t.contextMenu = false;
                    }
                }, 100);
            });
        }

//        if (TRpresetData.noTooltips != true) $("td.tdcard").on("mouseenter", "*", function (A) {
//            A.stopPropagation();
//            var top = $(this).parents("td.tdcard")
//            var theId = top.attr("id").split("card")[1];

//            if (!theId || theId == 0) {
//                return;
//            }

//            var zz;
//            if (zz = unsafeWindow.kocThroneItems[theId]) {
//                unsafeWindow.cm.ThroneView.hoverItem(A, top, zz);
//                $("#kofcNewTooltipDiv").css('position', 'absolute');
//                $("#kofcNewTooltipDiv").css('left', ($("#org_dialog").position().left + 200) + 'px');
//                $("#kofcNewTooltipDiv").css('top', A.pageY - 350 + 'px');
//            }
//            else {
//                $("#kofcNewTooltipDiv").remove();
//                setTimeout(function () { Tabs.throneOrganizer.show(); }, 200);
//            }
//        });

//        if (TRpresetData.noTooltips != true) $("td.tdcard").on("mouseleave", "*", function (A) {
//            var theId = $(this).parents("td.tdcard").attr("id").split("card")[1];
//            if (unsafeWindow.kocThroneItems[theId]) { }
//            //unsafeWindow.cm.ThroneView.unhoverItem(A, this, unsafeWindow.kocThroneItems[theId])
//        });

        // add yellow and blue borders
        $("div.trCard").removeClass("blueBorder2");
        $("div.trCard").removeClass("yellowBorder2");
        $("div.trCard").children("div.greenBorder2").remove();

        for (ii in TRqueueData.list) {
            var list_item = TRqueueData.list[ii];
            if (!list_item) continue;
            if (list_item.status != "complete") {
                var id = list_item.item;

                if (list_item.action == "upgrade") $("div#trCardItem" + id).find("div.trCard").addClass("blueBorder2");
                if (list_item.action == "enhance") $("div#trCardItem" + id).find("div.trCard").addClass("yellowBorder2");
            }
        }

        //Tabs.throneOrganizer.paintTags();
        Tabs.thronePresets.paintTags();

    },

    // select a kabam preset
    selectPreset: function (p) {
        // highlight the selected set of cards
        var t = Tabs.throneOrganizer;
        t.clearHighlights();

        p += "";

        if (p.indexOf("local") >= 0) {
            // highlight the local preset
            var localNum = +(p.split("local")[1]);
            var items = TRpresetData.items[localNum];

            if (!items || items.length == 0) return;

            for (i in items) {
                t.selectCard(items[i], "green");
            }
            return;
        }

        // highlight the standard preset
        var equipedItems = Seed.throne.slotEquip[parseInt(p)];
        if (equipedItems != null) {
            for (ll = 0; ll < equipedItems.length; ll++) {
                t.selectCard(equipedItems[ll], "green");
            }
        }
    },

    // fill the lists w/ the current TR items
    fillLists: function () {
        var t = Tabs.throneOrganizer;

        for (i in t.itemTypes) {
            t.itemLists[i] = new Array;
        }

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

            // apply filters
            var faction = throne_item.faction;
            var level = throne_item.level;
            var thronetype = throne_item.type;
            var quality = throne_item.quality;
            var unique = throne_item.unique;
            var jewelQuality = 0;
            var isBroken = throne_item.isBroken;

            var noJewel = ($('#trNoJewel').is(':checked'));
            var hasJewel = (throne_item.jewel == null ? false : true);
            if (hasJewel) jewelQuality = throne_item.jewel.quality;


            if (jewelQuality > 0) {
                if (!($('#trJewel' + jewelQuality).is(':checked'))) continue;
            } else {
                if (!noJewel) continue;
            }

            if (($('#trIgnoreBroken').is(':checked')) && isBroken) continue;
            if (!($('#trUnique').is(':checked')) && unique) continue;
            if (!($('#trQuality' + quality).is(':checked')) && !unique) continue;
            if (!($('#trThroneType' + thronetype).is(':checked'))) continue;
            if (!($('#trFaction' + faction).is(':checked'))) continue;
            if (!($('#trLevel' + level).is(':checked'))) continue;

            // put the equipped items first
            if (throne_item.isEquipped)
                t.itemLists[throne_item.type].unshift(throne_item);
            else
                t.itemLists[throne_item.type].push(throne_item);
        }
    },

    // sort the lists in the desired order
    sortLists: function () {
        var t = Tabs.throneOrganizer;
        TRupgradeData.sortInactive = ($("#trSortInactive").attr('checked') == 'checked');
        for (i in t.itemLists) {
            t.itemLists[i].sort(function (item1, item2) {
                return t.sortValue(item2) - t.sortValue(item1);
            });
        }
    },

    sortValue: 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 && !TRupgradeData.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;
    },

    // clear all the highlists
    clearHighlights: function () {
        var t = Tabs.throneOrganizer;

        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            t.selectCard(throne_item.id, "white");
        }

    },

    // highlight a card
    selectCard: function (itemId, color) {
        var t = Tabs.throneOrganizer;
        var item = unsafeWindow.kocThroneItems[itemId];

        if (item) t.selectedItems[item.type] = itemId;
        td = document.getElementById("card" + itemId);
        if (td) {
            td.style.borderColor = color;
        }
    },

    clearCards: function () {
        var t = Tabs.throneOrganizer;
        for (k in t.selectedItems) {
            var td = document.getElementById("card" + t.selectedItems[k]);
            if (td) {
                td.style.borderColor = "white";
            }
        }
        t.selectedItems = [];
    },


    show: function () {
        var t = Tabs.throneOrganizer;
        t.fillLists();
        t.sortLists()
        t.paintTable();
        t.selectPreset(document.getElementById('TRPresetList').value);
    },

    hide: function () {
    }
}

Tabs.throneOrganizerCompact = {
    tabOrder: 300,
    tabLabel: 'Organize TR',
    tabDisabled: false,
    myDiv: null,
    throneCards: [],
    //itemTypes: { chair: 0, table: 1, window: 2, banner: 3, advisor: 4, trophy: 5, candelabrum: 6, hero: 7, statue: 8, pet: 9, tapestry: 10 },
    selectedItems: [],
    panelId: -1,
    panelType: "upgrade",
    panelNextLevel: 2,
    sortEffect: "none",
    sortType: "both",
    throneTypes: ['chair', 'table', 'window', 'banner', 'advisor', 'trophy', 'candelabrum', 'hero', 'statue', 'pet', 'tapestry', 'pillar'],  
    qualitiesNames: ['simple', 'common', 'uncommon', 'rare', 'epic', 'wondrous', 'miraculous'],
    qualities: [0, 1, 2, 3, 4, 5, 6],
    jewels: ['cracked', 'flawed', 'cloudy', 'subdued', 'bright'],
    jewelsQualities: [1, 2, 3, 4, 5],
    switchingPresets: false,
    contextMenu: false,

    init: function (div) {
        var t = Tabs.throneOrganizerCompact;
        // setup the lists for tables, chairs, etc.
        t.fillLists();
        t.myDiv = div;

        // setup the tab
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=trOrganizer class=trStat>THRONE ROOM ORGANIZER</div>';
        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);
        }

        // header stuff
        // preset selector
        m += '<TABLE  width=100% class="trTabPad2 trTable">';
        m += '<tr width=100% align=center><td width=15%/><td width=30%/><td/></tr>';


        m += '<tr><td colspan=4 width=100%>';
        m += '<div width=100% id=localPresets style="display: ';
        if (GeneralOptions.localPresetHidden) {
            m += 'none;';
        } else {
            m += 'block;';
        }
        m += '"><table width=100%><tr width=100% align=center><td width=15%/><td width=30%/><td/></tr>';



        m += '<tr><td><div><span>View preset: </td><td><select id="TRPresetList">';
        m += '<option value="0">--Presets--</option>';

        for (k = 1; k <= Seed.throne.slotNum; k++) {
            m += '<option value="' + k + '"> Preset:  ' + k + '</option>';
        }
        for (k = 0; k < TRpresetData.num_presets; k++) {
            if (TRpresetData.ids[k])
                m += '<option value="local' + k + '"> Local:  ' + TRpresetData.ids[k] + '</option>';
            else
                m += '<option value="local' + k + '"> Local:  ' + String.fromCharCode(65 + k) + '</option>';
        }

        m += '</select></span></div></td>';
        m += '</tr>';

        m += '<tr  width=100% ><td colspan=1><span style="width: 130px; float: left; margin-top: 4px;  margin-right: 4px;"> Switch to preset: </span>';
        m += '</td><td colspan=3 width=450px>';
        for (a = 1; a <= Seed.throne.slotNum; a++) {
            m += '<a style="font-family: serif; width: 25px;" class="button20 loadGPreset" id=trPresetNum' + a + ' > <span> ' + a + ' </span></a>';
        }
        m += '</td></tr>';

        if (TRpresetData.num_presets > 0) {
            m += '<div id="preset_tt"> <b>: </b> </div></a>';
            m += '<tr width=100%><td colspan=1><span style="width: 130px; float: left; margin-top: 4px;  margin-right: 4px;"> Local preset: </span>';
            m += '</td><td colspan=3>';

            m += '<select id="trLocalPresetList" style="float: left;">';

            m += '<option value="-1">--Preset--</option>';
            for (a = 0; a < TRpresetData.num_presets; a++) {
                m += '<option value="' + a + '">' + TRpresetData.ids[a] + '</option>';
            }
            m += '</select>';
            m += '<a style=" font-family: serif; margin-left: 10px;" class="button20" id=trLoad><span>Load</span></a>';
            m += '<a style=" font-family: serif; margin-left: 5px;" class="buttonDown20" id=trSave><span>Save</span></a>';
            m += '<span style="float: left; margin-top: 4px;  margin-right: 4px; margin-left: 10px;">';
            if (TRpresetData.num_presets > 0) {
                m += "Switch to slot <INPUT id=trPresetNumber type=text size=2 maxlength=2 value='" + parseInt(TRpresetData.usePreset) + "' </input> when loading";
            }
            m += "</span></td></tr>";
        }

        m += '<tr align=center><td colspan=4><div id=trSwitchStatus></div></td></tr>';

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

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

        m += '<tr><td colspan=4 align=center><table cellspacing=0 cellpadding=0>';

        m += '<tr>';

        m += '<td>';
        m += '<center><b>TYPES</b></center>';
        m += '<div id=trTypeFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 95px; overflow-y: scroll; background-color: white;">';
        for (tr in t.throneTypes) {
            var throne = t.throneTypes[tr];
            m += '<INPUT id=trType' + throne + ' type=checkbox  CHECKED />' + throne.capitalize() + '<br />';
        }
        m += '</div>';
        m += '<br>';
        m += '<center><input id=trUnselectAllTypes type=button value="Unselect All"></center>';
        m += '<center><input id=trSelectAllTypes type=button value="Select All"></center>';
        m += '</td>';

        m += '<td>';
        m += '<center><b>QUALITIES</b></center>';
        m += '<div id=trQualityFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 95px; overflow-y: scroll; background-color: white;">';
        for (q in t.qualities) {
            m += '<INPUT id=trQuality' + t.qualities[q] + ' type=checkbox  CHECKED />' + t.qualitiesNames[q].capitalize() + '<br />';
        }
        m += '<INPUT id=trUnique type=checkbox CHECKED />Uniques<br />';
        m += '</div>';
        m += '<br>';
        m += '<center><input id=trUnselectAllQualities type=button value="Unselect All"></center>';
        m += '<center><input id=trSelectAllQualities type=button value="Select All"></center>';
        m += '</td>';

        m += '<td rowspan=2>';
        m += '<div>Sort: <select style="width:50%;" id="trSortList"><option value="none">--Effect--</option>';
        for (k in effects) {
            m += '<option value="' + effects[k] + '">' + effects[k] + '</option>';
        }
        m += "</select>&nbsp;&nbsp;<select id='trSortType'>";
        m += "  <option value='both'>Either</option>";
        m += "  <option value='buff'>Buff</option>";
        m += "  <option value='debuff'>Debuff</option>";
        m += "</select></div>";
        m += '<div id="trScrollDiv" style="position: static; width: 100%; height: 300px; overflow-x: auto; overflow-y: auto;">';
        m += '<center>';
        m += '<div id="trTableDiv" style="width: 100%;">';
        m += '<TABLE id=trDisplayTable height=0% class=trTab><tr align=center valign=top></tr></table>';
        m += '</div>';
        m += '</center>';
        m += '</div>';

        m += '<INPUT id=trSortInactive type=checkbox ' + (TRupgradeData.sortInactive ? ' CHECKED' : '') + '/> Include Inactive ';
        m += '<INPUT id=trIgnoreBroken type=checkbox ' + (TRupgradeData.ignoreBroken ? ' CHECKED' : '') + '/> Ignore Broken';
        m += '</td>';
        m += '</tr>';

        m += '<tr>';

        m += '<td>';
        m += '<center><b>LEVELS</b></center>';
        m += '<div id=trLevelFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 95px; overflow-y: scroll; background-color: white;">';
        for (level = 0; level <= OrganizerMaxTRLevel; level++) {
            m += '<INPUT id=trLevel' + level + ' type=checkbox CHECKED />' + level + '<br /> ';
        }
        m += '</div>';
        m += '<br>';
        m += '<center><input id=trUnselectAllLevels type=button value="Unselect All"></center>';
        m += '<center><input id=trSelectAllLevels type=button value="Select All"></center>';
        m += '</td>';


        m += '<td>';
        m += '<center><b>JEWELS</b></center>';
        m += '<div id=trJewelFilterRow style="float: left; width: 160px; border:2px solid #ccc; height: 95px; overflow-y: scroll; background-color: white;">';
        m += '<INPUT id=trNoJewel type=checkbox CHECKED />No Jewel<br />';
        for (j in t.jewels) {
            m += '<INPUT id=trJewel' + t.jewelsQualities[j] + ' type=checkbox CHECKED />' + t.jewels[j].capitalize() + '<br /> ';
        }
        m += '</div>';
        m += '<br>';
        m += '<center><input id=trUnselectAllJewels type=button value="Unselect All"></center>';
        m += '<center><input id=trSelectAllJewels type=button value="Select All"></center>';
        m += '</td>';

        m += '<td/>';

        m += '</tr>';

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

        m += '</table>';

        m += '</div>';

        t.myDiv.innerHTML = m;
        t.paintTable();

        /* remove resize restrictions
        $(document.querySelector("#trScrollDiv")).resizable({
        minWidth: 710,
        maxWidth: 900,
        minHeight: 180,
        maxHeight: 560,
        maxHeight: 1000,
        stop: function (event, ui) {
        TRupgradeData.organizeH = ui.size.height + 'px';
        TRupgradeData.organizeW = ui.size.width + 'px';
        TRsaveUpgradeData();
        }
        });
        */
        $("#TRPresetList").click(function () { t.selectPreset($(this).val()); });
        // $("#testSalvage").click(function () { t.testSalvage(); });

        // default to highlight the active preset
        document.getElementById('TRPresetList').value = Seed.throne.activeSlot;
        t.selectPreset(Seed.throne.activeSlot);

        $("a.loadGPreset").css('border-color', 'transparent');

        $("a.loadGPreset").bind("mouseenter", function (I) {
            unsafeWindow.cm.ThroneView.boostsTooltip(this, I, I.target.id)
        }); 

        $("a.loadGPreset").bind("mouseleave", function (I) {
            unsafeWindow.removeTooltip()
        });

        $("#trPresetNum" + Seed.throne.activeSlot).css('border-color', 'green')

        $("#trSortList").change(function () {
            t.sortEffect = $(this).val();
            t.show();
        });

        $("#trLocalPresetList").children("option").hover(
                    function (e) {
                        var target = $(e.target);
                        var id = target.val();
                        if (id >= 0) {
                            $("#preset_tt").html('<b>' + TRpresetData.ids[id] + ':</b> ' + TRpresetData.desc[id]);
                            $("#preset_tt").addClass('showit');
                        }
                    },
                    function () {
                        $(document.querySelector("#preset_tt")).removeClass('showit');
                    }

            );

        $("#trSortType").change(function () {
            t.sortType = $(this).val();
            t.show();
        });

        $("#trSortInactive").change(function () {
            t.show();
        });

        $("#trIgnoreBroken").change(function () {
            TRupgradeData.ignoreBroken = document.getElementById('trIgnoreBroken').checked;
            TRsaveUpgradeData();
            t.show();
        });

        $("#trPresetNumber").change(function () {
            TRpresetData.usePreset = $('#trPresetNumber').val();
            TRsavePresetData();
        });

        $(".loadGPreset").click(function () {
            var id = $(this).attr('id');
            processPresetClick(+id.split("trPresetNum")[1]);
        });

        $(".loadPreset").click(function () {
            var id = $(this).attr('id');
            Tabs.throneOrganizerCompact.loadLocalPreset(+id.split("trLoad")[1]);
        });

        $("#trUnselectAllQualities").click(function () {
            for (q in t.qualities) {
                var ch = document.getElementById("trQuality" + t.qualities[q]);
                ch.checked = false;
            }
            var ch = document.getElementById("trUnique");
            ch.checked = false;
            t.show();
        });

        $("#trSelectAllQualities").click(function () {
            for (q in t.qualities) {
                var ch = document.getElementById("trQuality" + t.qualities[q]);
                ch.checked = true;
            }
            var ch = document.getElementById("trUnique");
            ch.checked = true;
            t.show();
        });


        $("#trUnselectAllTypes").click(function () {
            for (tr in t.throneTypes) {
                var ch = document.getElementById("trType" + t.throneTypes[tr]);
                ch.checked = false;
            }
            t.show();
        });

        $("#trSelectAllTypes").click(function () {
            for (tr in t.throneTypes) {
                var ch = document.getElementById("trType" + t.throneTypes[tr]);
                ch.checked = true;
            }
            t.show();
        });

        $("#trUnselectAllJewels").click(function () {
            for (j in t.jewelsQualities) {
                var ch = document.getElementById("trJewel" + t.jewelsQualities[j]);
                ch.checked = false;
            }
            var ch = document.getElementById('trNoJewel');
            ch.checked = false;
            t.show();
        });

        $("#trSelectAllJewels").click(function () {
            for (j in t.jewelsQualities) {
                var ch = document.getElementById("trJewel" + t.jewelsQualities[j]);
                ch.checked = true;
            }
            var ch = document.getElementById('trNoJewel');
            ch.checked = true;
            t.show();
        });



        $("#trUnselectAllLevels").click(function () {
            for (level = 0; level <= OrganizerMaxTRLevel; level++) {
                var ch = document.getElementById("trLevel" + level);
                ch.checked = false;
            }
            t.show();
        });

        $("#trSelectAllLevels").click(function () {
            for (level = 0; level <= OrganizerMaxTRLevel; level++) {
                var ch = document.getElementById("trLevel" + level);
                ch.checked = true;
            }
            t.show();
        });


        $("#trLoad").click(function () {
            var preset = $('#trLocalPresetList').val();
            if (preset >= 0) Tabs.throneOrganizerCompact.loadLocalPreset(preset);
        });

        $("#trSave").click(function () {
            var preset = $('#trLocalPresetList').val();
            if (preset >= 0) Tabs.throneOrganizerCompact.saveLocalPreset(preset);
        });

        $("#trJewelFilterRow input").change(function () {
            t.show();
        });

        $("#trQualityFilterRow input").change(function () {
            t.show();
        });

        $("#trTypeFilterRow input").change(function () {
            t.show();
        });

        //        $("#factionFilterRow input").change(function () {
        //            t.show();
        //        });

        $("#trLevelFilterRow input").change(function () {
            t.show();
        });

        $("#trSortList").val(TRupgradeData.sortSelected);
        $("#trSortType").val(TRupgradeData.buffSelected);
        t.sortEffect = TRupgradeData.sortSelected;
        t.sortType = TRupgradeData.buffSelected;

        t.show();
        //$("#trSortList").trigger("change");
    },

    setSwitchStatus: function (s) {
        $("#trSwitchStatus").html(s);
    },

    loadLocalPreset: function (id) {
        var t = Tabs.throneOrganizerCompact;

        if (t.switchingPresets) {
            t.setSwitchStatus("Local preset switch still in prgres ....");
            return;
        }

        var items = TRpresetData.items[id];
        if (!items || items.length == 0) {
            t.setSwitchStatus("Local preset is empty");
            return;
        }

        var c = 0;
        t.switchingPresets = true;

        var slot = parseInt(TRpresetData.usePreset);

        if (!slot) slot = parseInt(Seed.throne.activeSlot);

        // make sure it is in the valid range
        if (slot < 1 || slot > Seed.throne.slotNum) slot = parseInt(Seed.throne.activeSlot);

        // grab the list of items equipped in the slot about to be switched to
        var ei = Seed.throne.slotEquip[slot];

        // see if we are already on the correct slot
        if (slot != Seed.throne.activeSlot) {
            // switch to the correct preset
            t.setSwitchStatus("Switching to slot " + slot);
            processPresetClick(slot);
            c++;
        } else {
            t.setSwitchStatus("Already in correct slot.");
        }

        var delay = 7;
        for (i in items) {
            if (!items[i]) continue;

            // only equip the items not already equipped
            if (ei.indexOf(items[i]) < 0) {
                var I = unsafeWindow.kocThroneItems[+items[i]];

                if (!I) {
                    t.setSwitchStatus("Throne Room item " + items[i] + " not found");
                    continue;
                }

                var f = function (I2, s) {
                    return function () {
                        Tabs.throneOrganizerCompact.equipItem(I2, s);
                        Tabs.throneOrganizerCompact.setSwitchStatus("Equipping " + I2.name);
                    };
                }
                setTimeout(f(I, slot), c * delay * 1000); // have to wait at least 5 seconds between switches
                c++;
            }
            else {
                var I = unsafeWindow.kocThroneItems[+items[i]];
            }
        }

        setTimeout(function () {
            Tabs.throneOrganizerCompact.show();
            t.switchingPresets = false;
            t.setSwitchStatus("Local preset " + TRpresetData.ids[id] + " loaded.")
        }, c * delay * 1000 + 1000);
    },

    saveLocalPreset: function (id) {
        var equipedItems = {};
        var ei = Seed.throne.slotEquip[Seed.throne.activeSlot];

        // convert array to an object
        for (j = 0; j < ei.length; j++) {
            equipedItems[j] = ei[j];
        }

        TRpresetData.items[id] = equipedItems;
        TRsavePresetData();
        Tabs.throneOrganizerCompact.setSwitchStatus("Local preset " + TRpresetData.ids[id] + " saved.");
    },

    unequipItem: function (I, preset) {
        if (!I) return;
        unsafeWindow.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "throneRoom\\ThroneRoomServiceAjax",
            action: "unequipItem",
            itemId: I.id,
            presetId: preset
        }, function (u) {
            if (u.ok === true) {
                unsafeWindow.cm.ThroneView.clickItemUnequip(I);
                Tabs.throneOrganizerCompact.show();
            } else {
                if (I && I.name) {
                    Tabs.throneOrganizerCompact.setSwitchStatus("Unable to unequip item " + I.name);
                } else {
                    Tabs.throneOrganizerCompact.setSwitchStatus("Unable to unequip item");
                }
                logit("Unable to unequip item.");
                cm.ModalManager.alert({
                    button_text: unsafeWindow.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        unsafeWindow.Modal.hideModalAll();
                        unsafeWindow.cm.ModalManager.close()
                    }
                })
            }
        }, function (u) {
            logit("unequip error");
            logit("e:" + inspect(u, 3, 1));

        })
    },

    equipItem: function (I, preset) {
        if (!I) return;
        unsafeWindow.AjaxCall.gPostRequest("ajax/_dispatch53.php", {
            ctrl: "throneRoom\\ThroneRoomServiceAjax",
            action: "equipItem",
            itemId: I.id,
            presetId: preset
        }, function (u) {
            //logit("result: "+ inspect(u,3,1));
            if (u.ok === true) {
                unsafeWindow.cm.ThroneView.clickItemEquip(I);
                Tabs.throneOrganizerCompact.show();
            } else {
                if (I && I.name) {
                    Tabs.throneOrganizerCompact.setSwitchStatus("Unable to equip item " + I.name);
                } else {
                    Tabs.throneOrganizerCompact.setSwitchStatus("Unable to equip item");
                }
                logit("Unable to equip item.");
                cm.ModalManager.alert({
                    button_text: unsafeWindow.g_js_strings.commonstr.ok,
                    text: u.msg,
                    "class": "craftFailure",
                    exe: function () {
                        unsafeWindow.Modal.hideModalAll();
                        unsafeWindow.cm.ModalManager.close()
                    }
                })
            }
        }, function (u) {
            logit("equip error");
            logit("e:" + inspect(u, 3, 1));

        })
    },

    showNext: function () {
        var t = Tabs.throneOrganizerCompact;
        if (t.panelId < 0) return;
        var X = unsafeWindow.kocThroneItems[t.panelId];
        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) > OrganizerMaxTRLevel) {
            bump = OrganizerMaxTRLevel - level;
        }

        var R = [],
            Q, Y, S, U, N = {},
            T, W;
        if (V == "next") {
            if (P == "enhance") {
                quality += bump;
                $("#nextStatContainer span").html('<span> ' + X.createPrefix() + ' </span>');
            } else {
                if (P == "upgrade") {
                    level += bump;
                    $("#nextStatContainer span").html('<span> Level ' + level + ' </span>');
                }
            }
        }
        $.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)) {
                W = $("<div/>").addClass("lock").attr("id", "lockedStatIcon");
                $("#nextStatContainer").append(W)
            } else {
                $("#lockedStatIcon").remove()
            }
        }
        t.panelNextLevel++;
        $("#thronePanelStat2").html(R.join(""));

        $("#thronePanelStat2 li").unbind("mouseenter").bind("mouseenter", function (Z) {
            unsafeWindow.Tooltip.show(Z, $(this).html(), [-180, 5])
        })
    },

    paintTable: function () {
        // fill in the table
        var t = Tabs.throneOrganizerCompact;
        var mm = "";
        var tab = document.getElementById('trDisplayTable');

        var item_count = t.throneCards.length;
        for (item_index = 0; item_index < item_count; item_index++) {
            var throne_item = unsafeWindow.kocThroneItems[t.throneCards[item_index]];
            if (throne_item == null || !throne_item) continue;
            mm += '<TR><TD class="tdcard" style="white-space: normal; padding: 0px;" id="' + t.throneCards[item_index] + '" >';
            if (GeneralOptions.graphicalThrone) {
                mm += BuildThroneCardGraphical(throne_item, "trCardOrganizerItem", "trOrganizerDisp");
            } else {
                mm += BuildThroneCardTextual(throne_item, "trCardOrganizerItem", "trOrganizerDisp");
            }
            mm += '</TD></TR>';
        }
        tab.innerHTML = mm;

        $(".trOrganizerDisp").click(function (A) {
            var theId = $(this).attr("id").split("trCardOrganizerItem")[1];
            unsafeWindow.cm.ContextualMenuThrone.renderMenu($(this), unsafeWindow.kocThroneItems[theId]);
            t.contextMenu = true;
            document.getElementById("contextMenu").addEventListener("mouseenter", function () { t.contextMenu = false; }, false);
        });


        if (!GeneralOptions.graphicalThrone) {
            $(".trOrganizerDisp").mouseenter(function () {
                var theId = $(this).attr("id").split("trCardOrganizerItem")[1];
                ShowThroneTooltip($(this), "chtrTooltip", theId);
            });


            $(".trOrganizerDisp").mouseleave(function () {
                HideThroneTooltip("chtrTooltip");
                setTimeout(function () {
                    if (t.contextMenu) {
                        $("#contextMenu").remove();
                        t.contextMenu = false;
                    }
                }, 100);
            });
        }

        // add the large tooltip

        //        if (TRpresetData.noTooltips != true) $("td.tdcard").on("mouseenter", "*", function (A) {
        //            A.stopPropagation();
        //            var top = $(this).parents("td.tdcard");
        //            var theId = top.attr("id");

        //            if (!theId || theId == 0) {
        //                return;
        //            }

        //            var zz;
        //            if (zz = unsafeWindow.kocThroneItems[theId]) {
        //                unsafeWindow.cm.ThroneView.hoverItem(A, top, zz);
        //                $("#kofcNewTooltipDiv").css('position', 'absolute');
        //                $("#kofcNewTooltipDiv").css('left', ($("#org_dialog").position().left + 200) + 'px');
        //                $("#kofcNewTooltipDiv").css('top', A.pageY - 350 + 'px');
        //            }
        //            else {
        //                $("#kofcNewTooltipDiv").remove();
        //                setTimeout(function () { Tabs.throneOrganizerCompact.show(); }, 200);
        //            }
        //        });

        // add yellow and blue borders
        $("div.trCard").removeClass("blueBorder2");
        $("div.trCard").removeClass("yellowBorder2");
        //$("div.trCard").children("div.activeBorder2").remove();
        Tabs.thronePresets.paintTags();

    },

    // select a kabam preset
    selectPreset: function (p) {
        // highlight the selected set of cards
        var t = Tabs.throneOrganizerCompact;
        t.clearHighlights();

        p += "";

        if (p.indexOf("local") >= 0) {
            // highlight the local preset
            var localNum = +(p.split("local")[1]);
            var items = TRpresetData.items[localNum];

            if (!items || items.length == 0) return;

            for (i in items) {
                t.selectCard(items[i], "green");
            }
            return;
        }

        // highlight the standard preset
        var equipedItems = Seed.throne.slotEquip[parseInt(p)];
        if (equipedItems != null) {
            for (ll = 0; ll < equipedItems.length; ll++) {
                t.selectCard(equipedItems[ll], "green");
            }
        }
    },

    // fill the lists w/ the current TR items
    fillLists: function () {
        var t = Tabs.throneOrganizerCompact;

        t.throneCards = [];

        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            if (throne_item == null || !throne_item) continue;
            // apply filters
            var faction = throne_item.faction;
            var level = throne_item.level;
            var thronetype = throne_item.type;
            var quality = throne_item.quality;
            var unique = throne_item.unique;
            var jewelQuality = 0;
            var isBroken = throne_item.isBroken;

            var noJewel = ($('#trNoJewel').is(':checked'));
            var hasJewel = (throne_item.jewel == null ? false : true);
            if (hasJewel) jewelQuality = throne_item.jewel.quality;


            if (jewelQuality > 0) {
                if (!($('#trJewel' + jewelQuality).is(':checked'))) continue;
            } else {
                if (!noJewel) continue;
            }

            if (($('#trIgnoreBroken').is(':checked')) && isBroken) continue;
            if (!($('#trUnique').is(':checked')) && unique) continue;
            if (!($('#trQuality' + quality).is(':checked')) && !unique) continue;
            if (!($('#trType' + thronetype).is(':checked'))) continue;
            if (!($('#trLevel' + level).is(':checked'))) continue;

            t.throneCards.push(throne_item.id);
        }
    },

    // sort the lists in the desired order
    sortLists: function () {
        var t = Tabs.throneOrganizerCompact;
        TRupgradeData.sortInactive = ($("#trSortInactive").attr('checked') == 'checked');
        t.throneCards.sort(function (item1, item2) {
            return t.sortValue(item2) - t.sortValue(item1);
        });
    },

    sortValue: function (itemId) {
        var t = Tabs.throneOrganizerCompact;
        var retValue = 0.0;
        var item = unsafeWindow.kocThroneItems[itemId];
        if (item == null || !item) return;
        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 && !TRupgradeData.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;
    },

    // clear all the highlists
    clearHighlights: function () {
        var t = Tabs.throneOrganizerCompact;

        for (k in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[k];
            if (throne_item == null || !throne_item) continue;
            t.selectCard(throne_item.id, "white");
        }

    },

    // highlight a card
    selectCard: function (itemId, color) {
        var t = Tabs.throneOrganizerCompact;
        var item = unsafeWindow.kocThroneItems[itemId];
        if (item == null || !item) return;
        if (item) t.selectedItems[item.type] = itemId;
        td = document.getElementById("card" + itemId);
        if (td) {
            td.style.borderColor = color;
        }
    },

    clearCards: function () {
        var t = Tabs.throneOrganizerCompact;
        for (k in t.selectedItems) {
            var td = document.getElementById("card" + t.selectedItems[k]);
            if (td) {
                td.style.borderColor = "white";
            }
        }
        t.selectedItems = [];
    },

    show: function () {
        var t = Tabs.throneOrganizerCompact;
        t.fillLists();
        t.sortLists()
        t.paintTable();
        t.selectPreset(document.getElementById('TRPresetList').value);
    },

    hide: function () {
    }
}

/** ********************************* TR Caps Tab ************************* **/
Tabs.Caps = {
        tabOrder: 1100,
        tabLabel : 'TR Caps',
        myDiv : null,

        init : function (div){
            var t = Tabs.Caps;
            t.myDiv = div;
            var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
            m += '<DIV class=chStat>THRONE ROOM CAPS</div><hr/>';
            m += '<DIV style="height:535px; max-height:535px;">';
            m += '<TABLE cellpadding=0 cellspacing=0 width=60% align=center>';
            m += '<tr><th align=left>Boost</th><th align=left>Max</th><th align=left>Min</th></tr>';
            for (var k in unsafeWindow.cm.thronestats.boosts) {
                var cap = unsafeWindow.cm.thronestats.boosts[k];
                m += '<tr class=trTabLined><td>' + cap.BoostName + '</td><td>' + cap.Max + ((cap.CapType == "percent") ? '%' : '') + '</td><td>' + ((cap.Min == "none") ? 'None' : cap.Min + '%') + '</td></tr>';
            }
            m += '</table></div></div>';
            t.myDiv.innerHTML = m
                
                

        },
        hide : function () {
        },
        show : function () {
        }
}

/** ********************************* Jewels Organizer Tab **************** **/
Tabs.jewelOrganizer = {
    tabOrder: 1200,
    tabLabel: 'Throne Jewels',
    myDiv: null,
    inventoryList: [],
    totalInventroy: 0,
    jewelEffects: [],
    jewelQualities: ['Cracked', 'Flawed', 'Cloudy', 'Subdued', 'Bright'],
    thronesWithSix: [],
    jewelsList: [],
    salvageTime: 0,
    unexpectedError: false,
    removing: false,

    init: function (div) {
        var t = Tabs.jewelOrganizer;
        t.myDiv = div;
        t.fillJewelList();
        t.buildList();

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV class=chStat>JEWEL SALVAGER</div>';
        m += '<div style="position: static; width: 100%; overflow-x: hidden; overflow-y: auto;" >';
        m += '<table cellspacing=5 cellpadding=0>';
        m += '<tr><td></td><td></td><td></td></tr>';
        m += '<tr>';
        m += '<td>Throne Item:</td>';
        m += '<td colspan=2><select id="trItems">';
        m += '<option value="0">--NONE SELECTED--</option>';
        var found_salvage_throne = false;
        for (i = 0; i < t.thronesWithSix.length; i++) {

            var throne_item = unsafeWindow.kocThroneItems[t.thronesWithSix[i]];
            m += '<option value="' + t.thronesWithSix[i] + '" ' + (JLsalvageData.throneItemId == t.thronesWithSix[i] ? ' SELECTED' : '') + '>' + throne_item.name + '</option>';
            if (!found_salvage_throne) {
                if (JLsalvageData.throneItemId == t.thronesWithSix[i]) found_salvage_throne = true;
            }
        }
        if (!found_salvage_throne) {
            JLsalvageData.throneItemId = 0;
            JLsaveSalvageData();
        }
        m += '</select></td>';
        m += '</tr>';

        if (t.jewelsList.length == 0) {
            m += '<tr><td colspan=4>No Jewel Inventory To Salvage</td></tr>';
        } else {
            m += '<tr>';
            m += '<td>Select Jewel:</td>';
            m += '<td colspan=2><select id="jwlItems"><option value="-1">--Select Jewel To Salvage--</option>';
            for (i = 0; i < t.jewelsList.length; i++) {
                var jewel_index = t.jewelsList[i];
                var jewel_item = unsafeWindow.kocJewelItems[jewel_index];
                var jewel_quantity = unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item);
                var jewel_name = unsafeWindow.cm.ThroneController.jewelName(jewel_item);
                m += '<option value="' + jewel_index + '">' + jewel_name + ' (' + jewel_quantity + ')</option>';
            }
            m += '</select></td>';
            m += '</tr>';

            m += '<tr>';
            m += '<td>Quantity:</td>';
            m += '<td style="width: 125px;"><div style="background-color: white; border:1px solid black; width: 125px;"><input style="width: 100px" type=number id=jwlQty value=0></div></td>';
            m += '<td><input type=button id=jwlSalvage value="Salvage"></td>';
            m += '<td></td>';
            m += '</tr>';
            m += '<tr>';
            m += '<td>Salvage Time:</td>';
            m += '<td id=jwlWaitTime>Complete</td>';
            m += '<td><font color=red><i>(6 sec per jewel)</i></font></td>';
            m += '</tr>';
            m += '<tr><td colspan=3><font color="red"><i><b>NOTE: Refreshing during this process can produce unexpected results...</b></i></font></td></tr>';
        }
        m += '</table>';
        m += '<DIV class=chStat>JEWEL ORGANIZER</div>';
        m += '<table cellpadding=0 cellspacing=0 align=center>';

        m += '<tr><td align=center><b>Effects</b></td><td width=10px></td><td align=center><b>Quality</b></td></tr>';

        m += '<tr>';
        m += '<td><div id=jwlEffectFilterRow style="float: left; width: 250px; border:2px solid #ccc; height: 110px; overflow-y: scroll; background-color: white;">';
        for (k in t.jewelEffects) {
            var effect = t.jewelEffects[k];
            effect = effect.split(' ').join('');
            effect = effect.split('.').join('');
            m += '<INPUT id=jwlEffect' + effect + ' type=checkbox  CHECKED />' + t.jewelEffects[k] + '<br />';

        }
        m += '</div></td>';
        m += '<td></td>';
        m += '<td><div id=jwlQualityFilterRow style="float: left; width: 150px; border:2px solid #ccc; height: 110px; overflow-y: scroll; background-color: white;">';
        for (k in t.jewelQualities) {
            m += '<INPUT id=jwlQuality' + t.jewelQualities[k] + ' type=checkbox  CHECKED />' + t.jewelQualities[k] + '<br />';
        }
        m += '</div></td>';
        m += '</tr>';

        m += '<tr><td align=center><input type=button id=unselectAllJewelEffects value="Unselect All"></td><td></td><td align=center><input type=button id=unselectAllJewelQualities value="Unselect All"></td></tr>';
        m += '<tr><td align=center><input type=button id=selectAllJewelEffects value="Select All"></td><td></td><td align=center><input type=button id=selectAllJewelQualities value="Select All"></td></tr>';

        m += '<tr>';
        m += '<td align=center colspan=3><br/><div id=jwlBuffFilterRow>';
        m += '<INPUT id=jwlBuff' + true + ' type=checkbox  CHECKED />Buff';
        m += '&nbsp;&nbsp;&nbsp;<INPUT id=jwlBuff' + false + ' type=checkbox  CHECKED />Debuff';
        m += '</div></td>';
        m += '</tr>';

        m += '</table></div>';
        m += '<hr/>';
        m += '<div style="position: static; width: 100%; height: 225px; overflow-x: hidden; overflow-y: auto;" >';
        m += '<TABLE id=jwl_inventory_table cellpadding=0 cellspacing=0 width=100%>';

        m += '<thead>';
        m += '<tr>';
        m += '<th align=left id="thEffectName">Effect</th>';
        m += '<th align=left id="thQualityName">Quality</th>';
        m += '<th align=left id="thEffectBuff">Type</th>';
        m += '<th align=center id="thAmount">Amount</th>';
        m += '<th align=center id="thQuantity">In Stock</th>';
        m += '</tr>';
        m += '</thead>';

        m += '<tbody></tbody>';

        m += '<tfoot>';
        m += '<tr><td colspan=5 align=center><hr/></td></tr>';
        m += '<tr><td colspan=3><input id=jwl_refresh type=button value="Refresh"/>&nbsp;<i>(new jewels found may take a couple seconds to add to total)</i></td><td align=right>Total:</td><td align=center><div id=jwlTotal></div></td></tr>';
        m += '</tfoot>';

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

        t.myDiv.innerHTML = m;

        var spinner = $("#jwlQty").spinner();

        $("#jwlQty").spinner("option", "icons", { down: "ui-icon-arrowthick-1-s", up: "ui-icon-arrowthick-1-n" });
        $("#jwlQty").spinner("option", "max", 0);
        $("#jwlQty").spinner("option", "min", 0);

        $("#jwlItems").change(function () {
            var t = Tabs.jewelOrganizer;
            var jewel_index = document.getElementById('jwlItems').value;
            if (jewel_index == -1) {
                $("#jwlQty").spinner('option', 'max', 0);
                $("#jwlQty").spinner('option', 'min', 0);
                $("#jwlQty").spinner('value', 0);
                document.getElementById('jwlWaitTime').innerHTML = "Complete";
                return;
            }
            var jewel_item = unsafeWindow.kocJewelItems[jewel_index];
            var jewel_quantity = unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item);
            $("#jwlQty").spinner('option', 'max', jewel_quantity);
            $("#jwlQty").spinner('option', 'min', 0);
            $("#jwlQty").spinner('value', jewel_quantity);
            t.salvageTime = jewel_quantity * 6;
            document.getElementById('jwlWaitTime').innerHTML = secondsToTime(t.salvageTime);
        });

        $("#jwlQty").change(function () {
            var t = Tabs.jewelOrganizer;
            var max = $(this).spinner('option', 'max');
            var val = $(this).spinner('value');
            if (Number(val) == 0) {
                val = 0;
                $(this).spinner('value', 0);
            }
            if (val > max) {
                $(this).spinner('value', max);
                val = max;
            }
            if (val < 0) {
                $(this).spinner('value', 0);
                val = 0;
            }
            t.salvageTime = val * 6;
            document.getElementById('jwlWaitTime').innerHTML = secondsToTime(t.salvageTime);
        });

        $("#jwlQty").on("spin", function (event, ui) {
            var t = Tabs.jewelOrganizer;
            var val = ui.value;
            t.salvageTime = val * 6;
            document.getElementById('jwlWaitTime').innerHTML = secondsToTime(t.salvageTime);
        });

        $("#jwlSalvage").click(function () {
            var t = Tabs.jewelOrganizer;

            if (t.removing) {
                alert('Still removing jewels, please try back soon');
                return;
            }

            if (JLsalvageData.throneItemId == 0) {
                alert('You must select a throne item to use this feature');
                return;
            }

            var jewel_index = document.getElementById('jwlItems').value;

            var jewel_item = unsafeWindow.kocJewelItems[jewel_index];

            var jewel_quantity = unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item);

            if (jewel_quantity == 0) return; //alert('Please select a jewel to remove');

            var jewels_to_remove = document.getElementById('jwlQty').value;

            if (jewels_to_remove == 0) return;                //alert('Please select 1 or more jewel to remove');

            document.getElementById('trItems').disabled = true;
            document.getElementById('jwlItems').disabled = true;
            document.getElementById('jwlSalvage').disabled = true;

            var refresh_needed = false;

            if (jewels_to_remove == jewel_quantity) refresh_needed = true;

            var finished_quantity = jewels_to_remove * -1;

            setTimeout(function () {
                t.removing = false;
                unsafeWindow.cm.ThroneController.updateJewelCount(jewel_item.quality, jewel_item.id, jewel_item.gift, finished_quantity);
                unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
                unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocJewelItems);
                document.getElementById('jwlWaitTime').innerHTML = 'Complete';
                document.getElementById('trItems').disabled = false;
                document.getElementById('jwlItems').disabled = false;
                document.getElementById('jwlSalvage').disabled = false;
                $("#jwlQty").spinner('option', 'max', unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item));
                $("#jwlQty").spinner('option', 'min', 0);
                var jewel_items = document.getElementById('jwlItems');
                jewel_items.options[jewel_items.selectedIndex].text = unsafeWindow.cm.ThroneController.jewelName(jewel_item) + ' (' + (unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item)) + ')';

                if (t.unexpectedError) {
                    //alert('Some sort of unexpected error occured during the salvage operation.  A page refresh will be required.');
                    RefreshCamelot();
                }

                if (refresh_needed && unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item) == 0) {
                    //alert('You have depleted this jewel.  A page refresh will be required.');
                    RefreshCamelot();
                } else {
                    refresh_needed = false;
                    t.buildList();
                    t.show();
                }

            }, (jewels_to_remove * 6000) + 1000);

            var c = 1;

            var jewel_throne_id = JLsalvageData.throneItemId;
            t.removing = true;

            while (jewels_to_remove != 0) {

                setTimeout(function (ji, tid) {
                    if (t.addJewel(ji.id, ji.quality, tid) != null) t.unexpectedError = true;
                    t.salvageTime = t.salvageTime - 3;
                    document.getElementById('jwlWaitTime').innerHTML = secondsToTime(t.salvageTime);
                    document.getElementById('jwlQty').value = document.getElementById('jwlQty').value - 1;
                }, c * 3000, jewel_item, jewel_throne_id);

                c = c + 1;

                setTimeout(function (tid) {
                    var city_num = pickAetherSalvageCity();
                    var city_id = Seed.cities[city_num][0];
                    if (t.removeJewel(city_id, tid) != null) t.unexpectedError = true;
                    t.salvageTime = t.salvageTime - 3;
                    document.getElementById('jwlWaitTime').innerHTML = secondsToTime(t.salvageTime);
                }, c * 3000, jewel_throne_id);

                jewels_to_remove = jewels_to_remove - 1;

                c = c + 1;
            }

        });

        $("#trItems").change(function () {
            JLsalvageData.throneItemId = document.getElementById('trItems').value;
            JLsaveSalvageData();
        });

        $("#unselectAllJewelQualities").click(function () {
            for (qly in t.jewelQualities) {
                var quality = t.jewelQualities[qly];
                var ch = document.getElementById("jwlQuality" + quality);
                ch.checked = false;
            }
            t.show();
        });

        $("#selectAllJewelQualities").click(function () {
            for (qly in t.jewelQualities) {
                var quality = t.jewelQualities[qly];
                var ch = document.getElementById("jwlQuality" + quality);
                ch.checked = true;
            }
            t.show();
        });

        $("#unselectAllJewelEffects").click(function () {
            for (ef in t.jewelEffects) {
                var effect = t.jewelEffects[ef];
                effect = effect.split(' ').join('');
                effect = effect.split('.').join('');
                var ch = document.getElementById("jwlEffect" + effect);
                ch.checked = false;
            }
            t.show();
        });

        $("#selectAllJewelEffects").click(function () {
            for (ef in t.jewelEffects) {
                var effect = t.jewelEffects[ef];
                effect = effect.split(' ').join('');
                effect = effect.split('.').join('');
                var ch = document.getElementById("jwlEffect" + effect);
                ch.checked = true;
            }
            t.show();
        });

        $("#jwlEffectFilterRow input").change(function () {
            t.show();
        });

        $("#jwlQualityFilterRow input").change(function () {
            t.show();
        });

        $("#jwlBuffFilterRow input").change(function () {
            t.show();
        });

        $('#jwl_refresh').click(function () {
            t.buildList();
            t.show();
        });

        t.buildInventory();

        t.show();

    },

    addJewel: function (jewel_id, jewel_quality, throne_item_id) {
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'addJewel';
        params.itemId = throne_item_id;
        params.quality = jewel_quality;
        params.effectId = jewel_id;

        //logit("Sending enhance request");
        //t.setStatus("Sending enhance request");
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.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 = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'removeJewel';
        params.cityId = city_id;
        params.itemId = throne_item_id;

        //logit("Sending enhance request");
        //t.setStatus("Sending enhance request");
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.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();
    },

    fillJewelList: function () {
        var t = Tabs.jewelOrganizer;
        t.thronesWithSix = [];
        t.jewelsList = [];

        if (unsafeWindow.kocJewelItems.size() > 0) {
            for (jewel_index in unsafeWindow.kocJewelItems) {
                var jewel_item = unsafeWindow.kocJewelItems[jewel_index];
                var qlty = unsafeWindow.cm.thronestats.jewelGrowthLimit[jewel_item.quality];
                var amt = unsafeWindow.cm.ThroneController.getEffectAmount(jewel_item, qlty);
                if (amt == 0) continue;
                t.jewelsList.push(jewel_index);
            }
        }

        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item = unsafeWindow.kocThroneItems[trId];
            if (throne_item.quality == OrganizerMaxTRQuality && throne_item.jewel.valid == false && throne_item.isBroken == false) {
                t.thronesWithSix.push(trId);
            }
        }
    },

    buildInventory: function () {
        var t = Tabs.jewelOrganizer;
        var inv = "";

        for (i = 0; i < t.inventoryList.length; i++) {

            var jewel_item = t.inventoryList[i];

            var qlty = unsafeWindow.cm.thronestats.jewelGrowthLimit[jewel_item.quality];

            var amt = unsafeWindow.cm.ThroneController.getEffectAmount(jewel_item, qlty);

            var name = unsafeWindow.cm.ThroneController.jewelName(jewel_item);

            var buffed = true;

            if (name.indexOf("Debuff") > 0) buffed = false;

            var effect = unsafeWindow.cm.ThroneController.getEffectName(jewel_item.id);

            var qty = unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item);

            var qaulityName = unsafeWindow.cm.ThroneController.jewelQualityName(jewel_item.quality);

            var tmpEffect = unsafeWindow.cm.ThroneController.getEffectName(jewel_item.id);
            tmpEffect = tmpEffect.split(' ').join('');
            tmpEffect = tmpEffect.split('.').join('');

            if (!($('#jwlEffect' + tmpEffect).is(':checked'))) continue;
            if (!($('#jwlQuality' + qaulityName).is(':checked'))) continue;
            if (!($('#jwlBuff' + buffed).is(':checked'))) continue;

            inv += '<tr><td>' + effect + '</td><td>' + qaulityName + '</td><td>' + (buffed ? 'Buff ' : 'Debuff') + '</td><td align=center>' + amt + '%</td><td align=center>' + qty + '</td></tr>';

        }

        var jwl_inv = document.getElementById('jwl_inventory_table').tBodies[0];
        jwl_inv.innerHTML = inv;

        var jwl_total = document.getElementById('jwlTotal');
        jwl_total.innerHTML = t.totalInventroy;

    },

    buildList: function () {
        var t = Tabs.jewelOrganizer;
        t.inventoryList = [];
        t.totalInventroy = 0;
        for (var k in unsafeWindow.kocJewelItems) {
            var jewel_item = unsafeWindow.kocJewelItems[k];
            var qlty = unsafeWindow.cm.thronestats.jewelGrowthLimit[jewel_item.quality];
            var amt = unsafeWindow.cm.ThroneController.getEffectAmount(jewel_item, qlty);
            var effect = unsafeWindow.cm.ThroneController.getEffectName(jewel_item.id);
            if (amt == 0) break;
            if (t.jewelEffects.indexOf(effect) < 0) t.jewelEffects.push(effect);
            var jewel_quantity = unsafeWindow.cm.ThroneController.getJewelQuantity(jewel_item);
            t.totalInventroy += jewel_quantity;
            t.inventoryList.push(jewel_item);
        }
    },

    hide: function () {
    },

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

        t.buildInventory();

    }
}

JLsalvageData = {
    throneItemId : 0
}

function JLsaveSalvageData () {
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('JLSalvDataMM2_'+serverID, JSON2.stringify(JLsalvageData));}, 0);
}

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

/** ********************************* Throne Preview Tab ****************** **/
Tabs.thronePreview = {
    tabOrder: 1500,
    tabLabel: 'TR Preview',
    myDiv: null,
    equipingPreview: false,
    contextMenu: false,

    init: function (div) {
        var t = Tabs.thronePreview;
        t.myDiv = div;
        //t.buildLists();

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

        var presetsTagList = "";

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

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV style="height:535px; max-height:535px;">';
        m += '<DIV class=trStat>THRONE ROOM PREVIEWING</div>';
        m += '<TABLE id=trDisplayTable width=100% height=0% class=trTab cellspacing=5 cellpadding=0>';


        m += '<tr>';
        m += '<td colspan=3>';
        m += '<input type=button value="Reset" id=trPreviewReset>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button value="Equip Now" id=trPreviewEquip><font color=black><b>(5 sec per card to load)</b></font>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button value="Post Stats to Chat" id=trPreviewPost>&nbsp;';
        m += '<input type=button value="Export to Excel" id=trPreviewExcel>&nbsp;';
        m += '<br>';
        m += '<input type=button value="Export To Text" id=trPreviewExport>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button value="Load Text Export" id=trPreviewExportLoad><input id=trPreviewExportLoadItem type=file>';
        m += '<br>';
        m += '<input type=button value="Load TR Preset" id=trPreviewLoadPreset>&nbsp;<select style="width:15%;" id=trPreviewLoadPresetValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button value="Copy To" id=trPreviewCopyTo><b>&nbsp;Preset Tag&nbsp;</b><select style="width:15%;" id=trPreviewCopyToValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button value="Load TR From" id=trPreviewLoadPresetTag><b>&nbsp;Preset Tag&nbsp;</b><select style="width:15%;" id=trPreviewLoadPresetTagValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '</td>';
        m += '</tr>';

        m += '<tr><td colspan=3><hr></td></tr>';

        m += '<tr>';

        m += '<td rowspan=12 style="vertical-align:text-top;width:300px;"><div id=trPreviewDetails></div></td>';

        m += '<td style="vertical-align:text-top;"><b>Chair</b><br/><select id="trPreviewchairValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "chair") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td style="vertical-align:text-top;"><b>Table</b><br/><select id="trPreviewtableValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "table") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="trPreviewchair" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="trPreviewtable" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Window</b><br/><select id="trPreviewwindowValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "window") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td style="vertical-align:text-top;"><b>Banner</b><br/><select id="trPreviewbannerValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "banner") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="trPreviewwindow" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="trPreviewbanner" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Advisor</b><br/><select id="trPreviewadvisorValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "advisor") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';


        m += '<td style="vertical-align:text-top;"><b>Trophy</b><br/><select id="trPreviewtrophyValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "trophy") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="trPreviewadvisor" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="trPreviewtrophy" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Statue</b><br/><select id="trPreviewstatueValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "statue") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';


        m += '<td style="vertical-align:text-top;"><b>Pet</b><br/><select id="trPreviewpetValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "pet") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';


        m += '</tr>';

        m += '<tr>';
        m += '<td id="trPreviewstatue" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="trPreviewpet" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Tapestry</b><br/><select id="trPreviewtapestryValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "tapestry") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td style="vertical-align:text-top;"><b>Candelabrum</b><br/><select id="trPreviewcandelabrumValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "candelabrum") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="trPreviewtapestry" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="trPreviewcandelabrum" class="tdcard" style="overflow: visible;  width: auto; height: auto;"></td>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Hero</b><br/><select id="trPreviewheroValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "hero") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td style="vertical-align:text-top;"><b>Pillar</b><br/><select id="trPreviewpillarValue" class="trPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (trId in unsafeWindow.kocThroneItems) {
            var throne_item;
            if (throne_item = unsafeWindow.kocThroneItems[trId]) {
                if (throne_item.type != "pillar") continue;
                m += '<option value="' + throne_item.id + '" ' + (TRpresetData.previewThrone[throne_item.id] ? "SELECTED" : "") + '>' + throne_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="trPreviewhero" class="tdcard" style="overflow: visible;  width: auto; height: auto;"></td>';
        m += '<td id="trPreviewpillar" class="tdcard" style="overflow: visible;  width: auto; height: auto;"></td>';  
        m += '</tr>';


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

        t.myDiv.innerHTML = m;

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

        t.paintCards();

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

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


        document.getElementById('trPreviewExportLoad').addEventListener('click', function() {
            var fileInput = document.getElementById("trPreviewExportLoadItem");
            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;
				TRpresetData.previewThrone = JSON.parse(output);
                TRsavePresetData();
                Tabs.thronePreview.init(Tabs.thronePreview.myDiv);
                alert('Preview Throne Now Loaded From File');
            };
            reader.readAsText(file);

        }, false);

        $("#trPreviewCopyTo").click(function () {
            var presetNum = document.getElementById('trPreviewCopyToValue').value;
            var presetTag = getPresetTRObject(parseInt(presetNum));
            for (var p in presetTag) delete presetTag[p];
            for (var p in TRpresetData.previewThrone) presetTag[p] = true;
            TRpresetData.presetNames[presetNum] = "PREVIEW";
            document.getElementById('trPresetName' + presetNum).value = "PREVIEW";
            TRsavePresetData();
            Tabs.thronePreview.init($("#tabs-previewTR")[0]);
        });

        $("#trPreviewLoadPreset").click(function () {
            var t = Tabs.thronePreview;
            var presetIndex = document.getElementById('trPreviewLoadPresetValue').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 = unsafeWindow.kocThroneItems[equipped_items[ei]];
                if (throne_item == null || !throne_item) continue;
                t.loadCard(throne_item.id);
            }
            //t.paintCards();
        });

        $("#trPreviewLoadPresetTag").click(function () {
            var t = Tabs.thronePreview;
            var presetNum = document.getElementById('trPreviewLoadPresetTagValue').value;
            var presetTag = getPresetTRObject(parseInt(presetNum));
            t.resetPreview();
            for (var p in presetTag) {
                t.loadCard(p);
            }
            //t.paintCards();
        });

        $("#trPreviewPost").click(function () {
            t.postPreviewThroneDetails();
        });

        $("#trPreviewEquip").click(function () {

            var presetIndex = Seed.throne.activeSlot;

            var t = Tabs.thronePreview;

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

            if (getObjectCollectionCount(TRpresetData.previewThrone) == 0) return;

            var c = 0;
            t.equipingPreview = true;

            var delay = 7;

            var types_equiped = [];

            for (var trId in TRpresetData.previewThrone) {

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

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

                types_equiped.push(throne_item.type);

                if (!throne_item.isEquipped) {

                    var goEquip = function (I2, s) {
                        return function () {
                            if (GeneralOptions.compactView) {
                                Tabs.throneOrganizerCompact.equipItem(I2, s);
                            } else {
                                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 (var i = 0; i < counter; i++) {
                var throne_item = unsafeWindow.kocThroneItems[equipped_items[i]];
                if (throne_item == null || !throne_item) continue;
                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 () {
                            if (GeneralOptions.compactView) {
                                Tabs.throneOrganizerCompact.unequipItem(I2, s);
                            } else {
                                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.equipingPreview = false;
                alert("loading from PREVIEW complete")
            }, (c * (delay * 1000)) + 1000);

        });

        $("#trPreviewReset").click(function () {
            t.resetPreview();
        });

        if (!GeneralOptions.graphicalThrone) {
            if (TRpresetData.noTooltips != true) $("td.tdcard").on("mouseleave", "*", function (A) {
                HideThroneTooltip("chtrTooltip");
            });

            if (TRpresetData.noTooltips != true) $("td.tdcard").on("mouseenter", "*", function (A) {
                A.stopPropagation();
                var tdCard = $(this).parents("td.tdcard");
                var divCard_id = $(this).parents("div.trPreviewDisp").attr("id");

                var trId = divCard_id.split(tdCard.attr("id"))[1];

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

                ShowThroneTooltip($(this), "chtrTooltip", trId);

            });
        }

        $('select.trPcard').keyup(function (event) {
            var throne_type = $(this).attr('id');
            throne_type = throne_type.split("trPreview")[1];
            throne_type = throne_type.split("Value")[0];

            var trId = $(this).val();

            if (trId == 0) document.getElementById('trPreview' + throne_type).innerHTML = "";

            t.loadCard(trId, throne_type);
        });

        $("select.trPcard").change(function () {
            var throne_type = $(this).attr('id');
            throne_type = throne_type.split("trPreview")[1];
            throne_type = throne_type.split("Value")[0];

            var trId = $(this).val();

            if (trId == 0) document.getElementById('trPreview' + throne_type).innerHTML = "";

            t.loadCard(trId, throne_type);

        });

    },

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

        for (trId in TRpresetData.previewThrone) delete TRpresetData.previewThrone[trId];
        TRsavePresetData();

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

        for (i = 0; i < throneTypes.length; i++) {
            document.getElementById('trPreview' + throneTypes[i]).innerHTML = "";
            document.getElementById('trPreview' + throneTypes[i] + 'Value').value = 0;
        }

        document.getElementById('trPreviewDetails').innerHTML = t.getPreviewThroneDetails();
    },

    paintCard: function (trId, throne_type, force_paint) {
        var t = Tabs.thronePreview;
        force_paint = force_paint || false;
        var divName = 'trPreview' + throne_type;
        var throne_item = unsafeWindow.kocThroneItems[trId];
        if (throne_item == null || !throne_item) return;
        var trPreviewCard = document.getElementById(divName);
        var throneDiv = divName + throne_item.id;
        if (document.getElementById(throneDiv) == null || force_paint) {
            trPreviewCard.innerHTML = ""
            if (GeneralOptions.graphicalThrone) {
                trPreviewCard.innerHTML = BuildThroneCardGraphical(throne_item, divName, "trPreviewDisp");
            } else {
                trPreviewCard.innerHTML = BuildThroneCardTextual(throne_item, divName, "trPreviewDisp");
            }
        }
        document.getElementById('trPreviewDetails').innerHTML = t.getPreviewThroneDetails();
    },

    paintCards: function (force_paint) {
        force_paint = force_paint || false;
        var t = Tabs.thronePreview;
        for (trId in TRpresetData.previewThrone) {
            var throne_item = unsafeWindow.kocThroneItems[trId];
            if (throne_item == null || !throne_item) continue;
            t.paintCard(throne_item.id, throne_item.type, force_paint);
        }
    },

    postPreviewThroneDetails: function () {
        var t = Tabs.thronePreview;
        var previewPreset = [];
        for (var trId in TRpresetData.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;

    },

    getPreviewThroneDetails: function () {
        var t = Tabs.thronePreview;
        var previewPreset = [];
        for (var trId in TRpresetData.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;
    },

    loadCard: function (throneID, throne_type) {

        var t = Tabs.thronePreview;

        throne_type = throne_type || null;


        if (throne_type == null) {  //if throne type = null that means you're loading it from the TR inventory, so you'll also need to change the dropdown selection value
            var throne_item = unsafeWindow.kocThroneItems[throneID];
            if (throne_item == null || !throne_item) return;
            throne_type = throne_item.type;
            var trPreviewValue = document.getElementById('trPreview' + throne_type + 'Value');
            trPreviewValue.value = throneID;
        }

        for (pId in TRpresetData.previewThrone) {
            var throne_item = unsafeWindow.kocThroneItems[pId];
            if (throne_item == null || !throne_item) continue;
            if (throne_item.type == throne_type) {
                delete TRpresetData.previewThrone[pId];
                break;
            }
        }

        if (throneID != 0) TRpresetData.previewThrone[throneID] = true

        TRsavePresetData();

        t.paintCard(throneID, throne_type);
    },


    hide: function () {

    },

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

}


/** ********************************* Champ Preview Tab ****************** **/
Tabs.champPreview = {
    tabOrder: 1500,
    tabLabel: 'CH Preview',
    myDiv: null,
    equipingPreview: false,
    contextMenu: false,

    init: function (div) {
        var t = Tabs.champPreview;
        t.myDiv = div;
        //t.buildLists();

        //var presetSlots = getObjectCollectionCount(Seed.throne.slotEquip);
        var presetsTagList = "";
        if (OrganizerMaxChampions != 0)  {
            for (var i = 1; i < OrganizerMaxChampions + 1; i++) {
                presetsTagList += '<option value="' + i + '">' + i + ' (' + CHpresetData.presetNames[i-1] + ')</option>';
            }
        }

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV style="height:535px; max-height:535px;">';
        m += '<DIV class=trStat>CHAMPION HALL PREVIEWING</div>';
        m += '<TABLE id=trDisplayTable width=100% height=0% class=trTab cellspacing=5 cellpadding=0>';


        m += '<tr>';
        m += '<td colspan=3>';
        m += '<input type=button value="Reset" id=chPreviewReset>&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 value="Post Stats to Chat" id=chPreviewPost>&nbsp;';
        m += '<input type=button value="Export to Excel" id=chPreviewExcel>&nbsp;';
        m += '<br>';
        m += '<input type=button value="Export To Text" id=chPreviewExport>&nbsp;&nbsp;||&nbsp;&nbsp;';
        m += '<input type=button value="Load Text Export" id=chPreviewExportLoad><input id=chPreviewExportLoadItem type=file>';
        m += '<br>';
        m += '<input type=button value="Load CH Preset" id=chPreviewLoadPreset>&nbsp;<select style="width:15%;" id=chPreviewLoadPresetValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button value="Copy To" id=chPreviewCopyTo><b>&nbsp;Preset Tag&nbsp;</b><select style="width:15%;" id=chPreviewCopyToValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '<br>';
        m += '<input type=button value="Load CH From" id=chPreviewLoadPresetTag><b>&nbsp;Preset Tag&nbsp;</b><select style="width:15%;" id=chPreviewLoadPresetTagValue>' + presetsTagList + '</select>&nbsp;&nbsp;';
        m += '</td>';
        m += '</tr>';

        m += '<tr><td colspan=3><hr></td></tr>';

        m += '<tr>';

        m += '<td rowspan=12 style="vertical-align:text-top;width:300px;"><div id=chPreviewDetails></div></td>';

        m += '<td style="vertical-align:text-top;"><b>Weapon</b><br/><select id="chPreviewweaponValue" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 1) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td style="vertical-align:text-top;"><b>Chest</b><br/><select id="chPreviewchestValue" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 2) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="chPreviewweapon" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="chPreviewchest" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Helm</b><br/><select id="chPreviewhelmValue" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 3) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td style="vertical-align:text-top;"><b>Boots</b><br/><select id="chPreviewbootsValue" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 4) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="chPreviewhelm" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="chPreviewboots" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Shield</b><br/><select id="chPreviewshieldValue" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 5) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td style="vertical-align:text-top;"><b>Ring1</b><br/><select id="chPreviewring1Value" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 6) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="chPreviewshield" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="chPreviewring1" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Ring2</b><br/><select id="chPreviewring2Value" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 7) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';


        m += '<td style="vertical-align:text-top;"><b>Pendant</b><br/><select id="chPreviewpendantValue" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 8) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';


        m += '</tr>';

        m += '<tr>';
        m += '<td id="chPreviewring2" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '<td id="chPreviewpendant" class="tdcard" style="overflow: visible;  width: auto; height: auto; "/>';
        m += '</tr>';

        m += '<tr>';

        m += '<td style="vertical-align:text-top;"><b>Cloak</b><br/><select id="chPreviewcloakValue" class="chPcard" style="width: 75%;">';
        m += '<option value="0">--Items--</option>';
        for (chId in unsafeWindow.kocChampionItems) {
            var champ_item;
            if (champ_item = unsafeWindow.kocChampionItems[chId]) {
                if (champ_item.type != 9) continue;
                m += '<option value="' + chId + '" ' + (CHpresetData.previewChamp[chId] ? "SELECTED" : "") + '>' + champ_item.name + ' </option>';
            }
        }
        m += '</select></td>';

        m += '<td/>';

        m += '</tr>';

        m += '<tr>';
        m += '<td id="chPreviewcloak" class="tdcard" style="overflow: visible;  width: auto; height: auto;"></td>';
        m += '<td/>';
        m += '</tr>';


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

        t.myDiv.innerHTML = m;

        document.getElementById('chPreviewDetails').innerHTML = t.getPreviewChampDetails();

        t.paintCards();

        document.getElementById('chPreviewExcel').addEventListener('click', function() {
            ExportChampToExcel(true);
        }, false);


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


        document.getElementById('chPreviewExportLoad').addEventListener('click', function() {
            var fileInput = document.getElementById("chPreviewExportLoadItem");
            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;
				CHpresetData.previewChamp = JSON.parse(output);
                CHsavePresetData();
                Tabs.champPreview.init(Tabs.champPreview.myDiv);
                alert('Preview Champ Now Loaded From File');
            };
            reader.readAsText(file);

        }, false);

        $("#chPreviewCopyTo").click(function () {
            var presetNum = document.getElementById('chPreviewCopyToValue').value;
            var presetTag = getPresetCHObject(parseInt(presetNum));
            for (var p in presetTag) delete presetTag[p];
            for (var p in CHpresetData.previewChamp) presetTag[p] = true;
            CHpresetData.presetNames[presetNum-1] = "PREVIEW";
            document.getElementById('chPresetName' + presetNum).value = "PREVIEW";
            CHsavePresetData();
            Tabs.champPreview.init($("#tabs-previewCH")[0]);
        });

        $("#chPreviewLoadPreset").click(function () {
            var t = Tabs.champPreview;

            var presetIndex = document.getElementById('chPreviewLoadPresetValue').value;

            var championID = unsafeWindow.seed.champion.champions[presetIndex-1].championId;// = 11007
            var equipped_items = [];
            for (chId in unsafeWindow.kocChampionItems) {
                if (unsafeWindow.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];
                    t.loadCard(chId);
                }
            }
            //t.paintCards();
        });

        $("#chPreviewLoadPresetTag").click(function () {
            var t = Tabs.champPreview;
            var presetNum = document.getElementById('chPreviewLoadPresetTagValue').value;
            var presetTag = getPresetCHObject(parseInt(presetNum));
            t.resetPreview();
            for (var p in presetTag) {
                t.loadCard(p);
            }
            //t.paintCards();
        });

        $("#chPreviewPost").click(function () {
            t.postPreviewChampDetails();
        });

//        $("#chPreviewEquip").click(function () {

//            var presetIndex = Seed.throne.activeSlot;

//            var t = Tabs.thronePreview;

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

//            if (getObjectCollectionCount(TRpresetData.previewThrone) == 0) return;

//            var c = 0;
//            t.equipingPreview = true;

//            var delay = 7;

//            var types_equiped = [];

//            for (var trId in TRpresetData.previewThrone) {

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

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

//                types_equiped.push(throne_item.type);

//                if (!throne_item.isEquipped) {

//                    var goEquip = function (I2, s) {
//                        return function () {
//                            if (GeneralOptions.compactView) {
//                                Tabs.throneOrganizerCompact.equipItem(I2, s);
//                            } else {
//                                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 (var i = 0; i < counter; i++) {
//                var throne_item = unsafeWindow.kocThroneItems[equipped_items[i]];
//                if (throne_item == null || !throne_item) continue;
//                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 () {
//                            if (GeneralOptions.compactView) {
//                                Tabs.throneOrganizerCompact.unequipItem(I2, s);
//                            } else {
//                                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.equipingPreview = false;
//                alert("loading from PREVIEW complete")
//            }, (c * (delay * 1000)) + 1000);

//        });

        $("#chPreviewReset").click(function () {
            t.resetPreview();
        });

        if (!GeneralOptions.graphicalThrone) {
            if (CHpresetData.noTooltips != true) $("td.tdcard").on("mouseleave", "*", function (A) {
                HideChampTooltip("chtrTooltip");
            });

            if (CHpresetData.noTooltips != true) $("td.tdcard").on("mouseenter", "*", function (A) {
                A.stopPropagation();
                var tdCard = $(this).parents("td.tdcard");
                var divCard_id = $(this).parents("div.chPreviewDisp").attr("id");

                var chId = divCard_id.split(tdCard.attr("id"))[1];

                if (!chId || chId == 0) return;

                ShowChampTooltip($(this), "chtrTooltip", chId);

            });
        }

        $('select.chPcard').keyup(function (event) {
            var champ_type = $(this).attr('id');
            champ_type = champ_type.split("chPreview")[1];
            champ_type = champ_type.split("Value")[0];

            var chId = $(this).val();

            if (chId == 0) document.getElementById('chPreview' + champ_type).innerHTML = "";

            t.loadCard(chId, champ_type);
        });

        $("select.chPcard").change(function () {
            var champ_type = $(this).attr('id');
            champ_type = champ_type.split("chPreview")[1];
            champ_type = champ_type.split("Value")[0];

            var chId = $(this).val();

            if (chId == 0) document.getElementById('chPreview' + champ_type).innerHTML = "";

            t.loadCard(chId, champ_type);

        });

    },

    resetPreview: function () {
        var t = Tabs.champPreview;

        for (chId in CHpresetData.previewChamp) delete CHpresetData.previewChamp[chId];
        CHsavePresetData();
        
        var champTypes = ['weapon', 'chest', 'helm', 'boots', 'shield', 'ring1', 'ring2', 'pendant', 'cloak'];

        for (i = 0; i < champTypes.length; i++) {
            document.getElementById('chPreview' + champTypes[i]).innerHTML = "";
            document.getElementById('chPreview' + champTypes[i] + 'Value').value = 0;
        }

        document.getElementById('chPreviewDetails').innerHTML = t.getPreviewChampDetails();
    },

    paintCard: function (chId, champ_type_id, force_paint) {
        var t = Tabs.champPreview;
        force_paint = force_paint || false;
        var champ_type = champItemNames[champ_type_id];
        var divName = 'chPreview' + champ_type;
        var champ_item = unsafeWindow.kocChampionItems[chId];
        if (champ_item == null || !champ_item) return;
        var chPreviewCard = document.getElementById(divName);
        var champDiv = divName + champ_item.equipmentId;
        if (document.getElementById(champDiv) == null || force_paint) {
            chPreviewCard.innerHTML = ""
            if (GeneralOptions.graphicalThrone) {
                chPreviewCard.innerHTML = BuildChampCardGraphical(champ_item);
            } else {
                chPreviewCard.innerHTML = BuildChampCardTextual(champ_item, divName, "chPreviewDisp");
            }
        }
        document.getElementById('chPreviewDetails').innerHTML = t.getPreviewChampDetails();
    },

    paintCards: function (force_paint) {
        force_paint = force_paint || false;
        var t = Tabs.champPreview;
        for (chId in CHpresetData.previewChamp) {
            var champ_item = unsafeWindow.kocChampionItems[chId];
            if (champ_item == null || !champ_item) continue;
            t.paintCard(champ_item.equipmentId, champ_item.type, force_paint);
        }
    },

    postPreviewChampDetails: function () {
        var t = Tabs.champPreview;
        var previewPreset = [];
        for (var chId in CHpresetData.previewChamp) previewPreset.push(chId);

        var stringPreviewChamp = GenerateChampPresetEffectsString(previewPreset, true);//GenerateThronePresetEffectsString(previewPreset);
        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;

    },

    getPreviewChampDetails: function () {
        var t = Tabs.champPreview;
        var previewPreset = [];
        for (var chId in CHpresetData.previewChamp) previewPreset.push(chId);

        var stringPreviewChamp = GenerateChampPresetEffectsString(previewPreset, true);//GenerateThronePresetEffectsString(previewPreset);
        if (stringPreviewChamp == "") {
            stringPreviewChamp = "No Stats To Preview";
        } else {
            stringPreviewChamp = "<b>PREVIEW STATS:</b>\n" + stringPreviewChamp;
        }
        return stringPreviewChamp;
    },

    loadCard: function (champID, champ_type) {

        var t = Tabs.champPreview;

        champ_type = champ_type || null;

        if (champ_type == null) {  //if throne type = null that means you're loading it from the TR inventory, so you'll also need to change the dropdown selection value
            var champ_item = unsafeWindow.kocChampionItems[champID];
            if (champ_item == null || !champ_item) return;
            champ_type = champItemNames[champ_item.type];
            var chPreviewValue = document.getElementById('chPreview' + champ_type + 'Value');
            chPreviewValue.value = champID;
        }

        for (cId in CHpresetData.previewChamp) {
            var champ_item = unsafeWindow.kocChampionItems[cId];
            if (champ_item == null || !champ_item) continue;
            if (champItemNames[champ_item.type] == champ_type) {
                delete CHpresetData.previewChamp[cId];
                break;
            }
        }

        if (champID == 0) return;

        //if (champID != 0) CHpresetData.previewChamp[champID] = true
        CHpresetData.previewChamp[champID] = true

        var champ_item = unsafeWindow.kocChampionItems[champID];

        champ_type = champ_item.type;

        CHsavePresetData();

        t.paintCard(champID, champ_type);
    },


    hide: function () {

    },

    show: function () {
        var t = Tabs.champPreview;
        t.paintCards(true);
    }

}

/** ********************************* Champ Presets Tab ******************* **/
Tabs.champPresets = {
    tabOrder: 1400,
    tabLabel: 'CH Preset',
    broke_items: 0,
    broke_count: 0,
    delay: 2000,
    myDiv: null,

    init: function (div) {
        var t = Tabs.champPresets;
        t.myDiv = div;
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV class=trStat>CHAMP PRESET TAGGING</div><TABLE id=chOptionTbl width=100% height=0% class=trTab>';
        m += '<tr><td width=100%>Preset Tag Color: <select id=chPresetColor>';
        m += '<option ' + (CHpresetData.presetColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (CHpresetData.presetColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (CHpresetData.presetColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (CHpresetData.presetColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (CHpresetData.presetColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (CHpresetData.presetColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (CHpresetData.presetColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (CHpresetData.presetColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tag Color: <select id=chTagColor>';
        m += '<option ' + (CHpresetData.tagColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (CHpresetData.tagColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (CHpresetData.tagColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (CHpresetData.tagColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (CHpresetData.tagColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (CHpresetData.tagColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (CHpresetData.tagColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (CHpresetData.tagColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Active Preset Color: <select id=chActiveColor>';
        m += '<option ' + (CHpresetData.activeColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (CHpresetData.activeColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (CHpresetData.activeColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (CHpresetData.activeColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (CHpresetData.activeColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (CHpresetData.activeColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (CHpresetData.activeColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (CHpresetData.activeColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>(Requires Refresh)</td></tr>';
        m += '<tr><td>';
        m += '<input type=button id=chClearTags value="Clear All Tags">';
        m += '<input type=button id=chClearAllPresetTags value="Clear All Preset Tags">';
        m += '<input type=button id=chSaveAllPresetTags value="Save All Preset Tags">';

        //m += '<input type=button id=chExportPresetTags value="Export Preset Tags">';

        m += '</td></tr>';
        m += '<tr><td>';
        m += '<input type=checkbox id=chShowMight ' + (CHpresetData.showCHMight ? 'CHECKED' : '') + '/>Show Might on Posts&nbsp;&nbsp;&nbsp;<input type=checkbox id=chShowName ' + (CHpresetData.showCHName ? 'CHECKED' : '') + '/>Show Preset Name on Posts';
        m += '</td></tr>';
        m += '<TR><td><div  class=trStat>CHAMP PRESET NAMING</div></td></TR>';
        m += '<tr><td>';
        if (OrganizerMaxChampions == 0) {
            m += 'No Champions';
        } else {

            m += '<table>';

            var presetsList = "";
            for (var i = 1; i < OrganizerMaxChampions + 1; i++) {
                presetsList += '<option value="' + i + '">' + i + '</option>';
            }

            for (var i = 1; i < OrganizerMaxChampions+1; i++) {
                var thisChampion = unsafeWindow.seed.champion.champions[i-1];
                m += '<tr>';
                m += '<td><input class=chPresetSlotPost type=button id=chPreset' + i + ' value="Post Slot"></td>';
                m += '<td><input class=chPresetTagPost type=button id=chPreset' + 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=chPresetNameEntry type=text size=15 id=chPresetName' + i + ' value="' + CHpresetData.presetNames[i-1] + '"></td>';
                m += '<td><input class=chPresetCopyTo type=button id=chPreset' + i + ' value="Copy To"><select id=chPresetCopyToWhat' + i + '>' + presetsList + '</select></td>';
                m += '<td><input class=chPresetSave type=button id=chPreset' + i + ' value="Save"></td>';
            
                if (getPresetCHTagCount(i) != 0) {
                    m += '<td><input class=chPresetClear type=button id=chPreset' + i + ' value="Clear"></td>';
                    m += '<td><input class=chPresetExcel type=button id=chPreset' + i + ' value="Excel"></td>';
                } else {
                    m += '<td/><td/>';
                }
                m += '</tr>';
            
            }

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

        m += '<TR><td><div  class=trStat>BREAK CHAMP HALL</div></td></TR>';
        m += '<tr><td>';

        m += '<TABLE id=trOptionTbl width=100% height=0% class=trTab>';
        m += '<tr><td><div id=chMightBroke></div></td></tr>';
        m += '<tr><td><input type=checkbox checked id=chExcludePresets>Exclude Tagged Presets</td></tr>';
        m += '<tr><td><input type=checkbox checked id=chExcludeTags>Exclude Regular Tagged</td></tr>';
        m += '<tr><td>Break Items Level <select id=chBreakLevelLow>';
        for (i = 1; i < OrganizerMaxCHLevel; i++) {
            m += '<option value=' + i + '>' + i + '</option>';
        }
        m += '</select> or Higher</td></tr>';
        m += '<tr><td>Break Items Level <select id=chBreakLevelHigh>';
        for (i = 1; i < OrganizerMaxCHLevel; i++) {
            m += '<option value=' + i + (i == OrganizerMaxCHLevel-1 ? ' SELECTED' : '') + '>' + i + '</option>';
        }
        m += '</select> or Lower</td></tr>';
        m += '<tr><td><input type=button id=chBreakAll value="Break CH"><font color=red><i>(all options above will reset after refresh)</i></font></td></tr>';
        m += '<tr><td><div id=chBreakCounter></div></td></tr>';
        m += '</table>';

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

        t.myDiv.innerHTML = m;

        document.getElementById('chMightBroke').innerHTML = getChampBrokeMight();

        $('#chShowMight').change(function () {
            CHpresetData.showCHMight = document.getElementById('chShowMight').checked;
            CHsavePresetData();
        });

        $('#chShowName').change(function () {
            CHpresetData.showCHName = document.getElementById('chShowName').checked;
            CHsavePresetData();
        });

        $('#chBreakAll').click(function () {
            if (!confirm('You cannot undo this action, are you sure you want to break your champ hall?')) return;
            var excludePresets = document.getElementById('chExcludePresets').checked;
            var excludeTags = document.getElementById('chExcludeTags').checked;
            var breakLevelLow = document.getElementById('chBreakLevelLow').value;
            var breakLevelHigh = document.getElementById('chBreakLevelHigh').value;
            var allTaggedPresets = [];
            if (excludePresets) {
                for (i = 1; i < OrganizerMaxChampions + 1; i++) {
                    if (getPresetCHTagCount(i) != 0) {
                        var thisPreset = getPresetCHObject(i);
                        for (var champId in thisPreset) {
                            var champ_item = unsafeWindow.kocChampionItems[champId];
                            if (champ_item == null || !champ_item) continue;
                            if (champ_item.level == OrganizerMaxCHLevel) continue;
                            if (champ_item.level < breakLevelLow || champ_item.level > breakLevelHigh) continue;
                            allTaggedPresets.push(champId);
                        }
                    }
                }
            }
            
            var champToBreak = [];
            for (chId in unsafeWindow.kocChampionItems) {
                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (champ_item == null || !champ_item) continue;
                if (champ_item.status != 1) continue;//card broken?
                if (excludeTags && CHpresetData.taggedItems[chId]) continue;
                if (allTaggedPresets.indexOf(chId) != -1) continue;
                if (champ_item.level == OrganizerMaxCHLevel) 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 = unsafeWindow.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 == OrganizerMaxCHLevel) 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 + OrganizerBreakAstoneBuffer <= 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);

        });


        // read the preset names and descriptions
        $("input.chPresetNameEntry").change(function () {
            var id = $(this).attr('id');
            var num = id.split("chPresetName")[1];
            var presetName = $(this).val();
            if (presetName == "") {
                presetName = "undefined";
                document.getElementById(id).value = presetName;
            }
            CHpresetData.presetNames[num-1] = presetName;
            CHsavePresetData();
            Tabs.champPreview.init($("#tabs-previewCH")[0]);
        });

        $("input.chPresetNameEntry").blur(function () {
            var id = $(this).attr('id');
            var num = id.split("chPresetName")[1];
            var presetName = $(this).val();
            if (presetName == "") {
                presetName = "undefined";
                document.getElementById(id).value = presetName;
                CHpresetData.presetNames[num-1] = presetName;
                CHsavePresetData();
                Tabs.champPreview.init($("#tabs-previewCH")[0]);
            }
        });

        $("input.chPresetSave").click(function () {
            var id = $(this).attr('id');
            var num = id.split("chPreset")[1];
            Tabs.champPresets.addPresetTags(num);
            Tabs.champPresets.init($("#tabs-presetsCH")[0]);
        });

        $("input.chPresetSlotPost").click(function () {
            var id = $(this).attr('id');
            var num = id.split("chPreset")[1];
            postChampSlot(num);
        });

        $("input.chPresetTagPost").click(function () {
            var id = $(this).attr('id');
            var num = id.split("chPreset")[1];
            postChampPreset(num);
        });


        $("input.chPresetClear").click(function () {
            var id = $(this).attr('id');
            var num = id.split("chPreset")[1];
            Tabs.champPresets.clearPresetTags(num);
            Tabs.champPresets.init($("#tabs-presetsCH")[0]);
            Tabs.champPreview.init($("#tabs-previewCH")[0]);
        });

        $("input.chPresetExcel").click(function () {
            var id = $(this).attr('id');
            var num = id.split("chPreset")[1];
            ExportChampPresetToExcel(num);
        });

        $('#chClearAllPresetTags').click(function () {
            Tabs.champPresets.clearAllPresetTagItems();
            Tabs.champPresets.init($("#tabs-presetsCH")[0]);
        });

        $("input.chPresetCopyTo").click(function () {
            var id = $(this).attr('id');
            var sourceNum = id.split("chPreset")[1];
            var destNum = document.getElementById("chPresetCopyToWhat" + sourceNum).value;
            var copyName = document.getElementById("chPresetName" + sourceNum).value;
            Tabs.champPresets.copyPresetTags(sourceNum, destNum, copyName);
            Tabs.champPresets.init($("#tabs-presetsCH")[0]);
            Tabs.champPreview.init($("#tabs-previewCH")[0]);
        });


        $('#chSaveAllPresetTags').click(function () {
            for (i = 1; i < OrganizerMaxChampions + 1; i++) {
                Tabs.champPresets.addPresetTags(i);
            }
            Tabs.champPresets.init($("#tabs-presetsCH")[0]);
        });

        $('#chClearTags').click(function () {
            Tabs.champPresets.removeAllTagItems();
        });

        $('#chActiveColor').change(function () {
            CHpresetData.activeColor = $("#chActiveColor").val();
            CHsavePresetData();
        });

        $('#chPresetColor').change(function () {
            CHpresetData.presetColor = $("#chPresetColor").val();
            CHsavePresetData();
        });

        $('#chTagColor').change(function () {
            CHpresetData.tagColor = $("#chTagColor").val();
            CHsavePresetData();
        });


    },

    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('chBreakCounter').innerHTML = m;
    },

    unequipAll: function (presetIndex) {

        var championID = unsafeWindow.seed.champion.champions[presetIndex-1].championId;// = 11007

        var equipped_items = [];


        for (chId in unsafeWindow.kocChampionItems) {
            if (unsafeWindow.kocChampionItems[chId].equippedTo != championID) continue;
            equipped_items.push(chId);
        }

        var el = equipped_items.length;

        if ( el == 0 ) return;

        function unequipLoop(counter, id) {
            setTimeout(function() { Tabs.champPresets.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) {
        unsafeWindow.cm.ChampionManager.unequipItem(chId);
        Tabs.champPresets.paintTags();
    },

    equipItem: function(chId) {
        unsafeWindow.cm.ChampionManager.equipItem(chId);
    },

    clearPresetTags: function (presetIndex) {
        var t = Tabs.champPresets;
        var preset = getPresetCHObject(parseInt(presetIndex));
        for (var p in preset) {
            delete preset[p];
        }
        TRsavePresetData();
        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 < OrganizerMaxChampions + 1; i++) t.clearPresetTags(i);
        
    },

    equipPresetTags: function (presetIndex) {
        var t = Tabs.champPresets;

        var equipLoop = function (id) { return function() { Tabs.champPresets.equipItem(id); }; }
        var unequipLoop = function (id) { return function() { Tabs.champPresets.unequipItem(id) };  }
        
        var c = 1;
        
        var championID = unsafeWindow.seed.champion.champions[presetIndex-1].championId;// = 11007
        var equipped_items = [];
        for (chId in unsafeWindow.kocChampionItems) {
            if (unsafeWindow.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 = getPresetCHObject(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 = getPresetCHObject(parseInt(sourcePresetNumber));
        var pDestination = getPresetCHObject(parseInt(destinationPresetNumber));
        for (var p in pDestination) delete pDestination[p];
        for (var p in pSource) pDestination[p] = true;
        CHpresetData.presetNames[destinationPresetNumber-1] = presetName + " (copy)";
        CHsavePresetData();
    },

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

        var preset = getPresetCHObject(parseInt(presetIndex));

        var championID = unsafeWindow.seed.champion.champions[presetIndex-1].championId;// = 11007

        var equipped_items = [];

        for (chId in unsafeWindow.kocChampionItems) {
            if (unsafeWindow.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;
            CHsavePresetData();
        }

        t.paintTags();

    },

    paintTags: function () {
        for (ii in unsafeWindow.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 ( CHpresetData.taggedItems[ii] ) {
                $("div#" + ii + ".champItem").children(".ioverlay").prepend("<div class='tagBorderChamp'></div>");
            }
            $("div#" + ii + ".equipSelected ").children(".ioverlay").prepend("<div class='activeBorderChamp'></div>");
            if ( CHpresetData.taggedItems01[ii] || CHpresetData.taggedItems02[ii] || CHpresetData.taggedItems03[ii] || CHpresetData.taggedItems04[ii] ) {
                $("div#" + ii + ".champItem").children(".ioverlay").prepend("<div class='presetBorderChamp'></div>");
            }
        }

        $("#itemInvetory div").removeClass('blueBorder');
        $("#itemInvetory div").removeClass('yellowBorder');
        
        for (ii in CHqueueData.list) {
            var list_item = CHqueueData.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('blueBorder');
                if (list_item.action == "enhance") $("div#" + id + ".champItem").addClass('yellowBorder');
            }

        }

    },

    removeAllTagItems: function () {
        var t = Tabs.champPresets;
        var taggedReverse = [];
        for (k in CHpresetData.taggedItems) taggedReverse.push(k);
        var len = taggedReverse.length;
        while (len--) {
            var chID = taggedReverse[len];
            delete CHpresetData.taggedItems[chID];
            //$("#" + chID).children(".tagBorderChamp").remove();
            $("td#ch_card" + chID).find("div.greenBorder2").remove();
        }
        CHsavePresetData();
        t.paintTags();
    },

    removeTagItem: function (itemId) {
        var t = Tabs.champPresets;
        if (CHpresetData.taggedItems[itemId]) {
            delete CHpresetData.taggedItems[itemId];
//            $("#" + itemId).children(".tagBorderChamp").remove();
            $("td#ch_card" + itemId).find("div.greenBorder2").remove();
            CHsavePresetData();
        }
        t.paintTags();
    },

    addAllTagItems: function () {
        var t = Tabs.champPresets;
        t.removeAllTagItems();
        for (chId in unsafeWindow.kocChampionItems) {
            CHpresetData.taggedItems[chId] = true;
            $("td#ch_card" + chId).find("div.chbox").append("<div class='greenBorder2' style='border: 4px solid cyan; background: none; width: 228px; height: 255px;'></div>");
        }
        CHsavePresetData();
        t.paintTags();
    },

    addTagItem: function (itemId) {
        var t = Tabs.champPresets;
        CHpresetData.taggedItems[itemId] = true;
//        $("#" + itemId).prepend("<div class='tagBorderChamp'></div>");
        $("td#ch_card" + itemId).find("div.chbox").append("<div class='greenBorder2' style='border: 4px solid cyan; background: none; width: 228px; height: 255px;'></div>");
        CHsavePresetData();
        t.paintTags();
    },


    hide: function () {

    },

    show: function () {

    }
}

function upgradeIt(citynum, chId, cost) {
    var t = Tabs.champPresets;

    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

    params.action = '5';
    params.cityId = citynum;
    params.eid = chId;
    params.chanceItem = 0;
    params.aetherstones = cost;
    params.gems = 0;

        //params.tvuid;
                

	new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.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) unsafeWindow.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) {
        	    logit("upgrade exception");
                logit("Exception: " + inspect(e, 3, 1));
	        }
		},
		onFailure: function (rrr) {
		}		
	});

    return true;
}

/** ********************************* Throne Presets Tab ****************** **/
Tabs.thronePresets = {
    tabOrder: 1400,
    tabLabel: 'TR Preset',
    broke_count: 0,
    broke_items: 0,
    delay: 1000,
    myDiv: null,

    init: function (div) {
        var t = Tabs.thronePresets;
        t.myDiv = div;

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV class=trStat>THRONE PRESET TAGGING</div><TABLE id=trOptionTbl width=100% height=0% class=trTab>';
        m += '<tr><td width=100%>Preset Tag Color: <select id=trPresetColor>';
        m += '<option ' + (TRpresetData.presetColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (TRpresetData.presetColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (TRpresetData.presetColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (TRpresetData.presetColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (TRpresetData.presetColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (TRpresetData.presetColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (TRpresetData.presetColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (TRpresetData.presetColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tag Color: <select id=trTagColor>';
        m += '<option ' + (TRpresetData.tagColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (TRpresetData.tagColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (TRpresetData.tagColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (TRpresetData.tagColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (TRpresetData.tagColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (TRpresetData.tagColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (TRpresetData.tagColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (TRpresetData.tagColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>';
        m += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Active Preset Color: <select id=trActiveColor>';
        m += '<option ' + (TRpresetData.activeColor == "#FFFFFF" ? 'SELECTED ' : '') + 'value="#FFFFFF">White</option>';
        m += '<option ' + (TRpresetData.activeColor == "#808080" ? 'SELECTED ' : '') + 'value="#808080">Gray</option>';
        m += '<option ' + (TRpresetData.activeColor == "#FF0000" ? 'SELECTED ' : '') + 'value="#FF0000">Red</option>';
        m += '<option ' + (TRpresetData.activeColor == "#FFFF00" ? 'SELECTED ' : '') + 'value="#FFFF00">Yellow</option>';
        m += '<option ' + (TRpresetData.activeColor == "#00FF00" ? 'SELECTED ' : '') + 'value="#00FF00">Lime</option>';
        m += '<option ' + (TRpresetData.activeColor == "#00FFFF" ? 'SELECTED ' : '') + 'value="#00FFFF">Aqua</option>';
        m += '<option ' + (TRpresetData.activeColor == "#0000FF" ? 'SELECTED ' : '') + 'value="#0000FF">Blue</option>';
        m += '<option ' + (TRpresetData.activeColor == "#FF00FF" ? 'SELECTED ' : '') + 'value="#FF00FF">Fuchsia</option>';
        m += '</select>(Requires Refresh)</td></tr>';
        m += '<tr><td>';
        m += '<input type=button id=trClearTags value="Clear All Tags">';
        m += '<input type=button id=trClearAllPresetTags value="Clear All Preset Tags">';
        m += '<input type=button id=trSaveAllPresetTags value="Save All Preset Tags">';

        //m += '<input type=button id=trExportPresetTags value="Export Preset Tags">';

        m += '</td></tr>';
        m += '<tr><td>';
        m += '<input type=checkbox id=trShowMight ' + (TRpresetData.showTRMight ? 'CHECKED' : '') + '/>Show Might on Posts&nbsp;&nbsp;&nbsp;<input type=checkbox id=trShowName ' + (TRpresetData.showTRName ? 'CHECKED' : '') + '/>Show Preset Name on Posts';
        m += '</td></tr>';
        m += '<TR><td><div  class=trStat>THRONE PRESET NAMING</div></td></TR>';
        m += '<tr><td><div id=throneDefinition style="float: left; overflow-x: hidden; overflow-y: auto;">';
        m += '<table>';

        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=trPresetSlotPost type=button id=trPreset' + i + ' value="Post Slot"></td>';
            m += '<td><input class=trPresetTagPost type=button id=trPreset' + i + ' value="Post Tag"></td>';
            m += '<td>&nbsp;<b>Preset ' + i + ': </b></td>';
            m += '<td><input class=trPresetNameEntry type=text size=15 id=trPresetName' + i + ' value="' + TRpresetData.presetNames[i] + '"></td>';
            m += '<td><input class=trPresetCopyTo type=button id=trPreset' + i + ' value="Copy To"><select id=trPresetCopyToWhat' + i + '>' + presetsList + '</select></td>';
            m += '<td><input class=trPresetSave type=button id=trPreset' + i + ' value="Save"></td>';

            if (getPresetTRTagCount(i) != 0) {
                m += '<td><input class=trPresetClear type=button id=trPreset' + i + ' value="Clear"></td>';
                m += '<td><input class=trPresetExcel type=button id=trPreset' + i + ' value="Excel"></td>';
            } else {
                m += '<td/><td/>';
            }
            m += '</tr>';
        }
        m += '</table>';
        m += '</div></td></tr>';
        m += '<TR><td><div  class=trStat>BREAK THRONE ROOM</div></td></TR>';
        m += '<tr><td>';

        m += '<TABLE id=trOptionTbl width=100% height=0% class=trTab>';
        m += '<tr><td><div id=trMightBroke>You have 0 throne room might broken</div></td></tr>';
        m += '<tr><td><input type=checkbox checked id=trExcludePresets>Exclude Tagged Presets</td></tr>';
        m += '<tr><td><input type=checkbox checked id=trExcludeTags>Exclude Regular Tagged</td></tr>';
        m += '<tr><td>Break Items Level <select id=trBreakLevelLow>';
        for (i = 1; i < OrganizerMaxTRLevel; i++) {
            m += '<option value=' + i + '>' + i + '</option>';
        }
        m += '</select> or Higher</td></tr>';
        m += '<tr><td>Break Items Level <select id=trBreakLevelHigh>';
        for (i = 1; i < OrganizerMaxTRLevel; i++) {
            m += '<option value=' + i + (i == OrganizerMaxTRLevel - 1 ? ' SELECTED' : '') + '>' + i + '</option>';
        }
        m += '</select> or Lower</td></tr>';

        m += '<tr><td><input type=button id=trBreakAll value="Break Now"><font color=red><i>(all options above will reset after refresh)</i></font></td></tr>';
        m += '<tr><td><div id=trBreakCounter></div></td></tr>';
        m += '<tr><td><hr></td></tr>';
        m += '<tr><td>Break Equiped Throne Room Only<select id=trPresetEquipBreak>' + presetsList + '</select><input type=button id=trPresetEquipBreakNow value="Break Now"></td></tr>';
        m += '<tr><td>Break Tagged Preset Only<select id=trPresetTaggedBreak>' + presetsList + '</select><input type=button id=trPresetTaggedBreakNow value="Break Now"></td></tr>';
        m += '<tr><td>Break <input type=number id=trMightBreak oncontextmenu="return false;"> Throne Might <input type=button id=trMightBreakNow value="Break Now"></td></tr>';
        m += '</table>';

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

        m += '</div>';
        t.myDiv.innerHTML = m;
        
        document.getElementById('trMightBroke').innerHTML = getThroneBrokeMight();

        $('#trMightBreak').keydown(function (e) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
            // 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();
            }
        });

        $('#trMightBreak').keyup(function (e) {
            document.getElementById('trMightBreak').value = document.getElementById('trMightBreak').value.replace('.','');
            document.getElementById('trMightBreak').value = document.getElementById('trMightBreak').value.replace(',','');
        });

        $('#trMightBreakNow').click(function () {
            document.getElementById('trMightBreak').value = document.getElementById('trMightBreak').value.replace('.','');
            document.getElementById('trMightBreak').value = document.getElementById('trMightBreak').value.replace(',','');
            var mightReach = document.getElementById('trMightBreak').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 unsafeWindow.kocThroneItems) {
                if (mightTally >= mightReach) break;
                var throne_item = unsafeWindow.kocThroneItems[throneId];
                var throne_might = unsafeWindow.cm.ThroneView.getMightBonus(throne_item);
                mightTally += throne_might;
                throneToBreak.push(throneId);
            };
            BreakIt(throneToBreak);
        });


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

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

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

        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 = unsafeWindow.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 == OrganizerMaxTRLevel) 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 = unsafeWindow.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 + OrganizerBreakAstoneBuffer <= 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 = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                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(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
                    method: "post",
                    parameters: params,
                    loading: true,
                    onSuccess: function (transport) {
                        try {
                            var rslt = eval("(" + transport.responseText + ")");
                            if (rslt.ok) {
                                if (rslt.updateSeed) unsafeWindow.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!');
                                return;
                            }

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

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

            }

            unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.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();
            }
        }

        $('#trBreakAll').click(function () {
            if (!confirm('You cannot undo this action, are you sure you want to break your throne room?')) return;
            var excludePresets = document.getElementById('trExcludePresets').checked;
            var excludeTags = document.getElementById('trExcludeTags').checked;
            var breakLevelLow = document.getElementById('trBreakLevelLow').value;
            var breakLevelHigh = document.getElementById('trBreakLevelHigh').value;
            var allTaggedPresets = [];
            if (excludePresets) {
                for (i = 1; i < presetSlots + 1; i++) {
                    if (getPresetTRTagCount(i) != 0) {
                        var thisPreset = getPresetTRObject(i);
                        for (throneId in thisPreset) {
                            var throne_item = unsafeWindow.kocThroneItems[throneId];
                            if (throne_item == null || !throne_item) continue;
                            if (throne_item.level == OrganizerMaxTRLevel) continue;
                            if (throne_item.level < breakLevelLow || throne_item.level > breakLevelHigh) continue;
                            allTaggedPresets.push(throneId);
                        }
                    }
                }
            }
            var throneToBreak = [];
            for (trId in unsafeWindow.kocThroneItems) {
                var throne_item = unsafeWindow.kocThroneItems[trId];
                if (throne_item == null || !throne_item) continue;
                if (throne_item.isBroken) continue;
                if (excludeTags && TRpresetData.taggedItems[trId]) continue;
                if (allTaggedPresets.indexOf(trId) != -1) continue;
                if (throne_item.level == OrganizerMaxTRLevel) continue;
                if (throne_item.level < breakLevelLow || throne_item.level > breakLevelHigh) continue;

                throneToBreak.push(trId);
            }
            delete allTaggedPresets;

            BreakIt(throneToBreak);

        });


        $('#trShowMight').change(function () {
            TRpresetData.showTRMight = document.getElementById('trShowMight').checked;
            TRsavePresetData();
        });

        $('#trShowName').change(function () {
            TRpresetData.showTRName = document.getElementById('trShowName').checked;
            TRsavePresetData();
        });

        /*
        $('#trExportPresetTags').click(function() {
            var uriContent = 'data:application/octet-stream,' + encodeURIComponent(JSON.stringify(TRpresetData.taggedItems01));
            newWindow = window.open(uriContent, 'file.txt');                
        });
        */

        $('#trSaveAllPresetTags').click(function () {
            for (i = 1; i < presetSlots + 1; i++) {
                Tabs.thronePresets.addPresetTags(i);
            }
            Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
        });


        $('#trClearTags').click(function () {
            Tabs.thronePresets.clearAllTagItems();
        });


        $('#trClearAllPresetTags').click(function () {
            Tabs.thronePresets.clearAllPresetTagItems();
            Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
        });


        $('#trActiveColor').change(function () {
            TRpresetData.activeColor = $("#trActiveColor").val();
            TRsavePresetData();
        });

        $('#trPresetColor').change(function () {
            TRpresetData.presetColor = $("#trPresetColor").val();
            TRsavePresetData();
        });

        $('#trTagColor').change(function () {
            TRpresetData.tagColor = $("#trTagColor").val();
            TRsavePresetData();
        });

        //trPresetCopyTo
        $("input.trPresetCopyTo").click(function () {
            var id = $(this).attr('id');
            var sourceNum = id.split("trPreset")[1];
            var destNum = document.getElementById("trPresetCopyToWhat" + sourceNum).value;
            var copyName = document.getElementById("trPresetName" + sourceNum).value;
            Tabs.thronePresets.copyPresetTags(sourceNum, destNum, copyName);
            Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
            Tabs.thronePreview.init($("#tabs-previewTR")[0]);
        });

        $("input.trPresetClear").click(function () {
            var id = $(this).attr('id');
            var num = id.split("trPreset")[1];
            Tabs.thronePresets.clearPresetTags(num);
            Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
            Tabs.thronePreview.init($("#tabs-previewTR")[0]);
        });

        $("input.trPresetExcel").click(function () {
            var id = $(this).attr('id');
            var num = id.split("trPreset")[1];
            ExportThronePresetToExcel(num);
        });

        $("input.trPresetSave").click(function () {
            var id = $(this).attr('id');
            var num = id.split("trPreset")[1];
            Tabs.thronePresets.addPresetTags(num);
            Tabs.thronePresets.init($("#tabs-presetsTR")[0]);
        });

        $("input.trPresetSlotPost").click(function () {
            var id = $(this).attr('id');
            var num = id.split("trPreset")[1];
            postThroneSlot(num);
        });

        $("input.trPresetTagPost").click(function () {
            var id = $(this).attr('id');
            var num = id.split("trPreset")[1];
            postThronePreset(num);
        });

        $("input.trPresetNameEntry").blur(function () {
            var id = $(this).attr('id');
            var num = id.split("trPresetName")[1];
            var presetName = $(this).val();
            if (presetName == "") {
                presetName = "undefined";
                document.getElementById(id).value = presetName;
                TRpresetData.presetNames[num] = presetName;
                TRsavePresetData();
                Tabs.thronePreview.init($("#tabs-previewTR")[0]);
            }
        });

        // read the preset names and descriptions
        $("input.trPresetNameEntry").change(function () {
            var id = $(this).attr('id');
            var num = id.split("trPresetName")[1];
            var presetName = $(this).val();
            if (presetName == "") {
                presetName = "undefined";
                document.getElementById(id).value = presetName;
            }
            TRpresetData.presetNames[num] = presetName;
            TRsavePresetData();
            Tabs.thronePreview.init($("#tabs-previewTR")[0]);
        });

    },

    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>");
            //if (GeneralOptions.graphicalThrone) { $("div#trCardOrganizerItem" + throneId).find("div.trCard").append("<div class='activeBorder2' style='border: 3px solid " + TRpresetData.activeColor + "; background: none; width: 145px; height: 195px;'></div>"); }

        }

        for (p in TRpresetData.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 < 17; idx++) {
            var preset = getPresetTRObject(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 (GeneralOptions.showJewels) {
            for (trId in unsafeWindow.kocThroneItems) {
                var throne_item = unsafeWindow.kocThroneItems[trId];
                if (throne_item.jewel && 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='" + JewelImages[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];
            var equipped_items = Seed.throne.slotEquip[Seed.throne.activeSlot];
            for (ei = 0; ei < equipped_items.length; ei++) {
                var trId = equipped_items[ei]
                if (unsafeWindow.kocThroneItems[trId].type == throneType) break;
                trId = ''
            }
            if (trId == '') return;
            var throne_item = unsafeWindow.kocThroneItems[trId];
            if (throne_item == null || !throne_item) return;
            var thisDiv = document.getElementById(displayContainer);
            var trDiv = document.getElementById('throneInventoryItem' + trId);
            var oldDiv = trDiv.parentNode;
            thisDiv.appendChild(trDiv);
            unsafeWindow.cm.ContextualMenuThrone.renderMenu(trDiv, throne_item);
            oldDiv.appendChild(trDiv);
        };

    },

    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('trBreakCounter').innerHTML = m;
    },

    unequipAllItems: function (presetIndex) {

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

        if (GeneralOptions.compactView) {
            var t = Tabs.throneOrganizerCompact;
        } else {
            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 = unsafeWindow.kocThroneItems[items.pop()];

            var goUnequip = function (I2, s) {
                return function () {
                    t.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;
        }

        if (GeneralOptions.compactView) {
            var t = Tabs.throneOrganizerCompact;
        } else {
            var t = Tabs.throneOrganizer;
        }
        var preset = getPresetTRObject(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 = unsafeWindow.kocThroneItems[p];

            types_equiped.push(throne_item.type);

            if (!throne_item.isEquipped) {

                var goEquip = function (I2, s) {
                    return function () {
                        t.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 = unsafeWindow.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 () {
                        t.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 = getPresetTRObject(parseInt(sourcePresetNumber));
        var pDestination = getPresetTRObject(parseInt(destinationPresetNumber));
        for (var p in pDestination) delete pDestination[p];
        for (var p in pSource) pDestination[p] = true;
        TRpresetData.presetNames[destinationPresetNumber] = presetName + " (copy)";
        TRsavePresetData();
    },

    addPresetTags: function (presetIndex) {  //presetIndex should be passed in as base 0 to index into the presetTaggedItems array

        var preset = getPresetTRObject(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>");
            TRsavePresetData();
        }
    },

    clearPresetTags: function (presetIndex) {
        var preset = getPresetTRObject(parseInt(presetIndex));
        //document.getElementById('trPresetName' + presetIndex).value = "undefined";
        //TRpresetData.presetNames[presetIndex] = "undefined";
        for (var p in preset) {
            delete preset[p];
            $("#throneInventoryItem" + p).children(".presetBorderThrone").remove();
            TRsavePresetData();
        }
    },

    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('trPresetName' + i).value = "undefined";
            TRpresetData.presetNames[i] = "undefined";
            var preset = getPresetTRObject(i);
            for (var p in preset) {
                delete preset[p];
                $("#throneInventoryItem" + p).children(".presetBorderThrone").remove();
                TRsavePresetData();
            }
        }
    },

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

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

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

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

    hide: function () {

    },

    show: function () {

    }
}

/** ********************************* Tutorials Tab *********************** **/
Tabs.Tutorials = {
    tabOrder: 1700,
    tabLabel: 'Tutorials',
    myDiv: null,

    init: function (div) {
        var t = Tabs.Tutorials;
        t.myDiv = div;
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV class=chStat>TUTORIALS</div>';
        m += '<table>';
        m += '<tr><td valign=top><b>Click A Tutorial Below&nbsp;</b><br>';
        m += '<ul style="list-style-type: none;">';
        m += '<li style="text-indent: -2em;"><input type=button id="tutVid1Play" class="tutVid" value="Tutorial 1" title="Preview/Preset/Repair Tabs Tutorial"></li>';
        m += '<li style="text-indent: -2em;"><input type=button id="tutVid2Play" class="tutVid" value="Tutorial 2" title="Throne Organizer-Preview Tutorial"></li>';
        m += '</ul>';
        m += '</td>';
        m += '<td><iframe id="tutVid" src="" width="500" height="300"></iframe></td></tr>';
        m += '</table>';
        m += '</div>';

        t.myDiv.innerHTML = m;
        $("#tutVid1Play").click(function () {
            $("#tutVid").attr("src", "http://www.youtube.com/embed/fXlHAzszico?rel=0&autoplay=1");
        });

        $("#tutVid2Play").click(function () {
            $("#tutVid").attr("src", "http://www.youtube.com/embed/-maykvcbk4o?rel=0&autoplay=1");
        });

    },
    hide: function () {
    },
    show: function () {
    }
}


/** ********************************* Links Tab *************************** **/
Tabs.Links = {
    tabOrder: 1600,
    tabLabel: 'Links',
    myDiv: null,

    init: function (div) {
        var t = Tabs.Links;
        t.myDiv = div;
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV style="height:535px; max-height:235px;">';
        m += '<DIV class=chStat>LINKS <i>(click titles to expand)</i></div>';
        m += '<TABLE cellpadding=0 cellspacing=0 width=100%>';

        m += '<TR><TD align=center><div id=link1 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>KOC Throne Room & Champ Organizer</td></tr>';
        m += '<TR><TD align=center><div id=link1data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://greasyfork.org/en/scripts/2610-koc-throne-room-champ-organizer"><font class=koclinks>https://greasyfork.org/en/scripts/2610-koc-throne-room-champ-organizer</a><br>';
        m += '<font class=koclinksdesc>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=link2 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>KOC Power Bot - Official KoC Scripters Edition</td></tr>';
        m += '<TR><TD align=center><div id=link2data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://greasyfork.org/scripts/892-koc-power-bot"><font class=koclinks>https://greasyfork.org/scripts/892-koc-power-bot</a><br>';
        m += '<font class=koclinksdesc>A powerful bot that automates features for KOC</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link3 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>KOC Power Tools - Official KoC Scripters Edition</td></tr>';
        m += '<TR><TD align=center><div id=link3data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://greasyfork.org/scripts/893-koc-power-tools"><font class=koclinks>https://greasyfork.org/scripts/893-koc-power-tools</a><br>';
        m += '<font class=koclinksdesc>A powerful tools that enhances the game and bug fixes for KOC</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link4 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>KoC Battle Console</td></tr>';
        m += '<TR><TD align=center><div id=link4data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://greasyfork.org/scripts/890-koc-battle-console"><font class=koclinks>https://greasyfork.org/scripts/890-koc-battle-console</a><br>';
        m += '<font class=koclinksdesc>Extremely useful console for controlling battles in KOC</font><br>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link5 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Firefox Version 19 (windows users)</td></tr>';
        m += '<TR><TD align=center><div id=link5data class=linkData style="display:none;">';
        m += '<a target="_blank" href="http://filehippo.com/download_firefox/14364/"><font class=koclinks>http://filehippo.com/download_firefox/14364/</a><br>';
        m += '<font class=koclinksdesc>A fast, light and tidy open source web browser, and the best browser for running KOC</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link6 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Firefox Version 19 (mac users)</td></tr>';
        m += '<TR><TD align=center><div id=link6data class=linkData style="display:none;">';
        m += '<a target="_blank" href="http://www.oldapps.com/mac/firefox.php?old_firefox=11885"><font class=koclinks>http://www.oldapps.com/mac/firefox.php?old_firefox=11885</a><br>';
        m += '<font class=koclinksdesc>A fast, light and tidy open source web browser, and the best browser for running KOC</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link7 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Greasemonkey ver1.10.1 Signed (for Firefox 19)</td></tr>';
        m += '<TR><TD align=center><div id=link7data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://addons.mozilla.org/en-us/firefox/addon/greasemonkey/versions/1.10.1-signed"><font class=koclinks>https://addons.mozilla.org/en-us/firefox/addon/greasemonkey/versions/1.10.1-signed</a><br>';
        m += '<font class=koclinksdesc>A Firefox 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=link8 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Google Translator - Plugin for Firefox</td></tr>';
        m += '<TR><TD align=center><div id=link8data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/google-translator-for-firefox/"><font class=koclinks>https://addons.mozilla.org/en-US/firefox/addon/google-translator-for-firefox/</a><br>';
        m += '<font class=koclinksdesc>With this addon you can translate any text to your own language with one click or hot-key</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link9 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Reload Every - Plugin for Firefox</td></tr>';
        m += '<TR><TD align=center><div id=link9data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/reloadevery/"><font class=koclinks>https://addons.mozilla.org/en-US/firefox/addon/reloadevery/</a><br>';
        m += '<font class=koclinksdesc>Reloads web pages every so many seconds or minutes</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link10 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>F89 Unofficial KOC Guide</td></tr>';
        m += '<TR><TD align=center><div id=link10data class=linkData style="display:none;">';
        m += '<a target="_blank" href="http://f89kocguide.weebly.com/"><font class=koclinks>http://f89kocguide.weebly.com/</a><br>';
        m += '<font class=koclinksdesc>KOC Guide</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link11 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Teamviewer</td></tr>';
        m += '<TR><TD align=center><div id=link11data class=linkData style="display:none;">';
        m += '<a target="_blank" href="http://www.teamviewer.com/en/index.aspx"><font class=koclinks>http://www.teamviewer.com/en/index.aspx</a><br>';
        m += '<font class=koclinksdesc>Remote control any computer or Mac over the internet within seconds or use TeamViewer for online meetings</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link12 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Greasy Fork</td></tr>';
        m += '<TR><TD align=center><div id=link12data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://greasyfork.org/"><font class=koclinks>https://greasyfork.org/</a><br>';
        m += '<font class=koclinksdesc>Greasy Fork is aiming to become the premier user script site after the collapse of userscripts.org, with the biggest audience for your scripts</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link13 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Throne Room Spreadsheet</td></tr>';
        m += '<TR><TD align=center><div id=link13data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://docs.google.com/spreadsheets/d/1gs02x8aURak1D4MGTBzrYc5_ZDAg6cB_Kq2xiRU6kfE/edit?pli=1#gid=0"><font class=koclinks>https://docs.google.com/spreadsheets/d/1gs02x8aURak1D4MGTBzrYc5_ZDAg6cB_Kq2xiRU6kfE/edit?pli=1#gid=0</a><br>';
        m += '<font class=koclinksdesc>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=link14 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>AeroAdmin</td></tr>';
        m += '<TR><TD align=center><div id=link14data class=linkData style="display:none;">';
        m += '<a target="_blank" href="http://www.aeroadmin.com"><font class=koclinks>http://www.aeroadmin.com</a><br>';
        m += '<font class=koclinksdesc>FREE and EASY remote desktop software! Set up remote desktop connection within a few seconds!  No installation, no configuration, works behind NAT.</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link15 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>No Copy Paste</td></tr>';
        m += '<TR><TD align=center><div id=link15data class=linkData style="display:none;">';
        m += '<a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/nocopypaste/"><font class=koclinks>https://addons.mozilla.org/en-US/firefox/addon/nocopypaste/</a><br>';
        m += '<font class=koclinksdesc>This extension prevents websites from interfering with your copy and paste actions.</font>';
        m += '</div></td></tr>';

        m += '<TR><TD align=center><div id=link16 class=orgLinks style="cursor:pointer;"><font class=koclinksheader>Aderik\'s Slideshows For KOC</td></tr>';
        m += '<TR><TD align=center><div id=link16data class=linkData style="display:none;">';
        m += '<a target="_blank" href="http://www.slideshare.net/aderik/documents"><font class=koclinks>http://www.slideshare.net/aderik/documents</a><br>';
        m += '<font class=koclinksdesc>Aderik has a guide for just about anything!</font>';
        m += '</div></td></tr>';

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

        t.myDiv.innerHTML = m;

        $("div.orgLinks").click(function () {
            var id = $(this).attr('id');
            var linkNumber = id.split("link")[1];
            var divLinkName = 'link' + linkNumber + 'data';
            var divLink = document.getElementById(divLinkName);
            var hidden = (divLink.style.display == "none");
            var links = $('.linkData');
            for (i = 1; i < links.length + 1; i++) {
                document.getElementById('link' + i + 'data').style.display = "none";
            }
            if (hidden) {
                divLink.style.display = "block";
            } else {
                divLink.style.display = "none";
            }
        });
    },
    hide: function () {
    },
    show: function () {
    }
}

function NewsListItemTR(msg) {
    var m = '<TR><TD>&#149';
    m += msg;
    m += '</td></tr>';
    return m;
}

function NewsEndSection() {
    var m = '</table>';
    return m;
}

function NewsUpcomingListItemTR(msg) {
    var m = '<TR><TD>&#149';
    m += msg;
    m += '</td></tr>';
    return m;
}

function NewsUpdateHeader(headerMsg) {
    var m = '<DIV class=chStat>' + headerMsg + '</div>';
    m += '<TABLE cellpadding=0 cellspacing=0 width=100%>';
    return m;
}


/** ********************************* News Tab **************************** **/
Tabs.News = {
    tabOrder: 1500,
    tabLabel: 'News',
    myDiv: null,

    init: function (div) {
        var t = Tabs.News;
        t.myDiv = div;
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV class=chStat>NEWS</div>';
        m += '<DIV style="height:535px; max-height:535px;">';
        m += '<TABLE cellpadding=0 cellspacing=0 width=100% height=35px>';
        m += '<TR><TD align=center>';
        m += '<a href="https://www.facebook.com/koctrorgbyne0" 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%2Fkoctrorgbyne0&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>WE HIT 1,400+ LIKES ON THE FACEBOOK PAGE, THANK YOU ALL MY SUPPORTERS!!! (AND DONATORS!!!)</b></td></tr>';
        m += '</table>';
//        m += NewsUpdateHeader('COMING SOON!!! (no promises, but i will try)');
//        m += NewsUpcomingListItemTR('add a "mark for deletion" to throne & champ room (requested by Howard Clifton)');
//        m += NewsUpcomingListItemTR('Local throne presets interaction with preview tab (requested by Bethany Stout)');
//        m += NewsUpcomingListItemTR('Save repair queue list to file, similarly to throne/champ rules (requested by Patrick Bammens)');
//        m += NewsUpcomingListItemTR('Append throne & champ rules to existing rules');
//        m += NewsUpcomingListItemTR('put a "unique champ items" tab in if i can find the coding for it within kabams MESS of code, lol');
//        m += NewsUpcomingListItemTR('add a local champ preset widget, just like regular presets (requested by Pixie Cinnamon MacCarthy)');
//        m += NewsUpcomingListItemTR('local presets for champs (requested by Anna Szalkiewicz)');
//        m += NewsUpcomingListItemTR('edit existing salvager rules (requested by Audrius Audriulaitis)');
//        m += NewsUpcomingListItemTR('compare presets (requested by Jan Crenshaw Frady)');
//        m += NewsUpcomingListItemTR('add Master Tokens and Forge Tokens to the upgrader tabs (requested by Eric Wong)');
//        m += NewsUpcomingListItemTR('compare caps to current preset and show overcap actives in red (requested by Eric Wong)');
//        m += NewsUpcomingListItemTR('add jewels to preview tab, to see what cards look like with different jewels (requested by Antwyn Collins)');
//        m += NewsUpcomingListItemTR('auto sort by quality, type or level for upgrade tabs (requested by Jonathan Johnston)');
//        m += NewsUpcomingListItemTR('add auto-switch back to upgrading once repair list is complete (requested by Kash)');
//        m += NewsEndSection();
        m += '<DIV class=chStat>~~ UPDATES ~~</div>';
        m += NewsUpdateHeader('OCT 01-2015');
        m += NewsListItemTR('added some missing champ effects for rule making');
        m += NewsEndSection();
        m += NewsUpdateHeader('SEPT 30-2015');
        m += NewsListItemTR('opened context menu for champ rings');
        m += NewsListItemTR('fixed champ organizer to read only ONE ring (to rule them all!!!  lol) instead of 2');
        m += NewsListItemTR('post to chat reads ring instead of ring 1');
        m += NewsListItemTR('rules for champs will search for ring, not ring 1 or ring 2');
        m += NewsUpdateHeader('SEPT 11-2015');
        m += NewsListItemTR('removed greaseyfork as the main download for updates, it will now update straight from my website');
        m += NewsListItemTR('fixed the enhancement/upgrading statistics pages, did not realize they were not pushed for higher levels');
        m += NewsEndSection();
        m += NewsUpdateHeader('SEPT 05-2015');
        m += NewsListItemTR('got rid of the useless bacon phrase, sorry everyone, trying to keep relavent for my future revamp');
        m += NewsListItemTR('added an "upgrade all to level" option, for those events that are garunteed upgrade to a certain level');
        m += NewsListItemTR('removed selectable site to update, updates only on greaseyfork at this time');
        m += NewsListItemTR('added the ability to remove the new "chance" upgrade tokens from the dropdown');
        m += NewsListItemTR('updated some links and added Aderiks slideshow links');
        m += NewsEndSection();
        m += NewsUpdateHeader('AUGUST/JULY 2015');
        m += NewsListItemTR('fixed the disabling of upgrade button when below the safety threshold defined by user');
        m += NewsListItemTR('made auto selecting next masters token on manual upgrade');
        m += NewsListItemTR('added "tag all" to throne/champ inventory, this tags everything with a generic tag (requested by Sam Adams)');
        m += NewsListItemTR('WARNING!!!: changes in game code have caused disabling the upgrade button when below threshold to not work');
        m += NewsEndSection();
        m += NewsUpdateHeader('MAY/JUNE 2015');
        m += NewsListItemTR('fixed preset tagging to include the new 8 rows');
        m += NewsListItemTR('fixed the new 8 row preset glitch that causes the last card collection row to cut off (thanks Barbarossa Smith)');
        m += NewsListItemTR('fixed so higher master tokens would show when disabling them');
        m += NewsListItemTR('added the 8 new throne presets to the widget');
        m += NewsListItemTR('removed the "Disable success animation" which i left in by mistake while testing a few releases ago');
        m += NewsListItemTR('fixed the images due to kabam changing their image host');
        m += NewsListItemTR('fixed the images links on the uniques throne pictures as well');
        m += NewsEndSection();
        m += NewsUpdateHeader('FEBRUARY/MARCH 2015');
        m += NewsListItemTR('fixed for missing throne uniques');
        m += NewsListItemTR('added "clear stats" buttons to all 4 stats tabs so you can reset the stats (requested by Shadows)');
        m += NewsListItemTR('made the popup menu for pendants available in champs');
        m += NewsEndSection();
        m += NewsUpdateHeader('JANUARY 2015');
        m += NewsListItemTR('kabam changed code on side bar in throne panel, had to adjust code to fix it');
        m += NewsListItemTR('fixed glitch when you click next on throne card it would only show in compact view');
        m += NewsListItemTR('fixed glitch when deleting throne/champ rules when sorted (requested by Corinne Morris)');
        m += NewsListItemTR('added break individual equipped throne room (requested by Ron Moe)');
        m += NewsListItemTR('added break individual tagged presest throne room (requested by Ron Moe)');
        m += NewsListItemTR('added break throne room to a certain might level');
        m += NewsListItemTR('added throne/champ preview tab export to excel (thanks Barbarossa Smith)');
        m += NewsListItemTR('added export tagged presets to file (requested by Jaddoo Emmanuel)');
        m += NewsEndSection();
        m += NewsUpdateHeader('DECEMBER 2014');
        m += NewsListItemTR('fixed some display issues where sometimes you can only see the first 3 lines of a card');
        m += NewsListItemTR('fixed effects dropdown for champ organizer, where it was showing both buff and debuff for effect names');
        m += NewsListItemTR('removed clearing of the name from throne presets when you click "clear" (request by  Wendy Taylor)');
        m += NewsListItemTR('updated the change level when upgrading if you complete a level but want to go to another level on the same champ card (thanks Audrius Audriulaitis)');
        m += NewsListItemTR('updated advanced throne rules for new findings (thanks again Gunvald Storheil)');
        m += NewsListItemTR('updated link to Gunvalds spreadsheet on google');
        m += NewsListItemTR('added "any tower" to the salvage rules');
        m += NewsEndSection();
        m += NewsUpdateHeader('NOVEMBER 2014');
        m += NewsListItemTR('added damage back to the searchable champ stats even though it is only in weapon slot 1');
        m += NewsListItemTR('added options to show/hide preset names and might when posting to chat [find under preset tabs]');
        m += NewsListItemTR('added posting to chat, throne slots AND preset slots for throne rooms without room being active');
        m += NewsListItemTR('added posting to chat, champ slots AND preset slots for champ halls without hall being active');
        m += NewsListItemTR('added advanced rules for pillar');
        m += NewsListItemTR('added advanced rules section for champs');
        m += NewsListItemTR('added new throne item "pillar"');
        m += NewsListItemTR('fixed outlining of champ upgrade/enhance');
        m += NewsEndSection();
        m += NewsUpdateHeader('OCTOBER 2014');
        m += NewsListItemTR('i believe i fixed the champ might display');
        m += NewsListItemTR('fixed the salvage routine to make cloaks work properly');
        m += NewsListItemTR('added champ preview tab');
        m += NewsListItemTR('added a useless bacon phrase button as a joke for those bacon lovers who keep asking me for bacon stuff in the script');
        m += NewsListItemTR('script will now update new levels and qualities as kabam adds more, without a physical update from me');
        m += NewsListItemTR('added under the break throne/champ sections how much might is broken (requested by Antwyn Collins)');
        m += NewsListItemTR('added total champ might to the champion hall (requested by Kenneth Tompkins)');
        m += NewsListItemTR('added total champ might to the display when posting champ stats');
        m += NewsListItemTR('fixed some issues with unequip all, equip from preset and the copy feature for preset tags');
        m += NewsListItemTR('added a confirmation prompt to the break throne/champ buttons in case you hit them by accident');
        m += NewsListItemTR('added a "below" criteria for breaking throne/champ rooms (requested by Barrie Morris)');
        m += NewsListItemTR('added champ hall repair tab');
        m += NewsListItemTR('extended champ to level 14');
        m += NewsListItemTR('made throne/champ organizer display over all other bots (requested by Eric Wong)');
        m += NewsListItemTR('fixed some issues with horizontal spacing at the item selection for upgraders (requested by Eric Wong)');
        m += NewsListItemTR('added champ preset tagging');
        m += NewsListItemTR('added break champion hall');
        m += NewsListItemTR('added "unequip all" to champs');
        m += NewsListItemTR('added sort order to throne/champ salvager rules by card type (requested by Audrius Audriulaitis)');
        m += NewsListItemTR('added more hourglasses (requested by Henriette Paagh)');
        m += NewsListItemTR('added "no forced salvage" option to hide that feature if you want (requested by Jeffrey Donati)');
        m += NewsListItemTR('updated advanced salvager rules to include most recent updated info from spreadsheet');
        m += NewsListItemTR('moved the delete button for upgrader queue to the left, hopefully clearing up scrolling issues');
        m += NewsEndSection();
        m += NewsUpdateHeader('SEPTEMBER 2014');
        m += NewsListItemTR('added an "advanced rule" creater to salvage tab (requested by Jaddoo Emmanuel)');
        m += NewsListItemTR('added the ability to take all throne/champ items from one quality to another quality (requested by Gary Cummins)');
        m += NewsListItemTR('added a tutorial tab for the throne/champ tutorials');
        m += NewsListItemTR('added custom color choosing for the tabs');
        m += NewsListItemTR('added export preview throne setup to file (requested by Kenneth Tompkins)');
        m += NewsListItemTR('added a throne uniques tab (thanks to Barbarossa Smith)');
        m += NewsListItemTR('changed tab colors (throne = green, champ = purple, bot = blue)');
        m += NewsListItemTR('with the change in tabs, I relabeled them and added hover title tooltip');
        m += NewsListItemTR('added "forced salvage" to the context menu, this will salvage an item even with a jewel');
        m += NewsListItemTR('fixed custom champ salvage button');
        m += NewsListItemTR('added back the column view in champ organizer, just like throne organizer you now have the compact option');
        m += NewsListItemTR('added export to excel file for throne AND champ inventory (requested by Leslie Grilley)');
        m += NewsListItemTR('added "Any Spellcaster" to the throne room rules (requested by Onebiggoxx Baker)');
        m += NewsListItemTR('fixed (hopefully) the auto update');
        m += NewsListItemTR('fixed the custom enhance/upgrade yellow buttons for champ context menu');
        m += NewsListItemTR('added a salvage button to the custom context menu for champs');
        m += NewsListItemTR('added the ability to take all champ items of one level to another level');
        m += NewsListItemTR('fixed sizing issue with throne organizer when in 11 column view');
        m += NewsListItemTR('added a repair throne item by level option to repair tab (requested by Peter Johnston)');
        m += NewsListItemTR('added back the 11 column view of throne organizer, BUT with an option to switch to compact view');
        m += NewsListItemTR('added the ability to take all throne items of one level to another level (requested by Ian Broadbent)');
        m += NewsListItemTR('added contextmenu to the champ item images');
        m += NewsListItemTR('added check to remove auto-enhance/upgrade if champ item is already at max rarity/level');
        m += NewsListItemTR('added menu on champ organizer when you select a card, just like throne organizer (requested by Robert Jon)');
        m += NewsListItemTR('fixed more bugs');
        m += NewsListItemTR('fixed problem with the images in throne room where the context menu would not work after switching thrones');
        m += NewsListItemTR('fixed the glitches that were causing the bot to crash while using the repair tab (lets cross our fingers!)');
        m += NewsListItemTR('added horizontal scroll bar to upgrader and repair queue lists');
        m += NewsListItemTR('fixed the champion card posting to chat and copying to clipboard');
        m += NewsListItemTR('fixed the preview stats loading in preview tr tab, after breaking it on my last update');
        m += NewsListItemTR('added back the "active" highlights to equipped cards in the organizer tab, but only while using the graphic view option');
        m += NewsListItemTR('fixed the display of uniques name in the textual display of throne cards (in preview, compare and organizer tab)');
        m += NewsListItemTR('added option to select the new textual display or the old graphical display for viewing cards');
        m += NewsListItemTR('reduced the number of repaints to each card in preview tr, which i believe was causing so many crashes');
        m += NewsListItemTR('added hover tooltip for champ card while in the champ upgrader and organizer tabs');
        m += NewsListItemTR('added context menu for throne cards in both compare tr tabs');
        m += NewsListItemTR('revamped throne room organizer tab to be more compact');
        m += NewsListItemTR('revamped champ room organizer tab to be more compact');
        m += NewsListItemTR('added more filters for champ in the organizer tab');
        m += NewsListItemTR('revamped size of the tr/champ bot so it should now fit on a screen even if you do not use widescreen mode');
        m += NewsListItemTR('revamped preview tr and compare tr visual display to make more compact and save space, also added card hover tooltip');
        m += NewsEndSection();
        m += NewsUpdateHeader('AUGUST 2014:');
        m += NewsListItemTR('added repair tab as optional for showing/hiding');
        m += NewsListItemTR('added "post stats to chat" for the preview tr tab (requested by Rodney Lamontagne)');
        m += NewsListItemTR('clearing tag items will also clear the name; also added prompt if you click "clear all preset tags"');
        m += NewsListItemTR('fixed a repair glitch that had to do with starting at the wrong repair item, AND sometimes items appearing as if fixed but not');
        m += NewsListItemTR('fixed links so that they will open in a new tab; also added a few more links');
        m += NewsListItemTR('added the "repair preset tag", allowing you to select a preset that you want to repair, providing you have it tagged beforehand');
        m += NewsListItemTR('added the name of the preset to the dropdowns wherever there is preset tagging involved, so you know the name of the preset instead of just the #');
        m += NewsListItemTR('added the "add all" for broken items in repair tab');
        m += NewsListItemTR('added an ETA for the total time to repair all queued items (requested by Patrick Bammens)');
        m += NewsListItemTR('fixed a glitch with preview tr, that if you previewed a card that was recently salvaged, it would cause bot to disappear');
        m += NewsListItemTR('added a repair tab to have enhanced functionality and more convenient options for repairing, like queing specific cards for repair (request by Rose Hodge)');
        m += NewsListItemTR('fixed a glitch with preview tr, that sometimes it would not load a random card from your preset slot setup');
        m += NewsListItemTR('fixed 6th row display on throne cards when posting to chat and on the display throughout the tr/champ bot (requested by PixieCinnamon)');
        m += NewsListItemTR('add a "click next" to the champ items upgrade panel just like the throne room has (requested by Dieter Neely)');
        m += NewsListItemTR('NOTICE: scrapping the idea of trying to extend the throne inventory panel to go wider so less scrolling through items, i seriously think its not possible, but the idea will always be in my head');
        m += NewsListItemTR('fixed might display on throne cards when choose "post stats to chat" or "copy stats"');
        m += NewsListItemTR('added enhance/upgrade stats tabs for champs');
        m += NewsListItemTR('added options to hide/show the new stats tabs for champs');
        m += NewsListItemTR('fixed a glitch with the new aether display in upgrade tabs, now displays appropriate city to use from');
        m += NewsListItemTR('added back the enhance/upgrade stats tab, as some users had really missed that feature, sorry i removed it, but added option to show/hide them');
        m += NewsEndSection();
        m += NewsUpdateHeader('JULY 2014:');
        m += NewsListItemTR('returned the aetherstone counter in the upgraders so people can know what cities they are reaping astone from and how much is left during upgrades/enhancements');
        m += NewsListItemTR('changed the height of the champion hall inventory so you do not have to scroll through your champ items (thanks to Barbarossa Smith)');
        m += NewsListItemTR('changed the links on the links tab to expand/contract when clicked');
        m += NewsListItemTR('added yes/no prompt for unequip all feature (requested by Dieter Neely and many others)');
        m += NewsListItemTR('added a save all presets button so you can save all your presets at once');
        m += NewsListItemTR('added throne menu options when clicking on the throne image, much like the champ room (requested by George Anadiotis)');
        m += NewsListItemTR('added the option to make hourglasses be restricted to specific levels or qualities');
        m += NewsListItemTR('reformated speedups section for better use of space, and put the "conditions of use" in a tooltip instead');
        m += NewsListItemTR('enhanced the card selection in preview tr to change the preview with up/down keyboard presses making for quicker viewing without the use of a mouse (request by Dean Mason)');
        m += NewsListItemTR('added counts of stones and tokens so people can track their quantity used during enhance/upgrade');
        m += NewsListItemTR('added a "load from preset tag" in the preview tr tab, that way people can view a broken tagged tr preset');
        m += NewsListItemTR('fixed the looping spinney during jewel attachment/removal process in the throne inventory panel');
        m += NewsListItemTR('added different colored jewels for the different jewel qualities (thanks Barbarossa Smith)');
        m += NewsListItemTR('added ability to load a throne room item into the "preview TR" section from organizer or the throne inventory panel');
        m += NewsListItemTR('added ability to load an actual throne preset into the "preview TR" section (requested by Pandora Box)');
        m += NewsListItemTR('changed compare to allow 3 cards to be compared (requested by Mary Bowyer)');
        m += NewsListItemTR('updated throne room max upgrade level to 19, which also allows 17s to be broke in the "break tr" function');
        m += NewsListItemTR('added a jewel filter to the throne organizer tab');
        m += NewsListItemTR('added "unique" to the filter list for throne qualities (thank you Barbarossa)');
        m += NewsListItemTR('added a "minimum" for only breaking throne items higher than selected (requested by Audrius Audriulaitis)');
        m += NewsListItemTR('enabled users to "show extra tabs", for those old schoolers who do not want bells n wistles');
        m += NewsListItemTR('added throne organizer filter for ignoring broken tr items (request by Kees Raymond Vermeulen)');
        m += NewsListItemTR('reversed the order that rules are added, newest rule will now display at the top');
        m += NewsListItemTR('added the rest of the higher MT past +12 to the remove from tokens option when manually upgrading');
        m += NewsListItemTR('added option to turn off "showing jewels" in the throne room inventory (requested by Jason DeLeone)');
        m += NewsListItemTR('fixed speedups, turns out by fixing the override i messed up normal speedups');
        m += NewsListItemTR('fixed the glitch with override hourglass feature');
        m += NewsListItemTR('added an astone buffer to the break tr of 50k, so you will need (50k + cost to upgrade) in your city or wont break');
        m += NewsListItemTR('fixed the "equipped to" feature for preset equipping when you copied from another preset, now it will unequip the types (i.e. chair, table, etc) that were not in the source preset');
        m += NewsListItemTR('added "preview tr", for setting up a throne room before you use it so enemy cannot see it, like a preview before using (requested by John Barnett)');
        m += NewsListItemTR('added "fail safe" protocol to stop the breaking feature if gems are used, after hearing of some people losing gems with the break TR feature somehow by mistake');
        m += NewsListItemTR('reworked the "break tr" function and removed previous authors checks for gem usage and made my own, should now be 100% secure no gem usage');
        m += NewsListItemTR('created an "override hourglass" function that allows you to use any 1 type of hourglass all the time no matter what (requested by Joe Stephens)');
        m += NewsListItemTR('added functionality for new throne item "Tapestry"');
        m += NewsListItemTR('fixed small glitch where throne cards can be broken when using lesser protection stones (thanks Audrius Audriulaitis)');
        m += NewsListItemTR('added notation to action log about remaining "boost items" if boost items are used (thanks Audrius Audriulaitis)');
        m += NewsListItemTR('updated the change level when upgrading if you complete a level but want to go to another level on the same card (thanks Audrius Audriulaitis)');
        m += NewsEndSection();
        m += NewsUpdateHeader('JUNE 2014:');
        m += NewsListItemTR('removed selection dropdown for type of update, now only updates using googlecode site');
        m += NewsListItemTR('added highlighting for active throne preset different color from rest (requested by John Barnett)');
        m += NewsListItemTR('added "copy to" for throne room presets so you can copy from 1 preset to another, then you can equip it into the destination preset');
        m += NewsListItemTR('fixed glitch when equiping from preset or unequiping all, jewel icon would start duplicating itself');
        m += NewsListItemTR('removed refresh prompt for when salvaging jewels is finished, bot will just refresh once done without prompt');
        m += NewsListItemTR('added descriptions to the links, giving the users more detail on what the links are for');
        m += NewsListItemTR('enabled users to switch on/off the "draggable" throne items option, some people have never liked that draggable option');
        m += NewsListItemTR('updated champion upgrade level to 12 ');
        m += NewsListItemTR('added a links tab for bots and other useful links ');
        m += NewsListItemTR('fixed break tr function so it will exclude level 17 cards that cannot be upgrade to 18 yet ');
        m += NewsListItemTR('enhanced the look/feel of jewel salvager, and also removed the 5 jewel cap ');
        m += NewsListItemTR('fixed early disabling of the dropdowns in jewel salvager if you do not select a jewel ');
        m += NewsListItemTR('fixed prompting if you do not select a throne item to salvage with ');
        m += NewsEndSection();
        m += NewsUpdateHeader('MAY 2014:');
        m += NewsListItemTR('fixed upgrade +1 glitch where you had to have upgrader set to ON in order for it to work ');
        m += NewsListItemTR('fixed messaging glitch when champ enhancements are successful ');
        m += NewsListItemTR('fixed refresh after breaking TR so you are not prompted after the message to refresh ');
        m += NewsListItemTR('added jewel salvager, to remove 5 jewels at a time (per click)... this feature will improve as i have more time to think of a better interface ');
        m += NewsListItemTR('added tokens and speedups to champ upgrader ');
        m += NewsListItemTR('removed the link to userscripts page until they get themselves sorted out ');
        m += NewsListItemTR('added a check to make sure you have hourglass in your inventory before it attempts to use any ');
        m += NewsListItemTR('added send to inbox upon success upgrade/enhancement (great for those who have refresh on & whisper log off) ');
        m += NewsListItemTR('separated back out the salvage by minimum safety option into the 2 types, throne room and champ ');
        m += NewsListItemTR('added a jewel indicator in the throne inventory screen so you know which items have jewels ');
        m += NewsListItemTR('BREAK YOUR THRONE ROOM!!!!!  that is right, by popular demand, you can now break your entire throne in 1 click within seconds! You can find this new feature in the presets tab ');
        m += NewsListItemTR('fixed the champ panel menu for removing of mass salvage and removing salvage from first ## ');
        m += NewsListItemTR('improved equip preset so it only equips items not already equipped and thus saving time ');
        m += NewsListItemTR('added more functionality to the presets section, now you can save preset tags without having the preset equipped ');
        m += NewsListItemTR('added posting of champ stats to chat ');
        m += NewsListItemTR('moved preset options from general organizer options to a new presets tab for more development ');
        m += NewsListItemTR('switched speedups section on upgrader, so the user can select the speedups they want to use  ');
        m += NewsListItemTR('fixed updater glitch, organizer will now auto update properly ');
        m += NewsListItemTR('added using speedups for repair times on throne items ');
        m += NewsListItemTR('added user defined upgrade/enhance levels for when using stones/tokens/orbs');
        m += NewsListItemTR('updated userscripts links to include 8080 so people can access them again, but i still recommend google code');
        m += NewsListItemTR('added using protection stones, orbs and tokens when enhancing/upgrading throne room items ');
        m += NewsListItemTR('combined both champ log & throne log into 1 complete log ');
        m += NewsListItemTR('added saving/loading of throne/champ salvage rules ');
        m += NewsListItemTR('fixed glitch for upgrader scrolling through queued items ');
        m += NewsListItemTR('additional option given to show or hide the local presets section in the options tab ');
        m += NewsListItemTR('added throne preset naming (options section), so now you will be able to define your type of throne room preset <br/>(NOTE: this does not show up in the throne panel, only on the preset widget and throne map area)');
        m += NewsListItemTR('post to chat will also post the name of your throne preset ');
        m += NewsListItemTR('fixed glitch for enhance/upgrade button which stuck in endless loop and crashed browser (only since miraculous was released) ');
        m += NewsListItemTR('enhanced and renamed the jewel inventory section to be like the other organizers with filtering (no sorting yet) ');
        m += NewsListItemTR('fixed code for loading champ salvager settings from another domain (thought i already did that, oops!) ');
        m += NewsListItemTR('fixed glitch where tagging would cause multiple borders around card, eventually hiding it, if it was tagged a lot ');
        m += NewsListItemTR('changed filtering to checked list boxes in throne organizer to flow more aesthetically pleasing ');
        m += NewsListItemTR('added quality filter to throne organizer ');
        m += NewsListItemTR('option given to show or hide the local presets section in throne organizer, giving some people more viewing room if they choose ');
        m += NewsListItemTR('added facebook link, facebook like/share, and userscripts link to news section ');
        m += NewsListItemTR('added equipping a throne preset by tags ');
        m += NewsListItemTR('added unequipping all throne items in an active preset ');
        m += NewsListItemTR('added throne preset tagging ');
        m += NewsListItemTR('added options for changing throne preset tag colors and general tag colors ');
        m += NewsListItemTR('added level 6 (miraculous) auto-enhancing ');
        m += NewsListItemTR('added a news section so users can see what is new in the latest update ');
        m += NewsListItemTR('added a throne room caps section so users can see the caps coded from the game');
        m += NewsListItemTR('added a jewel inventory section so users can view the jewels they have found');
        m += NewsEndSection();
        m += NewsUpdateHeader('APRIL 2014:');
        m += NewsListItemTR('added "remove all tags" from throne and champ organizer context menu ');
        m += NewsListItemTR('fixed minor glitch with the update dropdown selection');
        m += NewsListItemTR('integrated champion organizer functions to give users 2 for 1 organizer tool  ');
        m += NewsListItemTR('added donate button in the options tab, for those who care to donate');
        m += NewsListItemTR('added "preset #" to the throne room post to chat display so you know which # of throne room item you are displaying ');
        m += NewsListItemTR('removed most of the IDs for throne room items when posting and displaying (for now so it looks prettier, may add back later)');
        m += NewsListItemTR('removed stats tabs to reduce memory');
        m += NewsListItemTR('added a "compare" feature which allows the user to take 2 tr cards and pull them up side by side to compare the stats ');
        m += NewsListItemTR('added update dropdown to choose updating by Userscripts or Google Code');
        m += NewsListItemTR('temporarily removed the donate button');
        m += NewsEndSection();
        m += NewsUpdateHeader('MARCH 2014:');
        m += NewsListItemTR('added pets');
        m += NewsListItemTR('updated for level 17 upgrade');
        m += NewsListItemTR('fixed the NEXT on the upgrade/enhance to see future card stats ');
        m += NewsListItemTR('fixed the 6 slot display');
        m += NewsListItemTR('filter by throne types in organize tab');
        m += NewsListItemTR('added select all and unselect all to the throne and level filters (got tired of clicking 16 times to only show 1 level)');
        m += NewsListItemTR('fixed the auto update to work with this new script');
        m += NewsEndSection();
        m += '</div></div></div>';

        t.myDiv.innerHTML = m;
    },
    hide: function () {
    },
    show: function () {
    }
}

/** ********************************* Action Log Tab ********************** **/
Tabs.ActionLog = {
        tabOrder: 900,
        tabLabel : 'Action Log',
        myDiv : null,
        logTab : [null, null, null],
        maxEntries: 300,
        saveEntries : [[],[],[]],
        state : null,

        init : function (div){
            var t = Tabs.ActionLog;
            t.myDiv = div;
            var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
            m += '<DIV style="height:535px; max-height:535px;">';
            m += '<DIV class=chStat>UPGRADE LOG</div>';
            m += '<TABLE cellpadding=0 cellspacing=0 id=successlog class=chTabLined width=100%><TR><TD width=20%></td><TD width=80%></td></tr></table>';
            m += '<DIV class=chStat>ACTION LOG</div>';
            m += '<TABLE cellpadding=0 cellspacing=0 id=actionlog class=chTabLined  width=100%><TR><TD width=20%></td><TD width=80%></td></tr></table>';
            m += '<DIV class=chStat>SALVAGE LOG</div>';
            m += '<TABLE cellpadding=0 cellspacing=0 id=salvagelog class=chTabLined  width=100%><TR><TD width=20%></td><TD width=80%></td></tr></table>';
            m += '</div></div>';
            t.myDiv.innerHTML = m;
            t.logTab[0]  = document.getElementById('successlog');
            t.logTab[1]  = document.getElementById('actionlog');
            t.logTab[2]  = document.getElementById('salvagelog');
            t.state = 1;

            for (var j=0; j<3; j++)
            {
                var logVar = 'log_';
                if (j !=0)  logVar += (j + "_")
                logVar += getServerId();

                var a = JSON2.parse(GM_getValue (logVar, '[]'));

                if (matTypeof(a) == 'array'){
                    t.saveEntries[j] = a;
                    for (var i=0; i<t.saveEntries[j].length; i++)
                        t._addTab(j, t.saveEntries[j][i].msg, t.saveEntries[j][i].ts);
                }
            }

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

//            $("#ch_logScroll").resizable({
//                minWidth: 710,
//                maxWidth: 1000,
//                minHeight: 180,
//                maxHeight: 1100,
//                stop: function(event, ui) {
//                    CHupgradeData.logH = ui.size.height + 'px';
//                    CHupgradeData.logW = ui.size.width  + 'px';
//                    CHsaveUpgradeData();
//                }
//            });

//            $("#ch_logScroll").css('height', CHupgradeData.logH).css('width', CHupgradeData.logW);
        },

        hide : function (){
        },

        show : function (){
        },

        onUnload : function (){
            var t = Tabs.ActionLog;
            if (!ResetAll) GM_setValue ('log_'+getServerId(),  JSON2.stringify(t.saveEntries[0]));
            if (!ResetAll) GM_setValue ('log_1_'+getServerId(), JSON2.stringify(t.saveEntries[1]));
            if (!ResetAll) GM_setValue ('log_2_'+getServerId(), JSON2.stringify(t.saveEntries[2]));
        },

        _addTab : function (lnum, msg, ts){
            var t = Tabs.ActionLog;
            if (t.state != 1)
                return;
            if (t.logTab[lnum].rows.length >= t.maxEntries)
                t.logTab[lnum].deleteRow(t.maxEntries-1);
            var row = t.logTab[lnum].insertRow(0);
            row.vAlign = 'top';
            row.insertCell(0).innerHTML = ts;
            row.insertCell(1).innerHTML = msg;
        },

        log : function (lnum, msg){
            var t = Tabs.ActionLog;
            var d = new Date();
            var ts = d.toDateString().substring(3,10) + " "+ d.toTimeString().substring(0,8);
            t._addTab (lnum, msg, ts);
            while (t.saveEntries[lnum].length >= 30)
                t.saveEntries[lnum].shift();
            t.saveEntries[lnum].push ({msg:msg, ts:ts});
        }
}

function SuccessLog (msg){
    if (!Tabs.ActionLog.tabDisabled)
        Tabs.ActionLog.log (0,msg);
}

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

function SalvageLog (msg){
    if (!Tabs.ActionLog.tabDisabled)
        Tabs.ActionLog.log(2,msg);
}

/** ********************************* Organizer Options ******************* **/
Tabs.OrganizerOptions = {
    tabOrder: 1000,
    tabLabel: 'Options',
    tabID: 0,
    myDiv: null,

    init: function (div) {
        var t = Tabs.OrganizerOptions;
        t.myDiv = div;

        // header stuff
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';

        m += '<DIV id=trOptions class=trStat>GENERAL ORGANIZER OPTIONS</div><TABLE id=trOptionTbl width=100% height=0% class=trTab>';
        m += '<TR><TD width=100% align=center><hr/><a id=trpplink><img id=trpp /></a></div><hr/></TD></TR>';

        //m += '<TR><TD width=100%><INPUT id=OrganizerUpdate type=checkbox ' + (GlobalOptions.OrganizerUpdate ? 'CHECKED ' : '') + '/>Check updates on ' + htmlSelector({ 0: "GreasyFork", 1: "GoogleCode" }, GlobalOptions.UpdateSite, 'id=OrganizerUpdateSite') + '(All Domains) &nbsp; &nbsp; <INPUT id=OrganizerUpdateNow type=button value="Update Now" /></TD></TR>';
        m += '<TR><TD width=100%><INPUT id=OrganizerUpdate type=checkbox ' + (GlobalOptions.OrganizerUpdate ? 'CHECKED ' : '') + '/>Check For Updates (All Domains) &nbsp; &nbsp; <INPUT id=OrganizerUpdateNow type=button value="Update Now" /></TD></TR>';
        //ScriptURL
        m += '<TR><TD width=100%><INPUT id=OrganizerDisableAnim type=checkbox ' + (GeneralOptions.disableAnim ? 'CHECKED ' : '') + '/> Disable failure animation (Big red X) </TD></TR>';
        //m += '<TR><TD width=100%><INPUT id=OrganizerDisableSuccessCheck type=checkbox ' + (GeneralOptions.disableSuccessCheck ? 'CHECKED ' : '') + '/> Disable success animation (Big green checkmark) </TD></TR>';
        m += '<TR><TD width=100%><INPUT id=OrganizerPresetOption type=checkbox ' + (GeneralOptions.presetWidget ? 'CHECKED ' : '') + '/> Enable preset selector widget (requires refresh)</TD></TR>';
        m += '<TR><TD width=100%>Reset guardian/preset widget locations<INPUT id=trResetWidgets type=button value="Reset" /></TD></TR>';

        m += '<TR><td><INPUT id=OrganizerLocalPresetHidden type=checkbox ' + (GeneralOptions.localPresetHidden ? 'CHECKED ' : '') + '/> Hide local presets section from options section and throne organizer</td></tr> ';
        m += '<TR><td><INPUT id=OrganizerDraggable type=checkbox ' + (GeneralOptions.draggableThroneItems ? 'CHECKED ' : '') + '/> Enable draggable throne room items </td></tr> ';
        m += '<TR><td><INPUT id=OrganizerShowJewels type=checkbox ' + (GeneralOptions.showJewels ? 'CHECKED ' : '') + '/> Show jewels icon in throne room inventory </td></tr> ';
        m += '<TR><td><INPUT id=OrganzierGraphicalThrone type=checkbox ' + (GeneralOptions.graphicalThrone ? 'CHECKED ' : '') + '/> Display graphical throne card viewing (refresh recommended)</td></tr>';
        m += '<TR><td><INPUT id=OrganizerCompactView type=checkbox ' + (GeneralOptions.compactView ? 'CHECKED ' : '') + '/> Compact organizer view (refresh will be forced)</td></tr>';

        m += '<TR><td><div  class=trStat>SHOW EXTRA TABS <i>(<a id="OrganizerOptionsRefresh">requires click to refresh</a>)</i></div></td></TR>';

        m += '<TR><TD><TABLE id=trOptionTbl width=100% height=0% class=trTab>';
        m += '<TR>';
        m += '<td colspan=4>';

        m += '&nbsp;Options Tab Colors: <select id=OrganizerTabColorOptions>';
        for (var i = 0; i < tabColorsIndex.length; i++) {
            m += '<option value=' + i + '>' + tabColorsIndex[i] + '</option>';
        }
        m += '</select>';

        m += '&nbsp;Throne Tab Colors: <select id=OrganizerTabColorThrone>';
        for (var i = 0; i < tabColorsIndex.length; i++) {
            m += '<option value=' + i + '>' + tabColorsIndex[i] + '</option>';
        }
        m += '</select>';

        m += '&nbsp;Champ Tab Colors: <select id=OrganizerTabColorChamp>';
        for (var i = 0; i < tabColorsIndex.length; i++) {
            m += '<option value=' + i + '>' + tabColorsIndex[i] + '</option>';
        }
        m += '</select>';

        m += '</td>';
        m += '</TR>';
        m += '<TR>';
        m += '<td><INPUT id=OrganizerShowTabPresetsTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabPresetsTR ? 'CHECKED ' : '') + '/>TR Preset</td>';
        m += '<td><INPUT id=OrganizerShowTabCompareTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabCompareTR ? 'CHECKED ' : '') + '/>TR Compare</td>';
        m += '<td><INPUT id=OrganizerShowTabPreviewTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabPreviewTR ? 'CHECKED ' : '') + '/>TR Preview</td>';
        m += '<td><INPUT id=OrganizerShowTabRepairTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabRepairTR ? 'CHECKED ' : '') + '/>TR Repair</td>';
        m += '</TR>';
        m += '<TR>';
        m += '<td><INPUT id=OrganizerShowEnhanceStatsTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabEnhanceStatsTR ? 'CHECKED ' : '') + '/>TR Enhance Stats</td>';
        m += '<td><INPUT id=OrganizerShowUpgradeStatsTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabUpgradeStatsTR ? 'CHECKED ' : '') + '/>TR Upgrade Stats</td>';
        m += '<td><INPUT id=OrganizerShowEnhanceStatsCH class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabEnhanceStatsCH ? 'CHECKED ' : '') + '/>CH Enhance Stats</td>';
        m += '<td><INPUT id=OrganizerShowUpgradeStatsCH class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabUpgradeStatsCH ? 'CHECKED ' : '') + '/>CH Upgrade Stats</td>';
        m += '</tr>';
        m += '<TR>';
        m += '<td><INPUT id=OrganizerShowTabJewelsTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabJewelsTR ? 'CHECKED ' : '') + '/>TR Jewels</td>';
        m += '<td><INPUT id=OrganizerShowTabCapsTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabCapsTR ? 'CHECKED ' : '') + '/>TR Caps</td>';
        m += '<td><INPUT id=OrganizerShowUniquesTR class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabUniquesTR ? 'CHECKED ' : '') + '/>TR Uniques</td>';
        m += '<td><INPUT id=OrganizerShowPresetCH class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabPresetsCH ? 'CHECKED ' : '') + '/>CH Preset</td>';
        m += '</tr>';
        m += '<TR>';
        m += '<td><INPUT id=OrganizerShowTutorials class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabTutorials ? 'CHECKED ' : '') + '/>Tutorials</td>';
        m += '<td><INPUT id=OrganizerShowTabLog class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabLog ? 'CHECKED ' : '') + '/> Show Log Tab</td>';
        m += '<td><INPUT id=OrganizerShowTabNews class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabNews ? 'CHECKED ' : '') + '/> News</td>';
        m += '<td><INPUT id=OrganizerShowTabLinks class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabLinks ? 'CHECKED ' : '') + '/> Links</td>';
        m += '</TR>';
        m += '<TR>';
        m += '<td><INPUT id=OrganizerShowTabRepairCH class=OrganizerShowTabs type=checkbox ' + (GeneralOptions.showTabRepairCH ? 'CHECKED ' : '') + '/>CH Repair</td>';
        m += '<td/>';
        m += '<td/>';
        m += '<td/>';
        m += '</TR>';
        m += '</TABLE></TD></TR>';

        m += '<TR><td><div  class=trStat>THRONE/CHAMP SALVAGER OPTIONS</div></td></TR>';
        m += '<TR><td><b>Primary city to put aetherstones: </b><div style="display: inline;" id=OrganizerSalvageCity /></td></tr>';
        m += '<TR><TD><div style="white-space: pre;" ><INPUT id=OrganizerSalAnyCity type=checkbox ' + (GeneralOptions.salvageAnyCity ? ' CHECKED' : '') + '/> When primary city is full, put aetherstones in any city. ';
        m += '    Maximum number of aetherstones: <INPUT id=OrganizerMaxStone type=text size=7 maxlength=7 value="' + GeneralOptions.maxStones + '"/></div></td></TR>';
        m += '<TR><TD>Overflow method: <select id=OrganizerOverflow><option value="order">City order</option><option value="lowest">Lowest city</option>  </select></TD></TR>';
        m += '<tr><td><div>Load Throne Room salvager settings from domain number: <INPUT id=trLoadDomain type=text size=3 maxlength=3 /><INPUT id=trLoadRules type=button value="Load"/></div></td></tr>';
        m += '<tr><td><div>Load Champ Hall salvager settings from domain number: <INPUT id=chLoadDomain type=text size=3 maxlength=3 /><INPUT id=chLoadRules type=button value="Load"/></div></td></tr>';
        m += '<TR><TD><div style="white-space: pre;" ><INPUT id=trSalUpgradeFirst type=checkbox ' + (TRsalvageData.upgradeFirst ? ' CHECKED' : '') + '/> Upgrade items to +1 before deleting.';
        m += ' Maximum quality: <select id="trSalUpgradeQuality">';
        m += '<option value="0">' + uW.g_js_strings.throneRoom.simple + '</option>';
        m += '<option value="1">' + uW.g_js_strings.throneRoom.common + '</option>';
        m += '<option value="2">' + uW.g_js_strings.throneRoom.uncommon + '</option>';
        m += '<option value="3">' + uW.g_js_strings.throneRoom.rare + '</option>';
        m += '<option value="4">' + uW.g_js_strings.throneRoom.epic + '</option>';
        m += '<option value="5">' + uW.g_js_strings.throneRoom.wondrous + '</option>';
        m += '</select> (Throne Room Only) </div></td></tr>';
        m += '<TR><TD><div style="white-space: pre;" ><INPUT id=trSalUpgradeManual type=checkbox ' + (TRsalvageData.upgradeManual ? ' CHECKED' : '') + '/> Upgrade items to +1 on manual delete. (Throne Room Only)</td></tr>';

        m += '<TR><td><div  class=trStat>THRONE/CHAMP ENHANCE & UPGRADER OPTIONS</div></td></TR>';
        m += '<tr><td><div><b>Primary city to use aetherstones from: </b><span id="OrganizerUpgradeCity"></span></div></td></tr>'; //<span id=OrganizerStonesRemain></span></div></td></tr>';
        m += '<tr><td width=25%>Retry interval (seconds): <INPUT id=OrganizerUpgradeRefresh type=text size=3 maxlength=3 value="' + GeneralOptions.retryInterval + '"/></td></tr>';
        m += '  <tr><td colspan=2><div style="white-space: pre;"><INPUT id=OgranizerUseAnyCity type=checkbox ' + (GeneralOptions.useAnyCity ? ' CHECKED' : '') + '/> When primary city is low, use aetherstones from any city.  ';
        m += ' Minimum number of aetherstones: <INPUT id=OrganizerMinStone type=text size=7 maxlength=7 value="' + GeneralOptions.minStones + '"/> </div></td></tr>';
        m += '<tr><td colspan=2><INPUT id=OrganizerWhisperCheck type=checkbox ' + (GeneralOptions.whisperToMe ? 'CHECKED ' : '') + '/> Whisper to myself on successful upgrades/enhancements</td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerSendInbox type=checkbox ' + (GeneralOptions.sendToInbox ? 'CHECKED ' : '') + '/> Send to my inbox on successful upgrades/enhancements</td></tr>';
        m += '<tr><td colspan=2><INPUT id=OrganizerSafetyCheck type=checkbox ' + (GeneralOptions.safetyOn ? 'CHECKED ' : '') + '/> Disable manual upgrades if less than <input id=OrganizerSafetyLimit size=10 maxlength=10 value="' + GeneralOptions.safetyLimit + '" /> aetherstone</td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerBuffsCheck type=checkbox ' + (GeneralOptions.buffsOff ? 'CHECKED ' : '') + '/> Prevent Kabam from automatically selecting upgrade tokens</td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerMastersTokenCheck type=checkbox ' + (GeneralOptions.removeMastersTokens? 'CHECKED ' : '') + '/> Remove master tokens only from upgrade panel </td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerOtherTokenCheck type=checkbox ' + (GeneralOptions.removeOtherTokens ? 'CHECKED ' : '') + '/> Remove all other token from upgrade panel (not LLT or stones) </td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerUseToken type=checkbox ' + (GeneralOptions.useTokens ? 'CHECKED ' : '') + '/> Use next masters on manual upgrade (overrides above 3 options if checked) </td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerMultiUp type=checkbox ' + (GeneralOptions.multiUpgrade ? 'CHECKED ' : '') + '/> Add button for combined upgrade/enhancement (Throne Room Only)</td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerNoMassS type=checkbox ' + (GeneralOptions.noMassSalvage ? 'CHECKED ' : '') + '/> Remove button for Mass Salvage</td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerNoForce type=checkbox ' + (GeneralOptions.noForcedSalvage ? 'CHECKED ' : '') + '/> Remove button for Forced Salvage</td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerSalvageSafetyTR type=checkbox ' + (GeneralOptions.TRsalvageSafety ? 'CHECKED ' : '') + '/> Remove Salvage button for the first <INPUT id=OrganizerSafetyNumTR type=text size=3 maxlength=3 value="' + GeneralOptions.TRnumSafety + '"/> throne room items</td></tr> ';
        m += '<tr><td colspan=2><INPUT id=OrganizerSalvageSafetyCH type=checkbox ' + (GeneralOptions.CHsalvageSafety ? 'CHECKED ' : '') + '/> Remove Salvage button for the first <INPUT id=OrganizerSafetyNumCH type=text size=3 maxlength=3 value="' + GeneralOptions.CHnumSafety + '"/> champion items</td></tr> ';

        m += '<tr><td><div id=OrganizerLocalPresets style="display: ';
        if (GeneralOptions.localPresetHidden) {
            m += 'none;';
        } else {
            m += 'block;';
        }
        m += '"><table>';
        m += '<TR><td><div  class=trStat>THRONE ROOM LOCAL PRESET OPTIONS</div></td></TR>';
        m += '<TR><td><div style="text-align:center;"> Local Preset Names/Descriptions</div></td></TR>';

        for (j = 0; j < TRpresetData.num_presets; j++) {
            if (!TRpresetData.desc[j]) TRpresetData.desc[j] = 'Preset ' + String.fromCharCode(65 + j);
            if (!TRpresetData.ids[j]) TRpresetData.ids[j] = String.fromCharCode(65 + j);
            m += '<tr><td style="width: 650px; white-space: nowrap;">Name: <INPUT class=trNameEntry id=trPresetName' + j + ' type=text size=8 maxlength=8 value="' + TRpresetData.ids[j] + '"/> Description: <INPUT class=trDescEntry id=trPresetDesc' + j + ' type=text size=80 maxlength=100 value="' + TRpresetData.desc[j] + '"/></td></tr>';
        }

        m += '<TR><TD><div style="white-space: pre;" >Number of presets: <INPUT id=trNumPresets type=text size=4 maxlength=2 value="' + TRpresetData.num_presets + '"/>  <INPUT id=trNoTooltips type=checkbox ' + (TRpresetData.noTooltips ? ' CHECKED' : '') + '/> Do not show large portrait tooltips</div></td></tr>';
        m += '</table></div></td></tr>';
        m += '</table></div>';

        t.myDiv.innerHTML = m;

        new CdispCityPicker('salcitysel', document.getElementById('OrganizerSalvageCity'), true, t.SalvageCityButton, GeneralOptions.salvageCityNum);
        new CdispCityPicker('upcitysel', document.getElementById('OrganizerUpgradeCity'), true, t.UsedCityButton, GeneralOptions.usedCityNum);

        $("#trpplink")
        .attr('href', 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=TJ9YQ8S75HFEL')
        .attr('target', '_blank');
        $("#trpp")
        .attr('src', 'https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif')
        .attr('alt', 'donate')
        .css('cursor', 'pointer');

        /* remove resizing restrictions

        $("#optionScroll").resizable({
        minWidth: 710,
        maxWidth: 810,
        minHeight: 300,
        maxHeight: 780,
        stop: function (event, ui) {
        TRupgradeData.optionH = ui.size.height + 'px';
        TRupgradeData.optionW = ui.size.width + 'px';
        TRsaveUpgradeData();
        }
        });

        $("#optionScroll").css('height', TRupgradeData.optionH).css('width', TRupgradeData.optionW);
        */

        $('#OrganizerOptionsRefresh').click(function() {
            RefreshCamelot();
        });

        $('#OrganizerTabColorOptions').change(function() {
            GeneralOptions.tabColorOptions = document.getElementById('OrganizerTabColorOptions').value;
            saveGeneralOptions();
        });

        $('#OrganizerTabColorChamp').change(function() {
            GeneralOptions.tabColorChamp = document.getElementById('OrganizerTabColorChamp').value;
            saveGeneralOptions();
        });

        $('#OrganizerTabColorThrone').change(function() {
            GeneralOptions.tabColorThrone = document.getElementById('OrganizerTabColorThrone').value;
            saveGeneralOptions();
        });

        $("#OrganizerTabColorOptions").val(GeneralOptions.tabColorOptions);
        $("#OrganizerTabColorChamp").val(GeneralOptions.tabColorChamp);
        $("#OrganizerTabColorThrone").val(GeneralOptions.tabColorThrone);



        $('#OrganizerShowTutorials').change(function() {
            GeneralOptions.showTabTutorials = document.getElementById('OrganizerShowTutorials').checked;
            saveGeneralOptions();
        });

        $('#OrganizerSendInbox').click(function () {
            GeneralOptions.sendToInbox = document.getElementById('OrganizerSendInbox').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowUniquesTR').change(function () {
            GeneralOptions.showTabUniquesTR = document.getElementById('OrganizerShowUniquesTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowJewels').change(function () {
            GeneralOptions.showJewels = document.getElementById('OrganizerShowJewels').checked;
            saveGeneralOptions();
        });

        $('#OrganzierGraphicalThrone').change(function () {
            GeneralOptions.graphicalThrone = document.getElementById('OrganzierGraphicalThrone').checked;
            saveGeneralOptions();
        });

        $('#OrganizerCompactView').change(function () {
            GeneralOptions.compactView = document.getElementById('OrganizerCompactView').checked;
            saveGeneralOptions();
            RefreshCamelot();
        });

//        $('#OrganizerDisableSuccessCheck').change(function() {
//            GeneralOptions.disableSuccessCheck = document.getElementById('OrganizerDisableSuccessCheck').checked;
//            saveGeneralOptions();
//        });

        $('#OrganizerDisableAnim').change(function () {
            GeneralOptions.disableAnim = document.getElementById('OrganizerDisableAnim').checked;
            disableAnimation(GeneralOptions.disableAnim);
            saveGeneralOptions();
        });

        $('#OrganizerPresetOption').change(function () {
            GeneralOptions.presetWidget = document.getElementById('OrganizerPresetOption').checked;
            saveGeneralOptions();
        });

        $('#OrganizerDraggable').change(function () {
            GeneralOptions.draggableThroneItems = document.getElementById('OrganizerDraggable').checked;
            saveGeneralOptions();
        }
            );
        $('#OrganizerUpdate').change(function () {
            GlobalOptions.OrganizerUpdate = document.getElementById('OrganizerUpdate').checked;
            GM_setValue('TROptions_??', JSON2.stringify(GlobalOptions));
        }
            );

        $('#OrganizerUpdateSite').change(function () {
            GlobalOptions.UpdateSite = $("#OrganizerUpdateSite").val();
            GM_setValue('TROptions_??', JSON2.stringify(GlobalOptions));
        }
            );

        $('#OrganizerWhisperCheck').change(function () {
            GeneralOptions.whisperToMe = document.getElementById('OrganizerWhisperCheck').checked;
            saveGeneralOptions();
        }
            );

        $('#OrganizerSafetyCheck').change(function () {
            GeneralOptions.safetyOn = document.getElementById('OrganizerSafetyCheck').checked;
            saveGeneralOptions();
        }
            );

        $('#OrganizerMastersTokenCheck').change(function () {
            GeneralOptions.removeMastersTokens = document.getElementById('OrganizerMastersTokenCheck').checked;
            saveGeneralOptions();
        }
            );

        $('#OrganizerOtherTokenCheck').change(function () {
            GeneralOptions.removeOtherTokens = document.getElementById('OrganizerOtherTokenCheck').checked;
            saveGeneralOptions();
        }
            );

        $('#OrganizerUseToken').change(function () {
            GeneralOptions.useTokens = document.getElementById('OrganizerUseToken').checked;
            saveGeneralOptions();
        }
            );

        $('#OrganizerMultiUp').change(function () {
            GeneralOptions.multiUpgrade = document.getElementById('OrganizerMultiUp').checked;
            saveGeneralOptions();
        }
            );

        $('#OrganizerNoForce').change(function () {
            GeneralOptions.noForcedSalvage = document.getElementById('OrganizerNoForce').checked;
            saveGeneralOptions();
        });

        $('#OrganizerNoMassS').change(function () {
            GeneralOptions.noMassSalvage = document.getElementById('OrganizerNoMassS').checked;
            saveGeneralOptions();
        });

        $('#OrganizerSalvageSafetyTR').change(function () {
            GeneralOptions.TRsalvageSafety = document.getElementById('OrganizerSalvageSafetyTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerSalvageSafetyCH').change(function () {
            GeneralOptions.CHsalvageSafety = document.getElementById('OrganizerSalvageSafetyCH').checked;
            saveGeneralOptions();
        });

        $('#OrganizerLocalPresetHidden').change(function () {
            GeneralOptions.localPresetHidden = document.getElementById('OrganizerLocalPresetHidden').checked;
            var lp = document.getElementById('localPresets');
            var lpOptions = document.getElementById('OrganizerLocalPresets');
            if (GeneralOptions.localPresetHidden) {
                lp.style.display = "none";
                lpOptions.style.display = "none";
            } else {
                lp.style.display = "block";
                lpOptions.style.display = "block";
            }
            saveGeneralOptions();
        });

        $("#OrganizerSafetyNumTR").change(function () {
            GeneralOptions.TRnumSafety = parseInt($("#OrganizerSafetyNumTR").val());
            saveGeneralOptions();
        });

        $("#OrganizerSafetyNumCH").change(function () {
            GeneralOptions.CHnumSafety = parseInt($("#OrganizerSafetyNumCH").val());
            saveGeneralOptions();
        });


        $('#OrganizerBuffsCheck').change(function () {
            GeneralOptions.buffsOff = document.getElementById('OrganizerBuffsCheck').checked;
            saveGeneralOptions();
        }
            );

        $('#OrganizerSafetyLimit').change(function () {
            GeneralOptions.safetyLimit = parseInt($("#OrganizerSafetyLimit").val());
            saveGeneralOptions();
        }
            );

        $('#OrganizerUpdateNow').click( function () { 
                    AutoUpdater.call(false, true);
        }
            );

        $('#trResetWidgets').click(
                    function () { resetGuardWidget(); resetPresetWidget(); }
            );

        $('#OrganizerSalAnyCity').change(function () {
            GeneralOptions.salvageAnyCity = document.getElementById('OrganizerSalAnyCity').checked;
            saveGeneralOptions();
        });

        $('#OgranizerUseAnyCity').change(function () {
            GeneralOptions.useAnyCity = document.getElementById('OgranizerUseAnyCity').checked;
            saveGeneralOptions();
        });

        $('#trSalUpgradeFirst').change(function () {
            TRsalvageData.upgradeFirst = document.getElementById('trSalUpgradeFirst').checked;
            TRsaveSalvageData();
        });

        $('#trSalUpgradeManual').change(function () {
            TRsalvageData.upgradeManual = document.getElementById('trSalUpgradeManual').checked;
            TRsaveSalvageData();
        });

        // set the upgrade quality limit widget
        $("#trSalUpgradeQuality").val(TRsalvageData.upgradeFirstQual);
        $("#trSalUpgradeQuality").change(function () { TRsalvageData.upgradeFirstQual = $("#trSalUpgradeQuality").val(); TRsaveSalvageData(); });

        $("#OrganizerMaxStone").change(function () {
            GeneralOptions.maxStones = $("#OrganizerMaxStone").val();
            saveGeneralOptions();
        });

        $('#OrganizerUpgradeRefresh').change(function () {
            GeneralOptions.retryInterval = parseInt(document.getElementById('OrganizerUpgradeRefresh').value);
            if (GeneralOptions.retryInterval < 15) GeneralOptions.retryInterval = 15;
            saveGeneralOptions();
        });

        $("#OrganizerMinStone").change(function () {
            GeneralOptions.minStones = $("#OrganizerMinStone").val();
            saveGeneralOptions();
        });

        $("#trLoadRules").click(function () {
            var d = $("#trLoadDomain").val();
            if (d != null)
                TRloadSalvageData(d);
        });

        $("#chLoadRules").click(function () {
            var d = $("#chLoadDomain").val();
            if (d != null)
                CHloadSalvageData(d);
        });

        // set the overflow widget
        $("#OrganizerOverflow").val(GeneralOptions.overflow);
        $("#OrganizerOverflow").change(function () {
            GeneralOptions.overflow = $("#OrganizerOverflow").val();
            saveGeneralOptions();
        });

        // read the preset names and descriptions
        $("input.trNameEntry").change(function () {
            var id = $(this).attr('id');
            var num = id.split("trPresetName")[1];
            TRpresetData.ids[num] = $(this).val();
            TRsavePresetData();
            if (GeneralOptions.compactView) {
                Tabs.throneOrganizerCompact.init(Tabs.throneOrganizerCompact.myDiv);
            } else {
                Tabs.throneOrganizer.init(Tabs.throneOrganizer.myDiv);
            }
        });

        $("input.trDescEntry").change(function () {
            var id = $(this).attr('id');
            var num = id.split("trPresetDesc")[1];
            TRpresetData.desc[num] = $(this).val();
            TRsavePresetData();
            if (GeneralOptions.compactView) {
                Tabs.throneOrganizerCompact.init(Tabs.throneOrganizerCompact.myDiv);
            } else {
                Tabs.throneOrganizer.init(Tabs.throneOrganizer.myDiv);
            }
        });

        $('#trNoTooltips').change(function () {
            TRpresetData.noTooltips = document.getElementById('trNoTooltips').checked;
            TRsavePresetData();
            if (GeneralOptions.compactView) {
                Tabs.throneOrganizerCompact.show();
            } else {
                Tabs.throneOrganizer.show();
            }

        });

        $("#trNumPresets").change(function () {
            var newNum = $("#trNumPresets").val();
            if (TRpresetData.num_presets != newNum) {
                TRpresetData.num_presets = newNum;
                t.init(t.myDiv);
                TRsavePresetData();
                if (GeneralOptions.compactView) {
                    Tabs.throneOrganizerCompact.init(Tabs.throneOrganizerCompact.myDiv);
                } else {
                    Tabs.throneOrganizer.init(Tabs.throneOrganizer.myDiv);
                }
            }
        });

        $('#OrganizerShowTabRepairTR').change(function () {
            GeneralOptions.showTabRepairTR = document.getElementById('OrganizerShowTabRepairTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowEnhanceStatsTR').change(function () {
            GeneralOptions.showTabEnhanceStatsTR = document.getElementById('OrganizerShowEnhanceStatsTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowPresetCH').change(function () {
            GeneralOptions.showTabPresetsCH = document.getElementById('OrganizerShowPresetCH').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowUpgradeStatsTR').change(function () {
            GeneralOptions.showTabUpgradeStatsTR = document.getElementById('OrganizerShowUpgradeStatsTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowEnhanceStatsCH').change(function () {
            GeneralOptions.showTabEnhanceStatsCH = document.getElementById('OrganizerShowEnhanceStatsCH').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowUpgradeStatsCH').change(function () {
            GeneralOptions.showTabUpgradeStatsCH = document.getElementById('OrganizerShowUpgradeStatsCH').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabPresetsTR').change(function () {
            GeneralOptions.showTabPresetsTR = document.getElementById('OrganizerShowTabPresetsTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabCompareTR').change(function () {
            GeneralOptions.showTabCompareTR = document.getElementById('OrganizerShowTabCompareTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabPreviewTR').change(function () {
            GeneralOptions.showTabPreviewTR = document.getElementById('OrganizerShowTabPreviewTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabLog').change(function () {
            GeneralOptions.showTabLog = document.getElementById('OrganizerShowTabLog').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabCapsTR').change(function () {
            GeneralOptions.showTabCapsTR = document.getElementById('OrganizerShowTabCapsTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabJewelsTR').change(function () {
            GeneralOptions.showTabJewelsTR = document.getElementById('OrganizerShowTabJewelsTR').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabNews').change(function () {
            GeneralOptions.showTabNews = document.getElementById('OrganizerShowTabNews').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabLinks').change(function () {
            GeneralOptions.showTabLinks = document.getElementById('OrganizerShowTabLinks').checked;
            saveGeneralOptions();
        });

        $('#OrganizerShowTabRepairCH').change(function () {
            GeneralOptions.showTabRepairCH = document.getElementById('OrganizerShowTabRepairCH').checked;
            saveGeneralOptions();
        });

        disableAnimation(GeneralOptions.disableAnim);
        //disableAnimation(false);
    },

    SalvageCityButton: function (city, x, y) {
        var t = Tabs.OrganizerOptions;
        GeneralOptions.salvageCityNum = city.idx;
        saveGeneralOptions();
    },


    UsedCityButton: function (city, x, y) {
        var t = Tabs.OrganizerOptions;
        GeneralOptions.usedCityNum = city.idx;
        saveGeneralOptions();
    },

    show: function () {

    },

    hide: function () {

    }

}

/** ********************************* Champion Upgrade ******************** **/
Tabs.champUpgrader = {
    tabOrder: 600,
    tabLabel: 'Champ Upgrade',
    tabDisabled: false,
    myDiv: null,
    repairId: 0,
    repairEnd: 0,
    timerH: null,
    clearTimerH: null,
    speedup: 0,
    doingSpeedup: false,
    qualities: [uW.g_js_strings ? uW.g_js_strings.throneRoom.simple : "Simple",
           uW.g_js_strings ? uW.g_js_strings.throneRoom.common : "Common",
           uW.g_js_strings ? uW.g_js_strings.throneRoom.uncommon : "Uncommon",
           uW.g_js_strings ? uW.g_js_strings.throneRoom.rare : "Rare",
           uW.g_js_strings ? uW.g_js_strings.throneRoom.epic : "Epic",
           uW.g_js_strings ? uW.g_js_strings.throneRoom.wondrous : "Wondrous"],
    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 }
    },

    repaint: function () {
        var t = Tabs.champUpgrader;
        t.init(t.myDiv);
    },

    init: function (div) {
        var t = Tabs.champUpgrader;
        t.myDiv = div;

        if (unsafeWindow.g_js_strings) {
            t.qualities = [unsafeWindow.g_js_strings.throneRoom.simple,
                                    unsafeWindow.g_js_strings.throneRoom.common,
                                    unsafeWindow.g_js_strings.throneRoom.uncommon,
                                    unsafeWindow.g_js_strings.throneRoom.rare,
                                    unsafeWindow.g_js_strings.throneRoom.epic,
                                    unsafeWindow.g_js_strings.throneRoom.wondrous];
        }

        // header stuff
        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=chUpgrader class=chStat>CHAMPION UPGRADER</div>';

        // 
        m += '<TABLE width=100% id=chupdtable class=chTabPad>';

        m += '<tr>';
        if (CHupgradeData.active == false) {
            m += '<TD width=25%><div><INPUT id=chUpgraderPower type=button value="Upgrader = OFF"/></div></td>';
        } else {
            m += '<TD width=25%><div><INPUT id=chUpgraderPower type=button value="Upgrader = ON"/></div></td>';
        }

        m += '<td width=25%><INPUT id=chOneItem type=checkbox ' + (CHqueueData.oneItem ? ' CHECKED' : '') + '/>  Upgrade 1 at a time</td>';
        m += '<td width=25%><INPUT id=chRepairAll type=checkbox ' + (CHupgradeData.repairAll ? ' CHECKED' : '') + '/>  Repair all items</td>';
        m += '<td width=25%><div id=chAetherDisplay>' + displayCityAstone() + '</div></td></tr>';

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

        m += '<tr align="center"><td colspan=4><div id=chUpgradeStatus class=indent25> <br> </div></td></tr>';
        m += '<tr align="center"><td colspan=4><div id=chLastResult class=indent25> <br> </div></td></tr>';
        m += '<tr><td colspan=4><DIV id=chUpgrader class=chStat>UPGRADE/ENHANCE SPEEDUPS</div></td></tr>';
        m += '<tr><td colspan=4 align=center>';
        m += '<table width=100% cellpadding=0 cellspacing=0>'
        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=chHourglassLevelSpecific ' + (CHupgradeData.hourglassLevelSpecific ? "CHECKED" : "") + '>Only use hourglass for levels ';
        m += '<select id=chHourglassLevel>';
        for (i = 1; i < OrganizerMaxCHLevel; i++) m += '<option value=' + i + '>' + i + '</option>';
        m += '</select> and higher</td>';
        m += '</tr>';

        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=chHourglassQualitySpecific ' + (CHupgradeData.hourglassQualitySpecific ? "CHECKED" : "") + '>Only use hourglass for qualities ';
        m += '<select id=chHourglassQuality>';
        m += '<option value="1">Common</option>';
        m += '<option value="2">Uncommon</option>';
        m += '<option value="3">Rare</option>';
        m += '<option value="4">Epic</option>';
        m += '<option value="5">Wondrous</option>';
        m += '</select> and higher</td>';
        m += '</tr>';

        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[1] + "'><input type=checkbox id=chUseSH " + (CHupgradeData.useSH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[1] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseSHLabel>" + unsafeWindow.ksoItems[1].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[2] + "'><input type=checkbox id=chUseKH " + (CHupgradeData.useKH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[2] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseKHLabel>" + unsafeWindow.ksoItems[2].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[3] + "'><input type=checkbox id=chUseGH " + (CHupgradeData.useGH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[3] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseGHLabel>" + unsafeWindow.ksoItems[3].count + "</div>)</div></td>";
        m += "</tr>";
        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[4] + "'><input type=checkbox id=chUseMH " + (CHupgradeData.useMH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[4] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseMHLabel>" + unsafeWindow.ksoItems[4].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[5] + "'><input type=checkbox id=chUseAH " + (CHupgradeData.useAH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[5] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseAHLabel>" + unsafeWindow.ksoItems[5].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[6] + "'><input type=checkbox id=chUseWH " + (CHupgradeData.useWH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[6] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseWHLabel>" + unsafeWindow.ksoItems[6].count + "</div>)</div></td>";
        m += "</tr>";
        m += '<tr>';
        m += "<td title='" + HourGlassTDLabel[7] + "'><input type=checkbox id=chUseDH " + (CHupgradeData.useDH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[7] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseDHLabel>" + unsafeWindow.ksoItems[7].count + "</div>)</div></td>";
        m += "<td title='" + HourGlassTDLabel[8] + "'><input type=checkbox id=chUseEH " + (CHupgradeData.useEH ? "CHECKED" : "") + "><div style='white-space:nowrap;display:inline-block;'>" + HourGlassName[8] + " (<div style='white-space:nowrap;display:inline-block;' id=chUseEHLabel>" + unsafeWindow.ksoItems[8].count + "</div>)</div></td>";
        m += "<td/>";
        m += "</tr>";
        m += '<tr>';
        m += '<td colspan=3><input type=checkbox id=chOverrideSpeedUps ' + (CHupgradeData.overrideSpeedUp ? "CHECKED" : "") + '>Override hourglasses by using ';
        m += '<select id=chSpeedUp>';
        m += '<option value=0>None</option>';
        m += '<option value=1>Squires Hourglass</option>';
        m += '<option value=2>Knights Hourglass</option>';
        m += '<option value=3>Guineveres Hourglass</option>';
        m += '<option value=4>Morganas Hourglass</option>';
        m += '<option value=5>Arthurs Hourglass</option>';
        m += '<option value=6>Merlins Hourglass</option>';
        m += '<option value=7>Divine Hourglass</option>';
        m += '<option value=8>Epic Hourglass</option>';
        m += '</select> every time</td>';
        m += '</tr>';

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

        m += '<tr><td colspan=4><DIV id=chUpgrader class=chStat>UPGRADE/ENHANCE BOOST ITEMS</div></td></tr>';

        m += '<tr><td colspan=4>';

        m += '<table cellspacing=0 cellpadding=0 width=100%>';
        m += '<tr>';
        m += '<td><input type=checkbox ' + (CHupgradeData.useLOM ? "CHECKED" : "") + ' id=chUseLOM><div style="white-space:nowrap;display:inline-block;">Lesser Orb of Metallurgy (<div style="white-space:nowrap;display:inline-block;" id=chUseLOMLabel>' + unsafeWindow.ksoItems[21001].count + '</div>)</div></td>';
        m += '<td><input type=checkbox ' + (CHupgradeData.useGOM ? "CHECKED" : "") + ' id=chUseGOM><div style="white-space:nowrap;display:inline-block;">Greater Orb of Metallurgy (<div style="white-space:nowrap;display:inline-block;" id=chUseGOMLabel>' + unsafeWindow.ksoItems[21002].count + '</div>)</div></td>';
        m += '<td>Quality <select id="chUseQuality">';
        m += '<option value="1">Common</option>';
        m += '<option value="2">Uncommon</option>';
        m += '<option value="3">Rare</option>';
        m += '<option value="4">Epic</option>';
        m += '<option value="5">Wondrous</option>';
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += "<td><input type=checkbox " + (CHupgradeData.useJT ? "CHECKED" : "") + " id=chUseJT><div style='white-space:nowrap;display:inline-block;'>Journeyman Smith's Token (<div style='white-space:nowrap;display:inline-block;' id=chUseJTLabel>" + unsafeWindow.ksoItems[21051].count + "</div>)</div></td>";
        m += "<td><input type=checkbox " + (CHupgradeData.useST ? "CHECKED" : "") + " id=chUseST><div style='white-space:nowrap;display:inline-block;'>Smith's Token (<div style='white-space:nowrap;display:inline-block;' id=chUseSTLabel>" + unsafeWindow.ksoItems[21052].count + "</div>)</div></td>";
        m += '<td>Level <select id="chUseLevel">';
        for (i = 1; i <= OrganizerMaxCHLevel; i++) {
            m += '<option value="' + i + '"> +' + i + '</option>';
        }
        m += '</select> and higher</td>';
        m += '</tr>';
        m += '<tr>';
        m += "<td><input type=checkbox " + (CHupgradeData.useET ? "CHECKED" : "") + " id=chUseET><div style='white-space:nowrap;display:inline-block;'>Expert Smith's Token (<div style='white-space:nowrap;display:inline-block;' id=chUseETLabel>" + unsafeWindow.ksoItems[21058].count + "</div>)</div></td>";
        m += "<td/>";
        m += "<td/>";
        m += "</tr>";
        m += "</table>";

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

        m += '<tr><td colspan=4><DIV id=trUpgrader class=trStat>UPGRADE/ENHANCE LIST</div></td></tr>';

        m += '<tr><td colspan=4>';
        m += '<TABLE id=chupdtable2 class=chTabPad width=100%>';

        m += '<tr><td colspan=4>Enhance All Quality <select id="chEnhanceAllQuality">';
        for (i = 0; i <= OrganizerMaxCHQuality-1; i++) {
            m += '<option value="' + i + '">' + t.qualities[i] + '</option>';
        }
        m += '</select> To Quality <select id="chEnhanceAllQualityTo">';
        for (i = 1; i <= OrganizerMaxCHQuality; i++) {
            m += '<option value="' + i + '">' + t.qualities[i] + '</option>';
        }
        m += '</select>&nbsp;&nbsp;<input type=button value="Add" id="chEnhanceAddAllQuality"></td></tr>';

        m += '<tr><td colspan=4>Upgrade All Cards Less To Level <select id="chUpgradeAddAllLevelMaxTo">';
        for (i = 1; i <= OrganizerMaxCHLevel; i++) {
            m += '<option value="' + i + '"> +' + i + '</option>';
        }
        m += '</select>&nbsp;&nbsp;<input type=button value="Add" id="chUpgradeAddAllLevelMax"></td></tr>';

        m += '<tr><td colspan=4>Upgrade All Level <select id="chUpgradeAllLevel">';
        for (i = 0; i <= OrganizerMaxCHLevel-1; i++) {
            m += '<option value="' + i + '"> +' + i + '</option>';
        }
        m += '</select> To Level <select id="chUpgradeAllLevelTo">';
        for (i = 1; i <= OrganizerMaxCHLevel; i++) {
            m += '<option value="' + i + '"> +' + i + '</option>';
        }
        m += '</select>&nbsp;&nbsp;<input type=button value="Add" id="chUpgradeAddAllLevel"></td></tr>';

        m += '<tr><td colspan=4 style="white-space:nowrap;display:inline-block;">Item: <select id="chUpgradeList" style="white-space:nowrap;display:inline-block;max-width: 200px;">';
        m += '<option value="0">--Items--</option>';
        for (k in unsafeWindow.kocChampionItems) {
            var champ_item = unsafeWindow.kocChampionItems[k];
            m += '<option value="' + k + '">' + champ_item.name + '</option>';
            //logit("CI: " + inspect(champ_item,8,3));
        }
        m += '</select>';

        m += 'Action: <select style="white-space:nowrap;display:inline-block;" id="chAction">';
        m += '<option value="upgrade">Upgrade</option>';
        m += '<option value="enhance">Enhance</option>';
        m += '<option value="both">Both</option>';
        m += '</select>';
        m += '<div style="white-space:nowrap;display:inline-block;" id=chMaxDiv></div>';
        m += '<INPUT style="white-space:nowrap;display:inline-block;" id=chQueueAdd type=button value="Add"/>';
        m += '</td></tr>';

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

        m += '<tr><td colspan=4><div id=chQScroll style=" position: static; width: 100%; height: 250px; overflow-x: auto; overflow-y: auto;"><div id=chQDiv /></div></td></tr>';

        m += '<tr align=center><td colspan=4><input style="float: left;" id=chClearQ type=button value="Clear Queue"/></td></tr>';
        m += '</table>';

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

        $('#chClearQ').click(function () {
            CHqueueData.list = [];
            CHsaveQueueData();
            //Tabs.champUpgrader.buildQueueDisplay();
            t.buildQueueDisplay();
        });

        //               $("#chQScroll").resizable({
        //                   minWidth: 710,
        //                   maxWidth: 1200,
        //                   minHeight: 200,
        //                   maxHeight: 800,
        //                   stop: function(event, ui) {
        //                       CHupgradeData.upgradeH =  ui.size.height + 'px';
        //                       CHupgradeData.upgradeW =  ui.size.width  + 'px';
        //                       CHsaveUpgradeData();
        //                   }
        //               });

        //               $("#chQScroll").css('height', CHupgradeData.upgradeH).css('width', CHupgradeData.upgradeW);

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

        document.getElementById('chRepairAll').addEventListener('change', function () {
            CHupgradeData.repairAll = document.getElementById('chRepairAll').checked;
            CHsaveUpgradeData();
        }, false);

        // wait for the current repair to finish before starting
        t.setStatus("Loading ....");

        $("#chQDiv").html('<div><table id="chQueue" class="chTabLined" width="100%"/></div>');

        $('#chEnhanceAddAllQuality').click(function () {
            var low_level = parseInt($('#chEnhanceAllQuality').val());
            var high_level = parseInt($('#chEnhanceAllQualityTo').val());
            if (low_level >= high_level) return;
            for (chId in unsafeWindow.kocChampionItems) {
                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (!champ_item) continue;
                if (champ_item.rarity == low_level) {
                    var qItem = new QueueItem();
                    qItem.item = chId;
                    qItem.action = "enhance";
                    qItem.level = high_level;
                    CHqueueData.list.push(qItem);
                }
            }
            CHsaveQueueData();
            t.buildQueueDisplay();

        });

        $('#chUpgradeAddAllLevel').click(function () {
            var low_level = parseInt($('#chUpgradeAllLevel').val());
            var high_level = parseInt($('#chUpgradeAllLevelTo').val());
            if (low_level >= high_level) return;
            for (chId in unsafeWindow.kocChampionItems) {
                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (!champ_item) continue;
                if (champ_item.level == low_level) {
                    var qItem = new QueueItem();
                    qItem.item = chId;
                    qItem.action = "upgrade";
                    qItem.level = high_level;
                    CHqueueData.list.push(qItem);
                }
            }
            CHsaveQueueData();
            t.buildQueueDisplay();

        });

        $('#chUpgradeAddAllLevelMax').click(function () {
            var high_level = parseInt($('#chUpgradeAddAllLevelMaxTo').val());
            for (chId in unsafeWindow.kocChampionItems) {
                var champ_item = unsafeWindow.kocChampionItems[chId];
                if (!champ_item) continue;
                if (champ_item.level < high_level) {
                    var qItem = new QueueItem();
                    qItem.item = chId;
                    qItem.action = "upgrade";
                    qItem.level = high_level;
                    CHqueueData.list.push(qItem);
                }
            }
            CHsaveQueueData();
            t.buildQueueDisplay();

        });

        $('#chHourglassLevelSpecific').change(function () {
            CHupgradeData.hourglassLevelSpecific = document.getElementById('chHourglassLevelSpecific').checked;
            CHsaveUpgradeData();
            t.doAction();
        });

        $('#chHourglassQualitySpecific').change(function () {
            CHupgradeData.hourglassQualitySpecific = document.getElementById('chHourglassQualitySpecific').checked;
            CHsaveUpgradeData();
            t.doAction();
        });


        $('#chOverrideSpeedUps').change(function () {
            CHupgradeData.overrideSpeedUp = document.getElementById('chOverrideSpeedUps').checked;
            CHsaveUpgradeData();
        });


        $('#chUsewH').change(function () {
            CHupgradeData.useWH = document.getElementById('chUseWH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useWH) t.doingSpeedup = true;
        });

        $('#chUseDH').change(function () {
            CHupgradeData.useDH = document.getElementById('chUseDH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useDH) t.doingSpeedup = true;
        });

        $('#chUseEH').change(function () {
            CHupgradeData.useEH = document.getElementById('chUseEH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useEH) t.doingSpeedup = true;
        });
        
        $('#chUseSH').change(function () {
            CHupgradeData.useSH = document.getElementById('chUseSH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useSH) t.doingSpeedup = true;
        });

        $('#chUseKH').change(function () {
            CHupgradeData.useKH = document.getElementById('chUseKH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useKH) t.doingSpeedup = true;
        });

        $('#chUseGH').change(function () {
            CHupgradeData.useGH = document.getElementById('chUseGH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useGH) t.doingSpeedup = true;
        });

        $('#chUseMH').change(function () {
            CHupgradeData.useMH = document.getElementById('chUseMH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useMH) t.doingSpeedup = true;
        });

        $('#chUseAH').change(function () {
            CHupgradeData.useAH = document.getElementById('chUseAH').checked;
            CHsaveUpgradeData();
            if (CHupgradeData.useAH) t.doingSpeedup = true;
        });

        $("#chUseLOM").change(function () {
            CHupgradeData.useLOM = document.getElementById('chUseLOM').checked;
            CHsaveUpgradeData();
        });

        $("#chUseGOM").change(function () {
            CHupgradeData.useGOM = document.getElementById('chUseGOM').checked;
            CHsaveUpgradeData();
        });

        $("#chUseJT").change(function () {
            CHupgradeData.useJT = document.getElementById('chUseJT').checked;
            CHsaveUpgradeData();
        });

        $("#chUseST").change(function () {
            CHupgradeData.useST = document.getElementById('chUseST').checked;
            CHsaveUpgradeData();
        });

        $("#chUseET").change(function () {
            CHupgradeData.useET = document.getElementById('chUseET').checked;
            CHsaveUpgradeData();
        });

        document.getElementById('chUseQuality').value = CHupgradeData.useQuality;
        document.getElementById('chUseLevel').value = CHupgradeData.useLevel;
        document.getElementById('chSpeedUp').value = CHupgradeData.useSpeedUp;
        document.getElementById('chHourglassLevel').value = CHupgradeData.hourglassLevel;
        document.getElementById('chHourglassQuality').value = CHupgradeData.hourglassQuality;

        $('#chSpeedUp').change(function () {
            CHupgradeData.useSpeedUp = document.getElementById('chSpeedUp').value;
            CHsaveUpgradeData();
        });

        $('#chUseQuality').change(function () {
            CHupgradeData.useQuality = document.getElementById('chUseQuality').value;
            CHsaveUpgradeData();
        });

        $('#chUseLevel').change(function () {
            CHupgradeData.useLevel = document.getElementById('chUseLevel').value;
            CHsaveUpgradeData();
        });

        $('#chHourglassLevel').change(function () {
            CHupgradeData.hourglassLevel = document.getElementById('chHourglassLevel').value;
            CHsaveUpgradeData();
            t.doAction();
        });

        $('#chHourglassQuality').change(function () {
            CHupgradeData.hourglassQuality = document.getElementById('chHourglassQuality').value;
            CHsaveUpgradeData();
            t.doAction();
        });


        $("#chQueueAdd").click(function () { t.addQueue(); });
        $("#chOneItem").change(function () {
            CHqueueData.oneItem = document.getElementById('chOneItem').checked;
            CHsaveQueueData();
        });


        var d = 2 + Math.random() * 8;
        logit("checking repair time")

        if (Seed.queue_champion == null) {
            for (kk in unsafeWindow.kocChampionItems) {
                var K = unsafeWindow.kocChampionItems[kk];
                if ((K.status == 2) || (K.status == 3)) {
                    logit("Object is being repaired, but there's no queue");
                    Seed.queue_champion = {};
                    Seed.queue_champion.start = parseInt(K.start);
                    Seed.queue_champion.end = parseInt(K.eta);
                    Seed.queue_champion.itemId = K.equipmentId;
                    break;
                }
            }
        }

        if (Seed.queue_champion != null && Seed.queue_champion.end != null) {
            var repairTimeLeft = Seed.queue_champion.end - unixTime();
            logit("time left: " + repairTimeLeft);
            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: " + unsafeWindow.kocChampionItems[t.repairId].name);

            if (CHupgradeData.useAH || CHupgradeData.useGH || CHupgradeData.useKH || CHupgradeData.useMH || CHupgradeData.useSH || CHupgradeData.useWH || CHupgradeData.useDH || CHupgradeData.useEH || (CHupgradeData.overrideSpeedUp && CHupgradeData.useSpeedUp > 0)) {
                var champItem = unsafeWindow.kocChampionItems[t.repairId];
                var chQuality = champItem.rarity;
                var chLevel = champItem.level;
                var useThoseSpeedups = true;
                if (CHupgradeData.hourglassQualitySpecific && chQuality < CHupgradeData.hourglassQuality) useThoseSpeedups = false;
                if (CHupgradeData.hourglassLevelSpecific && chLevel < CHupgradeData.hourglassLevel) useThoseSpeedups = false;
                if (useThoseSpeedups) {
                    t.doingSpeedup = true;
                    setTimeout(function () { t.doSpeedup(); }, 2000);
                }
            }

            setTimeout(t.clearRepair, (repairTimeLeft + 1) * 5000);
            if (repairTimeLeft > 0) d += repairTimeLeft;
        }

        t.buildLevelWidget();
        t.buildQueueDisplay();
        $("#chAction").change(function () { t.buildLevelWidget(); });

        Tabs.champPresets.paintTags();

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

    },

    doSpeedup: function () {

        var t = Tabs.champUpgrader;
        var champ_item = unsafeWindow.kocChampionItems[t.repairId];

        if (!CHupgradeData.active) {
            t.doingSpeedup = false;
            return;
        }

        //if (champ_item.status != CM.CHAMPION.STATUS_BROKEN_UPGRADE && champ_item.status != CM.CHAMPION.STATUS_BROKEN_ENHANCE)
        if (!t.doingSpeedup || champ_item.status == 1) {
            setTimeout(function () { t.doAction }, 1000);
            return;
        }

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

        t.speedup = 0;

        if (secondsForRepair > 0 && CHupgradeData.overrideSpeedUp && CHupgradeData.useSpeedUp > 0) {

            t.speedup = TRupgradeData.useSpeedUp;

        } else {

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.day25 && CHupgradeData.useEH && unsafeWindow.ksoItems[8].count > 0) { t.speedup = 8; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour24 && CHupgradeData.useDH && unsafeWindow.ksoItems[7].count > 0) { t.speedup = 7; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour15 && CHupgradeData.useWH && unsafeWindow.ksoItems[6].count > 0) { t.speedup = 6; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour8 && CHupgradeData.useAH && unsafeWindow.ksoItems[5].count > 0) { t.speedup = 5; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour25 && CHupgradeData.useMH && unsafeWindow.ksoItems[4].count > 0) { t.speedup = 4; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.hour1 && CHupgradeData.useGH && unsafeWindow.ksoItems[3].count > 0) { t.speedup = 3; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute15 && CHupgradeData.useKH && unsafeWindow.ksoItems[2].count > 0) { t.speedup = 2; }

            if (t.speedup == 0 && secondsForRepair >= HOURGLASSES_TIME_MIN_THRESHOLD.minute1 && CHupgradeData.useSH && unsafeWindow.ksoItems[1].count > 0) { t.speedup = 1; }
        }

        switch (t.speedup) {
            case "1":
            case 1:
                secondsForRepair -= HOURGLASSES_TIME.minute1;
                divId = 'chUseSHLabel';
                break;
            case "2":
            case 2:
                secondsForRepair -= HOURGLASSES_TIME.minute15;
                divId = 'chUseKHLabel';
                break;
            case "3":
            case 3:
                secondsForRepair -= HOURGLASSES_TIME.hour1;
                divId = 'chUseGHLabel';
                break;
            case "4":
            case 4:
                secondsForRepair -= HOURGLASSES_TIME.hour25;
                divId = 'chUseMHLabel';
                break;
            case "5":
            case 5:
                secondsForRepair -= HOURGLASSES_TIME.hour8;
                divId = 'chUseAHLabel';
                break;
            case "6":
            case 6:
                secondsForRepair -= HOURGLASSES_TIME.hour15;
                divId = 'chUseWHLabel';
                break;
            case "7":
            case 7:
                secondsForRepair -= HOURGLASSES_TIME.hour24;
                divId = 'chUseDHLabel';
                break;
            case "8":
            case 8:
                secondsForRepair -= HOURGLASSES_TIME.day25;
                divId = 'chUseEHLabel';
                break;
        }
        if (t.speedup != 0) {
            t.setResult('Used ' + unsafeWindow.ksoItems[t.speedup].name);
            var divCount = unsafeWindow.ksoItems[t.speedup].count - 1;

            var divSpeedups = document.getElementById(divId);
            divSpeedups.innerHTML = divCount;
            unsafeWindow.modal_speedup_apply("champion", t.speedup, t.repairId);

            if (secondsForRepair <= 0) {
                secondsForRepair = 0;
                endTime = 0;
                //t.clearTimerH = setTimeout(t.clearRepair, 0);
                champ_item.status = 1;
                t.doingSpeedup = false;
                t.clearTimerH = null;
                t.timerH = null;
                t.setStatus("Repair Completed Using Hourglasses");
                t.buildQueueDisplay();
            } else {
                endTime = unixTime() + secondsForRepair;
                t.repairEnd = endTime;
                var n = new Date(t.repairEnd * 1000);
                t.setStatus("Repair begun ... Repair will be complete at " + n.toLocaleTimeString() + ". Item: " + champ_item.name);
                t.clearTimerH = setTimeout(t.clearRepair, secondsForRepair * 1000);
                t.buildQueueDisplay();
            }
            t.repairEnd = endTime;
            setTimeout(function () { t.doSpeedup(); }, 3000);
        } else {
            t.doingSpeedup = false;
            setTimeout(function () { t.doAction }, 3000);
        }
    },

    addUpgradeItem: function (id) {
        var t = Tabs.champUpgrader;
        var qItem = new QueueItem();
        qItem.item = id;
        qItem.action = "upgrade";
        qItem.level = OrganizerMaxCHLevel;
        CHqueueData.list.push(qItem);
        CHsaveQueueData();
        $("div#" + id).addClass('blueBorder');
        $("td#ch_card" + id).find("div.chbox").addClass('blueBorder2');
        t.buildQueueDisplay();
    },

    addEnhanceItem: function (id) {
        var t = Tabs.champUpgrader;
        var qItem = new QueueItem();
        qItem.item = id;
        qItem.action = "enhance";
        qItem.level = OrganizerMaxCHQuality;
        CHqueueData.list.push(qItem);
        CHsaveQueueData();
        $("div#" + id).addClass('yellowBorder');
        $("td#ch_card" + id).find("div.chbox").addClass("yellowBorder2");
        t.buildQueueDisplay();
    },

    addBothItem: function (id) {
        var t = Tabs.champUpgrader;

        var champ_item = unsafeWindow.kocChampionItems[id];
        if (!champ_item) {
            logit("Unable to find champion item.");
            return;
        }

        var qual = +champ_item.rarity;
        var lev = +champ_item.level;

        if (qual >= OrganizerMaxCHQuality) {
            logit("Item already at wondrous");
            return;
        }

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

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

            if (lev < maxLev) {
                qItem = new QueueItem();
                qItem.item = id;
                qItem.action = "upgrade";
                qItem.level = maxLev;
                CHqueueData.list.push(qItem);
                $("div#" + id).addClass('blueBorder');
                $("td#ch_card" + id).find("div.chbox").addClass("blueBorder2");
            }

            qItem = new QueueItem();
            qItem.item = id;
            qItem.action = "enhance";
            qItem.level = nextQual;
            CHqueueData.list.push(qItem);
            $("div#" + id).addClass('yellowBorder');
            $("td#ch_card" + id).find("div.chbox").addClass("yellowBorder2");
            lev = maxLev;
            qual = nextQual;
        }

        CHsaveQueueData();
        t.buildQueueDisplay();
    },

    doAction: function () {
        if (CHrepairData.active) return;
        var t = Tabs.champUpgrader;
        var retryTime = GeneralOptions.retryInterval;

        var repairChamp_Item = unsafeWindow.kocChampionItems[t.repairId];

        if (t.doingSpeedup && repairChamp_Item.status == 1) {
            t.doingSpeedup = false;
            t.repairEnd = 0;
            setTimeout(function () { t.clearRepair(); }, 0);
            clearTimeout(Tabs.champUpgrader.timerH);
            t.timerH = setTimeout(t.doAction, retryTime * 1000);
            return;
        }

        try {
            // check if repair is done
            var ti = t.clearRepair();
            if (ti <= 0) {
                // repair is done
                if (CHqueueData.oneItem || (CHqueueData.doingRepairs == true)) {
                    if (CHupgradeData.repairAll == true) {
                        var lastBroken = 0;

                        // repair everything
                        for (k in unsafeWindow.kocChampionItems) {
                            var champ_item = unsafeWindow.kocChampionItems[k];
                            if (!champ_item) continue;


                            if (champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                                lastBroken = champ_item.equipmentId;
                            }
                        }

                        // repair from the botton up.  This forces the items broken in the +1 upgrades to be fixed first so the salvager can continue
                        if (lastBroken != 0) {
                            t.doRepair(lastBroken);
                            clearTimeout(t.timerH);
                            t.timerH = setTimeout(t.doAction, retryTime * 1000);
                            return;
                        }
                    } else {
                        // repair first broken item in queue
                        for (k in CHqueueData.list) {
                            var q = CHqueueData.list[k];
                            if (!q) continue;
                            var champ_item = unsafeWindow.kocChampionItems[q.item];
                            if ((champ_item == null) || (CHqueueData.list[k].status == "complete"))
                                continue;

                            if (champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                                t.doRepair(champ_item.equipmentId);
                                clearTimeout(t.timerH);
                                t.timerH = setTimeout(t.doAction, retryTime * 1000);
                                return;
                            } else if (CHqueueData.oneItem) {
                                break;
                            }
                        }
                    }
                }

                // all repairs complete
                CHqueueData.doingRepairs = false;
                // set the index
                t.selectNext();
                CHsaveQueueData();

                // if we reach the end of the queue, start repair cycle
                if (CHqueueData.index < 0) {
                    t.setStatus("Reached end of queue.")
                    t.setResult("");
                    CHqueueData.doingRepairs = true;
                    CHsaveQueueData();
                    clearTimeout(Tabs.champUpgrader.timerH);
                    t.timerH = setTimeout(t.doAction, retryTime * 1000);
                    return;
                }

                // upgrade/enhance next item
                var qItem = CHqueueData.list[CHqueueData.index];

                if (qItem) {
                    //qItem.triesTotal++;
                    //qItem.triesThis++;

                    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: " + unsafeWindow.kocChampionItems[t.repairId].name);
                if (CHupgradeData.useSH || CHupgradeData.useKH || CHupgradeData.useGH || CHupgradeData.useMH || CHupgradeData.useAH || CHupgradeData.useWH || CHupgradeData.useDH || CHupgradeData.useEH || (CHupgradeData.overrideSpeedUp && CHupgradeData.useSpeedUp > 0)) {
                    var champItem = unsafeWindow.kocChampionItems[t.repairId];
                    var chQuality = champItem.rarity;
                    var chLevel = champItem.level;
                    var useThoseSpeedups = true;
                    if (CHupgradeData.hourglassQualitySpecific && chQuality < CHupgradeData.hourglassQuality) useThoseSpeedups = false;
                    if (CHupgradeData.hourglassLevelSpecific && chLevel < CHupgradeData.hourglassLevel) useThoseSpeedups = false;
                    if (useThoseSpeedups) {
                        t.doingSpeedup = true;
                        setTimeout(function () { t.doSpeedup(); }, 2000);
                    }
                    //                    t.doingSpeedup = true;
                    //                    t.doSpeedup();
                    retryTime = 1;
                }

            }
            //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocChampionItems);
        } catch (e) {
            logit("do action exception");
            logit("exception: " + inspect(e, 3, 1));
        }
        // recycle
        clearTimeout(Tabs.champUpgrader.timerH);
        t.timerH = setTimeout(t.doAction, retryTime * 1000);
    },

    selectNext: function () {

        if (CHqueueData.index >= CHqueueData.list.length) CHqueueData.index = 0;
        if (CHqueueData.index < 0) CHqueueData.index = 0;

        // for single item mode, always start from the top
        if (CHqueueData.oneItem) CHqueueData.index = 0;

        var l = CHqueueData.list.length;
        for (i = CHqueueData.index; i < l; i++) {
            var item = CHqueueData.list[i];
            if (!item) continue;
            //var id = item.item;
            var champ_item = unsafeWindow.kocChampionItems[item.item];
            if ((CHqueueData.list[i].status != "complete")
                           && (champ_item != null)
                           && !(champ_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE)) {
                if (((item.action == "enhance") && (item.level <= champ_item.rarity)) ||
                               ((item.action == "upgrade") && (item.level <= champ_item.level))) {
                    item.status = "complete";
                } else {
                    CHqueueData.index = i;
                    return;
                }
            }
        }

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

    doEnhance: function (eItem) {
        //logit("enhance");
        var t = Tabs.champUpgrader;
        try {
            if (CHupgradeData.active == false || eItem == 0) {
                t.setStatus("Powered off");
                return;
            }
            var y = unsafeWindow.kocChampionItems[eItem];

            if (!y) return;

            if (y.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || y.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                // 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 " + GeneralOptions.minStones + " needed.  Waiting for more ...");
                return;
            }

            var z = CM.WorldSettings.getSettingAsObject("CE_ENHANCE_AETHERSTONE_MAP");
            var w = z[parseInt(y.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 = CHqueueData.list[CHqueueData.index];
            if (qI) {

                qI.triesTotal++;
                qI.triesThis++;
            }

            var chanceItem = 0

            var useDiv = '';

            if (CHupgradeData.active && CHqueueData.index != -1 && CHupgradeData.useQuality <= eItem.rarity) {

                if (CHupgradeData.useLOM) {
                    if (Seed.items['i21001'] > 0) {
                        chanceItem = 21001;
                        useDiv = 'chUseLOMLabel';
                    }
                }

                if (CHupgradeData.useGOM) {
                    if (Seed.items['i21002'] > 0) {
                        chanceItem = 21002;
                        useDiv = 'chUseGOMLabel';
                    }
                }

                //if (chanceItem) unsafeWindow.cm.InventoryView.removeItemFromInventory(chanceItem);

            }

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

            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

            //params.ctrl = 'ChampionRoom\\ChampionRoomServiceAjax';
            params.action = '4';
            params.cityId = Seed.cities[num_city][0];
            params.eid = eItem;
            params.chanceItem = chanceItem;
            params.aetherstones = w;
            params.gems = 0;

            //logit("Sending enhance request");
            t.setStatus("Sending enhance request");
            new AjaxRequest(unsafeWindow.g_ajaxpath + 'ajax/ceEquipmentManagerAjax.php' + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                loading: true,
                onSuccess: function (transport) {
                    try {
                        //logit("enhance request sucess");
                        //logit("transport: " + inspect(transport,3,1));
                        var rslt = eval("(" + transport.responseText + ")");
                        //logit("rslt: " + inspect(rslt,3,1));
                        if (rslt.ok) {
                            //if (rslt.updateSeed) unsafeWindow.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) {
                                ActionLog('Upgrader accidentally spent gems!  Upgrader turned off');
                                t.setStatus("Error ... shutting down");
                                CHupgradeData.active = false;
                                CHsaveUpgradeData();
                            }

                            if (rslt.itemConsumed.itemId != "0") unsafeWindow.ksoItems[rslt.itemConsumed.itemId].subtract()

                            Seed.player.might += rslt.mightGain;
                            $("#topnav_might").html(Seed.player.might);

                            if (y.rarity != parseInt(rslt.rarity)) {
                                logit("successful enhancement");
                                CHupgradeStats.enhanceSuccess[y.rarity][y.level]++;
                                CHsaveUpgradeStats();
                                y.rarity = rslt.rarity;
                                y.name = y.createName();
                                Tabs.champUpgrader.repaint();
                                t.setResult("Enhance successful.  " + addCommas(rslt.aetherstones) + " aetherstones used.");
                                document.getElementById('chAetherDisplay').innerHTML = displayCityAstone();
                                t.setStatus("Attempting next action");
                                unsafeWindow.cm.sounds.play("ch_success_build");
                                // update the cost line
                                var qItem = CHqueueData.list[CHqueueData.index];
                                if (qItem) {
                                    var now = new Date();
                                    qItem.lastUpgrade = "Enhanced to " + Tabs.champUpgrader.qualities[y.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 ' + unsafeWindow.kocChampionItems[eItem].name + ' [ ' + eItem + '] to quality ' + rslt.rarity + " in " + qItem.triesThis + " attempts. " + qItem.triesTotal + " total attempts for this item.";
                                    SuccessLog(msg);
                                    if (GeneralOptions.whisperToMe) sendChat("/" + Seed.player.name + ' ' + msg);

                                    if (GeneralOptions.sendToInbox) sendComposedMail(Seed.player.name, 'CHAMPION: Enhance Success: ' + unsafeWindow.kocChampionItems[eItem].name, msg);

                                    if (qItem.level <= y.rarity) {
                                        qItem.status = "complete";
                                        CHupgradeData.newUpgradeState = 2;
                                    }
                                    else {
                                        var now = new Date();
                                        qItem.status = "Partially enhanced";
                                        qItem.triesLast = qItem.triesThis;
                                        qItem.triesThis = 0;
                                        if (CHupgradeData.newUpgradeState != 2) CHupgradeData.newUpgradeState = 1;
                                    }
                                    CHsaveUpgradeData();
                                    setUpgradeColor();
                                }
                                CHsaveQueueData();
                                Tabs.champUpgrader.buildQueueDisplay();
                                clearTimeout(Tabs.champUpgrader.timerH);
                                t.timerH = setTimeout(t.doAction, 10 * 1000);
                            }
                            else {
                                logit("enhance failed");
                                CHupgradeStats.enhanceFailure[y.rarity][y.level]++;
                                CHsaveUpgradeStats();
                                ActionLog('Enhance failed Champion item ' + unsafeWindow.kocChampionItems[eItem].name);
                                if (rslt.broken == "yes") {
                                    y.status = CM.CHAMPION.STATUS_BROKEN_ENHANCE;
                                }

                                y.name = y.createName();
                                t.setResult("Enhance failed.  " + addCommas(rslt.aetherstones) + " aetherstones used");
                                document.getElementById('chAetherDisplay').innerHTML = displayCityAstone();
                                var qItem = CHqueueData.list[CHqueueData.index];
                                if (qItem) if (qItem.status == "not started") qItem.status = "started";
                                CHsaveQueueData();
                                t.buildQueueDisplay();
                                clearTimeout(t.timerH);
                                t.timerH = setTimeout(t.doAction, 10 * 1000);
                                //t.doRepair(y.id);
                            }
                            //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocChampionItems);
                        }
                        else {
                            logit("enhance error");
                            logit("Enhance result:" + inspect(rslt, 3, 1));
                            if (rslt.feedback)
                                t.setStatus(rslt.feedback);
                            else
                                t.setStatus("Unable to enhance at this time ... waiting for next cycle");

                        }
                    } catch (e) {
                        logit("exception: " + inspect(e, 3, 1));
                    }
                    return;
                },
                onFailure: function (rst) {
                    logit("Enhance request error.  Waiting for next cycle.");
                    t.setStatus("Unable to send enhance request.  Waiting for next cycle");
                    logit("result: " + inspect(rst, 3, 1));
                    // try to repair item
                    //t.doRepair(y.id);

                    return;
                }
            });
        } catch (e) {
            logit("exception");
            logit("exception: " + inspect(e, 3, 1));

        }
        return;
    },

    doUpgrade: function (uItem, bypass) {
        var t = Tabs.champUpgrader;
        var y = unsafeWindow.kocChampionItems[uItem];
        if (uItem == 0 || y == null) {
            t.setStatus("Item not found.");
            return;
        }

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

        if (y.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || y.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
            // repair and then try again later
            t.doRepair(uItem);
            return;
        }

        if (y.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE || y.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 " + GeneralOptions.minStones + " needed.  Waiting for more ...");
            return;
        }

        var z = CM.WorldSettings.getSettingAsObject("CE_UPGRADE_AETHERSTONE_MAP");
        var w = z[parseInt(y.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 = CHqueueData.list[CHqueueData.index];
            if (qI) {
                qI.triesTotal++;
                qI.triesThis++;
            }

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

        var chanceItem = 0

        var useDiv = '';

        if (CHupgradeData.active && CHqueueData.index != -1 && CHupgradeData.useLevel <= y.level) {

            if (CHupgradeData.useET) {
                if (Seed.items['i21058'] > 0) {
                    chanceItem = 21058;
                    useDiv = 'chUseETLabel';
                }
            }

            if (CHupgradeData.useST) {
                if (Seed.items['i21052'] > 0) {
                    chanceItem = 21052;
                    useDiv = 'chUseSTLabel';
                }
            }

            if (CHupgradeData.useJT) {
                if (Seed.items['i21051'] > 0) {
                    chanceItem = 21051;
                    useDiv = 'chUseJTLabel';
                }
            }
            //if (chanceItem) unsafeWindow.cm.InventoryView.removeItemFromInventory(chanceItem);
        }

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

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.action = '5';
        params.cityId = Seed.cities[num_city][0];
        params.eid = uItem;
        params.chanceItem = chanceItem;
        params.aetherstones = w;
        params.gems = 0;

        //params.tvuid;

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

                    //logit("transport: " + inspect(transport,3,1));
                    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');
                            CHupgradeData.active = false;
                            CHsaveUpgradeData();
                        }

                        if (rslt.itemConsumed.itemId != "0") unsafeWindow.ksoItems[rslt.itemConsumed.itemId].subtract()

                        Seed.player.might += rslt.mightGain;
                        $("#topnav_might").html(Seed.player.might);

                        if (parseInt(rslt.level) != y.level) {
                            logit("upgrade successful");
                            CHupgradeStats.upgradeSuccess[y.rarity][y.level]++;
                            CHsaveUpgradeStats();
                            //t.setStones(Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0]);
                            //y.level = parseInt(rslt.level);
                            y.level = rslt.level;
                            y.name = y.createName();

                            if (bypass != true) {
                                Tabs.champUpgrader.repaint();

                                t.setResult("Upgrade successful.  " + addCommas(rslt.aetherstones) + " aetherstones used.");
                                document.getElementById('chAetherDisplay').innerHTML = displayCityAstone();
                                t.setStatus("Attempting next upgrade");
                                unsafeWindow.cm.sounds.play("ch_success_build");

                                var qItem = CHqueueData.list[CHqueueData.index];
                                if (qItem) {
                                    var now = new Date();
                                    qItem.lastUpgrade = "Upgraded to +" + y.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 ' + unsafeWindow.kocChampionItems[uItem].name + ' [' + uItem + '] to level ' + rslt.level + " in " + qItem.triesThis + " attempts. " + qItem.triesTotal + " total attempts for this item.";
                                    if (GeneralOptions.whisperToMe) sendChat("/" + Seed.player.name + ' ' + msg);
                                    if (GeneralOptions.sendToInbox) sendComposedMail(Seed.player.name, 'CHAMPION: Upgrade Success : ' + unsafeWindow.kocChampionItems[uItem].name, msg);
                                    SuccessLog(msg);
                                    if (qItem.level <= y.level) {
                                        qItem.status = "complete";
                                        CHupgradeData.newUpgradeState = 2;
                                    }
                                    else {
                                        var now = new Date();
                                        qItem.status = "Partially upgraded";
                                        qItem.triesLast = qItem.triesThis;
                                        qItem.triesThis = 0;
                                        if (CHupgradeData.newUpgradeState != 2) CHupgradeData.newUpgradeState = 1;
                                    }
                                    CHsaveUpgradeData();
                                    setUpgradeColor();
                                }
                                CHsaveQueueData();
                                t.buildQueueDisplay();
                                clearTimeout(t.timerH);
                                t.timerH = setTimeout(t.doAction, 10 * 1000);

                            }
                        }
                        else {
                            logit("upgrade failed");
                            CHupgradeStats.upgradeFailure[y.rarity][y.level]++;
                            CHsaveUpgradeStats();
                            //t.setStones(Seed.resources["city" + Seed.cities[num_city][0]]["rec5"][0]);
                            ActionLog('Upgrade failed Champion item ' + unsafeWindow.kocChampionItems[uItem].name);
                            if (rslt.broken == "yes") {
                                y.status = CM.CHAMPION.STATUS_BROKEN_UPGRADE;
                            }
                            y.name = y.createName();
                            if (bypass != true) {
                                if (rslt.feedback) {
                                    t.setResult(rslt.feedback);
                                } else {
                                    t.setResult("Upgrade failed.  " + addCommas(rslt.aetherstones) + " aetherstones used");
                                    document.getElementById('chAetherDisplay').innerHTML = displayCityAstone();
                                }


                                //t.setStatus("Starting repair ... ");
                                var qItem = CHqueueData.list[CHqueueData.index];
                                if (qItem.status == "not started") qItem.status = "started";
                                CHsaveQueueData();
                                t.buildQueueDisplay();
                                //t.doRepair(uItem);  // fix item
                                clearTimeout(t.timerH);
                                t.timerH = setTimeout(t.doAction, 10 * 1000);
                            }
                        }
                        //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocChampionItems);
                        return;
                    }
                    else {
                        logit("upgrade not ok");
                        logit("result: " + inspect(rslt, 3, 1));

                        if (bypass != true) {
                            t.setResult(rslt.feedback);
                        }

                        logit("Upgrade result:" + inspect(rslt, 3, 1));

                    }
                } catch (e) {
                    logit("upgrade exception");
                    logit("Exception: " + inspect(e, 3, 1));
                }
                return;
            },
            onFailure: function (rrr) {
                logit("upgrade failure");
                logit("RRR: " + inspect(rrr, 3, 1));

                t.setStatus("Unable to transmitt upgrade request.  Waiting for next cycle.");

                return;
            }
        });

        return;
    },

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

        var action = $("#chAction").val();

        if (action == "both") {
            t.addBothItem($("#chUpgradeList").val());
            return;
        }

        var qItem = new QueueItem();
        qItem.item = $("#chUpgradeList").val();
        qItem.action = $("#chAction").val();
        qItem.level = $("#chMaxLevel").val();

        if (qItem.item == 0) return;

        CHqueueData.list.push(qItem);
        CHsaveQueueData();
        t.buildQueueDisplay();
    },

    buildLevelWidget: function () {
        var t = Tabs.champUpgrader;
        var m;
        if ($("#chAction").val() == "enhance") {
            m = '<div id=chMaxDiv> Max: <select id="chMaxLevel">';
            for (i = 1; i <= 5; i++) {
                m += '<option value="' + i + '">' + t.qualities[i] + '</option>';
            }
            m += '</select></div>';
        } else if ($("#chAction").val() == "upgrade") {
            m = '<div id=chMaxDiv> Max: <select id="chMaxLevel">';
            for (i = 1; i <= OrganizerMaxCHLevel; i++) {
                m += '<option value="' + i + '"> +' + i + '</option>';
            }
            m += '</select></div>';
        } else {
            m = '<div id=chMaxDiv> - <select id="chMaxLevel">';
            m += '</select></div>';
        }

        $("#chMaxDiv").html(m);
        if ($("#chAction").val() == "enhance") {
            $("#chMaxLevel").val(5);
        } else if ($("#chAction").val() == "upgrade") {
            $("#chMaxLevel").val(OrganizerMaxCHLevel);
        }

    },

    buildQueueDisplay: function () {
        var t = Tabs.champUpgrader;
        $("#chQueue").html("<table id='chQueue' width='100%' class=chTabPad/>");
        $("#chQueue").append("<tr><th width='10%'>Remove</th><th width=5%>Reorder</th><th width='8%'>Status</th><th width='25%'>Item</th><th width='5%'>Action</th><th width='5%'>Max</th><th width='40%'>Status/Last Upgrade/Attempts</th></tr>");

        for (ii in CHqueueData.list) {
            var q = CHqueueData.list[ii];
            if (!q) continue;
            var the_item = unsafeWindow.kocChampionItems[q.item];

            var name = "Unknown / Item removed";
            var id = 0;

            if (the_item) {
                name = the_item.name;
                id = the_item.equipmentId;
            }

            var m = "<tr>";
            m += "<td><div><div id=chQueueRemove" + ii + " class=chremove/></div></td>";
            m += "<td><div class='chup' id=chUpRow" + ii + " /><div class='chdown'  id=chDownRow" + ii + " /></td>"
                   + "<td><div id=chState" + ii + "></div></td><td class=chUpdaterItemName><div id=chUpdaterItem" + id + ">"
                   + name + "</div></td><td>" + q.action + "</td><td>";

            if (q.action == "enhance") {
                m += '<div style="text-align: center;"><select id="chChangeLevel' + ii + '" style="width:90px; text-align: center;">';
                for (i = 1; i <= 5; i++) {
                    m += '<option value="' + i + '" ' + (q.level == i ? 'selected' : '') + '>' + t.qualities[i] + '</option>';
                }
                m += '</select></div>';
            } else {
                m += '<div  style="text-align: center;"><select id="chChangeLevel' + ii + '" style="width:90px; text-align: center;">';
                for (i = 1; i <= OrganizerMaxCHLevel; i++) {
                    m += '<option value="' + i + '"  ' + (q.level == i ? 'selected' : '') + '> +' + i + '</option>';
                }
                m += '</select></div>';
            }

            m += "</td><td style='text-align: center; white-space: pre-wrap;'>" + q.status + " / ";
            if (q.lastUpgrade) m += q.lastUpgrade;

            m += " / " + q.triesThis + " tries this level, " + q.triesTotal + " tries total"

            m += "</td>";
            m += "</tr>";

            $("#chQueue").append(m);
        }

        for (var j = 0; j < CHqueueData.list.length; j++) {
            var q = CHqueueData.list[j];
            if (!q) continue;
            var the_item = unsafeWindow.kocChampionItems[q.item];

            if (the_item) {

                $("#chUpdaterItem" + q.item).mouseover(function (A) {
                    var champ_id = $(this).attr("id").split("chUpdaterItem")[1];
                    ShowChampTooltip($(this), "chtrTooltip", champ_id);
                });

                $("#chUpdaterItem" + q.item).mouseout(function (A) {
                    HideChampTooltip("chtrTooltip");
                });

            }

            $("#chQueueRemove" + j).attr('v1', j);
            $("#chQueueRemove" + j).click(function () { t.deleteQueueItem($(this).attr('v1')); });

            $("#chUpRow" + j).attr('v1', j);
            $("#chUpRow" + j).click(function () { t.moveUpRow(+($(this).attr('v1'))); });

            $("#chDownRow" + j).attr('v1', j);
            $("#chDownRow" + j).click(function () { t.moveDownRow(+($(this).attr('v1'))); });

            $("#chChangeLevel" + j).attr('v1', j);
            $("#chChangeLevel" + j).change(function () { t.changeLevel(+($(this).attr('v1')), $(this).val()) });

            if (!the_item || !(the_item.equipmentId)) {
                $("#chState" + j).html("<div style='text-align:center'> ??</div>");
            } else if (q.status == "complete") {
                $("#chState" + j).addClass('chsuccess');
            } else if (the_item.status == CM.CHAMPION.STATUS_BROKEN_UPGRADE || the_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) {
                $("#chState" + j).addClass('chbroken');
            } else if (the_item.status == CM.CHAMPION.STATUS_REPAIRING_UPGRADE || the_item.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE) {
                $("#chState" + j).addClass('chhammer');
            } else {
                $("#chState" + j).html("<div class='chgbtn'/>");
                $("#chState" + j).css('text-align', 'center');
            }
        }

    },

    deleteQueueItem: function (i) {
        // delete an item from the queue
        var t = Tabs.champUpgrader;
        CHqueueData.list.splice(i, 1);
        if (i > CHqueueData.index) CHqueueData.index--;
        CHsaveQueueData();
        t.buildQueueDisplay();
    },

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

        var q = CHqueueData.list[index];
        if (!q) return;

        q.level = level;
	    if (q.status == "complete") q.status = "started";
        CHsaveQueueData();
        t.buildQueueDisplay();
    },

    moveUpRow: function (i) {
        if (i < 1) return;
        var t = Tabs.champUpgrader;
        var q = CHqueueData.list.splice(i, 1);
        CHqueueData.list.splice(i - 1, 0, q[0]);

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

        CHsaveQueueData();
        t.buildQueueDisplay();
    },

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

        var t = Tabs.champUpgrader;
        var q = CHqueueData.list.splice(index, 1);
        CHqueueData.list.splice(index + 1, 0, q[0]);

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

        CHsaveQueueData();
        t.buildQueueDisplay();

    },

    updateCHTab: function () {
        $("#chexecupgrade").html("Upgrade " + (CHupgradeData.active ? "ON" : "OFF"));
    },

    togglePower: function (obj) {
        var t = Tabs.champUpgrader;
        
        if (!CHupgradeData.active && CHrepairData.active) {
            alert('You must disable repair tab first');
            return;
        }

        var btn = document.getElementById('chUpgraderPower');
        if (CHupgradeData.active == true) {
            CHupgradeData.active = false;
            btn.value = "Upgrade = OFF";
            t.setStatus("Powered off");

        } else {
            CHupgradeData.active = true;
            btn.value = "Upgrade = ON";
            t.setStatus("Power on");
        }

        if (CHupgradeData.active == false) {

        }

        t.updateCHTab();
        CHsaveUpgradeData();

    },

    toggleSelect: function (obj) {
        var btn = document.getElementById('chUpgraderSelect');
        var t = Tabs.champUpgrader;
        if (CHupgradeData.enhanceAction == true) {
            CHupgradeData.enhanceAction = false;
            btn.value = "Action = Upgrade";
        } else {
            CHupgradeData.enhanceAction = true;
            btn.value = "Action = Enhance";
        }
        t.updateTRSelect();
        CHsaveUpgradeData();
    },

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

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

    doRepair: function (rItem) {
        var t = Tabs.champUpgrader;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        if (CHupgradeData.active == false || rItem == 0 || unsafeWindow.kocChampionItems[rItem] == null) {
            logit("repair is turned off");
            return;
        }
        var theItem = unsafeWindow.kocChampionItems[rItem];

        params.action = "6";
        params.eid = rItem;
        params.cityId = unsafeWindow.currentcityid;
        params.gems = 0;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                //logit("repair success");
                //logit("tport: " + inspect(transport,3,1));
                var rslt = eval("(" + transport.responseText + ")");

                //logit("rslt: " + inspect(rslt,3,1));
                if (rslt.ok) {
                    //logit("ok");
                    var item = unsafeWindow.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();
                    //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocChampionItems);
                    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;
                    Tabs.champUpgrader.buildQueueDisplay();
                    // uW.cm.ThronePanelView.clickSpeedUp(item);
                }
                else {
                    logit("Repair failed");
                    logit("result:" + inspect(rslt, 3, 1));

                    // 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);

                        unsafeWindow.kocChampionItems[rItem].status = CM.CHAMPION.STATUS_INACTIVE;
                        t.clearRepair();
                    }

                }
                return;
            },
            onFailure: function (ttt) {
                logit("repair error");
                // 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;
                }
                logit("ttt: " + inspect(ttt, 3, 1));
                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 && unsafeWindow.kocChampionItems[t.repairId] != null) {
                if (unsafeWindow.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_INACTIVE
                               || unsafeWindow.kocChampionItems[t.repairId].status != CM.CHAMPION.STATUS_ACTIVE) {
                    t.setStatus("Repair time complete.");
                }
                unsafeWindow.kocChampionItems[t.repairId].status = CM.CHAMPION.STATUS_INACTIVE;
                t.repairId = 0;
                Tabs.champUpgrader.repaint();
            }

        }
        //unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocChampionItems);
        return timeUntilDone;
    },

    show: function () {
        Tabs.champUpgrader.repaint();
    },

    hide: function () {
    }
};


Tabs.throneUpgradeStats = {
    tabOrder: 400,
    tabLabel: 'Upgrade Stats TR',
    tabDisabled: false,
    myDiv: null,

    init: function (div) {
        var t = Tabs.throneUpgradeStats;
        t.myDiv = div;
        t.buildTab();
    },

    buildTab: function () {
        var t = Tabs.throneUpgradeStats;

        var m = '<div style=" position: static; width: ' + OrganizerWindowWidth + '; height: ' + OrganizerWindowHeight + '; overflow-x: hidden; overflow-y: auto;" >';
        m += '<DIV id=trStatsMain2 class=trStat>THRONE UPGRADE STATISTICS</div>';
        m += '<DIV id= trStatsTabDiv2 align=left style="margin-top:10px; overflow-x: auto; overflow-y: auto;position: static;width: 100%;">';
        m += '<TABLE class=trStatTab align=center cellspacing=0>';

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

        var qstrings = new Array(uW.g_js_strings.throneRoom.simple, uW.g_js_strings.throneRoom.common, uW.g_js_strings.throneRoom.uncommon,
                    uW.g_js_strings.throneRoom.rare, uW.g_js_strings.throneRoom.epic, uW.g_js_strings.throneRoom.wondrous, uW.g_js_strings.throneRoom.miraculous);


        m += '<TR valign=top align=center><th></th>';

        for (l = 0; l < OrganizerMaxTRLevel; l++) {
            m += "<td style='font-weight: bold;' class='td" + (l % 2) + "'  >";
            m += "&nbsp;+" + (l + 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];
        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];

        for (q = 0; q <= OrganizerMaxTRQuality; q++) {
            m += '<TR valign=top align=center><th>' + qstrings[q] + '</th>';
            for (l = 0; l < OrganizerMaxTRLevel; l++) {
                if (TRupgradeStats.upgradeSuccess[q][l] == null || isNaN(TRupgradeStats.upgradeSuccess[q][l])) TRupgradeStats.upgradeSuccess[q][l] = 0;
                if (TRupgradeStats.upgradeFailure[q][l] == null || isNaN(TRupgradeStats.upgradeFailure[q][l])) TRupgradeStats.upgradeFailure[q][l] = 0;
                st[l] += TRupgradeStats.upgradeSuccess[q][l];
                ft[l] += TRupgradeStats.upgradeFailure[q][l];

                m += "<td class='td" + (l % 2) + "'  >";
                m += TRupgradeStats.upgradeSuccess[q][l] + " / " + TRupgradeStats.upgradeFailure[q][l];
                m += "</td>";
            }
            m += '</TR>';
        }

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

        m += '<TR valign=top align=center><th> Percents: </th>';
        for (l = 0; l < OrganizerMaxTRLevel; l++) {
            m += "<td style='font-weight: bold;' class='td" + (l % 2) + "'  >";
            if ((st[l] + ft[l]) == 0)
                m += "--";
            else {
                var p = (100 * st[l] / (st[l] + ft[l]));
                m += p.toFixed(2) + &q