// This is a Greasemonkey user script.
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "Hello World", and click Uninstall.
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name          IC Build below %age
// @namespace     http://www.imperialconflict.com
// @description   This script adds an input to the planets page. Works only in Advanced game mode. Lets you check all planets that are below the entered overbuild percentage. 
// @include       http://www.imperialconflict.com/myPlanets.php*
// ==/UserScript==

var maxbuildings = 120;
var curbuildings = 0;

function loader()
{
		
	var form = document.getElementsByTagName('form')[0];
	form.innerHTML = form.innerHTML + 'Check planets that are OB less than <input type="text" size="3" id="upto" />%<input type="button" value="Check boxes" id="syrinx" />';
}



function checkBoxes(event)
{
	var target = event ? event.target : this;
	var trs = document.getElementsByTagName('tr');
	var cbs = document.getElementsByName('planet[]');
	var row, posinrow, obperc, cb;
	var cbindex = new Array();
		
	if(target.type != "button" && target.id != "syrinx") return false;
	upto = parseInt(document.getElementById('upto').value);
  if (upto < 1 ) return false;
	
	//build an index to reference checkbox.id by value
	for (var i=0; i < cbs.length; i++){
							cbv = cbs[i].value;
							cbindex[cbv]=i;
						
	}
	
	for(i = 0; i < trs.length; i++)
	{
		row = trs[i];
		rowstr = row.innerHTML.toString(); 
		posinrow = rowstr.search("</font><br>+");

		if  ( posinrow > 0 ) {
				obperc = rowstr.substr(posinrow+12);
				obperc = parseInt(obperc.substr(0, obperc.search("%")));
		
				// check da box
				if (obperc < upto) {
					
					cb = rowstr.substr(rowstr.search('value=')+7);
					cb = cb.substr(0, cb.search('"'));
					//cb is the value of the checkbox
						var x=cbindex[cb];
					cbs[x].checked=true;
				}
		}
		
	}
	
}

window.addEventListener('load', loader, true);
window.addEventListener('click', checkBoxes, true);
