// ==UserScript==
// @name          Gmail Delete Button
// @namespace     http://www.arantius.com/article/arantius/gmail+delete+button/
// @description   Add a "Delete" button to Gmail's interface.
// @include       http*://*mail.google.com/*mail*?*
// @version       2.8.3
// ==/UserScript==

//
// Version 2.8.3:
//  - Polish translation
// Version 2.8.2:
//  - Russian translation
// Version 2.8.1:
//  - Bulgarian translation
// Version 2.8:
//  - Cleaned up bits of the code.  No more global scope objects.
//  - Deer Park compatible.
// Version 2.7.2:
//  - Better i81n, file encoded as unicode, to be compatible with newer 
//    versions of greasemonkey.
// Version 2.7:
//  - Internationalization.  If you speak a language other than english,
//    please check the existing text (if there) and/or suggest the right
//    word to mean 'Delete' in your language.
//  - A change to the default include path.
// Version 2.6:
//  - Add button into starred and sent mail section as per user request.
//  - Rework logic to use events (mouse click and key press) instead of
//    timers to further ameliorate lockouts.  I've recieved at least one
//    report that it was fixed by 2.3, and others that it was not at 2.5.
//    Perhaps it was fixed and the timing of reports was off, but this
//    should make things more certain.  I always welcome constructive
//    bug reports, I have never had a problem so I need information from 
//    those who have to change anything.
// Version 2.5:
//  - Change default include pattern to match a change in Gmail's code.
// Version 2.4:
//  - Remove red text.  You may restore the red color by un-commenting 
//    the proper line in _gd_make_dom_button.
//  - Do not show for a message in the spam folder.
//  - Minor tweaks.
// Version 2.3:
//  - Add/change code to track down/eliminate error conditions.
//  - Display error when there are no selected messages to delete.
//  - Include delete button in all labels and 'All Mail' section.
// Version 2.2:
//  - Patched to work with GreaseMonkey 0.3.3
//
// --------------------------------------------------------------------
// 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 _gd_dumpErr(e) {
	var s='Error in Gmail Delete Button:\n';
	s+='  Line: '+e.lineNumber+'\n';
	s+='  '+e.name+': '+e.message+'\n';
	dump(s);
}

function _gd_element(id) {
	try {
		var el=document.getElementById(id);
	} catch (e) {
		_gd_dumpErr(e);
		return false;
	}
	if (el) return el;
	return false;
}

function _gd_gmail_delete(e) {
	dump('Called _gd_gmail_delete()...\n');
	//find the command box
	var delete_button=e.target;
	var command_box=delete_button.parentNode.getElementsByTagName('select')[0];
	command_box.onfocus();

	//find the command index for 'move to trash'
	var delete_index=-1;
	for (var i=0; i<command_box.options.length; i++) {
		if ('tr'==command_box.options[i].value && !command_box.options[i].disabled ) {
			delete_index=i;
			break;
		}
	}

	//don't try to continue if we can't move to trash now
	if (-1==delete_index) {
		var box=_gd_element('nt1'); 
		if (box) {
			try {
				//if we find the box put an error message in it
				box.firstChild.style.visibility='visible';
				box.getElementsByTagName('td')[1].innerHTML='Could not delete. Make sure at least one conversation is selected.';
			} catch (e) {
				_gd_dumpErr(e);
			}
		}
		return;
	}

	//set the command index and fire the change event
	command_box.selectedIndex=delete_index;
	command_box.onchange();
	//command_box.dispatchEvent('click');
	//var evt=createEvent();
}

function _gd_make_dom_button(id) {
	var delete_button= document.createElement('button');
	delete_button.setAttribute('class', 'ab');
	delete_button.setAttribute('id', '_gd_delete_button'+id);
	delete_button.addEventListener('click', _gd_gmail_delete, false);
	
	//uncomment (remove the two leading slashes) from the next line for red text
	//delete_button.style.color='#EE3311';
	
	//this is a little hack-y, but we can find the code for the language here
	var lang='';
	try {
		var urlToTest=window.top.document.getElementsByTagName('frame')[1].src;
		var m=urlToTest.match(/html\/([^\/]*)\/loading.html$/);
		if (null!=m) lang=m[1];
	} catch (e) {
		_gd_dumpErr(e);
	}
	//now check that language, and find the right word!
	var buttonText='Delete'; //the default text for the button, overriden
	                         //in the switch below if we know the right word
	switch (lang) {
	case 'it': buttonText='Elimina'; break;
	case 'es': buttonText='Borrar'; break;
	case 'fr': buttonText='Supprimer'; break;
	//case 'pt-BR': buttonText='Supress&#227;o'; break;
	//it was suggested by a user that 'Apaga' is more proper for this language
	case 'pt-BR': buttonText='Apaga'; break;
	case 'de': buttonText='L&#246;schen'; break;
	case 'bg': buttonText='&#1048;&#1079;&#1090;&#1088;&#1080;&#1081;'; break;
	case 'ru': buttonText='&#1059;&#1076;&#1072;&#1083;&#1080;&#1090;&#1100;'; break;
	case 'pl': buttonText='Usu&#324;'; break;
	}
	
	delete_button.innerHTML='<b>'+buttonText+'</b>';
	return delete_button;
}

function _gd_insert_button(insert_container, id) {
	if (!insert_container) return false;
	if (_gd_element('_gd_delete_button'+id)) {
		return false;
	}

	//get the elements
	var spacer, delete_button;
	delete_button=_gd_make_dom_button(id);
	spacer=insert_container.firstChild.nextSibling.cloneNode(false);

	//pick the right place to put them
	var insert_point=insert_container.firstChild;  //this is default
	if (2==id || 3==id) {
		// 2 and 3 are inside the message and go at a different place
		insert_point=insert_point.nextSibling.nextSibling;
	}
	if (document.location.search.match(/search=query/)) {
		//inside the search page we go yet different places with different spacers
		if (0==id) {
			spacer=insert_container.firstChild.nextSibling.nextSibling.cloneNode(false);
			insert_point=insert_container.firstChild.nextSibling.nextSibling.nextSibling;
		}
		if (1==id) spacer=document.createElement('span'); //no space really needed here
	} else if (document.location.search.match(/search=sent/)) {
		//inside the sent page we go yet different places with different spacers
		if (0==id) {
			//spacer=insert_container.firstChild.nextSibling.nextSibling.cloneNode(false);
			//insert_point=insert_container.firstChild.nextSibling.nextSibling.nextSibling;
			spacer=document.createTextNode(' ');
			insert_point=insert_container.firstChild.nextSibling.nextSibling;
		}
		if (1==id) spacer=document.createElement('span'); //no space really needed here
	}

	//put them in
	insert_container.insertBefore(spacer, insert_point);
	insert_container.insertBefore(delete_button, spacer);
}

function _gd_place_delete_buttons() {
	if (!window || ! document || ! document.body) return;
	var top_menu=_gd_element('tamu');  if (top_menu) _gd_insert_button(top_menu.parentNode, 0);
	var bot_menu=_gd_element('bamu');  if (bot_menu) _gd_insert_button(bot_menu.parentNode, 1);
	var mtp_menu=_gd_element('ctamu'); if (mtp_menu) _gd_insert_button(mtp_menu.parentNode, 2);
	var mbt_menu=_gd_element('cbamu'); if (mbt_menu) _gd_insert_button(mbt_menu.parentNode, 3);
}

function _gd_button_event() {
	try{
		setTimeout(_gd_place_delete_buttons, 333);
		_gd_place_delete_buttons();
	} catch(e) {
		_gd_dumpErr(e);
	}
}

if (document.location.search) {
	var s=document.location.search;
	dump('Load gmail page: '+s+'\n');
	if (s.match(/\bsearch=(inbox|query|cat|all|starred|sent)\b/) ||
		( s.match(/view=cv/) && !s.match(/search=(trash|spam)/) )
	) {
		dump('==== Apply Gmail Delete Button to: ====\n'+s+'\n');
		//put the main button in
		try{_gd_place_delete_buttons();}catch(e){dump(e.message);}

		//set events to try adding buttons when the user does things
		//because gmail might create new places to need buttons.
		window.addEventListener('mouseup', _gd_button_event, false);
		window.addEventListener('keyup', _gd_button_event, false);
	}
}

})();
