// Wolffauer's KoL Scripts
// Questions, comments, bug reports or donations to: Wolffauer (#1137554)
// 
// ==UserScript==
// @name          Wolffauer's Desert Safety
// @namespace     http://www.knauer.org/mike/kol/
// @description   Version 1.2
// @include       *kingdomofloathing.com/fight.php*
// @include       *kingdomofloathing.com/adventure.php*
// @include       *kingdomofloathing.com/charpane.php*
// @include       http://127.0.0.1:*/fight.php*
// @include       http://127.0.0.1:*/adventure.php*
// @include       http://127.0.0.1:*/charpane.php*
// @exclude       http://images.kingdomofloathing.com/*
// @exclude       http://forums.kingdomofloathing.com/*
// ==/UserScript==
//
/********************************** Recent Changes *****************************************
Recent Updates:
Version 1.2: Removed code for main frame (KoL now has those links built in)
Version 1.1: Added includes for KoLMafia
Version 1.0: Initial release
Version 0.9: Initial version of the script - Testing desert safety links
********************************************************************************************/

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

// - BEGIN MANUAL SECTION -
var currentVersion = "1.2";
var scriptURL = "http://www.knauer.org/mike/kol/WolffauerDesertSafety.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 -
// ---------------------------------------------------------------------------

if (window.location.pathname == "/charpane.php")
{
	curItem = document.firstChild;
	var numLeft = 0;
	var strStart = curItem.innerHTML.indexOf('Ultrahydrated');
	if (curItem.innerHTML.indexOf('Ultrahydrated') > -1)
	{
		numLeft = curItem.innerHTML.substring(strStart + 15,strStart + 16);
	}
	GM_setValue("numLeft", numLeft)

	results = document.getElementsByTagName("a");
    for (var i=0; i < results.length; i++ )
	{
      	curItem = results[i];
        if ((curItem.search == "?snarfblat=121") ||
			((curItem.search == "?snarfblat=123") && (numLeft < 1)))
		{
			curItem.style.color = "red";
			curItem.parentNode.innerHTML = curItem.parentNode.innerHTML 
				+ "<br><a target=mainpane href=\"adventure.php?snarfblat=122\">Visit the Oasis</a>";
			break;
		}
	}
}


/********  No longer needed ***********
if ((window.location.pathname == "/fight.php") ||	
	(window.location.pathname == "/adventure.php"))
{
	results = document.getElementsByTagName("a");
	numLeft = GM_getValue("numLeft", 0);
    for (var i=0; i < results.length; i++ )
	{
      	curItem = results[i];
        if ((curItem.search == "?snarfblat=121") ||
			((curItem.search == "?snarfblat=123") && (numLeft < 2)))
		{
			curItem.style.color = "red";
			curItem.parentNode.innerHTML = curItem.parentNode.innerHTML 
				+ "</p><p><a href=\"adventure.php?snarfblat=122\">Visit the Oasis</a>";
			break;
		}
		else if ((curItem.search == "?snarfblat=122") 
			&& (document.firstChild.innerHTML.indexOf('Ultrahydrated') > -1))
		{
			curItem.parentNode.innerHTML = curItem.parentNode.innerHTML 
				+ "</p><p><a href=\"adventure.php?snarfblat=123\">Visit the Arid, Extra Dry Desert</a>";
			break;
		}
	}
}
**********/
