/*
	javascript: go through all links, replace those that link to wowhead items with mouseover coolness. (using ajax lookup)
	phpbbcode : replace [item] with a link to wowhead! (what about named items?)
*/

enable_debug = false;
enable_debuglog = false;
emistats_install_location = "/emistats/"

function debug_clearlog(msg)
{
	if (enable_debuglog) {
		var d = document.getElementById('debuglog');
		d.value = "";
	}
}

function debug(msg)
{
	if (enable_debug) alert(msg);
	if (enable_debuglog) {
		var d = document.getElementById('debuglog');
		d.value = d.value + msg + "\n";
	}
}

function emistats_callback(data, textStatus) {
	debug("---");
	debug("ajax callback : " + textStatus + "\n" + data);
	if ( !data ) {
		debug("no data!");
		return;
	}
	// trim whitespace
	data = data.replace(/^\s+|\s+$/g, '') ;
	
	// split the response up into it's parts
	result = data.split("|");
	
	var prefix = result[0];
	var obj_id = result[1];
	var obj_name = result[2];
	var obj_qual = result[3];
	var obj_icon = result[4];
	
	var hashid = prefix+obj_id;
	var queuehashid = "queue"+hashid;
	
	// store in wowhead_cache
	$.jCache.setItem(hashid, new Array(obj_id, obj_name, obj_qual, obj_icon) );
	
	// check type (item etc)
	
	// call the updatehtml function for each member that cared
	var callbacks = $.jCache.getItem(queuehashid);
	
	
	// update the item in html, based on the callback DOM Nodes.
	debug( "type : " + typeof(callbacks));
	debug( "length : " + callbacks.length);
	for ( i = 0; i < callbacks.length; i++ )
	{
		emistats_updatefromcache(callbacks[i], prefix, hashid);
	}
	$.jCache.removeItem(queuehashid);
	
	debug("---");
}


// updates an item from the cache
function emistats_updatefromcache( linky, type, hashid )
{
	// item from cache:
	var cached = $.jCache.getItem(hashid);
	var obj_id = cached[0];
	var obj_name = cached[1];
	var obj_qual = cached[2];
	var obj_icon = cached[3];
	
	debug("linky: " + linky);
	switch ( type )
	{
		case "i":
			linky.innerHTML = "<span onmouseover=\"get_tooltip('"+type+"', '"+obj_id+"')\" onmouseout=\"clear_tooltip()\" class=\""+obj_qual+"name\">["+obj_name+"]</span>";
			break;
		case "a":
			linky.innerHTML = "<span onmouseover=\"get_tooltip('"+type+"', '"+obj_id+"')\" onmouseout=\"clear_tooltip()\" class=\""+obj_qual+"name\">["+obj_name+"]</span>";
			break;
		default:
			debug("emistats_updatefromcache: Unknown type.");
			break;
	}
}

// Item sites:
// - wowhead              http://www.wowhead.com/?item=32344
// - wotlk.wowhead        http://wotlk.wowhead.com/?item=32344
// - wowarmory            http://www.wowarmory.com/item-info.xml?i=32344
// - thottbot             http://thottbot.com/i32344
// - wow.allakhazam       http://wow.allakhazam.com/db/item.html?witem=32344;source=live
// - wowdb                http://www.wowdb.com/item.aspx?id=32344

// npc sites:
// - wowhead
// - wowarmory
// - wowdb

// recipe sites: (ie. mana potion=felweed+dreaming glory)
// - wowhead

// player char sites:
// - wowarmory

// zone sites:
// - wowhead
var itemlink_regex = new Array(
		Array("wowhead", "wowhead\\.com\\/\\?item=([0-9]+)"),
		Array("wowarmory", "wowarmory.com\\/item-info\\.xml\\?i=([0-9]+)"),
		Array("thottbot", "thottbot\\.com\\/i([0-9]+)"),
		Array("wow.allakhazam", "wow\\.allakhazam\\.com\\/db\\/item\\.html\\?witem=([0-9]+)"),
		Array("wowdb", "wowdb\\.com\\/item\\.aspx\\?id=([0-9]+)")
);
var charlink_regex = new Array(
	Array("wowarmory", "www\\.wowarmory.com\\/character-[A-Za-z]+\\.xml\\?r=([A-Za-z]+)&n=([A-Za-z]+)"),
	Array("wowarmory", "www\\.wowarmory.com\\/character-[A-Za-z]+\\.xml\\?r=([A-Za-z]+)&n=([A-Za-z]+)"),
	Array("wowarmoryeu", "eu\\.wowarmory.com\\/character-[A-Za-z]+\\.xml\\?r=([A-Za-z]+)&n=([A-Za-z]+)")
);
var achievement_regex = new Array(
		Array("wowhead", "wowhead\\.com\\/\\?achievement=([0-9]+)")
);

function emistats_processlink( index, linky )
{
	debug( "Processing Link : " + linky );
	// match item links

	jQuery.each(itemlink_regex, function(i,site_regex){
		var results = emistats_matchregex( site_regex[1], linky );
		if ( results ) emistats_requestupdate(linky, "i",  results[1]);
	});
	
	jQuery.each(charlink_regex, function(i,site_regex){
		var results = emistats_matchregex( site_regex[1], linky );
		if ( results ) emistats_requestupdate(linky, "c", results);
	});
	
	jQuery.each(achievement_regex, function(i,site_regex){
		var results = emistats_matchregex( site_regex[1], linky );
		if ( results ) emistats_requestupdate(linky, "a", results[1]);
	});
}

function emistats_matchregex(regex, linky) {
	//debug("checking" + regex);
	var linky_href = linky.href;
	var re = new RegExp(regex);
	var results = linky_href.match(re);
	if ( results && results[1] && linky.childNodes.length == 1 )
	{
			return results;
	}
	return false;
}

// takes the link object, type and id of the item(item id, char/server name, npc name/id).
function emistats_requestupdate( linky, type, data )
{
	var hashid, queuehashid, ajax_getdata;
	switch ( type ) {
		case "i":
			var itemid = data;
			
			hashid = type+itemid;
			queuehashid = "queue"+hashid;
			ajax_getdata = "item="+itemid;
			break;
		case "c":
			var server = data[1];
			var charname = data[2];
			
			hashid = type+server+charname;
			queuehashid = "queue"+hashid;
			ajax_getdata = "r="+server+"&n="+charname;
			break;
		case "a":
			var achievementid = data;
			
			hashid = type+achievementid;
			queuehashid = "queue"+hashid;
			ajax_getdata = "a="+achievementid;
			break;
		default:
			debug("unknown type!");
	}
	
	debug("hashid : "+ hashid);
	// check if we have this in our cache!
	var cached = $.jCache.getItem(hashid);
	var queued =  $.jCache.getItem(queuehashid);
	if ( cached )
	{
		 debug("Result: already in cache");
		 emistats_updatefromcache( linky, type, hashid )
	}
	else 	if ( queued )
	{
		// if theres already a waiting callback, just add ourselves to the list of DOM Nodes who care
		queued.push(linky);
		$.jCache.setItem( queuehashid, queued );
		debug("Result: Someone else cares too! Added ourselves to 'care list'");
	}
	else
	{
		debug("Result: Adding to Ajax request.");
		// if we don't, trigger an ajax call for this item, storing the current DOM element (carefully!).
		$.jCache.setItem( queuehashid, new Array(linky) );
		debug("GETDATA: "+ajax_getdata);
		$.ajax({
			type: "GET",
			url: emistats_install_location+"getquick.php",
			data: ajax_getdata,
			success: emistats_callback
		});
	}
}

function emistats_load()
{
	$.jCache.maxSize = 250;
	
	debug_clearlog();
	
	// if cookie exists AND we're disabled, bail out.
	if ( readCookie("emistats_disabled") == "true" )
		return;
	
	var hyperlinks = jQuery('a');
	debug("Total num links:" + hyperlinks.length);
	hyperlinks.each( emistats_processlink );
}

// add to onload
$(document).ready(emistats_load);
