// Note, any changes made to this will need to be modified at the end of ../../comb.js

var HoverIntent = new Class({

	Implements: [Options, Events],

	options: {
		delay:200,
		tag:'ul',
		onRemove:function(){
			this.clone.destroy();
			this.links[this.current].removeClass('hover');
			this.current = false;
		}
	},

	initialize: function(links,location,options){
		this.links = $$(links);
		this.location = $(location);
		this.setOptions(options);
		
		this.current = false;
		this.mouseover = false;
		this.mouseover_link = false;
		
		this.hover_function = function(i){
			this.current = i;
			el = this.links[i];
			el.getParent().getChildren().removeClass('hover');
			el.addClass('hover');
			if(ul = el.getNext('ul')){
				this.location.set('html','');
				this.clone = ul.clone();
				this.clone.injectInside(this.location);
				this.fireEvent('onInject',this.clone);
			}
		}.bind(this);
		
		this.timer_function = function(){
			if(!this.mouseover){
				this.fireEvent('onRemove',this.clone);
			}
		}.bind(this);
		
		this.links.each(function(el,i){
		
			el.addEvent('mouseenter',function(){
				this.mouseover = true;
				this.mouseover_link = true;
				if(this.timer)$clear(this.timer);
				if(this.hover_timer)$clear(this.hover_timer);
				if(this.current !== i){
					if(this.current === false){
						this.hover_function(i);
					} else {
						this.hover_timer = this.hover_function.delay(this.options.delay,this,i);
					}
				}
			}.bindWithEvent(this));
			
			el.addEvent('mouseleave',function(){
				this.mouseover = false;
				if(this.hover_timer)$clear(this.hover_timer);
				this.timer = this.timer_function.delay(this.options.delay);
			}.bindWithEvent(this));
			
		}.bind(this));
		
		this.location.addEvent('mouseenter',function(){
			this.mouseover = true;
			if(this.timer)$clear(this.timer);
			if(this.hover_timer)$clear(this.hover_timer);
		}.bindWithEvent(this));
			
		this.location.addEvent('mouseleave',function(){
			this.mouseover = false;
			if(this.hover_timer)$clear(this.hover_timer);
			this.timer = this.timer_function.delay(this.options.delay);
		}.bindWithEvent(this));
	}

});
