var Tips = new Class({

	Implements: [Events, Options],

	options: {
		onShow: function(tip){
			tip.setStyle('visibility', 'visible');
		},
		onHide: function(tip){
			tip.setStyle('visibility', 'hidden');
		},
		showDelay: 100,
		hideDelay: 0,
		className: null,
		offsets: {x: 20, y: -35},
		fixed: false
	},

	initialize: function(){
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		this.setOptions(params.options || null);
		
		this.tip = new Element('div').inject(document.body);
		
		if (this.options.className) this.tip.addClass(this.options.className);
		
		var top = new Element('div', {'class': 'tip_top'}).inject(this.tip);
		this.container = new Element('div', {'class': 'tip'}).inject(this.tip);
		var bottom = new Element('div', {'class': 'tip_bottom'}).inject(this.tip);

		this.tip.setStyles({position: 'absolute', top: 0, left: 0, visibility: 'hidden'});
		
		if (params.elements) this.attach(params.elements);
	},
	
	attach: function(elements){
		$$(elements).each(function(element){
			var title = element.retrieve('tip:title', element.get('title'));
			var text = element.retrieve('tip:text', element.get('rel') || element.get('href'));
			var enter = element.retrieve('tip:enter', this.elementEnter.bindWithEvent(this, element));
			var leave = element.retrieve('tip:leave', this.elementLeave.bindWithEvent(this, element));
			element.addEvents({mouseenter: enter, mouseleave: leave});
			if (!this.options.fixed){
				var move = element.retrieve('tip:move', this.elementMove.bindWithEvent(this, element));
				element.addEvent('mousemove', move);
			}
			element.store('tip:native', element.get('title'));
			element.erase('title');
		}, this);
		return this;
	},
	
	detach: function(elements){
		$$(elements).each(function(element){
			element.removeEvent('mouseenter', element.retrieve('tip:enter') || $empty);
			element.removeEvent('mouseleave', element.retrieve('tip:leave') || $empty);
			element.removeEvent('mousemove', element.retrieve('tip:move') || $empty);
			element.eliminate('tip:enter').eliminate('tip:leave').eliminate('tip:move');
			var original = element.retrieve('tip:native');
			if (original) element.set('title', original);
		});
		return this;
	},
	
	elementEnter: function(event, element){
		
		$A(this.container.childNodes).each(Element.dispose);
		
		var title = element.retrieve('tip:title');
		
		if (title){
			this.titleElement = new Element('div', {'class': 'tip_title'}).inject(this.container);
			this.fill(this.titleElement, title);
		}
		
		var text = element.retrieve('tip:text');
		if (text){
			this.textElement = new Element('div', {'class': 'tip_text'}).inject(this.container);
			this.fill(this.textElement, text);
		}
		
		this.timer = $clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);

		this.position((!this.options.fixed) ? event : {page: element.getPosition()});
	},
	
	elementLeave: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},
	
	elementMove: function(event){
		this.position(event);
	},
	
	position: function(event){
		var size = window.getSize(), scroll = window.getScroll();
		var tip = {x: this.tip.offsetWidth, y: this.tip.offsetHeight};
		var props = {x: 'left', y: 'top'};
		for (var z in props){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > size[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
			this.tip.setStyle(props[z], pos);
		}
	},
	
	fill: function(element, contents){
		(typeof contents == 'string') ? element.set('html', contents) : element.adopt(contents);
	},

	show: function(){
		this.fireEvent('show', this.tip);
	},

	hide: function(){
		this.fireEvent('hide', this.tip);
	}

});

var MooScroll = new Class({
	Implements: Options,
	options: {
    selector: '.scroll',
		increment:30,
		fixHeight:true,
		fixedHeight:'423px',
		upBtnClass:'upBtn',
		downBtnClass:'downBtn',
		scrollBarClass:'scrollBar',
		scrollHandleClass:'scrollHandle',
		scrollHandleBGClass:'scrollHandleBG',	
		scrollHandleTopClass:'scrollHandleTop',
		scrollHandleMiddleClass:'scrollHandleMiddle',			
		scrollHandleBottomClass:'scrollHandleBottom',
		scrollControlsYClass: 'scrollControlsY',
		handleOpacity:1,
		handleActiveOpacity:0.85,
		disabledOpacity:0.5,
		fullWindowMode:false,
		smoothMooScroll:{
			toAnchor:true,
			toMooScrollArea:true
		},
		restrictedBrowsers:[Browser.Engine.presto925,Browser.Platform.ipod,Browser.Engine.webkit419]
  },
	
	initialize: function(options){
		if(this.options.restrictedBrowsers.contains(true)){
			return;
		}
		
		this.setOptions(options);		
		this.mooScrollAreas = [];
		this.windowFxScroll = new Fx.Scroll(document.window,{wait: false});

		$(document.body).getElements(this.options.selector).each(function(item,index){
			var scrollArea = new MooScrollArea(this.options, item,this.windowFxScroll);
			this.mooScrollAreas.include(scrollArea);
			if(this.options.smoothMooScroll.toAnchor || this.options.smoothMooScroll.toMooScrollArea){				
				this.smoothMooScroll = new SmoothMooScroll({toAnchor:this.options.smoothMooScroll.toAnchor,toMooScrollArea:this.options.smoothMooScroll.toMooScrollArea},scrollArea.contentEl,this.windowFxScroll);
			}
		}.bind(this));
	},
	
	loadContent:function(content){
		this.mooScrollAreas.each(function(item,index){
			item.loadContent(content);
		});
	},
	
	refresh:function(){
		this.mooScrollAreas.each(function(item,index){
			item.refresh();
		});
	},
	
	setSlider:function(v){
		this.mooScrollAreas.each(function(item,index){
			item.setSlider(v);			
		});
	}
});

var MooScrollArea = new Class({
	Implements: Options,		

	initialize: function(options, parentEl, windowFxScroll){
		this.windowFxScroll = windowFxScroll;
		this.setOptions(options);
		this.parentEl = parentEl.setProperty('rel', 'MooScrollArea');
		this.viewPort = {x:$(window).getSize().x,y:$(window).getSize().y};
		this.parentElPadding = this.parentEl.getStyles('padding-top','padding-right','padding-bottom','padding-left');
		this.paddingHeight = parseFloat(this.parentEl.getStyle('padding-top'))+parseFloat(this.parentEl.getStyle('padding-bottom'));
		this.paddingWidth = parseFloat(this.parentEl.getStyle('padding-left'))+parseFloat(this.parentEl.getStyle('padding-right'));
		
		this.contentEl = new Element('div',{'class':'contentEl'}).adopt(this.parentEl.getChildren()).inject(this.parentEl,'top');
		this.parentEl.setStyle('overflow', 'hidden').setStyles({
			'padding':0, 
			width:parseFloat(this.parentEl.getStyle('width')) + this.paddingWidth,	
			height:parseFloat(this.parentEl.getStyle('height')) + this.paddingHeight	
		});
		
		this.borderHeight = parseFloat(this.parentEl.getStyle('border-top-width'))+parseFloat(this.parentEl.getStyle('border-bottom-width'));
		this.contentEl.setStyles({'height':this.parentEl.getSize().y-this.borderHeight, overflow:'hidden','padding':0});
		this.paddingEl = new Element('div',{'class':'paddingEl'}).adopt(this.contentEl.getChildren()).inject(this.contentEl,'top').setStyles(this.parentElPadding);
		
		if(this.options.fullWindowMode){
			$(document).getElement('html').setStyle('overflow','hidden');
			this.parentEl.setStyles({ 'height':'100%', 'width':'100%', 'position':'absolute' });
			this.contentEl.setStyles({ 'height':'100%', 'width':'100%', 'position':'absolute'});		
		}
		
		this.scrollControlsYWrapper = new Element('div', {'class': this.options.scrollControlsYClass	}).inject(this.parentEl,'bottom');
		this.upBtn = new Element('div', {'class': this.options.upBtnClass	}).inject(this.scrollControlsYWrapper,'bottom');
		this.downBtn = new Element('div', {'class': this.options.downBtnClass	}).inject(this.scrollControlsYWrapper,'bottom');
		this.scrollBar = new Element('div', {'class': this.options.scrollBarClass	}).inject(this.scrollControlsYWrapper,'bottom');
		this.scrollHandle = new Element('div', {'class': this.options.scrollHandleClass	}).inject(this.scrollBar,'inside');
		this.scrollHandleTop = new Element('div', {'class': this.options.scrollHandleTopClass }).inject(this.scrollHandle,'inside');
		this.scrollHandleBG = new Element('div', {'class': this.options.scrollHandleBGClass }).inject(this.scrollHandle,'inside');
		this.scrollHandleMiddle = new Element('div', {'class': this.options.scrollHandleMiddleClass }).inject(this.scrollHandle,'inside');
		this.scrollHandleBottom = new Element('div', {'class': this.options.scrollHandleBottomClass }).inject(this.scrollHandle,'inside');
		this.coverUp = new Element('div').inject(this.scrollControlsYWrapper,'bottom');

		this.fixIE6CSSbugs();
		
		this.overHang = this.paddingEl.getSize().y - this.parentEl.getSize().y   ;
		
		this.setHandleHeight();
		
		if(this.overHang <=0) {
			this.greyOut();
			return;
		}

		this.initSlider();		
		
		this.parentEl.addEvents({
			'mousewheel': function(e){
				e = new Event(e).stop();							
				if (e.wheel > 0) { this.scrollUp(true); }				
				else if (e.wheel < 0) { this.scrollDown(true); }			
			}.bind(this),
			'keydown': function(e){	
				if (e.key === 'up') { 
					e = new Event(e).stop();
					this.scrollUp(true); 					
				} 						
				else if (e.key === 'down' || e.key === 'space') { 
					e = new Event(e).stop();
					this.scrollDown(true);
				}			
			}.bind(this),			
			
			'click':function(e){				
				this.hasFocus = true;				
				this.hasFocusTimeout = (function(){
					$clear(this.hasFocusTimeout);
					this.hasFocus = true;
				}.bind(this)).delay(50);				
			}.bind(this)		
			
		});
		
		this.contentEl.addEvents({
			'scroll': function(e){
				this.slider.set(this.contentEl.getScroll().y);			
			}.bind(this)
		})
		
		this.scrollHandle.addEvents({
				'mousedown': function(e){					
					this.scrollHandle.addClass(this.options.scrollHandleClass +'-Active').setStyle('opacity',this.options.handleActiveOpacity);
				}.bind(this)
		});
		
		document.addEvents({
			'mouseup': function(e){					
				this.scrollHandle.removeClass(this.options.scrollHandleClass +'-Active').setStyle('opacity',this.options.handleOpacity);
				this.upBtn.removeClass(this.options.upBtnClass +'-Active');
				this.downBtn.removeClass(this.options.downBtnClass +'-Active');
			}.bind(this),
			
			'keydown':function(e){				
				if( (this.hasFocus ||this.options.fullWindowMode) && (e.key === 'down' || e.key === 'space' ||e.key === 'up') ){	this.parentEl.fireEvent('keydown',e);		}
			}.bind(this),
			
			'click':function(e){				
				this.hasFocus = false;									
			}.bind(this)			
		});
		
		window.addEvent('resize', function() {			

		$clear(this.refreshTimeout);
			if (this.options.fullWindowMode) {
				this.refreshTimeout = (function(){
					$clear(this.refreshTimeout);
					if (this.viewPort.x != $(window).getSize().x || this.viewPort.y != $(window).getSize().y) {
						this.refresh();
						this.viewPort.x = $(window).getSize().x;
						this.viewPort.y = $(window).getSize().y;
					}
				}.bind(this)).delay(250);
			}	
		}.bind(this));
		
		this.upBtn.addEvents({
				'mousedown': function(e){					
					$clear(this.upInterval);
					$clear(this.downInterval);
					this.upInterval = this.scrollUp.periodical(10,this);
					this.upBtn.addClass(this.options.upBtnClass +'-Active');					
				}.bind(this),
				
				'mouseup': function(e){
					$clear(this.upInterval);
					$clear(this.downInterval);					
				}.bind(this),
				
				'mouseout': function(e){
					$clear(this.upInterval);
					$clear(this.downInterval);
				}.bind(this)
		});
			
		this.downBtn.addEvents({
				'mousedown': function(e){
					$clear(this.upInterval);
					$clear(this.downInterval);
					this.downInterval = this.scrollDown.periodical(10,this);
					this.downBtn.addClass(this.options.downBtnClass +'-Active');
				}.bind(this),
				
				'mouseup': function(e){
					$clear(this.upInterval);
					$clear(this.downInterval);
				}.bind(this),
				
				'mouseout': function(e){
					$clear(this.upInterval);
					$clear(this.downInterval);
				}.bind(this)
		});
	},
	
	initSlider:function(){
		this.slider = new Slider(this.scrollBar, this.scrollHandle, {	
			range:[0, Math.round(this.overHang )],	
			mode: 'vertical',	
			onChange: function(step,e){
				this.contentEl.scrollTo(0, step);				
				this.webKitKludge(step);				 
			}.bind(this)
		}).set(0);
	},
	
	webKitKludge:function(step){
		if (!Browser.Engine.webkit) {return;}
		if(this.step > step){ 
			this.step = step;	
			return; 
		}
		
		$clear(this.sliderTimeout);
		
		this.sliderTimeout = (function(){ 
			$clear(this.sliderTimeout);						
			var onePercent = (1*this.paddingEl.getSize().y)/100;			
			if((onePercent + step) >= this.overHang ){						
				if(this.paddingElTopMargin == null){this.paddingElTopMargin = parseFloat(this.paddingEl.getStyle('margin-top'));}	
				this.paddingEl.setStyle('margin-top', this.paddingElTopMargin -onePercent);	
				if(!this.scrollHandleTopMargin){this.scrollHandleTopMargin = parseFloat(this.scrollHandle.getStyle('margin-top'));}
				this.scrollHandle.setStyle('margin-top',this.scrollHandleTopMargin+2);				
				this.contentEl.scrollTo(0, this.overHang );					
				this.step = this.overHang ;	
			}else{
				this.paddingEl.setStyle('margin-top', this.paddingElTopMargin );
				this.scrollHandle.setStyle('margin-top',this.scrollHandleTopMargin);
				this.contentEl.scrollTo(0, step);
				this.step = step;
			}	
		}.bind(this)).delay(10);
	},

	scrollUp:function(scrollPageWhenDone){		
		var target = this.contentEl.getScroll().y - 30;
		this.slider.set(target);
		if(this.contentEl.getScroll().y <= 0 && scrollPageWhenDone){
			document.window.scrollTo(0 ,document.window.getScroll().y - this.options.increment );
		}
	},
	
	scrollDown:function(scrollPageWhenDone){		
		var target = this.contentEl.getScroll().y + this.options.increment;
		this.slider.set(target);
		var onePercent = (1*this.paddingEl.getSize().y)/100;
		var atBottom = 	(this.paddingEl.getSize().y - this.parentEl.getSize().y)<= (this.contentEl.getScroll().y + onePercent);	
		if(atBottom && scrollPageWhenDone){
			document.window.scrollTo(0 ,document.window.getScroll().y + this.options.increment );
		}
	},
	
	fixIE6CSSbugs:function(){
		if(Browser.Engine.trident4){			
			this.parentEl.setStyle('height',this.parentEl.getStyle('height'));
			this.contentEl.setStyle('height',this.parentEl.getStyle('height'));
			var top = this.scrollBar.getStyle('top').toInt();
			var bottom = this.scrollBar.getStyle('bottom').toInt();
			var parentHeight = this.parentEl.getSize().y - this.borderHeight;
			this.scrollControlsYWrapper.setStyles({'height':parentHeight});
			this.scrollBar.setStyles({'height':parentHeight-top-bottom });
		}
	},
	
	setHandleHeight:function(){		
		var handleHeightPercent = (100 - ((this.overHang*100)/this.paddingEl.getSize().y));		
		this.handleHeight = ((handleHeightPercent*this.parentEl.getSize().y)/100) - (this.scrollHandleTop.getSize().y + this.scrollHandleBottom.getSize().y );
		if((this.handleHeight + this.scrollHandleTop.getSize().y + this.scrollHandleBottom.getSize().y ) >= this.scrollBar.getSize().y){
			this.handleHeight-=( this.scrollHandleTop.getSize().y + this.scrollHandleBottom.getSize().y )*2;
		}
		if(this.scrollHandle.getStyle('min-height') && this.handleHeight < parseFloat(this.scrollHandle.getStyle('min-height'))){
			this.handleHeight = parseFloat(this.scrollHandle.getStyle('min-height')) + this.scrollHandleBottom.getSize().y + this.scrollHandleTop.getSize().y;
		}	
		this.scrollHandle.setStyles({'height':this.handleHeight});
	},
	
	greyOut:function(){
		this.scrollHandle.setStyles({'display':'none'});
		this.upBtn.setStyles({'opacity':this.options.disabledOpacity});
		this.scrollControlsYWrapper.setStyles({opacity:this.options.disabledOpacity});
		this.downBtn.setStyles({'opacity':this.options.disabledOpacity});
		this.scrollBar.setStyles({'opacity':this.options.disabledOpacity});				
		this.coverUp.setStyles({'display':'block','position':'absolute','background':'white','opacity':0.01,'right':'0','top':'0','width':'100%','height':this.scrollControlsYWrapper.getSize().y});
	},
	
	unGrey:function(){
		this.scrollHandle.setStyles({'display':'block','height':'auto'});
		this.scrollControlsYWrapper.setStyles({opacity:1});
		this.upBtn.setStyles({'opacity':1});
		this.downBtn.setStyles({'opacity':1});
		this.scrollBar.setStyles({'opacity':1});		
		this.coverUp.setStyles({'display':'none','width':0,	'height':0	});
		this.setHandleHeight();
	},
	
	loadContent:function(content){
		this.slider.set(0);
		this.paddingEl.empty().set('html',content);	
		this.refresh();
	},
	
	refresh:function(){
		var scrollPercent = Math.round(((100* this.step)/this.overHang));
		
		if(this.options.fullWindowMode){
			var windowSize = $(window).getSize();
			this.parentEl.setStyles({ width:'100%',height:'100%'});
		}

		this.fixIE6CSSbugs();		
		this.overHang = this.paddingEl.getSize().y - this.parentEl.getSize().y   ;
		this.setHandleHeight();
		
		if(this.overHang <= 0){
			this.greyOut();
			return;
		}else{
			this.unGrey();
		}
		
		this.scrollHandle.removeEvents();		
		
		var newStep = Math.round((scrollPercent*this.overHang)/100);
		
		this.initSlider();
		this.slider.set(newStep);
		
		if (Browser.Engine.trident4) {this.scrollHandleBG.setStyle('height','0').setStyle('height','100%');}
		
		if(this.options.smoothMooScroll.toAnchor || this.options.smoothMooScroll.toMooScrollArea){				
			this.smoothMooScroll = new SmoothMooScroll({toAnchor:this.options.smoothMooScroll.toAnchor,toMooScrollArea:this.options.smoothMooScroll.toMooScrollArea},this.contentEl,this.windowFxScroll);
		}
	},
	
	setSlider:function(v){
		if(v =='top'){
			this.slider.set(0);
		}else if(v=='bottom'){
			this.slider.set('100%');
		}else{
			this.slider.set(v);
		}			
	}
 
});

var SmoothMooScroll = new Class({
	Extends: Fx.Scroll,
	initialize: function(options, context, windowFxScroll){
		this.setOptions(options);
		this.windowFxScroll = windowFxScroll;
		this.context = context;
		context = context || document;
		this.context = context;
		var doc = context.getDocument(), win = context.getWindow();		
		this.parent(context, options);
		
		this.links = (this.options.links) ? $$(this.options.links) : $$(doc.links);
		var location = win.location.href.match(/^[^#]*/)[0] + '#';
		this.links.each(function(link){
			if (link.href.indexOf(location) != 0) {	return;	}
			var anchor = link.href.substr(location.length);
			if (anchor && $(anchor) && $(anchor).getParents().contains($(this.context))) {
				this.useLink(link,anchor, true);
			}else if(anchor && $(anchor) && !this.inMooScrollArea($(anchor))){
				this.useLink(link,anchor, false);
			}
		}, this);
		if (!Browser.Engine.webkit419) this.addEvent('complete', function(){
			win.location.hash = this.anchor;
		}, true);
	},
	
	inMooScrollArea:function(el){
		return el.getParents().filter(function(item, index){return item.match('[rel=MooScrollArea]');}).length > 0;
	},
	
	putAnchorInAddressBar:function(anchor){
		window.location.href = "#" + anchor;      
	},

	useLink: function(link, anchor, inThisMooScrollArea){		
		link.removeEvents('click');
		link.addEvent('click', function(event){			
			if(!anchor || !$(anchor)){return;}			
			this.anchor = anchor;
			if (inThisMooScrollArea) {
				if(this.options.toMooScrollArea && this.options.toAnchor){
					this.windowFxScroll.toElement(this.context.getParent()).chain(function(item, index){				
						this.toElement(anchor).chain(function(){	this.putAnchorInAddressBar(anchor);	}.bind(this));				
					}.bind(this));
				}else if(this.options.toMooScrollArea){
					this.windowFxScroll.toElement(this.context.getParent()).chain(function(){	this.putAnchorInAddressBar(anchor);	}.bind(this));
				}else if(this.options.toAnchor){
					this.toElement(anchor).chain(function(){	this.putAnchorInAddressBar(anchor);	}.bind(this));	
				}				
			}else{
				this.windowFxScroll.toElement(anchor).chain(function(){	this.putAnchorInAddressBar(anchor);	}.bind(this));     
			}
			event.stop();		
		}.bind(this));
	}

});
