function RemoteFormInstance(form) {

	for (var idx in RemoteForm)
		this[idx] = RemoteForm[idx];
		
	this.__construct(form);
		
	return this;

}

var RemoteForm = {

	form : null,
	instance : null,

	/**
	 *	Initialize the data-members
	 */
	__construct : function(form) {
	
		this.form = form;
		this.hookEvents();
	},
	
	/**
	 * 	Hook events to submit button
	 */
	hookEvents : function() {
		var thiz = this;

		$(this.form).one("submit", function(evt) {
			
			$(this).trigger("before-submit");
			RemoteForm.instance = thiz;

			var url = thiz.form.attr("action");
			var ajaxUrl = '';
			
			// cut off 
			if (url) {
				if (url.indexOf("?") > -1) {
					url = url.substring(0, url.indexOf("?"));
				}
				ajaxUrl = thiz.recode(url);
			}
				
			$.get(ajaxUrl, thiz.form.serialize(), thiz.ajaxCallback); 
			
			evt.preventDefault();
		}); 
	},

		 
	/**
	 *	This function is called upon form callback
	 */
	ajaxCallback : function(data) {
		var wrapper = RemoteForm.instance.form.parent(".formWrapper");
		RemoteForm.instance.form.remove();
		$(wrapper).replaceWith($(data).html());
		
		wrapper = $(".formWrapper");
		
		RemoteForm.instance.form = $("form", wrapper);
		RemoteForm.instance.hookEvents();
		
		// set the focus on the fist visible input text field.
		$("p.error :input:text:visible:first").focus();
	},
	
		
	/**
	 *	This method adjusts all URLs to contain a proper ajax parameter
	 *  so the server will return a different view
	 */
	recode : function(url) {
		var base, params;

		if (url.indexOf("?") != -1) {
			base = url.substring(0, url.indexOf("?"));
			params = url.substring(url.indexOf("?"));
			
			return base + params + "&view=ajax";
		}
		else {
			return url + "?view=ajax";
		}
	}		

};

