// ==UserScript==
// @name           WR2ogame
// @namespace      ogame.fr
// @description    War-rider's link to ogame
// @include        http://www.war-riders.de/*/details/player/*
// ==/UserScript==

// LastMod : 2008-07-07

(function () {
	// Get ogame informations from referer
	var url = document.referrer+'' ; // TransTyping
	var cut = url.split('\/') ;
	var host = cut[2] ;
	var cut = host.split('\.') ;
	var uni = cut[0].substr(3) ;
	var lang = cut[2] ;
	var vars = getvars(url) ;
	var urls = new Array() ;
	if ( vars['session'] ) { // If referer is ogame
		var session = vars['session'] ;
		// First line : title line -> colspan++
		mytable = xpath('//TABLE[@class="border"]').snapshotItem(1) ;
		mytable.rows[0].cells[0].colSpan++ ;
		// Second line : columns titles -> add image
		var mycell = mytable.rows[1].insertCell(1) ;
		mycell.className = 'cl' ;
		var mycolumntitle = ogameimage() ;
		mycolumntitle.title = 'Open all systems' ;
		mycell.appendChild(mycolumntitle) ;
		// Each other line
		for ( var i=2 ; i < mytable.rows.length ; i++ ) {
			var myrow = mytable.rows[i] ;
			var planet = myrow.cells[0].firstChild.firstChild.nodeValue ;
			var coords = planet.split(':') ;
			var mya = document.createElement('A') ;
			mya.href = 'http://uni'+uni+'.ogame.'+lang+'/game/index.php?page=galaxy&galaxy='+coords[0]+'&system='+coords[1]+'&planet='+coords[2]+'&session='+session
			mya.target = '_blank' ;
			mya.appendChild(ogameimage()) ;
			mycell = myrow.insertCell(1)
			mycell.appendChild(mya) ;
			if ( i < mytable.rows.length ) { // Not on last line
				var j = i ;
				do {
					j++ ;
					changed = false ;
					if ( j < mytable.rows.length ) { // Not on last line
						var mynextrow = mytable.rows[j] ;
						var nextplanet = mynextrow.cells[0].firstChild.firstChild.nodeValue ;
						var nextcoords = nextplanet.split(':') ; // Let's look coords of next line
						if ( ( coords[0] == nextcoords[0] ) && ( coords[1] == nextcoords[1] ) ) { // Next planet in the same system
							mycell.rowSpan++ ; // Use same link, by merging this cell and next one
							mya.href += '&planet='+nextcoords[2] ; // Add this planet to the link
							i = j ; // Don't create next line
							changed = true ; // Retry one time at least
						}
					}
				} while ( changed )
			}
		urls.push(mya.href) ;
		}
	mycolumntitle.addEventListener('click',function(evt) {
		for ( link in urls )
			window.open(urls[link]) ;
	},false) ;
	}
})();

// === [ FUNCTIONS ] ===========================================================
function ogameimage() {
	var myimg = document.createElement('IMG') ;
	myimg.src = 'http://www.ogame.fr/favicon.ico' ;
	myimg.alt = 'link to ogame galaxy view' ;
	return myimg ;
}
function getvars(myurl) { // parse URL, returns it as an array
	var myurlvar = Array() ; // result
	myurl = myurl.substring(1,myurl.length) ;
	var myurlvars = myurl.split('&') ; // Cut URL in absolute + params
	if ( myurlvars.length > 1 ) { // If there are params
		for ( var i = 0 ; i < myurlvars.length ; i++ ) {
			var tmp = myurlvars[i].split('=') ;
			if ( tmp.length == 2 )
				myurlvar[tmp[0]] = tmp[1] ;
			else
				alert('Pas la bonne longueur : '+tmp.length+' - '+myurlvars[i]) ;
		}
	}
	return myurlvar ;
}

// -------------------------------------------------------- [ AUTRES ] ---------
// Fonctions repompees, a refaire, peut-etre
function xpath(query) {
	return document.evaluate( query , document , null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE , null );
}
function strip(str) { // Removes all type of spaces from the string (space, tab, carriage return, newline ...)
	return str.replace(/\f/g,'').replace(/\n/g,'').replace(/\r/g,'').replace(/\t/g,'').replace(/\v/g,'').replace(/^\s*/g,'').replace(/\s*$/g,'') ;
}
function debug_xml_element_new(node,prefix) {
// Fonction de debug : retourne une chaine indiquant la structure de l'objet XML passe en parametre
// La fonction est recursive et doit etre appelee avec un prefixe pour l'affichage, de preference, mettre une chaine vide
	var result ='';
	switch (node.nodeType) {
		case 1:
		case 9:
			var childs = node.childNodes ;
			result += prefix + '<' + node.nodeName + '>' ;
			if ( node.nodeValue != null )
				result += '(' + node.nodeValue + ')' ;
			result += '\n' ;
			if ( childs.length > 0 ) {
				for( var i = 0 ; i < childs.length ; i++ ) {
					child = childs.item(i) ;
					result += debug_xml_element_new(child,prefix+'\t('+i+')') ;
				}
			}
			break;
		case 3:
			var text = strip(node.nodeValue) ;
			//if ( text != '' ) 
				result += prefix + '"' + text + '"\n' ;
			break;
		default:
			result += prefix + 'unknown node type ' + node.nodeType + '\n'
	}
	return result ;
}
function debug(node) {
	alert(debug_xml_element_new(node,'')) ;
}
