﻿/// <reference path="jquery-1.3.2.js"/>

OWL.form = OWL.form || {};


(function() {

	var that = OWL.form;
	var thatObj = {

		onFormSubmit: function(form, e, dataType, waitID, targetID, onBegin, onSuccess, onError) {

			if (!$.browser.msie) {
				e.stopPropagation();
			}
			var isValid = true;

			if (onBegin !== null && typeof onBegin !== 'undefined') {
				isValid = onBegin(form, e);
			}

			if (isValid) {
				// create the form body
				var formBody = $(form).serialize();
				that.doPost(form, form.method, form.action, dataType, formBody, waitID, targetID, onSuccess, onError);
			}
			return false;
		},
		postForm: function(sender, e, formID, dataType, waitID, targetID, onBegin, onSuccess, onError) {

		if (!$.browser.msie) {
			e.stopPropagation();
		}

			var form = document.getElementById(formID);
			if (form) {
				var isValid = true;

				if (onBegin !== null && typeof onBegin !== 'undefined') {
					isValid = onBegin(sender, e);
				}

				if (isValid) {
					// create the form body
					var formBody = $("#" + formID).serialize();
					that.doPost(sender, form.method, form.action, dataType, formBody, waitID, targetID, onSuccess, onError);
					return true;
				}
			}
			return false;
		},
		doPost: function(sender, actionType, url, dataType, formBody, waitID, targetID, onSuccess, onError) {

			that.toggleVisibility(waitID, true);

			$.ajax({
				type: actionType,
				dataType: dataType,
				url: url,
				data: formBody,
				success: function(result) {
					that.toggleVisibility(waitID, false);

					if (onSuccess !== null && typeof onSuccess !== 'undefined')
						onSuccess(sender, targetID, result);
				},
				error: function(xhr, textStatus, errorThrown) {
					that.toggleVisibility(waitID, false);

					if (onError !== null && typeof onError !== 'undefined')
						onError(sender, xhr, textStatus, errorThrown);
				}
			});
		},
		toggleVisibility: function(id, show) {
			if (id) {
				if (show) {
					$("#" + id).show();
				} else {
					$("#" + id).hide();
				}
			}
		}
	};

	OWL.lang.augmentObject(that, thatObj, true);
})();
