/* (function(){ var w=window,u='http://www.canazza.co.uk/wittyRPG',l=w.location,d=w.document,s=d.createElement('script'),e=encodeURIComponent,x='undefined'; function g(){if(d.readyState && d.readyState!='complete'){setTimeout(g,200);}else{if(typeof MainApp==x) { s.setAttribute('src',u+'.js'); d.body.appendChild(s);} function f(){ if(typeof MainApp==x){setTimeout(f,200) }else {MainApp.show(); }} f();} } g();}() )*/
var vNum = "0.1b";
if(!extractIFrameBody) { var extractIFrameBody = function(iframe) {	return (iframe.contentWindow.document) }}
function getURLParam(strParamName,strHref){
  var strReturn = "";
  if(!strHref)
  var strHref = window.location.href;
  strHref = strHref.toString();
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
} 
window.size = function()
{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}
var LOCATION = "http://wittyrpg.com?";//window.location;
try {
document.getElementsByTagName("head")[0].parentNode.removeChild(document.getElementsByTagName("head")[0])
for(var i = 0; i < window.document.body.childNodes.length; i++) {
	if(window.document.body.childNodes[i].tagName !="script") {
		window.document.body.removeChild(window.document.body.childNodes[i]);
		i --
	}
}
} catch(e) {
	;	
}
var VersionNumber = document.createElement("span");
VersionNumber.innerText = "Version " + vNum;
var WindowHeight = window.size().height - 25
var WindowWidth = window.size().width - 10
var GAMEWINDOW = document.createElement("iframe");//window.open(LOCATION,"GAMEWINDOW")
GAMEWINDOW.style.width = WindowWidth+"px";
GAMEWINDOW.style.height =  (WindowHeight -25) +"px";
GAMEWINDOW.style.position = "absolute";
GAMEWINDOW.style.left = "0px";
GAMEWINDOW.style.top = "25px";
GAMEWINDOW.src = LOCATION;
GAMEWINDOW.name = "GAMEWINDOW";
window.document.body.appendChild(GAMEWINDOW);

if(GAMEWINDOW.addEventListener) {
	GAMEWINDOW.addEventListener('load',readWindow,false);
} else {
		GAMEWINDOW.attachEvent("onload",readWindow)
	
} 
var PageStatus;
var tmp = document.createElement("div");

tmp.style.position = "absolute";
tmp.style.float = "left";
tmp.style.left = "0px";
tmp.style.top = "0px";
tmp.style.border = "1px solid black";
tmp.style.width = WindowWidth+"px";
tmp.style.height = "25px";
var ActiveLabel = document.createElement("label");


ActiveLabel.innerHTML = "Active:";
var PLAYCHECK = document.createElement("input");
PLAYCHECK.type = "checkbox";
PLAYCHECK.checked = true;

ActiveLabel.appendChild(PLAYCHECK);
tmp.appendChild(ActiveLabel);
document.body.appendChild(tmp);


function toggleConsole() {
	if(CONSOLE.style.display == "none")  {
		CONSOLE.style.display = null	
		GAMEWINDOW.style.top = "150px";
		GAMEWINDOW.style.height = (WindowHeight - 150) + "px";
	} else {
		CONSOLE.style.display = "none";
		GAMEWINDOW.style.top = "25px";
		GAMEWINDOW.style.height = (WindowHeight - 25) + "px";
	}
}
function newButton(name,type,onClick) {
	var BTN = document.createElement("input");
	BTN.type = type?type:'button';
	BTN.value = name;
	BTN.style.border = "1px solid black";
	BTN.style.height = "25px";
	try {
		BTN.addEventListener('click',onClick,false);
	} catch(e) {
		BTN.attachEvent("onclick",onClick)
	}
	return BTN
}

var LOOTLOGBTN = newButton("Show Loot Log","button",outputLootLog);
var TOGGLEBTN = newButton("Toggle Combinable/Cookable","button",toggleMakeable);
var TOGGLECONSOLE = newButton("Toggle Console","button",toggleConsole);
var BANKBTN = newButton("Bank all Money","button",bankMoney);
function outputLootLog(e) {
		CONSOLE.style.display = "none";
		toggleConsole();
	clearconsole() 
	cout("Loot Log") 
	for(var i in LootLog) {
		cout(i + " x" + LootLog[i]);	
	}
}
function alertOut(AlertTxt) {
	
}
function bankMoney() {
	BANK = true;
	GWD.location = "http://wittyrpg.com/index.php?p="+getURLParam('p',GWD.location)+"&z=-31&;t="+getURLParam('t',GWD.location)+"&nnn"+new Date().valueOf();
}
function doBankMoney() {
	
	var bmForm = GWD.getElementById("atmform");
	var deposit = bmForm.getElementsByTagName("input");
	for(var i = 0; i < deposit.length; i++) {
		if(deposit[i].name == "deposit") {
			deposit = deposit[i]
			break;	
		}
	}
	deposit.value = 99999999;
	bmForm.submit();
	
}
tmp.appendChild(LOOTLOGBTN);
tmp.appendChild(TOGGLEBTN);
tmp.appendChild(TOGGLECONSOLE);
tmp.appendChild(BANKBTN);
tmp.appendChild(VersionNumber);
var CONSOLE = document.createElement("div");
CONSOLE.style.position = "absolute";
CONSOLE.style.float = "left";
CONSOLE.style.left = "0px";
CONSOLE.style.top = "25px";
CONSOLE.style.border = "1px solid black";
CONSOLE.style.width = WindowWidth+"px";
CONSOLE.style.height = "125px";
CONSOLE.style.overflow = "auto";
CONSOLE.style.display = "none";
var CastLog = new Array();
function clearconsole() {
	CONSOLE.innerHTML = "";	
}
function cout(str) {
	var ln = document.createElement("div");	
	ln.innerHTML = str;
	CONSOLE.appendChild(ln)
}

document.body.appendChild(CONSOLE)
var Spellcast = false
var COMBAT = 0;
var LOOT = 1;
var FREE = 2;
var BANK = false;
var CharState = -1;
var LootLog = new Object();
var Togg = false;
var cm = new Array();
var st = new Date().valueOf();
var cooklist =null
function toggleMakeable() {
	
	clearconsole();
	cout("Searching for cookable/combinable items")
		var Faders = getElementsByClassName(GWD,"fade");
		var mark = new Date().valueOf();
		for(var i = 0; i < Faders.length; i++) {
			
			if(Faders[i].firstChild.nodeValue == "[ eat ]") {
				if(!cooklist) cooklist = Faders[i].parentNode.parentNode.parentNode
				continue;
			}
			if(Faders[i].firstChild.nodeValue == "[ use ]") {
				if(!cooklist) cooklist = Faders[i].parentNode.parentNode.parentNode
				continue;
			}
			if(Faders[i].parentNode.parentNode.mark == mark) continue;
			
			Faders[i].parentNode.parentNode.mark = mark;
			Faders[i].style.height = Togg?null:"0px";
			Faders[i].parentNode.parentNode.style.visibility = Togg?null:"hidden";
			Faders[i].parentNode.parentNode.style.display = Togg?null:"none";
			
		}
		cooklist = null
		Togg = !Togg;
		
}

function combatCheck() {
	Togg = false;
	try {
	var mLinks = GWD.getElementById("messages").getElementsByTagName("a");
	} catch(e) { 
		return false;
	}
	for(var i = 0; i < mLinks.length; i++) {
		try {
			
			if(mLinks[i].firstChild.nodeValue.indexOf("Adventure again")> -1) {
				cout(mLinks[i].firstChild.nodeValue);
				cout("Out of Combat - Looting")
				return LOOT;	
			}
		} catch(e) { ; }
	}
	var Headers = GWD.getElementsByTagName("h3");	
	for(var i = 0; i < Headers.length; i++ ) {
		try {
			if(Headers[i].firstChild.nodeValue.indexOf("fighting") > -1) {
				cout("In Combat");
				return COMBAT;	
			}
		} catch(e) { ; }
	}
	cout("Out of Combat");
	return FREE;
}
function getElementsByClassName(obj,name) {
	if(obj.getElementsByClassName) {
			return obj.getElementsByClassName(name);
	} else {
		return new Array();	
	}
}
function getStamina() {
	var Rights = GWD.getElementsByTagName("li")
	
	for(var i = 0; i < Rights.length; i ++) {
		try {
			if(Rights[i].childNodes[1].nodeValue	== "Stamina:") {
				return Rights[i].firstChild.firstChild.nodeValue;	
			}
		} catch(e) { 
			;
		}
	}
	return null;
}
function readWindow(E) {
	GWD = extractIFrameBody(GAMEWINDOW);
	if(GWD.getElementById('read')) {
		return;
	}
	var read = GWD.createElement("div");
	read.id = 'read'
	read.innerHTML = "Document Read";
	GWD.body.appendChild(read)
	
	clearconsole();
	cout(GWD.location);
	if(BANK == true) {
		cout("BANKING")
		BANK = false;	
		doBankMoney()
		return;
	}
	
	PageStatus = new Object();
	//Get Last Adventure
	var Paragraphs = GWD.getElementsByTagName("p");
	for(var i in Paragraphs) {
		try { 
			if(Paragraphs[i].firstChild.nodeValue.indexOf("Last adventure") > -1) {
				var Link = Paragraphs[i].getElementsByTagName("a")[0];
				PageStatus.LastAdventure = Link.href
			}
		} catch(e) {
			continue;	
		}
		
	}
	var Links = GWD.getElementsByTagName("a");
	for(var i = 0; i < Links.length; i++) {
		try {
		switch(Links[i].firstChild.nodeValue) {
			case "Heal at the Healer":
				PageStatus.heal = Links[i].href;
			
			break;
			case "Attack":
				PageStatus.Attack = Links[i].href;
			break;
			default:
			
		}
		} catch(e) {
		continue;	
		}
	}
	var Status = getElementsByClassName(GWD,"hasbar");
	for(var i = 0; Status[i]; i++) {
			var ValueType = "Unknown";
			var Value = 0;
		for(var Node = Status[i].firstChild; Node; Node = Node.nextSibling) {
			if(Node.firstChild.nodeValue.length < 3) continue;
			switch(Node.nodeName.toLowerCase()) {
				case "span"	: //Title
					ValueType = Node.firstChild.nodeValue.substr(0,2);
				break;
				case "div": //Value
					Value = Node.firstChild.nodeValue.split("/");
					Value = (parseInt(Value[0])/parseInt(Value[1])) * 100;
				break;
			}
			
		}
			PageStatus[ValueType] = Value >> 0;
	}
	PageStatus.Stamina = parseInt(getStamina());

	cout("Health:"+PageStatus["HP"]+"%")
	cout("Magic:"+PageStatus["MP"]+"%")
	cout("Stamina:" + PageStatus["Stamina"]);

	var _p = getURLParam('p',GWD.location);
	var _t = getURLParam('t',GWD.location);
	var _z = getURLParam('z',GWD.location);
	var SpellDropdown 
	try {
		SpellDropdown = GWD.getElementById("castspell")	;
	} catch(e) { 
		;
	}

	CharState = combatCheck();
	try {
		var Loot = GWD.getElementsByClassName("battle")[0].getElementsByTagName("a")[0].innerHTML
		cout("Looted:" + Loot) //Loot has Dropped
		if(!LootLog[Loot]) LootLog[Loot] = 0; 
		LootLog[Loot] ++
	} catch(ex) { ; }
	if(PLAYCHECK.checked == false){ 
		cout("Unchecked, stopping script. To start again, check the box and perform an action");
		return;
	}
	
	/*
		Main Descision State Machine
	*/
	switch(CharState) {
		case COMBAT:
			try {
			
			cout("Casting Spell " + SpellDropdown.options[SpellDropdown.options.length - 1].text);
			var SpellToCast = -1;
			if((PageStatus["HP"] > 10) && (PageStatus["MP"] > 1)) {
				SpellToCast = SpellDropdown.options.length -1;
				
			} else {
				SpellToCast = 2;
				CharState = -1;
			}
			} catch(e) { 
				cout("IM A WARRIUR! Attack!");
				GWD.location = PageStatus.Attack;
				return;
				;
			}
			if(SpellToCast > 0) {
				Spellcast = true;
				
				var SpellNumber = SpellDropdown.options[SpellToCast].value
			cout("Casting Spell #"+SpellNumber);
			GWD.location = "http://wittyrpg.com/index.php?p="+_p+"&z="+_z+"&a=s"+SpellNumber+"&t="+_t+"&nnn"+new Date().valueOf()
			} 
		
		break;
		case LOOT:
		
		CharState = FREE;
		if((PageStatus["HP"] < 70) || (PageStatus["MP"] < 50)) {
			if(PageStatus.heal) {
				GWD.location = PageStatus.heal
				return;
				break;
			}
		}
		case FREE:
			if(PageStatus.Stamina <= 0) {
				cout("Stamina is "+PageStatus['Stamina']+", eat something to continue");
				PLAYCHECK.checked = false;
				return;
			}
			if(PageStatus.LastAdventure) {
				GWD.location = PageStatus.LastAdventure
			
				CharState = COMBAT;	
			}
		default:
		
		break;
	}
}
