// ==UserScript==
// @name           Repeat Mine Ore
// @namespace      http://www.dealtinlead.com
// @description    Gives you 1-10 x Mine Ore 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_mineore")) {
//    alert("Chop wod counter: " + GM_getValue("dil_mineore"));
//}

var mineoreForms = document.evaluate(
     '//form[@action="/Game/MineOre"]',
      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 (mineoreForms.snapshotLength != 1) {
    GM_setValue("dil_mineore", 0);
//    GM_log("No mineore button found");
    return;
}

//GM_log("Found mineore button");

var mineoreForm = mineoreForms.snapshotItem(0);

// If you need to extend this to mineore more than 10 at a time, add the HTML to the innerHTML value
var newSelect = document.createElement('select');
newSelect.setAttribute("name", "gm_mineoreqty");
newSelect.setAttribute("id", "gm_mineoreqty");
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_mineore = 0;
for (var idx = 0; idx < mineoreForm.childNodes.length; idx++) {
    if (mineoreForm.childNodes[idx].type == "submit") {
        mineoreForm.childNodes[idx].setAttribute("id", "gm_mineore");
        mineoreForm.insertBefore(newSelect, mineoreForm.childNodes[idx]);
        found_mineore = 1;
    }
}

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

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

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

    if (GM_getValue("dil_mineore", 0) > 0) {
        // submit id mineore form
        // alert("Resubmitting...");
        document.getElementById("gm_mineore").form.submit();
    }
}

