// ==UserScript==
// @name           LJSupport Board Status Tracker
// @namespace      http://afunamatata.com/greasemonkey/
// @description    Keep track of the changes in the Support Board since your last visit
// @include        http://www.livejournal.com/support/help.bml*
// @tags           ljsupport
// ==/UserScript==

// keep track of page by state and category
search = document.location.search.split ("&");
state = "";
cat = "";
for(var i = 0; i < search.length; ++i)
{
	if((index = search[i].indexOf("state") )!= -1)
	{
		state  = search[i].split("=")[1];
	}
	else if((index = search[i].indexOf("cat") )!= -1)
	{
		cat = search[i].split("=")[1];
	}
}

if(state == "open") state = "";

// make sure it's in order, else state+cat will be different from cat+state
filter = state + cat;

requestStatusOld = eval(GM_getValue('requestStatus'+filter, new Object()));
requestStatusNew = new Object();
requestStatusNew['dateVisited'] = new Date();
statsPar = document.evaluate("//p[starts-with(text(), '[')]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
requestStatusNew['stats'] = (statsPar != undefined) ? statsPar.innerHTML: "";

insertionPoint = document.evaluate("//form[@action='help.bml']/preceding::p", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;


var x = 0;
for(var i in requestStatusOld) { x++; break; }
isFirstTime = (x == 0) ? true : false;

tableXpath1 = "//form[@action='help.bml']/following::table" // everything else?
//tableXpath2 = "//form[@action='help.bml']/following::p/table"; // dystopia
removedDiv = document.createElement("div");
table= document.evaluate(tableXpath1 /*+ "|" + tableXpath2*/, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
removedDiv.innerHTML = "The following requests have been closed or moved since you last visited:<br />";
removedDiv.style.display = "none";
showRemoved = false;

var numChanges = 0;
if( !isFirstTime)
{
	statsDiv = document.createElement("div");
	statsDiv.innerHTML = "Last loaded " + requestStatusOld['dateVisited'] + "<br />Just loaded " + requestStatusNew['dateVisited'] + "<br />"+requestStatusOld['stats'];
	insertionPoint.parentNode.insertBefore(statsDiv, insertionPoint.nextSibling);
	statsDiv.style.fontSize = '0.8em';
	statsDiv.style.color = 'gray';
}

table.parentNode.insertBefore(removedDiv,table);
//xpath = document.evaluate(tableXpath1+"//tr" + "|" + tableXpath2+"//tr", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var rows = table.rows;
var idCell = (rows[0].cells.length==6) ? 1 : 0;
// skip header row
for( var i = 1; i < rows.length; ++i)
{
	row = rows[i];

	// rely on structure never changing! Hm.
	var id = row.cells[idCell].textContent;
	var index = id;
	// requestStatusNew[index] = row.className;
	var itemStatus = row.cells[row.cells.length-1].textContent;
	var chop = itemStatus.indexOf('(');
	if(chop == -1) chop = itemStatus.length;
	requestStatusNew[index] = itemStatus.substring(0,chop);
	//GM_log(requestStatusNew[index]);
	if( !isFirstTime )
	{
		// changed status
		if(requestStatusNew[index] != requestStatusOld[index])
		{
			row.cells[idCell].firstChild.firstChild.appendChild(document.createTextNode("="));
			// new request
			if(requestStatusOld[index] == undefined)
			{
				row.cells[idCell].appendChild(document.createTextNode("+"));
			}
			numChanges++;
			//GM_log(index + " did not match. " + requestStatusOld[index] + "=>"+requestStatusNew[index]);
			if(requestStatusNew[index] == "answeredawaiting close")
				row.style.backgroundColor="rgb(222,222,176)"; // yellow
			else if(requestStatusNew[index] == "open"
				|| requestStatusNew[index] == "answeredstill needs help" )
				row.style.backgroundColor="rgb(176,222,176)"; // green
			else if(requestStatusNew[index] == "closed")
				row.style.backgroundColor="rgb(222,176,176)"; // red
		}
	}
}

var removed = new Array();
// check for closed items as well
for( var i in requestStatusOld )
{
	if( requestStatusNew[i] == undefined )
	{
		removed.push(i + "'>#" + i);
	}
}


if (!isFirstTime)
{
	if(state != "youreplied" ) statsDiv.innerHTML += "<br />";
	statsDiv.innerHTML += numChanges + " updated and " + removed.length + " moved off this view for a total of " + (numChanges + removed.length) + " changed since your last visit.";

}

if(removed.length > 0 )
{
	removedDiv.innerHTML = "<a href='http://www.livejournal.com/support/see_request.bml?id=" + removed.join("</a> <a href='http://www.livejournal.com/support/see_request.bml?id=") + "</a>";
	removedDiv.style.display = "block";
}

GM_setValue('requestStatus'+filter, uneval(requestStatusNew));
