/*
 * Add onChange event for all stages 
 * of the function increase()
 */

Fx.Custom = Fx.Style.extend({
	increase: function() {
		this.fireEvent('onChange');
		this.parent();
	}
});

/*
 * BUG: Avec la valeur min negative
 */

var Scale = Drag.Move.extend({
	options: {
		setHTML: function() {
			this.element.setHTML(this.options.value);
		},
		wait: false,
		duration: 300,
		value: null,
		snap: 0,
		max: 10,
		min: 0
	},
	initialize: function(container, options) {
		this.options.container = container;
		this.parent(container.getElement('div.cursor') || 
			new Element('div', {'class': 'cursor'}).injectInside(container), options);

		this.container.addEvents({
			mousedown: this.mousedown.bindWithEvent(this)
		});

		this.fx = new Fx.Custom(this.element, 'left', {
			duration: this.options.duration
		}).addEvent('onChange', (function() {
			this.proportion();
			this.fireEvent('onChange');
		}).bind(this));
		
		if (!this.options.wait)
			this.setValue(this.options.value || this.options.min);
	},
	getCoor: function() {
		return {
			c: this.container.getCoordinates(),	
			e: this.element.getCoordinates()
		}
	},
	getValue: function() {
		return this.options.value;
	},	
	setValue: function(value) {
		if (value < this.options.min)
			value = this.options.min;

		// BUG ? with value = 0
		if (value != 0 && value > this.options.max)
			value = this.options.max;

		var coo = this.getCoor(), p, x;
		p = (coo.c.width - coo.e.width) / (this.options.max - this.options.min);
		//x = coo.c.left + (p * (value - this.options.min));
		x = p * (value - this.options.min);

		this.options.value = value;
		this.fx.start(x).chain((function() {
			this.options.setHTML.bind(this)();
			this.fireEvent('onComplete');
		}).bind(this));
	},
	proportion: function() {
		var coo = this.getCoor(), p, x;
		
		p = (coo.e.left - coo.c.left) / (coo.c.width - coo.e.width);
		x = (this.options.max - this.options.min) * p;	
		
		this.options.value = (this.options.min + x).round();
		this.options.setHTML.bind(this)();
	},
	drag: function(event) {
	   	this.parent(event);
		this.proportion();
		this.fireEvent('onChange');
	},
	mousedown: function(event) {
		var coo = this.getCoor(), x;		
		x = event.client.x - coo.c.left - (coo.e.width / 2);
		if (x < 0)
			x = 0;
			
		if (x > coo.c.width - coo.e.width) 
			x = coo.c.width - coo.e.width;
				
		this.fx.start(x).chain((function() {
			this.proportion();
			this.fireEvent('onComplete');
		}).bind(this));
	}
});
