$.fn.clearInputs = function()
{
	return this.each(function()
	{
		var t = this.type, tag = this.tagName.toLowerCase();

		if (t == 'text' || t == 'password' || tag == 'textarea') this.value = '';
		else if (t == 'checkbox' || t == 'radio') this.checked = false;
		else if (tag == 'select') this.selectedIndex = -1;
	});
}

$.fn.clearForm = function()
{
	return this.each(function() {
		$('input,select,textarea', this).clearInputs();
	});
}

$.fn.ajaxSubmit = function(e)
{
	/* Change a form's submission type to ajax */
	this.submit(function()
	{
		var this_form = this;
		var params = {};

		$(this)
		.find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea")
		.filter(":enabled")
		.each(function() {
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
		});

		$("#note").fadeOut("slow");

		$.post(this.getAttribute("action") + "?call=ajax", params, function(xml)
		{
			var status = 0;
			var response = '';

			$("AjaxResponse", xml).each(function() {
				status = this.getAttribute("status");
				response = this.getAttribute("response");
			});

			if (response.length == 0)
			{
				$("#note").remove();
				$("#secure").append('<p id="note">Warning: Form submit failed.</p>').fadeIn("slow");
			}
			else
			{
				if (status == 2)
				{
					var hiddens = {};

					$(this_form).find("input[@type='hidden']").filter(":enabled").each(function(){
						hiddens[this.name] = this;
					});

					if (typeof(hiddens['real_page'])!='undefined' && typeof(hiddens['page'])!='undefined') {
						hiddens['page'].value = hiddens['real_page'].value;
					}

					this_form.action = this_form.getAttribute('_real_action');
					this_form.target = '_parent';
					this_form.submit();

					return false;
				}

				$("#note").remove();
				$("#secure").append('<p id="note">Response: ' + response + '</p>').fadeIn("slow");

				if (status == 1) {
					$("#secure").clearForm();
				}
			}
		});

		return false;
	});

	return this;
}

$(document).ready(function()
{
	$('#warning').remove();

	$.get("token.php",function(txt)
	{
		$("#secure").append('<input type="hidden" name="ts" value="'+txt+'" />');
		$("#secure").ajaxSubmit();
	});
});
