/* IScroll class by orbi: akira@aenigma.de */

var IScroll = new Class({

	options: {
		onComplete: function(el){
			// not implemented yet
		},
		className: 'iscrollframe',
		idName: 'iscrollframe'
	},

	initialize: function(element, options){
		this.setOptions(options);

		/* --- Modify HTML --- */
		if(!$($(element).parentNode).hasClass(this.options.className) && $(element).parentNode.id != this.options.idName){
			this.draggable = $(element).clone();
			this.frame = new Element('div',{
				'class': this.options.className,
				'id': this.options.idName,
				'styles': {
					'position': 'absolute',
					'overflow': 'hidden'
				}
			});
			$(element).replaceWith($(this.frame));
			this.draggable.injectInside($(this.frame));
		}else{
			this.draggable = $(element);
			this.frame = $(element).parentNode;
		}

		/* --- Modify Visuals --- */
		var frameHeight = $(this.frame).getSize().size['y'];
		this.draggable.setStyles({
			'position':'absolute',
			'top': frameHeight,
			'left':0,
			'cursor': 'move'
		});

		/* --- Variables --- */
		var distance=0;
		var prevY=0;
		this.boundTop = frameHeight / 2;
		this.boundBottom = frameHeight / 2 - $(this.draggable).getSize().size['y'];

		/* -- Scroll In --- */
		this.draggable.effect('top',{
			transition: Fx.Transitions.cubicOut,
			duration: 1500
		}).start(0);

		/* --- Drag --- */
		this.draggable.makeDraggable({
			modifiers:{x:'', y:'top'},
			onDrag: function(){
				distance = this.draggable.getStyle('top').toInt() - prevY;
				prevY = this.draggable.getStyle('top').toInt();
			}.bind(this),
			onComplete: function(){
				var to = this.draggable.getStyle('top').toInt()+distance*10;
				var dura = 500 + Math.abs(distance * 10);
				this.draggable.effect('top',{
					transition: Fx.Transitions.cubicOut,
					duration: dura
				}).start(to).chain(function(){
					if(to < this.boundBottom){
						this.draggable.effect('top',{
							transition: Fx.Transitions.cubicOut,
							duration: dura
						}).start(this.boundBottom);
					}else if(to > this.boundTop){
						this.draggable.effect('top',{
							transition: Fx.Transitions.cubicOut,
							duration: dura
						}).start(this.boundTop);
					};
				}.bind(this));
			}.bind(this)
		});

	}

});

IScroll.implement(new Options);