dojo.provide("UI.Dialog.Modal");


(function() {
	var DEFAULT_MODAL_NODE_SELECTOR = "#dialog-system-modal",
		ANIMATION_DURATION_IN       = 150,
		ANIMATION_DURATION_OUT      = 150;
	var initScreen;
	
	dojo.declare("UI.Dialog._Modal", UI.Base, {
		constructor: function(screen) {
			this.screen = screen || dojo.query(DEFAULT_MODAL_NODE_SELECTOR)[0];
			this.ready  = false;
			this.aniShow = null;
			this.aniHide = null;
			this.isShown = false;
			
			// Make sure the screen is available in the dom
			initScreen = dojo.hitch(this, function() {
				if ( !this.screen ) {
					this.screen = dojo.query(DEFAULT_MODAL_NODE_SELECTOR)[0];
				}
				
				if ( !this.ready ) {
					this.aniShow = dojo.fadeIn({node: this.screen, duration: ANIMATION_DURATION_IN});
					this.aniHide = dojo.fadeOut({node: this.screen, duration: ANIMATION_DURATION_OUT});
					
					dojo.connect(this.aniShow, "onBegin", this, function() {
						this.screen.style.display = "block";
						this.isShown = true;
					});
					dojo.connect(this.aniHide, "onBegin", this, function() { this.isShown = false; });
					dojo.connect(this.aniHide, "onEnd", this, function() {
						this.screen.style.display = "none";
					});
					
					// Initialize to hidden
					dojo.fadeOut({node: this.screen, duration: 1}).play();
					
					this.ready = true;
				}
				
			});
			
			if ( !this.screen ) {
				dojo.addOnLoad(initScreen);
			} else {
				initScreen();
			}
			
			return this;
		},
		
		open: function() {
			if ( !this.isUnset() && !this.isShown ) {
				this.aniHide.stop();
				this.aniShow.play();
			}
			return this;
		},
		
		close: function() {
			if ( !this.isUnset() ) {
				this.aniShow.stop();
				this.aniHide.play();
			}
			return this;
		},
		
		isOpen: function() {
			initScreen();
			return this.isShown;
		},
		
		isClosed: function() {
			return !this.isOpen();
		},
		
		isUnset: function() {
			initScreen();
			return this.screen === null;
		},
		
		setZIndex: function(zIndex) {
			initScreen();
			this.screen.style.zIndex = zIndex;
		}
	});
	
	UI.Dialog.Modal = new UI.Dialog._Modal();
})();
