// ==UserScript==
// @name           WeeWar_Suite_v1.0
// @namespace      tag:katana@iaxs.net,2009-04-20:wwui
// @include        http://*weewar.com/game/*
// ==/UserScript==

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// WARNING /////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// Unfortunately, this script uses UNSAFE access to the web page's window object //
// There is *potential* for malicious scripts on the page to use this script for //
// SINISTER purposes - for details, see doc at                                   //
//               http://wiki.greasespot.net/UnsafeWindow                         //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////


// ============================================================================================
// =  This Weewar Suite is dedicated to all those weewar warriors who love the fight!         =
// =                                                                                          =
// =     Portions of this code were bastardized from several sources such as Pluto's Weewar   =
// =     Suite and Wombat's Weewar Suite.  The changes herein are for the new code revision   =
// =     of Weewar that occurred somewhere around 17 April, 2009.                             =
// ============================================================================================



// ============================================================================================
// - User Configurable Options -
// --------------------------------------------------------------------------------------------


var bDisable_Email_Notifications = true;			// Set this to false if you do not wish to have email notifications automatically turned off
var bEnable_Immediate_End_Round_Option = true;		// Set this to false if you only want the option to end safely (5 second countdown);
var bEnable_AutoRepair = true;						// Set this false if you do not want this item to be available in the toolbar



// ============================================================================================
// - End User Configurable Options - 
// **** No need to change anything below ***
// --------------------------------------------------------------------------------------------


// ============================================================================================
// - Global Variables -
// --------------------------------------------------------------------------------------------

var colorIndex = new Array();

InitTypes();          

// ============================================================================================
// - Enable Options based on User Configurable Options above -
// --------------------------------------------------------------------------------------------             

if (bDisable_Email_Notifications) { DisableEmailNotifications(); }
if (bEnable_Immediate_End_Round_Option) { EnableImmediateEndRound(); }

if (document.getElementById("endRoundLink") != null)						// Is it really our turn?
{
	drawToolbar();
}

// ============================================================================================
// - End Processing -
// - Functions Defined Below -
// --------------------------------------------------------------------------------------------             



// ============================================================================================
// - drawToolbar Functions -
// --------------------------------------------------------------------------------------------             

function drawToolbar() 
{
	var eMap = document.getElementById("map");
	var eParent = eMap.parentNode;	
	
	var eToolBar = document.createElement("a");
	eToolBar.id = "customToolBar";
	eToolBar.setAttribute("style", "font-size: .95em;");
	eToolBar.appendChild(document.createTextNode("WeeWar Suite Commands:"));
	
	var eToolDiv = document.createElement("div");
	eToolDiv.title = "Weewar Suite Tools";
	eToolDiv.setAttribute("style", "background-color: #EEE; padding: 3px 3px 5px 3px; margin: 3px 0px 0px 0px;");
	eToolDiv.appendChild(eToolBar);
	eParent.insertBefore(eToolDiv,eMap); 
	
	if (bEnable_AutoRepair)														// Create and Place AutoRepair Option in Toolbar
	{
		var eAutoRepair = document.createElement("a");
		eAutoRepair.id = "autoRepairLink";
		eAutoRepair.title = "**WARNING** Cannot be undone!";
		eAutoRepair.href = "#";
		eAutoRepair.setAttribute("style", "font-size: .85em; padding-left: 25px; color: #00BF00; text-decoration:none");
		eAutoRepair.addEventListener("click", AutoRepair, false);
		
		eAutoRepairImg = document.createElement("img");
		eAutoRepairImg.width = 16;
		eAutoRepairImg.height = 16;
		eAutoRepairImg.src = "http://plutosforge.com/images/wrench.png";
		eAutoRepairImg.alt = "AutoRepair";
		
		eAutoRepair.appendChild(eAutoRepairImg);
		eAutoRepair.appendChild(document.createTextNode("AutoRepair"));
		
		eToolDiv.appendChild(eAutoRepair);
	}
}

// ============================================================================================
// - AutoRepair Functions -
// --------------------------------------------------------------------------------------------             

function AutoRepair()  
{  
	var aUnits = new Array();  
	var oUnit = getElementsByAttribute(document, "img", "alt", colorIndex[findCurrentPlayerColor()] + ".*");  
	for (var i = 0; i < oUnit.length; i++)  
	{  
		if(oUnit[i].id.split("_").length == 3)   
         {  
             var hp = oUnit[i].src.split("_")[1].split(".")[0];  
             if (hp != "10" && oUnit[i].parentNode.childNodes[2] == null)                // If hp = 10 or unit is greyed then don't try to repair  
             {  
                 aUnits.push(oUnit[i]);  
             }  
         }  
     }  
     if (aUnits.length > 0)   
     {  
         // Click on enemy unit to ensure that no active units are currently selected.  Without this, the function can initiate an UNDO  
           
         var oElm = document.getElementsByTagName("area");  
         var x = 0;  
         do  
         {     
             var i = oElm[x].alt.indexOf(",");  
             var uID = "unit_" + oElm[x].alt.substr(0, i) + "_" + oElm[x++].alt.substr(i + 2);  
         } while( document.getElementById('uID') != null);  
         GenerateMouseEvent(oElm[x-1]);  
         setTimeout(function() { RepairUnit(aUnits); }, 1000);   
     }  
     return true;  
}  

function RepairUnit(aUnits, iPlayerInterface)
{
	var oElm = aUnits.pop();
	var x = oElm.id.split("_")[1];
	var y = oElm.id.split("_")[2];
	
	if (iPlayerInterface == null)
	{
		var oArea = getElementsByAttribute(document, "area", "alt", x + ", " + y)[0];
		var iPlayerInterface = oArea.getAttribute("onclick").split(":")[2];
	}
				
	var bResult = unsafeWindow.wicketAjaxGet("../?wicket:interface=:" + iPlayerInterface + ":map:container::IBehaviorListener:1:1&x=" + x + "&y=" + y,
		//null, 
		function() {unsafeWindow.wicketAjaxGet("../?wicket:interface=:" + iPlayerInterface + ":commandBox:linkList:0:commandLink::IBehaviorListener:0:1", 
			function() {return unsafeWindow.Wicket.$('commandLinkfc') != null;},
			null, 
			function(){return true;})},
		null, 
		null, 
		"clickmap");
		
	if (aUnits.length > 0) { setTimeout(function() { RepairUnit(aUnits); }, 1000); }			// setTimeout required to allow Ajax time to respond
}

// ============================================================================================
// - Turn off Email Notifications -
// --------------------------------------------------------------------------------------------

function DisableEmailNotifications()
{
	oEmail = getElementsByAttribute(document, "INPUT", "id", "emailNotification.*");
	if (oEmail != null && oEmail[0].checked) 	{ GenerateMouseEvent(oEmail[0]); }	
}

// ============================================================================================
// - Immediate End Round Functions -
// --------------------------------------------------------------------------------------------

function EnableImmediateEndRound()
{
	var originalLink = document.getElementById("endRoundLink");
	
	if (originalLink!= null)
	{
		originalLink.innerHTML = "End Safely";
		var parentNode = originalLink.parentNode;
		parentNode.innerHTML = parentNode.innerHTML.substring(0, parentNode.innerHTML.indexOf("<a href")) +
			"   <a href=\"#\" class=\"endRoundLink\" id=\"endImmediate\" onclick=\"countdownUpdate('endRoundLink', 0, false); return false;\">End Now</a>" +
			parentNode.innerHTML.substring(parentNode.innerHTML.indexOf("<a href"));
	}	
}

// ============================================================================================
// - Generic Functions -
// --------------------------------------------------------------------------------------------

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue)
{
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute(strAttributeName);
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}

function findCurrentPlayerColor(){
	
	return ({ 
		"colorIndex0 current": 0,
   	"colorIndex1 current": 1,
   	"colorIndex2 current": 2,
   	"colorIndex3 current": 3,
   	"colorIndex4 current": 4,
   	"colorIndex5 current": 5
   })[getElementsByAttribute(document, "li", "class", "colorIndex[0-9] current" )[0].className];
}

function GenerateMouseEvent(oElement)
{
	var evt = document.createEvent("MouseEvents");
	evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	oElement.dispatchEvent(evt);
}


function InitTypes()
{
	colorIndex = {	0 : "blue", 1 : "red",	2 : "purple", 3 : "yellow",	4 : "green", 5 : "white" };
}



