/*
warnchange.js
This script should be included in pages where forms
information entering could take a long time.  It adds
an OnChange handler to every input, select, and textarea
tag that sets a global "form has changed" flag.  It also
adds an OnBeforeUnload handler to the window that checks 
whether form has changed and warns the user before 
allowing them to go to another page.
*/


//addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
function addEventWC( obj, type, fn ) {/* added WC to name to avoid namespace conflict */
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

var isFormChanged = false;

function setInputHandlers(items) {
	for(var i = 0; i < items.length; i++)
		addEventWC(items[i], 'change', function() { isFormChanged = true; });
}

function initWC() {
	var forms = document.getElementsByTagName('form');
	for(var i = 0; i < forms.length; i++) { 
	    var form = forms[i];
	    setInputHandlers(form.getElementsByTagName('input'));
	    setInputHandlers(form.getElementsByTagName('select'));
	    setInputHandlers(form.getElementsByTagName('textarea'));
		
		//Make sure that submit buttons don't trigger the confirmation for leaving the page:
		var s = form.getElementsByTagName('input');
		for(var j = 0; j < s.length; j++) {
			if(s[j].type == 'submit')
				s[j].onclick = function() { isFormChanged = false; };
		}
	}
}

if(document.getElementById && document.createTextNode) {
	addEventWC(window, 'load', initWC);
	
	//Make both FF and IE warn the window has changed before navigating away (or refreshing, etc.)
	window.onbeforeunload = function(oEvent) { 
		if(!oEvent)
			oEvent = window.event;
		if(isFormChanged) 
			oEvent.returnValue = 'If you continue, you will lose all changes on this page.'; 
	};
}


