// ==UserScript==
// @name          Protect Textarea
// @namespace     http://arantius.com/misc/greasemonkey/
// @description   Protect from closing or navigating away from a web page with changed textareas.
// @include       *
// @exclude       https://spreadsheets.google.com/*
// @exclude       http://spreadsheets.google.com/*
// @exclude       https://mail.google.com/*
// @exclude       http://mail.google.com/*
// @exclude       http://translate.google.com/*
// @version       1.2
// ==/UserScript==

// Version History:
//
// 1.2 (2009-09-15): Complete rewrite, less false positives for hidden
//                   fields controlled by scripts, better handling of
//                   dynamic/ajax sites.
// 1.1 (2006-09-18): Add the "noprotect" class detection
//

var gChanged=false;
var gSkip=false;

window.addEventListener('keypress', handleKeypress, true);
window.addEventListener('submit', handleSubmit, true);
window.addEventListener('beforeunload', handleUnload, true);

function handleKeypress(event) {
	if (
		// Ignore events not in a textarea.
		!event.target
		|| !event.target.tagName
		|| 'TEXTAREA'!=event.target.tagName
		// Ignore non-character keypresses.
		|| 0==event.charCode
		// Ignore "noprotect" textareas.
		|| event.target.classname.match(/\bnoprotect\b/)
	) {
		return;
	}

	if (0 /* debug? */) {
		console.log('saw keypress', event, 'in', event.target);
	}

	// At this point we have noticed a keypress to a textarea.  Record it.
	gChanged=true;
}

function handleSubmit(event) {
	gSkip=true;
}

function handleUnload(event) {
	if (gChanged && !gSkip) {
		event.returnValue='You have modified a textarea, and ' +
			'have not submitted the form.';
	}
}
