var ScrollTween = new Class({
	Extends: Fx.Tween,
	
	set: function(now){
		this.parent(now);
		this.fireEvent('set', now);
	}
});

var HorizontalScroller = new Class({
	Implements: Options,
	
	options: {
		visableItems: 5,
		itemSpace: 10,
		scrollbarClassName: 'scroll-bar',
		scrollbuttonClassName: 'scroll-button',
		delay: 3000
	},
	
	initialize: function(element, options){
		element = this.element = document.id(element);
		var items = this.items = element.getChildren();
		if (items.length < this.options.visableItems) return;
		this.initBound();
		this.initScrollBar();
		this.initChildren();
		var size = element.getSize();
		this.scroller = new Element('div', {
			styles: {
				position: 'relative',
				width: size.x,
				height: size.y,
				overflow: 'hidden'
			}
		}).inject(element, 'top').adopt(this.items);
		var tween = this.tween = new ScrollTween(this.scrollbutton, {
			property: 'left',
			link: 'cancel',
			duration: 'short',
			transition: Fx.Transitions.Sine.easeOut
		});
		tween.addEvent('set', this.onTweenSet.bind(this));
		this.active = false;
		element.addEvents({
			'mouseenter': this.onMouseEnter.bind(this),
			'mouseleave': this.onMouseLeave.bind(this)
		});
		this.startTimer();
	},
	
	initBound: function(){
		var bound = this.bound = {};
		bound.onMouseDown = this.onMouseDown.bind(this);
		bound.onMouseUp = this.onMouseUp.bind(this);
		bound.onMouseMove = this.onMouseMove.bind(this);
	},
	
	initScrollBar: function(){
		var viewportWidth = this.element.getSize().x;
		var itemWidth = this.itemWidth = this.items[0].getSize().x + this.options.itemSpace;
		var ratio = this.ratio = viewportWidth / (itemWidth * this.items.length); //-10???
		var scrollbar = this.scrollbar = new Element('div.' + this.options.scrollbarClassName, {
			events: {
				'click': this.onScrollBarClick.bind(this)
			}
		});
		var scrollbutton = this.scrollbutton  = new Element('div.' + this.options.scrollbuttonClassName, {
			events: {
				'mousedown': this.bound.onMouseDown,
				'drag': function(event){
					event.preventDefault();
				},
				'click': this.stop
			}
		});
		scrollbutton.adopt(
			new Element('div.scroll-button-left'),
			new Element('div.scroll-button-right'),
			new Element('div.scroll-button-center').adopt(new Element('div.scroll-button-center-inner'))
		);
		scrollbutton.setStyle('width', Math.floor(ratio * viewportWidth));
		scrollbar.adopt(scrollbutton);
		this.element.adopt(scrollbar);
	},
	
	initChildren: function(){
		var items = Array.from(this.items);
		var w = this.itemWidth;
		items.each(function(item, index){
			item.setStyles({
				position: 'absolute',
				top: 0,
				left: w * index
			});
		});
		
		this.cords = items.map(function(item, index){
			return index * this.itemWidth;
		}, this);
	},
	
	onMouseDown: function(event){
		event.stop();
		if (this.active) return;
		this.active = true;
		var start = this.start = event.page.x;
		this.offset = start - this.scrollbutton.getPosition().x;
		var bounds = this.element.getCoordinates();
		this.end = bounds.width - this.scrollbutton.getSize().x;
		this.left = bounds.left;
		document.addEvents({
			'mouseup': this.bound.onMouseUp,
			'mousemove': this.bound.onMouseMove
		});
	},
	
	onMouseUp: function(event){
		this.active = false;
		document.removeEvents({
			'mouseup': this.bound.onMouseUp,
			'mousemove': this.bound.onMouseMove
		});
		this.settle();
	},
	
	onMouseMove: function(event){
		var left = (event.page.x - this.offset) - this.left;
		if (left < 0) left = 0;
		var end = this.end;
		if (left > end) left = end;
		this.scrollbutton.setStyle('left', left);
		var itemOffset = left / this.ratio;
		this.scroller.scrollTo(itemOffset, 0);
	},
	
	settle: function(){
		var scroll = this.scroller.getScroll().x;
		var closest = this.getClosest(scroll);
		left = closest.getStyle('left').toInt();
		this.tween.start(left * this.ratio);
	},
	
	getClosest: function(x){
		var cords = this.cords;
		var c = Array.clone(cords);
		c.sort(function(a, b){
			return Math.abs(a - x) - Math.abs(b - x);
		});
		var closest = c[0];
		var index = cords.indexOf(closest);
		return this.items[index];
	},
	
	onTweenSet: function(now){
		this.scroller.scrollTo(now.value / this.ratio, 0);
	},
	
	stop: function(event){
		event.stopPropagation();
	},
	
	onScrollBarClick: function(event){
		var scroll = event.page.x - this.scrollbar.getPosition().x - Math.floor(this.scrollbutton.getSize().x / 2);
		if (scroll < 0) scroll = 0;
		var end = this.element.getSize().x - this.scrollbutton.getSize().x;
		if (scroll > end) scroll = end;
		var closest = this.getClosest(scroll / this.ratio);
		left = closest.getStyle('left').toInt();
		this.tween.start(left * this.ratio);
	},
	
	onMouseEnter: function(){
		clearInterval(this.timer);
	},
	
	onMouseLeave: function(){
		this.startTimer();
	},
	
	startTimer: function(){
		this.timer = this.next.periodical(this.options.delay, this);
	},
	
	next: function(){
		var scroll = this.scroller.getScroll().x;
		var closest = this.getClosest(scroll + this.itemWidth);
		var left = closest.getStyle('left').toInt();
		var limit = (this.itemWidth * (this.items.length - this.options.visableItems))
		if (left > limit) left = 0;
		this.tween.start(left * this.ratio);
	}
});

var VerticalScroller = new Class({
	initialize: function(element){
		element = this.element = document.id(element);
		element.setStyle('position', 'relative');
		var scrollPane = this.scrollPane = new Element('div.v-scroll-pane', {
			styles: {
				'height': element.getSize().y
			}
		});
		var children = this.element.getChildren();
		scrollPane.inject(element, 'top').adopt(children);
		this.initScrollBar();
		this.boundOnMouseUp = this.onMouseUp.bind(this);
		this.boundOnMouseMove = this.onMouseMove.bind(this);
		this.calcRatio();
		window.addEvent('load', this.calcRatio.bind(this));
	},
	
	initScrollBar: function(){
		var scrollBar = this.scrollBar = new Element('div.v-scroll-bar', {
			events: {
				'click': this.onClick.bind(this)
			}
		});
		var scrollButton = this.scrollButton = new Element('div.v-scroll-button', {
			events: {
				'mousedown': this.onMouseDown.bind(this),
				'click': this.stop,
				'drag': this.stop
			}
		});
		var scrollButtonInner = this.scrollButtonInner = new Element('div.scroll-button-mid-inner');
		scrollButton.adopt(
			new Element('div.scroll-button-top'),
			new Element('div.scroll-button-bot'),
			new Element('div.scroll-button-mid').adopt(scrollButtonInner)
		);
		scrollBar.adopt(scrollButton);
		this.element.adopt(scrollBar);
	},
	
	calcRatio: function(){
		var height = this.scrollPane.getSize().y
		var ratio = this.ratio = height / (this.scrollPane.getScrollSize().y + height + 24);
		var h = (height * ratio) - 16//16 is the total height of the top and bottom elements.
		if (h <0) h = 0;
		this.scrollButtonInner.setStyle('height', h);
		this.scrollButton.setStyle('top', this.scrollPane.getScroll().y * ratio);
	},
	
	stop: function(event){
		event.stop();
	},
	
	onMouseDown: function(event){
		event.stop();
		if (this.active) return;
		this.active = true;
		this.offset = (event.page.y - this.scrollButton.getPosition().y) + this.scrollBar.getPosition().y;
		this.end = this.scrollPane.getSize().y - this.scrollButton.getSize().y;
		document.addEvents({
			'mouseup': this.boundOnMouseUp,
			'mousemove': this.boundOnMouseMove
		});
	},
	
	onMouseUp: function(event){
		this.active = false;
		document.removeEvents({
			'mouseup': this.boundOnMouseUp,
			'mousemove': this.boundOnMouseMove
		});
	},
	
	onMouseMove: function(event){
		var y = event.page.y - this.offset;
		this.setScroll(y);
	},
	
	onClick: function(event){
		var y = event.page.y - this.scrollBar.getPosition().y - Math.floor(this.scrollBar.getSize().y / 2);
		this.end = this.scrollPane.getSize().y - this.scrollButton.getSize().y;
		this.setScroll(y);
	},
	
	setScroll: function(y){
		if (y < 0) y = 0;
		if (y > this.end) y = this.end;
		this.scrollButton.setStyle('top', y);
		this.scrollPane.scrollTo(0, y / this.ratio);
	}
});

var CategoryItem = new Class({
	Implements: Options,
	
	options: {
		direction: 'top',
		relative: 'left',
		delay: 1
	},
	
	initialize: function(element, options){
		element = this.element = document.id(element);
		this.setOptions(options);
		var name = this.name = element.getElement('.category-item-header');
		var desc = this.desc = element.getElement('.category-item-text');
		this.img = element.getElement('.category-item-img');
		var swf = this.swf = name.getElement('embed, object');
		desc.setStyle('top', (-this.desc.getSize().y) + 20);
		this.nameTween = new Fx.Tween(name, {
			property: 'color',
			duration: 'long',
			link: 'cancel'
		});
		this.descTween = new Fx.Tween(desc, {
			property: 'top',
			duration: 'long',
			link: 'cancel'
		});
		this.href = element.get('data-url');
		element.addEvents({
			'mouseenter': this.onMouseEnter.bind(this),
			'mouseleave': this.onMouseLeave.bind(this),
			'click': this.onClick.bind(this)
		});
		
		name.setStyle('display', 'none');
		desc.setStyle('display', 'none');
		element.setStyles({
			'width': 1,
			'visibility': 'hidden'
		});
		window.addEvent('load', (function(){this.start.delay(this.options.delay, this)}).bind(this));
	},
	
	onMouseEnter: function(event){
		this.nameTween.start('#f00000');
		this.descTween.start(20);
		if (this.swf.over) this.swf.over();
	},
	
	onMouseLeave: function(event){
		this.nameTween.start('#fff');
		this.descTween.start((-this.desc.getSize().y) + 20);
		if (this.swf.out) this.swf.out();
	},
	
	onClick: function(event){
		window.location.href = this.href;
	},
	
	start: function(){
		var element = this.element;
		var dir = this.options.direction;
		var pos;
		if (dir == 'top'){
			pos = [0, -this.img.getSize().y];
		}
		else if (dir == 'bottom'){
			pos = [0, this.img.getSize().y];
		}
		else if (dir == 'left'){
			pos = [-this.img.getSize().y, 0];
		}
		else if (dir == 'right'){
			pos = [this.img.getSize().y, 0];
		}
		this.img.setStyle('background-position', pos);
		var startTween = this.startTween = new ScrollTween(element, {
			duration : 'long',
			onComplete: this.onStartComplete.bind(this)
		});
		startTween.addEvent('set', this.onStartTweenSet.bind(this));
		element.setStyle('visibility', 'visible');
		startTween.start('width', 1, 374);
	},
	
	onStartComplete: function(){
		var tween = this.imgTween = new Fx.Tween(this.img, {
			duration : 'long',
			onComplete: this.onImgComplete.bind(this)
		});
		tween.start('background-position', this.img.getStyle('background-position'), '0 0');
	},
	
	onStartTweenSet: function(now){
		this.element.setStyle(this.options.relative, (374 - now.value)/2);
	},
	
	onImgComplete: function(){
		var name = this.name;
		name.setStyles({
			'top': -20,
			'display': 'block'
		});
		var tween = this.nameTween = new Fx.Tween(name, {
			duration : 'long',
			onComplete: (function(){
				this.desc.setStyle('display', 'block');
			}).bind(this)
		});
		tween.start('top', -20, 0);
	}
});

window.addEvent('domready', function(){
	var horizontalScroller = new HorizontalScroller('pageFeaturedProducts');
	
	$('pageWelcomeInner').setStyle('height', 94);
	var verticalScroller = new VerticalScroller('pageWelcomeInner');
	
	var email = $('ekmResponseEmailAddress');
	if (email){
		email.addEvents({
			'focus': function(event){
				var t = $(event.target);
				if (t.get('value').trim() == t.defaultValue) t.set('value', '');
			},
			'blur': function(event){
				var t = $(event.target);
				if (t.get('value').trim() == '') t.set('value', t.defaultValue);
			}
		});
	}
	
	var categoryItems = [];
	var pos = ['bottom', 'top', 'right', 'left'];
	var rel = ['left', 'right'];
	$$('.category-item').each(function(item, index){
		var categoryItem = new CategoryItem(item, {
			direction: pos[index],
			relative: rel[index],
			delay: index * 1000
		})
		categoryItems.push(categoryItem);
	});
});
