var pathname = document.location.pathname;
var filename = pathname.substring(pathname.lastIndexOf("\/")+1, pathname.lastIndexOf(".php"));

function get_cookie( cname )
{
	var results = document.cookie.match( '(^|;) ?' + cname + '=([^;]*)(;|$)' );
	if (results)
		return results[2];
	else
		return null;
}

// ElementsByTagName is a collection, not an array, and IE will not allow you to parse it
// correctly if more than one element shares the same name.
function inputs_to_array()
{
	var inputs = document.getElementsByTagName("input");
	var a = new Array();
	var n=0;

	for (var i=0; i<inputs.length; i++) {
		if (inputs[i]['type'] == 'text' || inputs[i]['type'] == 'radio') {
			a[n++] = inputs[i];
		}
	}
	//alert("a " + a.length);
	return a;
}

function cookie_unloader()
{
	var cookie="";
	var inputs = inputs_to_array();

	for (var i=0; i<inputs.length; i++) {
		if (i>1)
			cookie += ",";
		if (i) {
			if (inputs[i]['type'] == 'radio') {
				if (inputs[i].checked == true)
					cookie += "1";
				else
					cookie += "0";
			}
			else
				cookie += escape(inputs[i]['value']);
		}
	}
	document.cookie=filename + '=' + cookie + ';';
	//alert(filename);
	//alert(cookie);
	//alert("unload "+i);

	if (window.detachEvent) { // IE memory leaks
		window.detachEvent("onunload", cookie_unloader);
		window.detachEvent("onload", cookie_loader);
	}
}

function cookie_loader()
{
	var v=get_cookie(filename);

	if (v==null) return;

	var a=v.split(",");
	var inputs = inputs_to_array();

	for (var i=0; i<inputs.length; i++) {
		if (inputs[i]['type'] == "text") {
			if (i) { // skip the "search" box
				if (a[i-1]) inputs[i]['value'] = unescape(a[i-1]);
				//alert(unescape(a[i-1]));
			}
		}
		else if (inputs[i]['type'] == "radio") {
			if (a[i-1] == "1")
				inputs[i].checked = true;
			else
				inputs[i].checked = false;
		}
	}
	//alert("load " + i);
}

if (window.addEventListener) {
	window.addEventListener("unload", cookie_unloader, false);
	window.addEventListener("load", cookie_loader, false);
}
else if (window.attachEvent) {
	window.attachEvent("onunload", cookie_unloader);
	window.attachEvent("onload", cookie_loader);
}
