// ==UserScript==
// @name          Layout-Table Remover
// @namespace     http://www.comp.lancs.ac.uk/~ss/remove-table-layout
// @description   Stops <table> elements appearing as tables if thought to be used for layout.
// @include       *
// ==/UserScript==

function endsWith(base, target) {
    return base.substr(base - target) == target;
}

function checkForLayout(elem) {
    // A <table> with a summary is regarded as genuine tabular data.
    var sum = elem.getAttribute('summary');
    if (sum != null && sum != '')
	return false;

    // Otherwise, if the <table> contains <Hn> elements, or further
    // <table>s, it is treated as layout.
    for (var i = 1; i <= 6; i++)
	if (elem.getElementsByTagName('h' + i).length > 0)
	    return true;
    if (elem.getElementsByTagName('table').length > 0)
	return true;

    // Give everything else the benefit of the doubt.
    return false;
}

function makeBlock(elem) {
    var style = elem.getAttribute('style');
    if (!style) style = "";
    if (style != "" && !endsWith(style, ";")) style += "; ";
    style += "display: block";
    elem.setAttribute('style', style);
}

function disguisePart(elem, depth) {
    makeBlock(elem);
    if (depth <= 0) return;

    var parts = elem.childNodes;
    for (var i = 0; i < parts.length; i++) {
	var node = parts.item(i);
	if (node.nodeType != 1)
	    continue;
	disguisePart(node, depth - 1);
    }
}

function disguiseTable(elem) {
    var oldclass = elem.getAttribute('class');
    if (!oldclass)
	oldclass = '';
    else
	oldclass += ' ';
    oldclass += 'uk_ac_lancs_comp_ss_layout_table';
    elem.setAttribute('class', oldclass);
    return;
    makeBlock(elem);
    var parts = elem.childNodes;
    for (var i = 0; i < parts.length; i++) {
	var node = parts.item(i);
	//alert('child is ' + node.nodeName + '  type ' + node.nodeType);
	if (node.nodeType != 1)
	    continue;
	if (node.nodeName == 'CAPTION') {
	    elem.removeChild(node);
	    continue;
	}
	if (node.nodeName == 'TBODY' || node.nodeName == 'THEAD') {
	    disguisePart(node, 2);
	    continue;
	}
    }
}

var allElements = document.getElementsByTagName('table');
for (var i = 0; i < allElements.length; i++) {
    if (checkForLayout(allElements[i]))
	disguiseTable(allElements[i]);
}
