Langoor.formHandler = new function () {
	
	this.handleForms = function (id) {
		if (typeof id == 'undefined') {
			var forms = $('form');
		} else {
			var forms = $('#' + id + ' form');
		}
		var formEle, index;
		for (index=0; index < forms.length; index++) {
			formEle = forms[index];
			var widgetId = $(formEle).parents('.widget').parent().attr('id');
			var widgetInfo = widgets_on_page[widgetId];
			$(formEle).validate({
				submitHandler: function() {
					$(formEle).mask("Submitting...");
					var postObj = {
						'c': 'widget',
						'm': 'userdefined'
					};
					postObj['master_widget_id'] = widgetInfo.master_widget_id;
					postObj['widget_instance_id'] = widgetInfo.widget_instance_id;
					postObj['um'] = $(formEle).attr('action');
					postObj['params'] =  $.toJSON($(formEle).serializeArray());
					Langoor.ajax.ajaxPost(Langoor.ajaxPath, postObj, false, null, function (data) {
						var response = jQuery.parseJSON(data);
						if (response.success == 1 && response.data == true) {
							Langoor.formHandler.handleResponse(response.wdata);	
						}
					});
				}	
			});	
		}
	}
	
	this.handleResponse = function (widget) {
		var html = constructWidgets([widget]);
		$('#' + widget.id + '-wrapper').replaceWith(html);
		this.handleForms(widget.id);
	}
	
	var constructWidgets = function (widgets) {
	   var html = [];
	   for (var index = 0; index < widgets.length; index++) {
		   var widget = widgets[index];
		   html.push('<div id="' + widget.id + '-wrapper">');
		   html.push('<div id="' + widget.id + '" class="widget ' + widget.name + '" type="' + widget.name + '">');
		   html.push(widget.html);
		   html.push('</div>');
		   html.push('</div>');
	   }
	   return html.join('');
	};
};

