/*
* FormController
* -----------------------
* @author        : Filatov Dmitry <alpha@design.ru>
* @last_modified : 13.04.2007
*/

function FormController(
	oForm,
	oParams
	) {

	FormController.baseConstructor.call(this);

	this.oForm = oForm;
	this.oParams = oParams;

	this.init();

}

FormController.CLASS_NAME_ERROR = 'error';

FormController.TAG_URL = 'url';

FormController.inheritFrom(
	Observable,
	{

		init : function() {

			var oThis = this;

			Common.Event.add(
				this.oForm.oElement,
				FormWidget.EVENT_TYPE_SUBMIT,
				function(oEvent) {

					Common.Event.cancel(Common.Event.normalize(oEvent));
					oThis.processSubmit();

				}
			);

		},

		processSubmit : function() {

			this.doRequest();

		},

		getWidgetById : function(sId) {

			return this.oForm.getWidgetById(sId);

		},

		doRequest : function() {

			this.sendRequest(this.getRequestData());

		},

		sendRequest : function(aData) {

			var
				oThis = this,
				oAjaxHelper = new AjaxHelper(
					this.oParams.sTargetUrl,
					function(oResponse) {

						oThis.onSuccess(oResponse);

					},
					function() {

						oThis.onError();

					},
					aData
					)
				;

			oAjaxHelper.send();

		},

		isWidgetReadyForSubmit : function(oWidget) {

			return oWidget.hasValue() &&
				oWidget.oParent &&
				!oWidget.oParent.hasValue() &&
				!oWidget.isTemplate() &&
				oWidget.isEnabled() &&
				!oWidget.getValue().isEmpty()
				;

		},

		getRequestData : function() {

			var
				aResult = [],
				aWidgets = this.oForm.getWidgets()
				;

			for(var sId in aWidgets) {

				if(!aWidgets.hasOwnProperty(sId) ||
					!this.isWidgetReadyForSubmit(aWidgets[sId])
					) {
					continue;
				}

				aResult[aWidgets[sId].getName()] = aWidgets[sId].getValue().toString();

			}

			return aResult;

		},

		onSuccess : function(oResponse) {


		},

		onError : function() {


		}

	}
);
