/***
*
*  Menu: Packages HashHandler, and MenuHandler and sets up PAGE IN/OUT functions 
*  
***/
var Menu = new Class({
        //
		//  
		//
		Implements: [Options,Events],
		options: {
				menulinks:'#menu a',
				parent_id:'main_border',
				content_id:'main_content',
				error_htmlstr:"<div id='load_error'>LOAD ERROR(1)</div>",
				error_hash:"error",
				checkReady: true,
				fadeIn:true
		},
		initialize: function(bind,options){
				this.setOptions(options);
		},
		enableHandler: function(handler,out_func,in_func){
				this.handler = handler
				this.in_func = in_func
				this.handler.addEvent('PAGE_REQUEST',function(){
						this.isOut = false
						this.isLoading = true
						out_func()	
				}.bind(this))
				this.handler.addEvent('PAGE_LOADED',function(){
						this.isLoading = false
						if (this.isOut || !this.options.checkReady) {
								this.replace()
								in_func()
						}		
				}.bind(this))
				this.handler.addEvent('ERROR',function(){
						this.isLoading = false
						if (this.isOut || !this.options.checkReady) {
								this.replace()
								if (this.isOut) in_func()
						}		
				}.bind(this))
		},
		pageReady: function(){
				this.isOut = true
				if (!this.isLoading) {
						this.replace()
						this.in_func()
				}		
		},
		enableHistory: function(history){
				this.history = history
				this.history.addEvent('HASH_CHANGED',function(){
						var elm = this.handler.getButton(this.history.hash)
						if (!elm) elm = new Element("a",{href:this.history.hash})
						this.handler.clicked(elm)
				}.bind(this))
				this.handler.addEvent('PAGE_LOADED',function(){
						this.history.update(this.handler.currentName)
				}.bind(this))
				this.handler.addEvent('ERROR',function(){
						this.history.update(this.options.error_hash)
				}.bind(this))
		},
		//
		//  INTERNAL [HANDLER]
		//
		replace: function(){
				document.id(this.options.content_id).destroy()
				var new_content = this.handler.page.getElement("[id='"+this.options.content_id+"']")
				if (!new_content) new_content = new Element('div',{id:this.options.content_id}).set('html',this.options.error_htmlstr+"[replace]")
				new_content.setStyle("opacity",0)
				document.id(this.options.parent_id).grab(new_content)
		},
		load: function(menulinks){
				this.handler.addEvent('MENU_READY',this.ready.bind(this))
				this.handler.addMenu(menulinks ? menulinks : this.options.menulinks)
		},
		ready: function(){
				this.handler.removeEvent('MENU_READY',this.ready.bind(this))
				if (this.options.fadeIn) document.id(document.body).fade(1)
		}
});
