/*	
	Updated @ 2008-09-05
	License: GNU General Public License v3
	Developer: Ehsun Behravesh
	email: ehsun7b@gmail.com
	Tested on Firefox 3.0.3, Opera 9.52, Safari 3.1.2, Internet Explorer 7
*/

var AjaxForm = Class.create({
	initialize: function(id, url, loader, board) {
		try {
			this.id 	= id;
			this.url 	= url;
	    	this.loader	= loader;
			this.board	= board;
			
			//	---------------------------------
			
			this.form = $(this.id);
				
			this.form.onsubmit = this.submit.bind(this);	
			this.form.onreset = this.reset.bind(this);
			
			//	---------------------------------
			
			if (this.loader.src == null) {			
				var path = this.loader;
				this.loader = new Image();
				this.loader.src = path;
			}
			
			//	---------------------------------
			
			if (this.board.id == null) {
				this.board = $(this.board);
			}
			
			//	---------------------------------
			
			this.loader.style.visibility = "hidden";
			this.board.appendChild(this.loader);
			
			//	---------------------------------
			
			var inputs = this.form.getElementsByTagName("input");
			for (i = 0; i < inputs.length; i++) {
				if (inputs[i].type == "submit")
					inputs[i].style.visibility = "visible";
			}
			
		} catch (e) {
			alert("error:" + e.name + " - "+ e.message);
		}
		
	},

	submit: function() {
		try {
			this.board.innerHTML = "";
			this.board.appendChild(this.loader);			
			this.loader.style.visibility = "visible";
			
			var params = this.form.serialize(true);
			this.form.disable();
			
			if (!this.url.include("?"))
				this.url += "?form=" + this.id + "&board=" + this.board.id;
			
			new Ajax.Request(this.url, {
				method: 'post',
				
				parameters: params,
				
				onSuccess: function(transport) {
					//alert(transport.responseText);
					transport.responseText.evalScripts();
				},
				
				onComplete: this.complete.bind(this),
				
				onException: this.exception.bind(this),
				
				onFailure: this.failure.bind(this)
			});		
			
			return false;
		} catch (e) {
			alert("error:" + e.name + " - " + e.message);
		}
	},
	
	//	----------------------------------------
	
	reset: function() {
		this.showMessage("", "#000000");
	},
	
	//	----------------------------------------
	
	complete: function() {
   		this.form.enable();
   		this.loader.style.visibility = "hidden";
	},
	
	exception: function() {	
		this.showMessage("Exception in AjaxForm!", 'red');
	},
	
	failure: function() {
		this.showMessage("AjaxForm failed!", 'red');
	},
	
	//	----------------------------------------
	
	hideForm: function() {
		this.form.style.display = "none";
	},

	showMessage: function(msg, color) {
		this.board.style.color = color;
		this.board.innerHTML = msg;
	},
	
	focusForm: function() {
		try {			
			setTimeout("$('" + this.id + "').focusFirstElement()", 1);
		} catch (e) {
			this.showMessage(e.message, 'red');
		}
	},
	
	resetForm: function() {
		this.form.reset();
	}
});

