// Tard's KoL Scripts
// Copyright (c) 2006, Byung Kim
// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html
//
// ==UserScript==
// @name           Tard's KoL Scripts - Recipes
// @namespace      http://kol.dashida.com
// @include        *kingdomofloathing.com/main_c.html
// @include        *kingdomofloathing.com/main.html
// @include        *kingdomofloathing.com/starchart.php
// @include        *kingdomofloathing.com/smith.php
// @include        *kingdomofloathing.com/cook.php
// @include        *kingdomofloathing.com/cocktail.php
// @include        *kingdomofloathing.com/jewelry.php
// @include        *kingdomofloathing.com/combine.php
// @include        *kingdomofloathing.com/gnomes.ph*
// @include        *kingdomofloathing.com/knoll.ph*
// @include        *127.0.0.1:*/main_c.html
// @include        *127.0.0.1:*/main.html
// @include        *127.0.0.1:*/starchart.php
// @include        *127.0.0.1:*/smith.php
// @include        *127.0.0.1:*/cook.php
// @include        *127.0.0.1:*/cocktail.php
// @include        *127.0.0.1:*/jewelry.php
// @include        *127.0.0.1:*/combine.php
// @include        *127.0.0.1:*/gnomes.ph*
// @include        *127.0.0.1:*/knoll.ph*
// @description    Version 1.8
// ==/UserScript==


/********************************** Change Log **********************************************
Refer to the following for past updates:
http://kol.dashida.com/

Refer to the following for current updates:
http://somestranger.kol.googlepages.com/

Latest Update:
1.8
- Changed data parsing to point to CMeister2's pages. (More up-to-date)
1.7
- Added "(3)" adventure use indication to the jewelry page (thanks Fryguy!)
********************************************************************************************/

recurl = 'http://kol.cmeister2.co.uk/recipes/';
//recurl = 'http://cmeister2.uwcs.co.uk/kol/recipes/';

if (window.location.pathname == "/main_c.html" || window.location.pathname == "/main.html") {

	setTimeout('if (window["checkForUpdate"]) checkForUpdate("recipes","1.8","Recipes","http://somestranger.kol.googlepages.com/tardskolscripts_recipes.user.js");',1000);

} else {
	var isRecipePage = true;
	var specialLocation = 'none';
	if (window.location.pathname.indexOf("gnomes.php") != -1 && document.getElementsByTagName("body")[0].innerHTML.indexOf("Gnorman") == -1) isRecipePage = false;
	if (window.location.pathname.indexOf("knoll.php") != -1 && document.getElementsByTagName("body")[0].innerHTML.indexOf("I'm Innabox the Smith") == -1 && document.getElementsByTagName("body")[0].innerHTML.indexOf("I am known as The Plunger") == -1) isRecipePage = false;
	
	if (window.location.pathname.indexOf("knoll.php") != -1) {
		if(document.getElementsByTagName("body")[0].innerHTML.indexOf("The Plunger") != -1) {
			specialLocation = 'plunger';
		}
		else if(document.getElementsByTagName("body")[0].innerHTML.indexOf("I'm Innabox the Smith") != -1) {
			specialLocation = 'innabox';
		}
	}
		
	function addGlobalStyle(css) {
	    var head, style;
	    head = document.getElementsByTagName('head')[0];
	    if (!head) { return; }
	    style = document.createElement('style');
	    style.type = 'text/css';
	    style.innerHTML = css;
	    head.appendChild(style);
	}
	addGlobalStyle(<r><![CDATA[
		.organizedSelect optgroup + optgroup {
			margin-top:.5em;
		}
		.organizedSelect:hover {
			padding:1px;
			border:1px blue solid;
		}
		.organizedSelect {
			margin-right:10em;
		}
		label {
			margin-bottom: .5em;
			float:left;
			text-align: right;
			padding-right: 20px;
			width: 7em;
		}
		label.disabled {
			color:gray;
		}
		.toggler {
			font-size:.5em;
			cursor:pointer;
			margin-right:10px;
		}
		span.toggler:hover {
			color: dimgray;
		}
		#submitButton {
		  float:left;
		}
		#skillTimesDiv {
		  float:left;
		  margin-left:10px;
		  margin-right:5px;
		  height:1.2em;
		  min-width:50px;
			width: 4.1em;
			border:1px solid black;
			min-height:18px;
		}
		#secondLineWrapper {
		  margin-left:7em;
		  padding-left:20px;
			margin-top:.4em;
			text-align:left;
		}
		#skilltimes {
		  min-height:inherit;
			border:none;
		}
			 	
			 	
		#selectForm {
			min-width:20em;
			text-align:left;
			white-space:nowrap;
		}

		#queueHolder {
			text-align:left;
			height:100%;
			float:left;
			clear:left;
			width:60%;
		}
		#queueStatusDiv {
			padding:2px;
			margin-bottom:3px;
			font-size:8pt;
			border: 1px solid gray;
		}
		#queue {
			border: 1px solid gray;
			position:relative;
			list-style-position:inside;
			padding:1px;
			text-align:left;
			font-size:8pt;
			height:15em;
			overflow-y:scroll;
			overflow-x:hidden;
		}
		#groupInterface {
			white-space:nowrap;
			float:right;
			width:38%;
		}
		#groupInterface select {
			border:1px solid gray;
			margin-top:10px;
			margin-bottom:10px;
			height:14em;
			width:80%;
		}
		#queue span.removeElement {
			position:absolute;
			right:0;
			font-size:10pt;
			font-weight: bold;
			cursor:pointer;
		}
		#clearQueue {
			margin-left:3em;
			font-size:9pt;
			text-decoration:underline;
			cursor:pointer;
		}
		#clearQueue:hover {

			color:gray;
		}
		#queue span.removeElement:hover {
			color:gray;
		}
		#queue li {
			padding-right:1em;
			border-bottom:1px solid lightgray;
		}
		input.groupFloat {
			margin-top:10px;
			cursor:pointer;
			width:2em;
			height:2em;
			padding:0;
			float:left;
			clear:left;
			margin-right:4px;
		}
		div.queueLabel {
			position:relative;
			font-weight:bold;
			text-align:center;
			border-bottom: 1px solid blue;
		}
		input.button {
			cursor:pointer;
		}
		div.queueAreaCost {
				position: absolute;
				right:0;
				top:4px;
				font-weight:normal;
				text-align:right;
				font-size:9pt;
		}
			
		]]></r>.toString());
		
	if (isRecipePage) {
		var sType = window.location.pathname.substring(1,window.location.pathname.indexOf("."));
		if (document.getElementsByTagName("body")[0].innerHTML.indexOf("Plunger") != -1) sType = "combine";
		else if (document.getElementsByTagName("body")[0].innerHTML.indexOf("Innabox") != -1) sType = "smith";
	
		var newDiv = document.createElement("div");
		newDiv.id = "recipes";
		document.getElementsByTagName("center")[0].insertBefore(newDiv,document.getElementsByTagName("table")[0]);
		var oDiv = document.getElementById("recipes");
		with(oDiv.style) {width = "95%";marginBottom="5px"}
	
		newDiv = document.createElement("div");
		with(newDiv) {id = "recipeHeader";innerHTML = "Recipes:";}
		with(newDiv.style) {background = "blue";textAlign = "center";fontSize = "16px";color="white";fontWeight="bold";}
		oDiv.appendChild(newDiv);
	
		newDiv = document.createElement("div");
		with(newDiv) {id = "recipeContent";}
		with(newDiv.style) {textAlign = "center";fontSize = "11px";border="1px solid blue";borderTop="0px";padding="5px";}
		oDiv.appendChild(newDiv);
		
	
		var aSelects = document.getElementsByTagName("select");
		var invList = ") ";
		if (aSelects && aSelects.length > 1) {
			for (var i=1;i<aSelects[1].options.length;i++) {
				if (aSelects[1].options[i] && aSelects[1].options[i].text) {
					var str = aSelects[1].options[i].text;
					if (str.indexOf("E-Z Cook Oven") == 0) {
						str = str.substring(0,13) + str.substring(14,str.length);
						aSelects[0].options[i].text = str;
						aSelects[1].options[i].text = str;
					} else if (str.match(/jaba.ero\spepper/)) {
						str = "jabanero pepper" + str.substr(str.indexOf("pepper")+6);
						aSelects[0].options[i].text = str;
						aSelects[1].options[i].text = str;
					}
					invList += str.toLowerCase() + " ";
				}
			}
		}
		
		function insertOptions(str) {
			function checkItemQty(item,q) {
				var b = true;
				var s = ") " + item + " (";
				var i0 = invList.indexOf(s);
				var i1 = invList.indexOf(") ",i0+s.length);
				var itemQty = invList.substring(i0+s.length,i1);
				if (itemQty < q) b = false;
				return b
			}
			if (sType == "starchart" || aSelects.length > 1) {
				var tmp = [];
				var aLines = str.match(/.+/g);
				tmp.push('<select id="recipeSelect" onChange="setCombine(this.options[this.selectedIndex])"><option value="">- select a recipe-</option>');
				for (var i in aLines) {
					var addOption = true;
					var aL = aLines[i].split("|");
					var aD = (aL[2] ? aL[2] : "");
					if (sType != "starchart") {
						var aC = aL[1].split(",");
						hasItems = true;
						for (var c in aC) {
							if (invList.indexOf(") " + aC[c] + " (") == -1) hasItems = false;
						}
						if (hasItems) {
							if (aC[0] == aC[1]) {
								addOption = checkItemQty(aC[0],2);
							}
							if (aC[0] == aC[2]) {
								addOption = checkItemQty(aC[0],2);
							}
							if (aC[1] == aC[2]) {
								addOption = checkItemQty(aC[1],2);
							}
							if (aC[0] == aC[1] && aC[1] == aC[2]) {
								addOption = checkItemQty(aC[0],3);
							}
						} else {
							addOption = false;
						}
					}
					if (addOption) tmp.push('<option value="' + aL[1] + '" title="' + aD + '">' + aL[0] + '</option>');
				}
				tmp.push('</select><div id="recipeDesc" style="font-size:12px;"></div>');
				if(tmp.length > 0) str = tmp.join('');
				document.getElementById("recipeContent").innerHTML = str;
			}
		}
		
		if (GM_getValue("recipe_"+sType,"") != "") {
			insertOptions(GM_getValue("recipe_"+sType,""));
		} else {
			GM_xmlhttpRequest({
		    method: 'GET',
		    url: recurl+sType+'.txt',
		    headers: {'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey','Accept': 'text/html',},
		    onload: function(responseDetails) {
					if (responseDetails.status == "200") {
						var strR = responseDetails.responseText;
						insertOptions(strR);
						GM_setValue("recipe_"+sType,strR);
					}
		    }
			});
		}
		
		setTimeout('setCombine = function(op) {' +
			'var val = op.value;' +
			'if (val != "") {' +
				'var type = "' + sType + '";' +
				'var a = val.split(",");' +
				'if (type == "starchart") {' +
					'ops = document.getElementsByTagName("input");' +
					'ops[2].value = a[0];' +
					'ops[3].value = a[1];' +
				'} else {' +
					'selects = document.getElementsByTagName("select");' +
					'for (var i=0;i<=2;i++) {' +
						'if (selects[i+1]) {' +
							'for (var j=0;j<selects[i+1].options.length;j++) {' +
								'str = selects[i+1].options[j].text;' +
								'str = str.toLowerCase();' +
								'if (str.indexOf(a[i]+ " (") == 0) {' + 
									'selects[i+1].selectedIndex = j;' +
									'break;' +
								'}' +
							'}' +
						'}' +
					'}' +
				'}' +
				'document.getElementById("recipeDesc").innerHTML = (op.title != "" ? op.title : "");' +
			'}' +
		'}',10);
		
		function GM_post( dest, vars, callback ) {
			 GM_xmlhttpRequest({
			    method: 'POST',
			    url: 'http://'+document.location.host + dest,
			    headers: {'Content-type': 'application/x-www-form-urlencoded'},
					data: vars,
					onload:function(details) {
						if( typeof callback=='function' ){
							callback( details.responseText);
						}
					}
			});
		}
		oldforms = document.getElementsByTagName('form');
		var useAdventures = "";
		var firstchar = sType.substring(0,1);
		firstchar = firstchar.toUpperCase();
		var restofchars = sType.substring(1);
		var newSType = firstchar + restofchars;
		switch (newSType)
		{
			case "Gnomes":
				newSType = "Tinker";
			break;
			case "Jewelry":
				newSType = "Ply";
			break;
		}
		
		function sortByGroupName(a,b) {
			var c=a[1].toLowerCase();
			var	d=b[1].toLowerCase();
			if (c<d) return -1;
			if (c>d) return 1;
			return 0;
		}
		function addLiToQueue(queueItem,first) {
			var li = document.createElement('li');
			li.style.color = 'red';
			var aLines = GM_getValue("recipe_"+sType,"").match(/.+/g);
			var queueText = sType != 'gnomes' ? queueItem.item1name + " , " + queueItem.item2name + " ("+queueItem.q+"x)" : queueItem.item1name + " , " + queueItem.item2name + " , " + queueItem.item3name + " ("+queueItem.q+"x)";
			for (var i in aLines) {
				var list = aLines[i].split("|");
				var realList = list[1].split(",");
				if (sType == 'gnomes') {
					if (realList[0] == queueItem.item1name.toLowerCase() && realList[1] == queueItem.item2name.toLowerCase() && realList[2] == queueItem.item3name.toLowerCase())  {
						queueText = list[0] + " ("+queueItem.q+"x)";
						li.style.color = 'black';
						break;
					}
				}
				else {
					if (realList[0] == queueItem.item1name.toLowerCase() && realList[1] == queueItem.item2name.toLowerCase())  {
						queueText = list[0] + " ("+queueItem.q+"x)";
						li.style.color = 'black';
						break;
					}
				}
			}
			var removeElement=document.createElement('span');
			with(removeElement) {
				appendChild(document.createTextNode('X'));
				removeElement.className = "removeElement";
				addEventListener('click',removeCurrentItem,true);
			}
			li.appendChild(removeElement);
			li.appendChild(document.createTextNode(queueText));
			//add li item to list
			if(first) {
				queue.insertBefore(li,queue.firstChild);
			} else {
				queue.appendChild(li);
			}
		}
		function submitSkill(evt) {
			evt.preventDefault(); 
			var opt = document.getElementsByTagName('select');
			if (opt.length>2) {
				var item1name = opt[1].options[opt[1].selectedIndex].firstChild.nodeValue.replace(/ \(\d+\)/,'');
				var item2name = opt[2].options[opt[2].selectedIndex].firstChild.nodeValue.replace(/ \(\d+\)/,'');
				var item3name = sType == 'gnomes' ? opt[3].options[opt[3].selectedIndex].firstChild.nodeValue.replace(/ \(\d+\)/,'') : '';
				var item1 = opt[1].options[opt[1].selectedIndex].value;
				var item2 = opt[2].options[opt[2].selectedIndex].value;
				var item3 = sType == 'gnomes' ? opt[3].options[opt[3].selectedIndex].value : '';
			}
			else {
				opt = document.getElementsByTagName('input');
				var item1name = opt[2].value;
				var item2name = opt[3].value;
				var item3name = '';
				var item1 = opt[2].value;
				var item2 = opt[3].value;
				var item3 = '';
			}
			var inputOffset1 = specialLocation == 'plunger' || sType == 'gnomes'? 1 : 0;
			var inputOffset2 = specialLocation == 'plunger'? 1 : (sType == 'gnomes' ? -1 : 0);
			if (sType != ('jewelry' && 'starchart')) {
				var quantity = document.getElementsByTagName('input')[3-inputOffset1].checked ?'ma':document.getElementsByTagName('input')[2+inputOffset2].value;
			}
			else {
				var quantity = 1;
			}
			var maxverb = sType == 'cook' || sType == 'combine' || sType == 'cocktail' || sType == 'gnomes' ? 'max' :'all';
			var makemax = document.getElementsByTagName('input')[3-inputOffset1].checked ?'&make'+maxverb+'=on':'';
			if(queueCheckbox.checked) {
				//add item to queue
				updateQueue("add",({item1name:item1name,item2name:item2name,item3name:item3name,item1:item1,item2:item2,item3:item3,q:quantity,max:makemax}));
			} else {
				oldforms[0].submit();
			}
		}
		selectForm = document.createElement('form');
		selectForm.addEventListener("submit",submitSkill,true);
		selectForm.id = "selectForm";
		//create a div to hold a few form elements
		var submitDiv = document.createElement('div');
		submitDiv.setAttribute('style','padding:5px 0 10px 0;clear:left;text-align:left;');
		
		var submitButton = document.createElement('input');
		//create submit button for skills. Same button used for buffs and skills
		with (submitButton) {
			type = "submit";
			id = "submitButton";
			className= "button";
			value = "Just " + newSType + "!";
		}
		var secondlineWrapper = document.createElement('div');
		with (secondlineWrapper) {
			id = "secondlineWrapper";
			appendChild(submitButton);
		}
		
		//append everything together and insert before original forms.
		submitDiv.appendChild(secondlineWrapper);
		selectForm.appendChild(submitDiv);
		
		function deleteGroup() {
			updateGroups('removeSelected');
		}
		function addNewGroupOption(tempGroupName) {
			//new Option results in "out of memory" error for some reason
			//groupSelect[groupSelect.length] = new Option("name","text");
			var newOption = document.createElement('option');
			newOption.text = tempGroupName;
			newOption.value = tempGroupName;
			groupSelect.appendChild(newOption);
		}
		//button functions
		function removeCurrentItem(e){
			var listItem = e.target.parentNode;
			updateQueue("remove",listItem);
		}
		function clearCurrentQueue() {
			updateQueue('clear');
		}
		function saveCurrentQueue(e) {
			if(currentQueue.length>0) {
				var newGroupName = prompt("Enter a name for new group");
				if(newGroupName!=null&&newGroupName!="") {
					var nameInUse=false;
					for(var i=0;i<storedGroups.length;i++) {
						if(storedGroups[i][1].toLowerCase() == newGroupName) {
							nameInUse=true;
							status("That group name is in use already");
							break;
						}
					}
					if(!nameInUse)updateGroups("add",[currentQueue.toSource(),newGroupName]);
				}
			} else {
				status("Can't save an empty queue");
			}
		}
		function updateGroups(action,info) {
			switch(action) {
				case "add":
					var newGroup = eval(info[0]);
					storedGroups.push([newGroup, info[1]]);
					addNewGroupOption(info[1]);
					status(" ");
				break;
				case "removeSelected":
					var numSelected=0;
					for(var i=groupSelect.options.length-1;i>=0;i--) {
						if(groupSelect.options[i].selected) {
							numSelected++;
							groupSelect.removeChild(groupSelect.options[i]);
							storedGroups.splice(i,1);
						}
					}
					status("Removed "+numSelected+" groups");
				break;
			}
			storeGroups();
		}
		function queueGroup() {
			updateQueue("addGroups");
		}
		function toggleQueue(e) {
			newState =(e.target.checked)?true:false;
			GM_setValue("queueState_"+sType+playerId,newState);
			//toggle queueSection
			//change submit button
			var verb = (newState)?"Queue Item to " + newSType:"Just " + newSType + "!";
			verb += useAdventures;
			submitButton.value = verb;
			queueSection.style.display=(newState)?"block":"none";
		}
		function updateFormElements(){
			if(typeof playerId!="undefined") {
				submitButton.value = (GM_getValue("queueState_"+sType+playerId,false))?"Queue an item to " + newSType:"Just " + newSType + "!";
				submitButton.value += useAdventures;
			} else {
				submitButton.value = "Just " + newSType + "!";
				submitButton.value += useAdventures;
			}
		}
		function runQueueFunction() {
			//need status indicators desperately
			//set password
			quickskillsResults.innerHTML = "";
			var numberRun = 1;
			var pwd = document.getElementsByName('pwd').length > 0 ? document.getElementsByName('pwd')[0].value : '';
			//fail on no pwd!
			failedQueue = new Array();
			//begin queue somehow.
			if(currentQueue.length>0) {
				parseFirstQueueItem()
			} else {
				status("Run an empty queue?");
			}
			
			function parseFirstQueueItem() {
				//parse currentQueue[0] and send to GM_post
				var variables;
				var c=currentQueue[0];
				c.q = c.q == 'ma' ? '1' : c.q;
				if (sType != 'gnomes' && sType != 'starchart') {
					variables = "action=combine&pwd="+pwd+"&item1="+c.item1+"&item2="+c.item2+c.max+"&quantity="+c.q;
				}
				else if (sType == 'gnomes') {
					variables = "action=tinksomething&item1="+c.item1+"&item2="+c.item2+"&item3="+c.item3+c.max+"&qty="+c.q;
				}
				else {
					variables = "action=makesomething&pwd="+pwd+"&numstars="+c.item1+"&numlines="+c.item2;
				}
				status("Creating Item #"+numberRun);
				numberRun++;
				GM_post(window.location.pathname,variables,queueAgain);
					
			}
					
			function queueAgain(details) {
				//check details for success
				//line below needs an apostrophe on dont but it mucks up my syntax highlighter
				var startText = '<table width=95%  cellspacing=0 cellpadding=0><tr><td style="color: white;" align=center bgcolor=blue><b>Results:</b></td></tr>';
			    var endText = '<td height=4></td></tr></table>';
				var startLoc = details.indexOf(startText);
			    var endLoc = details.indexOf(endText) +
			            endText.length;
			    var resultText = details.substring(
			            startLoc, endLoc);
				if (quickskillsResults.innerHTML == "") {
						quickskillText = resultText.replace(endText,"");
						quickskillsResults.innerHTML = quickskillText + endText;
				}
				else {
						quickskillText += resultText.replace(endText,"").replace(startText,"");
						quickskillsResults.innerHTML = quickskillText + endText;
				}
				if(/don.t/.test(details.toLowerCase()) || /doesn.t make any sense/.test(details.toLowerCase()) || /turn those particular items/.test(details.toLowerCase())) {
					updateQueue("fail");
				}
				else {
					//check for success
					if(/(new item|fuse)/.test(details.toLowerCase())) {
						updateQueue("success");
					} else {
						updateQueue("fail");
					}
				}
				if(currentQueue.length>0) {
					parseFirstQueueItem();
				} else {
					GM_setValue("delayedresults",quickskillText + endText);
					finished();
					//done!
				}

			}
			
		}
		function noQueue() {
				//because this script works on so many different pages, there are tons of exception-like things that need to be done
				if (specialLocation == 'innabox' || sType == 'gnomes') {
					document.getElementsByTagName('input')[3].parentNode.insertBefore(selectForm,document.getElementsByTagName('input')[3]);
					document.getElementsByTagName('input')[5].parentNode.removeChild(document.getElementsByTagName('input')[5]);
				}
				else if (sType == 'jewelry') {
					document.getElementsByTagName('input')[2].parentNode.insertBefore(selectForm,document.getElementsByTagName('input')[2]);
					document.getElementsByTagName('input')[4].parentNode.removeChild(document.getElementsByTagName('input')[4]);
					useAdventures = " (3)";
				}
				else {
					document.getElementsByTagName('input')[4].parentNode.insertBefore(selectForm,document.getElementsByTagName('input')[4]);
					if(document.getElementsByTagName('input')[6].value.indexOf("(1") != -1) { useAdventures = " (1)";}
					document.getElementsByTagName('input')[6].parentNode.removeChild(document.getElementsByTagName('input')[6]);
				}
				updateFormElements();
		}
		function createQueue() {
			currentQueue = eval(GM_getValue('currentQueue_'+sType+playerId,'[]'));
			storedGroups = eval(GM_getValue('storedGroups_'+sType+playerId,'[]'));
				
			//sort storedGroups
			storedGroups.sort(sortByGroupName);
			
			queueCheckbox = document.createElement('input');
			with(queueCheckbox) {
				type="checkbox";
				style.cursor = "pointer";
				checked=GM_getValue("queueState_"+sType+playerId,false);
				addEventListener('change',toggleQueue,true);
			}
			queueCheckboxLabel = document.createElement('span');
			with(queueCheckboxLabel) {
				appendChild(document.createTextNode('enable queue:'));
				style.fontSize = "9pt";
			}
			queueSpace = document.createElement('br');
			selectForm.appendChild(queueSpace);
			selectForm.appendChild(queueCheckboxLabel);
			selectForm.appendChild(queueCheckbox);
			
			//create queue section
			
		
			queueSection = document.createElement('div');
			queueSection.id = "queueSection";
			
			var queueHolder = document.createElement('div');
			queueHolder.id = "queueHolder";
			
			queue = document.createElement('ol');
			queue.id = "queue";
			
			var queueAreaLabel = document.createElement('div');
			
			queueAreaLabel.appendChild(document.createTextNode(newSType+' Queue:'));
			queueAreaLabel.className = "queueLabel";
			
			var queueAreaCost = document.createElement('div');
			queueAreaCost.className = "queueAreaCost";
			
			queueAreaCostVal = queueAreaCost.appendChild(document.createTextNode(''));
			
			queueAreaLabel.appendChild(queueAreaCost);
			
			queueStatusDiv = document.createElement('div');
		
			var queueStatusLabel=document.createElement('span');
			queueStatusLabel.style.fontWeight = "bold";
			queueStatusLabel.style.marginRight = "1em";
			queueStatusLabel.appendChild(document.createTextNode("Queue Status:"));
			queueStatusInfo = document.createElement('span');			
			
			with(queueStatusDiv) {
				title="Skill queue status area";
				id="queueStatusDiv";
				appendChild(queueStatusLabel);
				appendChild(queueStatusInfo);
			}
			updateQueue('populate');
					
			//queue interface
			var groupInterface = document.createElement('div');
			groupInterface.id = "groupInterface";
			
			var clearQueue = document.createElement('span');
			with (clearQueue) {
				title="Remove all items from the queue";
				appendChild(document.createTextNode("[ Clear queue ]"));
				clearQueue.id="clearQueue";
				addEventListener('click',clearCurrentQueue,true);
			}
			var saveQueue = document.createElement('input');
			with (saveQueue) {
				value=">>";
				type="button";
				className="button groupFloat";
				title="Save queue as buff group";
				addEventListener('click',saveCurrentQueue,true);
			}
			
			groupSelect = document.createElement('select');
			
			with(groupSelect) {
				multiple=true;
				size=9;
				for(var i=0;i<storedGroups.length;i++) {
					if(storedGroups[i][1]!=undefined) {
						addNewGroupOption(storedGroups[i][1]);
					}	else {
						storedGroups.splice(i,1);
					}
					storeGroups();
				}
			}	
			var groupAreaLabel = document.createElement('div');
			groupAreaLabel.appendChild(document.createTextNode('Group:'));
			groupAreaLabel.className = "queueLabel";
			
			var appendGroup = document.createElement('input');
			with(appendGroup) {
				title="Add all items from this buff group to the queue";
				type="button";
				className="button groupFloat";
				value="<<";
				addEventListener('click',queueGroup,true);
			}
			var groupDelete = document.createElement('input');
			with(groupDelete) {
				title="Delete this buff group";
				type="button";
				className="button groupFloat";
				value="X";
				addEventListener('click',deleteGroup,true);
			}
			
			
			var runQueue = document.createElement('input');
			with (runQueue) {
				title="Run the current queue";
				value="Run";
				type="button";
				style.cursor = "pointer";
				className="button";
				addEventListener('click',runQueueFunction,true);
			}
			
			queueHolder.appendChild(queueAreaLabel);
			queueHolder.appendChild(queue);
			queueHolder.appendChild(queueStatusDiv);
			queueHolder.appendChild(runQueue);
			queueHolder.appendChild(clearQueue);
			
			groupInterface.appendChild(groupAreaLabel);
			groupInterface.appendChild(saveQueue);
			groupInterface.appendChild(groupDelete);
			groupInterface.appendChild(appendGroup);
			groupInterface.appendChild(groupSelect);
		
			queueSection.appendChild(queueHolder);
			queueSection.appendChild(groupInterface);
			
			queueSection.style.display=(/you don.t have any meat paste/.test(document.getElementsByTagName('body')[0].innerHTML.toLowerCase()) ? "none" :((GM_getValue("queueState_"+sType+playerId,false))?"block":"none"));
			
			if(sType == 'gnomes') {
				document.forms[document.forms.length-2].parentNode.appendChild(queueSection);
			}
			else {
				document.forms[document.forms.length-1].parentNode.appendChild(queueSection);
			}
			
			quickskillsResults = document.createElement('div');
			quickskillsResults.id = "effdiv";
			var quickskillText = "";
			oDiv.parentNode.insertBefore(quickskillsResults,oDiv.nextSibling);
			
			var delayedresults = GM_getValue("delayedresults", "");
		    if (delayedresults != "")
		    {
		        quickskillsResults.innerHTML = delayedresults;
				GM_setValue("delayedresults", "");
		    }
			noQueue();
		}
		function getPID(callback,failedCallback) {
			if(unsafeWindow.top.playerId == undefined) {
				GM_xmlhttpRequest({
			    method: 'GET',
			    url: 'http://' + document.location.host + '/charsheet.php',
			    onload: function(details) {	
				  	playerId = /href="showplayer.php\?who=(\d+)"/.exec(details.responseText);
				  	if(playerId)
				  	{ 
				  		playerId=playerId[1]; 
				  		unsafeWindow.top.playerId = playerId;
						  if(typeof callback == "function") {
								callback();
							}
				  	}	else {	  	
						  if(typeof failedCallback == "function") {
								failedCallback();
							}
				  	}

					}
				});
			} else {
				playerId = unsafeWindow.top.playerId;
			  if(typeof callback == "function") {
					callback();
				}
			}
		}
		function status(note) {
			if(queueStatusInfo.childNodes.length>0) {
				queueStatusInfo.firstChild.nodeValue = note;
			} else {
				queueStatusInfo.appendChild(document.createTextNode(note));
			}
		}
		function getItemIndex(item,object) {
			for (var i=0;i<object.length;i++) {
				if(item==object[i])return i;
			}
			return -1;
		}
		function removeChildNodes(parent){
			while(parent.hasChildNodes()){
				parent.removeChild(parent.lastChild)
			}
		}
		function storeQueue() {
			GM_setValue("currentQueue_"+sType+playerId,currentQueue.toSource());
		}
		function storeGroups() {
			GM_setValue("storedGroups_"+sType+playerId,storedGroups.toSource());
		}
		function finished() {
			updateQueue('done');
		}
		function updateQueue(action,info) {
			switch(action) {				
				case "add":
					addLiToQueue(info);
					//push info to queue array
					currentQueue.push(info);
				break;
				case "clear":
					currentQueue.length=0;
					removeChildNodes(queue);
				break;
				case "populate":
					if(typeof currentQueue != "undefined") {
						for(var i=0;i<currentQueue.length;i++) {
							var queueItem = currentQueue[i];
							addLiToQueue(queueItem);
						}
					}
				break;
				case "remove":
					var arrayIndex = getItemIndex(info,info.parentNode.getElementsByTagName('li'));
					if(arrayIndex==-1)GM_log('Oh bugger.');
					info.parentNode.removeChild(info);
					currentQueue.splice(arrayIndex,1);
				break;
				case "fail":
					status("Item failed: removing from list");
					currentQueue.splice(0,1);
					queue.removeChild(queue.firstChild);
				break;
				case "success":
					status("Item creation successful");
					//remove top item from queuearray and list.
					currentQueue.splice(0,1);
					queue.removeChild(queue.firstChild);
				break;
				case "addGroups":
					for(var i=0;i<groupSelect.options.length;i++) {
						if(groupSelect.options[i].selected) {
							for(var x=0;x<storedGroups[i][0].length;x++) {
								var tempGroup = storedGroups[i][0][x];
								//try to update skill cost
								addLiToQueue(tempGroup);
							}
							currentQueue=currentQueue.concat(storedGroups[i][0]);
						}
					}
				break;
				case "done":
					status("Adding failed items back in");
					var failedCount=0;
					for(var i=0;i<failedQueue.length;i++) {
						failedCount++
						currentQueue.unshift(failedQueue[i]);
						addLiToQueue(failedQueue[i],true);
					}
					status("Done! ("+failedCount+" failed items(s))");
					window.document.location = window.document.location;
				break;
		}
		storeQueue();
		}
		//get player id 
		pidFail=false;
		//check for player id in mainpage.
			
		options=document.getElementsByTagName('option');
		var foundId=false;
		for(var i=0;i<options.length;i++) {
			if(options[i].firstChild.nodeValue == "(yourself)") {
				playerId = options[i].value;
				foundId=true;
				break;
			}
		}
		if(!foundId) {
			var y;
			menuSrc = top.frames[0].document.body.innerHTML.toSource();
			if(y=/donatepopup.php\?pid=(\d*)\\/.exec(menuSrc))	{
				playerId=y[1];
				createQueue();
			}	else	{
				getPID(createQueue,noQueue);
			}
		} else {
			createQueue();
		}
	}

	// Meat Maker
	if (sType == "combine" || sType == "smith") {
		var pwd = document.getElementsByName('pwd').length > 0 ? document.getElementsByName('pwd')[0].value : '';
		if (pwd.length > 1) {
			var newDiv = document.createElement("div");
			newDiv.id = "meat";
			document.getElementsByTagName("center")[0].appendChild(newDiv);
			var oDiv = document.getElementById("meat");
			with(oDiv.style) {width = "95%";marginTop="10px"}
		
			newDiv = document.createElement("div");
			with(newDiv) {id = "meatHeader";innerHTML = "Meat Maker:";}
			with(newDiv.style) {background = "blue";textAlign = "center";fontSize = "16px";color="white";fontWeight="bold";}
			oDiv.appendChild(newDiv);
		
			newDiv = document.createElement("div");
			with(newDiv) {id = "meatContent";}
			with(newDiv.style) {textAlign = "center";fontSize = "11px";border="1px solid blue";borderTop="0px";padding="5px";}
			oDiv.appendChild(newDiv);
			
			oDiv = document.getElementById("meatContent");
			strTarget = (top.document.getElementsByTagName("body").length > 0 ? "dataFrame" : "mainpane"); 
			strOnSubmit = (strTarget == "dataFrame" ? 'onSubmit="setTimeout(\'window.location.href = window.location.href;\',100)"' : "");
			oDiv.innerHTML = '<form action="inventory.php" target="'+strTarget+'" method="post" ' + strOnSubmit + '>Make: ' +
				'<input size="5" class="text" name="quantity" value="1" type="text"> ' +
				'<input name="action" value="makestuff" type="hidden">' +
				'<input name="pwd" value="' + pwd + '" type="hidden">' +
				'<select name="whichitem">' +
					'<option value="25">meat paste (10 Meat)</option>' +
					'<option value="88">meat stack (100 Meat)</option>' +
					'<option value="258" ' + (sType == "smith" ? "selected" : "") + '>dense meat stack (1000 Meat)</option>' +
				'</select> ' +
				'<input class="button" value="Make" type="submit"></form>';
		}
	}
}

