/*
 * Requires SVUI Object
 */

/*
 * SVUI.PopMenu
 */

SVUI.PopMenu = Class.create(SVUI.Base, {
	
	
	initialize: function(obj) {
		
	},
	
	Element: Class.create(SVUI.Element, {
		dboxLoader: null,
		positioned: false,
		timer: null,
		active:false,
		over: false,
		id: 0,
		
		initialize: function($super, element) {
			$super(element);
			this.positioned = false;
			this.element.hide();
			
			var parent = $(this.element.parentNode);
			
			if (parent) {
				parent.style.cursor = "pointer";
				
				parent.observe('click', this.eleClick.bind(this));
				
				parent.observe('mousemove', this.eleMouseMove.bind(this));
			
				parent.observe('mouseout', this.eleMouseOut.bind(this));
			}
		},
		
		eleClick: function(event) {
			if(this.active) {
				return;	
			};
				
			if(!this.dboxLoader) {
				this.dboxLoader = new SVUI.DialogBoxLoader;
				this.dboxLoader.load(this.element, {classSelector: ['.popmenu-dbox_loader'], autoLoad: true});
			}
			
			this.active = true;
			this.over = true;
			
			if(!this.positioned) {
				var parent = $(this.element.parentNode);
				var posi = parent.positionedOffset();
				
				var vPortPosition = document.viewport.getScrollOffsets();
				var vPortDimensions = document.viewport.getDimensions();
				var eleDimensions = this.element.getDimensions();
				var elePosition = this.element.cumulativeOffset();
				
				var parentDimensions = parent.getDimensions();
				var parentPosition = parent.cumulativeOffset();
				
				var docPosBottom = vPortPosition.top + vPortDimensions.height;
				var elePosBottom = parentPosition.top + eleDimensions.height;
				
				if(elePosBottom > docPosBottom) {
					this.element.style.top = (docPosBottom - eleDimensions.height - 20) + 'px';
				} else {
					this.element.style.top = posi.top+17+'px';
				}
				this.element.style.left = posi.left+5+'px';
				this.positioned = true;
			}
			
			this.element.style.zIndex = 50;
			this.element.style.display = 'block';
			this.element.absolutize();
			
			//this.element.show();
			new Effect.Fade(this.element, {to: .9, from: 1});
			
			this.timer = new PeriodicalExecuter(function(pe) {
				pe.stop();
				if(this.active && !this.over) {
					//this.element.hide();
					new Effect.Fade(this.element, {to: 0, duration: .2});
					this.active = false;
				}
			}.bind(this), 4.5);
		},
		
		eleMouseMove: function(event) {
			this.over = true;
			if(this.active) {
				this.timer.stop();
			}
		},
		
		eleMouseOut: function(event) {
			this.over = false;
			if(this.active) {
				this.timer = new PeriodicalExecuter(function(pe) {
					pe.stop();
					if(this.active && !this.over) {
						//this.element.hide();
						new Effect.Fade(this.element, {to: 0, duration: .2});
						this.active = false;
					}
				}.bind(this), .7);
			}
		}
		
	}),
	
	options: {
		autoLoad: true,
		classSelector: ['div.popmenu']
	}
});