/*
   This Greasemonkey userscript is designed to remove unnecessary TV channels
   from the TV by Grid feature of eurotv.com.

   Author: Eric Darchis <eric_GM@darchis.be>
   The selectNodes function comes from Patrick Cavit, pcavit@gmail.com
   License: GNU GPL
   Version 1.2

   Changelog:
   1.0: First version
   1.1: Adapted for recent greasemonkey versions
   1.2: Config Window added
*/

// ==UserScript==
// @name          EuroTV Grid Reducer
// @namespace     http://www.darchis.be/eric/
// @description	  Removes unwanted channels from the EuroTV.com TV by Grid
// @include       http://*.eurotv.com/scripts/grid*
// ==/UserScript==


var scriptVersion="1.2";
var configWindow=false; // Is the config window open ?
var allChannels=new Array();

/////////////////////////////////////////////////////////////////////////////////////
// Tools
var selectNodes=function (doc, context, xpath) {
   var nodes = doc.evaluate(xpath, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
   var result = new Array( nodes.snapshotLength );
   
   for (var x=0; x<result.length; x++) 
   {
      result[x] = nodes.snapshotItem(x);
   }
   
   return result;
}

/////////////////////////////////////////////////////////////////////////////////////
// Get the list of channels
///////////////////////////
// The idea is to list all <td> tags containing a <font> and a <b> inside.
// Those tags correspond to all headers of the grid, including the time.
// So we'll need to filter out those tags (starting with 1 or 2) and then
// return the parent->parent->parent to get the <tr> tag
var getChannelsList = function() {
	var channels = selectNodes(document, document.body, "//TD/FONT/B");
	var nodes = new Object();

	for (var x=0; x<channels.length; x++)
	{
		// Ignore the time cells (20:00, 21:00...)
		if (channels[x].textContent.indexOf("2")!=0) {
			//GM_log("channels[" + x + "] == " + channels[x].textContent + ", indexof(2)==" + channels[x].textContent.indexOf("2"));
			nodes[channels[x].textContent]=channels[x].parentNode.parentNode.parentNode;
		}
	}
	return nodes;
}

//////////////////////////////////////////////////////////////////////////////////////
// Configuration dialog
var cbChanged = function(e) {
	var cbName = e.target.getAttribute('name');
	if (e.target.checked) {
		GM_setValue(cbName,'checked');
		// GM_log("set " + cbName + " to checked");
	}
	else {
		GM_setValue(cbName,'unchecked');
		// GM_log("set " + cbName + " to UNchecked");
	}
}

var createConfigCheckbox = function(lab,nam,elem) {
	var span = document.createElement('span'); // a span to contain this line
	var cb = document.createElement('input'); // the checkbox
	cb.setAttribute('type','checkbox');
	var val=GM_getValue(nam);
	if (val) {
		if (val=='checked') {
			cb.setAttribute('checked',true);
			// GM_log(nam + " was explicitly checked");
		}
		else {
			// GM_log(nam + " was explicitly UNchecked");
		}
	}
	else {
		cb.setAttribute('checked',true);
		// GM_log(nam + " was not yet specified, checking by default");
	}
	cb.setAttribute('name',nam);
	cb.addEventListener('change',cbChanged,true);
	span.appendChild(cb);
	span.appendChild(document.createTextNode(lab)); // The label
	span.appendChild(document.createElement('br'));
	elem.appendChild(span);
}



var displayConfig=function(event) {
	if (configWindow)
		return false;
	
	configWindow=true;

	var body = document.body;

	// INIT Config DIV
	var newDiv = document.createElement('div');
	newDiv.setAttribute('id','configWindow');
	newDiv.style.position = 'absolute';
	newDiv.style.left = '50%';
	newDiv.style.top = '120px';
	newDiv.style.width = '700px';
	newDiv.style.height = '400px';
	//  newDiv.style.marginTop = '0px';
	newDiv.style.marginLeft = '-350px';
	newDiv.style.padding = '10px';
	newDiv.style.backgroundColor = 'gray';
	newDiv.style.borderWidth = '2px';
	newDiv.style.borderStyle = 'solid';
	newDiv.style.borderColor = '#9b0000';
	newDiv.style.MozBorderRadius = '10px';
	newDiv.style.color = '#000';
	//  newDiv.style.MozOpacity = '.95';

//	newDiv.style.backgroundImage = 'url(data:image/gif;base64,'+gm_logopic+')';
//	newDiv.style.backgroundPosition = 'bottom right';
//	newDiv.style.backgroundRepeat = 'no-repeat';

	var strongElem = document.createElement('strong');
	strongElem.innerHTML = '<u>Eurotv grid reducer</u> <small>[ '+scriptVersion+' ]</small><br>';
	newDiv.appendChild(strongElem);

	var div1 = document.createElement('div');
	div1.style.borderWidth = '1px';
	div1.style.borderColor = '#ccc';
	div1.style.borderStyle = 'solid';
	div1.style.width = '680px';
	div1.style.height = '300px';
	div1.style.marginLeft = '10px';
	div1.style.marginTop = '10px';
	div1.style.paddingLeft = '5px';
	div1.style.paddingTop = '5px';
	div1.style.overflow = 'auto';
	div1.setAttribute('id','chanDiv');

	// Affichages des chaînes disponibles.
	for (var i=0; i<allChannels.length; i++) {
		createConfigCheckbox(allChannels[i], "EGR_" + allChannels[i], div1);
	}
	
	newDiv.appendChild(div1);
	newDiv.appendChild(document.createElement('br'));

	var newA = document.createElement('a');
	newA.addEventListener('click',closeConfig,false);
	newA.href = '#';
	newA.appendChild(document.createTextNode('[fermer]'));
	newDiv.appendChild(newA);

	document.body.appendChild(newDiv);
	
	event.stopPropagation();
	event.preventDefault();
};

var closeConfig=function(event) {
	var win=document.getElementById("configWindow");
	win.parentNode.removeChild(win);
	configWindow=false;
	window.location.reload();
	event.stopPropagation();
	event.preventDefault();
};

var addIconForConfig=function() {
	// First find the second block of <centre> after which we'll insert the button
	var center2=selectNodes(document, document.body, "/html/body/center[2]");
	if (!center2 && center2.length>0) {
		alert("could not locate the place to insert the icon");
		return;
	}
	var button=document.createElement('a');
	button.setAttribute('href', '');
	button.appendChild(document.createTextNode('[ Configure the Eurotv grid reducer ]'));
	button.addEventListener('click', displayConfig, false);
	center2[0].parentNode.insertBefore(button, center2[0].nextSibling);
}

///////////////////////////////////////////////////////////////////////////////////////
// Main

// Check the script version and set it for future upgrades.
// Also take the opportunity to display an info message.
if (!GM_getValue("EGR_version")) {
	GM_setValue('EGR_version', '1.2');
	alert('To select your prefered channels, click on the link "[ Configure the Eurotv grid reducer ]"');
}

// First, list the channels
var channels = getChannelsList();

// Get the list of channel names before killing some of them
for (chan in channels) {
	allChannels[allChannels.length]=chan;
}

// Now, delete the undesired channels

//Note: refrain from doing a for (chan in channels) to delete them. The deleted objects will
//      make a mess in the object references and only half of them will actually disappear
for (var i=0; i<allChannels.length; i++) {
	var checked=GM_getValue("EGR_" + allChannels[i]);
	if (checked && checked=='unchecked') {
		//GM_log("del: " + channels[chan].innerHTML);
		channels[allChannels[i]].parentNode.removeChild(channels[allChannels[i]]);
	}
}

// Add the icon for the config
addIconForConfig();


