// ==UserScript==
// @author		tomasz.frelik (at) enzo.pl
// @namespace	http://frelo.enzo.pl/userscript
// @name		Travian: Mark Messages Read
// @description	Mark all unread messages read in one go on the Reports page. Note that it will only mark messages from the list on the current page. International version. Uses AJAX. The way it works is it loads all the unread messages in the background, so that the server marks them read. It may take a while sometimes. 
// @include		http://s*.travian*/berichte.php*
// ==/UserScript==

// EDIT HERE
// this is the text of the button
var markMessagesReadInYourLanguage = 'Mark new messages read';
// STOP EDITING

var msgURLs;
var newMessageFindPattern = "//table[@class='tbg']/tbody[1]//tr/td[@class='s7'][contains(text(),'(')][contains(text(),')')]/a[1]";
var delInputFindPattern = "//input[@name='del']";

messages_start();

function messages_start() {

	xPathResults = document.evaluate( newMessageFindPattern, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
	
	if ( xPathResults.snapshotLength == 0 ) {
		return;
	}
	
	var i = 0;
	msgURLs = new Array();
	while (( a = xPathResults.snapshotItem(i)) != null ) {
		msgURLs.push( a.href );
		i++;
	}	

	// add button to mark messages as read
	if ( msgURLs.length > 0 ) {
	
		var delInput = document.evaluate( delInputFindPattern, document, null,
			XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
		res = delInput.snapshotItem(0);
	
		var markReadButton = document.createElement( 'input' );
		markReadButton.type = "submit";
		markReadButton.className = "std";
		markReadButton.addEventListener( 'click', markRead, false );
		markReadButton.value = markMessagesReadInYourLanguage;		

		res.parentNode.insertBefore( markReadButton, res.nextSibling );
		res.parentNode.insertBefore( document.createTextNode( " " ), res.nextSibling );		
	}	

}

function markRead( e ) {

	while ( msgURLs.length > 0 ) {
		msgURL = msgURLs.pop();
		request( msgURL );
	}
	
	// and make the button disappear
	// srcElement for Opera, target for Firefox
	if ( e.srcElement ) {
		e.srcElement.parentNode.removeChild( e.srcElement );
	} else if ( e.target ) {
		e.target.parentNode.removeChild( e.target );
	}	
}

// make ajax request
function request( url ) {
	var ajax = new XMLHttpRequest();
	ajax.open( 'GET', url, false );
	ajax.send( '' );
}