/***
*
*  Menu Handler Class:  
*  - a simple class that simply blocks the default of <a> (for local pages), then loads the linked page - returned as 'page'.
*  - the function addLinks may be called repeatedly.  so only one instance of the class in necesary.
*  - if a 'group' is given in load pages, the listeners can later be removed with the pullEvents() function from the EventManager Class
*  - if options.hasHashListener - requries HashListener
*  
***/
var MenuHandler = new Class({
        //
		//  initialize
		//
		Implements: [Options,Events,EventManager],
                options: {
						errorClass: 'load_error',
						masterGroup: 'master',
						initial_index: 0,
						pageOpenTag:null,
						pageCloseTag:null,
						isReady: true,
						active: '#0ac',
						visited: '#666',
						hover: '#069',
						hasHashListener:true,
						historyEnabled:true,
						fileType:"html",
						altFolder:"content"
						//
						//
						//
						//
						//
                },
                initialize: function(lnks,options){
								//document.id(document.body).fade("hide")
								//this.ishidden = true
                                this.setOptions(options);
                                this.isReady = this.options.isReady
                                if ($chk(lnks)) {
                                        this.pages = $$(lnks)
                                        this.pages.each(function(elm){
                                                elm.color = elm.getStyle('color')
                                                elm.visited = false
                                        })
                                        this.addLinks(this.pages,this.options.masterGroup);
										if (this.options.initial_index >= 0) this.setCurrent(this.options.initial_index,this.options.masterGroup)
                                        this.page = document.body
								}
								if (this.options.hasHashListener){
										this.setHashListener()
								}
                },		
                //
                //  public
                //
                addLinks: function(lnks,grp){
                        $$(lnks).each(function(elm,index){
                                this.addlink(elm,index,grp)
                        }.bind(this))
                },	
                setCurrent: function(index,grp){
                        this.currentElement = this.pages[index]
                        if (this.options.active && this.options.active != "none") this.currentElement.setStyle('color',this.options.active)
                        this.currentIndex = index
                        this.currentRef = this.currentElement.get('href')
                        this.currentGroup = grp
                },
		//
		//
		//
		//
		//
		//
		//  internal
		//
		addlink: function(elm,index,grp){
				this.pushEvents(elm,'click',function(e){
						if (!elm.get('href').contains('http://') || grp == "tlLinks"){  //grp= ... cheap fix for IE timeline on jll
								if (e.stop) e.stop()
								e.href = elm.get('href') 
								if (!this.isLoading) this.clicked(e,elm,index,grp)
						}
						elm.blur()
				}.bind(this),grp)
				this.pushEvents(elm,'mouseover',function(){
						if (this.options.hover && this.options.hover != "none") elm.setStyle('color',this.options.hover)
						this.overElement = elm
						this.overIndex = index
						this.overRef = elm.get('href')
						this.overGroup = grp
						this.fireEvent('OVER')		
				}.bind(this),grp)
				this.pushEvents(elm,'mouseout',function(e){
						if (this.options.hover && this.options.hover != "none") {
								if (elm == this.currentElement && this.options.active && this.options.active != "none") elm.setStyle('color',this.options.active)
								else elm.setStyle('color',elm.color)
						}
						this.overElement = null
						this.overIndex = null
						this.overRef = null
						this.overGroup = null
						this.outElement = elm
						this.outIndex = index
						this.outRef = elm.get('href')
						this.outGroup = grp
						this.fireEvent('OUT')
				}.bind(this),grp)
		},
		clicked: function(e,elm,index,grp){
						if (e.href != this.currentRef && this.isReady) {
						if (this.currentElement){
								var clr = this.currentElement.clicked && this.options.visited && this.options.visited != "none" ? this.options.visited : this.currentElement.color
								this.currentElement.setStyle('color',clr)
								this.currentElement.justClicked = false
						}		
						elm.clicked = true
						this.requestElement = elm
						this.requestIndex = index
						this.requestRef = elm.get('href')
						this.requestGroup = grp
						this.fireEvent("PAGE_REQUEST")
						this.isLoading = true
						var uri = new URI(this.requestRef)
						var gdata = (uri.get("query")=="") ? "none" : uri.getData(); // this is an explorer fix posting rather than urlvar ... i wonder if it would be enought to just put the slash in html/?... rather that html?...
						var pth = this.options.altFolder ? this.options.altFolder + "/" : ""
						var req = new Request({
								url: pth + uri.get("file"),
								method:"post",
								data:gdata,
								onSuccess: function(htmlstring) {
										this.page = new Element('div',{id:'ajaxholder'})
										if (this.options.pageOpenTag && this.options.pageCloseTag){
												var startindex = htmlstring.search(this.options.pageOpenTag) + this.options.pageOpenTag.length                      
												var endindex = htmlstring.search(this.options.pageCloseTag)
												this.page.set('html',htmlstring.substring(startindex,endindex))
										} else {
												this.page.set('html',htmlstring)
										}
										this.currentRef = this.requestRef
										this.setCurrentElement(elm)
										this.currentIndex = index
										this.currentID = elm.get("id")
										this.currentGroup = grp
										this.error = null
										this.isLoading = false
										if 	(this.hashListener)	{
												this.isPageRequest = true
												var uri = new URI(this.currentRef)
												var pg = uri.get('file').split(".")[0]
												if (uri.get('query')!="") var uvars = "?"+uri.get('query')
												else var uvars = ""
												this.hashListener.updateHash(pg+uvars)
												this.isPageRequest = false
										};
										this.fireEvent('PAGE_LOADED')
								}.bind(this),
								onFailure: function(err) {
										var newpage = new Element('div',{'class': this.options.errorClass})
										this.error =  newpage.set('html','LOAD_ERROR:&nbsp;&nbsp;:'+this.requestRef)
										this.currentRef = this.requestRef
										this.setCurrentElement(elm)
										this.currentIndex = index
										this.currentID = elm.get("id")
										this.currentGroup = grp
										this.isLoading = false
										this.isPageRequest = false
										this.fireEvent('ERROR')
								}.bind(this)
						})	
						req.send()
				}
		},
		setCurrentElement: function(){
				if ($chk(this.pages)){
						this.pages.each(function(elm){
										if (this.currentRef == elm.get('href')) this.currentElement = elm;
						}.bind(this))
						if (this.currentElement){
								this.linkColor = this.currentElement.getStyle('color')
								this.currentElement.setStyle('color',this.options.active)                                
								this.currentElement.setStyle('color:hover','#f00')
						}
				} 
		},
		//
		//  Uses HashListener from forge
		//  authors:
		//		- Arieh Glazer
		//		- Dave De Vos
		//		- Digitarald
		//
		setHashListener: function(){
				this.hashListener= new HashListener();
				this.hashListener.addEvent('hashChanged',function(new_hash){
						this.hash = new_hash
						if (!this.isPageRequest){
								this.fireEvent("HASH_EVENT")
								var uri = new URI()
								if (uri.get('query')!="") var uvars = "?"+uri.get('query')
								else var uvars = ""
								if (this.options.historyEnabled){
										var e = new Object()
										//
										if (this.hash == "" || this.hash == "index" || !this.hash){
												var fname = "index"
												var uv_str = ""
										} else {
												var arr = this.hash.split("?")
												var fname = arr[0]
												if (arr.length == 2) var uv_str = "?" + arr[1]
												else var uv_str = "";
										}		
										//
										var elm = new Element("a",{href:fname+ "." + this.options.fileType+uv_str})
										e.href = elm.get("href")
										this.clicked(e,elm)
										if (this.ishidden) {
												document.body.fade(1)
												this.ishidden = false
										}
								}
						} 
						this.isPageRequest = false
				}.bind(this));
				//
				//
				//				
				var uri = new URI()
				if (uri.get('fragment')==""){
						if (uri.get("file")) var newhash = uri.get("file").split(".")[0]
						else var newhash = "index"
						this.hashListener.updateHash(newhash)
						this.redirect = false
				} else {
						var arr = uri.get("fragment").split("?")
						var fname = arr[0]
						if (arr.length == 2) var uv_str = "?" + arr[1]
						else var uv_str = "";
						//
						var elm = new Element("a",{href:fname+ "." + this.options.fileType+uv_str})
						var e = new Object()
						e.href = elm.get("href")
						this.redirect = true
						this.clicked(e,elm)
						//if (this.ishidden) {
						//		document.id(document.body).fade(1)
						//		this.ishidden = false
						//}
				}
				this.fireEvent("Ready")
		}
});
