Champion

Champ Tab

Dieses Skript sollte nicht direkt installiert werden. Es handelt sich hier um eine Bibliothek für andere Skripte, welche über folgenden Befehl in den Metadaten eines Skriptes eingebunden wird // @require https://update.greasyfork.org/scripts/399259/787088/Champion.js

/**************************** Champ Tab ****************************************/
// @tabversion 20190522

Tabs.Champ = {
	MinVersion: '3.32',
	tabOrder: 1905,
	tabLabel: 'Champ',
	tabColor : 'orange',
	activepanel: '',
	myDiv: null,
	MaxItems: 0,
	CHAMP_DELAY: 5,
	LoopCounter: 0,
	UpgradeTimer: null,
	RepairTimer: null,
	SalvageTimer: null,
	autoupgradedelay : 0,
	autorepairdelay : 0,
	autosalvagedelay : 0,
	intervalUpgradeSecs : 10,
	intervalRepairSecs : 10,
	intervalSalvageSecs : 6,
	intervalSalvageLoopSecs : 20,
	loopupgradeaction : false,
	looprepairaction : false,
	loopsalvageaction : false,
	logarealist : {GENERAL:'GENERAL',SUCCESS:'SUCCESS',REPAIR:'REPAIR',SALVAGE:'SALVAGE'},
	logfilter: 'GENERAL',
	logEntries: 100,
	SuccessLog : [],
	RepairLog : [],
	SalvageLog : [],
	EventLog : [],
	Tick	: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AgNBDgX+Hd0CAAACkZJREFUWMOtl3uMHdV9x7+/c2buzJ373rvvtb3exYuNDfYaMIkgkNYCFIdScB+CVm4UIWiTIKs0FVSplAqaBiUWbYXSh1CcREkr2lRKrZgoJThYLQWMIY6pjV+7fqx37fU+7t7nPO48zvn1j12btYG0fzDSkWbmjH6f3/m9h/AxXjw+DhoZAY+PL39NH/U5jYx85ObHAadfoQBfUeLjtcAYALosUyzBFxczL4EZRFfujQ8VNLsb1PMoeHb3tVv0oYdhE/BvAhQDDAJIgBYVYGYiIkK+JA6ceF0MWKVwVfcKtaQQyf8HnABIAMayZQIwwWyASIINAdEWICawKcFSAjBYJVInWoh1a2/Y33jl4ef/+e9uOHb4xKltD+wI4baAJWFXH/F9+GXwZXhqCWyAWQIgEBgsEpBOIEIF2VJgAVCOEBNTYTAj+3IPf3f+G1/6p3/44UzhTPHJnV98tI25SwKA+oACy059GZwCsw0gDSANIhuABZIGQEtCOAFTBOKIKYohg4RYKO4e7mnmW3/2l6e+8Dt7/uLlX95Tu/eJF/Z+7zguXGDWimnJm8Zysy8LGhOADWaHOcqQsIts9g6w6ByE2bGCjOwACAYnURXaryCuXxJxZZJUWIMwYwwMrflP77++/Df//c2b3/nH9974HO94Ytcru0/i9GliZk2LQbho8Wt8LpfgaWbOEUd5ZEc3atF/H6ziraTP9qE97iCuSbACkwWkVkZk3+hqlT4l3LP/EWbY+uvJ3Y98/+1/7fP2qEOfLz385Ne/9tWjcKOIQTERxwAxAH0lDZfgYgnuAJwHRCdnNm/V5urHBU+sUtMvQM2OEderoMAHtAIMA7CyEB0DMIYegp/7dPup9x5RP9y/L2O/lr30lY2P/cnjO3e8jbZosbICYjMGQV2Bj4wsxQCDmFgSk8VAhoiLiRzcAhJfRvXF3uDk9+GPTeL0RIDDFxOMuYQIAj22wK19FawfrqARuPyNeJe958dH0HPeCf/8tkde+KM/3T6FWtVkYYIow0hyGiw16EohgqFndoOJiSBMgNJEXIyVU2pWjj6WSTd64+M/wuShi/y374Z0yFYIugF7kJAyJURi4hXXwrrAxOFjh+n4wTrK1RR23f+78lPXdwlEbo6p3SJDSmaficFQhcUEWqqaBhETWMgk4VQcJ7l0Pp8be+2lB4dvHrnZO/Yyzr0zx398XFG8iZHrIHQ6EqmUgZRhwmQLuayDt+bmMLm/jlQd+IM1a/me0aIRq/rO6dNnj3f3FWogmIZhCKYAlHQxrb7rSuk2AIJmLWfnG+lm0y/H/rmhjrL5W62Jw7ww1aRdk4rkbUCulIKdk7DTApZpwDIspMnGa+dmMfGzOrgFdIQONgyVCe1ZTtmZ4vmTr25Plz77Aqswk8vYrmkFIczqYvSPjCylIYHaYSLn5pvZpuuWUZ28rTige4TU+EUtxsJaRld/CrYjIC1C2rFgWyk4lMKrv5zG+L4auAlYvsTarR3Y17iAmysOFTMBEFa2jB058VLvYFeDhDZLliOWesWyGFAartc2kiSxDSnSbb+15uhpP7WfGfb6TbjRIJRzOQz2F9BdBCbrb6MR+jjwbgWn9tXANYB94IZPlJFeyXhvrIKTF4vYPNiDsNXq8uKplUFPfsK2zJRWaRLi6nZiRLGiSqVlhlFkmwIpt97q6x7Iov/wDJ79zpsIshoJAUoA/Wvy+Pz2h3DLiINnf/I8kspiQvV2OejfYqHuBWgjwuGLC9jQ3wnfi7NNv97ZFSe2F0RmSWmZEle3HyNRilpeIJJESdMUorHg5YbXFLD11k68qAowmDBzJsB8JcD8/zTx9SPfhkwDZrRYM2VMWPepAiinEDZiKJ1guhEgijQ8P6F6HGS11jIMI8la07X9TxhSIopiUlozEalarQ3PjRDGhDiMYQ8DN95fwvobOyAjgsWAEQCsAB0C/QNZdG1OwQ1DhGGMOFIQzGi3GW5ToR0xhCAthODF5nV18xOCiP0gUk3XB6QIqy1uNioe2LBQikw0FiKEMsLqbRnctKUMERKQAEgA8oCN9xXg6jZarQhtTyH2NQYyeXhujHo9VjDthmEYkWkaioj0td1XaGaO4kS5XhhL0wgi2JOXLjSRsIFNHR1waxG8Zgg3bGPwM2msHS2CPSDxgOs25iAGFKqVNrxqjHZdId2WuK5cRr3iYqGauFZH57QhRdswRGRIyR9QgDVzqZiNAPKI2LN6uo9NnmuGrZrHd16/Dk5LoDUfoTEfoO75WHWvhcG1GZhtQtctJiqVAM25GMGCQljTGM33omxnMDvR4LmWMX395pEJaRieachIpIwPWiDtWOjrKSaWlXJdL/Juv3v08PiMnpw6MUu92Sz/9rrNaC9oNC/FWLgQoFb3Ud4iMXCTjdCIUb8Ywp+NES5olBIHf3jHJ7k24+L8WI3D3hVv3H7r6mkhhJ9x7BBgDYCXj3oCkjiftZN83vFct+3eccvgVGH0hj0HDs4kp35xhn7/rl/nZx5+EiVagYUJH3NnfXjtCM4GRmM2RO18gGge+OR1n8a/PfU0ty62cPTAJE4E6bOPPr7tpTCIXCmFl8+lYyitL09dVyafp7+yHZlcGm0/RLXuk5WS4p5fWz/z04PnCxPvXVyfNOdpw8AK3n73Q3Td0B2oVpuYn51H24tRTHVj6033Y+dnv4DPdPXiyMuv0pv7jtHxKi9s27H1mw/8xuiR6kKrkcukXcs2I9bQRMAzz+29espl/nfUxqbkkRMXHGIurBnuzi9UWqueeXbvl8Tcpfs2rusRfUNl7h8eoKGNd6J71TqwFvCac7h44iDGDr2D6Ykanxmfo/GWWrj3wdufe+KLd/88jpNKorhRLmU9IoqZmUXvYx8cs9XMtyE683TwlXfNS7N1Z6CvlO3rKRTqzaDv6V0/2VE9PbVtZdHs6u3OUqlkIZNLIYk1Aj9GoxZiZs7HdM2PgnT25P0PfuK7Tz1+92uNZlCPE9Uo5h3fNI0YgLo8eS13wfsjWeMHmJmap5/tP2r5fphZv7Y/vWao2wFzx4t7Do2+9dbYXa1KY1RFcb9g7TBDxppjlrKWLWTHhq8feOOh7Vtev/Outefr861WnGg3n7N9y05F0Kw/DP6+C5Y23HN/j3/Zc1CMnZmxchk7fcumVamucs4xDMqFYVLw/Cg/N98qzle8YhTFZqHguEODXZU1w90LpYLTJEIrUdozDcN30qlQSpEwL0b+tab/yD+dd/Z+FT/6+SExuKJDpm3TZGbbsmTasc10PmunOss52dmRg22nWEqhACRac6SZQ9OQQS6TjiApgWbFzPqjwFea0fKH5//q97DlN7+GqXef0xk7pf0wSl5/ayy6MF1tt7zA15qtXNaW/b1FvXpllyrk0yqbsVQuk45LRScRpqGhtGKlmYhY9D72oWb/lRb48Q924oHPfWtxVuW9OPDTN1EqZumNg2N08vSMUEqLVSs6sGnDKu4qZzmfc/RAbxFSCmZmEBFfBv5fcAD4X6XxV1xnuaXKAAAAAElFTkSuQmCC",
	Button	: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAK8AAACvABQqw0mAAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAAQxSURBVFiF7ZZdbFNlGMd/pz09Pf1ut+4rdGVM1mZswJwEJAESQ0zkXsiqESXxyo8bFuKF8QqJ0Zh4IV6oFzJvRuJmJhDChYnTBAJEsyVmmE1gcFhbWkrH6NqefuwcL/oSZvzYChpu9iT/PO95nyfv/5ec85xzJNM0eZJheaLuawBrAGsAgLzaxomJiV6fz/ei0+HcpyhKFxJypVzRinrxh3w+/01PT89PjwIgrfQiGv9xPBTp6nrH6/LFisVioxbXSKXTADQ0BOgIdeByucoFvXAmnoh/2N/ff/k/A5icnNgbWtd+olqqhkbOjnLu8jnuLc1TVZeQLCBXZAKWALt6dzGwbwCP31NJppKHN23adPyxASYnJ/e2trad1a7fVI4cP8LPhV9wR9yozXZM1cTAQK7IFDM6+g2dqBTh2KvH6NvSRzqTPtzT0/PJIwOcP3++bX14/YR2Q2uJHY2h+TUsmy0YjQY4AZXa41sCCiDNS5jTJs3pZobeHmJr71biqfhz257ZNr4SwN9OQTAYfLeY01sGPx1Ec2vQB8YGAzqBCLAReAroqmVzgwm9kG5KM/j1IJk7d/F5fR+cPHlSqRvg0qVL3YpVefnbc6NczFyELUAYWAe0Aa1CLSK3iVoY6IYrhSsMfz+M1bQ+G+mKvFI3gM1mi92/d98/emEUOoRREGgEAoAP8IrsA/yiFhS9YTj96ynuZrMg8VbdAJi8oM1pzCzMQJMw8wIuHt5/FbCL7BQ1t+hrgqv5q8RTcxhLRl/dAOVyeWM8EacgF2qH2wFlWbYBViFZXD+o2wEHlGwlEpkEekFfyf+vALquy7qugyQ2JP68Xh7SMlkeri0WC6VyicX8Yv0AlWrllkN14MJVG7MyUFmmJcAATKAqVBF9ZaAEclXGq3qpVCv1AxiGMe5xeWi3t0MWWBQqALpQaZl0UVsEckAWwo4wLpsLE/NW3QAOh2PYrtorO8I7IAncAe4C88CCMHkAlRN78zVjMkAcdod2I0kSNpvty7oB9uzZc8G0mmf6N/bTLXfDTO1QksBtIC2g7oj1bVFLAL9Dh9zB9vbtLLF0LRqNflE3AGA0NTcddbqd1QObD9CSbYEp4DowC9wANKGbYm8WmILGTCOHNh9ClmTcHvf7nZ2dqZUA/vFjNPbd2BvJueRn8WScU9dOMSVPYQvZkAISurU2XoqhYMlZ0Od0okaU/V37aXW30tDcMBSLxV5byfxfAQBGRkYGU8nUxwv3FpjOTDNbmiVrzaJ47LVRWyzhNTxEXBGigSgOxUEgGBg6ePDg69Tm4/EAAE6fOf18Yi7xXiFX2J0v5EGGYrUIEjhsTqyGBUVWUF3qbw3Bho9iA7ETqzFeNYAIx9jY2Evz2fk3c7nc08V8EcM0UFUVt9et+f3+z3fu3PlVKBRK1mNeD8D/Fk/8r3gN4A/o86RnMMwtFQAAAABJRU5ErkJggg==",
	Hammer	: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAbvAAAG7wBureguwAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAAAPdEVYdFdyaXRlcgBTdXBlclBOR8XEr90AAAAYdEVYdEZpbGUgTmFtZQBUUjJfaGFtbWVyLnBuZ9ktavUAAAVaSURBVFiF7Zd/UFRVFMe/9y27y/4AIlxYwNjQRh1g0pJKjWkUcNUBETRDRRrNIkvDxB+j2JjVOOjkrxpRtMgfkIkpmI5jLgsaUSoCi4ogyU9RBPnVKvt22bdvb3+4YwgrrsqM/3hm3syb+8655zP3fc899xJKKZ6lMc80+3MAAE6OOBFCiM1X7u7u5h4ZMdFn6BCVOwABazR2Hfglp/7GjVstAAyUUuvjAJBHiZAQIgAg8/PzVS5MiH8taenH8dU1DYNvt3ZIARCxWNz9atCw6rj4RZuOHddUANBTSvkBASCEMABc4+e+O3LH9pTlZ8/rgvJOn1MWl5Y7m80cCCGwWq1Qh47tWp70oW5x4pp1P+05WALgDnWwvB4KYFt2afDokQEFZ7I3bvl+75uncgtlPX0YhgHb1YXOjg5ETQ1n1yR/phkXMnVZVVVNg6Or0J8IhQqFh++GlOT3Mg4cC+6dHAAopeAsHAhDUHap0onneYlYJHJIV/0CEEJEALz27dkW1dqmn/PzweMu9vysVis4CwdQiphpkzrPnPn75KXLlXoADguxDwAhxAOA/285e2YQRvhR+r4jCnu/iRACnudh4Tg4S5wxdszrHSd/zy/HvUpweHvtA6DVZEVSy83tL7i7J32XmuHf3W0W9vaxWq1wchKC5y0wm8xQeimor6+X/uLFilYA3Y4mB+zsA2GhIdGhk+eNk7u6SZylcmIwsA9853keEokEchcXVNfWoq2tE/M/mHNnkMeLNVerqjsAOFyCdgEASECIiBBC2ltvP5jcYoFUJodU7oLKinKMU8kQEPMOklcktE+JnJvJssa7j7sR2ROhycJxFpORhYfC8/6gxWKB3MUVErkcutJiTFEJ4CXi0V5eBLajWRQZET4YgIwQ8nRVkJdfeKpAm9loZFnOZDTCQ+EJnufhpVTCw9MTVy5dxPTh/1dkWPBQ6HIyFAviohalrF8dAmDQ40D0AQhXx57Iyy/cVaDNbGANXZyJNSAgMBCubm4oLSmBxPlBTVopRWfTdXFp9r4RiQmzV2/dvG4CAAUhpI94HQIA0Byujv01L78w7Y/cjAaDwcA11teh+to1MOC5rZvW6tcfPKIHwPUM6mysdb5waPeIBbMjV+3auVENwNMRiD4AlFJzT4gCbWY9a+o2CRjGVFGmqWcI0s4V6dK+/jG9AQB3uqT2XiAh0Dc1Ohcf+mH4DPWYlYcP7Y4RiYR+hBC5raHZtf56gQiAUqvJiggLDZkE3NNHuDpWAwBaTVZ0gFK6cOPKZBUA4YTRQ+7HiqRyc6A6pvmlUW+VzIxduOVI9omHdslHdUMRABcAEtuQEcBd27tSq8maoxIbE7enbPYGgJ4QhBCqGv1214iwqLJlq1LWp+7YWwzg394QjzwP9AMn9vHx8m+sK/r2iiZnfHpqurwnAAAIBAwGvRLEjop+vyzh09VfZGQeLqWU6nv6PM2RzNzU1HJzckR8SuDEaF1c/Az2vh5syRlqxbm8PGl22o6Rqdu+WhYQMMy79yRPDGBrOIZcbcHVxZ+v3RConl4NmyidBAxAeVy7fhsNLXdRcjpf1lBZ4RcTPdl3wABsEFYA+p1p+3VndZX7k775sg0AcouqUVlzC3UtXWAIAx9//24vP7+28+d17QMKYIPgAbTPjE047hsUfGHW/Ll33GVierPNBAHDwFul6p61ZGlV1tHc3dq8P2/Ym+CpHwAEgHySevwbVnNj1uW/sv/JSElkMzcuMTTXnb2wM3VDHABvAMI+sQMBYINgAMhEIuHLK5Z/Ms3QefWoobMye/682HAAnvaSU0qfvAwHyp75zeg5wH/MzdvLITf70gAAAABJRU5ErkJggg==",
	Fail	: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAcIAAAHCABzQ+bngAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAASySURBVFiF7ZZZbJRVGIaf88+UmU7L0NLFloKyFNBCsYGmlJaALF4IRgmRJaEiuBBiDIhRMDExXACJgXChRgPiAokElURIDCl7wZSySICEtFilDAJ2o4udmc60M/+8XlCNkeK0XMgNX3LyX5yT8z15v/N9/2sk8SDDeqDZHwI8BHgIADj7etCA6/iuV5/y+hpWeWPBaY5YjA65TnRkpX/01otbK855s7ruB8D0ZRD9/MHM5SOvNC1NuNpaqNuh5FBnRBhwexKMlZEYYEzqT7dGZ+zKeafiy34TSLrnqlj8XHbbgvHlmpSmC25La0FTQU+AngTNBr0HuuyxpJJ0NT87uvzb4knZ/3Xnv9c9N3ZMKhzakZlW057o1OsgFygJo3zL0kzQ06BC0DDQUNB6UMSToJbBg6o/zM3N6StAryUwtRetaxOnHnEGgzOWACeB6cCsIUNw+f0E/X5iQCegnm8NMAHYbOCqy31s/LbNs7X0jfj17Y2q3JO4vM4YvQAyoPdLSuTbs0cte/fqwJQp2gLaBjpcUKBr69erYcsWHSuerNmgdaA6Y7TdNWDZfZUgz+t1HTKmcjtoEGiOM0Ff5+cr7PNJkvxnzuhkaqqqc3NlX74sSQrW1GhTdpaeB40AfQ86bFmVZGa64gHcNQeeCYdnhKSCfUAGUDLIS1J9PWfmzSPS1kpyURFT165l7IrXsMaNo7uxkW/mzuVSfQMG8AKnAa9U8LLfPyNeBe4CkG2v8YHnKpBjDKldXXiCQQbXVBPavfvOG1m5EuulZSgWo3LNaprq6vBYFjaQBlwHIpLn0Wh0Tb8B2qUZvwIdPe8jGgiQHA4zZtYskuvrif5SSywlBTszk6adO7H37Sc5M4MuoIs7k60FCAHpsVj/FWgEEwC6gfYeEMvhgGgUq7mJSCRKVzgMkQgpo0aSkpJKUyBIwBhSvV6iDgd+IAB0S6bfAM1SRSfgBsKAH2izbc4dPoK/YCLOvDx+//QTWioqcE2bjvvN1Vzt7GRU5iOMHTyYVglnjxp1UsX9KLA1CTpHAFHgNlAucWFyMQllS7BOV1G1YSNHN26A366TV1bGvEWLKPUOpDEY5EYsRhbQDJ3HjdkaD+DuvnTgXghV63omXBFoQXqa6k9VSlWntH/xIpWBFoLOv7tOam6WQiF9UVSkkT2tuwm0CqqwLHe8Nrzrb6iowrnG7BgLxcXAAWB+aSn+S5fwXbxAZflBhrkGMHaAixuHDmGlpKKcHOqHD6fu7FnmAzHgJOyQbYfjCdD7KDbGmmY4ttrpnP6DxLGozQggF3jc7WaYy4WV4KQ2anOmvZ3L3Gm9mQ4H84xhj22f+FGaKSkWD6BXPyApZowpy7DtoytyM8ZkOGy+q2khAjSFw3SFwwSAVuAmIIfh7dLhjLsZ4ONrt2vPSmV9SX5PBf6hRE6hy/pq+WMDZ6eMSKLaePFdaaehvQNbUTwDLEaO8jIhK5Fgm8VnZ28dqQ51L5N0qy/J4wL8FUnGvDIt1bk0v3D0pNEZQ5MSW+uJ2m2EIjZNbd3B077A+fI/undJ+ryvif+OPhsHSATmDISDoyCSDZE0OAjMARL7Y0Li+oH/Mx64K34I8CeySkjFt1kdMAAAAABJRU5ErkJggg==",
	SelectedItem : 0,
	SelectedType : 0,
	NextLevel : 0,
	MasterTokens : [],
	OtherTokens : [],
	FORGED_TOKEN_LEVELS : {},
	MAX_EFFECTS : 5,
	PreviewCardScale : 0.9,
	PreviewPreset : 0,
	PreviewCards : {},
	InitialCards : {},
	PopCards : {},
	popChamp:null,
	popuppos:{x: -999, y: -999},
	NextPresetNumber : 100,
	UnequipQueue : [],
	EquipQueue : [],
	ErrorQueue : [],
	PresetNameChanged : false,
	PresetTargetChanged : false,
	PresetTimer : null,
	PresetBusy : false,
	ChampEffects : [],
	SearchResults : [],
	TotalRules: 0,
	EditRuleNumber : -1,
	SalvageItems : [],
	SalvageStatus : '',
	UpgradeStatus : '',
	UpgradeReturnStatus : '',
	RepairStatus : '',
	serverwait : false,
	SpeedupItemList : [1, 2, 3, 4, 5, 6, 7, 8],
	SpeedupItemTrans : ["SH","KH","GH","MH","AH","RH","DH","EH"],
	Squire:0,
	Knight:0,
	Guinevere:0,
	Morgana:0,
	Arthur:0,
	Merlin:0,
	Divine:0,
	Epic:0,
	LessMetallurgy:0,
	Metallurgy:0,
	Journeyman:0,
	Smith:0,
	Expert:0,
	EnhanceItemList : [21001,21002],
	EnhanceItemTrans : ["LOM","GOM"],
	UpgradeItemList : [21051,21052,21058],
	UpgradeItemTrans : ["JST","ST","EST"],
	GemUseTripSwitch:false,
	UpgradeQueueIndex:0,
	BreakInProgress:false,
	BreakQueue:[],
	BreakMight:0,
	BreakTotal:0,
	BreakCounter:0,
	EnhanceCost:{},
	UpgradeCost:{},
	AdvancedStatsGrid : {
	"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:1,205:0,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:1,114:1,115:0,116:0,117:0,118:0,119:1,120:1,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:1,205:0,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:1,118:1,119:0,120:0,121:0,122:0,123:1,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},
					3: {201:0,202:0,203:0,204:1,205:0,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:1,116:1,117:0,118:0,119:0,120:0,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},
					4: {201:0,202:0,203:0,204:1,205:0,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:1,114:1,115:0,116:1,117:1,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: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: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}},
	"pendant" :		{1: {201:0,202:1,203:1,204:1,205:0,206:1,207:1,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:1,203:1,204:1,205:0,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:1,203:1,204:1,205:0,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: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: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},
					4: {201:0,202:1,203:1,204:1,205:0,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:1,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: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: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: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}},
	},

	Options: {
		Stats : {
			EnhanceSuccess : {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}},
			EnhanceFail : {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}},
			UpgradeSuccess : {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}},
			UpgradeFail : {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}},
		},
		DefaultNextToken : false,
		safetyOn: true,
		safetyLimit: 50000,
		removeMastersTokens: false,
		NoEquippedSalvage: true,
		NoMassSalvage: true,
		SalvageSafety: false,
		SalvageSafetyNum: 100,
		SalvageRunning : false,
		UpgradeRunning : false,
		RepairRunning : false,
		LocalPresets : {},
		ToggleButton : true,
		SalvageRuleSet : [],
		SalvageKeepFirst : 40,
		SalvageMaxQuality : 3,
		SalvageCityNum : 0,
		SalvageMaxAether : 2000000,
		SalvageAnyCity : true,
		SalvageOverflow : "order",
		SalvageQueue : [],
		NumSalvaged : 0,
		AetherSalvaged : 0,
		SalvageStartDate : 0,
		SalvageSortColNum : 0,
		SalvageSortDir : 1,
		UpgradeCityNum : 0,
		UpgradeMinAether : 50000,
		UpgradeAnyCity : true,
		UpgradeOverflow : "order",
		UseEH: false,
		UseDH: false,
		UseRH: false,
		UseAH: false,
		UseMH: false,
		UseGH: false,
		UseKH: false,
		UseSH: false,
		UseOverride: false,
		OverrideSpeedup: 0,
		OverrideHours: 0,
		OverrideMinutes: 1,
		UpgradeOneItem: false,
		UpgradeOneMax: false,
		UpgradeOneMaxAttempts: 100,
		UpgradeInterval: 10,
		WhisperToMe: false,
		SendToInbox: true,
		RepairSpeedupMinQuality : 0,
		RepairSpeedupMinLevel : 1,
		UseLOM: false,
		UseGOM: false,
		UseJST: false,
		UseST: false,
		UseEST: false,
		EnhanceBoostMinQuality : 5,
		EnhanceUseMasters : false,
		EnhanceUseMastersMin : 0,
		EnhanceUseMastersMax : 5,
		EnhanceUseMasters : false,
		EnhanceNoBoosts : false,
		EnhanceBoostLevelOnly : true,
		UpgradeBoostMinLevel : 7,
		UpgradeUseMasters : false,
		UpgradeUseMastersMin : 4,
		UpgradeUseMastersMax : 28,
		UpgradeNoBoosts : false,
		UpgradeBoostLevelOnly : true,
		UpgradeDefaultQuality : 5,
		UpgradeDefaultLevel : 28,
		ChatPostShowMight : true,
		UpgradeQueue : [],
		RepairQueue : [],
		SalvageUpgradeAuto : false,
		BreakIgnorePreset : true,
		BreakMaxMight : 0,
		BreakMinLevel : 0,
		BreakMaxLevel : 28,
		BreakRepairAuto : true,
		SearchMenu : false,
	},

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

		if (uW.isNewServer()) {
			if (GlobalOptions.btPowerBar) {
				var elem = ById("bttcChamp");
				elem.setAttribute("style","display:none");
			}
			return;
		}
		
		if (parseFloat(Version) < parseFloat(t.MinVersion)) {
			div.innerHTML = '<center>'+tx('Minimum script version for Champ tab is '+t.MinVersion)+'</center>';
			actionLog('Minimum script version for Champ tab is '+t.MinVersion,'CHAMP');
			return;
		}

		if (!Options.ChampOptions) {
			Options.ChampOptions = t.Options;
		}
		else {
			for (var y in t.Options) {
				if (!Options.ChampOptions.hasOwnProperty(y)) {
					Options.ChampOptions[y] = t.Options[y];
				}
			}
		}

		// check cities still exist

		if (Options.ChampOptions.SalvageCityNum > Seed.cities.length-1 ) { Options.ChampOptions.SalvageCityNum = 0; }
		if (Options.ChampOptions.UpgradeCityNum > Seed.cities.length-1 ) { Options.ChampOptions.UpgradeCityNum = 0; }

		// modify loaded rules to include functions

		var RuleLength = Options.ChampOptions.SalvageRuleSet.length;
		for (var k=0;k<RuleLength;k++) {
			var r = Options.ChampOptions.SalvageRuleSet[k];
			var rule = new t.ChampRule(r.type, r.faction, r.conditions, r.advancedrule);
			for (var j in rule.conditions) {
				rule.conditions[j].ChampCheckCondition = t.ChampCheckCondition;
			}
			Options.ChampOptions.SalvageRuleSet[k] = rule;
		}

		if (Options.ChampOptions.ToggleButton) {
			AddMainTabLink(tx('CHAMP'), 'PBPChampButton', function () { ById('bttcChamp').click(); });
		}

		t.MaxItems = CM.WorldSettings.getSettingAsNumber("CE_INVENTORY_HARDLIMIT");

		t.MAX_EFFECTS = CM.CHAMPION.MAX_EFFECTS;

		t.FORGED_TOKEN_LEVELS = {};
		var Obj = CM.WorldSettings.getSettingAsObject("CE_UPGRADE_ITEM_MAP");
		for (var k in Obj) {
			if (Obj[k] && Obj[k].Buff && parseIntNan(Obj[k].Buff)<0) {
				t.FORGED_TOKEN_LEVELS[k] = parseIntNan(Obj[k].Buff)*(-1);
			}
		}

		t.ChampEffects = [];
		var effectTiers = CE_EFFECT_TIERS;
		for (var k in effectTiers) {
			var effsplit=effectTiers[k]["Id_Tier"].split(",");
			if (t.ChampEffects.indexOf(effsplit[0]) < 0) t.ChampEffects.push(effsplit[0]);
		}

		t.EnhanceCost = CM.WorldSettings.getSettingAsObject("CE_ENHANCE_AETHERSTONE_MAP");
		t.UpgradeCost = CM.WorldSettings.getSettingAsObject("CE_UPGRADE_AETHERSTONE_MAP");

		CM.ChampionPanelView.restartRepairQueue(); // need to do this to create Seed.queue_champion FFS!

		// load logs

		var a = JSON2.parse(GM_getValue ('ChampSuccessLog_'+getServerId()+'_'+uW.tvuid, '[]'));
		if (matTypeof(a) == 'array'){
			t.SuccessLog = a;
		}
		var a = JSON2.parse(GM_getValue ('ChampRepairLog_'+getServerId()+'_'+uW.tvuid, '[]'));
		if (matTypeof(a) == 'array'){
			t.RepairLog = a;
		}
		var a = JSON2.parse(GM_getValue ('ChampSalvageLog_'+getServerId()+'_'+uW.tvuid, '[]'));
		if (matTypeof(a) == 'array'){
			t.SalvageLog = a;
		}
		var a = JSON2.parse(GM_getValue ('ChampEventLog_'+getServerId()+'_'+uW.tvuid, '[]'));
		if (matTypeof(a) == 'array'){
			t.EventLog = a;
		}

		uWExportFunction('btFetchChampion', function(uid,name,ChampId,ChampName) {
			if (uid==uW.tvuid) name = '';
			Tabs.Champ.FetchChampion(uid,name,ChampId,ChampName,Tabs.Champ.ViewChampCards);
		});

		uWExportFunction('btchampSelectAllSearchEffect', Tabs.Champ.SelectAllSearchEffect);
		uWExportFunction('btchampSelectNoneSearchEffect', Tabs.Champ.SelectNoneSearchEffect);
		uWExportFunction('btchampSelectAllSearchType', Tabs.Champ.SelectAllSearchType);
		uWExportFunction('btchampSelectNoneSearchType', Tabs.Champ.SelectNoneSearchType);
		uWExportFunction('btchampSelectAllSearchQuality', Tabs.Champ.SelectAllSearchQuality);
		uWExportFunction('btchampSelectNoneSearchQuality', Tabs.Champ.SelectNoneSearchQuality);
		uWExportFunction('btchampSelectAllSearchLevel', Tabs.Champ.SelectAllSearchLevel);
		uWExportFunction('btchampSelectNoneSearchLevel', Tabs.Champ.SelectNoneSearchLevel);
		uWExportFunction('btchampSelectAllSearchFaction', Tabs.Champ.SelectAllSearchFaction);
		uWExportFunction('btchampSelectNoneSearchFaction', Tabs.Champ.SelectNoneSearchFaction);

		uWExportFunction('btchampSalvageClickSort', Tabs.Champ.SalvageClickSort);
		uWExportFunction ('btchampSalvageEditRule', Tabs.Champ.SalvageEditRule);
		uWExportFunction ('btchampSalvageDeleteRule', Tabs.Champ.SalvageDeleteRule);

		uWExportFunction('btchamppaintTags', Tabs.Champ.paintTags);
		uWExportFunction('btchampModifyEvents', Tabs.Champ.ModifyChampEvents);
		uWExportFunction('btchamprepairSpeedup',Tabs.Champ.SpeedupRepair);
		uWExportFunction('cancelChampRepair', Tabs.Champ.CancelRepair);

		uWExportFunction('btChampQueueUp', Tabs.Champ.ChampQueueUp);
		uWExportFunction('btChampQueueDn', Tabs.Champ.ChampQueueDn);
		uWExportFunction('btChampQueueMaxChange', Tabs.Champ.ChampQueueMaxChange);
		uWExportFunction('btChampQueueDeleteAll', Tabs.Champ.deleteChampQueueAll);
		uWExportFunction('btChampQueueDelete', Tabs.Champ.deleteChampQueue);

		uWExportFunction('btChampRepairQueueUp', Tabs.Champ.ChampRepairQueueUp);
		uWExportFunction('btChampRepairQueueDn', Tabs.Champ.ChampRepairQueueDn);
		uWExportFunction('btChampRepairQueueDeleteAll', Tabs.Champ.deleteChampRepairQueueAll);
		uWExportFunction('btChampRepairQueueDelete', Tabs.Champ.deleteChampRepairQueue);

		// champ hall display hooks

		function addPostChamp() {
			var button_sizes = '65px';
			var assign_button = document.getElementsByClassName('assign_city')[0];
			if (assign_button) {
				assign_button.style.width = button_sizes;
				assign_button.className += ' divNoWrap';
				assign_button.parentElement.className += ' divNoWrap';

				if (!ById('btchampPostChamp')) {
					var post_button = document.createElement('div');
					post_button.className = 'buttonv2 blue divNoWrap';
					post_button.innerHTML = tx('Post');
					post_button.id = 'btchampPostChamp';
					post_button.style.width = button_sizes;
					assign_button.parentElement.appendChild(post_button);
					post_button.addEventListener('click', function () {
						var champDiv = document.getElementsByClassName('name active')[0];
						var champClass = champDiv.className;
						var champIndex = parseInt(champClass.replace(' name active', '').replace('name', ''));
						t.PostChampSlot(champIndex+1);
					}, false);
				}
			}
		}

//		var oldOpen = CM.ChampionModalController.open;
//		var newOpen = function (j) {
//			oldOpen(j);
//		}
//		if (typeof exportFunction == 'function') { exportFunction(newOpen,CM.ChampionModalController, {defineAs:"open"}); }
//		else { CM.ChampionModalController.open = newOpen; };

		var oldRenderFilteredItems = CM.ChampionModalView.renderFilteredItems;
		var newRenderFilteredItems = function () {
			oldRenderFilteredItems();
			t.ModifyChampEvents();
			t.paintTags();
		}
		if (typeof exportFunction == 'function') { exportFunction(newRenderFilteredItems,CM.ChampionModalView, {defineAs:"renderFilteredItems"}); }
		else { CM.ChampionModalView.renderFilteredItems = newRenderFilteredItems; };

		var oldRender = CM.ChampionModalView.render;
		var newRender = function (ab,aa) {
			oldRender(ab,aa);
			addPostChamp();
			t.ModifyChampEvents();
			t.paintTags();
		};
		if (typeof exportFunction == 'function') { exportFunction(newRender,CM.ChampionModalView, {defineAs:"render"}); }
		else { CM.ChampionModalView.render = newRender; };

		var oldRenderUpgEnh = CM.ChampionModalView.renderUpgEnh;
		var newRenderUpgEnh = function (ag, aa) {
			oldRenderUpgEnh(ag, aa);

			Tabs.Champ.SelectedItem = ag;  //this is the champ item ID
			Tabs.Champ.NextLevel = uW.kocChampionItems[ag].level + 1;

			ById('upgEnhStatsTarget').removeEventListener("click", Tabs.Champ.showNextChampLevel);
			var Locked = document.getElementById('chLockedStatIcon');
			if (Locked != null) return;
			ById('upgEnhStatsTarget').addEventListener("click", Tabs.Champ.showNextChampLevel);

			var champUpgTab = ById('champUpgTab');
			var champEnhTab = ById('champEnhTab');
			if (!champUpgTab || !champEnhTab) return;

			var champDisableUpgradeButton = function () {
				// change the appearance
				var container = document.querySelector('#upgEnhBody');
				jQuery(container).children("div.gemButtonv2").remove();
				var an = jQuery("<div/>");
				an.addClass("upgEnhButton gemButtonv2 gray");
				an.html(tx("Low Aether"));
				jQuery(container).append(an);
			}

			var champCheckAstoneLevel = function () {
				// check limit
				var stones = parseInt(Seed.resources["city" + uW.currentcityid]["rec5"][0]);
				if (stones < Options.ChampOptions.safetyLimit || isNaN(stones) ) {
					champDisableUpgradeButton();
					return false;
				} else {
					return true;
				}
			}

			var champSafetyCheck = function () {
				if (champCheckAstoneLevel()) { // see if we have enough a-stone
					jQuery("#upgEnhButton").click(function () { // every time the button is pushed, check the levels
						champCheckAstoneLevel();
					});
				}
			}

			var autoSelectForged = function() {
				var ChampID = 0;
				ChampID = Tabs.Champ.SelectedItem;

				var champItem = uW.kocChampionItems[ChampID];
				var nextForgedID = parseIntNan(Tabs.Champ.getNextAvailableForged(champItem));
				if (nextForgedID != 0) {
					var selected_index = 0;

					jQuery(document.querySelector("#upgEnhBuffSelect")).children("option").each(function () {
						if ( jQuery(this).text() == uW.ksoItems[nextForgedID].name ) {
							selected_index = jQuery(this).val();
							return false;
						}
					});
					jQuery('#upgEnhBuffSelect').val(selected_index).change();
					CM.ChampionModalView.renderCosts();
					CM.ChampionUpgEnhManager.calcCosts();
					if (selected_index > 0) {
						var upgEnhCostNum = document.getElementsByClassName('upgEnhCostNum')[1];
						jQuery(upgEnhCostNum).text(uW.ksoItems[nextForgedID].count + "/1");
						jQuery(upgEnhCostNum).css('opacity', 1);
						var upgEnhCostIconItem = ById('upgEnhCostIconItem');
						upgEnhCostIconItem.className = 'upgEnhCostIcon i' + nextForgedID;
					}
				}
			}

			var clearForgedTokens = function () {
				// remove options for tokens
				var removeItems = [];
				for (var tk in t.FORGED_TOKEN_LEVELS) { removeItems.push(uW.ksoItems[tk].name); }

				jQuery(document.querySelector("#upgEnhBuffSelect")).children("option").each(function () {
					if (jQuery.inArray(jQuery(this).text(), removeItems) > -1) jQuery(this).remove();
				});
			}

			if ((champUpgTab.className == 'upgEnhTab active')) {
				if (Options.ChampOptions.DefaultNextToken) autoSelectForged();
				if (Options.ChampOptions.removeMastersTokens && !Options.ChampOptions.DefaultNextToken) clearForgedTokens();
			}
			if ((champUpgTab.className == 'upgEnhTab active') || (champEnhTab.className == 'upgEnhTab active')) {
				if (Options.ChampOptions.safetyOn) { champSafetyCheck(); }
			}
		}
		if (typeof exportFunction == 'function') { exportFunction(newRenderUpgEnh,CM.ChampionModalView, {defineAs:"renderUpgEnh"}); }
		else { CM.ChampionModalView.renderUpgEnh = newRenderUpgEnh; };

		if (GlobalOptions.btWinSize.x == 750) { t.PreviewCardScale = 0.70;}
		if (GlobalOptions.btWinSize.x == 1250) { t.PreviewCardScale = 1.0;}

		// adjust styles...

		var styles = '\
					.divNoWrap {white-space: nowrap; display:inline-block;}\
					#itemInventory {width:460px; min-height: 490px; background-color:#884422;}'; //this expands the height of the champion hall inventory space

		styles += 'div#contextMenuPBP { position:absolute; z-index:1000000; padding:2px 2px 0; background-color:#c69f78; border:2px solid transparent; border-top-color:#ffffde; border-right-color:#87603c; border-bottom-color:#623f20; border-left-color:#ffecc9; overflow: hidden; } \
					div#contextMenuPBP div.title { font:bold 12px Georgia; color:#3f2300; text-transform: capitalize; text-align:center; } \
					div#contextMenuPBP div.title span.type, div #contextMenuPBP div.title span.level { display:block; text-transform:capitalize; text-align:center; } \
					div#contextMenuPBP div.body { text-align:center; } \
					div#contextMenuPBP a { display:block; margin-bottom:2px; } \
					div#contextMenuPBP ul { padding:0; margin:0; list-style:none; }';

		styles += 'div.btchampHammer { background-image: url('+ t.Hammer +'); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 32px; height: 32px; margin: 2px; vertical-align: middle;}';
		styles += 'div.btchampBroken { background-image: url('+ t.Fail + '); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 32px; height: 32px; margin: 2px; vertical-align: middle;}';
		styles += 'div.btchampSuccess { background-image: url('+ t.Tick +'); background-repeat: no-repeat; background-color: transparent; display: inline-block; width: 32px; height: 32px; margin: 2px; vertical-align: middle;}';
		styles += 'div.btchampGoButton { background-image: url('+ t.Button +'); background-repeat: no-repeat; background-color: transparent; display=inline-block; width: 32px; height: 32px; margin: 2px; vertical-align: middle;}';

		styles += '#PBPChampContextMenu #contextMenu { z-index:1000; }';
		styles += '#PBPChampContextMenu .context_menu_title { padding:6px;width:110px;font-weight: bold; }';
		styles += '#PBPChampContextMenu #contextMenu .buttonv2 { padding:6px;width:110px; }';

		var m = '<STYLE>'+ styles +'</style><DIV class=divHeader align=center>'+tx('CHAMPION HALL MANAGEMENT')+'</div>';
		m += '<div id=btChampMenu style="width:'+GlobalOptions.btWinSize.x+'px;"><ul>';
		m += '<li><a href="#btChamp_container_Overview" id=btChamp_Overview style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Overview')+'</a></li>';
		m += '<li><a href="#btChamp_container_Upgrader" id=btChamp_Upgrader style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Enhance/Upgrade')+'</a></li>';
		m += '<li><a href="#btChamp_container_Repairer" id=btChamp_Repairer style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Break/Repair')+'</a></li>';
		m += '<li><a href="#btChamp_container_Salvager" id=btChamp_Salvager style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Salvage')+'</a></li>';
		m += '<li><a href="#btChamp_container_Presets" id=btChamp_Presets style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Champions')+'</a></li>';
		m += '<li><a href="#btChamp_container_Compare" id=btChamp_Compare style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Compare')+'</a></li>';
		m += '<li><a href="#btChamp_container_Options" id=btChamp_Options style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Options')+'</a></li>';
		m += '<li><a href="#btChamp_container_Log" id=btChamp_Log style="background-color:'+Options.Colors.Panel+';color:'+Options.Colors.PanelText+';">'+tx('Log')+'</a></li>';
		m += '</ul>';

		// overview

		m += '<DIV id=btChamp_container_Overview style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Overview style="width:100%;overflow-x:auto;min-height:500px;max-height:600px;overflow-y:auto;">';
		m += '</DIV></DIV>';

		// upgrade

		m += '<DIV id=btChamp_container_Upgrader style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Upgrader style="width:100%;overflow-x:auto;min-height:600px;overflow-y:auto;">';
		m += '</DIV></DIV>';

		// repair

		m += '<DIV id=btChamp_container_Repairer style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Repairer style="width:100%;overflow-x:auto;min-height:600px;overflow-y:auto;">';
		m += '</DIV></DIV>';

		// salvage

		m += '<DIV id=btChamp_container_Salvager style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Salvager>';
		m += '</DIV></DIV>';

		// compare

		m += '<DIV id=btChamp_container_Compare style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Compare style="width:100%;overflow-x:auto;min-height:500px;max-height:600px;overflow-y:auto;">';
		m += '</DIV></DIV>';

		// presets

		m += '<DIV id=btChamp_container_Presets style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Presets style="width:100%;overflow-x:auto;min-height:600px;overflow-y:auto;">';
		m += '</DIV></DIV>';

		// options

		m += '<DIV id=btChamp_container_Options style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Options style="width:100%;overflow-x:auto;min-height:500px;max-height:600px;overflow-y:auto;">&nbsp;</DIV></DIV>';

		// log

		m += '<DIV id=btChamp_container_Log style="color:'+Options.Colors.PanelText+';padding-left:4px;padding-bottom:0px;width:'+(parseInt(GlobalOptions.btWinSize.x)-4)+'px;">';
		m += '<DIV align=center id=btChampDiv_Log style="width:100%;overflow-x:auto;min-height:500px;max-height:600px;overflow-y:auto;">&nbsp;</DIV></DIV>';

		m += '</DIV><br>';

		t.myDiv.innerHTML = m;
		jQuery("#btChampMenu").tabs({ activate: function (event, ui) { ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x); } });

		$("btChamp_Overview").addEventListener('click', t.display_overview, false);
		$("btChamp_Upgrader").addEventListener('click', t.display_upgrader, false);
		$("btChamp_Repairer").addEventListener('click', t.display_repairer, false);
		$("btChamp_Salvager").addEventListener('click', t.display_salvager, false);
		$("btChamp_Compare").addEventListener('click', t.display_compare, false);
		$("btChamp_Presets").addEventListener('click', t.display_presets, false);
		$("btChamp_Options").addEventListener('click', t.display_options, false);
		$("btChamp_Log").addEventListener('click', t.display_log, false);
		$("btChamp_Overview").click();

		// paint any static tabs

		t.paint_upgrader();
		t.paint_repairer();
		t.paint_salvager();
		t.paint_compare();
		t.paint_presets();

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

		t.UpgradeStatus = tx('Powered Off');
		t.RepairStatus = tx('Powered Off');
		t.SalvageStatus = tx('Powered Off');

		// start auto loop timers to start in 15 seconds...
		if (Options.ChampOptions.UpgradeRunning) {
			t.UpgradeStatus = tx('Waiting to start')+'...';
			t.UpgradeTimer = setTimeout(function () { t.doAutoUpgradeLoop();}, (14 * 1000));
		}
		if (Options.ChampOptions.RepairRunning) {
			t.RepairStatus = tx('Waiting to start')+'...';
			t.RepairTimer = setTimeout(function () { t.doAutoRepairLoop();}, (15 * 1000));
		}
		if (Options.ChampOptions.SalvageRunning) {
			t.SalvageStatus = tx('Waiting to start')+'...';
			t.SalvageTimer = setTimeout(function () { t.doAutoSalvageLoop();}, (16 * 1000));
		}
	},

	onUnload : function (){
		var t = Tabs.Champ;
		if (uW.btLoaded) {
			if (!ResetAll) t.saveLogs();
		}
	},

	CheckChampActive : function () {
		if(!ById('itemInventory')) {
			CM.ChampionModalController.open();
		}
	},

	SubChampContextMenu : function (el,menutype,chId, container) {
		var t = Tabs.Champ;
		if (ById('contextMenuPBP')) return;
		var e = document.createElement ('div');
		e.id = 'contextMenuPBP';
		if (menutype == 'STATS') {
			// create a button to copy the stats
			var btn = document.createElement('a');
			jQuery(btn).addClass("buttonv2 h20 blue")
			.html(tx("Copy Stats"))
			.css('color', 'white')
			.bind("click", function () {
				var displayText = Tabs.Champ.getChampItemStats(chId, "	");
				if (displayText != "") window.prompt("Copy to clipboard: Ctrl+C", displayText);
				jQuery("#contextMenuPBP").remove();
			});
			e.appendChild(btn);

			// create a button to post the stats
			var btn = document.createElement('a');
			jQuery(btn).addClass("buttonv2 h20 blue")
			.html(tx("Post to Chat"))
			.css('color', 'white')
			.bind("click", function () {
				var displayText = Tabs.Champ.getChampItemStats(chId, "||");
				if (displayText != "") sendChat(displayText);
				jQuery("#contextMenuPBP").remove();
			});
			e.appendChild(btn);
		}
		if (menutype == 'AUTO') {
			// enhance
			var btn = document.createElement('a');
			jQuery(btn).addClass("buttonv2 h20 brown")
			.html(tx("Enhance"))
			.css('color', 'white')
			.bind("click", function () {
				t.addChampQueue(chId,'enhance',Options.ChampOptions.UpgradeDefaultQuality);
				jQuery("#contextMenuPBP").remove();
			});
			e.appendChild(btn);
			// upgrade
			var btn = document.createElement('a');
			jQuery(btn).addClass("buttonv2 h20 brown")
			.html(tx("Upgrade"))
			.css('color', 'white')
			.bind("click", function () {
				t.addChampQueue(chId,'upgrade',Options.ChampOptions.UpgradeDefaultLevel);
				jQuery("#contextMenuPBP").remove();
			});
			e.appendChild(btn);
			// repair
			var champItem = uW.kocChampionItems[chId];
			if (champItem) {
				if (Tabs.Reference.isBroken(champItem)) {
					var btn = document.createElement('a');
					jQuery(btn).addClass("buttonv2 h20 blue")
					.html(tx("Repair"))
					.css('color', 'white')
					.bind("click", function () {
						t.addChampRepairQueue(chId);
						jQuery("#contextMenuPBP").remove();
					});
					e.appendChild(btn);
				}
				else {
					if (champItem.level<CM.CHAMPION.MAX_LEVELS) {
						var btn = document.createElement('a');
						jQuery(btn).addClass("buttonv2 h20 red")
						.html(tx("Break"))
						.css('color', 'white')
						.bind("click", function () {
							t.UpgradeItem(chId,null,0);
							jQuery("#contextMenuPBP").remove();
						});
						e.appendChild(btn);
					}
				}
			}
		}
		var off = getAbsoluteOffsets(el);
		if (container) {
			e.style.top = off.top+'px';
			e.style.left = (off.left+jQuery('#contextMenu').width()-4)+'px';
		}
		else {
			e.style.top = (off.top+WideScreen.OffsetTop+4)+'px';
			e.style.left = (off.left+WideScreen.PowerBarWidth+jQuery('#contextMenu').width()+24)+'px';
		}
		jQuery(e).mouseover(function (m) {
			m.stopPropagation();
		});
		jQuery(e).mouseleave(function (m) {
			m.stopPropagation();
			jQuery("#contextMenuPBP").remove();
		});
		jQuery('#contextMenu').mouseleave(function (m) {
			if(!m && window.event)m=event;
			var goingto=m.relatedTarget|| event.toElement;
			if (goingto.id != "contextMenuPBP" && goingto.parentNode.id != "contextMenuPBP") {
				jQuery("#contextMenuPBP").remove();
			}
		});

		if (container) container.appendChild (e);
		else ById('mainbody').appendChild (e);
	},

	getNextAvailableForged : function (champItem,LevelOnly) {
		var t = Tabs.Champ;
		var curCode = 0;
		for (var tk in t.FORGED_TOKEN_LEVELS) {
			if (LevelOnly) {
				if (champItem.level==t.FORGED_TOKEN_LEVELS[tk]-1 && uW.ksoItems[tk].count > 0) {
					curCode = tk;
					break;
				}
			}
			else {
				if (champItem.level<t.FORGED_TOKEN_LEVELS[tk] && uW.ksoItems[tk].count > 0) {
					curCode = tk;
					break;
				}
			}
		}
		return curCode;
	},

	ModifyChampEvents: function () {
		var t = Tabs.Champ;

		jQuery(".champItem").click(function () { Tabs.Champ.DoChampContextMenu(jQuery(this)[0].id); });

		jQuery(".shield").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".weapon").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".chestArmor").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".helmet").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".feet").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".cloak").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".ring1").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".ring2").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });
		jQuery(".pendant").click(function () { Tabs.Champ.CustomChampContextMenu(jQuery(this).attr('hover_id'), getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,document.getElementsByClassName("cmModalContainer")[0]); });

	},

	DoChampContextMenu : function (id, fullmenu, container, FromSearch) {
		var t = Tabs.Champ;
		var champ_item = uW.kocChampionItems[id];
		if (!champ_item) return;

		if (fullmenu) {
			if (Tabs.Reference.isBroken(champ_item)) {
				var btn4 = document.createElement('a');
				jQuery(btn4).addClass("buttonv2 blue box").html(uW.g_js_strings.throneRoom.button_repair).css('color', 'white').bind("click", function () {
					jQuery("#contextMenu").remove();
					t.CheckChampActive();
					CM.ChampionPanelView.renderBroken(champ_item);
				});
				jQuery("#contextMenu div.context_menu_title").after(btn4);
			}
			else {
				var btn4 = document.createElement('a');
				jQuery(btn4).addClass("buttonv2 red box").html(uW.g_js_strings.mass_salvage.title).css('color', 'white').bind("click", function () {
					jQuery("#contextMenu").remove();
					t.CheckChampActive();
					CM.ChampionModalView.renderMassSalvage();
				});
				jQuery("#contextMenu div.context_menu_title").after(btn4);

				var btn4 = document.createElement('a');
				jQuery(btn4).addClass("buttonv2 red box").html(uW.g_js_strings.commonstr.salvage).css('color', 'white').bind("click", function () {
					jQuery("#contextMenu").remove();
					t.CheckChampActive();
					CM.ChampionPanelView.renderMassSalvageConfirm({1:uW.kocChampionItems[id]});
				});
				jQuery("#contextMenu div.context_menu_title").after(btn4);

				var btn4 = document.createElement('a');
				jQuery(btn4).addClass("buttonv2 brown box").html(uW.g_js_strings.commonstr.upgrade).css('color', 'white').bind("click", function () {
					jQuery("#contextMenu").remove();
					t.CheckChampActive();
					CM.ChampionModalView.upgEnhSlideIn(id, "upg");
				});
				jQuery("#contextMenu div.context_menu_title").after(btn4);

				var btn4 = document.createElement('a');
				jQuery(btn4).addClass("buttonv2 brown box").html(uW.g_js_strings.commonstr.enhance).css('color', 'white').bind("click", function () {
					jQuery("#contextMenu").remove();
					t.CheckChampActive();
					CM.ChampionModalView.upgEnhSlideIn(id, "enh");
				});
				jQuery("#contextMenu div.context_menu_title").after(btn4);

				var btn4 = document.createElement('a');
				if (champ_item.equippedTo) {
					jQuery(btn4).addClass("buttonv2 blue box").html(uW.g_js_strings.commonstr.unequip).css('color', 'white').bind("click", function () {
						jQuery("#contextMenu").remove();
						CM.ChampionManager.unequipItem(id);
					});
				}
				else {
					jQuery(btn4).addClass("buttonv2 blue box").html(uW.g_js_strings.commonstr.equip).css('color', 'white').bind("click", function () {
						jQuery("#contextMenu").remove();
						CM.ChampionManager.equipItem(id);
					});
				}
				jQuery("#contextMenu div.context_menu_title").after(btn4);
			}
		}
		else {
			var menuDiv = ById('contextMenu');
			var Equip = ById(id);
			menuDiv.style.left = getAbsoluteOffsets(Equip).left + "px";
			menuDiv.style.top = getAbsoluteOffsets(Equip).top + "px";
		}

		// add selection button and submenus

		btn = document.createElement('a');
		jQuery(btn).addClass("buttonv2 blue box").html('<table width=100% cellpadding=0 cellspacing=0 class=xtab style="padding-right:0px;"><tr><td style="width:13px;">&nbsp;</td><td align=center>'+tx('Statistics')+'</td><td style="width:13px;" align=right><img src="'+WhiteRightArrow+'"></td></tr></table>')
		.css('color', 'white')
		.bind("mouseover", function () {
			t.SubChampContextMenu(this,'STATS',id, container);
		})
		.bind("mouseout", function (m) {
			if(!m && window.event)m=event;
			var goingto=m.relatedTarget|| event.toElement;
			if (goingto.id != "contextMenuPBP" && goingto.parentNode.id != "contextMenuPBP") {
				jQuery("#contextMenuPBP").remove();
			}
		});
		jQuery("#contextMenu div.context_menu_title").after(btn);

		btn = document.createElement('a');
		jQuery(btn).addClass("buttonv2 blue box").html('<table width=100% cellpadding=0 cellspacing=0 class=xtab style="padding-right:0px;"><tr><td style="width:13px;">&nbsp;</td><td align=center>'+tx('Auto')+'</td><td style="width:13px;" align=right><img src="'+WhiteRightArrow+'"></td></tr></table>')
		.css('color', 'white')
		.bind("mouseover", function () {
			t.SubChampContextMenu(this,'AUTO',id, container);
		})
		.bind("mouseout", function (m) {
			if(!m && window.event)m=event;
			var goingto=m.relatedTarget|| event.toElement;
			if (goingto.id != "contextMenuPBP" && goingto.parentNode.id != "contextMenuPBP") {
				jQuery("#contextMenuPBP").remove();
			}
		});
		jQuery("#contextMenu div.context_menu_title").after(btn);

		if (FromSearch) {
			btn = document.createElement('a');
			var champType = chTypeStrings[champ_item.type-1];
			if (champType=="ring") {
				var Sel = ((t.PreviewCards["ring1"] && t.PreviewCards["ring1"]==champ_item.equipmentId) || (t.PreviewCards["ring2"] && t.PreviewCards["ring2"]==champ_item.equipmentId));
			}
			else {
				var Sel = (t.PreviewCards[champType] && t.PreviewCards[champType]==champ_item.equipmentId);
			}
			if (Sel) {
				jQuery(btn).addClass("buttonv2 red box").html(tx('UnSelect')).css('color', 'white').bind("click", function () { jQuery("#contextMenu").remove(); t.ClickedSearchCard(champ_item.equipmentId); })
			}
			else {
				jQuery(btn).addClass("buttonv2 green box").html(tx('Select')).css('color', 'white').bind("click", function () { jQuery("#contextMenu").remove(); t.ClickedSearchCard(champ_item.equipmentId); })
			}
			jQuery("#contextMenu div.context_menu_title").after(btn);
		}

		if (champ_item.status == 1) {
			// no salvage if equipped
			if (Options.ChampOptions.NoEquippedSalvage && champ_item.equippedTo>0) {
				jQuery("#contextMenu a:nth-last-child(2)").remove();
			}
			else {
				// no salvage on first x items
				if (Options.ChampOptions.SalvageSafety) {
					var keys = uW.Object.keys(uW.kocChampionItems);
					if (keys.indexOf(id) < Options.ChampOptions.SalvageSafetyNum && keys.indexOf(id) > -1) {
						jQuery("#contextMenu a:nth-last-child(2)").remove();
					}
				}
			}

			if (Options.ChampOptions.NoMassSalvage) {
				jQuery("#contextMenu a").last().remove();
			}
		}
	},

	CustomChampContextMenu : function (id, top, left, fullmenu, container, outside, FromSearch) {
		var t = Tabs.Champ;
		var champ_item = uW.kocChampionItems[id];
		if (!champ_item) return;

		jQuery(".tooltip").remove();
		jQuery("#contextMenu").remove();

		if (outside) {
			if (!ById('PBPChampContextMenu')) {
				var newDiv = document.createElement('div');
				newDiv.id = "PBPChampContextMenu";
			}
			else {
				var newDiv = ById('PBPChampContextMenu');
			}
			if (FromSearch) {
				left = left - jQuery('#btchampSearchResults').scrollLeft(); // well this is shit even if it works...
			}
			newDiv.style.position = "absolute";
			newDiv.style.left = left + "px";
			newDiv.style.top = top + "px";
			newDiv.addEventListener("mouseleave", function () {
				jQuery(this).remove();
			}, false);
			container.appendChild(newDiv);
			container = newDiv;
		}

		var newDiv = document.createElement('div');
		newDiv.id = "contextMenu";
		if (!outside) {
			newDiv.style.left = left + "px";
			newDiv.style.top = top + "px";
		}

		newDiv.addEventListener("mouseleave", function () {
			jQuery(this).remove();
		}, false);

		var titleDiv = document.createElement('div');
		titleDiv.className = "context_menu_title";
		titleDiv.innerHTML = "<b>" + champ_item.name + "</b>";
		newDiv.appendChild(titleDiv);

		container.appendChild(newDiv);

		if (outside) { t.DoChampContextMenu(id, fullmenu, container, FromSearch); }
		else { t.DoChampContextMenu(id, fullmenu); }
	},

	paintTags: function () {
		var t = Tabs.Champ;

	},

	show: function (){
		var t = Tabs.Champ;
		if (t.activepanel=='overview') { t.display_overview(); }
		if (t.activepanel=='upgrader') { t.display_upgrader(); }
		if (t.activepanel=='repairer') { t.display_repairer(); }
		if (t.activepanel=='salvager') { t.display_salvager(); }
		if (t.activepanel=='compare') { t.display_compare(); }
		if (t.activepanel=='presets') { t.display_presets(); }
		if (t.activepanel=='options') { t.display_options(); }
		if (t.activepanel=='log') { t.display_log(); }
	},

	EverySecond : function () {
		var t = Tabs.Champ;

		if (uW.isNewServer()) { return; }
		
		t.LoopCounter = t.LoopCounter + 1;

		if (t.LoopCounter%2==0) { // refresh displays if any every 2 seconds
			if (tabManager.currentTab.name == 'Champ' && Options.btWinIsOpen){
				if (t.activepanel=="overview") {
					t.update_overview();
				}
				if (t.activepanel=="upgrader") {
					t.update_upgrader();
				}
				if (t.activepanel=="repairer") {
					t.update_repairer();
				}
			}
			var FreeSpace = t.MaxItems - Object.keys(uW.kocChampionItems).length;
			if (FreeSpace<=0) { if (jQuery("#mod_views2")) { jQuery("#mod_views2 a:eq(1)").css("color","red"); }}
			else { if (jQuery("#mod_views2")) { jQuery("#mod_views2 a:eq(1)").css("color",""); }}
		}
	},

	AddOverviewButton : function (tabId, text, eventListener, id, colourclass) {
		var t = Tabs.Champ;
		var a = createButton (text,id);
		if (colourclass == null) colourclass = 'blue20';
		a.className='inlineButton btButton '+colourclass;
		a.style.paddingLeft = '2px';
		var tabs=ById(tabId);
		if (tabs) {
			var e = document.createElement ('div');
			tabs.appendChild(e);
			e.appendChild(a);
			a.addEventListener('click',eventListener, false);
			if (id != null) { a.id = id; }
			return a;
		}
		return null;
	},

	// DISPLAY AND PAINT SUBTABS

	display_overview : function (){
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Overview");
		t.activepanel = "overview";

		var m = '<div class="divHeader" align="center">'+tx('OVERVIEW')+'</div>';
		m += '<div align=right><INPUT id=btChampToggle type=checkbox />&nbsp;'+tx("Add toggle button")+'</div>';
		m += '<div id=btchampoverviewinfo></div>';
		m += '<div class="divHeader" align="center">'+tx('AUTOMATIC FUNCTIONS')+'</div>';
		m += '<div id=btchampoverviewauto align=left><br><table class=xtab width=100%>';
		m += '<tr><td id=btchampoverviewupgradebuttondiv align=right width=100></td><td><div class="oddRow wrap xtabBorder" style="vertical-align:top;height:30px;" id=btchampoverviewupgradestatusdiv>&nbsp;</div></td></tr>';
		m += '<tr><td id=btchampoverviewrepairbuttondiv align=right width=100></td><td><div class="oddRow wrap xtabBorder" style="vertical-align:top;height:30px;" id=btchampoverviewrepairstatusdiv>&nbsp;</div></td></tr>';
		m += '<tr><td id=btchampoverviewsalvagebuttondiv align=right width=100></td><td><div class="oddRow wrap xtabBorder" style="vertical-align:top;height:30px;" id=btchampoverviewsalvagestatusdiv>&nbsp;</div></td></tr>';
		m += '</table></div><br>';
		m += '<div align=center><div style="position:absolute;bottom:0px;width:'+GlobalOptions.btWinSize.x+'px;"><br><hr>';
		m += '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">\
				<input type="hidden" name="cmd" value="_s-xclick">\
				<input type="hidden" name="hosted_button_id" value="8VEDPV3X9X82L">\
				<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">\
				<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">\
				</form>';
		m += '<br>'+tx('This additional tab has been provided free of charge for the benefit of players. Please donate to help with future support and development of this and other features')+'.<br>'+tx('Thanks')+',&nbsp;Barbarossa.</div></div>';

		div.innerHTML = m;

		t.update_overview();
		ToggleOption('ChampOptions','btChampToggle','ToggleButton');

		t.AddOverviewButton('btchampoverviewupgradebuttondiv','Upgrade',t.toggleAutoUpgradeState, 'ChampUpgradeToggleTab');
		SetToggleButtonState('ChampUpgrade',Options.ChampOptions.UpgradeRunning,'Upgrade');
		t.AddOverviewButton('btchampoverviewrepairbuttondiv','Repair',t.toggleAutoRepairState, 'ChampRepairToggleTab');
		SetToggleButtonState('ChampRepair',Options.ChampOptions.RepairRunning,'Repair');
		t.AddOverviewButton('btchampoverviewsalvagebuttondiv','Salvage',t.toggleAutoSalvageState, 'ChampSalvageToggleTab');
		SetToggleButtonState('ChampSalvage',Options.ChampOptions.SalvageRunning,'Salvage');

		t.PaintUpgradeStatus();
		t.PaintRepairStatus();
		t.PaintSalvageStatus();

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	update_overview : function () {
		var t = Tabs.Champ;

		var NumCards = Object.keys(uW.kocChampionItems).length;

		var totMight = 0;
		var brokeMight = 0;
		var brokeCount = 0;
		for (chId in uW.kocChampionItems) {
			var champ_item = uW.kocChampionItems[chId];
			if (champ_item == null || !champ_item) continue;
			var might = CardMight(champ_item,true);
			totMight += might;
			if (Tabs.Reference.isBroken(champ_item)) {
				brokeCount++;
				brokeMight += might;
			}
		}

		var m = '<table align=center cellpadding=2 cellspacing=0 class=xtab>';
		m += '<tr><td align=right>'+tx('Total Number of Cards')+':&nbsp;</td><td><b>'+NumCards+'</b></td><td align=right>'+tx('Total Champ Might')+':&nbsp;</td><td><b>'+addCommas(totMight)+'</b></td></tr>';
		var FreeSpace = t.MaxItems - NumCards;
		var span = '<span>';
		if (FreeSpace>=20) span = '<span class=boldGreen>'; // more than 20 items good!
		if (FreeSpace<10) span = '<span class=boldRed>'; // less than 10 items bad!
		if (FreeSpace>0) { m += '<tr><td align=right>'+tx('Free Space')+':&nbsp;</td><td><b>'+span+FreeSpace+' '+tx('Cards')+'</span></b></td>'; }
		else { m += '<tr><td align=right>'+tx('Free Space')+':&nbsp;</td><td>'+span+tx('None')+'!</span></b></td>'; }
		m += '<td align=right>'+tx('Broken Champ Might')+':&nbsp;</td><td><b>'+addCommas(brokeMight)+'</b></td></tr>';
		m += '<tr><td align=right>'+tx('Number of Active Champions')+':&nbsp;</td><td><b>'+Seed.champion.champions.length+'</b></td>';
		m += '<td align=right>'+tx('Number of Broken Cards')+':&nbsp;</td><td><b>'+brokeCount+'</b></td></tr>';
		m += '</table>';

		m += '<br><DIV id=btChampOverviewDiv style="width:'+(GlobalOptions.btWinSize.x-10)+'px;overflow-x:auto;">';
		m += '<TABLE width=98% class=xtab cellpadding=1 cellspacing=0 align=center style="font-size:'+Options.OverviewOptions.OverviewFontSize+'px;"><TR valign=bottom><td width=20>&nbsp;</td><td width=100>&nbsp;</td>';
		for (var i = 1; i <= Cities.numCities; i++) {
			m += '<TD style="font-size:11px;" align=center width=100><span id="btchampCity_'+i+'"><B>'+Cities.cities[i-1].name.substring(0, 12)+'</b></span></td>';
		}
		m += "<td>&nbsp;</td>"; // spacer

		var totaether = 0;
		m += '</tr><TR align=right class="oddRow"><TD style="padding-left: 0px;"><img height=18 src="'+AetherImage+'" title="'+uW.g_js_strings.commonstr.aetherstone+'"></td><td><div id=btchampTotAether class="totalCell xtabBorder">&nbsp;</div></td>';
		for (var i = 0; i < Cities.numCities; i++) {
			citynum = i+1;
			cityId = Cities.cities[i].id;
			var cityaether = parseIntNan(Seed.resources["city"+cityId]['rec5'][0]);
			totaether+=cityaether;
			var span = '<span>';
			if (cityaether >= Options.ChampOptions.SalvageMaxAether) { span = '<span class=boldGreen>'; }
			if (cityaether < Options.ChampOptions.safetyLimit) { span = '<span class=boldRed>'; }
			m += '<TD><div align=center class=xtabBorder><span id="btchampAetherCity_'+citynum+'">'+span+addCommas(cityaether)+'</span></span></div></td>';
		}

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

		ById('btchampoverviewinfo').innerHTML = m;
		ById('btchampTotAether').innerHTML = addCommas(totaether);

		t.PaintRepairStatus();
		var now = unixTime();
		if (Seed.queue_champion && Seed.queue_champion.end) {
			if (Seed.queue_champion.end>now) {
				if (ById('btchampoverviewrepairtimer')) ById('btchampoverviewrepairtimer').innerHTML = timestr(Seed.queue_champion.end - now);
			}
			else {
				if (ById('btchampoverviewrepairtimer')) ById('btchampoverviewrepairtimer').innerHTML = tx('Complete')+'!';
			}
		}
	},

	paint_upgrader : function () {
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Upgrader");

		var m = '<DIV class=divHeader align=center>'+tx('AUTOMATED CHAMPIONS HALL ENHANCE/UPGRADE')+'</div>';
		m += '<table width=100% class=xtab><tr><td width=30%>&nbsp;</td><td colspan=2 align=center><INPUT id=btAutoChampUpgradeState type=submit value="'+tx("Upgrade")+' = '+ (Options.ChampOptions.UpgradeRunning?'ON':'OFF')+'"></td><td width=30% align=right>&nbsp;</td></tr></table>';
		m += '<a id=btchampUpgradeOptionLink class=divLink><div class="divHeader" align="left"><img id=btchampUpgradeOptionArrow height="10" src="'+RightArrow+'">&nbsp;'+tx('OPTIONS')+'</div></a>';
		m += '<div id=btchampUpgradeOption align=center class="divHide">';

		m += '<TABLE class=xtab width="100%">';
		m += '<tr><td width=30>&nbsp;</td><td>'+tx('Use Aetherstone from')+'&nbsp;<div style="display:inline;" id=btchampUpgradeCity></div></td>';
		m += '<td align=right>&nbsp;</td></tr>';
		m += '<tr><td width=30>&nbsp;</td><td>'+tx('Minimum Aetherstone')+':&nbsp;<input class=btInput id=btchampUpgradeMinAether type=text size=7 maxlength=8 value="' + Options.ChampOptions.UpgradeMinAether + '"></td>';
		m += '<td align=right>&nbsp;</td></tr>';
		m += '<tr><td><input id=btchampUpgradeAnyCity type=checkbox '+(Options.ChampOptions.UpgradeAnyCity ? ' CHECKED' : '') + '></td><td colspan=2>'+tx('When empty, use Aetherstone from any city')+':-&nbsp;&nbsp;&nbsp;'+tx('Overflow Method')+':&nbsp;'+htmlSelector({order:"City Order",lowest:"Highest Aetherstone"},Options.ChampOptions.UpgradeOverflow, 'class=btInput id=btchampUpgradeOverflow')+'</td></tr>';
		m += '<tr><td><input id=btchampUpgradeOneItem type=checkbox '+(Options.ChampOptions.UpgradeOneItem ? ' CHECKED' : '') + '></td><td colspan=2>'+tx('Upgrade one card at a time')+'</td></tr>';
		m += '<tr><td>&nbsp;</td><td colspan=2><input id=btchampUpgradeOneMax type=checkbox '+(Options.ChampOptions.UpgradeOneMax ? ' CHECKED' : '') + '>&nbsp;'+tx('Maximum attempts for each card')+'&nbsp;<INPUT id=btchampUpgradeOneMaxAttempts type=text size=3 maxlength=4 value="'+Options.ChampOptions.UpgradeOneMaxAttempts+'"\></td></tr>';
		m += '<tr><td>&nbsp;</td><td>'+tx("Upgrade interval")+' <INPUT id=btchampUpgradeInterval type=text size=2 maxlength=2 value="'+Options.ChampOptions.UpgradeInterval+'"\> '+tx("seconds")+'</td></tr>';
		m += '<tr><td><input id=btchampWhisperToMe type=checkbox '+(Options.ChampOptions.WhisperToMe ? ' CHECKED' : '') + '></td><td colspan=2>'+tx('Whisper yourself successful attempts')+'</td></tr>';
		m += '<tr><td><input id=btchampSendToInbox type=checkbox '+(Options.ChampOptions.SendToInbox ? ' CHECKED' : '') + '></td><td colspan=2>'+tx('Mail yourself successful attempts')+'</td></tr>';

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

		TempQuals = {};
		for (k=0;k<cardQuality.length-1;k++) {
			var quality = cardQuality[k].toLowerCase();
			TempQuals[k] = uW.g_js_strings.throneRoom[quality];
		}
		MasterQuals = {};
		for (k=1;k<cardQuality.length-1;k++) {
			var quality = cardQuality[k].toLowerCase();
			MasterQuals[k] = uW.g_js_strings.throneRoom[quality];
		}
		TempLevels = {};
		for (var type_index = 0; type_index < CM.CHAMPION.MAX_LEVELS + 1; ++type_index) {
			TempLevels[type_index] = type_index;
		}
		MasterLevels = {};
		for (var type_index = 6; type_index < CM.CHAMPION.MAX_LEVELS + 1; ++type_index) {
			MasterLevels[type_index] = type_index;
		}

		m += '<a id=btchampUpgradeBoostsLink class=divLink><div class="divHeader" align="left"><img id=btchampUpgradeBoostsArrow height="10" src="'+RightArrow+'">&nbsp;'+tx('BOOST ITEMS')+'</div></a>';
		m += '<div id=btchampUpgradeBoosts align=center class="divHide">';

		var Boosts = '<table class="xtab" width="95%" cellspacing="0" cellpadding="0" align="center"><tr><td><b>'+tx('Enhance')+'</b></td><td align=right>'+tx('Minimum Quality')+':&nbsp;'+htmlSelector(TempQuals,Options.ChampOptions.EnhanceBoostMinQuality, 'class=btInput id=btchampUpgradeBoostMinQuality')+'</td></tr></table><br>';
		Boosts += '<table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr style="vertical-align:top;">';
		for (var i = 0; i < t.EnhanceItemList.length; i++) {
			Boosts += '<td width=30 rowspan=2><img height=28 src="'+IMGURL+'items/70/'+t.EnhanceItemList[i]+'.jpg" title="'+itemTitle(t.EnhanceItemList[i],true)+'" /></td><td>(<span id=btchampUse'+t.EnhanceItemTrans[i]+'Label>' + parseIntNan(uW.ksoItems[t.EnhanceItemList[i]].count) + '</span>)</td>';
		}
		Boosts += '</tr><tr style="vertical-align:top;">';
		for (var i = 0; i < t.EnhanceItemList.length; i++) {
			Boosts += '<td><input type=checkbox id="btchamp'+t.EnhanceItemTrans[i]+'" '+(Options.ChampOptions["Use"+t.EnhanceItemTrans[i]]?"CHECKED" : "")+'></td>';
		}
		Boosts += '</tr></table>';
		Boosts += '<table style="display:none;" width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr><td><input type=checkbox id=btchampEOV >'+tx('Automatically use Masters Orbs for qualities between')+' '+htmlSelector(MasterQuals,Options.ChampOptions.EnhanceUseMastersMin, 'id=btchampEOVItemMin') + ' '+tx('and')+' '+htmlSelector(MasterQuals,Options.ChampOptions.EnhanceUseMastersMax, 'id=btchampEOVItemMax')+'</td></tr></table>';
		Boosts += '<table style="display:none;" width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr><td><input type=checkbox id=btchampELevelOnly ><b>'+tx('Only use Orbs for the current quality')+'</b></td></tr></table>';
		Boosts += '<table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr><td><input type=checkbox id=btchampENoBoost ><b>'+tx('Do not attempt Enhance if no boost items available')+'</b></td></tr></table>';
		Boosts += '<hr>';

		Boosts += '<table class="xtab" width="95%" cellspacing="0" cellpadding="0" align="center"><tr><td><b>'+tx('Upgrade')+'</b></td><td align=right>'+tx('Minimum Level')+':&nbsp;'+htmlSelector(TempLevels,Options.ChampOptions.UpgradeBoostMinLevel, 'class=btInput id=btchampUpgradeBoostMinLevel')+'</td></tr></table><br>';
		Boosts += '<table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr style="vertical-align:top;">';
		for (var i = 0; i < t.UpgradeItemList.length; i++) {
			Boosts += '<td width=30 rowspan=2><img height=28 src="'+IMGURL+'items/70/'+t.UpgradeItemList[i]+'.jpg" title="'+itemTitle(t.UpgradeItemList[i],true)+'" /></td><td>(<span id=btchampUse'+t.UpgradeItemTrans[i]+'Label>' + parseIntNan(uW.ksoItems[t.UpgradeItemList[i]].count) + '</span>)</td>';
		}
		Boosts += '</tr><tr style="vertical-align:top;">';
		for (var i = 0; i < t.UpgradeItemList.length; i++) {
			Boosts += '<td><input type=checkbox id="btchamp'+t.UpgradeItemTrans[i]+'" '+(Options.ChampOptions["Use"+t.UpgradeItemTrans[i]]?"CHECKED" : "")+'></td>';
		}
		Boosts += '</tr></table>';
		Boosts += '<table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr><td><input type=checkbox id=btchampUOVM >'+tx("Automatically use Forgemasters Tokens for levels between")+' '+htmlSelector(MasterLevels,Options.ChampOptions.UpgradeUseMastersMin, 'class=btInput id=btchampUOVMItemMin')+' '+tx('and')+' '+htmlSelector(MasterLevels,Options.ChampOptions.UpgradeUseMastersMax, 'class=btInput id=btchampUOVMItemMax')+'</td></tr></table>';
		Boosts += '<table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr><td><input type=checkbox id=btchampULevelOnly ><b>'+tx('Only use Tokens for the current level')+'</b></td></tr></table>';
		Boosts += '<table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr><td><input type=checkbox id=btchampUNoBoost ><b>'+tx('Do not attempt Upgrade if no boost items available')+'</b></td></tr></table>';

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

		m += '<div class="divHeader">'+tx('ADD CARDS')+'</div>';
		m += '<table class="xtab" width=100%><tr>';
		m += '<td><b>'+uW.g_js_strings.commonstr.item+':&nbsp;</b><select id="btchampUpgradeItem">';
		m += '</select>&nbsp;'+strButton8(uW.g_js_strings.commonstr.upgrade,'id=btchampUpgradeUpgrade')+'&nbsp;'+strButton8(uW.g_js_strings.commonstr.enhance,'id=btchampUpgradeEnhance')+'</td>';
		m += '<td align=right>'+tx('Default Enhance Quality')+':&nbsp;'+htmlSelector(MasterQuals,Options.ChampOptions.UpgradeDefaultQuality, 'class=btInput id=btchampUpgradeDefaultQuality')+'</td></tr>';
		m += '<tr><td>&nbsp;</td><td align=right>'+tx('Default Upgrade Level')+':&nbsp;'+htmlSelector(MasterLevels,Options.ChampOptions.UpgradeDefaultLevel, 'class=btInput id=btchampUpgradeDefaultLevel')+'</td></tr>';
		m += '</table><hr><TABLE class=xtab cellpadding=0 cellspacing=0>';
		m += '<tr><td>'+tx('Enhance ALL Qualities')+'&nbsp;</td><td>'+htmlSelector(TempQuals,0, 'class=btInput id=btchampEnhanceAllFrom')+'&nbsp;</td><td>'+tx('and below')+'&nbsp;<input type=checkbox style="vertical-align:bottom;" id=btchampEnhanceAllBelow>&nbsp;</td><td>'+tx('to Quality')+'&nbsp;</td><td>'+htmlSelector(MasterQuals,6, 'class=btInput id=btchampEnhanceAllTo')+'&nbsp;</td><td>'+strButton8(tx('Add to Queue'),'id=btchampEnhanceAllAdd')+'</td></tr>';
		m += '<tr><td>'+tx('Upgrade ALL Levels')+'&nbsp;</td><td>'+htmlSelector(TempLevels,0, 'class=btInput id=btchampUpgradeAllFrom')+'&nbsp;</td><td>'+tx('and below')+'&nbsp;<input type=checkbox style="vertical-align:bottom;" id=btchampUpgradeAllBelow>&nbsp;</td><td>'+tx('to Level')+'&nbsp;</td><td>'+htmlSelector(TempLevels,CM.MAX_MASTERS_TOKEN_LEVEL, 'class=btInput id=btchampUpgradeAllTo')+'&nbsp;</td><td>'+strButton8(tx('Add to Queue'),'id=btchampUpgradeAllAdd')+'</td></tr>';
		m += '</table>';
		m += '<div id=btChampUpgradeMessages align=center>&nbsp;</div>';
		m += '<div class="divHeader"><TABLE width=100% cellspacing=0><TR><TD class=xtab width=100>&nbsp;</td><TD class=xtab align=center>'+tx('UPGRADE QUEUE')+'</td><TD class=xtab width=100 align=right><span id=btchampUpgradeQueueCount></span>&nbsp;'+tx('Cards')+'</TD></tr></table></div>';
		m += '<div id=btchampUpgradeQueue style="min-height:300px;max-height:500px;overflow-y:scroll;">&nbsp;</div>';

		div.innerHTML = m;

		t.fillUpgradeItemDropdown();

		new CdispCityPicker('btchampupgrade_city', ById('btchampUpgradeCity'), true, t.UpgradeCityButton, Options.ChampOptions.UpgradeCityNum);

		ById('btchampUpgradeOptionLink').addEventListener ('click', function () {ToggleMainDivDisplay("Champ",100,GlobalOptions.btWinSize.x,"btchampUpgradeOption",false);}, false);
		ById('btchampUpgradeBoostsLink').addEventListener ('click', function () {ToggleMainDivDisplay("Champ",100,GlobalOptions.btWinSize.x,"btchampUpgradeBoosts",false);}, false);

		ChangeIntegerOption('ChampOptions', 'btchampUpgradeMinAether', 'UpgradeMinAether', 50000)
		ChangeIntegerOption('ChampOptions', 'btchampUpgradeInterval','UpgradeInterval',10);
		ToggleOption('ChampOptions','btchampUpgradeAnyCity','UpgradeAnyCity');
		ToggleOption('ChampOptions','btchampUpgradeOneItem','UpgradeOneItem');
		ToggleOption('ChampOptions','btchampUpgradeOneMax','UpgradeOneMax');
		ChangeIntegerOption('ChampOptions', 'btchampUpgradeOneMaxAttempts','UpgradeOneMaxAttempts',100);
		ToggleOption('ChampOptions','btchampWhisperToMe','WhisperToMe');
		ToggleOption('ChampOptions','btchampSendToInbox','SendToInbox');
		ChangeOption('ChampOptions','btchampUpgradeOverflow','UpgradeOverflow');

		ById('btAutoChampUpgradeState').addEventListener('click', function(){
			t.toggleAutoUpgradeState(this);
		}, false);

		ToggleOption('ChampOptions','btchampLOM','UseLOM');
		ToggleOption('ChampOptions','btchampGOM','UseGOM');
		ToggleOption('ChampOptions','btchampJST','UseJST');
		ToggleOption('ChampOptions','btchampST','UseST');
		ToggleOption('ChampOptions','btchampEST','UseEST');

		ChangeIntegerOption('ChampOptions', 'btchampUpgradeBoostMinQuality', 'EnhanceBoostMinQuality', 0);
		ToggleOption('ChampOptions','btchampEOV','EnhanceUseMasters');
		ChangeIntegerOption('ChampOptions', 'btchampEOVItemMin', 'EnhanceUseMastersMin', 0);
		ChangeIntegerOption('ChampOptions', 'btchampEOVItemMax', 'EnhanceUseMastersMax', 6);
		ToggleOption('ChampOptions','btchampENoBoost','EnhanceNoBoosts');
		ToggleOption('ChampOptions','btchampELevelOnly','EnhanceBoostLevelOnly');

		ChangeIntegerOption('ChampOptions', 'btchampUpgradeBoostMinLevel', 'UpgradeBoostMinLevel', 3);
		ToggleOption('ChampOptions','btchampUOVM','UpgradeUseMasters');
		ChangeIntegerOption('ChampOptions', 'btchampUOVMItemMin', 'UpgradeUseMastersMin', 7);
		ChangeIntegerOption('ChampOptions', 'btchampUOVMItemMax', 'UpgradeUseMastersMax', 28);
		ToggleOption('ChampOptions','btchampUNoBoost','UpgradeNoBoosts');
		ToggleOption('ChampOptions','btchampULevelOnly','UpgradeBoostLevelOnly');

		ChangeIntegerOption('ChampOptions', 'btchampUpgradeDefaultQuality', 'UpgradeDefaultQuality', 6);
		ChangeIntegerOption('ChampOptions', 'btchampUpgradeDefaultLevel', 'UpgradeDefaultLevel', 28);

		ById('btchampUpgradeUpgrade').addEventListener('click', function () {
			t.addChampQueue(ById('btchampUpgradeItem').value,'upgrade',Options.ChampOptions.UpgradeDefaultLevel);
		}, false);
		ById('btchampUpgradeEnhance').addEventListener('click', function () {
			t.addChampQueue(ById('btchampUpgradeItem').value,'enhance',Options.ChampOptions.UpgradeDefaultQuality);
		}, false);
		ById('btchampUpgradeAllAdd').addEventListener('click', function () {
			for (var k in uW.kocChampionItems) {
				var champ_item = uW.kocChampionItems[k];
				if (champ_item && ((champ_item.level == parseIntNan(ById('btchampUpgradeAllFrom').value)) || (champ_item.level < parseIntNan(ById('btchampUpgradeAllFrom').value) && ById('btchampUpgradeAllBelow').checked))) {
					t.addChampQueue(champ_item.equipmentId,'upgrade',parseIntNan(ById('btchampUpgradeAllTo').value),true);
				}
			}
			t.paintUpgradeQueue();
		}, false);
		ById('btchampEnhanceAllAdd').addEventListener('click', function () {
			for (var k in uW.kocChampionItems) {
				var champ_item = uW.kocChampionItems[k];
				if (champ_item && ((champ_item.rarity == parseIntNan(ById('btchampEnhanceAllFrom').value)) || (champ_item.rarity < parseIntNan(ById('btchampEnhanceAllFrom').value) && ById('btchampEnhanceAllBelow').checked))) {
					t.addChampQueue(champ_item.equipmentId,'enhance',parseIntNan(ById('btchampEnhanceAllTo').value),true);
				}
			}
			t.paintUpgradeQueue();
		}, false);

		t.paintUpgradeQueue();
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	display_upgrader : function (){
		var t = Tabs.Champ
		t.activepanel = "upgrader";
		t.fillUpgradeItemDropdown();
		t.paintUpgradeQueue();
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	paint_repairer : function (){
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Repairer");

		TempQuals = {};
		for (k=0;k<cardQuality.length-1;k++) {
			var quality = cardQuality[k].toLowerCase();
			TempQuals[k] = uW.g_js_strings.throneRoom[quality];
		}
		TempLevels = {};
		for (var type_index = 0; type_index < CM.CHAMPION.MAX_LEVELS + 1; ++type_index) {
			TempLevels[type_index] = type_index;
		}

		var m = '<DIV class=divHeader align=center>'+tx('AUTOMATED CHAMPION HALL BREAK/REPAIR')+'</div>';
		m += '<table width=100% class=xtab><tr><td width=30%>&nbsp;</td><td colspan=2 align=center><INPUT id=btAutoChampRepairState type=submit value="'+tx("Repair")+' = '+ (Options.ChampOptions.RepairRunning?'ON':'OFF')+'"></td><td width=30% align=right>&nbsp;</td></tr></table>';

		m += '<div class="divHeader">'+tx('BREAK CHAMPION CARDS')+'</div>';
		m += '<table class="xtab" width=100%>';
		m += '<tr><td align=left><input id=btchampBreakIgnorePreset type=checkbox '+(Options.ChampOptions.BreakIgnorePreset ? ' CHECKED' : '') + '>&nbsp;'+tx('Ignore any cards assigned to a champion')+'</td><td align=right>'+tx('Maximum champion might to break (Zero for no maximum)')+'&nbsp;<input class=btInput id=btchampBreakMaxMight type=text size=14 maxlength=14 value="'+Options.ChampOptions.BreakMaxMight+'"></td></tr>';
		m += '<tr><td align=left colspan=2><input id=btchampBreakRepairAuto type=checkbox '+(Options.ChampOptions.BreakRepairAuto ? ' CHECKED' : '') + '>&nbsp;'+tx('Automatically add cards broken to the Repair queue')+'</td></tr>';
		m += '<tr><td align=center colspan=2>'+tx('Break cards between levels')+'&nbsp;'+htmlSelector(TempLevels,Options.ChampOptions.BreakMinLevel, 'class=btInput id=btchampBreakMinLevel')+'&nbsp;'+tx('and')+'&nbsp;'+htmlSelector(TempLevels,Options.ChampOptions.BreakMaxLevel, 'class=btInput id=btchampBreakMaxLevel')+'</td></tr>';
		m += '<tr><td align=center colspan=2>'+strButton14(tx('Break Champion Hall'),'id=btchampBreakChamp','red14')+'</td></tr>';
		m += '<tr><td align=center colspan=2><div id=btchampBreakMessages><span class=boldRed>'+tx('WARNING - This action may consume a lot of Aetherstone')+'!</span></div></td></tr>';
		m += '</table>';

		m += '<div class="divHeader" align="center">'+tx('REPAIR SPEEDUPS')+'</div>';
		m += '<div id=btchampRepairSpeedup align=center><table width=100% class=xtab><tr><td><div align=center>';

		var Speedups = '<table class="xtab" width="95%" cellspacing="0" cellpadding="0" align="center"><tr><td>'+tx('Minimum Quality')+':&nbsp;'+htmlSelector(TempQuals,Options.ChampOptions.RepairSpeedupMinQuality, 'class=btInput id=btchampRepairSpeedupMinQuality')+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+tx('Minimum Level')+':&nbsp;'+htmlSelector(TempLevels,Options.ChampOptions.RepairSpeedupMinLevel, 'class=btInput id=btchampRepairSpeedupMinLevel')+'</td></tr></table><br>';
		Speedups += '<table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr style="vertical-align:top;">';
		for (var i = 0; i < t.SpeedupItemList.length; i++) {
			Speedups += '<td width=30 rowspan=2><img height=28 src="'+IMGURL+'items/70/'+t.SpeedupItemList[i]+'.jpg" title="'+itemTitle(t.SpeedupItemList[i],true)+'\n'+tx(HourGlassHint[i])+'" /></td><td>(<span id=btchampUse'+t.SpeedupItemTrans[i]+'Label>' + parseIntNan(uW.ksoItems[t.SpeedupItemList[i]].count) + '</span>)</td>';
		}
		Speedups += '</tr><tr style="vertical-align:top;">';
		for (var i = 0; i < t.SpeedupItemList.length; i++) {
			Speedups += '<td><input type=checkbox id="btchamp'+t.SpeedupItemTrans[i]+'" '+(Options.ChampOptions["Use"+t.SpeedupItemTrans[i]]?"CHECKED" : "")+'></td>';
		}
		Speedups += '<td width=70 rowspan=2 align=right><INPUT id=btchampHelp type=submit value="'+tx('HELP')+'!"></td>';
		Speedups += '</tr></table></td></tr>';
		Speedups += '<tr><td><div align=center><table width=95% class=xtab align=center cellpadding=0 cellspacing=0><tr><td><input type=checkbox id=btchampOV >'+tx('Override above by always using')+' '+htmlSelector(HourGlassName,Options.ChampOptions.OverrideSpeedup, 'id=btchampOVItem') + ' '+tx('when more than')+' ';
		Speedups += '<INPUT style="width: 30px;text-align:right;" id="btchampOVHours" type=text maxlength=4 >&nbsp;'+uW.g_js_strings.timestr.timehr+'&nbsp;<INPUT style="width: 30px;text-align:right;" id="btchampOVMinutes" type=text maxlength=4 >&nbsp;'+uW.g_js_strings.timestr.timemin+' '+tx('remaining')+'.</td></tr></table></div></td></tr>';

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

		m += '<div class="divHeader">'+tx('REPAIR CHAMPION CARDS')+'</div>';
		m += '<table class="xtab" width=100%><tr>';
		m += '<td><b>'+uW.g_js_strings.commonstr.item+':&nbsp;</b><select id="btchampRepairItem">';
		m += '</select>&nbsp;'+strButton8(uW.g_js_strings.throneRoom.button_repair,'id=btchampRepairButton')+'</td></tr>';
		m += '</table><hr><TABLE class=xtab cellpadding=0 cellspacing=0>';

		m += '<tr><td>'+tx('Repair ALL broken cards between levels')+'&nbsp;</td><td>'+htmlSelector(TempLevels,0, 'class=btInput id=btchampRepairAllFrom')+'&nbsp;</td><td>'+tx('and')+'&nbsp;'+htmlSelector(TempLevels,CM.CHAMPION.MAX_LEVELS, 'class=btInput id=btchampRepairAllTo')+'&nbsp;</td><td>'+strButton8(tx('Add to Queue'),'id=btchampRepairAllAdd')+'</td></tr>';
		m += '</table>';
		m += '<div id=btChampRepairMessages align=center>&nbsp;</div>';
		m += '<div class="divHeader"><TABLE width=100% cellspacing=0><TR><TD class=xtab width=100>&nbsp;</td><TD class=xtab align=center>'+tx('REPAIR QUEUE')+'</td><TD class=xtab width=100 align=right><span id=btchampRepairQueueCount></span>&nbsp;'+tx('Cards')+'</TD></tr></table></div>';
		m += '<div id=btchampRepairQueue style="min-height:300px;max-height:500px;overflow-y:scroll;">&nbsp;</div>';

		div.innerHTML = m;

		t.fillRepairItemDropdown();

		ById('btAutoChampRepairState').addEventListener('click', function(){
			t.toggleAutoRepairState(this);
		}, false);

		ById('btchampHelp').addEventListener ('click', t.helpPop, false);

		ToggleOption('ChampOptions','btchampSH','UseSH');
		ToggleOption('ChampOptions','btchampKH','UseKH');
		ToggleOption('ChampOptions','btchampGH','UseGH');
		ToggleOption('ChampOptions','btchampMH','UseMH');
		ToggleOption('ChampOptions','btchampAH','UseAH');
		ToggleOption('ChampOptions','btchampRH','UseRH');
		ToggleOption('ChampOptions','btchampDH','UseDH');
		ToggleOption('ChampOptions','btchampEH','UseEH');
		ToggleOption('ChampOptions','btchampOV','UseOverride');

		ChangeIntegerOption('ChampOptions','btchampOVItem','OverrideSpeedup');
		ChangeIntegerOption('ChampOptions','btchampOVHours','OverrideHours');
		ChangeIntegerOption('ChampOptions','btchampOVMinutes','OverrideMinutes');

		ChangeIntegerOption('ChampOptions', 'btchampRepairSpeedupMinQuality', 'RepairSpeedupMinQuality', 1);
		ChangeIntegerOption('ChampOptions', 'btchampRepairSpeedupMinLevel', 'RepairSpeedupMinLevel', 1);

		ChangeIntegerOption('ChampOptions', 'btchampBreakMinLevel', 'BreakMinLevel', 0);
		ChangeIntegerOption('ChampOptions', 'btchampBreakMaxLevel', 'BreakMaxLevel', 0);
		ChangeIntegerOption('ChampOptions','btchampBreakMaxMight','BreakMaxMight',0);
		ToggleOption('ChampOptions','btchampBreakIgnorePreset','BreakIgnorePreset');
		ToggleOption('ChampOptions','btchampBreakRepairAuto','BreakRepairAuto');

		ById('btchampRepairButton').addEventListener('click', function () {
			t.addChampRepairQueue(ById('btchampRepairItem').value);
		}, false);

		ById('btchampRepairAllAdd').addEventListener('click', function () {
			for (var k in uW.kocChampionItems) {
				var champ_item = uW.kocChampionItems[k];
				if (champ_item && Tabs.Reference.isBroken(champ_item) && (champ_item.level >= parseIntNan(ById('btchampRepairAllFrom').value)) && (champ_item.level <= parseIntNan(ById('btchampRepairAllTo').value))) {
					t.addChampRepairQueue(champ_item.equipmentId,true);
				}
			}
			t.paintRepairQueue();
		}, false);

		ById('btchampBreakChamp').addEventListener('click', t.BreakChampButtonClicked, false);

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	display_repairer : function (){
		var t = Tabs.Champ;
		t.activepanel = "repairer";
		t.fillRepairItemDropdown();
		t.paintRepairQueue();
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	paint_salvager : function (){
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Salvager");

		TempQuals = {};
		for (var k=0;k<=t.MAX_EFFECTS;k++) {
			var quality = cardQuality[k].toLowerCase();
			TempQuals[k] = uW.g_js_strings.throneRoom[quality];
		}

		var m = '<DIV class=divHeader align=center>'+tx('AUTOMATED CHAMPION HALL SALVAGE')+'</div>';
		m += '<table width=100% class=xtab><tr><td width=30%>&nbsp;</td><td colspan=2 align=center><INPUT id=btAutoChampSalvageState type=submit value="'+tx("Salvage")+' = '+ (Options.ChampOptions.SalvageRunning?'ON':'OFF')+'"></td><td width=30% align=right>&nbsp;</td></tr></table>';
		m += '<a id=btchampSalvageOptionLink class=divLink><div class="divHeader" align="left"><img id=btchampSalvageOptionArrow height="10" src="'+RightArrow+'">&nbsp;'+tx('OPTIONS')+'</div></a>';
		m += '<div id=btchampSalvageOption align=center class="divHide">';
		m += '<TABLE class=xtab width="100%">';
		m += '<tr><td width=30>&nbsp;</td><td>'+tx('Deposit Aetherstone in')+'&nbsp;<div style="display:inline;" id=btchampSalvageCity></div></td>';
		m += '<td align=right>'+tx('Keep all')+'&nbsp;'+htmlSelector(TempQuals,Options.ChampOptions.SalvageMaxQuality, 'id=btchampSalvageQuality class=btInput')+'&nbsp;'+tx('cards and above')+'</td></tr>';
		m += '<tr><td width=30>&nbsp;</td><td>'+tx('Maximum Aetherstone')+':&nbsp;<input class=btInput id=btchampSalvageMaxAether type=text size=7 maxlength=8 value="' + Options.ChampOptions.SalvageMaxAether + '"></td>';
		m += '<td align=right>'+tx('Keep first')+'&nbsp;<input class=btInput id=btchampSalvageKeepFirst type=text size=2 maxlength=3 value="' + Options.ChampOptions.SalvageKeepFirst + '"/>&nbsp;'+tx('cards')+'</td></tr>';
		m += '<tr><td><input id=btchampSalvageAnyCity type=checkbox '+(Options.ChampOptions.SalvageAnyCity ? ' CHECKED' : '') + '></td><td colspan=2>'+tx('When full, deposit Aetherstone in any city')+':-&nbsp;&nbsp;&nbsp;'+tx('Overflow Method')+':&nbsp;'+htmlSelector({order:"City Order",lowest:"Lowest Aetherstone"},Options.ChampOptions.SalvageOverflow, 'class=btInput id=btchampSalvageOverflow')+'</td></tr>';
		m += '<tr><td><input id=btchampSalvageUpgradeAuto type=checkbox '+(Options.ChampOptions.SalvageUpgradeAuto ? ' CHECKED' : '') + '></td><td colspan=2>'+tx('Automatically add any cards that match a salvage rule to the Enhance/Upgrade queues')+'</td></tr>';

		m += '</table>';
		m += '</div><div id=btchampSalvagePanel></div>';
		m += '<div id=btchampSalvageMessages align=center>&nbsp;</div>';

		div.innerHTML = m;

		new CdispCityPicker('btchampsalvage_city', ById('btchampSalvageCity'), true, t.SalvageCityButton, Options.ChampOptions.SalvageCityNum);

		ById('btchampSalvageOptionLink').addEventListener ('click', function () {ToggleMainDivDisplay("Champ",100,GlobalOptions.btWinSize.x,"btchampSalvageOption",false);}, false);

		ChangeIntegerOption('ChampOptions', 'btchampSalvageMaxAether', 'SalvageMaxAether', 2000000)
		ChangeIntegerOption('ChampOptions', 'btchampSalvageQuality', 'SalvageMaxQuality', 3)
		ChangeIntegerOption('ChampOptions', 'btchampSalvageKeepFirst', 'SalvageKeepFirst', 40)
		ToggleOption('ChampOptions','btchampSalvageAnyCity','SalvageAnyCity');
		ChangeOption('ChampOptions','btchampSalvageOverflow','SalvageOverflow');
		ToggleOption('ChampOptions','btchampSalvageUpgradeAuto','SalvageUpgradeAuto');

		ById('btAutoChampSalvageState').addEventListener('click', function(){
			t.toggleAutoSalvageState(this);
		}, false);

		t.paint_salvage_rules();

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	paint_salvage_rules : function () {
		var t = Tabs.Champ;

		var m = '<div class="divHeader"><TABLE width=100% cellspacing=0><TR><TD class=xtab width=100>&nbsp;</td><TD class=xtab align=center>'+tx('SALVAGE RULES')+'</td><TD class=xtab width=100 align=right><span id=btchampSalvageRulesCount></span>&nbsp;'+tx('Rules')+'</TD></tr></table></div>';
		m += '<div align="center"><br><TABLE cellSpacing=0 width=98% height=0% class=xtab><tr><td>'+strButton20(tx('New Simple Rule'), 'id=btchampNewSimpleRule')+'&nbsp;';
		if (GlobalOptions.btWinSize.x == 750) m += '<br>';
		m += strButton20(tx('New Advanced Rule'), 'id=btchampNewAdvancedRule')+'</td><td align=right width=90px>';
		m += tx('Effect')+':&nbsp;<select id=btchampAutoLoadEffect class=btInput>';
		m += '<option value="0">-- '+tx('Select')+' --</option>';
		for (var k=0;k<t.ChampEffects.length;k++) {
			var effect = t.ChampEffects[k];
			if (effect<300) {
				var effectName = CM.ChampionManager.getEffectName(effect);
				m += '<option value="' + effect + '">' + effectName + '</option>';
			}
		}
		m += '</select>&nbsp;';
		m += strButton20(tx('Auto-Create Rules'), 'id=btchampAutoLoadRule')+'&nbsp;';
		if (GlobalOptions.btWinSize.x == 750) m += '<br>';
		m += strButton20(tx('Delete ALL Rules'), 'id=btchampClearRules')+'</td></tr></table></div>';
		m += '<br><div align=center><b>'+tx('Automatic Salvager will keep all cards matching any of these rules')+'</b></div>';

		function sortFunc(a, b) {
			if (typeof (a[Options.ChampOptions.SalvageSortColNum]) == 'number') {
				if (Options.ChampOptions.SalvageSortDir > 0)
					return a[Options.ChampOptions.SalvageSortColNum] - b[Options.ChampOptions.SalvageSortColNum];
				else
					return b[Options.ChampOptions.SalvageSortColNum] - a[Options.ChampOptions.SalvageSortColNum];
			} else if (typeof (a[Options.ChampOptions.SalvageSortColNum]) == 'boolean') {
				return 0;
			} else {
				if (Options.ChampOptions.SalvageSortDir > 0)
					return a[Options.ChampOptions.SalvageSortColNum].localeCompare(b[Options.ChampOptions.SalvageSortColNum]);
				else
					return b[Options.ChampOptions.SalvageSortColNum].localeCompare(a[Options.ChampOptions.SalvageSortColNum]);
			}
		}

		var dat = [];
		var EmptyDatabase = true;
		t.TotalRules = Options.ChampOptions.SalvageRuleSet.length;

		for (var k=0;k<Options.ChampOptions.SalvageRuleSet.length;k++) {
			var salvage_rule = Options.ChampOptions.SalvageRuleSet[k];
			EmptyDatabase = false;
			dat.push([(k+1),(salvage_rule.type=="any"?tx("Any"):uW.g_js_strings.champ[salvage_rule.type]),(salvage_rule.faction=="any"?tx("Any"):uW.g_js_strings.commonstr[salvage_rule.faction]),t.FormatSalvageCondition(salvage_rule.conditions,(salvage_rule.advancedrule||false))]);
		}

		if (!EmptyDatabase) {
			dat.sort(sortFunc);

			m += '<div style="width:100%;overflow-x:auto;min-height:300px;max-height:400px;overflow-y:auto;" align="center"><table width=98% cellspacing=0 cellpadding=0 class=xtab>';
			m += '<TR><TD width=40 align=left nowrap><A id=SalvageCol0 onclick="btchampSalvageClickSort(this)" class="buttonv2 std blue" style="padding-left:0px;padding-right:0px;"><span style="display:inline-block;width:100%;">&nbsp;'+tx('Seq')+'&nbsp;</span></a></td>\
				<TD width=80 align=left nowrap><A id=SalvageCol1 onclick="btchampSalvageClickSort(this)" class="buttonv2 std blue" style="padding-left:0px;padding-right:0px;"><span style="display:inline-block;width:100%;">&nbsp;'+uW.g_js_strings.commonstr.type+'&nbsp;</span></a></td>\
				<TD width=80 nowrap><A id=SalvageCol2 onclick="btchampSalvageClickSort(this)" class="buttonv2 std blue" style="padding-left:0px;padding-right:0px;"><span style="display:inline-block;width:100%;">&nbsp;'+uW.g_js_strings.commonstr.faction+'&nbsp;</span></a></td>\
				<TD align=right nowrap><A id=SalvageCol3 onclick="btchampSalvageClickSort(this)" class="buttonv2 std blue" style="padding-left:0px;padding-right:0px;"><span style="display:inline-block;width:100%;">&nbsp;'+tx('Conditions')+'&nbsp;</span></a></td>\
				<TD width=80 align=left nowrap><A class="buttonv2 std blue" style="padding-left:0px;padding-right:0px;"><span style="display:inline-block;width:100%;">&nbsp;'+tx('Action')+'&nbsp;</span></a></td>\
				</tr>';

			var r = 0;

			for (var G=0;G<dat.length;G++) {
				r=r+1;
				rowClass = 'evenRow';
				var rem = (r % 2);
				if (rem == 1) rowClass = 'oddRow';
				var n = dat[G][0]-1;

				m += '<tr class='+rowClass+'><td class=xtab align=center valign=top>' + dat[G][0] + '</td>';
				m += '<td valign=top>' + dat[G][1] + '</td>';
				m += '<td valign=top>' + dat[G][2] + '</td>';
				m += '<td valign=top>' + dat[G][3] + '</td>';
				m += '<td align=right valign=top><a id="btchampSalvageRuleEdit'+n+'" class="inlineButton btButton brown8" onclick="btchampSalvageEditRule('+n+')"><span>Edit</span></a>&nbsp;<a id="btchampSalvageRuleDelete'+n+'" class="inlineButton btButton brown8" onclick="btchampSalvageDeleteRule('+n+')"><span>Del</span></a></td></tr>';
			}
			m += '</table></div>';
		}
		else {
			m += '<div align=center><br><br><span style="opacity:0.3;">'+tx('No salvage rules defined')+'</div><br><br></div>';
		}
		m += '<div align=right><input class=btInput id=btchampsalvageSave type=button value="'+tx("Save Rules")+'">&nbsp;<input class=btInput id=btchampsalvageLoad type=button value="'+tx("Load Rules")+'">&nbsp;<input class=btInput id=btchampsalvageLoadFile type=file></div>';

		ById('btchampSalvagePanel').innerHTML = m;

		ById('btchampSalvageRulesCount').innerHTML = t.TotalRules;
		if (!EmptyDatabase) {
			ById('SalvageCol' + Options.ChampOptions.SalvageSortColNum).className = 'buttonv2 std green';
		}

		ById('btchampNewSimpleRule').addEventListener ('click', function() {t.SalvageNewRule(false);}, false);
		ById('btchampNewAdvancedRule').addEventListener ('click', function() {t.SalvageNewRule(true);}, false);
		ById('btchampClearRules').addEventListener ('click', function() {t.SalvageClearRules();}, false);

		ById('btchampAutoLoadRule').addEventListener('click', function () {
			var effectId = ById('btchampAutoLoadEffect').value;
			if (effectId == 0) {
				ById('btchampSalvageMessages').innerHTML = tx('Please select an effect');
				return;
			}
			var GotRules = false;
			for (var category in t.AdvancedStatsGrid) {
				var faction = 'any';
				var type = category;
				var conditions = [];
				for (var i=1;i<6;i++) {
					if (t.AdvancedStatsGrid[category][i][effectId] != 0) {
						GotRules = true;
						var slots = [];
						var minTier = t.AdvancedStatsGrid[category][i][effectId];
						for (var slotChecker = 1; slotChecker < 6; slotChecker++) slots.push(slotChecker==i);
						var buffDebuff = "b";
						var ruleEffect = effectId;
						if (DebuffEffects.indexOf(parseInt(effectId))!=-1) {
							buffDebuff = "d";
							for (var efx in EffectDebuffs) {
								if (EffectDebuffs[efx]==effectId) {
									ruleEffect = efx;
									break;
								}
							}
						}
						var c = new t.ChampCondition(true, 1, ruleEffect, buffDebuff, slots, minTier);
						conditions.push(c);
					}
				}
				if (conditions.length > 0) {
					var rule = new t.ChampRule(type, faction, conditions, true);
					t.SalvageAddRule(rule);
				}
			}
			saveOptions();
			if (GotRules) { ById('btchampSalvageMessages').innerHTML = tx("Salvage rules automatically generated")+"!"; }
			else { ById('btchampSalvageMessages').innerHTML = tx("No rules found")+" :("; }
			t.paint_salvage_rules();
		}, false);

		ById('btchampsalvageSave').addEventListener ('click',function() {
			var Export = {};
			Export.SalvageRuleSet = Options.ChampOptions.SalvageRuleSet;
			uriContent = 'data:application/octet-stream;content-disposition:attachment;filename=file.txt,' + encodeURIComponent(JSON2.stringify(Export));
			Tabs.Options.saveConfig(uriContent,'champ_salvage_'+getServerId()+'_'+uW.tvuid+'.txt');
		},false);

		ById('btchampsalvageLoad').addEventListener ('click',function() {
			ById('btchampSalvageMessages').innerHTML = '&nbsp;'
			var fileInput = ById("btchampsalvageLoadFile");
			var files = fileInput.files;
			if (files.length == 0) {
				ById('btchampSalvageMessages').innerHTML = '<span style="color:#800;">'+tx('Please select a salvage rules file')+'</span>';
				return;
			}
			var file = files[0];

			var reader = new FileReader();

			reader.onload = function (e) {
				var Import = JSON2.parse(e.target.result);
				if (Import.SalvageRuleSet) {
					for (var k=0;k<Import.SalvageRuleSet.length;k++) {
						var faction = Import.SalvageRuleSet[k].faction;
						var type = Import.SalvageRuleSet[k].type;
						var advanced = Import.SalvageRuleSet[k].advancedrule||false;
						var conditions = [];
						for (var i=0;i<Import.SalvageRuleSet[k].conditions.length;i++) {
							var cond = Import.SalvageRuleSet[k].conditions[i];
							var c = new t.ChampCondition(cond.mustHave, cond.number, cond.effect, cond.buffType, cond.slots, cond.minTier);
							conditions.push(c);
						}
						var rule = new t.ChampRule(type, faction, conditions, advanced);
						t.SalvageAddRule(rule);
					}
					saveOptions();
					ById('btchampSalvageMessages').innerHTML = tx('New salvage rules loaded');
					t.SalvageItems = []; // force reset of items to salvage
					t.paint_salvage_rules();
				}
				else {
					if (matTypeof(Import)=="array") { // TCO RULE SET
						for (var k=0;k<Import.length;k++) {
							var faction = Import[k].faction||"any";
							var type = Import[k].type||"any";
							var advanced = Import.advancedrule||false;
							var conditions = [];
							if (Import[k].conditions) {
								for (var i=0;i<Import[k].conditions.length;i++) {
									var cond = Import[k].conditions[i];
									var NewEffect = t.getEffect(cond.effect);
									if (NewEffect!="") {
										var c = new t.ChampCondition(cond.mustHave, cond.number, NewEffect, cond.buffType, cond.slots, cond.minTier);
										conditions.push(c);
									}
								}
							}
							var rule = new t.ChampRule(type, faction, conditions, advanced);
							t.SalvageAddRule(rule);
						}
						saveOptions();
						ById('btchampSalvageMessages').innerHTML = tx('TCO salvage rules imported - PLEASE CHECK!');
						t.SalvageItems = []; // force reset of items to salvage
						t.paint_salvage_rules();
					}
					else {
						ById('btchampSalvageMessages').innerHTML = tx('Invalid File')+'!';
					}
				}
			};
			reader.readAsText(file);
		},false);

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	display_salvager : function (){
		var t = Tabs.Champ;
		t.activepanel = "salvager";
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	paint_compare : function (){
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Compare");

		var selectedCard1 = 0;
		var selectedCard2 = 0;
		var selectedType1 = 0;
		var selectedType2 = 0;

		var m = '<div align=center style="height:450px;overflow-y:auto;">';
		m += '<div class="divHeader" align="center">'+tx('COMPARE CHAMPION HALL CARDS')+'</div>';
		m += '<TABLE width=90% class=xtabBR>';
		m += '<tr align=center><td width=50%/><td width=50%/></tr>';

		m += '<tr><td><div style="max-width:100%;"><b>'+uW.g_js_strings.commonstr.type+':&nbsp;</b><select id="btchampCompareType1">';
		m += '<option value="0">-- '+tx('ALL')+' --</option>';
		for (var type in chTypeStrings) {
			m += '<option value="' + (Number(type)+1) + '">' + uW.g_js_strings.champ[chTypeStrings[type]] + '</option>';
		}
		m += '</select></div></td>';

		m += '<td><div style="max-width:100%;"><b>'+uW.g_js_strings.commonstr.type+':&nbsp;</b><select id="btchampCompareType2">';
		m += '<option value="0">-- '+tx('ALL')+' --</option>';
		for (var type in chTypeStrings) {
			m += '<option value="' + (Number(type)+1) + '">' + uW.g_js_strings.champ[chTypeStrings[type]] + '</option>';
		}
		m += '</select></div></td>';

		m += '<tr><td><div style="max-width:100%;"><b>'+uW.g_js_strings.commonstr.item+':&nbsp;</b><select id="btchampCompare1">';
		m += '<option value="0" style="padding-left:15px;">-- '+tx('Select Champ Hall Item')+' --</option>';
		for (var k in uW.kocChampionItems) {
			var champ_item = uW.kocChampionItems[k];
			if (champ_item == null || !champ_item) continue;
			var OStyle = 'padding-left:15px;';
			if (champ_item.status<0) { OStyle += 'background-image:url('+BrokenIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
			else if (champ_item.equippedTo && champ_item.equippedTo!=0) { OStyle += 'background-image:url('+EquippedIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
			m += '<option style="'+OStyle+'" value="' + champ_item.equipmentId + '">' + champ_item.name + ' </option>';
		}
		m += '</select></div></td>';

		m += '<td><div style="max-width:100%;"><b>'+uW.g_js_strings.commonstr.item+':&nbsp;</b><select id="btchampCompare2">';
		m += '<option value="0" style="padding-left:15px;">-- '+tx('Select Champ Hall Item')+' --</option>';
		for (var k in uW.kocChampionItems) {
			var champ_item = uW.kocChampionItems[k];
			if (champ_item == null || !champ_item) continue;
			var OStyle = 'padding-left:15px;';
			if (champ_item.status<0) { OStyle += 'background-image:url('+BrokenIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
			else if (champ_item.equippedTo && champ_item.equippedTo!=0) { OStyle += 'background-image:url('+EquippedIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
			m += '<option style="'+OStyle+'" value="' + champ_item.equipmentId + '">' + champ_item.name + ' </option>';
		}
		m += '</select></div></td>';

		m += '<tr>';
		m += '<td id="btchampCompareItem1" style="overflow: visible; width: auto; height: auto;"/>';
		m += '<td id="btchampCompareItem2" style="overflow: visible; width: auto; height: auto;"/>';
		m += '</tr>';
		m += '<tr>';
		m += '<td id="btchampCompareInv1" style="overflow: visible; width: auto; height: auto;"/>';
		m += '<td id="btchampCompareInv2" style="overflow: visible; width: auto; height: auto;"/>';
		m += '</tr>';

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

		div.innerHTML = m;

		jQuery("#btchampCompareType1").change(function () {
			var chType = ById('btchampCompareType1').value;
			var chList = ById('btchampCompare1');
			if (selectedType1 != chType && chType != 0) {
				selectedCard1 = 0;
			}
			jQuery("#btchampCompare1").empty();
			var chOption = document.createElement('option');
			chOption.text = '-- '+tx('Select Champ Hall Item')+' --';
			chOption.value = 0;
			chOption.style = 'padding-left:15px;';
			chList.add(chOption);
			for (var k in uW.kocChampionItems) {
				var champ_item = uW.kocChampionItems[k];
				if (champ_item == null || !champ_item) continue;
				if (champ_item.type == chType || chType == 0) {
					var chOption = document.createElement('option');
					chOption.text = champ_item.name;
					chOption.value = champ_item.equipmentId;
					var OStyle = 'padding-left:15px;';
					if (Tabs.Reference.isBroken(champ_item)) { OStyle += 'background-image:url('+BrokenIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
					else if (champ_item.equippedTo && champ_item.equippedTo!=0) { OStyle += 'background-image:url('+EquippedIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
					chOption.style = OStyle;
					chList.add(chOption);
				}
			}

			if (selectedCard1 != 0) {
				jQuery("#btchampCompare1").val(selectedCard1);
			}

		});

		jQuery("#btchampCompareType2").change(function () {
			var chType = ById('btchampCompareType2').value;
			var chList = ById('btchampCompare2');
			if (selectedType2 != chType && chType != 0) {
				selectedCard2 = 0;
			}
			jQuery("#btchampCompare2").empty();
			var chOption = document.createElement('option');
			chOption.text = '-- '+tx('Select Champ Hall Item')+' --';
			chOption.value = 0;
			chOption.style = 'padding-left:15px;';
			chList.add(chOption);
			for (var k in uW.kocChampionItems) {
				var champ_item = uW.kocChampionItems[k];
				if (champ_item == null || !champ_item) continue;
				if (champ_item.type == chType || chType == 0) {
					var chOption = document.createElement('option');
					chOption.text = champ_item.name;
					chOption.value = champ_item.equipmentId;
					var OStyle = 'padding-left:15px;';
					if (Tabs.Reference.isBroken(champ_item)) { OStyle += 'background-image:url('+BrokenIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
					else if (champ_item.equippedTo && champ_item.equippedTo!=0) { OStyle += 'background-image:url('+EquippedIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
					chOption.style = OStyle;
					chList.add(chOption);
				}
			}

			if (selectedCard2 != 0) {
				jQuery("#btchampCompare2").val(selectedCard2);
			}
		});

		jQuery("#btchampCompare1").change(function () { changeCompareCard1(this); });

		jQuery("#btchampCompare1").keyup(function (event) { changeCompareCard1(this); });

		function changeCompareCard1(thisObj) {
			var chID = jQuery(thisObj).val();
			var chDisplay = ById('btchampCompareItem1');
			selectedCard1 = 0;
			selectedType1 = 0;
			if (chID!=0) {
				if (t.ConvertToCard(chID,chDisplay,true)) {
					t.GetInventory(chID,1,'btchampCompareInv1');
					selectedCard1 = chID;
					selectedType1 = uW.kocChampionItems[chID].type;
				}
				else {
					chDisplay.innerHTML = '<br><span class=boldRed>'+tx('Card no longer exists')+'!</span>';
				}
			}
			else {
				chDisplay.innerHTML = '&nbsp;';
			}
		}

		jQuery("#btchampCompare2").change(function () { changeCompareCard2(this); });

		jQuery("#btchampCompare2").keyup(function (event) { changeCompareCard2(this); });

		function changeCompareCard2(thisObj) {
			var chID = jQuery(thisObj).val();
			var chDisplay = ById('btchampCompareItem2');
			selectedCard2 = 0;
			selectedType2 = 0;
			if (chID!=0) {
				if (t.ConvertToCard(chID,chDisplay,true)) {
					t.GetInventory(chID,2,'btchampCompareInv2');
					selectedCard2 = chID;
					selectedType2 = uW.kocChampionItems[chID].type;
				}
				else {
					chDisplay.innerHTML = '<br><span class=boldRed>'+tx('Card no longer exists')+'!</span>';
				}
			}
			else {
				chDisplay.innerHTML = '&nbsp;';
			}
		}
	},

	display_compare : function (){
		var t = Tabs.Champ;
		t.activepanel = "compare";
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	paint_presets : function (){
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Presets");

		var m = '<DIV class=divHeader align=center>'+tx('CHAMPION BUILDER')+'</div>';
		m += '<a id=btchampPresetSearchLink class=divLink><div class="divHeader" align="left"><img id=btchampPresetSearchArrow height="10" src="'+RightArrow+'">&nbsp;'+tx('CARD SEARCH')+'</div></a>';
		m += '<div id=btchampPresetSearch align=center class="divHide">';

		m += '<div style="padding-top:3px;"><span style="float:left;">'+tx('Sort By')+':&nbsp;<select class=btInput id=btchampSearchSortEffects>';
		m += '<option value="0">-- '+tx('Select Effect')+' --</option>';
		for (var k=0;k<t.ChampEffects.length;k++) {
			var effect = t.ChampEffects[k];
			if (!CM.thronestats.effects[effect] || CM.thronestats.effects[effect][7]=="0" || DebuffOnly.indexOf(e)!=-1) {
				var effectName = CM.ChampionManager.getEffectName(effect);
				m += '<option value="' + effect + '">' + effectName + '</option>';
			}
		}
		m += '</select>&nbsp;';
		m += '<select class=btInput id=btchampSearchSortBuffType>';
		m += '<option value="both">'+tx('Either')+'</option>';
		m += '<option value="buff">'+tx('Buff')+'</option>';
		m += '<option value="debuff">'+tx('Debuff')+'</option>';
		m += '</select>&nbsp;';
		m += '<select class=btInput id=btchampSearchSortTierType>';
		m += '<option value="value">'+tx('Values')+'</option>';
		m += '<option value="tiers">'+tx('Tiers')+'</option>';
		m += '</select>&nbsp;<a id=btchampSearchAutoPop style="display:none;" class="inlineButton btButton red14"><span style="width:150px;display:inline-block;text-align:center;">'+tx('Auto-populate Preview')+'</span></a></span>';
		m += '<span style="float:right;">';
		m += '<input id=btchampSearchInactive type=checkbox>'+tx('Ignore Inactive Effects')+'&nbsp;&nbsp;&nbsp;';
		m += '<input id=btchampSearchBroken type=checkbox>'+tx('Ignore Broken Cards')+'&nbsp;&nbsp;&nbsp;';
		m += '<input id=btchampSearchEquipped type=checkbox>'+uW.g_js_strings.champ.fUnequipped+'</span>';
		m += '</span></div><br>';

		m += '<table width=100% cellpadding=0 cellspacing=0 class=xtab><tr><td>';
		m += '<table cellpadding=0 cellspacing=0 class=xtab>';
		m += '<tr><td style="padding-top:5px;"><b>'+tx('Effects')+'</b></td><td style="padding-top:5px;"><b>'+uW.g_js_strings.commonstr.type+'</b></td><td style="padding-top:5px;"><b>'+uW.g_js_strings.commonstr.quality+'</b></td><td style="padding-top:5px;"><b>'+uW.g_js_strings.commonstr.level+'</b></td><td style="padding-top:5px;"><b>'+uW.g_js_strings.commonstr.faction+'</b></td></tr>';
		m += '<tr><td><div id=btchampSearchEffectFilter style="width:300px;border:2px solid #ccc;height:96px;overflow-y:scroll;background-color:white;">';
		for (var k=0;k<t.ChampEffects.length;k++) {
			var effect = t.ChampEffects[k];
			m += '<INPUT id=btchampSearchEffect_'+effect+' type=checkbox CHECKED />'+CM.ChampionManager.getEffectName(effect)+'<br />';
		}
		m += '</div></td>';
		m += '<td><div id=btchampSearchTypeFilter style="width:150px;border:2px solid #ccc;height:96px;overflow-y:scroll;background-color: white;">';
		for (var type in chTypeStrings) {
			m += '<INPUT id=btchampSearchType_'+(Number(type)+1)+' type=checkbox CHECKED /><span style="text-transform:capitalize;">'+uW.g_js_strings.champ[chTypeStrings[type]]+'</span><br />';
		}
		m += '</div></td>';
		m += '<td><div id=btchampSearchQualityFilter style="width:150px;border:2px solid #ccc;height:96px;overflow-y:scroll;background-color: white;">';
		for (var k=0;k<=t.MAX_EFFECTS;k++) {
			var quality = cardQuality[k].toLowerCase();
			m += '<INPUT id=btchampSearchQuality_'+k+' type=checkbox CHECKED />'+uW.g_js_strings.throneRoom[quality]+'<br />';
		}
		m += '<INPUT id=btchampSearchQualityUnique type=checkbox CHECKED />'+uW.g_js_strings.throneRoom.unique+'<br />';
		m += '</div></td>';
		m += '<td><div id=btchampSearchLevelFilter style="width:100px;border:2px solid #ccc;height:96px;overflow-y:scroll;background-color: white;">';
		for (var k=0;k<=CM.CHAMPION.MAX_LEVELS;k++) {
			m += '<INPUT id=btchampSearchLevel_'+k+' type=checkbox CHECKED />'+k+'<br />';
		}
		m += '</div></td>';
		m += '<td><div id=btchampSearchFactionFilter style="width:100px;border:2px solid #ccc;height:96px;overflow-y:scroll;background-color: white;">';
		for (var k=0;k<cardFaction.length;k++) {
			var faction = cardFaction[k];
			m += '<INPUT id=btchampSearchFaction_'+faction+' type=checkbox CHECKED /><span style="text-transform:capitalize;">'+uW.g_js_strings.commonstr[faction]+'</span><br />';
		}
		m += '</div></td></tr>';
		m += '<tr><td style="padding-bottom:5px;">'+strButton8('All','id=btchampSearchEffectAll onclick="btchampSelectAllSearchEffect()"')+'&nbsp;'+strButton8('None','id=btchampSearchEffectNone onclick="btchampSelectNoneSearchEffect()"')+'</td>';
		m += '<td style="padding-bottom:5px;">'+strButton8('All','id=btchampSearchTypeAll onclick="btchampSelectAllSearchType()"')+'&nbsp;'+strButton8('None','id=btchampSearchTypeNone onclick="btchampSelectNoneSearchType()"')+'</td>';
		m += '<td style="padding-bottom:5px;">'+strButton8('All','id=btchampSearchQualityAll onclick="btchampSelectAllSearchQuality()"')+'&nbsp;'+strButton8('None','id=btchampSearchQualityNone onclick="btchampSelectNoneSearchQuality()"')+'</td>';
		m += '<td style="padding-bottom:5px;">'+strButton8('All','id=btchampSearchLevelAll onclick="btchampSelectAllSearchLevel()"')+'&nbsp;'+strButton8('None','id=btchampSearchLevelNone onclick="btchampSelectNoneSearchLevel()"')+'</td>';
		m += '<td style="padding-bottom:5px;">'+strButton8('All','id=btchampSearchFactionAll onclick="btchampSelectAllSearchFaction()"')+'&nbsp;'+strButton8('None','id=btchampSearchFactionNone onclick="btchampSelectNoneSearchFaction()"')+'</td></tr>';

		m += '</table>';
		m += '</td></tr></table>';
		m += '<div class="divHeader"><TABLE width=100% cellspacing=0><TR><TD class=xtab width=100>&nbsp;</td><TD class=xtab align=center>'+tx('SEARCH RESULTS')+'</td><TD class=xtab width=100 align=right><span id=btchampSearchCount></span>&nbsp;'+tx('Cards')+'</TD></tr></table></div>';
		m += '<div id=btchampSearchMsg align=center style="opacity:0.3;">'+tx('Click card to select or unselect')+'</div>';
		m += '<div id=btchampSearchResults style="min-height:200px;width:'+(GlobalOptions.btWinSize.x-20)+'px;overflow-x:scroll;">&nbsp;</div>';
		m += '</div><hr>';

		m += '<div style="width:100%;display:inline-block;">';
		m += '<table align=left class=xtabBR width=100% style="padding-right:0px;"><tr>';
		m += '<td style="width:50px;">'+tx('Champion')+':</td><td style="width:130px;"><select style="width:130px;" id=btchamppresetselect><option value="0" selected>-- '+tx('Select Champ')+' --</option><option value="-1">('+tx('NEW')+')</option>';
		for (var y in Seed.champion.champions) {
			if (Seed.champion.champions[y].championId) {
				var chkchamp = Seed.champion.champions[y];
				var champnum = parseIntNan(y)+1;
				m += '<option value="'+champnum+'">'+chkchamp.name+'</option>';
			}
		}
		var found = false;
		t.NextPresetNumber = 100;
		for (var y in Options.ChampOptions.LocalPresets) {
			found = true;
			m +='<option style="color:#888;" value="'+y+'">'+Options.ChampOptions.LocalPresets[y].name+'</option>';
		}
		if (found) t.NextPresetNumber = parseIntNan(y)+1;

		m += '</select></td><td><div id=btchamppresetcommitdiv style="height:20px;"><span style="text-align:center;display:inline-block;margin-top:3px;" id=btchamppresetMsg>&nbsp;</span></div></td></tr>';
		m += '<tr><td valign=top colspan=2><div class=divHeader><span id=btchamppresettitle style="display:inline-block;"><b>'+tx('Preview Stats')+'</b></span><span title="'+tx('Click to revert')+'" style="display:inline-block;vertical-align:middle;margin-top:-6px;font-weight:normal;float:right;margin-right:-12px;" id=btchamppresetinitial>&nbsp;</span></div><div id=btchamppresetpreview>&nbsp;</div><div id=btchamppresetpostdiv style="display:none;" align=center><br>'+strButton8('Post to Chat',' id=btchamppresetpost')+'</div></td><td style="padding-right:0px;"><div style="max-width:'+(GlobalOptions.btWinSize.x-220)+'px;overflow-x:auto;max-height:1000px;overflow-y:auto;padding-right:0px;"><table cellpadding=0 cellspacing=0 style="padding-right:2px;border:1px solid;border-collapse:collapse;" class=xtab width=100%><tr>';

		var LineBreak = 3;
		var DropWidth = 198;
		if (GlobalOptions.btWinSize.x == 750) {DropWidth=160;}

		for (var type_index = 0; type_index < chTypes.length; ++type_index) {
			if (type_index % LineBreak == 0) m += '</tr><tr>';
			m += '<td valign=top style="padding:2px;overflow:visible;width:180px;height:auto;border:1px solid;">';
			m += '<div id=btchampPresetItemHead' + chTypes[type_index] + ' ><div style="text-transform:capitalize;"><b>'+uW.g_js_strings.champ[chTypes[type_index]]+'</b></div></div>';
			m += '<div id="btchampPresetItemSelectContainer'+chTypes[type_index]+'" style="display:none;">'+htmlSelector({0:'-- '+tx('Please Choose')+' --'},0,' id="btchampPresetItemSelect'+chTypes[type_index]+'" style="width:'+DropWidth+'px;"')+'</div>';
			m += '<div><span id=btchampPresetItemRevert' + chTypes[type_index] + ' style="display:none;">'+strButton8('Revert',' id="btchampPresetItemRevertButton'+chTypes[type_index]+'"')+'</span>&nbsp;</div>';
			m += '<div id=btchampPresetItem' + chTypes[type_index] + ' style="min-height:200px;">&nbsp;</div>';
			m += '</td>';
		}

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

		div.innerHTML = m;

		t.fillPresetItemDropdowns();

		ById('btchampPresetSearchLink').addEventListener ('click', function () {ToggleMainDivDisplay("Champ",100,GlobalOptions.btWinSize.x,"btchampPresetSearch",false);t.SearchCards();}, false);

		for (var type_index = 0; type_index < chTypes.length; ++type_index) {
			ById('btchampPresetItemSelect'+chTypes[type_index]).addEventListener('change', function() {
				var champ_Type = this.id.split('btchampPresetItemSelect')[1];
				var chId = this.value;
				var div = ById('btchampPresetItem'+champ_Type);
				if (chId!=0) {
					t.PreviewCards[champ_Type] = chId;
					if (div) { t.ConvertToCard(chId,div,false,t.PreviewCardScale,false,true); }
				}
				else {
					delete t.PreviewCards[champ_Type];
					if (div) {
						div.innerHTML = '&nbsp;';
						div.className = '';
						jQuery(div).unbind();
					}
				}
				t.CheckPreviewRevert();
			}, false);

			ById('btchampPresetItemRevertButton'+chTypes[type_index]).addEventListener('click', function() {
				var champ_Type = this.id.split('btchampPresetItemRevertButton')[1];
				var chId=0;
				if (t.InitialCards[champ_Type]) chId = t.InitialCards[champ_Type];
				ById('btchampPresetItemSelect'+champ_Type).value = chId;
				var div = ById('btchampPresetItem'+champ_Type);
				if (chId!=0) {
					t.PreviewCards[champ_Type] = chId;
					if (div) { t.ConvertToCard(chId,div,false,t.PreviewCardScale,false,true); }
				}
				else {
					delete t.PreviewCards[champ_Type];
					if (div) {
						div.innerHTML = '&nbsp;';
						div.className = '';
						jQuery(div).unbind();
					}
				}
				t.CheckPreviewRevert();
			}, false);

		}

		ById('btchamppresetselect').addEventListener('change',t.PresetSelected, false);
		ById('btchamppresetpost').addEventListener('click',t.PostPreviewSlot, false);
		ById('btchampSearchAutoPop').addEventListener ('click', t.PreviewAutoPop, false);

		jQuery("#btchampSearchEffectFilter input").change(t.SearchCards);
		jQuery("#btchampSearchTypeFilter input").change(t.SearchCards);
		jQuery("#btchampSearchQualityFilter input").change(t.SearchCards);
		jQuery("#btchampSearchLevelFilter input").change(t.SearchCards);
		jQuery("#btchampSearchFactionFilter input").change(t.SearchCards);

		ById('btchampSearchInactive').addEventListener('change',t.SearchCards, false);
		ById('btchampSearchBroken').addEventListener('change',t.SearchCards, false);
		ById('btchampSearchEquipped').addEventListener('change',t.SearchCards, false);
		ById('btchampSearchSortEffects').addEventListener('change',t.SearchCards, false);
		ById('btchampSearchSortBuffType').addEventListener('change',t.SearchCards, false);
		ById('btchampSearchSortTierType').addEventListener('change',t.SearchCards, false);
	},

	display_presets : function (){
		var t = Tabs.Champ;
		t.activepanel = "presets";

		// check selected cards still exist!
		t.RefreshPresetDropdowns();
		t.fillPresetItemDropdowns();

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	display_options : function (){
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Options");
		t.activepanel = "options";

		var m = '<DIV class=divHeader align=center>'+tx('MANUAL CHAMPION OPTIONS')+'</div>';
		m += '<TABLE width="100%">';
		m += '<TR><TD class=xtab width=30><INPUT id=btchampSafetyOn type=checkbox /></td><TD class=xtab>'+tx('Disable manual upgrade if less than')+' <input class=btInput type=text id=btchampSafetyLimit size=10 maxlength=10 value="' + Options.ChampOptions.safetyLimit + '"> '+tx('aetherstone available')+'</td></tr>';
		m += '<TR><TD class=xtab><INPUT id=btchampChatMight type=checkbox /></td><TD class=xtab>'+tx('Show might in chat posts')+'</td></tr>';
		m += '<TR><TD class=xtab><INPUT id=btchampRemoveMastersTokens type=checkbox /></td><TD class=xtab>'+tx('Remove Forgemasters Tokens from the upgrade token list')+'</td></tr>';
		m += '<TR><TD class=xtab><INPUT id=btchampDefaultNextToken type=checkbox /></td><TD class=xtab>'+tx('Default next available Forgemasters Token on manual upgrade (overrides above!)')+'</td></tr>';

		m += '<TR><TD class=xtab><INPUT id=btchampNoEquippedSalvage type=checkbox /></td><TD class=xtab>'+tx('Remove Salvage Button if card is Equipped on a champion')+'</td></tr>';
		m += '<TR><TD class=xtab><INPUT id=btchampNoMassSalvage type=checkbox /></td><TD class=xtab>'+tx('Remove Mass Salvage Button')+'</td></tr>';
		m += '<TR><TD class=xtab><INPUT id=btchampSalvageSafety type=checkbox /></td><TD class=xtab>'+tx('Remove Salvage Button for the first')+'&nbsp;<input class=btInput id=btchampSalvageSafetyNum type=text size=3 maxlength=3 value="' + Options.ChampOptions.SalvageSafetyNum + '"> '+tx('cards')+'</td></tr>';
		m += '<TR><TD class=xtab><INPUT id=btchampSearchMenu type=checkbox /></td><TD class=xtab>'+tx('Display Champion item menu when clicking on items in Card Search')+'</td></tr>';

		m += '</table>';

		div.innerHTML = m;
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);

		ToggleOption('ChampOptions','btchampDefaultNextToken', 'DefaultNextToken');
		ToggleOption('ChampOptions','btchampSafetyOn', 'safetyOn');
		ToggleOption('ChampOptions','btchampRemoveMastersTokens', 'removeMastersTokens');
		ToggleOption('ChampOptions','btchampChatMight', 'ChatPostShowMight');

		ToggleOption('ChampOptions','btchampNoEquippedSalvage', 'NoEquippedSalvage');
		ToggleOption('ChampOptions','btchampNoMassSalvage', 'NoMassSalvage');
		ToggleOption('ChampOptions','btchampSalvageSafety', 'SalvageSafety');
		ToggleOption('ChampOptions','btchampSearchMenu', 'SearchMenu');

		ChangeIntegerOption('ChampOptions','btchampSafetyLimit','safetyLimit',0);
		ChangeIntegerOption('ChampOptions','btchampSalvageSafetyNum','SalvageSafetyNum',0);

	},

	display_log : function (){
		var t = Tabs.Champ;
		var div = ById("btChampDiv_Log");
		t.activepanel = "log";

		var ShowLog = [];
		if (t.logfilter == 'GENERAL') ShowLog = t.EventLog;
		if (t.logfilter == 'SUCCESS') ShowLog = t.SuccessLog;
		if (t.logfilter == 'REPAIR') ShowLog = t.RepairLog;
		if (t.logfilter == 'SALVAGE') ShowLog = t.SalvageLog;

		var m = '<DIV class=divHeader align=center>'+tx('CHAMPION HALL ACTIVITY LOG')+'</div>';
		m += '<div align="center"><TABLE cellSpacing=0 width=98% height=0%><tr><td class="xtab"> Area Filter:&nbsp;'+htmlSelector(t.logarealist, t.logfilter, 'id=btchamplogfilter class=btInput')+'<td class="xtab" align=right>('+ShowLog.length+'/'+t.logEntries+')</td></tr></table>';
		m += '<TABLE cellSpacing=0 width=98% height=0%><tr><td class="xtabHD" style="width:100px"><b>Date/Time</b></td><td class="xtabHD"><b>Log Message</b></td><td class="xtabHD" align=right>'+strButton14(tx('Clear Log'),'id=btchampClearLog')+'</td></tr></table>';
		m += '<div style="max-height:530px; height:530px; overflow-y:scroll" align="center"><TABLE cellSpacing=0 width=98% height=0%>';

		var r = 0;
		var logshow = false;

		var n = ShowLog.length;
		while (n--) {
			var a = ShowLog[n];

			logshow = true;
			r=r+1;
			rowClass = 'evenRow';
			var rem = (r % 2);
			if (rem == 1) rowClass = 'oddRow';

			m += '<tr class="'+rowClass+'">';
			m += '<TD style="width:100px" class=xtab>'+formatDateTime(a.ts)+'</td>';
			m += '<TD class=xtabBRTop>'+a.msg+'</td>';
			m += '</tr>';
		}

		if (!logshow) {
			m += '<tr><td colspan=2 class=xtab><div align="center"><br><br>No log entries</div></td></tr>';
		}

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

		div.innerHTML = m;
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);

		ById('btchamplogfilter').addEventListener('change', t.ChangeLogFilter, false);
		ById('btchampClearLog').addEventListener ('click', function() {t.ClearLog();}, false);
	},

	// PRESET FUNCTIONS

	GeneratePreviewStats : function (htmlEffects,Colours) {
		var t = Tabs.Champ;
		var chCards = [];
		for (var y in t.PreviewCards) {
			var champ_item = uW.kocChampionItems[t.PreviewCards[y]];
			if (champ_item) {
				chCards.push(champ_item.equipmentId);
			}
		}
		return t.GenerateChampionEffectsString(chCards,htmlEffects,Colours);
	},

	GenerateInitialStats : function () {
		var t = Tabs.Champ;

	},

	fillPresetItemDropdowns : function () {
		var t = Tabs.Champ;

		for (var type_index = 0; type_index < chTypes.length; ++type_index) {
			ById('btchampPresetItemSelect'+chTypes[type_index]).options.length = 0;
			var o = document.createElement("option");
			o.text = "-- "+tx('Select Item')+" --"
			o.style = 'padding-left:15px;"';
			o.value = 0;
			ById('btchampPresetItemSelect'+chTypes[type_index]).options.add(o);
		}

		for (var champId in uW.kocChampionItems) {
			var champItem = uW.kocChampionItems[champId];
			var champType = chTypeStrings[champItem.type-1];

			function AddOption (elemSelect,passItem,passId,passType) {
				var t = Tabs.Champ;
				if (elemSelect) {
					var o = document.createElement("option");
					o.text = passItem.name;
					o.value = passId;
					var OStyle = 'padding-left:15px;';
					if (Tabs.Reference.isBroken(passItem)) { OStyle += 'background-image:url('+BrokenIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
					else if (passItem.equippedTo && passItem.equippedTo!=0) {
						if (Seed.champion.champions[t.PreviewPreset-1] && passItem.equippedTo==Seed.champion.champions[t.PreviewPreset-1].championId) { OStyle += 'background-image:url('+EquippedIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
						else { OStyle += 'background-image:url('+EquippedOtherIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
					}
					o.style = OStyle;
					if (t.PreviewCards[passType] && t.PreviewCards[passType]==passId) o.selected = true;
					elemSelect.options.add(o);
				}

			}

			if (champItem.type!=6) { // not ring
				AddOption(ById('btchampPresetItemSelect'+champType),champItem,champId,champType);
			}
			else {
				AddOption(ById('btchampPresetItemSelect'+champType+'1'),champItem,champId,champType+'1');
				AddOption(ById('btchampPresetItemSelect'+champType+'2'),champItem,champId,champType+'2');
			}
		}

		for (var champType in t.PreviewCards) {
			var champId = t.PreviewCards[champType];
			if (!uW.kocChampionItems[champId]) {
				ById('btchampPresetItem'+champType).innerHTML = '&nbsp;';
			}
		}
	},

	PresetSelected : function () {
		var t = Tabs.Champ;
		t.PresetBusy = false;
		clearTimeout (t.PresetTimer);
		t.PreviewPreset = ById('btchamppresetselect').value;
		var Preset = t.PreviewPreset;

		if (Preset>0) {
			t.PreviewCards = {};
			t.InitialCards = {};
			if (Preset>=100) {
				if (Options.ChampOptions.LocalPresets[Preset].cards) {
					for (var ii=0;ii<Options.ChampOptions.LocalPresets[Preset].cards.length;ii++) {
						var chId = Options.ChampOptions.LocalPresets[Preset].cards[ii];
						if (uW.kocChampionItems[chId]) {
							var thisType = chTypeStrings[uW.kocChampionItems[chId].type-1];
							if (thisType=="ring") {
								if (!t.PreviewCards["ring1"] || t.PreviewCards["ring1"]==0) { thisType="ring1"; }
								else { thisType="ring2"; }
							}
							t.PreviewCards[thisType] = chId;
							t.InitialCards[thisType] = chId;
						}
					}
				}
				ById('btchamppresetinitial').innerHTML = '<TABLE cellspacing=0 cellpadding=0><TR><TD id="btchamppre'+Preset+'" class="xtab trimg" style="padding-right: 2px;"><a style="text-decoration:none;"><img style="margin-top:4px;margin-right:2px;width:16px;" src="'+ShieldImage+'"></a></td></tr></table>'; }
			else {
				var chkchamp = Seed.champion.champions[Preset-1];
				for (chId in uW.kocChampionItems) {
					if (uW.kocChampionItems[chId].equippedTo == chkchamp.championId) {
						var thisType = chTypeStrings[uW.kocChampionItems[chId].type-1];
						if (thisType=="ring") {
							if (!t.PreviewCards["ring1"] || t.PreviewCards["ring1"]==0) { thisType="ring1"; }
							else { thisType="ring2"; }
						}
						t.PreviewCards[thisType] = chId;
						t.InitialCards[thisType] = chId;
					}
				}
				ById('btchamppresetinitial').innerHTML = '<TABLE cellspacing=0 cellpadding=0><TR><TD id="btchamppre'+Preset+'" class="xtab trimg" style="padding-right: 2px;"><a style="text-decoration:none;"><img style="margin-top:4px;margin-right:2px;width:16px;" src="'+ChampImagePrefix+chkchamp.avatarId+ChampImageSuffix+'"></a></td></tr></table>';
			}

			ById('btchamppre'+Preset).addEventListener ('mouseover', function(){
				ById('btchamppresettitle').innerHTML = '<b>'+tx('Preset Stats')+'</b>';
				var slot = this.id.substring(10);
				if (slot<100) {
					var chkchamp = Seed.champion.champions[slot-1];
					var chCards = [];
					for (var y in uW.kocChampionItems) {
						var champ_item = uW.kocChampionItems[y];
						if (champ_item.equippedTo && champ_item.equippedTo==chkchamp.championId) {
							chCards.push(champ_item.equipmentId);
						}
					}
					ById('btchamppresetpreview').innerHTML = t.GenerateChampionEffectsString(chCards,true,true);
				}
				else {
					var chCards = [];
					for (var y in t.InitialCards) {
						var champ_item = uW.kocChampionItems[t.InitialCards[y]];
						if (champ_item) {
							chCards.push(champ_item.equipmentId);
						}
					}
					ById('btchamppresetpreview').innerHTML = t.GenerateChampionEffectsString(chCards,true,true);
				}
			},false);
			ById('btchamppre'+Preset).addEventListener ('mouseout', function(){
				ById('btchamppresettitle').innerHTML = '<b>'+tx('Preview Stats')+'</b>';
				t.PaintPreviewStats();
			},false);
			ById('btchamppre'+Preset).addEventListener ('click', function(){
				t.PresetSelected();
			},false);
		}
		else {
			t.PreviewCards = {};
			t.InitialCards = {};
			ById('btchamppresetinitial').innerHTML = '&nbsp;';
		}
		for (var type_index = 0; type_index < chTypes.length; ++type_index) {
			var div = ById('btchampPresetItem'+chTypes[type_index]);
			if (div) {
				div.innerHTML = '&nbsp;';
				div.className = '';
				jQuery(div).unbind();
			}
			if (Preset!=0) {
				ById('btchampPresetItemSelectContainer'+chTypes[type_index]).style.display='';
			}
			else {
				ById('btchampPresetItemSelectContainer'+chTypes[type_index]).style.display='none';
			}
		}
		for (var ii in t.PreviewCards) {
			var chId = t.PreviewCards[ii];
			if (uW.kocChampionItems[chId]) {
				t.ConvertToCard(chId,ById('btchampPresetItem' + ii),false,t.PreviewCardScale,false,true);
			}
		}
		t.fillPresetItemDropdowns();
		t.CheckPreviewRevert();

		if (Preset != 0) {
			var PresetName = '';
			if (Preset>=100) { PresetName = Options.ChampOptions.LocalPresets[Preset].name; }
			else if (Preset>0) { PresetName = Seed.champion.champions[Preset-1].name; }
			var NumPresets = {0:'('+tx('NEW')+')'};
			var PresetTags = {};
			if (Preset<0 || Preset>=100) {
				for (var y in Seed.champion.champions) {
					if (Seed.champion.champions[y].championId) {
						var chkchamp = Seed.champion.champions[y];
						var champnum = parseIntNan(y)+1;
						NumPresets[champnum]=chkchamp.name;
					}
				}
			}
			else {
				if (Preset>0) {
					var chkchamp = Seed.champion.champions[Preset-1];
					NumPresets[Preset]=chkchamp.name;
				}
			}
			for (var y in Options.ChampOptions.LocalPresets) {
				NumPresets[y] = Options.ChampOptions.LocalPresets[y].name;
				PresetTags[y] = 'style="color:#888;"';
			}

			ById('btchamppresetcommitdiv').innerHTML = '<span style="display:inline-block;float:left;">'+tx('Name')+':&nbsp;<INPUT class="btInput" id="btchamppresetLabel" style="width:120px;" maxlength=15 type=text value="'+PresetName+'" />&nbsp;</span><span id=btchamppresetdeletespan style="display:none;">&nbsp;'+strButton8(tx('Delete'),'id=btchamppresetdelete')+'&nbsp;</span><span style="text-align:center;display:inline-block;margin-top:3px;" id=btchamppresetMsg>&nbsp;</span><span style="display:inline-block;float:right;" id=btchamppresetcommitspan><a id=btchamppresetcommit class="inlineButton btButton blue14 disabled"><span style="width:120px;display:inline-block;text-align:center;">'+tx('Commit Changes')+'</span></a><a id=btchamppresetcommitcancel style="display:none;" class="inlineButton btButton red14"><span style="width:120px;display:inline-block;text-align:center;">'+tx('Cancel')+'</span></a>&nbsp;'+tx('to')+'&nbsp;'+htmlSelector(NumPresets,Preset,'id=btchamppresetcommitnum',PresetTags)+'</span>';
			ById('btchamppresetcommit').addEventListener('click',t.CommitPresetChanges,false);
			ById('btchamppresetcommitcancel').addEventListener('click',t.CancelPresetChanges,false);
			if (Preset>=100) { ById('btchamppresetdeletespan').style='margin-top:2px;display:inline-block;float:left'; }
			ById('btchamppresetdelete').addEventListener('click',t.DeleteLocalPreset,false);
			ById('btchamppresetLabel').addEventListener('change',t.PresetLabelChanged,false);
			ById('btchamppresetcommitnum').addEventListener('click',t.PresetCommitNumChanged,false);
		}
		else {
			ById('btchamppresetcommitdiv').innerHTML = '<span style="text-align:center;display:inline-block;margin-top:3px;" id=btchamppresetMsg>&nbsp;</span>';
		}

		t.PresetNameChanged = false;
		t.PresetTargetChanged = false;

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	PresetLabelChanged : function() {
		var t = Tabs.Champ;
		t.PresetNameChanged = true;
		jQuery('#btchamppresetcommit').removeClass("disabled").removeClass("blue14").addClass("red14");
	},

	PresetCommitNumChanged : function() {
		var t = Tabs.Champ;
		t.PresetTargetChanged = true;
		jQuery('#btchamppresetcommit').removeClass("disabled").removeClass("blue14").addClass("red14");
	},

	CheckCommitButton : function () {
		var t = Tabs.Champ;
		var PreviewChanged = false;
		for (var type_index = 0; type_index < chTypes.length; ++type_index) {
			var champType = chTypes[type_index];
			if ((t.PreviewCards[champType] && !t.InitialCards[champType]) || (!t.PreviewCards[champType] && t.InitialCards[champType]) || (t.PreviewCards[champType] && t.InitialCards[champType] && t.PreviewCards[champType] != t.InitialCards[champType])) {
				PreviewChanged = true;
				break;
			}
		}
		if (PreviewChanged || t.PresetNameChanged || t.PresetTargetChanged) {
			jQuery('#btchamppresetcommit').removeClass("disabled").removeClass("blue14").addClass("red14");
		}
		else {
			jQuery('#btchamppresetcommit').addClass("disabled").addClass("blue14").removeClass("red14");;
		}
	},

	PaintPreviewStats : function () {
		var t = Tabs.Champ;
		ById('btchamppresetpreview').innerHTML = t.GeneratePreviewStats(true,true);
		if (jQuery.isEmptyObject(t.PreviewCards)) { ById('btchamppresetpostdiv').style.display='none'; }
		else { ById('btchamppresetpostdiv').style.display=''; }
		if (t.PreviewPreset==0) { ById('btchamppresetpreview').style.display='none'; }
		else { ById('btchamppresetpreview').style.display=''; }
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	CheckPreviewRevert : function () {
		var t = Tabs.Champ;
		for (var type_index = 0; type_index < chTypes.length; ++type_index) {
			var champType = chTypes[type_index];
			if ((t.PreviewCards[champType] && !t.InitialCards[champType]) || (!t.PreviewCards[champType] && t.InitialCards[champType]) || (t.PreviewCards[champType] && t.InitialCards[champType] && t.PreviewCards[champType] != t.InitialCards[champType])) {
				ById('btchampPresetItemRevert'+chTypes[type_index]).style.display='';
			}
			else {
				ById('btchampPresetItemRevert'+chTypes[type_index]).style.display='none';
			}
		}
		t.CheckCommitButton();
		t.CheckSearchPreview();
		t.PaintPreviewStats();
	},

	CancelPresetChanges : function () {
		var t = Tabs.Champ;
		t.PresetBusy = false;
		clearTimeout(t.PresetTimer);
		var Preset = parseIntNan(ById('btchamppresetcommitnum').value);
		t.PreviewPreset = Preset;
		t.display_presets();
		t.PresetSelected();
		t.setPresetMessage(tx('Action cancelled')+'!');
	},

	CommitPresetChanges : function () {
		var t = Tabs.Champ;
		if (jQuery('#btchamppresetcommit').hasClass("disabled")) return;
		ById('btchamppresetcommit').style.display="none";
		ById('btchamppresetcommitcancel').style.display='';
		var Preset = parseIntNan(ById('btchamppresetcommitnum').value);
		if (Preset==0) { Preset = t.NextPresetNumber; }

		if (Preset>=100) {
			// local preset
			if (!Options.ChampOptions.LocalPresets[Preset]) Options.ChampOptions.LocalPresets[Preset] = {name:'Local '+(Preset-99)};
			if (t.PresetNameChanged) {
				Options.ChampOptions.LocalPresets[Preset].name = ById('btchamppresetLabel').value;
			}
			Options.ChampOptions.LocalPresets[Preset].cards = [];
			for (var champType in t.PreviewCards) {
				var champId = t.PreviewCards[champType];
				Options.ChampOptions.LocalPresets[Preset].cards.push(champId);
			}
			saveOptions();
			t.PreviewPreset = Preset;
			t.display_presets();
			t.PresetSelected();
			t.setPresetMessage(tx('Champion Saved'));
		}
		else {
			var chkchamp = Seed.champion.champions[Preset-1];
			// validate items are not equipped on other champs!
			var valid = true;
			for (var type_index = 0; type_index < chTypes.length; ++type_index) {
				if (t.PreviewCards[chTypes[type_index]]) {
					var equipId = t.PreviewCards[chTypes[type_index]];
					if (uW.kocChampionItems[equipId] && uW.kocChampionItems[equipId].equippedTo && uW.kocChampionItems[equipId].equippedTo!=chkchamp.championId) {
						valid = false;
						break;
					}
				}
			}
			if (!valid) {
				t.setPresetMessage(tx('Cannot equip cards already equipped on other champions'));
				ById('btchamppresetcommit').style.display='';
				ById('btchamppresetcommitcancel').style.display="none";
				return;
			}

			t.setPresetMessage(tx('Committing Changes to '+Seed.champion.champions[Preset-1].name+'...'));
			// kabam champion
			var equipped = {};
			for (chId in uW.kocChampionItems) {
				if (uW.kocChampionItems[chId].equippedTo == chkchamp.championId) {
					var thisType = chTypeStrings[uW.kocChampionItems[chId].type-1];
					if (thisType=="ring") {
						if (!equipped["ring1"] || equipped["ring1"]==0) { thisType="ring1"; }
						else { thisType="ring2"; }
					}
					equipped[thisType] = chId;
				}
			}
			t.UnequipQueue = [];
			t.EquipQueue = [];
			for (var type_index = 0; type_index < chTypes.length; ++type_index) {
				if (!t.PreviewCards[chTypes[type_index]] && equipped[chTypes[type_index]]) {
					// unequip old card from preset
					t.UnequipQueue.push(equipped[chTypes[type_index]]);
				}
				else {
					if (t.PreviewCards[chTypes[type_index]] && (!equipped[chTypes[type_index]] || (t.PreviewCards[chTypes[type_index]] != equipped[chTypes[type_index]]))) {
						if ((type_index==5||type_index==6) && equipped[chTypes[type_index]]) { // always unequip rings first!
							t.UnequipQueue.push(equipped[chTypes[type_index]]);
						}
						// equip new card to preset
						t.EquipQueue.push(t.PreviewCards[chTypes[type_index]]);
					}
				}
			}
			t.ErrorQueue = [];
			t.PresetBusy = true;
			t.PresetTimer = setTimeout(t.EquipPresetCards,0,Preset);
		}
	},

	EquipPresetCards : function(Preset) {
		var t = Tabs.Champ;
		if (!t.PresetBusy) return;
		clearTimeout (t.PresetTimer);
		if (t.UnequipQueue.length>0) {
			var chId = t.UnequipQueue.shift();
			if (uW.kocChampionItems[chId]) {
				t.unequipItem(uW.kocChampionItems[chId],Preset,t.EquipPresetCards);
			}
			else {
				t.log(tx('Unequip Error')+' - '+('Card does not exist'),'GENERAL',true);
				t.PresetTimer = setTimeout(t.EquipPresetCards,0,Preset);
			}
			return;
		}
		if (t.EquipQueue.length>0) {
			var chId = t.EquipQueue.shift();
			if (uW.kocChampionItems[chId]) {
				t.equipItem(uW.kocChampionItems[chId],Preset,t.EquipPresetCards);
			}
			else {
				t.log(tx('Equip Error')+' - '+('Card does not exist'),'GENERAL',true);
				t.PresetTimer = setTimeout(t.EquipPresetCards,0,Preset);
			}
			return;
		}
		if (t.PresetNameChanged) {
			t.ChangeChampName(Preset,ById('btchamppresetLabel').value);
		}
		else {
			t.PresetBusy = false;
			t.PreviewPreset = Preset;
			t.display_presets();
			t.PresetSelected();
			t.setPresetMessage(tx('Complete')+'!');
		}
	},

	unequipItem: function (I, preset, notify) {
		var t = Tabs.Champ;
		if (!I) return;
		if (!preset) preset = CM.ChampionManager.get("selectedChampion")+1;

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action = CM.CHAMPION.CEI_TAKE_OFF;
		params.cityId = uW.currentcityid;
		params.eid = I.equipmentId;
		params.championId = Seed.champion.champions[preset-1].championId;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					uW.kocChampionItems[I.equipmentId].equippedTo = null;
					t.setPresetMessage(tx('Unequipping')+' '+chTypeStrings[I.type-1]+'...');
					t.refreshInventory();
					if (notify && t.PresetBusy) { t.PresetTimer = setTimeout(notify,t.CHAMP_DELAY*1000,preset); }
				}
				else {
					t.log(tx('Unequip Error')+' - '+rslt.msg,'GENERAL',true);
					t.setPresetMessage('<span class=boldRed>'+tx('Error unequipping')+' '+chTypeStrings[I.type-1]+'...</span>');
					if (notify && t.PresetBusy) { t.PresetTimer = setTimeout(notify,1000,preset); }
				}
			},
			onFailure: function () {
				t.setPresetMessage('<span class=boldRed>'+tx('Server Error')+'</span>');
				t.log(tx('Unequip Error')+' - '+tx('Server Error'),'GENERAL',true);
			},
		},true); // noretry
	},

	equipItem: function (I, preset, notify) {
		var t = Tabs.Champ;
		if (!I) return;
		if (!preset) preset = CM.ChampionManager.get("selectedChampion")+1;

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action = CM.CHAMPION.CEI_PUT_ON;
		params.cityId = uW.currentcityid;
		params.eid = I.equipmentId;
		params.championId = Seed.champion.champions[preset-1].championId;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					for (var eq in uW.kocChampionItems) {
						var champ_item = uW.kocChampionItems[eq];
						if (champ_item.equippedTo && champ_item.equippedTo==params.championId && champ_item.type==I.type && I.type!=CM.CHAMPION.TYPE_ID_RING) {
							champ_item.equippedTo = null;
						}
					}
					uW.kocChampionItems[I.equipmentId].equippedTo = params.championId;
					t.setPresetMessage(tx('Equipping')+' '+chTypeStrings[I.type-1]+'...');
					t.refreshInventory();
					if (notify && t.PresetBusy) { t.PresetTimer = setTimeout(notify,t.CHAMP_DELAY*1000,preset); }
				}
				else {
					t.log(tx('Equip Error')+' - '+rslt.msg,'GENERAL',true);
					t.setPresetMessage('<span class=boldRed>'+tx('Error equipping')+' '+chTypeStrings[I.type-1]+'...</span>');
					if (notify && t.PresetBusy) { t.PresetTimer = setTimeout(notify,1000,preset); }
				}
			},
			onFailure: function () {
				t.setPresetMessage('<span class=boldRed>'+tx('Server Error')+'</span>');
				t.log(tx('Equip Error')+' - '+tx('Server Error'),'GENERAL',true);
			},
		},true); // noretry
	},

	ChangeChampName : function(preset,Name) {
		var t = Tabs.Champ;
		t.setPresetMessage(tx('Changing champion name')+'...');

		if (!preset) preset = CM.ChampionManager.get("selectedChampion")+1;

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.championId = Seed.champion.champions[preset-1].championId;
		params.name = Name;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/updateChampionInfo.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					Seed.champion.champions[preset-1].name = Name;
				}
				t.PresetBusy = false;
				t.PreviewPreset = preset;
				t.display_presets();
				t.PresetSelected();
				if (rslt.ok) { t.setPresetMessage(tx('Complete')+'!'); }
				else { t.setPresetMessage('<span class=boldRed>'+rslt.msg+'</span>'); }
			},
			onFailure: function () {
				t.PresetBusy = false;
				t.PreviewPreset = preset;
				t.display_presets();
				t.PresetSelected();
				t.setPresetMessage('<span class=boldRed>'+tx('Server Error')+'</span>');
			},
		},true); // noretry
	},

	DeleteLocalPreset : function () {
		var t = Tabs.Champ;
		var Preset = t.PreviewPreset;
		if (Preset>=100) {
			// local preset
			if (Options.ChampOptions.LocalPresets[Preset]) {
				delete Options.ChampOptions.LocalPresets[Preset];
				saveOptions();
				t.PreviewPreset = 0;
				t.display_presets();
				t.PresetSelected();
				t.setPresetMessage(tx('Champion Deleted'));
			}
		}
	},

	setPresetMessage : function (msg) {
		ById('btchamppresetMsg').innerHTML = '&nbsp;&nbsp;&nbsp;'+msg;
	},

	RefreshPresetDropdowns : function () {
		var t = Tabs.Champ;
		ById('btchamppresetselect').options.length = 0;
		var o = document.createElement("option");
		o.text = "-- "+tx('Select Champ')+" --"
		o.value = 0;
		ById('btchamppresetselect').options.add(o);
		var o = document.createElement("option");
		o.text = "("+tx('NEW')+")"
		o.value = -1;
		if (t.PreviewPreset == -1) o.selected = true;
		ById('btchamppresetselect').options.add(o);

		for (var y in Seed.champion.champions) {
			if (Seed.champion.champions[y].championId) {
				var chkchamp = Seed.champion.champions[y];
				var champnum = parseIntNan(y)+1;
				var o = document.createElement("option");
				o.text = chkchamp.name;
				o.value = champnum;
				if (t.PreviewPreset == champnum) o.selected = true;
				ById('btchamppresetselect').options.add(o);
			}
		}
		var found = false;
		t.NextPresetNumber = 100;
		for (var y in Options.ChampOptions.LocalPresets) {
			found = true;
			var o = document.createElement("option");
			o.text = Options.ChampOptions.LocalPresets[y].name;
			o.value = y;
			o.style = 'color:#888;';
			if (t.PreviewPreset == y) o.selected = true;
			ById('btchamppresetselect').options.add(o);
		}
		if (found) t.NextPresetNumber = parseIntNan(y)+1;

		if (ById('btchamppresetcommitnum')) {
			ById('btchamppresetcommitnum').options.length = 0;
			var o = document.createElement("option");
			o.text = "("+tx('NEW')+")"
			o.value = 0;
			ById('btchamppresetcommitnum').options.add(o);

			if (t.PreviewPreset<0 || t.PreviewPreset>=100) {
				for (var y in Seed.champion.champions) {
					if (Seed.champion.champions[y].championId) {
						var chkchamp = Seed.champion.champions[y];
						var champnum = parseIntNan(y)+1;
						var o = document.createElement("option");
						o.text = chkchamp.name;
						o.value = champnum;
						if (t.PreviewPreset == champnum) o.selected = true;
						ById('btchamppresetcommitnum').options.add(o);
					}
				}
			}
			else {
				if (t.PreviewPreset>0) {
					var chkchamp = Seed.champion.champions[t.PreviewPreset-1];
					var o = document.createElement("option");
					o.text = chkchamp.name;
					o.value = t.PreviewPreset;
					o.selected = true;
					ById('btchamppresetcommitnum').options.add(o);
				}
			}
			for (var y in Options.ChampOptions.LocalPresets) {
				var o = document.createElement("option");
				o.text = Options.ChampOptions.LocalPresets[y].name;
				o.value = y;
				o.style = 'color:#888;';
				if (t.PreviewPreset == y) o.selected = true;
				ById('btchamppresetcommitnum').options.add(o);
			}
		}
	},

	SelectAllSearchEffect : function () {
		var t = Tabs.Champ;
		for (var k=0;k<t.ChampEffects.length;k++) {
			var effect = t.ChampEffects[k];
			ById("btchampSearchEffect_"+effect).checked = true;
		}
		t.SearchCards();
	},

	SelectNoneSearchEffect : function () {
		var t = Tabs.Champ;
		for (var k=0;k<t.ChampEffects.length;k++) {
			var effect = t.ChampEffects[k];
			ById("btchampSearchEffect_"+effect).checked = false;
		}
		t.SearchCards();
	},

	SelectAllSearchType : function () {
		var t = Tabs.Champ;
		for (var type in chTypeStrings) {
			ById("btchampSearchType_"+(Number(type)+1)).checked = true;
		}
		t.SearchCards();
	},

	SelectNoneSearchType : function () {
		var t = Tabs.Champ;
		for (var type in chTypeStrings) {
			ById("btchampSearchType_"+(Number(type)+1)).checked = false;
		}
		t.SearchCards();
	},

	SelectAllSearchQuality : function () {
		var t = Tabs.Champ;
		for (var k=0;k<=t.MAX_EFFECTS;k++) {
			ById("btchampSearchQuality_"+k).checked = true;
		}
		ById("btchampSearchQualityUnique").checked = true;
		t.SearchCards();
	},

	SelectNoneSearchQuality : function () {
		var t = Tabs.Champ;
		for (var k=0;k<=t.MAX_EFFECTS;k++) {
			ById("btchampSearchQuality_"+k).checked = false;
		}
		ById("btchampSearchQualityUnique").checked = false;
		t.SearchCards();
	},

	SelectAllSearchLevel : function () {
		var t = Tabs.Champ;
		for (var k=0;k<=CM.CHAMPION.MAX_LEVELS;k++) {
			ById("btchampSearchLevel_"+k).checked = true;
		}
		t.SearchCards();
	},

	SelectNoneSearchLevel : function () {
		var t = Tabs.Champ;
		for (var k=0;k<=CM.CHAMPION.MAX_LEVELS;k++) {
			ById("btchampSearchLevel_"+k).checked = false;
		}
		t.SearchCards();
	},

	SelectAllSearchFaction : function () {
		var t = Tabs.Champ;
		for (var k=0;k<cardFaction.length;k++) {
			var faction = cardFaction[k];
			ById("btchampSearchFaction_"+faction).checked = true;
		}
		t.SearchCards();
	},

	SelectNoneSearchFaction : function () {
		var t = Tabs.Champ;
		for (var k=0;k<cardFaction.length;k++) {
			var faction = cardFaction[k];
			ById("btchampSearchFaction_"+faction).checked = false;
		}
		t.SearchCards();
	},

	SearchCards : function () {
		var t = Tabs.Champ;
		t.SearchResults = [];
		var m = '<table align=left class=xtabBR><tr>';

		// search for matching cards

		for (champId in uW.kocChampionItems) {
			var champItem = uW.kocChampionItems[champId];

			// apply filters
			var faction = cardFaction[champItem.faction-1];
			var level = champItem.level;
			var champtype = champItem.type;
			var quality = champItem.rarity;
			if (quality>t.MAX_EFFECTS) quality=t.MAX_EFFECTS; // uniques are rarity 6 (for now!) but we don't need to do it like that...
			var unique = champItem.unique != 0;
			var isBroken = Tabs.Reference.isBroken(champItem);
			var isEquipped = champItem.equippedTo != 0;

			if (ById('btchampSearchBroken').checked && isBroken) continue;
			if (ById('btchampSearchEquipped').checked && isEquipped) continue;
			if (!(ById('btchampSearchQualityUnique').checked) && unique) continue;
			if (!(ById('btchampSearchQuality_' + quality).checked) && !unique) continue;
			if (!(ById('btchampSearchFaction_' + faction).checked)) continue;
			if (!(ById('btchampSearchLevel_' + level).checked)) continue;
			if (!(ById('btchampSearchType_' + champtype).checked)) continue;

			// effects filter

			var rejectcard = true;
			for (var k in champItem.effects) {
				var inactive = (parseInt(k) > parseInt(quality));
				if (ById('btchampSearchInactive').checked && inactive) continue;
				if ((ById('btchampSearchEffect_' + champItem.effects[k].id).checked)) {
					rejectcard = false;
					break;
				}
			}
			if (rejectcard) continue;

			t.SearchResults.push(champItem.equipmentId);
		}

		// sort if required

		if (ById('btchampSearchSortEffects').value!=0) {
			t.SearchResults.sort(function (a,b) { return SortChampValue(b) - SortChampValue(a); });
		}

		function SortChampValue (chId) {
			var t = Tabs.Champ;
			var retValue = 0;
			var EffectSearch = ById('btchampSearchSortEffects').value;
			var EffectSearchNum = parseIntNan(EffectSearch);
			var BuffType = ById('btchampSearchSortBuffType').value;
			var TierType = ById('btchampSearchSortTierType').value;
			y = uW.kocChampionItems[chId];
			if (!y) return +retValue;
			var quality = y.rarity || 0;
			for (var O in y["effects"]) {
				var N = y["effects"][O];
				var i = +O;
				if (i > quality && (ById('btchampSearchInactive').checked)) { return +retValue; }
				var effect = N["id"];
				if (EffectSearchNum<200) {
					if (effect==EffectDebuffs[EffectSearch] && BuffType != "buff") {
						if (TierType=="value") { retValue -= parseFloat(getCHSlotStat(N,y.level)); }
						else { retValue -= t.getCHTier(N); }
					}
					else if (effect==EffectSearch && BuffType != "debuff") {
						if (TierType=="value") { retValue += parseFloat(getCHSlotStat(N,y.level)); }
						else { retValue += t.getCHTier(N); }
					}
				}
				else {
					if (effect==EffectSearch) {
						if (EffectSearchNum<220 || (EffectSearchNum>=300 && EffectSearchNum<400)) {
							if (TierType=="value") { retValue += parseFloat(getCHSlotStat(N,y.level)); }
							else { retValue += t.getCHTier(N); }
						}
						else {
							if (TierType=="value") { retValue -= parseFloat(getCHSlotStat(N,y.level)); }
							else { retValue -= t.getCHTier(N); }
						}
					}
				}
			}
			return +retValue;
		};

		// display results

		for (var k=0;k<t.SearchResults.length;k++) {
			var chId = t.SearchResults[k];
			m += '<td style="vertical-align:top;"><div id="btchampSearchItem_'+chId+'" style="cursor:pointer;border:3px solid transparent;">&nbsp;</div></td>';
		}
		m += '</tr></table>';
		ById('btchampSearchResults').innerHTML = m;

		for (var k=0;k<t.SearchResults.length;k++) {
			var chId = t.SearchResults[k];
			t.ConvertToCard(chId,ById('btchampSearchItem_' + chId),false,t.PreviewCardScale,!Options.ChampOptions.SearchMenu,true,true);
			if (!Options.ChampOptions.SearchMenu) {
				jQuery('#btchampSearchItem_' + chId).click(function () {
					var chId = jQuery(this).attr("class");
					t.ClickedSearchCard(chId);
				});
			}
		}

		ById('btchampSearchCount').innerHTML = t.SearchResults.length;
		t.CheckSearchPreview();

		if(ById('btchampSearchSortEffects').value!=0) {
			ById('btchampSearchAutoPop').style.display='';
		}
		else {
			ById('btchampSearchAutoPop').style.display='none';
		}

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	getCHTier : function (N) {
		var percent = 0;
		tier = parseInt(N.tier);
		var p = ChampionStatTiers[N.id][tier];
		while (!p && (tier > 0)) { tier--; p = ChampionStatTiers[N.id][tier]; }
		if (p) { // can't find stats for tier
			var percent = +p.base || 0;
		}
		return percent;
	},
	
	ClickedSearchCard : function (chId) {
		var t = Tabs.Champ;
		var champItem = uW.kocChampionItems[chId];
		if (champItem) {
			if (ById('btchamppresetselect').value==0) { ById('btchamppresetselect').value=-1; t.PresetSelected(); }

			var champType = chTypeStrings[champItem.type-1];
			if (champType=="ring") {
				if (t.PreviewCards["ring1"] && t.PreviewCards["ring1"]==champItem.equipmentId) {
					champType="ring1";
				}
				else {
					if (t.PreviewCards["ring2"] && t.PreviewCards["ring2"]==champItem.equipmentId) {
						champType="ring2";
					}
					else {
						if (!t.PreviewCards["ring1"] || t.PreviewCards["ring1"]==0) { champType="ring1"; }
						else { champType="ring2"; }
					}
				}
			}
			var div = ById('btchampPresetItem'+champType);
			if (t.PreviewCards[champType] && t.PreviewCards[champType]==chId) {
				delete t.PreviewCards[champType];
				ById('btchampPresetItemSelect'+champType).value = 0;
				if (div) {
					div.innerHTML = '&nbsp;';
					div.className = '';
					jQuery(div).unbind();
				}
			}
			else {
				t.PreviewCards[champType] = chId;
				ById('btchampPresetItemSelect'+champType).value = chId;
				if (div) { t.ConvertToCard(chId,div,false,t.PreviewCardScale,false,true); }
			}
			t.CheckPreviewRevert();
		}
	},

	CheckSearchPreview : function () {
		var t = Tabs.Champ;
		for (var k=0;k<t.SearchResults.length;k++) {
			var chId = t.SearchResults[k];
			var champItem = uW.kocChampionItems[chId];
			if (champItem) {
				var champType = chTypeStrings[champItem.type-1];
				var colour = 'transparent';
				if (champType!="ring") {
					if (t.PreviewCards[champType] && t.PreviewCards[champType]==chId) {
						colour = 'green';
					}
				}
				else {
					if ((t.PreviewCards["ring1"] && t.PreviewCards["ring1"]==chId) || (t.PreviewCards["ring2"] && t.PreviewCards["ring2"]==chId)) {
						colour = 'green';
					}
				}
				jQuery('#btchampSearchItem_' + chId).css('border', '3px solid '+colour);
			}
		}
	},

	PreviewAutoPop : function () {
		var t = Tabs.Champ;
		if (ById('btchamppresetselect').value==0) { ById('btchamppresetselect').value=-1; t.PresetSelected(); }
		var TempPreview = {};
		for (var k=0;k<t.SearchResults.length;k++) {
			var chId = t.SearchResults[k];
			var champItem = uW.kocChampionItems[chId];
			if (champItem) {
				var champType = chTypeStrings[champItem.type-1];
				if (champType=="ring") {
					if (!TempPreview["ring1"]) { TempPreview["ring1"] = chId; }
					else {
						if (!TempPreview["ring2"]) { TempPreview["ring2"] = chId; }
					}
				}
				else {
					if (!TempPreview[champType]) {
						TempPreview[champType] = chId;
					}
				}
			}
		}
		for (var champType in TempPreview) {
			var chId = TempPreview[champType];
			t.PreviewCards[champType] = chId;
			ById('btchampPresetItemSelect'+champType).value = chId;
			var div = ById('btchampPresetItem'+champType);
			if (div) { t.ConvertToCard(chId,div,false,t.PreviewCardScale,false,true); }
		}
		t.CheckPreviewRevert();
	},

	// LOG FUNCTIONS

	saveLogs : function () {
		var t = Tabs.Champ;
		GM_setValue ('ChampSuccessLog_'+getServerId()+'_'+uW.tvuid, JSON2.stringify(t.SuccessLog));
		GM_setValue ('ChampRepairLog_'+getServerId()+'_'+uW.tvuid, JSON2.stringify(t.RepairLog));
		GM_setValue ('ChampSalvageLog_'+getServerId()+'_'+uW.tvuid, JSON2.stringify(t.SalvageLog));
		GM_setValue ('ChampEventLog_'+getServerId()+'_'+uW.tvuid, JSON2.stringify(t.EventLog));
	},

	log : function (msg,area,error){
		var t = Tabs.Champ;
		if (!area) area = 'GENERAL';
		var ts = unixTime();
		if (area=='GENERAL') {
			while (t.EventLog.length >= t.logEntries) {	t.EventLog.shift();	}
			t.EventLog.push ({msg:msg, ts:ts});
			if (GlobalOptions.ExtendedDebugMode) {
				logit(msg); // also send to browser log
			}
		}
		if (area=='SUCCESS') {
			while (t.SuccessLog.length >= t.logEntries) { t.SuccessLog.shift();	}
			t.SuccessLog.push ({msg:msg, ts:ts});
		}
		if (area=='REPAIR') {
			while (t.RepairLog.length >= t.logEntries) { t.RepairLog.shift();	}
			t.RepairLog.push ({msg:msg, ts:ts});
		}
		if (area=='SALVAGE') {
			while (t.SalvageLog.length >= t.logEntries) { t.SalvageLog.shift(); }
			t.SalvageLog.push ({msg:msg, ts:ts});
		}

		if (error && GlobalOptions.ExtendedDebugMode) actionLog(msg,'CHAMP');

		if (tabManager.currentTab && tabManager.currentTab.name == 'Champ' && Options.btWinIsOpen && t.activepanel=='log') {
			t.display_log();
		}
	},

	ChangeLogFilter : function (evt) {
		var t = Tabs.Champ;
		t.logfilter = evt.target.value;
		t.display_log();
	},

	ClearLog : function () {
		var t = Tabs.Champ;
		if (t.logfilter == 'GENERAL') t.EventLog = [];
		if (t.logfilter == 'SUCCESS') t.SuccessLog = [];
		if (t.logfilter == 'REPAIR') t.RepairLog = [];
		if (t.logfilter == 'SALVAGE') t.SalvageLog = [];
		t.saveLogs();
		t.display_log();
	},

	// STATS FUNCTIONS

	AddToStats : function (Type,Quality,Level,Success) {
		var t = Tabs.Champ;
		if (Type=="E") {
			if (Success) {
				if (!Options.ChampOptions.Stats.EnhanceSuccess[Quality][Level]) Options.ChampOptions.Stats.EnhanceSuccess[Quality][Level] = 0;
				Options.ChampOptions.Stats.EnhanceSuccess[Quality][Level]++;
			}
			else {
				if (!Options.ChampOptions.Stats.EnhanceFail[Quality][Level]) Options.ChampOptions.Stats.EnhanceFail[Quality][Level] = 0;
				Options.ChampOptions.Stats.EnhanceFail[Quality][Level]++;
			}
		}
		if (Type=="U") {
			if (Success) {
				if (!Options.ChampOptions.Stats.UpgradeSuccess[Quality][Level]) Options.ChampOptions.Stats.UpgradeSuccess[Quality][Level] = 0;
				Options.ChampOptions.Stats.UpgradeSuccess[Quality][Level]++;
			}
			else {
				if (!Options.ChampOptions.Stats.UpgradeFail[Quality][Level]) Options.ChampOptions.Stats.UpgradeFail[Quality][Level] = 0;
				Options.ChampOptions.Stats.UpgradeFail[Quality][Level]++;
			}
		}
		saveOptions();
	},

	ClearStats : function (type) {
		var t = Tabs.Champ;
		if (type=="E") {
			Options.ChampOptions.Stats.EnhanceSuccess = {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}};
			Options.ChampOptions.Stats.EnhanceFail = {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}};
		}
		if (type=="U") {
			Options.ChampOptions.Stats.UpgradeSuccess = {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}};
			Options.ChampOptions.Stats.UpgradeFail = {0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}};
		}
		saveOptions();
		t.ViewUpgradeStats();
	},

	// UPGRADE FUNCTIONS

	toggleAutoUpgradeState: function(obj){
		var t = Tabs.Champ;
		obj = ById('btAutoChampUpgradeState');
		if (Options.ChampOptions.UpgradeRunning == true) {
			Options.ChampOptions.UpgradeRunning = false;
			obj.value = tx("Upgrade = OFF");
			t.UpgradeStatus = tx('Powered Off');
			t.UpgradeReturnStatus = '';
			t.PaintUpgradeStatus();
			clearTimeout(t.UpgradeTimer);
		}
		else {
			Options.ChampOptions.UpgradeRunning = true;
			obj.value = tx("Upgrade = ON");
			t.UpgradeStatus = tx('Starting')+'...';
			t.UpgradeReturnStatus = '';
			t.PaintUpgradeStatus();
			t.UpgradeQueueIndex = 0; // start from top of queue again
			t.UpgradeTimer = setTimeout(function () { t.doAutoUpgradeLoop();}, 0);
		}
		saveOptions();
		SetToggleButtonState('ChampUpgrade',Options.ChampOptions.UpgradeRunning,'Upgrade');
	},

	doAutoUpgradeLoop : function() {
		var t = Tabs.Champ;
		clearTimeout(t.UpgradeTimer);
		if (!Options.ChampOptions.UpgradeRunning) {
			t.UpgradeStatus = tx('Powered Off');
			t.UpgradeReturnStatus = '';
			t.PaintUpgradeStatus();
			return;
		}

		if (t.GemUseTripSwitch) {
			t.log(tx('Upgrader accidentally used gems - Please refresh game! Turning off'),'GENERAL',true);
			t.toggleAutoUpgradeState();
			uW.Modal.showAlert('<div align="center">'+tx('Upgrader accidentally used gems - Please refresh game! Turning off')+'</div>');
			return;
		}

		var BrokenItemInQueue = false;
		t.loopupgradeaction = false;
		t.autoupgradedelay = 0; // no delay if no action taken!

		if (t.UpgradeQueueIndex >= Options.ChampOptions.UpgradeQueue.length) {
			t.UpgradeQueueIndex = 0;
		}

		if (!t.BreakInProgress) {
			if (Options.ChampOptions.UpgradeQueue.length != 0) {
				// only process repair logic if repair queue inactive (otherwise it gets handled there)
				if (!Options.ChampOptions.RepairRunning) {
					var now = unixTime();
					if (Seed.queue_champion && Seed.queue_champion.end && Seed.queue_champion.end>now) {
						t.autoSpeedup("upgrade");
					}
					else {
						// Find first of any broken items in queue to repair!
						for (var Qitem = 0; Qitem < Options.ChampOptions.UpgradeQueue.length; Qitem++) {
							var QObj = Options.ChampOptions.UpgradeQueue[Qitem];
							if (QObj) {
								var champItem = uW.kocChampionItems[QObj.item];
								if (champItem && Tabs.Reference.isBroken(champItem)) {
									t.RepairItem(champItem.equipmentId,"upgrade");
									break;
								}
							}
						}
					}
				}

				// now loop from index position for next available queue entry to upgrade

				var GotEntry = false;
				for (var Qitem = t.UpgradeQueueIndex; Qitem < Options.ChampOptions.UpgradeQueue.length; Qitem++) {
					var QObj = Options.ChampOptions.UpgradeQueue[Qitem];
					if (QObj) {
						var champItem = uW.kocChampionItems[QObj.item];
						if (!champItem) {
//							t.log(tx('Unknown card removed from Upgrade Queue'),'GENERAL',true);
//							Options.ChampOptions.UpgradeQueue.splice(Qitem, 1);
//							Qitem--; //decrement
//							saveOptions();
						}
						else {
							if (QObj.action=="upgrade") {
								if (champItem.level>=QObj.maximum && QObj.status!=2) {
									QObj.status = 2;
									Options.ChampOptions.UpgradeQueue[Qitem].status = 2;
									saveOptions();
									t.paintUpgradeQueue();
								}
								if (champItem.level<QObj.maximum && QObj.status==2) {
									QObj.status = 1;
									Options.ChampOptions.UpgradeQueue[Qitem].status = 1;
									saveOptions();
									t.paintUpgradeQueue();
								}
							}
							if (QObj.action=="enhance") {
								if (champItem.rarity>=QObj.maximum && QObj.status!=2) {
									QObj.status = 2;
									Options.ChampOptions.UpgradeQueue[Qitem].status = 2;
									saveOptions();
									t.paintUpgradeQueue();
								}
								if (champItem.rarity<QObj.maximum && QObj.status==2) {
									QObj.status = 1;
									Options.ChampOptions.UpgradeQueue[Qitem].status = 1;
									saveOptions();
									t.paintUpgradeQueue();
								}
							}
							if (QObj.status!=2) {
								if (!Tabs.Reference.isBroken(champItem)) {
									GotEntry = true;
									t.UpgradeQueueIndex = Qitem;
									break;
								}
								else {
									BrokenItemInQueue = true;
									if (Options.ChampOptions.UpgradeOneItem) {
										t.UpgradeQueueIndex = Qitem; // one at a time selected, so not got entry, but also don't loop round for next item!
										break;
									}
								}
							}
						}
					}
				}
				if (GotEntry) {
					var QObj = Options.ChampOptions.UpgradeQueue[t.UpgradeQueueIndex];
					var champItem = uW.kocChampionItems[QObj.item];
					// We have an item for Upgrading/Enhancing!
					if (QObj.action=="upgrade") {
						t.UpgradeStatus = tx('Upgrading')+' '+champItem.name+' '+tx('to level')+' '+parseIntNan(champItem.level+1);
					}
					else {
						t.UpgradeStatus = tx('Enhancing')+' '+champItem.name+' '+tx('to')+' '+CardQuality(champItem.rarity+1);
					}
					t.UpgradeReturnStatus = '';

					var OKtoUpgrade = true;

					if (OKtoUpgrade) {
						// Select a boost item if required...
						var boostItem = 0;
						if (QObj.action=="upgrade") {
							var NextLevel = champItem.level+1;
							if (boostItem==0 && Options.ChampOptions.UpgradeUseMasters && NextLevel>=Options.ChampOptions.UpgradeUseMastersMin && NextLevel<=Options.ChampOptions.UpgradeUseMastersMax) {
								boostItem = Tabs.Champ.getNextAvailableForged(champItem,Options.ChampOptions.UpgradeBoostLevelOnly);
								if (t.FORGED_TOKEN_LEVELS[boostItem]>Options.ChampOptions.UpgradeUseMastersMax) { boostItem=0; }
							}
							if (Options.ChampOptions.UpgradeBoostMinLevel<=NextLevel) {
								if (boostItem==0 && Options.ChampOptions.UseEST && uW.ksoItems[21058].count > 0) { boostItem = 21058; }
								if (boostItem==0 && Options.ChampOptions.UseST && uW.ksoItems[21052].count > 0) { boostItem = 21052; }
								if (boostItem==0 && Options.ChampOptions.UseJST && uW.ksoItems[21051].count > 0) { boostItem = 21051; }
								if (boostItem==0 && Options.ChampOptions.UpgradeNoBoosts) {
									t.UpgradeReturnStatus = tx('No upgrade boosts available')+'!';
									OKtoUpgrade = false;
								}
							}
						}
						if (QObj.action=="enhance") {
							var NextQuality = champItem.rarity+1;
							if (Options.ChampOptions.EnhanceBoostMinQuality<=NextQuality) {
								if (boostItem==0 && Options.ChampOptions.UseGOM && uW.ksoItems[21002].count > 0) { boostItem = 21002; }
								if (boostItem==0 && Options.ChampOptions.UseLOM && uW.ksoItems[21001].count > 0) { boostItem = 21001; }
								if (boostItem==0 && Options.ChampOptions.EnhanceNoBoosts) {
									t.UpgradeReturnStatus = tx('No enhance boosts available')+'!';
									OKtoUpgrade = false;
								}
							}
						}
						if (boostItem!=0) {
							t.UpgradeStatus = t.UpgradeStatus+' '+tx('with')+' '+uW.itemlist["i"+boostItem].name;
						}
						t.PaintUpgradeStatus();
					}

					if (OKtoUpgrade) {
						if (QObj.action=="upgrade") {
							t.UpgradeItem(QObj.item,t.UpdateUpgradeStats,boostItem,true,t.UpgradeQueueIndex);
						}
						else {
							t.EnhanceItem(QObj.item,t.UpdateEnhanceStats,boostItem,true,t.UpgradeQueueIndex);
						}
					}

					if (!Options.ChampOptions.UpgradeOneItem) {
						t.UpgradeQueueIndex++; // go to next entry for next pass
					}
					t.autoupgradedelay = Options.ChampOptions.UpgradeInterval; // delay next action
				}
				else { // all queue entries complete or broken - loop round again... or One at a time, so leave it...
					if (BrokenItemInQueue) {
						t.UpgradeStatus = tx('Waiting for repair to complete')+'...';
						t.UpgradeReturnStatus = '';
					}
					else {
						if (t.UpgradeQueueIndex == 0) { // whole queue done!
							t.UpgradeStatus = tx('Upgrade queue completed')+'!';
							t.UpgradeReturnStatus = '';
						}
					}
					t.PaintUpgradeStatus();
					if (!Options.ChampOptions.UpgradeOneItem) {
						t.UpgradeQueueIndex = 0;
					}
					t.autoupgradedelay = Options.ChampOptions.UpgradeInterval; // delay next action
				}
			}
			else { // no queue! loop round again...
				t.UpgradeQueueIndex = 0;
				t.UpgradeStatus = tx('No cards in upgrade queue')+'!';
				t.UpgradeReturnStatus = '';
				t.PaintUpgradeStatus();
				t.autoupgradedelay = Options.ChampOptions.UpgradeInterval; // delay next action
			}
		}
		else {
			t.UpgradeStatus = tx('Upgrades suspended while champion hall cards are being broken')+'!';
			t.UpgradeReturnStatus = '';
			t.PaintUpgradeStatus();
			t.autoupgradedelay = Options.ChampOptions.UpgradeInterval; // delay next action
		}
		t.UpgradeTimer = setTimeout(function () { t.doAutoUpgradeLoop(); }, (t.autoupgradedelay * 1000));
	},

	UpdateUpgradeStats : function(rslt,chId,aetherbalance,Qitem) {
		var t = Tabs.Champ;
		var champItem = uW.kocChampionItems[chId];
		if (!champItem) {
			t.UpgradeReturnStatus = tx('Unknown Item')+'?';
		}
		else {
			if (rslt.ok) {
				if (rslt.success) {
					t.UpgradeReturnStatus = tx('Upgrade Successful')+'!';
					t.AddToStats('U',champItem.rarity,champItem.level,true);
					t.UpdateUpgradeQueue(champItem,Qitem,true);
				}
				else {
					t.UpgradeReturnStatus = tx('Upgrade Failed')+'!';
					t.AddToStats('U',champItem.rarity,champItem.level+1,false);
					var now = unixTime();
					if (!Seed.queue_champion || (Seed.queue_champion.end && Seed.queue_champion.end<now)) { // send to repair
						if (Tabs.Reference.isBroken(champItem) || rslt.break) {
							t.RepairItem(champItem.equipmentId,"upgrade");
						}
					}
					t.UpdateUpgradeQueue(champItem,Qitem,false);
				}
			}
		}
		t.PaintUpgradeStatus();
	},

	UpdateEnhanceStats : function(rslt,chId,aetherbalance,Qitem) {
		var t = Tabs.Champ;
		var champItem = uW.kocChampionItems[chId];
		if (!champItem) {
			t.UpgradeReturnStatus = tx('Unknown Item')+'?';
		}
		else {
			if (rslt.ok) {
				if (rslt.success) {
					t.UpgradeReturnStatus = tx('Enhance Successful')+'!';
					t.AddToStats('E',champItem.rarity,champItem.level,true);
					t.UpdateUpgradeQueue(champItem,Qitem,true);
				}
				else {
					t.UpgradeReturnStatus = tx('Enhance Failed')+'!';
					t.AddToStats('E',champItem.rarity+1,champItem.level,false);
					var now = unixTime();
					if (!(Seed.queue_champion && Seed.queue_champion.end && Seed.queue_champion.end>now)) { // repair not busy
						if (Tabs.Reference.isBroken(champItem) || rslt.break) {
							t.RepairItem(champItem.equipmentId,"upgrade");
						}
					}
					t.UpdateUpgradeQueue(champItem,Qitem,false);
				}
			}
		}
		t.PaintUpgradeStatus();
	},

	UpdateUpgradeQueue : function(champItem,Qitem,Success) {
		var t = Tabs.Champ;
		var QObj = Options.ChampOptions.UpgradeQueue[Qitem];
		if (QObj) {
			Options.ChampOptions.UpgradeQueue[Qitem].triesTotal ++;
			Options.ChampOptions.UpgradeQueue[Qitem].triesThis ++;
			Options.ChampOptions.UpgradeQueue[Qitem].triesLimiter ++;
			if (QObj.status==0) {
				Options.ChampOptions.UpgradeQueue[Qitem].status = 1;
				Options.ChampOptions.UpgradeQueue[Qitem].messages = tx('No upgrades yet')+'...';
			}

			if (QObj.action=="upgrade") {
				if (Success) {
					Options.ChampOptions.UpgradeQueue[Qitem].messages = tx('Upgraded to level')+' '+champItem.level+' '+tx('in')+' '+Options.ChampOptions.UpgradeQueue[Qitem].triesThis+' '+tx('attempts')+'.';
					Options.ChampOptions.UpgradeQueue[Qitem].triesThis = 0;
					Options.ChampOptions.UpgradeQueue[Qitem].triesLimiter = 0;
					if (champItem.level>=QObj.maximum) {
						Options.ChampOptions.UpgradeQueue[Qitem].status = 2;
					}
					var msg = champItem.name+' ['+champItem.equipmentId+'] '+Options.ChampOptions.UpgradeQueue[Qitem].messages;
					t.log(msg,'SUCCESS');
					if (Options.ChampOptions.WhisperToMe) { sendChat("/" + Seed.player.name + ' :::. |' + msg); }
					if (Options.ChampOptions.SendToInbox) { t.sendMail(Seed.player.name, tx('CHAMP: Upgrade Success')+': '+champItem.name, msg); }
				}
			}
			if (QObj.action=="enhance") {
				if (Success) {
					Options.ChampOptions.UpgradeQueue[Qitem].messages = tx('Enhanced to')+' '+CardQuality(champItem.rarity)+' '+tx('in')+' '+Options.ChampOptions.UpgradeQueue[Qitem].triesThis+' '+tx('attempts')+'.';
					Options.ChampOptions.UpgradeQueue[Qitem].triesThis = 0;
					Options.ChampOptions.UpgradeQueue[Qitem].triesLimiter = 0;
					if (champItem.rarity>=QObj.maximum) {
						Options.ChampOptions.UpgradeQueue[Qitem].status = 2;
					}
					var msg = champItem.name+' ['+champItem.equipmentId+'] '+Options.ChampOptions.UpgradeQueue[Qitem].messages;
					t.log(msg,'SUCCESS');
					if (Options.ChampOptions.WhisperToMe) { sendChat("/" + Seed.player.name + ' :::. |' + msg); }
					if (Options.ChampOptions.SendToInbox) { t.sendMail(Seed.player.name, tx('CHAMP: Enhance Success')+': '+champItem.name, msg); }

				}
			}
			if (!Success && Options.ChampOptions.UpgradeOneItem && Options.ChampOptions.UpgradeOneMax && parseIntNan(Options.ChampOptions.UpgradeQueue[Qitem].triesLimiter)>=Options.ChampOptions.UpgradeOneMaxAttempts) {
				// send to the back of the queue and reset...
				Options.ChampOptions.UpgradeQueue[Qitem].triesLimiter = 0;
				Options.ChampOptions.UpgradeQueue.push(Options.ChampOptions.UpgradeQueue.splice(Qitem, 1)[0]);
				t.log(champItem.name+' ['+champItem.equipmentId+']: '+tx('Upgrade/Enhance attempts limit reached - Card requeued'),'GENERAL');
			}
			saveOptions();
			t.paintUpgradeQueue();
		}
	},

	sendMail: function (sendTo, subject, msg) {
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.emailTo = sendTo;
		params.subject = subject;
		params.message = msg;
		params.requestType = "COMPOSED_MAIL";
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
			method:"post",
			parameters:params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					DeleteLastMessage();
				}
			}
		})
	},

	PaintUpgradeStatus : function () {
		var t = Tabs.Champ;
		var Stats = '';

		if (Options.ChampOptions.UpgradeRunning) {
			var Stats = '<span style="inline-block;float:right;margin-top:4px;">'+strButton8(tx('View Stats'),'id=btchampupgradeoverviewstats')+'</span>';
		}
		if (ById('btchampoverviewupgradestatusdiv')) ById('btchampoverviewupgradestatusdiv').innerHTML = t.UpgradeStatus+'<br><i>'+t.UpgradeReturnStatus+Stats+'</i>';
		if (ById('btchampupgradeoverviewstats')) ById('btchampupgradeoverviewstats').addEventListener('click',t.ViewUpgradeStats,false);
	},

	ViewUpgradeStats : function () {
		var t = Tabs.Champ;

		var HeadColour = 'rgba('+HEXtoRGB(Options.Colors.PanelText).r+','+HEXtoRGB(Options.Colors.PanelText).g+','+HEXtoRGB(Options.Colors.PanelText).b+',0.5)';

		var maxlevel = CM.CHAMPION.MAX_LEVELS;
		var maxquality = t.MAX_EFFECTS;

		var m = '<DIV class=divHeader align=center>'+tx('UPGRADE STATISTICS')+'</div>';
		m += '<DIV style="width:'+(GlobalOptions.btWinSize.x-10)+'px;overflow-x:scroll;"><TABLE cellpadding=2 cellspacing=0 align=left>';
		m += '<TR><TD class=xtabHD style="border-right:1px solid '+HeadColour+';">&nbsp;</td>';

		var c = 0;
		for (var i=maxlevel;i>0;i--) {
			c=c+1;
			colClass = 'evenRow';
			var rem = (c % 2);
			if (rem == 1) colClass = 'oddRow';
			m += '<TD width=30 class="xtabHD '+colClass+'" align=center>+'+i+'</td>';
		}
		m += '</tr>';

		var st = [];
		var ft = [];

		for (var j=0;j<=maxquality;j++) {
			m += '<TR><TD class=xtab style="border-right:1px solid '+HeadColour+';"><b>'+CardQuality(j)+'</b></td>';
			var c = 0;
			for (var i=maxlevel;i>0;i--) {
				c=c+1;
				colClass = 'evenRow';
				var rem = (c % 2);
				if (rem == 1) colClass = 'oddRow';
				var s = (Options.ChampOptions.Stats.UpgradeSuccess[j][i])?Options.ChampOptions.Stats.UpgradeSuccess[j][i]:0;
				var f = (Options.ChampOptions.Stats.UpgradeFail[j][i])?Options.ChampOptions.Stats.UpgradeFail[j][i]:0;
				if (!st[i]) st[i]=0;
				st[i] = st[i]+s;
				if (!ft[i]) ft[i]=0;
				ft[i] = ft[i]+f;
				m += '<TD width=30 class="xtab '+colClass+'" align=center>'+s+'/'+(s+f)+'</td>';
			}
			m += '</tr>';
		}
		m += '<TR><TD class=xtab style="border-right:1px solid '+HeadColour+';border-top:1px solid '+HeadColour+';"><b>'+tx('Totals')+'</b></td>';
		var c = 0;
		for (var i=maxlevel;i>0;i--) {
			c=c+1;
			colClass = 'evenRow';
			var rem = (c % 2);
			if (rem == 1) colClass = 'oddRow';
			m += '<TD width=30 class="xtab '+colClass+'" style="border-top:1px solid '+HeadColour+';" align=center><b>'+st[i]+'/'+(st[i]+ft[i])+'</b></td>';
		}
		m += '<TR><TD class=xtab style="border-right:1px solid '+HeadColour+';border-top:1px solid '+HeadColour+';"><b>'+tx('Percentage')+'</b></td>';
		var c = 0;
		for (var i=maxlevel;i>0;i--) {
			c=c+1;
			colClass = 'evenRow';
			var rem = (c % 2);
			if (rem == 1) colClass = 'oddRow';
			if (st[i]+ft[i]==0) { m += '<TD width=30 class="xtab '+colClass+'" style="border-top:1px solid '+HeadColour+';" align=center><b>--</b></td>'; }
			else { m += '<TD width=30 class="xtab '+colClass+'" style="border-top:1px solid '+HeadColour+';" align=center><b>'+(Math.round((st[i]/(st[i]+ft[i]))*100*100)/100)+'%</b></td>'; }
		}
		m += '</tr>';
		m += '</table></div>';
		m += '<DIV align=center>'+strButton14('Clear Stats','id=btchampClearUpgradeStats')+'</div><br>';

		m += '<DIV class=divHeader align=center>'+tx('ENHANCE STATISTICS')+'</div>';
		m += '<DIV style="width:'+(GlobalOptions.btWinSize.x-10)+'px;overflow-x:scroll;"><TABLE cellpadding=2 cellspacing=0 align=left>';
		m += '<TR><TD class=xtabHD style="border-right:1px solid '+HeadColour+';">&nbsp;</td>';
		m += '<TD width=30 class="xtabHD oddRow" style="border-right:1px solid '+HeadColour+';" align=center>'+tx('Percent')+'</td>';
		m += '<TD width=30 class="xtabHD evenRow" style="border-right:1px solid '+HeadColour+';" align=center>'+tx('Totals')+'</td>';

		var c = 0;
		for (var i=maxlevel;i>=0;i--) {
			c=c+1;
			colClass = 'evenRow';
			var rem = (c % 2);
			if (rem == 1) colClass = 'oddRow';
			m += '<TD width=30 class="xtabHD '+colClass+'" align=center>+'+i+'</td>';
		}
		m += '</tr>';

		var st = [];
		var ft = [];

		for (var i=maxlevel;i>=0;i--) {
			for (var j=1;j<=maxquality;j++) {
				var s = (Options.ChampOptions.Stats.EnhanceSuccess[j][i])?Options.ChampOptions.Stats.EnhanceSuccess[j][i]:0;
				var f = (Options.ChampOptions.Stats.EnhanceFail[j][i])?Options.ChampOptions.Stats.EnhanceFail[j][i]:0;
				if (!st[j]) st[j]=0;
				st[j] = st[j]+s;
				if (!ft[j]) ft[j]=0;
				ft[j] = ft[j]+f;
			}
		}

		for (var j=1;j<=maxquality;j++) {
			m += '<TR><TD class=xtab style="border-right:1px solid '+HeadColour+';"><b>'+CardQuality(j)+'</b></td>';
			if (st[j]+ft[j]==0) { m += '<TD width=30 class="xtab oddRow" style="border-right:1px solid '+HeadColour+';" align=center><b>--</b></td>'; }
			else { m += '<TD width=30 class="xtab oddRow" style="border-right:1px solid '+HeadColour+';" align=center><b>'+(Math.round((st[j]/(st[j]+ft[j]))*100*100)/100)+'%</b></td>'; }
			m += '<TD width=30 class="xtab evenRow" style="border-right:1px solid '+HeadColour+';" align=center><b>'+st[j]+'/'+(st[j]+ft[j])+'</b></td>';
			var c = 0;
			for (var i=maxlevel;i>=0;i--) {
				c=c+1;
				colClass = 'evenRow';
				var rem = (c % 2);
				if (rem == 1) colClass = 'oddRow';
				var s = (Options.ChampOptions.Stats.EnhanceSuccess[j][i])?Options.ChampOptions.Stats.EnhanceSuccess[j][i]:0;
				var f = (Options.ChampOptions.Stats.EnhanceFail[j][i])?Options.ChampOptions.Stats.EnhanceFail[j][i]:0;
				m += '<TD width=30 class="xtab '+colClass+'" align=center>'+s+'/'+(s+f)+'</td>';
			}
			m += '</tr>';
		}
		m += '</table></div>';
		m += '<DIV align=center>'+strButton14('Clear Stats','id=btchampClearEnhanceStats')+'</div>';

		var pop = new CPopup ('btUpgradeStatsPopup', 0, 0, 750, 400, true);
		pop.getMainDiv().innerHTML = m;
		pop.getTopDiv().innerHTML = '<CENTER><B>'+tx("Stats")+'</b></center>';
		pop.show (true);
		ResetFrameSize('btUpgradeStatsPopup',400,GlobalOptions.btWinSize.x);
		pop.centerMe (mainPop.getMainDiv());

		ById('btchampClearUpgradeStats').addEventListener ('click', function() {t.ClearStats("U");}, false);
		ById('btchampClearEnhanceStats').addEventListener ('click', function() {t.ClearStats("E");}, false);
	},

	update_upgrader : function () {
		var t = Tabs.Champ;

		t.LessMetallurgy = parseIntNan(Seed.items.i21001);
		t.Metallurgy = parseIntNan(Seed.items.i21002);
		t.Journeyman = parseIntNan(Seed.items.i21051);
		t.Smith = parseIntNan(Seed.items.i21052);
		t.Expert = parseIntNan(Seed.items.i21058);

		ById('btchampUseLOMLabel').innerHTML = t.LessMetallurgy;
		ById('btchampUseGOMLabel').innerHTML = t.Metallurgy;
		ById('btchampUseJSTLabel').innerHTML = t.Journeyman;
		ById('btchampUseSTLabel').innerHTML = t.Smith;
		ById('btchampUseESTLabel').innerHTML = t.Expert;

		// check queue item status

		for (var Qitem=0;Qitem<Options.ChampOptions.UpgradeQueue.length;Qitem++) {
			var QObj = Options.ChampOptions.UpgradeQueue[Qitem];
			if (QObj) {
				var champItem = uW.kocChampionItems[QObj.item];
				if (champItem) {
					if (QObj.status == 2) {
						champStatusClass = 'btchampSuccess';
					} else if (Tabs.Reference.isBroken(champItem)) {
						if (Seed.queue_champion && champItem.equipmentId == Seed.queue_champion.itemId) {
							champStatusClass = 'btchampHammer';
						} else {
							champStatusClass = 'btchampBroken';
						}
					} else {
						champStatusClass = 'btchampGoButton';
					}
					if (ById('btChampQueueState'+Qitem)) { ById('btChampQueueState'+Qitem).className = champStatusClass; }
				}
			}
		}

	},

	update_repairer : function () {
		var t = Tabs.Champ;

		t.Squire = parseIntNan(Seed.items.i1);
		t.Knight = parseIntNan(Seed.items.i2);
		t.Guinevere = parseIntNan(Seed.items.i3);
		t.Morgana = parseIntNan(Seed.items.i4);
		t.Arthur = parseIntNan(Seed.items.i5);
		t.Merlin = parseIntNan(Seed.items.i6);
		t.Divine = parseIntNan(Seed.items.i7);
		t.Epic = parseIntNan(Seed.items.i8);

		ById('btchampUseSHLabel').innerHTML = t.Squire;
		ById('btchampUseKHLabel').innerHTML = t.Knight;
		ById('btchampUseGHLabel').innerHTML = t.Guinevere;
		ById('btchampUseMHLabel').innerHTML = t.Morgana;
		ById('btchampUseAHLabel').innerHTML = t.Arthur;
		ById('btchampUseRHLabel').innerHTML = t.Merlin;
		ById('btchampUseDHLabel').innerHTML = t.Divine;
		ById('btchampUseEHLabel').innerHTML = t.Epic;

		// check queue item status

		var BrokenMight = 0;
		var BrokenTime = 0;

		for (var Qitem=0;Qitem<Options.ChampOptions.RepairQueue.length;Qitem++) {
			var QObj = Options.ChampOptions.RepairQueue[Qitem];
			if (QObj) {
				var champItem = uW.kocChampionItems[QObj.item];
				if (champItem) {
					if (Tabs.Reference.isBroken(champItem)) {
						BrokenMight += CardMight(champItem,true);
						if (Seed.queue_champion && champItem.equipmentId == Seed.queue_champion.itemId) {
							champStatusClass = 'btchampHammer';
							var reptime = Seed.queue_champion.end - uW.unixtime();
						} else {
							champStatusClass = 'btchampBroken';
							var reptime = t.getRepairTime(champItem);
						}
						BrokenTime += reptime;
					} else {
						champStatusClass = 'btchampSuccess';
					}
					if (ById('btChampRepairQueueState'+Qitem)) { ById('btChampRepairQueueState'+Qitem).className = champStatusClass; }
				}
			}
		}
		t.UpdateRepairQueueSummary(BrokenMight,BrokenTime);
	},

	getRepairTime : function (champItem) {
		var reptime = CM.ChampionPanelController.breakTimeGet(champItem);
		return reptime;
	},

	UpdateRepairQueueSummary : function (BrokenMight,BrokenTime) {
		if (ById('btchampRepairQueueMight')) { ById('btchampRepairQueueMight').innerHTML = '<i>'+tx('Broken might in Queue')+':&nbsp;'+addCommas(BrokenMight)+'</i>'; }
		if (ById('btchampRepairQueueTime')) { ById('btchampRepairQueueTime').innerHTML = '<i>'+tx('Estimated time to Repair')+':&nbsp;'+timestr(BrokenTime)+'</i>'; }
	},

	UpgradeCityButton: function (city, x, y) {
		var t = Tabs.Champ;
		Options.ChampOptions.UpgradeCityNum = city.idx;
		saveOptions();
	},

	fillUpgradeItemDropdown : function () {
		var t = Tabs.Champ;

		ById('btchampUpgradeItem').options.length = 0;
		var o = document.createElement("option");
		o.text = "-- "+tx('Select Item')+" --"
		o.style = 'padding-left:15px;"';
		o.value = 0;
		ById('btchampUpgradeItem').options.add(o);

		for (var champId in uW.kocChampionItems) {
			var champItem = uW.kocChampionItems[champId];
			var o = document.createElement("option");
			o.text = champItem.name;
			o.value = champId;
			var OStyle = 'padding-left:15px;';
			if (Tabs.Reference.isBroken(champItem)) { OStyle += 'background-image:url('+BrokenIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
			else if (champItem.equippedTo && champItem.equippedTo!=0) { OStyle += 'background-image:url('+EquippedIcon+');background-size:12px 12px;background-repeat:no-repeat;'; }
			o.style = OStyle;
			ById('btchampUpgradeItem').options.add(o);
		}
	},

	helpPop : function (){
		var t = Tabs.Champ;
		var helpText = '<br>'+tx("Using Speedups for Champ Hall Repairs");
		helpText += '<p>'+tx('Hourglasses will be used in the following order if they are selected, and the required criteria is met')+' :-</p>';
		helpText += '<TABLE class=xtab><TR><TD><b>'+uW.g_js_strings.commonstr.item+'</b></td><TD><b>'+uW.g_js_strings.commonstr.time+'</b></td><TD><b>'+tx('Criteria')+'</b></td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i8.name+'</td><TD>2.5 days</td><TD>'+tx('More than 48 hours remaining')+'</td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i7.name+'</td><TD>24 hrs</td><TD>'+tx('More than 23 hours 30 minutes remaining')+'</td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i6.name+'</td><TD>15 hrs</td><TD>'+tx('More than 14 hours 30 minutes remaining')+'</td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i5.name+'</td><TD>8 hrs</td><TD>'+tx('More than 7 hours 30 minutes remaining')+'</td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i4.name+'</td><TD>2.5 hrs</td><TD>'+tx('More than 2 hours remaining')+'</td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i3.name+'</td><TD>1 hr</td><TD>'+tx('More than 45 minutes remaining')+'</td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i2.name+'</td><TD>15 mins</td><TD>'+tx('More than 5 minutes remaining')+'</td></tr>';
		helpText += '<TR><TD>'+uW.itemlist.i1.name+'</td><TD>1 min</td><TD>'+tx('More than 30 seconds remaining')+'</td></tr>';
		helpText += '</table>';
		helpText += '<p>'+tx('If the override box is ticked, then the override rule specified will take priority')+'.</p><br>';

		var pop = new CPopup ('BotHelp', 0, 0, 460, 420, true);
		pop.centerMe (mainPop.getMainDiv());
		pop.getMainDiv().innerHTML = helpText;
		pop.getTopDiv().innerHTML = '<CENTER><B>'+tx("PowerBot+ Help")+': '+tx("Speedups")+'</b></center>';
		pop.show (true);
	},

	addChampQueue : function (item,action,level,nopaint) {
		var t = Tabs.Champ;
		level = parseIntNan(level);
		if (level==0) return;
		if (item==0) return;

		var champItem = uW.kocChampionItems[item];
		if (!champItem) return;

		if (action=="upgrade" && champItem.level>=level) return;
		if (action=="enhance" && champItem.rarity>=level) return;

		// if item already in queue then ignore

		var found = false;
		for (var i=0;i<Options.ChampOptions.UpgradeQueue.length;i++) {
			var QObj = Options.ChampOptions.UpgradeQueue[i];
			if (QObj.item == item && QObj.action == action) {
				if (QObj.maximum<level) {
					Options.ChampOptions.UpgradeQueue[i].maximum=level; // update level if necessary
				}
				found = true;
				break;
			}
		}
		if (!found) {
			var QObj = {};
			QObj.item = item;
			QObj.action = action;
			QObj.maximum = level;
			QObj.status = 0;
			QObj.triesTotal = 0;
			QObj.triesThis = 0;
			QObj.triesLimiter = 0;
			QObj.messages = tx('Not Started');

			Options.ChampOptions.UpgradeQueue.push(QObj);
			if (!nopaint) { t.paintUpgradeQueue(); }
		}
	},

	deleteChampQueueAll : function() {
		var t = Tabs.Champ;
		Options.ChampOptions.UpgradeQueue = [];
		saveOptions();
		ById('btChampUpgradeMessages').innerHTML = tx("Upgrade Queue deleted!");
		t.paintUpgradeQueue();
	},

	deleteChampQueue : function(obj,index) {
		var t = Tabs.Champ;
		Options.ChampOptions.UpgradeQueue.splice(index,1);
		saveOptions();
		ById('btChampUpgradeMessages').innerHTML = tx("Queue entry deleted!");
		t.paintUpgradeQueue();
	},

	ChampQueueUp : function(obj,index) {
		var t = Tabs.Champ;
		if (index>0) {
			Options.ChampOptions.UpgradeQueue.splice(index-1, 0, Options.ChampOptions.UpgradeQueue.splice(index, 1)[0]);
		}
		saveOptions();
		t.paintUpgradeQueue();
	},

	ChampQueueDn : function(obj,index) {
		var t = Tabs.Champ;
		if (index<Options.ChampOptions.UpgradeQueue.length-1) {
			Options.ChampOptions.UpgradeQueue.splice(index+1, 0, Options.ChampOptions.UpgradeQueue.splice(index, 1)[0]);
		}
		saveOptions();
		t.paintUpgradeQueue();
	},

	ChampQueueMaxChange : function(obj,index) {
		var t = Tabs.Champ;
		Options.ChampOptions.UpgradeQueue[index].maximum = parseIntNan(obj.value);

		saveOptions();
	},

	paintUpgradeQueue : function () {
		var t = Tabs.Champ;
		var m = '';

		MasterQuals = {};
		for (k=1;k<cardQuality.length-1;k++) {
			var quality = cardQuality[k].toLowerCase();
			MasterQuals[k] = uW.g_js_strings.throneRoom[quality];
		}
		MasterLevels = {};
		for (var type_index = 1; type_index < CM.CHAMPION.MAX_LEVELS + 1; ++type_index) {
			MasterLevels[type_index] = type_index;
		}

		var QLen = Options.ChampOptions.UpgradeQueue.length;

		if (QLen==0) {
			m = '<br><div align=center style="opacity:0.3;">'+tx('No champion cards queued')+'</div>';
			ById('btchampUpgradeQueue').innerHTML = m;
		} else {
			m = '<TABLE width=100% cellspacing=0 align=center class=xtab><tr><th class=xtabHD align=left>'+tx('Card')+'</th><th width=50px class=xtabHD align=left>'+tx('Action')+'</th><th width=70px class=xtabHD align=left>'+tx('Target')+'</th><th class=xtabHD align=left>'+tx('Messages')+'</th><th width=50px class=xtabHD align=center>'+tx('Order')+'</th><th width=50px class=xtabHD align=center>'+uW.g_js_strings.commonstr.status+'</th><th width=100px class=xtabHD align=right><a class="inlineButton btButton red14" onclick="btChampQueueDeleteAll()"><span>'+tx('Remove All')+'</span></a></th></tr>';
			var r = 0;

			for (var Qitem=0;Qitem<Options.ChampOptions.UpgradeQueue.length;Qitem++) {
				var QObj = Options.ChampOptions.UpgradeQueue[Qitem];
				if (QObj) {
					var champItem = uW.kocChampionItems[QObj.item];

					var champCardName = tx("Unknown / Salvaged")+ ' ['+QObj.item+']';
					var cardExists = false;
					var champStatusClass = '';
					if (champItem) {
						cardExists = true;
						champCardName = champItem.name;

						if (QObj.status == 2) {
							champStatusClass = 'btchampSuccess';
						} else if (Tabs.Reference.isBroken(champItem)) {
							if (Seed.queue_champion && champItem.equipmentId == Seed.queue_champion.itemId) {
								champStatusClass = 'btchampHammer';
							} else {
								champStatusClass = 'btchampBroken';
							}
						} else {
							champStatusClass = 'btchampGoButton';
						}
					}

					rowClass = 'evenRow';
					var rem = (r % 2);
					if (rem == 1) rowClass = 'oddRow';
					m += '<TR class="'+rowClass+'"><TD width=150px align=left><div id=btChampQueueItem'+Qitem+' style="white-space:nowrap;">'+champCardName+'</div></td>';
					if (cardExists) {
						m += '<TD align=left>'+capitalize(tx(QObj.action))+'</td>';
						if (QObj.action=="enhance") { m += '<TD align=left>'+htmlSelector(MasterQuals,QObj.maximum, 'class=btInput id="btchampUpgradeQueueMax_'+Qitem+'" onchange="btChampQueueMaxChange(this,'+Qitem+')" Qitem="'+Qitem+'"')+'</td>'; }
						else { m += '<TD align=left>'+htmlSelector(MasterLevels,QObj.maximum, 'class=btInput id="btchampUpgradeQueueMax_'+Qitem+'" onchange="btChampQueueMaxChange(this,'+Qitem+')" Qitem="'+Qitem+'"')+'</td>'; }
						m += '<td>'+QObj.messages+'&nbsp;';
						if (QObj.status==1) {
							m += '<br>'+QObj.triesThis+' '+tx('tries this level')+', '+QObj.triesTotal+' '+tx('tries in total');
						}
						m += '</td>';
						m += '<td align=center><a title="move up" onclick="btChampQueueUp(this,'+Qitem+')"><img class=flip style="height:10px;width:13px;" src="'+DownArrow+'"><br><a title="move down" onclick="btChampQueueDn(this,'+Qitem+')"><img style="height:10px;width:13px;" src="'+DownArrow+'"></td>';
						m += '<td align=center><div id=btChampQueueState'+Qitem+' class="'+champStatusClass+'"></div></td>';
					}
					else {
						m += '<TD align=left>&nbsp;</td><TD align=left>&nbsp;</td><TD align=left>&nbsp;</td><TD align=center>&nbsp;</td><TD align=center>&nbsp;</td>';
					}
					m += '<td align=right>'+strButton8(tx('Remove'),'onclick="btChampQueueDelete(this,'+Qitem+')"')+'</td>';
					m += '</td></tr>';
					r++;
				}
			}
			m += '</table><div align=center id=btchampUpgradeQueueMessage>&nbsp;</div>';
			ById('btchampUpgradeQueue').innerHTML = m;

			for (var Qitem=0;Qitem<Options.ChampOptions.UpgradeQueue.length;Qitem++) {
				var QObj = Options.ChampOptions.UpgradeQueue[Qitem];
				if (QObj) {
					var chItem = uW.kocChampionItems[QObj.item];
					if (chItem) {
						ById('btChampQueueItem'+Qitem).addEventListener('mouseover', function(A) {
							A.stopPropagation();
							var champId = Options.ChampOptions.UpgradeQueue[this.id.split('btChampQueueItem')[1]].item;
							var champItem = uW.kocChampionItems[champId];
							if (champItem) {
								uW.Tooltip.show(A, Tabs.Reference.DisplayCHCard(champItem,false))
							}
						}, false);
					}
				}
			}
		}
		ById('btchampUpgradeQueueCount').innerHTML = QLen;
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	// REPAIR FUNCTIONS

	BreakChampButtonClicked : function () {
		var t = Tabs.Champ;
		if (t.BreakInProgress) { // cancel
			t.BreakInProgress = false;
			ById('btchampBreakChamp').innerHTML = '<span>'+tx('Break Champion Hall')+'</span>';
			ById('btchampBreakMessages').innerHTML = tx("Champion hall breaking cancelled")+'!';
		}
		else { // do it!
			if (t.GemUseTripSwitch) { return; } // don't start if gem probs
			// build queue
			t.BreakQueue = [];
			t.BreakMight = 0;
			for (var champId in uW.kocChampionItems) {
				var champItem = uW.kocChampionItems[champId];
				if (champItem && !Tabs.Reference.isBroken(champItem)) {
					if (!Options.ChampOptions.BreakIgnorePreset || !champItem.equippedTo || champItem.equippedTo==0) {
						if ((champItem.level>=parseIntNan(Options.ChampOptions.BreakMinLevel)) && (champItem.level<=parseIntNan(Options.ChampOptions.BreakMaxLevel)) && champItem.level<CM.CHAMPION.MAX_LEVELS) {
							var itemMight = CardMight(champItem,true);
							t.BreakMight += itemMight;
							t.BreakQueue.push(champId);
							if ((parseIntNan(Options.ChampOptions.BreakMaxMight)!=0) && (t.BreakMight>parseIntNan(Options.ChampOptions.BreakMaxMight))) {
								break;
							}
						}
					}
				}
			}

			if (t.BreakQueue.length>0) {
				var popConfirm = null;
				popConfirm = new CPopup('ptConfirmAction', 0, -100, 500, 150, true, function () { clearTimeout(1000); });
				popConfirm.centerMe(mainPop.getMainDiv());
				var m = '<DIV style="height:50px;"><br><TABLE align=center style="width:500px;" class=xtab>';
				m += '<tr><TD align=center><div style="white-space:initial;">'+tx('Please confirm you want to break')+' '+t.BreakQueue.length+' '+tx('champion hall cards, reducing your might by')+' '+addCommas(t.BreakMight)+'?</div><br>&nbsp;</td></tr>';
				m += '<tr><TD align=center><INPUT id=ptConfirm type=submit value="'+tx('Break Champion Hall')+'" \>&nbsp;<INPUT id=ptCancel type=submit value="'+uW.g_js_strings.commonstr.cancel+'" \><br>&nbsp;</td></tr></table></div>';
				popConfirm.getMainDiv().innerHTML = m;
				ResetFrameSize('ptConfirmAction',150,500);
				popConfirm.getTopDiv().innerHTML = '<DIV align=center><b>'+tx('Break Champion Hall Confirmation')+'?</b></div>';
				popConfirm.show(true);
				ById('ptConfirm').addEventListener('click', function () {
					popConfirm.show(false);
					popConfirm.onClose();
					popConfirm.destroy();
					popConfirm = null;

					t.BreakInProgress = true;
					t.BreakTotal = t.BreakQueue.length;
					t.BreakCounter = 0;
					ById('btchampBreakChamp').innerHTML = '<span>'+tx('Cancel')+'</span>';
					ById('btchampBreakMessages').innerHTML = tx("Champion hall break initiated")+'!';
					t.ProcessChampBreak();

				}, false);
				ById('ptCancel').addEventListener('click', function () {
					popConfirm.show(false);
					popConfirm.onClose();
					popConfirm.destroy();
					popConfirm = null;
				}, false);
			}
			else {
				ById('btchampBreakMessages').innerHTML = tx("No cards matching Champion Hall breaking parameters")+'!';
			}
		}

	},

	ProcessChampBreak : function () {
		var t = Tabs.Champ;
		if (!t.BreakInProgress) { return; } // cancelled!
		if (t.BreakQueue.length==0) {
			t.BreakInProgress = false;
			ById('btchampBreakChamp').innerHTML = '<span>'+tx('Break Champion Hall')+'</span>';
			ById('btchampBreakMessages').innerHTML = tx('Champion hall breaking complete')+'!';
			return;
		}
		t.BreakCounter++;
		var chId = t.BreakQueue.pop(0);
		var champItem = uW.kocChampionItems[chId];
		if (champItem && !Tabs.Reference.isBroken(champItem)) { // just checking
			ById('btchampBreakMessages').innerHTML = tx("Breaking")+' '+champItem.name+' ('+t.BreakCounter+'/'+t.BreakTotal+')';
			t.UpgradeItem(chId,t.CheckBreakResult,0);
		}
	},

	CheckBreakResult : function(rslt,chId) {
		var t = Tabs.Champ;
		if (rslt.ok) {
			if (Options.ChampOptions.BreakRepairAuto) {
				t.addChampRepairQueue(chId);
			}
		}
		if (rslt.reason && rslt.reason=="aether") {
			t.BreakInProgress = false;
			ById('btchampBreakChamp').innerHTML = '<span>'+tx('Break Champion Hall')+'</span>';
			ById('btchampBreakMessages').innerHTML = tx('Aetherstone depleted. Turning off')+'!';
		}
		if (t.GemUseTripSwitch) {
			t.BreakInProgress = false;
			ById('btchampBreakChamp').innerHTML = '<span>'+tx('Break Champion Hall')+'</span>';
			ById('btchampBreakMessages').innerHTML = tx('Champion Hall Break accidentally used gems - Please refresh game! Turning off')+'!';
			uW.Modal.showAlert('<div align="center">'+tx('Champion Hall Break accidentally used gems - Please refresh game! Turning off')+'</div>');
		}
		setTimeout(t.ProcessChampBreak,2000);
	},

	toggleAutoRepairState: function(obj){
		var t = Tabs.Champ;
		obj = ById('btAutoChampRepairState');
		if (Options.ChampOptions.RepairRunning == true) {
			Options.ChampOptions.RepairRunning = false;
			obj.value = tx("Repair = OFF");
			t.RepairStatus = tx('Powered Off');
			t.PaintRepairStatus();
			clearTimeout(t.RepairTimer);
		}
		else {
			Options.ChampOptions.RepairRunning = true;
			obj.value = tx("Repair = ON");
			t.RepairStatus = tx('Starting')+'...';
			t.PaintRepairStatus();
			t.RepairTimer = setTimeout(function () { t.doAutoRepairLoop();}, 0);
		}
		saveOptions();
		SetToggleButtonState('ChampRepair',Options.ChampOptions.RepairRunning,'Repair');
	},

	doAutoRepairLoop : function() {
		var t = Tabs.Champ;
		clearTimeout(t.RepairTimer);
		if (!Options.ChampOptions.RepairRunning) {
			t.RepairStatus = tx('Powered Off');
			t.PaintRepairStatus();
			return;
		}

		var BrokenItemInQueue = false;
		t.looprepairaction = false;
		t.autorepairdelay = 2; // default 2 seconds delay if no action taken!

		t.RepairStatus = tx('Checking for cards to repair')+'...';
		t.PaintRepairStatus();

		if (Options.ChampOptions.RepairQueue.length != 0) {
			// if repair queue busy see if we can use repair speedups
			var now = unixTime();
			if (Seed.queue_champion && Seed.queue_champion.end && Seed.queue_champion.end>now) {
				t.autoSpeedup("repair");
				t.looprepairaction = true;
			}
			else {
				// Find first of any broken items in queue to repair!
				// If Upgrade queue running, broken items in that queuee take priority!
				if (Options.ChampOptions.UpgradeRunning) {
					// Find first of any broken items in queue to repair!
					for (var Qitem = 0; Qitem < Options.ChampOptions.UpgradeQueue.length; Qitem++) {
						var QObj = Options.ChampOptions.UpgradeQueue[Qitem];
						if (QObj) {
							var champItem = uW.kocChampionItems[QObj.item];
							if (champItem && Tabs.Reference.isBroken(champItem)) {
								BrokenItemInQueue = true;
								t.RepairItem(champItem.equipmentId,"upgrade");
								t.looprepairaction = true;
								break;
							}
						}
					}
				}

				if (!BrokenItemInQueue) {
					for (var Qitem = 0; Qitem < Options.ChampOptions.RepairQueue.length; Qitem++) {
						var QObj = Options.ChampOptions.RepairQueue[Qitem];
						if (QObj) {
							var champItem = uW.kocChampionItems[QObj.item];
							if (champItem && Tabs.Reference.isBroken(champItem)) {
								BrokenItemInQueue = true;
								t.RepairItem(champItem.equipmentId,"repair");
								t.looprepairaction = true;
								break;
							}
						}
					}
				}
				if (!BrokenItemInQueue) {
					t.RepairStatus = tx('Repair queue complete')+'!';
					t.PaintRepairStatus();
				}
			}
		}
		else { // no queue! loop round again...
			t.RepairStatus = tx('No cards in repair queue')+'!';
			t.PaintRepairStatus();
		}
		if (t.looprepairaction) { t.autorepairdelay = t.intervalRepairSecs; } // delay next action
		t.RepairTimer = setTimeout(function () { t.doAutoRepairLoop(); }, (t.autorepairdelay * 1000));
	},

	fillRepairItemDropdown : function () {
		var t = Tabs.Champ;

		ById('btchampRepairItem').options.length = 0;
		var o = document.createElement("option");
		o.text = "-- "+tx('Select Item')+" --"
		o.style = 'padding-left:15px;"';
		o.value = 0;
		ById('btchampRepairItem').options.add(o);

		for (var champId in uW.kocChampionItems) {
			var champItem = uW.kocChampionItems[champId];
			if (Tabs.Reference.isBroken(champItem)) {
				var o = document.createElement("option");
				o.text = champItem.name;
				o.value = champId;
				o.style = 'padding-left:15px;background-image:url('+BrokenIcon+');background-size:12px 12px;background-repeat:no-repeat;';
				ById('btchampRepairItem').options.add(o);
			}
		}
	},

	PaintRepairStatus : function () {
		var t = Tabs.Champ;

		var now = unixTime();
		if (!t.serverwait) {
			if (Seed.queue_champion && Seed.queue_champion.end && Seed.queue_champion.end>now) {
				var champ_item = uW.kocChampionItems[Seed.queue_champion.itemId];
				if (champ_item) {
					var m = '<div>'+tx('Repairing')+' '+champ_item.name+'</div>';
					m += '<div><i><span id=btchampoverviewrepairtimer>'+timestr(Seed.queue_champion.end - now)+'</span><span>&nbsp;'+tx('remaining')+'...</span></i><span style="inline-block;float:right;margin-top:-2px;">';

					var Squire = parseIntNan(Seed.items.i1);
					var Knight = parseIntNan(Seed.items.i2);
					var Guinevere = parseIntNan(Seed.items.i3);
					var Morgana = parseIntNan(Seed.items.i4);
					var Arthur = parseIntNan(Seed.items.i5);
					var Merlin = parseIntNan(Seed.items.i6);
					var Divine = parseIntNan(Seed.items.i7);
					var Epic = parseIntNan(Seed.items.i8);

					var Speedups = '';
					Speedups += t.paintSpeedup(1,Squire);
					Speedups += t.paintSpeedup(2,Knight);
					Speedups += t.paintSpeedup(3,Guinevere);
					Speedups += t.paintSpeedup(4,Morgana);
					Speedups += t.paintSpeedup(5,Arthur);
					Speedups += t.paintSpeedup(6,Merlin);
					Speedups += t.paintSpeedup(7,Divine);
					Speedups += t.paintSpeedup(8,Epic);
					Speedups += '<td class=xtab style="padding-right:2px">'+strButton8(tx("Cancel Repair"),'onClick="cancelChampRepair()"')+'</td>';
					if (Speedups != "") Speedups = "<table align=left cellspacing=0 cellpadding=0><tr>" + Speedups + "</tr></table>";
					m += Speedups+'</span>';
					if (ById('btchampoverviewrepairstatusdiv')) {
						ById('btchampoverviewrepairstatusdiv').innerHTML = m;
					}
				}
			}
			else {
				if (ById('btchampoverviewrepairstatusdiv')) ById('btchampoverviewrepairstatusdiv').innerHTML = t.RepairStatus;
			}
		}
	},

	paintSpeedup : function (item, count) {
		var t = Tabs.Champ;
		var n = '';
		if (count>0) {
			n += '<td class=xtab style="padding-right:2px"><a onClick="btchamprepairSpeedup('+item+')"><img height=18 style="opacity:0.8;vertical-align:text-top;" src="'+IMGURL+'items/70/'+item+'.jpg" title="'+itemTitle(item)+'"></a></td>';
		}
		return n;
	},

	SpeedupRepair : function (iid, notify) {
		var t = Tabs.Champ;
		var now = unixTime();
		if (Seed.queue_champion && Seed.queue_champion.end && Seed.queue_champion.end>now) {
			t.serverwait = true;
			if (ById('btchampoverviewrepairstatusdiv')) ById('btchampoverviewrepairstatusdiv').innerHTML = tx('Applying Speedup')+'...';
			var now = unixTime();
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.action = CM.CHAMPION.CEI_SPEEDUP_REPAIR;
			params.cityId = uW.currentcityid;
			params.eid = Seed.queue_champion.itemId;
			params.speedupItem = iid;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function (rslt) {
					if (rslt.ok) {
						var reduced = CM.intelligentOrdering.getReduceTime(iid),
						timeDifference = 0,
						startTime,
						endTime;
						Seed.items["i" + iid] = parseInt(Seed.items["i" + iid]) - 1;
						uW.ksoItems[iid].subtract();
						timeDifference = SpeedupArray[iid-1];
						startTime = Seed.queue_champion.start;
						endTime = Seed.queue_champion.end;
						Seed.queue_champion.start = startTime - reduced;
						Seed.queue_champion.end = endTime - reduced;
						if (Seed.queue_champion.end < uW.unixtime()) {
							if (jQuery("#championPanelBrokenContainer").length > 0) {
								CM.ModalManager.close();
							}
							clearInterval(CM.ChampionPanelView.repairIntervals);
							var champ_item = uW.kocChampionItems[params.eid];
							champ_item.status = 1;
							jQuery("#" + params.eid).removeClass("repairing");
							if (rslt.mightGain !== undefined) {
								Seed.player.might += rslt.mightGain;
								jQuery("#topnav_might").html(Seed.player.might);
							}
						}
						t.serverwait = false;
						t.refreshInventory();
						t.PaintRepairStatus();
					} else {
						t.serverwait = false;
						t.log(tx('Error using speedup')+' - '+rslt.feedback,'REPAIR',true);
					}
					if (notify) notify(rslt);
				},
				onFailure: function () {
					t.serverwait = false;
					if (notify) notify({msg: 'AJAX error'});
				}
			},true);
		}
	},

	CancelRepair : function (notify) {
		var t = Tabs.Champ;
		if (Seed.queue_champion && Seed.queue_champion.itemId) {
			t.serverwait = true;
			if (ById('btchampoverviewrepairstatusdiv')) ById('btchampoverviewrepairstatusdiv').innerHTML = tx('Cancelling Repair')+'...';

			var params = uW.Object.clone(uW.g_ajaxparams);
			params.action = CM.CHAMPION.CEI_CANCEL_REPAIR;
			params.cityId = uW.currentcityid;
			params.eid = Seed.queue_champion.itemId;
			params.gems = 0;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function (rslt) {
					if (rslt.ok) {
						var champ_item = uW.kocChampionItems[params.eid];
						if (champ_item.status == CM.CHAMPION.STATUS_REPAIRING_ENHANCE) { champ_item.status = CM.CHAMPION.STATUS_BROKEN_ENHANCE; }
						else { champ_item.status = CM.CHAMPION.STATUS_BROKEN_UPGRADE; }
						jQuery("#" + params.eid).removeClass("repairing").addClass("repair");
						Seed.queue_champion = {};
						clearInterval(CM.ChampionPanelView.repairIntervals);
						CM.ChampionPanelView.repairIntervals = null;
						t.serverwait = false;
						t.refreshInventory();
						t.PaintRepairStatus();
					}
					else {
						t.serverwait = false;
						t.log(tx('Error cancelling repair')+' - '+rslt.feedback,'REPAIR',true);
					}
					if (notify) notify(rslt);
				},
				onFailure: function () {
					t.serverwait = false;
					if (notify) notify({msg: 'AJAX error'});
				},
			},true); // noretry
		}
	},

	paintRepairQueue : function () {
		var t = Tabs.Champ;
		var m = '';

		var QLen = Options.ChampOptions.RepairQueue.length;

		if (QLen==0) {
			m = '<br><div align=center style="opacity:0.3;">'+tx('No champion cards queued')+'</div>';
			ById('btchampRepairQueue').innerHTML = m;
		} else {
			m = '<div><table class=xtab width=100%><tr><td align=right id=btchampRepairQueueMight>&nbsp;</td><td align=left id=btchampRepairQueueTime>&nbsp;</td></tr></table></div>';
			m += '<TABLE width=100% cellspacing=0 align=center class=xtab><tr><th class=xtabHD align=left>'+tx('Card')+'</th><th width=50px class=xtabHD align=center>'+tx('Order')+'</th><th width=50px class=xtabHD align=center>'+uW.g_js_strings.commonstr.status+'</th><th width=100px class=xtabHD align=right><a class="inlineButton btButton red14" onclick="btChampRepairQueueDeleteAll()"><span>'+tx('Remove All')+'</span></a></th></tr>';

			var BrokenMight = 0;
			var BrokenTime = 0;

			var r = 0;

			for (var Qitem=0;Qitem<Options.ChampOptions.RepairQueue.length;Qitem++) {
				var QObj = Options.ChampOptions.RepairQueue[Qitem];
				if (QObj) {
					var champItem = uW.kocChampionItems[QObj.item];

					var champCardName = tx("Unknown / Salvaged")+ ' ['+QObj.item+']';
					var cardExists = false;
					var champStatusClass = '';
					if (champItem) {
						cardExists = true;
						champCardName = champItem.name;

						if (Tabs.Reference.isBroken(champItem)) {
							BrokenMight += CardMight(champItem,true);
							if (Seed.queue_champion && champItem.equipmentId == Seed.queue_champion.itemId) {
								champStatusClass = 'btchampHammer';
								var reptime = Seed.queue_champion.end - uW.unixtime();
							} else {
								champStatusClass = 'btchampBroken';
								var reptime = t.getRepairTime(champItem);
							}
							BrokenTime += reptime;
						} else {
							champStatusClass = 'btchampSuccess';
						}
					}

					rowClass = 'evenRow';
					var rem = (r % 2);
					if (rem == 1) rowClass = 'oddRow';
					m += '<TR class="'+rowClass+'"><TD align=left><div><span id=btChampRepairQueueItem'+Qitem+' style="white-space:nowrap;">'+champCardName+'</span></div></td>';
					if (cardExists) {
						m += '<td align=center><a title="move up" onclick="btChampRepairQueueUp(this,'+Qitem+')"><img class=flip style="height:10px;width:13px;" src="'+DownArrow+'"><br><a title="move down" onclick="btChampRepairQueueDn(this,'+Qitem+')"><img style="height:10px;width:13px;" src="'+DownArrow+'"></td>';
						m += '<td align=center><div id=btChampRepairQueueState'+Qitem+' class="'+champStatusClass+'"></div></td>';
					}
					else {
						m += '<TD align=center>&nbsp;</td><TD align=center>&nbsp;</td>';
					}
					m += '<td align=right>'+strButton8(tx('Remove'),'onclick="btChampRepairQueueDelete(this,'+Qitem+')"')+'</td>';
					m += '</td></tr>';
					r++;
				}
			}
			m += '</table><div align=center id=btchampRepairQueueMessage>&nbsp;</div>';
			ById('btchampRepairQueue').innerHTML = m;

			t.UpdateRepairQueueSummary(BrokenMight,BrokenTime);

			for (var Qitem=0;Qitem<Options.ChampOptions.RepairQueue.length;Qitem++) {
				var QObj = Options.ChampOptions.RepairQueue[Qitem];
				if (QObj) {
					var chItem = uW.kocChampionItems[QObj.item];
					if (chItem) {
						ById('btChampRepairQueueItem'+Qitem).addEventListener('mouseover', function(A) {
							A.stopPropagation();
							var champId = Options.ChampOptions.RepairQueue[this.id.split('btChampRepairQueueItem')[1]].item;
							var champItem = uW.kocChampionItems[champId];
							if (champItem) {
								uW.Tooltip.show(A, Tabs.Reference.DisplayCHCard(champItem,false))
							}
						}, false);
					}
				}
			}
		}
		ById('btchampRepairQueueCount').innerHTML = QLen;
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	addChampRepairQueue : function (item,nopaint) {
		var t = Tabs.Champ;
		var champItem = uW.kocChampionItems[item];
		if (!champItem) return;

		// if item already in queue then ignore

		var found = false;
		for (var i=0;i<Options.ChampOptions.RepairQueue.length;i++) {
			var QObj = Options.ChampOptions.RepairQueue[i];
			if (QObj.item == item) { found = true; break; }
		}
		if (!found) {
			var QObj = {};
			QObj.item = item;
			Options.ChampOptions.RepairQueue.push(QObj);
			if (!nopaint) { t.paintRepairQueue(); }
		}
	},

	deleteChampRepairQueueAll : function() {
		var t = Tabs.Champ;
		Options.ChampOptions.RepairQueue = [];
		saveOptions();
		ById('btChampRepairMessages').innerHTML = tx("Repair Queue deleted!");
		t.paintRepairQueue();
	},

	deleteChampRepairQueue : function(obj,index) {
		var t = Tabs.Champ;
		Options.ChampOptions.RepairQueue.splice(index,1);
		saveOptions();
		ById('btChampRepairMessages').innerHTML = tx("Queue entry deleted!");
		t.paintRepairQueue();
	},

	ChampRepairQueueUp : function(obj,index) {
		var t = Tabs.Champ;
		if (index>0) {
			Options.ChampOptions.RepairQueue.splice(index-1, 0, Options.ChampOptions.RepairQueue.splice(index, 1)[0]);
		}
		saveOptions();
		t.paintRepairQueue();
	},

	ChampRepairQueueDn : function(obj,index) {
		var t = Tabs.Champ;
		if (index<Options.ChampOptions.RepairQueue.length-1) {
			Options.ChampOptions.RepairQueue.splice(index+1, 0, Options.ChampOptions.RepairQueue.splice(index, 1)[0]);
		}
		saveOptions();
		t.paintRepairQueue();
	},

	// SALVAGE FUNCTIONS

	toggleAutoSalvageState: function(obj){
		var t = Tabs.Champ;
		obj = ById('btAutoChampSalvageState');
		if (Options.ChampOptions.SalvageRunning == true) {
			Options.ChampOptions.SalvageRunning = false;
			obj.value = tx("Salvage = OFF");
			t.SalvageStatus = tx('Powered Off');
			t.PaintSalvageStatus();
			clearTimeout(t.SalvageTimer);
		}
		else {
			Options.ChampOptions.SalvageRunning = true;
			obj.value = tx("Salvage = ON");
			t.SalvageStatus = tx('Starting')+'...';
			t.PaintSalvageStatus();
			t.SalvageTimer = setTimeout(function () { t.doAutoSalvageLoop();}, 0);
		}
		saveOptions();
		SetToggleButtonState('ChampSalvage',Options.ChampOptions.SalvageRunning,'Salvage');
	},

	doAutoSalvageLoop : function() {
		var t = Tabs.Champ;
		clearTimeout(t.SalvageTimer);
		if (!Options.ChampOptions.SalvageRunning) {
			t.SalvageStatus = tx('Powered Off');
			t.PaintSalvageStatus();
			return;
		}

		t.loopsalvageaction = false;
		t.autosalvagedelay = t.intervalSalvageLoopSecs; // big delay if no action taken!

		if (t.SalvageItems.length == 0) { // build new salvage list
			t.SalvageItems = t.BuildSalvageList(false);
		}

		if (t.SalvageItems.length > 0) {
			var chId = t.SalvageItems.splice(0,1);
			var champ_item = uW.kocChampionItems[chId];
			if (champ_item) {
				var champ_seq = Object.keys(uW.kocChampionItems);
				var item_seq = champ_seq.indexOf(chId.toString())+1;
				t.loopsalvageaction = true;
				t.SalvageItem(chId,t.UpdateSalvageStats,0);
			}
		}
		else {
			t.SalvageStatus = tx('Waiting for cards to salvage')+'...';
			t.PaintSalvageStatus();
		}

		if (t.loopsalvageaction) { t.autosalvagedelay = t.intervalSalvageSecs; } // action taken, apply small delay...
		t.SalvageTimer = setTimeout(function () { t.doAutoSalvageLoop(); }, (t.autosalvagedelay * 1000));
	},

	BuildSalvageList : function () {
		var t = Tabs.Champ;

		var countItem = 0;
		var retList = [];

		for (k in uW.kocChampionItems) {
			var champ_item = uW.kocChampionItems[k];
			if (champ_item == null || !champ_item) continue;

			countItem++;

			// safety ignores
			if (champ_item.level != 0) continue;
			if (champ_item.unique > 0) continue;
			if (champ_item.isEquipped) continue;
			if (Tabs.Reference.isBroken(champ_item)) continue;

			if (countItem <= Options.ChampOptions.SalvageKeepFirst) continue;
			if (champ_item.rarity >= parseIntNan(Options.ChampOptions.SalvageMaxQuality)) continue;

			// check the rules
			if (t.applyRules(champ_item.equipmentId)) { //item was found in salvage rules
				if (Options.ChampOptions.SalvageUpgradeAuto) {
					t.addChampQueue(champ_item.equipmentId,'upgrade',Options.ChampOptions.UpgradeDefaultLevel);
					t.addChampQueue(champ_item.equipmentId,'enhance',Options.ChampOptions.UpgradeDefaultQuality);
				}
				continue;
			}

			// item not found, so needs to be salvaged
			retList.push(champ_item.equipmentId);
		}
		return retList;
	},

	getEffect : function(effString) {
		var t = Tabs.Champ;
		for (var k=0;k<t.ChampEffects.length;k++) {
			var efx = t.ChampEffects[k];
			if (effString==CM.ChampionManager.getEffectName(efx)) {
				return efx;
			}
		}
		if (effString=="Troop" || effString=="Champion") { return effString; }
		else { return ""; }
	},

	applyRules : function (chId) {
		var t = Tabs.Champ;
		for (var r=0;r<Options.ChampOptions.SalvageRuleSet.length;r++) {
			var rule = Options.ChampOptions.SalvageRuleSet[r];
			if (rule.ChampApplyRule(chId)) return true;
		}
		return false;
	},

	SalvageItem : function (chId,notify,aetherbalance) {
		var t = Tabs.Champ;
		var aetherbalance = aetherbalance||0;

		var num_city = t.pickAetherSalvageCity(Options.ChampOptions.SalvageCityNum);
		var SalvageCityId = Seed.cities[num_city][0];

		t.SalvageStatus = tx('Salvaging Item')+'...';
		t.PaintSalvageStatus();

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action = CM.CHAMPION.CEI_SALVAGE;
		params.eids = chId;
		params.cityId = SalvageCityId;

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				var champ_item = uW.kocChampionItems[chId];
				if (rslt.ok) {
					Seed.resources["city"+SalvageCityId]["rec5"][0] = parseIntNan(Seed.resources["city"+SalvageCityId]["rec5"][0]) + parseIntNan(rslt.aetherstones);
					if (rslt.mightGain !== undefined) {
						Seed.player.might -= rslt.mightGain;
					}
					if (champ_item) {
						delete uW.kocChampionItems[chId];
						t.SalvageStatus = tx('Salvaged')+' '+champ_item.name+' - '+tx('aetherstone gained')+' '+addCommas(rslt.aetherstones-aetherbalance);
						t.log(t.SalvageStatus,'SALVAGE');
					}
				} else {
					if (champ_item) {
						t.SalvageStatus = tx('Error Salvaging Item')+' '+champ_item.name+' - '+rslt.feedback;
						// assume already deleted so remove from kocChampionItems otherwise we'll get stuck on it
						delete uW.kocChampionItems[chId];
					}
				}
				t.refreshInventory();
				if (notify) notify(rslt,aetherbalance);
			}
		},true);
	},

	UpdateSalvageStats : function(rslt,aetherbalance) {
		var t = Tabs.Champ;
		var aetherbalance = aetherbalance||0;
		if (rslt.ok) {
			Options.ChampOptions.NumSalvaged++;
			Options.ChampOptions.AetherSalvaged += rslt.aetherstones-aetherbalance;
			saveOptions();
		}
		t.PaintSalvageStatus();
	},

	PaintSalvageStatus : function () {
		var t = Tabs.Champ;
		var Stats = '';

		if (Options.ChampOptions.SalvageRunning) {
			var now = new Date();
			if (!Options.ChampOptions.SalvageStartDate) Options.ChampOptions.SalvageStartDate = now.valueOf();
			var StartDate = new Date(Options.ChampOptions.SalvageStartDate);
			var since = StartDate.toDateString();

			var Stats = addCommas(Options.ChampOptions.NumSalvaged)+'&nbsp;'+tx('cards salvaged')+',&nbsp;'+addCommas(Options.ChampOptions.AetherSalvaged)+'&nbsp;'+tx('aetherstone collected')+'&nbsp;'+tx('since')+'&nbsp;'+since+'<span style="inline-block;float:right;margin-top:4px;">'+strButton8(tx('Reset Stats'),'id=btchampsalvageoverviewreset')+'</span>';
		}
		if (ById('btchampoverviewsalvagestatusdiv')) ById('btchampoverviewsalvagestatusdiv').innerHTML = t.SalvageStatus+'<br><i>'+Stats+'</i>';
		if (ById('btchampsalvageoverviewreset')) ById('btchampsalvageoverviewreset').addEventListener('click',t.ResetSalvageStats,false);
	},

	ResetSalvageStats : function() {
		var t = Tabs.Champ;
		Options.ChampOptions.SalvageStartDate = 0;
		Options.ChampOptions.NumSalvaged = 0;
		Options.ChampOptions.AetherSalvaged = 0;
		saveOptions();
		t.PaintSalvageStatus();
	},

	SalvageCityButton: function (city, x, y) {
		var t = Tabs.Champ;
		Options.ChampOptions.SalvageCityNum = city.idx;
		saveOptions();
	},

	FormatSalvageCondition : function(rule,advanced) {
		var t = Tabs.Champ;
		var innerM = tx('Simple Rule')+':<br>';
		if (advanced) { innerM = tx('Advanced Rule')+':<br>'; }

		if (rule.length==0) {
			innerM += tx('Keep ALL');
		}
		else {
			for (ii = 0; ii < rule.length; ii++) {
				var condition = rule[ii];
				if (ii == 0) innerM += tx('Card');
				else innerM += '<br><b>'+tx('AND')+'</b>';

				if (condition.mustHave != 'false') innerM += '&nbsp;'+tx('must have')+'&nbsp;';
				else innerM += '&nbsp;'+tx('must')+'&nbsp;<b>'+tx('NOT')+'</b>&nbsp;'+tx('have')+'&nbsp;';

				if (condition.number!=1) { innerM += condition.number+'x&nbsp;'; }

				if (condition.effect=="Troop" || condition.effect=="Champion") {
					innerM += tx(condition.effect)+'&nbsp;';
				}
				else {
					innerM += CM.ChampionManager.getEffectName(condition.effect)+'&nbsp;';
				}
				var debuffonlyeffect = false;
				if (!CM.thronestats.effects[condition.effect] || CM.thronestats.effects[condition.effect][7]=="1") {
					debuffonlyeffect = true;
				}

				if (!debuffonlyeffect) {
					if (condition.buffType=='b') innerM += tx('buff')+'&nbsp;';
					else if (condition.buffType=='d') innerM += tx('debuff')+'&nbsp;';
					else innerM += tx('buff or debuff')+'&nbsp;';
				}
				if (condition.minTier && condition.minTier > 1) {
					innerM += '('+tx('tier')+'&nbsp;'+condition.minTier+'+)&nbsp;';
				}
				var slotcount = 0;
				for (j = 0; j < condition.slots.length; j++) { if (condition.slots[j]) slotcount++;	}
				if (slotcount<=1) { innerM += tx('in slot')+':&nbsp;'; }
				else { innerM += tx('in slots')+':&nbsp;'; }

				for (j = 0; j < condition.slots.length; j++) {
					if (condition.slots[j]) innerM += (j + 1) + "&nbsp;";
				}
			}
		}
		innerM += '<br>&nbsp;';
		return innerM;
	},

	SalvageClickSort : function (e) {
		var t = Tabs.Champ;
		var newColNum = e.id.substr(10);
		ById('SalvageCol' + Options.ChampOptions.SalvageSortColNum).className = 'buttonv2 std blue';
		e.className = 'buttonv2 std green';
		if (newColNum == Options.ChampOptions.SalvageSortColNum) { Options.ChampOptions.SalvageSortDir *= -1; }
		else { Options.ChampOptions.SalvageSortColNum = newColNum; }
		saveOptions();
		t.paint_salvage_rules();
	},

	pickAetherSalvageCity : function(citynum) {
		var t = Tabs.Champ;
		if (!Options.ChampOptions.SalvageAnyCity || parseInt(Seed.resources["city"+Seed.cities[citynum][0]]["rec5"][0]) <= Options.ChampOptions.SalvageMaxAether) return citynum;
		var ind = citynum;
		var lowest = 99999999;

		for (var i=1;i<=Seed.cities.length; i++) {
			var ii=citynum+i;
			if (ii>=Seed.cities.length) ii-=Seed.cities.length;
			cityId = Seed.cities[ii][0];
			if (Options.ChampOptions.SalvageOverflow == "lowest") {
				if (parseInt(Seed.resources["city"+cityId]["rec5"][0]) < lowest) {
					lowest = +Seed.resources["city"+cityId]["rec5"][0];
					ind = ii;
				}
			}
			else {
				if (parseInt(Seed.resources["city"+cityId]["rec5"][0]) <= Options.ChampOptions.SalvageMaxAether) {
					return ii;
				}
			}
		}
//		if (ind==citynum) t.log(tx('Warning - All cities contain more than the maximum salvage aetherstone amount'),'GENERAL');
		return ind;
	},

	SalvageNewRule : function (advanced) {
		var t = Tabs.Champ;
		t.EditRuleNumber = -1;
		t.EditMode = true;
		ById('btchampSalvageMessages').innerHTML = "&nbsp;";

		if (advanced) { t.PaintAdvancedRulePanel(); }
		else { t.PaintSimpleRulePanel(); }
	},

	SalvageEditRule : function (entry) {
		var t = Tabs.Champ;
		t.EditRuleNumber = entry;
		t.EditMode = true;
		ById('btchampSalvageMessages').innerHTML = "&nbsp;";

		if (Options.ChampOptions.SalvageRuleSet[entry].advancedrule) { t.PaintAdvancedRulePanel(); }
		else { t.PaintSimpleRulePanel(); }
	},

	SalvageDeleteRule : function (entry) {
		var t = Tabs.Champ;
		Options.ChampOptions.SalvageRuleSet.splice(entry,1);
		saveOptions();
		ById('btchampSalvageMessages').innerHTML = tx("Salvage rule deleted")+"!";
		t.SalvageItems = []; // force reset of items to salvage
		t.paint_salvage_rules();
	},

	SalvageClearRules : function() {
		var t = Tabs.Champ;
		Options.ChampOptions.SalvageRuleSet = [];
		// for safety, switch off!
		if (Options.ChampOptions.SalvageRunning == true) {
			t.toggleAutoSalvageState();
		}
		saveOptions();
		ById('btchampSalvageMessages').innerHTML = tx("All salvage rules deleted")+"!";
		t.SalvageItems = []; // force reset of items to salvage
		t.paint_salvage_rules();
	},

	SalvageAddRule : function (rule) {
		var t = Tabs.Champ;
		Options.ChampOptions.SalvageRuleSet.unshift(rule);
		saveOptions();
	},

	SalvageReplaceRule : function (rule) {
		var t = Tabs.Champ;
		Options.ChampOptions.SalvageRuleSet[t.EditRuleNumber] = rule;
		saveOptions();
	},

	PaintSimpleRulePanel : function () {
		var t = Tabs.Champ;

		if (t.EditRuleNumber<0) { var z= '<div class=divHeader align=center>'+tx('NEW SIMPLE RULE')+'</div><br>'; }
		else { var z= '<div class=divHeader align=center>'+tx('EDIT SIMPLE RULE')+'</div><br>'; }

		z += '<table class=xtab cellpadding=2>';
		z += '<tr><td><b>'+tx('Define Champ Cards To Keep')+':</b></td>';
		z += '<td alight=left>'+uW.g_js_strings.commonstr.faction+':&nbsp;<select id=btchampSalvageFactionType class=btInput>';
		z += '<option value="any">'+tx('Any')+'</option>';
		for (var k=0;k<cardFaction.length;k++) {
			var faction = cardFaction[k];
			z += '<option value="' + faction + '">' + uW.g_js_strings.commonstr[faction] + '</option>';
		}
		z += '</select></td>';
		z += '<td alight=left>'+tx('Card Type')+':&nbsp;<select id=btchampSalvageCardType class=btInput>';
		z += '<option value="any">'+tx('Any')+'</option>';
		for (var type in chTypeStrings) {
			z += '<option value="' + chTypeStrings[type] + '">' + uW.g_js_strings.champ[chTypeStrings[type]] + '</option>';
		}
		z += '</select></td>';
		z += '</tr></table>';
		z += '<table id=btchampSalvageConditionTable class=xtab style="padding-left: 5px;">';
		z += '<tr><td align=left><input id=btchampSalvageAddRow type=button value="'+tx('Add Row')+'"/></td></tr>';
		z += '</table><br>';

		z += '<div align="center"><TABLE cellSpacing=0 width=98% height=0% class=xtab><tr><td>&nbsp;</td><td align=center>'+strButton20(tx('Save Rule'), 'id=btchampSalvageSaveRule')+'&nbsp;';
		if (t.EditRuleNumber>=0) { z += strButton20(tx('Save a Copy'), 'id=btchampSalvageCopyRule')+'&nbsp;'; }
		z += strButton20(uW.g_js_strings.commonstr.cancel, 'id=btchampSalvageCancelRule')+'</td><td align=right>&nbsp;</td></tr></table></div>';

		ById('btchampSalvagePanel').innerHTML = z;

		if (t.EditRuleNumber<0) {
			t.createRow();
			t.BuildTierSelect('r2ChampSel5',ById('r2ChampSel3').value);
		}
		else {
			var rule = Options.ChampOptions.SalvageRuleSet[t.EditRuleNumber];
			ById('btchampSalvageFactionType').value = rule.faction;
			ById('btchampSalvageCardType').value = rule.type;
			var table = ById('btchampSalvageConditionTable');
			while (table.rows.length > 1) table.deleteRow(0);
			for (var row = 0; row < rule.conditions.length; row++) {
				var condition = rule.conditions[row];
				t.createRow();
				table.rows[row].cells[0].children[0].value = condition.mustHave;
				table.rows[row].cells[1].children[0].value = condition.number;
				table.rows[row].cells[2].children[0].value = condition.effect;
				table.rows[row].cells[3].children[0].value = condition.buffType;
				t.BuildTierSelect('r'+(row+2)+'ChampSel5',ById('r'+(row+2)+'ChampSel3').value);
				table.rows[row].cells[4].children[0].value = condition.minTier;
				var slotCells = table.rows[row].cells[5];
				for (s = 0; s < condition.slots.length; s++) {
					if (condition.slots[s])
						slotCells.children[s].checked = true;
					else
						slotCells.children[s].checked = false;
				}
			}
		}

		ById('btchampSalvageAddRow').addEventListener ('click', t.createRow, false);
		ById('btchampSalvageSaveRule').addEventListener ('click', function() {t.SaveSimpleRule(false);}, false);
		if (ById('btchampSalvageCopyRule')) { ById('btchampSalvageCopyRule').addEventListener ('click', function() {t.SaveSimpleRule(true);}, false); }
		ById('btchampSalvageCancelRule').addEventListener ('click', function() {t.paint_salvage_rules();}, false);

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	PaintAdvancedRulePanel : function () {
		var t = Tabs.Champ;

		if (t.EditRuleNumber<0) { var z= '<div class=divHeader align=center>'+tx('NEW ADVANCED RULE')+'</div><br>'; }
		else { var z= '<div class=divHeader align=center>'+tx('EDIT ADVANCED RULE')+'</div><br>'; }

		z += '<table class=xtab cellpadding=2>';
		z += '<tr><td><b>'+tx('Define Champ Cards To Keep')+':</b></td>';
		z += '<td alight=left>'+uW.g_js_strings.commonstr.faction+':&nbsp;<select id=btchampSalvageFactionType class=btInput>';
		z += '<option value="any">'+tx('Any')+'</option>';
		for (var k=0;k<cardFaction.length;k++) {
			var faction = cardFaction[k];
			z += '<option value="' + faction + '">' + uW.g_js_strings.commonstr[faction] + '</option>';
		}
		z += '</select></td>';
		z += '<td alight=left>'+tx('Card Type')+':&nbsp;<select id=btchampSalvageCardType class=btInput>';
		z += '<option value="any">'+tx('Any')+'</option>';
		for (var type in chTypeStrings) {
			z += '<option value="' + chTypeStrings[type] + '">' + uW.g_js_strings.champ[chTypeStrings[type]] + '</option>';
		}
		z += '</select></td>';
		z += '</tr></table>';

		z += '<table id=btchampSalvageConditionTable class=xtab style="padding-left: 5px;">';
		z += '<tr><td align=left>'+tx('Row')+'&nbsp;1</td><td align=left><select style="width:250px;" id=btchampSalvageRow1Advanced class=btInput></select>&nbsp;<select style="width:75px;" id=btchampSalvageRow1MinTier class=btInput></select></td></tr>';
		z += '<tr><td align=left>'+tx('Row')+'&nbsp;2</td><td align=left><select style="width:250px;" id=btchampSalvageRow2Advanced class=btInput></select>&nbsp;<select style="width:75px;" id=btchampSalvageRow2MinTier class=btInput></select></td></tr>';
		z += '<tr><td align=left>'+tx('Row')+'&nbsp;3</td><td align=left><select style="width:250px;" id=btchampSalvageRow3Advanced class=btInput></select>&nbsp;<select style="width:75px;" id=btchampSalvageRow3MinTier class=btInput></select></td></tr>';
		z += '<tr><td align=left>'+tx('Row')+'&nbsp;4</td><td align=left><select style="width:250px;" id=btchampSalvageRow4Advanced class=btInput></select>&nbsp;<select style="width:75px;" id=btchampSalvageRow4MinTier class=btInput></select></td></tr>';
		z += '<tr><td align=left>'+tx('Row')+'&nbsp;5</td><td align=left><select style="width:250px;" id=btchampSalvageRow5Advanced class=btInput></select>&nbsp;<select style="width:75px;" id=btchampSalvageRow5MinTier class=btInput></select></td></tr>';
		z += '</table><br>';

		z += '<div align="center"><TABLE cellSpacing=0 width=98% height=0% class=xtab><tr><td>&nbsp;</td><td align=center>'+strButton20(tx('Save Rule'), 'id=btchampSalvageSaveRule')+'&nbsp;';
		if (t.EditRuleNumber>=0) { z += strButton20(tx('Save a Copy'), 'id=btchampSalvageCopyRule')+'&nbsp;'; }
		z += strButton20(uW.g_js_strings.commonstr.cancel, 'id=btchampSalvageCancelRule')+'</td><td align=right>&nbsp;</td></tr></table></div>';

		ById('btchampSalvagePanel').innerHTML = z;

		if (t.EditRuleNumber<0) { t.filterAdvancedStats(); }
		else {
			var rule = Options.ChampOptions.SalvageRuleSet[t.EditRuleNumber];
			ById('btchampSalvageFactionType').value = rule.faction;
			ById('btchampSalvageCardType').value = rule.type;
			t.filterAdvancedStats(rule.type);
			for (var row = 0; row < rule.conditions.length; row++) {
				var condition = rule.conditions[row];
				var slotNumber = 0;
				for (s = 0; s < condition.slots.length; s++) {
					if (condition.slots[s]) slotNumber = s+1;
				}
				var cell = ById('btchampSalvageRow'+slotNumber+'Advanced');
				cell.value = condition.effect;
				t.BuildTierSelect('btchampSalvageRow'+slotNumber+'MinTier',condition.effect);
				var cell = ById('btchampSalvageRow'+slotNumber+'MinTier');
				cell.value = condition.minTier;
			}
		}
		for (var row = 1; row <= 5; row++) {
			t.BuildTierSelect('btchampSalvageRow'+row+'MinTier',ById('btchampSalvageRow'+row+'Advanced').value);
			ById('btchampSalvageRow'+row+'Advanced').addEventListener('change',function(e) {
				var row = e.target.id.substring(17,18);
				t.BuildTierSelect('btchampSalvageRow'+row+'MinTier',e.target.value);
			}, false);
		}

		ById('btchampSalvageCardType').addEventListener('change', function() {
			var selectedValue = ById('btchampSalvageCardType').value;
			t.filterAdvancedStats(selectedValue);
		}, false);

		ById('btchampSalvageSaveRule').addEventListener ('click', function() {t.SaveAdvancedRule(false);}, false);
		if (ById('btchampSalvageCopyRule')) { ById('btchampSalvageCopyRule').addEventListener ('click', function() {t.SaveAdvancedRule(true);}, false); }
		ById('btchampSalvageCancelRule').addEventListener ('click', function() {t.paint_salvage_rules();}, false);

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	BuildTierSelect: function(sel,eff) {
		var t = Tabs.Champ;
		if (eff=="Troop" || eff=="Champion") { eff=0; }
		if (ById(sel)) {
			var CurrVal = ById(sel).value;
			ById(sel).options.length = 0;
			if (eff>0) {
				var keyz = Object.keys(ChampionStatTiers[eff]);
				for (var y in keyz) {
					var o = document.createElement("option");
					o.text = tx('Tier')+" "+keyz[y]+"+";
					o.value = keyz[y];
					ById(sel).options.add(o);
				}
			}
			else {
				for (var y=1;y<=10;y++) {
					var o = document.createElement("option");
					o.text = tx('Tier')+" "+y+"+";
					o.value = y;
					ById(sel).options.add(o);
				}
			}
			ById(sel).value = CurrVal;
		}
	},

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

		for (var i=1;i<=5;i++) {
			var row = ById('btchampSalvageRow'+i+'Advanced');
			row.innerHTML = "";
			ById("btchampSalvageRow"+i+"Advanced").options.add(new Option(tx("none"), "none"));
		}

		if (cardtype == 'any') {
			for (var i=1;i<=5;i++) {
				var row = ById('btchampSalvageRow'+i+'Advanced');
				for (var k=0;k<t.ChampEffects.length;k++) {
					var eff = t.ChampEffects[k];
					if (eff<300) {
						var effectName = CM.ChampionManager.getEffectName(eff);
						row.options.add(new Option(effectName, eff));
					}
				}
				row.options.add(new Option(tx("Any Troop"), "Troop"));
				row.options.add(new Option(tx("Any Champion"), "Champion"));
			}
		}
		else {
			for (var k=0;k<t.ChampEffects.length;k++) {
				var eff = t.ChampEffects[k];
				var effectName = CM.ChampionManager.getEffectName(eff);
				for (var i=1;i<=5;i++) {
					if (t.AdvancedStatsGrid[cardtype][i][eff] != 0) { ById("btchampSalvageRow"+i+"Advanced").options.add(new Option(tx(effectName), eff)); }
				}
			}
		}
	},

	ChampRule : function (type, faction, conditions, advancedrule) { //class definition for rules and conditions
		var t = Tabs.Champ;
		this.type = type;
		this.faction = faction;
		this.advancedrule = advancedrule;
		if (conditions)
			this.conditions = conditions;
		else
			this.conditions = [];

		this.ChampAddCondition = t.ChampAddCondition;
		this.ChampApplyRule	= t.ChampApplyRule;
	},

	ChampAddCondition : function (c) {
		var t = Tabs.Champ;
		this.conditions.push(c);
	},

	ChampApplyRule : function (id) {
		var t = Tabs.Champ;
		var ChampItem = uW.kocChampionItems[id];

		if (this.type != 'any' && (this.type != chTypeStrings[ChampItem.type-1])) return false;
		if (this.faction != 'any' && (this.faction != cardFaction[ChampItem.faction-1])) return false;
		for (var r=0;r<this.conditions.length;r++) {
			if (!this.conditions[r].ChampCheckCondition(id)) return false;
		}
		return true;
	},

	ChampCondition : function (mustHave, number, effect, buffType, slots, minTier) {
		var t = Tabs.Champ;
		this.mustHave = mustHave;
		this.number = number;
		this.effect = effect;
		this.buffType = buffType;
		this.slots = slots;
		this.minTier = minTier||1;
		this.ChampCheckCondition = t.ChampCheckCondition;
	},

	ChampCheckCondition : function (id) {
		var t = Tabs.Champ;
		var numberFound = 0;
		var effectsFound = false;
		// get card
		var ChampItem = uW.kocChampionItems[id];

		if (!ChampItem) return false;

		// for loop for stat
		// count up occurrences
		for (var i in ChampItem.effects) {
			var slotid = +i;
			if (!this.slots[slotid-1]) continue;

			var CardEffect = ChampItem.effects[i].id;
			var CardTier = ChampItem.effects[i].tier;
			var checkTier = parseInt(this.minTier||1);
			var eff = this.effect;
			var checkEffect = parseInt(CardEffect);

			if (checkEffect<200) { // buff or  debuff only for troop effects (for now)
				var isDebuff = (CM.thronestats.effects[CardEffect] && CM.thronestats.effects[CardEffect][7]=="1");

				if (this.buffType == "b" && isDebuff) continue;
				if (this.buffType == "d" && !isDebuff) continue;

				if (isDebuff) {
					for (var efx in EffectDebuffs) {
						if (EffectDebuffs[efx]==CardEffect) {
							checkEffect = efx;
							break;
						}
					}
				}
			}

			if (eff==checkEffect && CardTier>=checkTier) { numberFound++; }
			else {
				if (eff=="Troop" && checkEffect<200 && CardTier>=checkTier) { numberFound++; }
				if (eff=="Champion" && checkEffect>=200 && checkEffect<300 && CardTier>=checkTier) { numberFound++; }
			}
		}

		if ( numberFound >= this.number) { effectsFound = true; }

		if (this.mustHave != "false") {	return effectsFound; }
		else { return (!effectsFound); }
	},

	removeRow: function (row) {
		var t = Tabs.Champ;
		var table = ById('btchampSalvageConditionTable');

		for (i = 0; i < table.rows.length; i++) {
			if (table.rows[i] == row) {
				table.deleteRow(i);
				break;
			}
		}
		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	createRow: function () {
		var t = Tabs.Champ;
		var table = ById('btchampSalvageConditionTable');
		var rowCount = table.rows.length;
		var row = table.insertRow(rowCount - 1);
		rowCount++;
		var rowId = "r" + rowCount;
		row.id = rowId;

		var z = '<td><select class=btInput id="' + rowId + 'ChampSel1"><option value="true"></option><option value="false">'+tx('NOT')+'</option></select></td>';
		z += '<td><select class=btInput id="' + rowId + 'ChampSel2">';
		z += '<option value="1">1x</option>';
		z += '<option value="2">2x</option>';
		z += '<option value="3">3x</option>';
		z += '<option value="4">4x</option>';
		z += '<option value="5">5x</option>';
		z += '</select></td>';
		z += '<td><select class=btInput id="' + rowId + 'ChampSel3">';
		z += '</select></td>';
		z += '<td><select class=btInput id="' + rowId + 'ChampSel4">';
		z += '<option value="e">'+tx('Either')+'</option>';
		z += '<option value="b">'+tx('Buff')+'</option>';
		z += '<option value="d">'+tx('Debuff')+'</option>';
		z += '</select></td>';
		z += '<td><select style="width:75px;" class=btInput id="' + rowId + 'ChampSel5">';
		z += '</select></td>';

		z += '<td>';
		z += '<input type=checkbox value="1" checked=true id="' + rowId + 'ChampSlot1"/>1';
		z += '<input type=checkbox value="2" checked=true id="' + rowId + 'ChampSlot2"/>2';
		z += '<input type=checkbox value="3" checked=true id="' + rowId + 'ChampSlot3"/>3';
		z += '<input type=checkbox value="4" checked=true id="' + rowId + 'ChampSlot4"/>4';
		z += '<input type=checkbox value="5" checked=true id="' + rowId + 'ChampSlot5"/>5';
		z += '</td>';

		row.innerHTML = z;

		var select = ById(rowId + "ChampSel3");
		for (var k=0;k<t.ChampEffects.length;k++) {
			var e = t.ChampEffects[k];
			if (e<300) {
				if (!CM.thronestats.effects[e] || CM.thronestats.effects[e][7]=="0" || DebuffOnly.indexOf(e)!=-1) {
					var effectName = CM.ChampionManager.getEffectName(e);
					select.options.add(new Option(effectName, e));
				}
			}
		}
		t.BuildTierSelect(rowId+'ChampSel5',ById(rowId+'ChampSel3').value);
		ById(rowId+'ChampSel3').addEventListener('change',function(e) {
			var rowId = e.target.id.split('ChampSel3')[0];
			t.BuildTierSelect(rowId+'ChampSel5',e.target.value);
		}, false);

		// add in options for troops specific effects
		select.options.add(new Option(tx("Any Troop"), "Troop"));
		select.options.add(new Option(tx("Any Champion"), "Champion"));

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

		ResetFrameSize('btMain',100,GlobalOptions.btWinSize.x);
	},

	readRows: function () {
		var t = Tabs.Champ;
		var table = ById('btchampSalvageConditionTable');
		var rowCount = table.rows.length;

		var cType = ById('btchampSalvageCardType').value;
		var faction = ById('btchampSalvageFactionType').value;

		var conditions = [];
		for (var i = 0; i < table.rows.length; i++) {
			var row = table.rows[i];
			if (row.id) {
				var s1 = ById(row.id + "ChampSel1");
				var s2 = ById(row.id + "ChampSel2");
				var s3 = ById(row.id + "ChampSel3");
				var s4 = ById(row.id + "ChampSel4");
				var s5 = ById(row.id + "ChampSel5");

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

				var c = new t.ChampCondition(s1.value, s2.value, s3.value, s4.value, slots, s5.value);
				conditions.push(c);
			}
		}
		var rule1 = new t.ChampRule(cType, faction, conditions, false);
		if (t.EditRuleNumber<0) { t.SalvageAddRule(rule1); }
		else { t.SalvageReplaceRule(rule1); }
	},

	SaveSimpleRule : function (copy) {
		var t = Tabs.Champ;
		if (copy) t.EditRuleNumber = -1;
		t.readRows();
		ById('btchampSalvageMessages').innerHTML = tx("Simple rule saved")+"!";
		t.SalvageItems = []; // force reset of items to salvage
		t.paint_salvage_rules();
	},

	readAdvancedRows: function () {
		var t = Tabs.Champ;
		var cType = ById('btchampSalvageCardType').value;
		var faction = ById('btchampSalvageFactionType').value;
		var conditions = [];
		for (var i=1;i<=5;i++) {
			var row = ById("btchampSalvageRow"+i+"Advanced");
			var minTier = parseIntNan(ById("btchampSalvageRow"+i+"MinTier").value)||1;
			if (row.selectedIndex == 0) continue;
			var slots = [];
			for (var slotChecker = 1; slotChecker<=5;slotChecker++) {
				slots.push(slotChecker==i);
			}
			var buffDebuff = "b";
			var effect = row.options[row.selectedIndex].value;
			if (effect=="Troop" || effect=="Champion") {
				var buffDebuff = "e";
			}
			else {
				if (DebuffEffects.indexOf(parseInt(effect))!=-1) buffDebuff = "d";
			}
			var c = new t.ChampCondition(true, 1, effect, buffDebuff, slots, minTier);
			conditions.push(c);
		}
		if (conditions.length > 0) {
			var rule1 = new t.ChampRule(cType, faction, conditions, true);
			if (t.EditRuleNumber<0) { t.SalvageAddRule(rule1); }
			else { t.SalvageReplaceRule(rule1); }
		}
	},

	SaveAdvancedRule : function (copy) {
		var t = Tabs.Champ;

		var rulesOK = false;
		for (var i=1;i<=5;i++) {
			var row = ById("btchampSalvageRow"+i+"Advanced");
			if (row.selectedIndex != 0) {
				rulesOK = true;
				break;
			}
		}
		if (!rulesOK) {
			ById('btchampSalvageMessages').innerHTML = tx("No effects selected - Cannot save advanced rule")+"!";
			return;
		}

		if (copy) t.EditRuleNumber = -1;
		t.readAdvancedRows();
		ById('btchampSalvageMessages').innerHTML = tx("Advanced rule saved")+"!";
		t.SalvageItems = []; // force reset of items to salvage
		t.paint_salvage_rules();
	},

	pickAetherUpgradeCity : function(citynum,StonesRequired) {
		var t = Tabs.Champ;
		if (Options.ChampOptions.UpgradeMinAether > StonesRequired) { StonesRequired = Options.ChampOptions.UpgradeMinAether; }
		if (!Options.ChampOptions.UpgradeAnyCity || parseInt(Seed.resources["city"+Seed.cities[citynum][0]]["rec5"][0]) >= StonesRequired) return citynum;
		var ind = citynum;
		var highest = 0;

		for (var i=1;i<=Seed.cities.length; i++) {
			var ii=citynum+i;
			if (ii>=Seed.cities.length) ii-=Seed.cities.length;
			cityId = Seed.cities[ii][0];
			if (Options.ChampOptions.UpgradeOverflow == "highest") {
				if (parseInt(Seed.resources["city"+cityId]["rec5"][0]) > highest) {
					highest = +Seed.resources["city"+cityId]["rec5"][0];
					ind = ii;
				}
			}
			else {
				if (parseInt(Seed.resources["city"+cityId]["rec5"][0]) >= StonesRequired) {
					return ii;
				}
			}
		}
		return ind;
	},

	// COMPARE FUNCTIONS

	GetInventory : function (chID,num,div) {
		var t = Tabs.Champ;
		var Presets = [];
		var m = '';
		var champ_item = uW.kocChampionItems[chID];
		if (champ_item && champ_item.equippedTo) {
			Presets.push(champ_item.equippedTo);
		}

		if (Presets.length > 0) { m = '<br><b>'+tx('Equipped to Champion')+'</b><br><TABLE cellspacing=0 cellpadding=0><TR>'; }

		for (var i=0;i<Presets.length;i++) {
			for (var y in Seed.champion.champions) {
				if (Seed.champion.champions[y].championId && Seed.champion.champions[y].championId==Presets[i]) {
					var chkchamp = Seed.champion.champions[y];
					m += '<TD id="trchampcm'+num+Presets[i]+'td" class="xtab trimg" style="font-weight:normal;align:left;padding-right: 2px;"><a><img id="trchampcm'+num+Presets[i]+'" onMouseover="btCreateChampionPopUp(this,'+(chkchamp.assignedCity?chkchamp.assignedCity:0)+',true,'+chkchamp.championId+',false,true);" height=14 style="vertical-align:text-top;" src="'+ChampImagePrefix+chkchamp.avatarId+ChampImageSuffix+'"></a></td><td class=xtab>'+chkchamp.name+'&nbsp;</td>';
					break;
				}
			}
		}
		m += '</tr></table>';
		ById(div).innerHTML = m;
	},

	// GENERAL FUNCTIONS

	refreshInventory : function () {
		var t = Tabs.Champ;
		if (ById('itemInventory')) {
			CM.ChampionModalView.renderFilteredItems();
		}
	},

	getChampItemStats : function (chId, sep) {
		var t = Tabs.Champ;
		sep = sep || "	";
		var champ_item = uW.kocChampionItems[chId];
		if (!champ_item) return "";
		var D = [];
		D.push(champ_item.name.replace(/\'/g, ""));
		D.push(uW.g_js_strings.commonstr.faction + ": " + uW.g_js_strings.commonstr[cardFaction[champ_item.faction-1]]);
		D.push(uW.g_js_strings.commonstr.quality + ": " + (champ_item.unique?uW.g_js_strings.throneRoom.unique:cardQuality[champ_item.rarity]));
		D.push(uW.g_js_strings.commonstr.type + ": " + uW.g_js_strings.champ[chTypeStrings[champ_item.type-1]]);
//		D.push(uW.g_js_strings.commonstr.level + ": " + champ_item.level);
		if (Options.ChampOptions.ChatPostShowMight) {
			D.push(uW.g_js_strings.commonstr.might + ": " + addCommas(CardMight(champ_item,true)));
		}

		for (var slot in champ_item.effects) {
			try {
				var N = champ_item.effects[slot];
				effect = uW.g_js_strings.effects["name_"+N.id];
				var level = champ_item.level || 0;

				percent = getCHSlotStat(N,level);
				percent = (N.id>=300)?percent+'%':percent;
				D.push("Row " + slot + ": " + percent + " " + effect);
			}
			catch (e) { }
		}
		var cText = D.join(sep);
		if (sep == "||") cText = ":::. |" + cText;
		return cText;
	},

	getChampID : function (presetIndex) {
		var thisChampion = Seed.champion.champions[presetIndex-1];
		return thisChampion.championId;
	},

	getChampName : function (presetIndex) {
		var thisChampion = Seed.champion.champions[presetIndex-1];
		return thisChampion.name;
	},

	PostChampSlot : function (slot) {
		var t = Tabs.Champ;
		var champId = t.getChampID(slot);
		var chCards = [];
		for (var y in uW.kocChampionItems) {
			var champ_item = uW.kocChampionItems[y];
			if (champ_item.equippedTo && champ_item.equippedTo==champId) {
				chCards.push(champ_item.equipmentId);
			}
		}
		var champStats = t.GenerateChampionEffectsString(chCards, false);
		D = [];
		D.push(tx('Champion')+' #'+slot);
		D.push(t.getChampName(slot));
		if (Options.ChampOptions.ChatPostShowMight) {
			D.push(tx('Might')+': '+addCommas(t.getChampionMight(chCards)));
		}
		D.push(champStats);
		sendChat(":::. |" + D.join("||"));
	},

	GenerateChampionEffectsString : function (chCards,htmlEffects,Colours) {
		var t = Tabs.Champ;
		var equippedchampstats = JSON.parse(JSON.stringify(BaseChamp));
		var equippedtroopstats = {};
		var equippedbossstats = {};
		var SetBonus = {};
		var SteelHoofCount = 0;
		var LightBringerCount = 0;
		var DragonScaleCount = 0;
		var TestCount = 0;
		var WildHideCount = 0;
		var VespersCount = 0;
		var SilverCount = 0;
		var effectTiers = CE_EFFECT_TIERS;
		var Indent = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
		var J = new Array();

		if (htmlEffects) { J.push('<div><b>'+uW.g_js_strings.report_view.champion_stats+'</b></div>'); }
		else { J.push(uW.g_js_strings.report_view.champion_stats); }


		for (var y=0;y<chCards.length;y++) { // calculate unique set bonuses
			var item = uW.kocChampionItems[chCards[y]];
			if (!item.quality) item.quality = parseIntNan(item.rarity);
			item.level = parseIntNan(item.level);
			if (SteelHoofItems.indexOf(parseIntNan(item.unique)) !== -1) { SteelHoofCount++ }
			if (LightBringerItems && LightBringerItems.indexOf(parseIntNan(item.unique)) !== -1) { LightBringerCount++ }
			if (DragonScaleItems && DragonScaleItems.indexOf(parseIntNan(item.unique)) !== -1) { DragonScaleCount++ }
			if (TestItems && TestItems.indexOf(parseIntNan(item.unique)) !== -1) { TestCount++ }
			if (WildHideItems && WildHideItems.indexOf(parseIntNan(item.unique)) !== -1) { WildHideCount++ }
			if (VespersItems && VespersItems.indexOf(parseIntNan(item.unique)) !== -1) { VespersCount++ }
			if (SilverItems && SilverItems.indexOf(parseIntNan(item.unique)) !== -1) { SilverCount++ }

			for (var e in item.effects) {
				if (Number(e) <= Number(item.rarity)) {
					var id = item.effects[e].id;
					if (id >= 300 && id < 400) {
						var Set = item.set;
						var tier = item.effects[e].tier;
						if (id==312) Set = 'U';
						if (id==313) Set = 'N';
						if (id==314) Set = 'D';
						var S = effectTiers;
						var P = id + "," + tier;
						var TV = S[P];
						while (!TV && (tier > 0)) { tier--;P=id+","+tier;TV=S[P]; }
						if (TV) {
							var base = +TV.Base || 0;
							var growth = +TV.Growth || 0;
							var level = Number(item.level) || 0;
							percent = Number(base + (level * growth));
							if (!SetBonus[Set]) { SetBonus[Set] = 0; }
							SetBonus[Set] += percent;
						}
					}
				}
			}
		}
		for (var y=0;y<chCards.length;y++) {
			var item = uW.kocChampionItems[chCards[y]];
			if (!item.quality) item.quality = parseIntNan(item.rarity);
			item.level = parseIntNan(item.level);
			for (var e in item.effects) {
				if (Number(e) <= Number(item.rarity)) {
					var id = item.effects[e].id;
					var tier = item.effects[e].tier;
					var S = effectTiers;
					var P = id + "," + tier;
					var TV = S[P];
					while (!TV && (tier > 0)) { tier--;P=id+","+tier;TV=S[P]; }
					if (TV) {
						var base = +TV.Base || 0;
						var growth = +TV.Growth || 0;
						var level = Number(item.level) || 0;
						var bonus = 0;
						if (id<300 || id>=400) {
							bonus = SetBonus[item.set] || 0;
							if (item.unique && item.unique!=0 && SetBonus['U']) bonus += SetBonus['U'];
							if ((!item.unique || item.unique==0) && SetBonus['N']) bonus += SetBonus['N'];
							//if (SetBonus['D']) bonus += SetBonus['D'];
						}
						var percent = Number(base + ((level * level + level) * growth * 0.5));
						if (id >= 300) {
							percent = Number(base + (level * growth));
						}
						if (id>=400) {
							if (!equippedbossstats[item.unique]) { equippedbossstats[item.unique] = {}; }
							if (!equippedbossstats[item.unique][id]) { equippedbossstats[item.unique][id] = 0; }
							equippedbossstats[item.unique][id] += percent + (percent*bonus); // can this apply to boss stats?
						}
						else {
							if (id>=200) {
								if (!equippedchampstats[id]) { equippedchampstats[id] = 0; }
								equippedchampstats[id] += percent + (percent*bonus);
							}
							else {
								if (!equippedtroopstats[id]) { equippedtroopstats[id] = 0; }
								equippedtroopstats[id] += percent;
							}
						}
					}
				}
			}
		}
		var gotchamp = false;
		for (var k in equippedchampstats) {
			gotchamp = true;
			str = uW.g_js_strings.effects['name_'+k];
			var chEffect = getChampCappedValue(k,equippedchampstats[k]);
			if (k>= 300) {
				var pre = '';
				var post = '';
				if (htmlEffects && Colours) {
					pre = '<span style="color:#808;">';
					post = '</span>';
				}
				if (k==314) { str = pre+tx('Add. Defend Bonus'); }
				else { str = pre+tx('Inc. Bonus')+' '+str.split(" "+tx("equipment"))[0]; }
				var champvalue = +((chEffect*100).toFixed(2))+"%"+post;
			}
			else {
				var champvalue = +(chEffect.toFixed(2));
			}
			if (str && str!= "") {
				if (htmlEffects) {
					J.push('<div>'+Indent+str+' '+champvalue+'</div>');
				}
				else { J.push(Indent+str+' '+champvalue); }
			}
		}
		if (VespersCount >= 4) {
			gotchamp = true;
			if (htmlEffects) {
				if (Colours) {
					J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.vespers+": "+uW.g_js_strings.champ.damage+"&nbsp;"+CM.CHAMPION.getVespersDamageSetBonus().replace('+','')+"</div>");
				}
				else {
					J.push("<div>"+Indent+uW.g_js_strings.champ.vespers+": "+uW.g_js_strings.champ.damage+"&nbsp;"+CM.CHAMPION.getVespersDamageSetBonus().replace('+','')+"</div>");
				}
			}
			else { J.push(Indent+uW.g_js_strings.champ.vespers+": "+uW.g_js_strings.champ.damage+" "+CM.CHAMPION.getVespersDamageSetBonus().replace('+','')); }
		}
		
		if (!gotchamp) {
			if (htmlEffects) { J.push('<div><i>'+Indent+'None Available</i></div>'); }
			else { J.push(Indent+'None Available'); }
		}
		if (htmlEffects) { J.push('<div><b>'+uW.g_js_strings.report_view.troop_stats+'</b></div>'); }
		else { J.push(uW.g_js_strings.report_view.troop_stats); }
		var gottroops = false;
		if ((SteelHoofCount >= 4 && LightBringerCount >= 5) || (DragonScaleCount >= 6 && LightBringerCount >= 5)) {
			gottroops = true;
			if (htmlEffects) {
				if (Colours) {
					if (SteelHoofCount >= 4 && LightBringerCount >= 5) {
						J.push("<div style='color:#880;'>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackRange+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
					else {
						J.push("<div style='color:#880;'>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackLife+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
				}
				else {
					if (SteelHoofCount >= 4 && LightBringerCount >= 5) {
						J.push("<div>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackRange+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
					else {
						J.push("<div>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackLife+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
				}
			}
			else {
				if (SteelHoofCount >= 4 && LightBringerCount >= 5) {
					J.push(Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackRange+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
				}
				else {
					J.push(Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackLife+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
				}
			}
		} else {
			if (SteelHoofCount >= 4 || DragonScaleCount >= 6) {
				gottroops = true;
				if (htmlEffects) {
					if (Colours) {
						if (SteelHoofCount >= 4) {
							J.push("<div style='color:#080;'>"+Indent+uW.g_js_strings.champ.steelhoofsBonus+": "+uW.g_js_strings.champ.range+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
						else {
							J.push("<div style='color:#080;'>"+Indent+uW.g_js_strings.champ.dragonscalesBonus+": "+uW.g_js_strings.champ.life+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
					}
					else {
						if (SteelHoofCount >= 4) {
							J.push("<div>"+Indent+uW.g_js_strings.champ.steelhoofsBonus+": "+uW.g_js_strings.champ.range+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
						else {
							J.push("<div>"+Indent+uW.g_js_strings.champ.dragonscalesBonus+": "+uW.g_js_strings.champ.life+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
					}
				}
				else {
					if (SteelHoofCount >= 4) {
						J.push(Indent+uW.g_js_strings.champ.steelhoofsBonus+": "+uW.g_js_strings.champ.range+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
					}
					else {
						J.push(Indent+uW.g_js_strings.champ.dragonscalesBonus+": "+uW.g_js_strings.champ.life+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
					}
				}
			} else {
				if (LightBringerCount >= 5) {
					gottroops = true;
					if (htmlEffects) {
						if (Colours) {
							J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.lightbringersBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getLightbringersRangeSetBonus().replace('+','')+"</div>");
						}
						else {
							J.push("<div>"+Indent+uW.g_js_strings.champ.lightbringersBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getLightbringersRangeSetBonus().replace('+','')+"</div>");
						}
					}
					else { J.push(Indent+uW.g_js_strings.champ.lightbringersBonus+": "+uW.g_js_strings.champ.attack+" "+CM.CHAMPION.getLightbringersRangeSetBonus().replace('+','')); }
				}
				else {
					if (WildHideCount >= 5) {
						gottroops = true;
						if (htmlEffects) {
							if (Colours) {
								J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.wildhideBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getWildhideAttackSetBonus().replace('+','')+"</div>");
							}
							else {
								J.push("<div>"+Indent+uW.g_js_strings.champ.wildhideBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getWildhideAttackSetBonus().replace('+','')+"</div>");
							}
						}
						else { J.push(Indent+uW.g_js_strings.champ.wildhideBonus+": "+uW.g_js_strings.champ.attack+" "+CM.CHAMPION.getWildhideAttackSetBonus().replace('+','')); }
					}
					else {
						if (SilverCount >= 5) {
							gottroops = true;
							if (htmlEffects) {
								if (Colours) {
									J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.silver+": "+uW.g_js_strings.champ.silverKnightBonus+"&nbsp;"+CM.CHAMPION.getSilverknightSpeedDefenceSetBonus().replace('+','')+"</div>");
								}
								else {
									J.push("<div>"+Indent+uW.g_js_strings.champ.silver+": "+uW.g_js_strings.champ.silverKnightBonus+"&nbsp;"+CM.CHAMPION.getSilverknightSpeedDefenceSetBonus().replace('+','')+"</div>");
								}
							}
							else { J.push(Indent+uW.g_js_strings.champ.silver+": "+uW.g_js_strings.champ.silverKnightBonus+" "+CM.CHAMPION.getSilverknightSpeedDefenceSetBonus().replace('+','')); }
						}
					}
				}
			}
		}

		for (var k in equippedtroopstats) {
			gottroops = true;
			str = uW.g_js_strings.effects['name_'+k];
			if (str && str!= "") {
				var chEffect = getChampCappedValue(k,equippedtroopstats[k]);
				if (htmlEffects) {
					if (Colours) {
						var TRStyles = getTREffectStyle(k);
						J.push("<div>"+TRStyles.LineStyle+Indent+str+" "+(Math.round(chEffect*100)/100)+TRStyles.EndStyle+"</div>");
					}
					else {
						J.push("<div>"+Indent+str+" "+(Math.round(chEffect*100)/100)+"</div>");
					}
				}
				else { J.push(Indent+str+" "+(Math.round(chEffect*100)/100)); }
			}
		}
		if (!gottroops) {
			if (htmlEffects) { J.push('<div><i>'+Indent+'None Available</i></div>'); }
			else { J.push(Indent+'None Available'); }
		}
		for (var k in equippedbossstats) {
			var gotboss = false;
			var K = [];
			for (var kk in equippedbossstats[k]) {
				gotboss = true;
				str = uW.g_js_strings.effects['name_'+kk];
				if (str && str!= "") {
					var chEffect = getChampCappedValue(kk,equippedbossstats[k][kk]);
					var champvalue = +(chEffect.toFixed(2))+"%";
					if (htmlEffects) { K.push("<div>"+Indent+str+" "+champvalue+"</div>"); }
					else { K.push(Indent+str+" "+champvalue); }
				}
			}
			if (gotboss) {
				if (htmlEffects) { J.push('<div><b>'+uW.itemlist['i'+k].name+' '+uW.g_js_strings.commonstr.stats+'</b></div>'); }
				else { J.push(uW.itemlist['i'+k].name+' '+uW.g_js_strings.commonstr.stats); }
				for (var j=0;j<K.length;j++) {
					J.push(K[j]);
				}
			}
		}

		if (htmlEffects == true) {
			return J.join("");
		} else {
			return J.join("||");
		}
	},

	PostPreviewSlot : function() {
		var t = Tabs.Champ;
		var D = [];
		D.push(tx('Champion Preview'));
		if (Options.ChampOptions.ChatPostShowMight) {
			var chCards = [];
			for (var y in t.PreviewCards) {
				var champ_item = uW.kocChampionItems[t.PreviewCards[y]];
				if (champ_item) {
					chCards.push(champ_item.equipmentId);
				}
			}
			D.push(tx('Might')+': '+addCommas(t.getChampionMight(chCards)));
		}
		D.push(t.GeneratePreviewStats());
		sendChat(":::. |" + D.join("||"));
	},

	getChampionMight : function(cards) {
		var t = Tabs.Champ;
		var might = 0;
		for (var k=0;k<cards.length;k++) {
			var champ_item = uW.kocChampionItems[cards[k]];
			if (champ_item) {
				might += CardMight(champ_item,true);
			}
		}
		return might;
	},

	ConvertToCard : function (chId,div,Links,ScaleFactor,nomenu,showChamp,FromSearch) {
		var t = Tabs.Champ;
		div.innerHTML = '';
		var CHCard = uW.kocChampionItems[chId];
		if (CHCard) {
			div.innerHTML = Tabs.Reference.DisplayCHCard(CHCard,Links,ScaleFactor,showChamp);
			div.className = chId;

			if (!nomenu) {
				jQuery(div).click(function () {
					var chId = jQuery(this).attr("class");
					if (uW.kocChampionItems[chId]) {
						t.CustomChampContextMenu(chId, getAbsoluteOffsets(this).top, getAbsoluteOffsets(this).left,true,div,true,FromSearch);
					}
				});
			}
			return true;
		}
		return false;
	},

	showNextChampLevel: function () {
		var t = Tabs.Champ;
		if (t.SelectedItem < 0) return;
		if (jQuery('#champUpgTab.active').length==0) return;
		t.NextLevel++;
		if (t.NextLevel > CM.CHAMPION.MAX_LEVELS) return;

		var elemStatTitle = document.getElementsByClassName('upgEnhStatsTitle')[1];
		elemStatTitle.innerHTML = uW.g_js_strings.commonstr.level+' ' + t.NextLevel;

		var elemStatBody = document.getElementById('upgEnhStatsBodyTarget');
		var elemStatItems = elemStatBody.getElementsByTagName("li");

		var X = uW.kocChampionItems[t.SelectedItem];

		for (var elemIndex = 0; elemIndex < elemStatItems.length; ++elemIndex) {
			var elemItem = elemStatItems[elemIndex];
			var slotNumber = elemIndex + 1;
			var effectLine = X.effects[slotNumber];
			var effect = CM.ChampionManager.getEffect(effectLine, t.NextLevel);
			elemItem.innerHTML = effect.name + " " + effect.amount;
		}
	},

	ViewChampCards : function (uid, name, ChampId, ChampName, ChampCards) {
		var t = Tabs.Champ;

		if (name!="") { var poptitle=name+' - '+ChampName; }
		else { var poptitle = ChampName; }

		t.PopCards = {};
		for (var ii in ChampCards) {
			var EQ = ChampCards[ii];
			var CHCard = {};
			CHCard.id = EQ.equipmentId;
			CHCard.unique = parseIntNan(EQ.itemId);
			CHCard.quality = parseIntNan(EQ.rarity);
			if (CHCard.unique) { CHCard.name = uW.ksoItems[+CHCard.unique].name+' +'+EQ.level; }
			if (!CHCard.name) { CHCard.name = CardQuality(CHCard.rarity)+" "+uW.g_js_strings.champ[chTypeStrings[parseInt(EQ.type)-1]]+" "+uW.g_js_strings.commonstr.of+" "+uW.g_js_strings.effects["suffix_"+EQ["effects"][5]["id"]]+' +'+EQ.level; }
			CHCard.faction = EQ.faction;
			CHCard.type = EQ.type;
			CHCard.level = EQ.level;
			CHCard.rarity = EQ.rarity;
			CHCard.set = EQ.set;
			CHCard.createPrefix = function () { return ""; };
			CHCard.createSuffix = function () { return ""; };
			CHCard.effects = {};
			var slot = 0;
			for (var k in EQ.effects) {
				slot++
				CHCard.effects[slot] = {};
				CHCard.effects[slot].id = EQ.effects[k].id;
				CHCard.effects[slot].tier = EQ.effects[k].tier;
			}
			t.PopCards[ii] = CHCard;
		}

		var m = '';

		m += '<div style="width:100%;display:inline-block;">';
		m += '<table align=left class=xtabBR width=100% style="padding-right:0px;">';
		m += '<tr><td valign=top colspan=2><div class=divHeader><span id=btchamppoptitle style="display:inline-block;"><b>'+tx('Stats')+'</b></span></div><div id=btchamppoppreview>&nbsp;</div><div id=btchamppoppostdiv style="display:none;" align=center><br>'+strButton8('Post to Chat',' id=btchamppoppost')+'</div></td><td style="padding-right:0px;"><div style="max-width:'+(GlobalOptions.btWinSize.x-220)+'px;overflow-x:auto;max-height:1000px;overflow-y:auto;padding-right:0px;"><table cellpadding=0 cellspacing=0 style="padding-right:2px;border:1px solid;border-collapse:collapse;" class=xtab width=100%><tr>';

		var LineBreak = 3;

		for (var type_index = 0; type_index < chTypes.length; ++type_index) {
			if (type_index % LineBreak == 0) m += '</tr><tr>';
			m += '<td valign=top style="padding:2px;overflow:visible;width:180px;height:auto;border:1px solid;">';
			m += '<div id=btchampPopItemHead' + chTypes[type_index] + ' ><div style="text-transform:capitalize;"><b>'+uW.g_js_strings.champ[chTypes[type_index]]+'</b></div></div>';
			m += '<div id=btchampPopItem' + chTypes[type_index] + ' style="min-height:200px;">&nbsp;</div>';
			m += '</td>';
		}

		m += '</tr></table></div></td></tr>';
		m += '</table></div>';
		m += '<div align=center>'+strButton20(tx('Refresh'), 'id=btchamppoprefresh')+'</div>';

		if (t.popChamp) {
			t.popChamp.show(false);
			if (t.popChamp.onClose) t.popChamp.onClose();
			t.popChamp.destroy();
			t.popChamp = null;
		}
		t.popChamp = new CPopup ('PBPChampPopup', t.popuppos.x, t.popuppos.y, GlobalOptions.btWinSize.x, 300, true, function () {
			t.popuppos = t.popChamp.getLocation();
			clearTimeout(1000);
		});
		if ((t.popuppos.x == -999) && (t.popuppos.y == -999)) {
			t.popChamp.centerMe(mainPop.getMainDiv());
		}
		t.popChamp.getMainDiv().innerHTML = m;
		t.popChamp.getTopDiv().innerHTML = '<CENTER><B>'+poptitle+'</b></center>';
		t.popChamp.show (true);

		for (var ii in t.PopCards) {
			ById('btchampPopItem' + ii).innerHTML = Tabs.Reference.DisplayCHCard(t.PopCards[ii],false,t.PreviewCardScale);
		}

		ById('btchamppoppreview').innerHTML = t.GeneratePopEffectsString(t.PopCards,true,true);
		if (jQuery.isEmptyObject(t.PopCards)) { ById('btchamppoppostdiv').style.display='none'; }
		else { ById('btchamppoppostdiv').style.display=''; }

		ById('btchamppoppost').addEventListener('click',function() { t.PostPopSlot(uid,poptitle,t.PopCards); }, false);
		ById('btchamppoprefresh').addEventListener('click',function() {t.FetchChampion(uid, name, ChampId, ChampName, t.ViewChampCards);}, false);

		ResetFrameSize('PBPChampPopup',300,GlobalOptions.btWinSize.x);
	},

	GeneratePopEffectsString : function (chCards,htmlEffects,Colours) {
		var t = Tabs.Champ;
		var equippedchampstats = JSON.parse(JSON.stringify(BaseChamp));
		var equippedtroopstats = {};
		var equippedbossstats = {};
		var SetBonus = {};
		var SteelHoofCount = 0;
		var LightBringerCount = 0;
		var DragonScaleCount = 0;
		var TestCount = 0;
		var WildHideCount = 0;
		var VespersCount = 0;
		var SilverCount = 0;
		var effectTiers = CE_EFFECT_TIERS;
		var Indent = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
		var J = new Array();

		if (htmlEffects) { J.push('<div><b>'+uW.g_js_strings.report_view.champion_stats+'</b></div>'); }
		else { J.push(uW.g_js_strings.report_view.champion_stats); }


		for (var y in chCards) { // calculate unique set bonuses
			var item = chCards[y];
			if (!item.quality) item.quality = parseIntNan(item.rarity);
			item.level = parseIntNan(item.level);
			if (SteelHoofItems.indexOf(parseIntNan(item.unique)) !== -1) { SteelHoofCount++ }
			if (LightBringerItems && LightBringerItems.indexOf(parseIntNan(item.unique)) !== -1) { LightBringerCount++ }
			if (DragonScaleItems && DragonScaleItems.indexOf(parseIntNan(item.unique)) !== -1) { DragonScaleCount++ }
			if (TestItems && TestItems.indexOf(parseIntNan(item.unique)) !== -1) { TestCount++ }
			if (WildHideItems && WildHideItems.indexOf(parseIntNan(item.unique)) !== -1) { WildHideCount++ }
			if (VespersItems && VespersItems.indexOf(parseIntNan(item.unique)) !== -1) { VespersCount++ }
			if (SilverItems && SilverItems.indexOf(parseIntNan(item.unique)) !== -1) { SilverCount++ }

			for (var e in item.effects) {
				if (Number(e) <= Number(item.rarity)) {
					var id = item.effects[e].id;
					if (id >= 300 && id < 400) {
						var Set = item.set;
						var tier = item.effects[e].tier;
						if (id==312) Set = 'U';
						if (id==313) Set = 'N';
						if (id==314) Set = 'D';
						var S = effectTiers;
						var P = id + "," + tier;
						var TV = S[P];
						while (!TV && (tier > 0)) { tier--;P=id+","+tier;TV=S[P]; }
						if (TV) {
							var base = +TV.Base || 0;
							var growth = +TV.Growth || 0;
							var level = Number(item.level) || 0;
							percent = Number(base + (level * growth));
							if (!SetBonus[Set]) { SetBonus[Set] = 0; }
							SetBonus[Set] += percent;
						}
					}
				}
			}
		}
		for (var y in chCards) {
			var item = chCards[y];
			if (!item.quality) item.quality = parseIntNan(item.rarity);
			item.level = parseIntNan(item.level);
			for (var e in item.effects) {
				if (Number(e) <= Number(item.rarity)) {
					var id = item.effects[e].id;
					var tier = item.effects[e].tier;
					var S = effectTiers;
					var P = id + "," + tier;
					var TV = S[P];
					while (!TV && (tier > 0)) { tier--;P=id+","+tier;TV=S[P]; }
					if (TV) {
						var base = +TV.Base || 0;
						var growth = +TV.Growth || 0;
						var level = Number(item.level) || 0;
						var bonus = 0;
						if (id<300 || id>=400) {
							bonus = SetBonus[item.set] || 0;
							if (item.unique && item.unique!=0 && SetBonus['U']) bonus += SetBonus['U'];
							if ((!item.unique || item.unique==0) && SetBonus['N']) bonus += SetBonus['N'];
							//if (SetBonus['D']) bonus += SetBonus['D'];
						}
						var percent = Number(base + ((level * level + level) * growth * 0.5));
						if (id >= 300) {
							percent = Number(base + (level * growth));
						}
						if (id>=400) {
							if (!equippedbossstats[item.unique]) { equippedbossstats[item.unique] = {}; }
							if (!equippedbossstats[item.unique][id]) { equippedbossstats[item.unique][id] = 0; }
							equippedbossstats[item.unique][id] += percent + (percent*bonus); // can this apply to boss stats?
						}
						else {
							if (id>=200) {
								if (!equippedchampstats[id]) { equippedchampstats[id] = 0; }
								equippedchampstats[id] += percent + (percent*bonus);
							}
							else {
								if (!equippedtroopstats[id]) { equippedtroopstats[id] = 0; }
								equippedtroopstats[id] += percent;
							}
						}
					}
				}
			}
		}
		var gotchamp = false;
		for (var k in equippedchampstats) {
			gotchamp = true;
			str = uW.g_js_strings.effects['name_'+k];
			var chEffect = getChampCappedValue(k,equippedchampstats[k]);
			if (k>= 300) {
				var pre = '';
				var post = '';
				if (htmlEffects && Colours) {
					pre = '<span style="color:#808;">';
					post = '</span>';
				}
				if (k==314) { str = pre+tx('Add. Defend Bonus'); }
				else { str = pre+tx('Inc. Bonus')+' '+str.split(" "+tx("equipment"))[0]; }
				var champvalue = +((chEffect*100).toFixed(2))+"%"+post;
			}
			else {
				var champvalue = +(chEffect.toFixed(2));
			}
			if (str && str!= "") {
				if (htmlEffects) {
					J.push('<div>'+Indent+str+' '+champvalue+'</div>');
				}
				else { J.push(Indent+str+' '+champvalue); }
			}
		}
		if (VespersCount >= 4) {
			gotchamp = true;
			if (htmlEffects) {
				if (Colours) {
					J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.vespers+": "+uW.g_js_strings.champ.damage+"&nbsp;"+CM.CHAMPION.getVespersDamageSetBonus().replace('+','')+"</div>");
				}
				else {
					J.push("<div>"+Indent+uW.g_js_strings.champ.vespers+": "+uW.g_js_strings.champ.damage+"&nbsp;"+CM.CHAMPION.getVespersDamageSetBonus().replace('+','')+"</div>");
				}
			}
			else { J.push(Indent+uW.g_js_strings.champ.vespers+": "+uW.g_js_strings.champ.damage+" "+CM.CHAMPION.getVespersDamageSetBonus().replace('+','')); }
		}

		if (!gotchamp) {
			if (htmlEffects) { J.push('<div><i>'+Indent+'None Available</i></div>'); }
			else { J.push(Indent+'None Available'); }
		}
		if (htmlEffects) { J.push('<div><b>'+uW.g_js_strings.report_view.troop_stats+'</b></div>'); }
		else { J.push(uW.g_js_strings.report_view.troop_stats); }
		var gottroops = false;
		if ((SteelHoofCount >= 4 && LightBringerCount >= 5) || (DragonScaleCount >= 6 && LightBringerCount >= 5)) {
			gottroops = true;
			if (htmlEffects) {
				if (Colours) {
					if (SteelHoofCount >= 4 && LightBringerCount >= 5) {
						J.push("<div style='color:#880;'>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackRange+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
					else {
						J.push("<div style='color:#880;'>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackLife+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
				}
				else {
					if (SteelHoofCount >= 4 && LightBringerCount >= 5) {
						J.push("<div>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackRange+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
					else {
						J.push("<div>"+Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackLife+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
					}
				}
			}
			else {
				if (SteelHoofCount >= 4 && LightBringerCount >= 5) {
					J.push(Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackRange+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
				}
				else {
					J.push(Indent+uW.g_js_strings.champ.doubleBonus+": "+uW.g_js_strings.champ.attackLife+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
				}
			}
		} else {
			if (SteelHoofCount >= 4 || DragonScaleCount >= 6) {
				gottroops = true;
				if (htmlEffects) {
					if (Colours) {
						if (SteelHoofCount >= 4) {
							J.push("<div style='color:#080;'>"+Indent+uW.g_js_strings.champ.steelhoofsBonus+": "+uW.g_js_strings.champ.range+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
						else {
							J.push("<div style='color:#080;'>"+Indent+uW.g_js_strings.champ.dragonscalesBonus+": "+uW.g_js_strings.champ.life+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
					}
					else {
						if (SteelHoofCount >= 4) {
							J.push("<div>"+Indent+uW.g_js_strings.champ.steelhoofsBonus+": "+uW.g_js_strings.champ.range+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
						else {
							J.push("<div>"+Indent+uW.g_js_strings.champ.dragonscalesBonus+": "+uW.g_js_strings.champ.life+"&nbsp;"+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+','')+"</div>");
						}
					}
				}
				else {
					if (SteelHoofCount >= 4) {
						J.push(Indent+uW.g_js_strings.champ.steelhoofsBonus+": "+uW.g_js_strings.champ.range+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
					}
					else {
						J.push(Indent+uW.g_js_strings.champ.dragonscalesBonus+": "+uW.g_js_strings.champ.life+" "+CM.CHAMPION.getSteelhoofsRangeSetBonus().replace('+',''));
					}
				}
			} else {
				if (LightBringerCount >= 5) {
					gottroops = true;
					if (htmlEffects) {
						if (Colours) {
							J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.lightbringersBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getLightbringersRangeSetBonus().replace('+','')+"</div>");
						}
						else {
							J.push("<div>"+Indent+uW.g_js_strings.champ.lightbringersBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getLightbringersRangeSetBonus().replace('+','')+"</div>");
						}
					}
					else { J.push(Indent+uW.g_js_strings.champ.lightbringersBonus+": "+uW.g_js_strings.champ.attack+" "+CM.CHAMPION.getLightbringersRangeSetBonus().replace('+','')); }
				}
				else {
					if (WildHideCount >= 5) {
						gottroops = true;
						if (htmlEffects) {
							if (Colours) {
								J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.wildhideBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getWildhideAttackSetBonus().replace('+','')+"</div>");
							}
							else {
								J.push("<div>"+Indent+uW.g_js_strings.champ.wildhideBonus+": "+uW.g_js_strings.champ.attack+"&nbsp;"+CM.CHAMPION.getWildhideAttackSetBonus().replace('+','')+"</div>");
							}
						}
						else { J.push(Indent+uW.g_js_strings.champ.wildhideBonus+": "+uW.g_js_strings.champ.attack+" "+CM.CHAMPION.getWildhideAttackSetBonus().replace('+','')); }
					}
					else {
						if (SilverCount >= 5) {
							gottroops = true;
							if (htmlEffects) {
								if (Colours) {
									J.push("<div style='color:#800;'>"+Indent+uW.g_js_strings.champ.silver+": "+uW.g_js_strings.champ.silverKnightBonus+"&nbsp;"+CM.CHAMPION.getSilverknightSpeedDefenceSetBonus().replace('+','')+"</div>");
								}
								else {
									J.push("<div>"+Indent+uW.g_js_strings.champ.silver+": "+uW.g_js_strings.champ.silverKnightBonus+"&nbsp;"+CM.CHAMPION.getSilverknightSpeedDefenceSetBonus().replace('+','')+"</div>");
								}
							}
							else { J.push(Indent+uW.g_js_strings.champ.silver+": "+uW.g_js_strings.champ.silverKnightBonus+" "+CM.CHAMPION.getSilverknightSpeedDefenceSetBonus().replace('+','')); }
						}
					}
				}
			}
		}

		for (var k in equippedtroopstats) {
			gottroops = true;
			str = uW.g_js_strings.effects['name_'+k];
			if (str && str!= "") {
				var chEffect = getChampCappedValue(k,equippedtroopstats[k]);
				if (htmlEffects) {
					if (Colours) {
						var TRStyles = getTREffectStyle(k);
						J.push("<div>"+TRStyles.LineStyle+Indent+str+" "+(Math.round(chEffect*100)/100)+TRStyles.EndStyle+"</div>");
					}
					else {
						J.push("<div>"+Indent+str+" "+(Math.round(chEffect*100)/100)+"</div>");
					}
				}
				else { J.push(Indent+str+" "+(Math.round(chEffect*100)/100)); }
			}
		}
		if (!gottroops) {
			if (htmlEffects) { J.push('<div><i>'+Indent+'None Available</i></div>'); }
			else { J.push(Indent+'None Available'); }
		}
		for (var k in equippedbossstats) {
			var gotboss = false;
			var K = [];
			for (var kk in equippedbossstats[k]) {
				gotboss = true;
				str = uW.g_js_strings.effects['name_'+kk];
				if (str && str!= "") {
					var chEffect = getChampCappedValue(kk,equippedbossstats[k][kk]);
					var champvalue = +(chEffect.toFixed(2))+"%";
					if (htmlEffects) { K.push("<div>"+Indent+str+" "+champvalue+"</div>"); }
					else { K.push(Indent+str+" "+champvalue); }
				}
			}
			if (gotboss) {
				if (htmlEffects) { J.push('<div><b>'+uW.itemlist['i'+k].name+' '+uW.g_js_strings.commonstr.stats+'</b></div>'); }
				else { J.push(uW.itemlist['i'+k].name+' '+uW.g_js_strings.commonstr.stats); }
				for (var j=0;j<K.length;j++) {
					J.push(K[j]);
				}
			}
		}

		if (htmlEffects == true) {
			return J.join("");
		} else {
			return J.join("||");
		}
	},

	getPopMight : function (chCards) {
		var t = Tabs.Champ;
		var might = 0;
		for (var champType in chCards) {
			var champ_item = chCards[champType];
			if (champ_item) {
				might += CardMight(champ_item,true);
			}
		}
		return might;
	},

	PostPopSlot : function (uid,name,chCards) {
		var t = Tabs.Champ;
		var D = [];
		D.push(name);
		if (Options.ChampOptions.ChatPostShowMight) {
			D.push(tx('Might')+': '+addCommas(t.getPopMight(chCards)));
		}
		D.push(t.GeneratePopEffectsString(chCards, false));
		sendChat(":::. |" + D.join("||"));
	},

	FetchChampion : function (uid,name,ChampId,ChampName,notify) {
		var t = Tabs.Champ;

		if (uid==0) uid = uW.tvuid;

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action = 'getEquipped';
		params.playerId = uid;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/otherChampionHall.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					var equipped = {};
					for (var c in rslt.champion.equipment) {
						var item = rslt.champion.equipment[c];
						if (item.equippedTo && item.equippedTo==ChampId) {
							var thisType = chTypeStrings[item.type-1];
							if (thisType=="ring") {
								if (!equipped["ring1"]) { thisType="ring1"; }
								else { thisType="ring2"; }
							}
							equipped[thisType] = item;
						}
					}
					notify(uid,name,ChampId,ChampName,equipped);
				}
			},
		},true); // no retry
	},

	UpgradeItem : function (chId,notify,buffItemId,auto,Qitem) {
		var t = Tabs.Champ;

		var champ_item = uW.kocChampionItems[chId];
		if (champ_item) {
			var StonesRequired = 0;
			if (t.UpgradeCost[champ_item.level+1]) { StonesRequired = t.UpgradeCost[champ_item.level+1].Aetherstones; }
			var num_city = t.pickAetherUpgradeCity(Options.ChampOptions.UpgradeCityNum,StonesRequired);
			var UpgradeCityId = Seed.cities[num_city][0];

			if (auto && parseInt(Seed.resources["city"+UpgradeCityId]["rec5"][0])<Options.ChampOptions.UpgradeMinAether) {
				t.UpgradeReturnStatus = tx('Not enough aetherstone to attempt upgrade');
				t.PaintUpgradeStatus();
				return;
			}

			if (StonesRequired > parseInt(Seed.resources["city"+UpgradeCityId]["rec5"][0])) {
				t.log(tx('Not enough aetherstones to upgrade'),'GENERAL',true);
				if (auto) {
					t.UpgradeReturnStatus = tx('Not enough aetherstone to upgrade');
					t.PaintUpgradeStatus();
					return;
				}
				else {
					if (notify) notify({ok:false,reason:'aether'},chId,0);
				}
			}
			else {
				var params = uW.Object.clone(uW.g_ajaxparams);
				params.action = CM.CHAMPION.CEI_UPGRADE;
				params.cityId = UpgradeCityId;
				params.eid = chId;
				if (buffItemId && Seed.items["i"+buffItemId] && Seed.items["i"+buffItemId]>0) {
					params.chanceItem = buffItemId;
				}
				else {
					params.chanceItem = 0;
				}
				params.aetherstones = StonesRequired;
				params.gems = 0;

				new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					loading: true,
					onSuccess: function (rslt) {
						var aetherbalance = 0;
						if (rslt.ok) {
							aetherbalance = rslt.aetherstones;
							Seed.resources["city"+UpgradeCityId]["rec5"][0] = parseIntNan(Seed.resources["city"+UpgradeCityId]["rec5"][0]) - parseIntNan(rslt.aetherstones);
							if (rslt.itemConsumed && rslt.itemConsumed.itemId != "0") CM.InventoryView.removeItemFromInventory(rslt.itemConsumed.itemId,rslt.itemConsumed.quantity);
							if (rslt.gems > 0) {
								t.log(tx('ACCIDENTAL GEM USE DETECTED'),'GENERAL',true);
								t.GemUseTripSwitch = true;
							}
							if (rslt.mightGain) { Seed.player.might += rslt.mightGain; }
							var champ_item = uW.kocChampionItems[params.eid];
							if (champ_item) {
								if (rslt.broken && rslt.broken=="yes") {
									t.SetItemStatus(chId,"level");
								}
								else {
									if (rslt.level > champ_item.level) { // success!
										champ_item.level = rslt.level;
										champ_item.name = champ_item.createName();
										rslt.success=true; // for stats
									}
									else {
										if (rslt.level < champ_item.level) { // bad news, it reverted
											t.log(tx('CHAMP CARD REVERTED FROM LEVEL')+' '+champ_item.level+' '+tx('TO')+' '+rslt.level,'GENERAL',true);
											champ_item.level = rslt.level;
											champ_item.name = champ_item.createName();
										}
									}
								}
							}
							t.refreshInventory();
						}
						else {
							t.FixItemStatus(rslt,chId,"level");
							t.log(tx('Upgrade Error')+' - '+rslt.feedback,'GENERAL',true);
						}
						if (notify) notify(rslt,params.eid,aetherbalance,Qitem);
					},
					onFailure: function () {
						t.log(tx('Server error on upgrade'),'GENERAL',true);
						if (auto) { return; }
						else {
							if (notify) notify({ok:false},params.eid,0);
						}
					},
				});
			}
		}
	},

	EnhanceItem : function (chId,notify,buffItemId,auto,Qitem) {
		var t = Tabs.Champ;

		var champ_item = uW.kocChampionItems[chId];
		if (champ_item) {
			var StonesRequired = 0;
			if (t.EnhanceCost[champ_item.rarity+1]) { StonesRequired = t.EnhanceCost[champ_item.rarity+1].Aetherstones; }
			var num_city = t.pickAetherUpgradeCity(Options.ChampOptions.UpgradeCityNum,StonesRequired);
			var UpgradeCityId = Seed.cities[num_city][0];

			if (auto && parseInt(Seed.resources["city"+UpgradeCityId]["rec5"][0])<Options.ChampOptions.UpgradeMinAether) {
				t.UpgradeReturnStatus = tx('Not enough aetherstone to attempt enhance');
				t.PaintUpgradeStatus();
				return;
			}

			if (StonesRequired > parseInt(Seed.resources["city"+UpgradeCityId]["rec5"][0])) {
				t.log(tx('Not enough aetherstones to enhance'),'GENERAL',true);
				if (auto) {
					t.UpgradeReturnStatus = tx('Not enough aetherstone to enhance');
					t.PaintUpgradeStatus();
					return;
				}
				else {
					if (notify) notify({ok:false,reason:'aether'},chId,0);
				}
			}
			else {
				var params = uW.Object.clone(uW.g_ajaxparams);
				params.action = CM.CHAMPION.CEI_ENHANCE;
				params.cityId = UpgradeCityId;
				params.eid = chId;
				if (buffItemId && Seed.items["i"+buffItemId] && Seed.items["i"+buffItemId]>0) {
					params.chanceItem = buffItemId;
				}
				else {
					params.chanceItem = 0;
				}
				params.aetherstones = StonesRequired;
				params.gems = 0;

				new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					loading: true,
					onSuccess: function (rslt) {
						var aetherbalance = 0;
						if (rslt.ok) {
							aetherbalance = rslt.aetherstones;
							Seed.resources["city"+UpgradeCityId]["rec5"][0] = parseIntNan(Seed.resources["city"+UpgradeCityId]["rec5"][0]) - parseIntNan(rslt.aetherstones);
							if (rslt.itemConsumed && rslt.itemConsumed.itemId != "0") CM.InventoryView.removeItemFromInventory(rslt.itemConsumed.itemId,rslt.itemConsumed.quantity);
							if (rslt.gems > 0) {
								t.log(tx('ACCIDENTAL GEM USE DETECTED'),'GENERAL',true);
								t.GemUseTripSwitch = true;
							}
							if (rslt.mightGain) { Seed.player.might += rslt.mightGain; }
							var champ_item = uW.kocChampionItems[params.eid];
							if (champ_item) {
								if (rslt.broken && rslt.broken=="yes") {
									t.SetItemStatus(chId,"quality");
								}
								else {
									if (rslt.rarity > champ_item.rarity) { // success!
										champ_item.rarity = rslt.rarity;
										champ_item.name = champ_item.createName();
										rslt.success=true; // for stats
									}
									else {
										if (rslt.rarity < champ_item.rarity) { // bad news, it reverted
											t.log(tx('CHAMP CARD REVERTED FROM')+' '+CardQuality(champ_item.rarity)+' '+tx('TO')+' '+CardQuality(rslt.rarity),'GENERAL',true);
											champ_item.rarity = rslt.rarity;
											champ_item.name = champ_item.createName();
										}
									}
								}
							}
							t.refreshInventory();
						}
						else {
							t.FixItemStatus(rslt,chId,"quality");
							t.log(tx('Enhance Error')+' - '+rslt.feedback,'GENERAL',true);
						}
						if (notify) notify(rslt,params.eid,aetherbalance,Qitem);
					},
					onFailure: function () {
						t.log(tx('Server error on enhance'),'GENERAL',true);
						if (auto) { return; }
						else {
							if (notify) notify({ok:false},params.eid,0);
						}
					},
				});
			}
		}
	},

	SetItemStatus: function (chId,brokenType,repairing) {
		var t = Tabs.Champ;
		var champ_item = uW.kocChampionItems[chId];
		if (champ_item) {
			if (repairing) {
				if (brokenType=="quality") {
					champ_item.status = CM.CHAMPION.STATUS_REPAIRING_ENHANCE;
				}
				else {
					champ_item.status = CM.CHAMPION.STATUS_REPAIRING_UPGRADE;
				}
			}
			else {
				if (brokenType=="quality") {
					champ_item.status = CM.CHAMPION.STATUS_BROKEN_ENHANCE;
				}
				else {
					champ_item.status = CM.CHAMPION.STATUS_BROKEN_UPGRADE;
				}
			}
			CM.ChampionManager.unequip(chId);
			t.refreshInventory();
		}
	},

	FixItemStatus: function (rslt,chId,brokenType) {
		var t = Tabs.Champ;
		var champ_item = uW.kocChampionItems[chId];
		if (champ_item) {
			if (rslt.feedback && rslt.feedback.indexOf("invalid status") > -1) { // broken item
				t.SetItemStatus(chId,brokenType);
			}
			if (rslt.feedback && rslt.feedback.indexOf("already under repair") > -1) { // item already being repaired
				t.SetItemStatus(chId,brokenType,true);
				CM.ChampionPanelView.restartRepairQueue();
			}
			if (rslt.feedback && rslt.feedback.indexOf("is not under correct status for repair") > -1) { // not broken after all?
				champ_item.status = 1;
				t.refreshInventory();
			}
			if (rslt.feedback && rslt.feedback.indexOf("equipment in repairing queue") > -1) { // there is already an item being repaired
				CM.ChampionPanelView.restartRepairQueue();
			}
		}
	},

	RepairItem: function (chId,action,notify) {
		var t = Tabs.Champ;
		var champ_item = uW.kocChampionItems[chId];
		if (champ_item) {
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.action = CM.CHAMPION.CEI_REPAIR;
			params.eid = chId;
			params.cityId = uW.currentcityid;
			params.gems = 0;

			new MyAjaxRequest(uW.g_ajaxpath + "ajax/ceEquipmentManagerAjax.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function (rslt) {
					var champ_item = uW.kocChampionItems[chId];
					if (rslt.ok) {
						if (champ_item.status == CM.CHAMPION.STATUS_BROKEN_ENHANCE) { champ_item.status = CM.CHAMPION.STATUS_REPAIRING_ENHANCE; }
						else { champ_item.status = CM.CHAMPION.STATUS_REPAIRING_UPGRADE; }
						var startTime = unixTime();
						var endTime = rslt.eta;
						if (!Seed.queue_champion) { Seed.queue_champion = uWCloneInto({}); }
						Seed.queue_champion.itemId = rslt.equipmentId;
						Seed.queue_champion.start = parseInt(rslt.start);
						Seed.queue_champion.end = parseInt(rslt.eta);
						if (!CM.ChampionPanelView.repairIntervals) {
							CM.ChampionPanelView.repairIntervals = setInterval(function () {
								CM.ChampionPanelView.doInterval(champ_item, (Seed.queue_champion.end - Seed.queue_champion.start), 0);
							}, 1000)
						}
						t.refreshInventory();
						t.paintUpgradeQueue();
						t.paintRepairQueue();
						t.log(tx('Repairing')+' '+champ_item.name,'REPAIR');
						setTimeout(t.autoSpeedup, 3000, action);
					}
					else {
						if (rslt.feedback == "Item is not broken") {
							uW.kocChampionItems[chId].status = 1;
							t.refreshInventory();
							t.paintUpgradeQueue();
							t.paintRepairQueue();
						}
						else {
							t.FixItemStatus(rslt,chId,"level"); // assume level brokenType
							t.log(tx('Error Repairing')+' '+champ_item.name+' - '+rslt.feedback,'REPAIR',true);
						}
					}
					if (notify) notify(chId);
				},
				onFailure: function () {
					t.log(tx('Server error on Repair'),'GENERAL',true);
					if (notify) notify(chId);
				}
			},true); // noretry
		}
	},

	autoSpeedup: function (action) {
		var t = Tabs.Champ;
		var now = unixTime();
		var item = 0;
		var totTime = 0;
		if (Seed.queue_champion && Seed.queue_champion.end) {
			totTime = Seed.queue_champion.end - now;
		}

		if (totTime > 0) {
			var chItem = uW.kocChampionItems[Seed.queue_champion.itemId];
			if (chItem) {
				// check applicable level/quality
				var UseSpeedups = true;
				if (chItem.rarity<Options.ChampOptions.RepairSpeedupMinQuality) { UseSpeedups = false; }
				if (chItem.level<Options.ChampOptions.RepairSpeedupMinLevel) { UseSpeedups = false; }
				if (!UseSpeedups) { return; }
			}
			else { return; } // no item?

			if (Options.ChampOptions.UseOverride && Options.ChampOptions.OverrideSpeedup != 0) {
				var THRESHOLD_SECONDS = (parseIntNan(Options.ChampOptions.OverrideMinutes)*60)+(parseIntNan(Options.ChampOptions.OverrideHours)*60*60);
				if (totTime >= THRESHOLD_SECONDS && uW.ksoItems[Options.ChampOptions.OverrideSpeedup].count > 0) { item = Options.ChampOptions.OverrideSpeedup; }
			}
			if (item==0 && totTime >= HourGlassThreshold[7] && Options.ChampOptions.UseEH && uW.ksoItems[8].count > 0) { item = 8; }
			if (item==0 && totTime >= HourGlassThreshold[6] && Options.ChampOptions.UseDH && uW.ksoItems[7].count > 0) { item = 7; }
			if (item==0 && totTime >= HourGlassThreshold[5] && Options.ChampOptions.UseRH && uW.ksoItems[6].count > 0) { item = 6; }
			if (item==0 && totTime >= HourGlassThreshold[4] && Options.ChampOptions.UseAH && uW.ksoItems[5].count > 0) { item = 5; }
			if (item==0 && totTime >= HourGlassThreshold[3] && Options.ChampOptions.UseMH && uW.ksoItems[4].count > 0) { item = 4; }
			if (item==0 && totTime >= HourGlassThreshold[2] && Options.ChampOptions.UseGH && uW.ksoItems[3].count > 0) { item = 3; }
			if (item==0 && totTime >= HourGlassThreshold[1] && Options.ChampOptions.UseKH && uW.ksoItems[2].count > 0) { item = 2; }
			if (item==0 && totTime >= HourGlassThreshold[0] && Options.ChampOptions.UseSH && uW.ksoItems[1].count > 0) { item = 1; }
		}

		if (item != 0) {
			t.SpeedupRepair(item);
		}
	},

}