// Wolffauer's KoL Scripts
// Questions, comments, bug reports or donations to: Wolffauer (#1137554)
// 
// ==UserScript==
// @name          Wolffauer's Record Monitor
// @namespace     http://www.knauer.org/mike/kol/
// @description   Version 0.07
// @include       *kingdomofloathing.com/main.php*
// @include       *kingdomofloathing.com/records.php*
// @exclude       http://images.kingdomofloathing.com/*
// @exclude       http://forums.kingdomofloathing.com/*
// ==/UserScript==
//
/********************************** Recent Changes *****************************************
Recent Updates:
Version 0.07: Changed name.  Generalized to any one record.  Sort of works.
Version 0.06: Added color
Version 0.05: Does stuff.  Might even work
Version 0.01: Initial version of the script - does little to nothing
********************************************************************************************/

var monitorRecord = "Most Clan Warfare Wins";

// ---------------------------------------------------------------------------
// Picklish's VERSION CHECKER 1.3 

// - BEGIN MANUAL SECTION -
var currentVersion = "0.07";
var scriptURL = "http://www.knauer.org/mike/kol/WolffauerRecordMonitor.user.js";
var scriptName = "Wolffauer's Record Monitor";
// The version checker will show non-errors if and only if this boolean
// is false and GM_getValue("showOnlyErrors") is false or unset.
var showOnlyErrors = true;

// The elements of resources are five element arrays which contain a
// resource name (for displaying), a resource link (for downloading
// the resource), a downloaded value name (for storing the result of the
// resource in a greasemonkey variable of that name), and a time in days
// before re-checking this resource, and finally a variable to set to "1" 
// whenever a variable has been gotten.
var resources = "";
//var resources = new Array(
//    new Array(
//        "Item Database",
//        useitemdb,
//        "useitemdb",
//        2,
//        gotNewItemDB
//    )
//);

// - END MANUAL SECTION -

// - BEGIN CUT AND PASTE SECTION -
var datePrefix = "CheckTime-";

function MakeBullet(message)
{
    return "<tr><td><font size=-2>&nbsp;&#42;" + message + "</font></td></tr>";
}

// Check for an updated script version and print the result box...
function CheckScriptVersion()
{
    // Preemptively set error, in case request fails...
    GM_setValue("webVersion", "Error")

    GM_xmlhttpRequest({
        method: "GET",
        url: scriptURL,
        headers:
        {
            "User-agent": "Mozilla/4.0 (compatible) Greasemonkey",
            "Accept": "text/html",
        },
        onload: function(responseDetails)
        {
            if (responseDetails.status == "200")
            {
                var m = responseDetails.responseText.match(
                    /description\s*Version (\w+(?:\.\w+)?)/);
                if (m && !isNaN(m[1]))
                {
                    GM_setValue("webVersion", m[1]);
                }
            }

            var message;
            var warningLevel = 0;
            var forceGet = false;

            var webVer = parseFloat(GM_getValue("webVersion"));
            if (GM_getValue("webVersion", "Error") == "Error")
            {
                message = "Failed to check website for updated version of script.";
                warningLevel = 1;
            }
            else if (isNaN(webVer))
            {
                message = "Couldn't find suitable version number.";
                warningLevel = 1;
            }
            else
            {
                if (webVer > parseFloat(currentVersion))
                {
                    message = "Right click <a href='" + scriptURL + "' TARGET='_blank'>here</a> and select 'Install User Script' for Version " + webVer + ".";
                    warningLevel = 2;
                }
                else
                {
                    if (webVer < parseFloat(currentVersion))
                    {
                        message = "Script is newer than web version.";
                        warningLevel = 0;
                        forceGet = true;
                    }
                    else
                    {
                        message = "Script is latest version.";
                        warningLevel = 0;
                    }
                }
            }

            // In either case, check remaining resources...
            CheckResource(0, warningLevel, MakeBullet(message), forceGet);
        }
    });
}

function CheckResource(index, warningLevel, message, forceGet)
{
    if (index >= resources.length)
    {
        PrintCheckVersionBox(warningLevel, message, forceGet);
        return;
    }

    var name = resources[index][0];
    var url = resources[index][1];
    var varname = resources[index][2];
    var daylimit = parseFloat(resources[index][3]);
    var gotvar = resources[index][4];

    var now = new Date();

    // if the script version has changed, update resource.
    var oldVersion = GM_getValue(varname + "_version", "0.0");
    if (parseFloat(oldVersion) < parseFloat(currentVersion))
    {
        forceGet = true;
    }

    // if don't need to get...
    if (!forceGet && GM_getValue(datePrefix + varname, 0) != 0 &&
        (now.getTime() <= Date.parse(GM_getValue(datePrefix + varname)) +
        daylimit * 86400000))
    {
        var timeString;
        if (daylimit == 1.0)
            timeString = daylimit + " day";
        else
            timeString = daylimit + " days";
        message += MakeBullet(name + ": Less than " + timeString + 
            " old, using cached version.");
        CheckResource(index + 1, warningLevel, message, forceGet);
        return;
    }

    // otherwise we need to get this resource...
    GM_xmlhttpRequest({
        method: 'GET',
        url: url,
        headers: {'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
            'Accept': 'text/html',},
        varname: varname,
        name: name,
        index: index,
        gotvar: gotvar,
        onload: function(responseDetails)
        {
            if (responseDetails.status != 200)
            {
                GM_log("Error getting " + this.name + "@" + this.url + ": " + 
                    responseDetails.status);
                
                if (GM_getValue(varname, "") == "")
                {
                    if (warningLevel < 2)
                        warningLevel = 2;
                    message += MakeBullet(this.name + ": Error accessing resource.  No cached version to use.");
                }
                else
                {
                    if (warningLevel < 1)
                        warningLevel = 1;
                    message += MakeBullet(this.name + ": Error accessing stale resource.  Using cached version.");
                }
            }
            else
            {
                GM_setValue(this.varname, responseDetails.responseText);
                var size = GM_getValue(this.varname).length;
                message += MakeBullet(this.name + ": Downloaded new version (" + size + " bytes.)");
                GM_log("Got " + this.varname + " (" + size + " bytes)");

                var now = new Date();
                GM_setValue(datePrefix + this.varname, now.toString());

                GM_setValue(gotvar, 1);
                GM_setValue(varname + "_version", currentVersion);
            }

            CheckResource(index + 1, warningLevel, message, forceGet);
        }
    });
}

function PrintCheckVersionBox(resourceWarningLevel, resourceMessage, forceBox)
{
    // set color from warning level
    var color;
    if (resourceWarningLevel > 1)
    {
        color = "red";
    }
    else if (resourceWarningLevel > 0)
    {
        color = "orange";
    }
    else
    {
        color = "blue";

        // if no errors, return...
        if (!forceBox && (showOnlyErrors || 
            GM_getValue("showOnlyErrors", false)))
        {
            return;
        }
    }

    var span = document.createElement("center");
    span.innerHTML = "<table style='border: 1px solid " + color + "; margin-bottom: 4px;' width=95% cellpadding=1 cellspacing=0><tr><td bgcolor=" + color + "><font color=white size=-2><b>" + scriptName + "</b> " + currentVersion + ":</font></td></tr>" + resourceMessage + "</table>";

    document.body.insertBefore(span, document.body.firstChild);
}

if (window.location.pathname == "/main.php")
{
    CheckScriptVersion();
}
// - END CUT AND PASTE SECTION -
// ---------------------------------------------------------------------------

var newClans = "";

if (window.location.pathname == "/records.php")
{
	var tableThing = document.getElementsByTagName('tbody');
	var len = tableThing.length;
	var found = false;

	for (var i=1; i<len; i++)
	{	
		var temp = tableThing[i];
		if (temp.firstChild.firstChild.firstChild.firstChild)
		{
			if (temp.firstChild.firstChild.firstChild.firstChild.nodeValue == monitorRecord)
			{	
				tableThing = temp; 
				found = true;
				break;
			}
		}	
	}

	if (found)
	{
		// There must be an easier way to do this...
		tableThing = tableThing.childNodes[1].firstChild.firstChild.firstChild.firstChild.firstChild.firstChild.firstChild.firstChild;

		var rowThing = tableThing.getElementsByTagName('tr');
		len = rowThing.length;

		var cell = rowThing[0].insertCell(-1);
		cell.className = 'small';
		cell.align = 'right';
 	   	cell.innerHTML = '<b>&nbsp;&nbsp;<A name="change" href="#change">Change</a></b>';
		cell.addEventListener('click', function(event) {
			// event.target is the element that was clicked
			// do whatever you want here
			// if you want to prevent the default click action
			// (such as following a link), use these two commands:
			//event.stopPropagation();
			//event.preventDefault();
		
			GM_setValue(monitorRecord, uneval(newClans));
		}, true);

		oldClans = eval(GM_getValue(monitorRecord, new Array()));
		//GM_log(oldClans);

		newClans = new Array(len - 1);
		for (i=1; i<len; i++)
		{
			var clanName = rowThing[i].cells[0].getElementsByTagName('b');
			clanName = clanName[0].innerHTML;

			var clanStat = rowThing[i].cells[1].innerHTML;
			clanStat = Number(clanStat.replace(',',''));

			newClans[i-1] = [clanName,clanStat];

			var oldVal = -1;
			for (var j=0; j<oldClans.length; j++)
			{
				if (oldClans[j][0] == clanName)
				{
					oldVal = oldClans[j][1];
					break;
				}
			}

			cell = rowThing[i].insertCell(-1);
			cell.className = 'small';
			cell.align = 'right';
			if (oldVal == -1)
			{
				cell.style.cssText = '';
 	   			cell.innerHTML = '&nbsp;(new)&nbsp;';
			}
			else if (oldVal < clanStat)
			{
				cell.style.cssText = 'color: green;';
 	   			cell.innerHTML = '&nbsp;+' + (clanStat-oldVal) + '&nbsp;';
			}
			else if (oldVal == clanStat)
			{
				cell.style.cssText = '';
 	   			cell.innerHTML = '&nbsp;0&nbsp;';
			}
			else
			{
				cell.style.cssText = 'color: red;';
 	   			cell.innerHTML = '&nbsp;' + (clanStat-oldVal) + '&nbsp;';
			}
		}
	}
}
