// ==UserScript==
// @name           Repeat Chop Wood
// @namespace      http://www.dealtinlead.com
// @description    Gives you 1-10 x Chop wood option
// @include        http://www.dealtinlead.com/Game
// @include        http://dealtinlead.com/Game
// ==/UserScript==

if (!GM_setValue) {
    alert('Please upgrade to the latest version of Greasemonkey.');
    return;
}

//if (GM_getValue("dil_chopwood")) {
//    alert("Chop wod counter: " + GM_getValue("dil_chopwood"));
//}

var chopForms = document.evaluate(
     '//form[@action="/Game/ChopWood"]',
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null);

var errorDiv = document.evaluate(
      '//div[@class="errorContainer"]',
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null);

if ((errorDiv.snapshotLength > 0) && (GM_getValue("dil_panhandle") > 1)) {
    alert("Error message detected. Aborting.");
    GM_setValue("dil_panhandle", 0);
    return;
}

// If we didn't find a craft button, reset count and return...
if (chopForms.snapshotLength != 1) {
    GM_setValue("dil_chopwood", 0);
//    GM_log("No chop wood button found");
    return;
}

//GM_log("Found chop wood button");

var chopForm = chopForms.snapshotItem(0);

// If you need to extend this to chop more than 10 at a time, add the HTML to the innerHTML value
var newSelect = document.createElement('select');
newSelect.setAttribute("name", "gm_chopwoodqty");
newSelect.setAttribute("id", "gm_chopwoodqty");
newSelect.innerHTML = "";
for (var loop=1;loop<=10;loop++) {
    newSelect.innerHTML = newSelect.innerHTML + '<option value="' + loop + '">' + loop + 'x</option>';
}

// the Chop Wood button is [1]
// the select dropdown is [2]
var found_chopwood = 0;
for (var idx = 0; idx < chopForm.childNodes.length; idx++) {
    if (chopForm.childNodes[idx].type == "submit") {
        chopForm.childNodes[idx].setAttribute("id", "gm_chopwood");
        chopForm.insertBefore(newSelect, chopForm.childNodes[idx]);
        found_chopwood = 1;
    }
}

// didn't get all the indexes? abort! abort!
if (! found_chopwood) {
    GM_log("Something went wrong - and index wasn't found...");
    GM_log("Indexes q:" + qty_idx + " c:" + chopwood_idx); 
    return;
}

// setup the listener for the button.
// When you click it, store the number of loops...
document.getElementById("gm_chopwood").addEventListener('click',
    function(event) {
        var quantity = document.getElementById("gm_chopwoodqty");
        if (quantity) {
            quantity = quantity.value;
        } else {
            quantity = 0;
        }
        GM_setValue("dil_chopwood", quantity);
    },
true);

if (GM_getValue("dil_chopwood",0) > 0) {
    GM_setValue("dil_chopwood", GM_getValue("dil_chopwood",0) - 1);

    if (GM_getValue("dil_chopwood", 0) > 0) {
        // submit id chopwood form
        // alert("Resubmitting...");
        document.getElementById("gm_chopwood").form.submit();
    }
}

