// ==UserScript==
// @name          Gmail Delete Button
// @namespace     http://www.arantius.com/article/arantius/gmail+delete+button/
// @description	  Add a "Delete" button next to Gmail's "Archive" button.
// @include       http://gmail.google.com/gmail*
// @include       https://gmail.google.com/gmail*
// ==/UserScript==

//
// Originally written by Anthony Lieuallen of http://www.arantius.com/
// Please do not remove this text when creating modified versions.
// If possible, please contact me regarding new features, bugfixes
// or changes that I could integrate into the existing code instead of
// creating different versions.  Thank you
//

var _gd_js_frame=false,_gd_main_frame=false,_gd_insert_timer=false,_gd_button_num=0;

function _gd_gmail_delete(win){
	//find the command box
	var command_box=_gd_main_frame.document.getElementById('tamu');
	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;
		}
	}
	if (-1==delete_index) return;

	//set the command index and fire the change event
	command_box.selectedIndex=delete_index;
	command_box.onchange();
}

function _gd_button_exists(id) {
	if (!_gd_main_frame) return false;
	var el=_gd_main_frame.document.getElementById(id);
	if (el) return el;
	return false;
}

function _gd_insert_delete_button() {
	//Don't try to insert button if it already is there
	if (_gd_button_exists('_gd_delete_button')) return false;
	
	//Don't try to insert button if we can't find where to put it
	var archive_button=_gd_button_exists('ac_rc_^i');
	if (!archive_button) return false;

	//create DOM object for button
	var delete_button=_gd_main_frame.document.createElement('button');
	delete_button.setAttribute('class', 'ab');
	delete_button.setAttribute('id', '_gd_delete_button');
	delete_button.setAttribute('onclick', 'top._gd_gmail_delete(window);');
	delete_button.innerHTML='<b>Delete</b>';
	var spacer=archive_button.nextSibling.cloneNode(false);
	
	//insert button into DOM
	archive_button.parentNode.insertBefore(delete_button, archive_button);
	archive_button.parentNode.insertBefore(spacer, archive_button);
}

function _gd_magic() {
	_gd_js_frame=window.frames['js'];
	_gd_main_frame=window.frames['main'].frames[0];
	_gd_insert_delete_button();
}

if ('gmail.google.com/gmail'==document.location.hostname+document.location.pathname) {
	_gd_insert_timer=setInterval('_gd_magic();', 100);
}
