// ==UserScript==
// @name          Gmail Action Links
// @namespace     http://www.arantius.com/misc/greasemonkey/
// @description   Add links to easily perform actions in Gmail.
// @include       http*://mail.google.com/*
// @version       0.3
// ==/UserScript==

//
// Version 0.3:
//  - Action links in front of select links in message list, so they
//    are always in the same place.
// Version 0.2:
//  - Do not show 'Mark Read' action in message view
// Version 0.1:
//  - Initial release, based loosely on my delete script
//
// --------------------------------------------------------------------
// Originally written by Anthony Lieuallen of http://www.arantius.com/
// Licensed for unlimited modification and redistribution as long as
// this notice is kept intact.
// --------------------------------------------------------------------
//
// If possible, please contact me regarding new features, bugfixes
// or changes that I could integrate into the existing code instead of
// creating a different script.  Thank you
//

(function(){

function _gal_watch_click(e) {
	var el=e.target;
	if (!el) return;
	if (!el.id) return;
	if ('_gal_'!=el.id.substr(0, 5)) return;

	e.preventBubble();
	
	var action=el.id.substr(5);
	var cont=el;
	while (null!=cont && 'TABLE'!=cont.tagName) cont=cont.parentNode;
	if (!cont) return;
	
	var box=cont.getElementsByTagName('select')[0];
	box.onfocus();
	var action_index=-1;
	for (var i=0; i<box.options.length; i++) {
		if (action==box.options[i].value && !box.options[i].disabled ) {
			action_index=i;
			break;
		}
	}
	if (-1==action_index) return;
	box.selectedIndex=action_index;
	box.onchange();
}

if (document.location.href.match(/name=js/)) {
	//var action_links=
	var action_tr='<span class=l id="_gal_tr">Trash</span>';
	var action_rd='<span class=l id="_gal_rd">Mark Read</span>'
	var action_ur='<span class=l id="_gal_ur">Mark Unread</span>';

	var val, val2;
	for (key in unsafeWindow) {
		val=unsafeWindow[key];
		if ('function'==typeof val) continue;

		//in message list view
		if ('string'==typeof val && 'Select:'==val.substr(0, 7)) {
			//remove "star" and "unstar" selections, they're silly
			val=val.split(', ');
			val.pop();
			val.pop();
			val=val.join(', ');
			//add on our actions
			val='Actions: '+action_tr+', '+action_rd+', '+action_ur+' '+val;
			unsafeWindow[key]=val;
		}
		//with message open
		if ('object'==typeof val) {
			val2=String(val);
			if (val2.match(/span class=lk id=bk/) && '<table'==val2.substr(0, 6)) {
				//modify the last element of the array to add our bits
				val[val.length-1]=
					'</span></tr><tr><td style="padding: 0px 8px">'+
					' Actions: '+action_tr+', '+action_ur+
					'</td></tr></table>';
				unsafeWindow[key]=val;
			}
		}
	}
} else {
	window.addEventListener('click', _gal_watch_click, true);
}

})();
