var ModelScrollr = new Class({

	Implements: [ Options ],
	
	options: {
		adjustScrollable: -10,
		adjustTrack: -2,
		scrollbar: true
	},

	initialize: function(el, options) {
		this.bound = {
			synchronize: this.synchronize.bind(this)
		};
		this.setOptions(options);
		this.element = $(el);
		this.createScrollBar().inject(this.element);
		this.attach();
		this.optimize();
		this.synchronize();
		this.findPosition();
	},
	
	attach: function() {
		this.scrollable = this.element.getElement('ul').set('morph', {
			//transition: 'quad:in:out'
		});
		/*this.catalogDrag = new Drag.Move(this.scrollable, {
			modifiers: {
				y: false
			}
		}).addEvents({
			drag: function() {
				this.synchronize();
				this.move(-this.scrollable.getStyle('left').toInt() / (this.realWidth - this.element.offsetWidthÂ + this.options.adjustScrollable));
			}.bind(this)
		});*/
		var scrollr = this;
		this.scrollDrag = new Drag.Move(this.handleElement, {
			container: this.trackElement,
			modifiers: {
				y: false
			}
		}).addEvents({
			beforeStart: function() {
				$$(this.handles).addClass('active');
			},
			drag: function() {
				//$clear(this.updateDelay);
				//this.updateDelay = scrollr.update.delay(100, scrollr);
				scrollr.follow();
			},
			complete: function() {
				//$clear(this.updateDelay);
				$$(this.handles).removeClass('active');
				//scrollr.update();
			},
			cancel: function() {
				$$(this.handles).removeClass('active');
			}
		});
		this.handleElement.addEvents({
			mouseover: function() {
				this.addClass('hover');
			},
			mouseout: function() {
				this.removeClass('hover');
			}
		});
		this.element.addEvents({
			mousewheel: function(e) {
				e.stop();
				this.move(this.at() + this.unitSize / this.realWidth * e.wheel * 3);
			}.bind(this)
		});
		this.element.getElements('li a').addEvents({
			mouseover: function() {
				this.morph({
					'background-color': '#141516',
					'color': '#fbfffb'
				});
			},
			mouseout: function() {
				this.morph({
					'background-color': '#fff',
					'color': '#000'
				});
			}
		}).set('morph', {
			duration: 'short'
		});
		window.addEvent('beforeunload', function() {
			Cookie.write('pprz_slider_' + location.pathname.substr(1), this.at());
		}.bind(this));
	},
	
	createScrollBar: function() {
		this.scrollElement = new Element('div', { 'class': 'scroll' });
		this.trackElement = new Element('div', { 'class': 'track' }).inject(this.scrollElement);
		this.handleElement = new Element('div', { 'class': 'handle', morph: { duration: 100 } }).inject(this.trackElement);
		return this.scrollElement;
	},
	
	at: function() {
		return this.handleElement.offsetLeft / (this.trackElement.offsetWidth + this.options.adjustTrack - this.handleElement.offsetWidth);
	},
	
	findPosition: function() {
		var pos = Cookie.read('pprz_slider_' + location.pathname.substr(1));
		if (pos) this.move(Number(pos));
	},
	
	optimize: function() {
		this.totalUnits = 0;
		var width = 0;
		for (var i = 0, l = this.scrollable.childNodes.length; i < l; ++i) {
			if (this.scrollable.childNodes[i].nodeType == 1) {
				width += this.scrollable.childNodes[i].offsetWidth;
				++this.totalUnits;
			}
		}
		this.realWidth = width;
		this.unitSize = width / this.totalUnits;
	},
	
	synchronize: function() {
		this.handleElement.setStyle('width', this.trackElement.offsetWidth * (this.element.offsetWidth / this.realWidth));
		this.handleElement.setStyle('left',
			(this.trackElement.offsetWidth + this.options.adjustTrack - this.handleElement.offsetWidth)
			* (-this.scrollable.getStyle('left').toInt() / (this.realWidth - this.element.offsetWidthÂ + this.options.adjustScrollable)).limit(0, 1));
	},
	
	follow: function() {
		var pos = this.at();
		var preciseLeft = -(this.realWidth - this.element.offsetWidth + this.options.adjustScrollable) * pos;
		this.scrollable.setStyle('left', preciseLeft);
	},
	
	move: function(pos) {
		pos = pos.limit(0, 1);
		this.handleElement.morph({
			left: (this.trackElement.offsetWidth + this.options.adjustTrack - this.handleElement.offsetWidth) * pos
		});
		var preciseLeft = -(this.realWidth - this.element.offsetWidth + this.options.adjustScrollable) * pos;
		var scrollLeft = preciseLeft; //Math.round(preciseLeft / this.unitSize) * this.unitSize;
		this.scrollable.morph({
			left: scrollLeft
		});
	},
	
	update: function() {
		this.move(this.at());
	}
	
});

var ModelSets = new Class({
	
	Implements: Events,
	
	initialize: function(el) {
		this.element = $(el);
		this.scrollable = this.element.getElement('ul').set('morph', { duration: 'short' });
		this.fullSized = this.element.getElements('.full a');
		this.attach();
	},
	
	attach: function() {
		var sets = this;
		this.element.getElements('li').addEvents({
			mouseover: function() {
				this.addClass('hover');
			},
			mouseout: function() {
				this.removeClass('hover');
			},
			click: function(e) {
				e.stop();
				sets.activate(this);
			}
		});
		this.element.getElements('.previous').addEvent('click', this.previous.bind(this));
		this.element.getElements('.next').addEvent('click', this.next.bind(this));
		if (!this.active()) this.activate(this.scrollable.getFirst('li'));
		else this.follow();
	},
	
	active: function() {
		return this.element.getElement('li.active');
	},
	
	activate: function(el) {
		this.scrollable.getElements('li.active').removeClass('active');
		el.addClass('active');
		this.follow();
		this.fireEvent('activate', el);
		var thumbs = el.getElements('img');
		this.fullSized.each(function(full, i) {
			if (!thumbs[i]) {
				full.setStyle('display', 'none');
				full.getElements('img').dispose();
				return;
			}
			else full.setStyle('display', '');
			if (!thumbs[i]) return;
			var link = thumbs[i].getParent('a'), fullImg = full.getElement('img');
			if (!fullImg) full.adopt(fullImg = new Element('img'));
			fullImg.removeEvents('load');
			fullImg.addEvent('load', function() {
				if (this.width > this.height) {
					this.addClass('landscape');
				}
				else {
					this.removeClass('landscape');
				}
			});
			fullImg.src = full.href = (link ? link.href : thumbs[i].src);
		}, this);
	},
	
	follow: function() {
		var active = this.active(), scrollLeft;
		if (active.getNext('li') || !active.getPrevious('li')) {
			scrollLeft = -active.offsetLeft;
		}
		else {
			scrollLeft = -active.getPrevious('li').offsetLeft;
		}
		this.scrollable.morph({
			left: scrollLeft
		});
	},
	
	next: function(e) {
		try {
			e.stop();
			e.target.blur();
		}
		catch (e) {}
		this.activate(this.active().getNext('li') || this.scrollable.getFirst('li'));
	},
	
	previous: function(e) {
		try {
			e.stop();
			e.target.blur();
		}
		catch (e) {}
		this.activate(this.active().getPrevious('li') || this.scrollable.getLast('li'));
	}
	
});

document.addEvent('init', function() { // called just before </body>
	$$('.models').each(function(el) {
		new ModelScrollr(el);
	});
	$$('.model-sets').each(function(el) {
		new ModelSets(el);
	});
	function hideFinder() {
		var finder = $('find-model');
		if (!finder) return;
		finder.getElement('ul').scrollTop = 0;
		finder.removeClass('active');
	}
	$$('#find-model').addEvents({
		click: function(e) {
			if (e) e.stopPropagation();
			if (this.hasClass('active')) hideFinder();
			else this.addClass('active');
		},
		mouseleave: function() {
			this.store('ppr:hide', hideFinder.delay(1500));
		},
		mouseenter: function() {
			$clear(this.retrieve('ppr:hide'));
		}
	});
	document.addEvent('click', hideFinder);
});

