/*
**	Simple Scrollflow Javascript class
**
**	(c) 2010 Mikoon Webservices
*/

/*
**	Usage:
**
**	myscrollflow = new scrollflow('container-container-element-id', 'content-container-element-id', {options});
*/

var scrollflow = new Class({
	
	Implements: Options,
	
	options: {
		speed: -20,
		period: 25,
		onUpdate: function(){  } 
    },
	
	timer: null,
	impulse: 0,
	fx: null,
	
	initialize: function(in_container, in_content, options){
		
		//	assign local variables
		this.container 			= $(in_container);
		this.content 			= $(in_content);
		
		//	get element properties
		this.container_x 		= this.container.getPosition().x;
		this.container_width 	= this.container.getSize().x;
		this.content_x			= this.content.getStyle('margin-left').toInt();
		this.content_width  	= this.content.getSize().x;
		
		this.min				= 0.5 * this.container_width;
		this.max				= -1 * (this.content_width + (0.5 * this.container_width));
		
		//	set options
		this.setOptions(options);

		//	setup events
		this.container.addEvent('mousemove', (function(event){
			this.impulse = ((event.client.x-this.container_x) / (0.5 * this.container_width)) - 1;
		}).bind(this));
		
		this.container.addEvent('mouseenter', (function(){ 
			
			// stop end animation (if started)
			if(this.fx) this.fx.cancel();
			
			// start periodical move
			this.timer = this.move.periodical(this.options.period, this);
			
		}).bind(this));
		
		this.container.addEvent('mouseleave', (function(){
			
			//	stop periodical move
			clearTimeout(this.timer); 
			
			// stop end animation (if started)
			if(this.fx) this.fx.cancel();
			
			//	start end animation based on current impulse
			var endpoint = this.content_x + (this.impulse * this.options.speed * 10);
			endpoint = Math.min(this.min, endpoint);
			endpoint = Math.max(this.max, endpoint);
			this.fx = new Fx.Tween(this.content, {duration: 1000, transition: Fx.Transitions.Quad.easeOut}).start('margin-left', this.content_x, endpoint);
			
		}).bind(this));
		
	},
	
	move: function(){
		
		//	determine min/max x-position for scroll container
		this.content_x = this.content.getStyle('margin-left').toInt() + (this.options.speed*this.impulse);
		this.content_x = Math.min(this.min, this.content_x);
		this.content_x = Math.max(this.max, this.content_x);
		
		//	set x
		this.content.setStyle('margin-left',  this.content_x + 'px');
		
		//	run custom update function
		var update_function = this.options.onUpdate.bind(this);
		update_function();
	},
	
});
