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");
			// cut off 
			if (url.indexOf("?") > -1)		
				url = url.substring(0, url.indexOf("?"));

			var ajaxUrl = thiz.recode(url);
			$.get(ajaxUrl, thiz.form.serialize(), thiz.ajaxCallback);
	
			evt.preventDefault();
		}); 
	},
	
	/**
	 *	This function removes duplicate url elements

	removeDuplicate : function(rawUrl) {
	
		url = rawUrl.substring(rawUrl.indexOf("?") + 1);
		keyArr = url.split("&");
		
		for (var idx = 0; idx < keyArr.length; ++idx) {
			var eqIdx = keyArr[idx].indexOf("=");
			console.log("key: " + keyArr[idx].substring(0, eqIdx));
		}
	
		return rawUrl;
	},
		 */
		 
	/**
	 *	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";
		}
	}		

};

