/*
 * ess-modal.js
 * ---
 * EZEL 04/2010
 * locking inputs on submit/postback
 * ---
 * requires:
 *   jquery.js
 * ---
 */

/*jslint browser: true */
/*global $: false, ESSENCE: true, window: false */
/**/

if (typeof ESSENCE === 'undefined') { 
	ESSENCE = {}; 
}
ESSENCE.ModalSubmit = (function () {
    'use strict';
    var CONST, MAIN;

	// constants
	CONST = { 
		wndName: 'attachment',
		cssModal: {
			position: 'absolute',
			zIndex: 100,
			left: 0,
			top: 0,
			backgroundColor: 'black',
			cursor: 'wait'
		}
	};

	// main object
	MAIN = { 
		allforms: [], 
		opacity: 0, 
		enabled: false, 
		originalPostBack: null 
	};

	function myShowBusy() {
		if (!MAIN.panelModal) {
			MAIN.panelModal = $('<div></div>').css(CONST.cssModal);
			$('body').append(MAIN.panelModal);
		}
		MAIN.panelModal.css({
			opacity: MAIN.opacity,
			width: $(document).width(),
			height: $(document).height()
		});
	}
	
	function myDisableInputs(parent, enable) {
		if (typeof enable !== 'boolean') {
			enable = false;
		}
		if (!parent) {
			parent = document;
		}
		$(parent).find("*:input").attr('disabled', enable ? null : 'disabled');
	}
	
	function myModalGo(parent) {
		if (MAIN.enabled) {
			setTimeout(function () {
				myDisableInputs(parent);
			}, 100);
			myShowBusy();
		}
		return true;
	}
	
	function myFormSubmit(form, evnt) {
		if (!evnt.originalEvent.cancelBubble) {
			return myModalGo(form);
		} else {
			return true;
		}
	}
	
	function myDisable() {
		if (MAIN.enabled) {
			MAIN.enabled = false;
		}
	}
	
	function myEnable() {
		if (!MAIN.enabled) {
			MAIN.enabled = true;
		}
	}

	function myInit() {
		$('form').each(function () {
			var form = this;
			MAIN.allforms.push(form);
			$(this).submit(function (evnt) { 
				return myFormSubmit(form, evnt);
			});
		});
		myEnable();
	}
	
	$(myInit); 
	
	MAIN.init = myInit;
	MAIN.enable = myEnable;
	MAIN.disable = myDisable;
	MAIN.go = function (parent) {
		if (typeof parent === 'undefined' || !parent) {
			parent = MAIN.allforms;
		}
		myModalGo(parent);
	};
	
	MAIN.disableInputs = myDisableInputs;

	return MAIN;
}());
/**/

