// ==UserScript==
// @name           Item Quantity CM2
// @namespace      http://kol.cmeister2.co.uk
// @description    Counts how many of an item you have from the fight/choice page
// @include        http://*.kingdomofloathing.com/fight.php*
// @include        http://*.kingdomofloathing.com/choice.php*
// @include        http://*.kingdomofloathing.com/main.php*
// @description    Version 1.0
// ==/UserScript==

//Some code used with permission from lukifer

function GM_get(dest, callback){
//Wrapper
	GM_xmlhttpRequest({
		method: 'GET',
		url: 'http://' + dest,
		onload:function(details) {
			if(details.status==200){	//Custom - fails if 304
				if( typeof(callback)=='function' ){
					callback(details.responseText);
				}
			}
		}
	});
}

function jNum(x){
	//returns only numerics in x
	tmp = x.replace(/[^0-9]/g,'');
	return (tmp)?tmp:0;
}
function elem(name, attrs, style, text) {
	//generates html element
    var e = document.createElement(name);
    if(attrs){
        for(key in attrs){
			switch(key){
				case 'class': e.className = attrs[key]; break;
				case 'id': e.id = attrs[key]; break;
				default: e.setAttribute(key, attrs[key]);
			}
        }
    }
    if(style) {
        for(key in style)e.style[key]=style[key];
    }
    if(text)e.appendChild(document.createTextNode(text));
    return e;
}

function hasItem(descid, text){
	// I tried regular expressions, honest!

	fs = text.indexOf(descid);

	if(fs+1){
		
		total=0;

		//Yes, whilst hackish, it works.
		while(fs+1){
		
			var ff = text.indexOf('<font',fs)+1;
			tmp = text.substring(fs,ff);

			tmp2 = tmp.split('</b>')[1];
			tmp3 = tmp2.substring(0,tmp2.indexOf('<'));
			tmp4 = jNum(tmp3)*1;

			total+=(tmp4)?tmp4:1;

			fs=text.indexOf(descid,ff);
		}	
		
		return total;
	}else{
		return 0;
	}
}

function GetDomain(){ return window.location.host; }

function addquantities(){

	var zimg = document.getElementsByTagName('img');
	for (var i=0, len=zimg.length; i<len; i++){							//step through images
		img = zimg[i];
		if(!img)continue;

		if( match=(/([0-9]{9})/).exec( img.getAttribute('onclick') ) ){ //do we match a descid
			img.setAttribute('descid',match[1]);						//allows us to retrieve descid inside listener

			img.addEventListener('contextmenu',function(event){
				var itemdb = getdb();									//get itemdb
				var descid = this.getAttribute('descid');				//get image descid
		
				var td = elem('td');
				var span = elem('span',{'class':'tiny','id':'span'+descid},null, '(loading total)');
				td.appendChild(span);
				this.parentNode.parentNode.appendChild(td);				//add span to end of row

				if( itemdb && (item = itemdb['items'][descid]) ){		//find item from db
					GM_xmlhttpRequest({
						method: 'GET',
						url: 'http://' + GetDomain() + '/inventory.php?which='+item['invpage'],
						descid: descid,									//Custom request allows us to pass descid
						onload:function(details) {
							tmp = hasItem(descid,details.responseText);	//get number of item
							document.getElementById('span'+descid).innerHTML = '('+tmp+' in inventory)';	//and update span
						}
					});
				}
				event.stopPropagation(); event.preventDefault(); //stop the menu
			}, false);
		}

	}
}

function updatedb(){
	var lastupdated = GM_getValue('lastUpdate',0);
	var version = GM_getValue('version',0);

	var now = (new Date()).getTime()/1000; //make unix timestamp

	if( (now - lastupdated) > 60*60*24 ){	//have we checked today?
		GM_log('Checking item db');
		GM_get('kol.cmeister2.co.uk/items/?mode=json2&version='+version,function(response){
				if(response!=''){			//we get here if our version is not current
					GM_log('Saving database to Greasemonkey');
					GM_setValue('itemdb',response);
			
					if(m=(/"version":"(\d+)"/).exec(response)){
						GM_setValue('version',m[1]);
					}
				}
		});
		x=Math.floor((new Date()).getTime()/1000);
		GM_setValue('lastUpdate',x);
	}
}

function getdb(){
	//Simple function to load itemdb from config and return as an object
	var tmp = GM_getValue('itemdb','');
	if(tmp!=''){
		eval('var itemdb='+tmp);
		return itemdb;
	}else{
		return false;
	}
}


switch(window.location.pathname){
	case '/main.php':
		updatedb();
		break;
	case '/fight.php':
		addquantities();
		break;
	case '/choice.php':
		addquantities();
		break;
}