// A very simple and rough script to pick out the largest element on a
// page.  It is useful for some news papers for example.

// ==UserScript==
// @name           tidy
// @namespace      http://kalvis.com
// @description    Tidy up a page
// @include        http://www.telegraph.co.uk/*/*
// @include        http://www.guardian.co.uk/*/*
// ==/UserScript==

var body = document.getElementsByTagName("body")[0];
var best = body;

function mySize(object){
    // This should give a high score for stuff that looks like text.
    return object.textContent.split(/ +/).length;
}

function guts(bot, bottom){
    var active = false;
    var bits = best.getElementsByTagName("div");
    var biggest;
    var oldSize = 0;
    var size = 0;

    for (var i=0; i < bits.length; i++){
	var newSize = mySize(bits[i]);
	oldSize += newSize;
	if (newSize > size){
	    size = newSize;
	    biggest = bits[i];
	}
    }

    if ((size > bot*oldSize) && (size > bottom)){
	active = true;
	best = biggest;
    }

    return active;
}

function main(){
    var active = true;
    var body = best;
    var last;
    
    while (active)
	active = guts(0.10, 100);
    
    body.style.backgroundColor = "white";
    body.style.color = "black";
    body.style.font="12pt Helvetica";
    body.style.margin = "2%";
    body.align = "left";
    body.innerHTML = best.innerHTML;

    var articleTitle = document.createElement("H1");
    var tweet = document.createElement("H2");
    var email = document.createElement("H2");
    var articleFirst = body.firstChild;
    
    articleTitle.innerHTML = document.title;
    body.insertBefore(articleTitle, articleFirst);

    tinySource = {};
    tinySource.method = "GET";
    tinySource.url = "http://tinyurl.com/api-create.php?url=" 
	+ document.location;
    tinySource.onload = function(responseDetails){
	tweet.innerHTML = '<a href="http://twitter.com?status=' 
	+ escape(document.title + ' ' + responseDetails.responseText) 
	+ '">tweet</a>';
	var info;
	info = document.getElementsByName('Description')
	if (info.length > 0)
	    info = info[0].content;
	else
	    info = "";
	email.innerHTML = '<a href="mailto:?subject=' 
	+ escape(document.title) + '&body=' 
	+ escape(responseDetails.responseText + " " + info)
	+ '">email</a>';
    }
    
    GM_xmlhttpRequest(tinySource);
    
    body.insertBefore(tweet, articleFirst);
    body.insertBefore(email, articleFirst);

    var bits = body.getElementsByTagName("div");
    for (var i=0; i < bits.length; i++){
	bits[i].align = "left";
	bits[i].style.margin = "1%";
	bits[i].style.backgroundColor = "white";
	bits[i].style.color = "black";
    }
}

GM_log(document.location);

last = GM_getValue("last");

if (last != document.location.href){
    GM_setValue("last", document.location.href);
    main();
}else
    GM_setValue("last", "");

//Local Variables:
//mode: java
//End:
//
// Note that this is not exactly the right mode, but it works.
//
