// Dropdown Menu
var Dropdown = Class.create({

	initialize: function(config) {
		
		// class properties
	
		this.container = $(config.container);
		this.sub_container = $$('#'+config.container+' .dropdown-sub-container')[0];
		this.parent_item = $$('#'+config.container+' .dropdown-parent-item')[0];
		this.parent_menu = config.parent_menu;
		this.touch_screen = config.touch_screen;

		if(this.parent_menu) {
		//	alert(Element.Offset(this.container));
		
		}
		
		this.menu_open = false;
		this.menu_clicked = false;
		this.menu_timeout;
		
		if(config.children) {
			
			this.children = $H(config.children);
			child_hash = $H();

			this.children.each(function(child) {
			
				key = child[0];
				config = child[1];
				config.parent_menu = this;
				
				sub_menu = new Dropdown(config);
				
				child_hash.set(key,sub_menu);
				
	
			}.bind(this));
			
			this.children = child_hash.toObject();
			this.children_hash = child_hash;

		}

		// observes
		if(this.touch_screen) {
		
			this.container.observe('click',this.showMenu.bind(this));
		
		}
		else {
		
			this.container.observe('mouseenter',this.showMenu.bind(this));
			this.container.observe('mouseleave',this.hideMenu.bind(this));
		
		}

	},

	showMenu: function() {

		clearTimeout(this.menu_timeout);

		if(!this.menu_open){

			this.menu_timeout = setTimeout(function(){

				this.menu_open = true;
		        Effect.SlideDown(this.sub_container, { duration: 0.2});
		        
		        if(this.touch_screen) {
				
					this.container.setStyle({border:'1px solid #666'});
					
				}

			}.bind(this),200);
               
		}
		else if(this.touch_screen) {

			this.hideMenu();
		
		}

	},

	hideMenu: function() {

		clearTimeout(this.menu_timeout);

        if(this.menu_open){

			this.menu_timeout = setTimeout(function(){

				this.menu_open = false;
				Effect.SlideUp(this.sub_container, { duration: 0.2});
				
				if(this.touch_screen) {
				
					this.container.setStyle({border:'none'});
					
				}

			}.bind(this),200);
               
		 }

	},

	stayOpen:function () {

		if(this.menu_open && !this.menu_clicked) {

			this.menu_clicked = true;
			this.container.stopObserving('mouseleave');
			
			if(this.parent_menu) {
				this.parent_menu.menu_click = true;
				this.parent_menu.container.stopObserving('mouseleave');		
			}

		} else if(this.menu_clicked) {
	
			this.menu_clicked = false;
			this.container.observe('mouseleave',this.hideMenu.bind(this));
			
			if(this.parent_menu) {
				this.parent_menu.menu_click = false;
				this.parent_menu.container.observe('mouseleave',this.parent_menu.hideMenu.bind(this));
			}
			
		}
		
	}

});


