// precondition: Prototype is already linked in this page

var Slider = function(min, max, step, value) {
    this.min = min || 0;
    this.max = max || 100;
    this.step = step || 10;
    this.value = value || 0;

    this.outer = $(document.createElement("div"));
    this.outer.addClassName("sliderouterarea");
    
    this.bg = $(document.createElement("img"));
    this.thumb = $(document.createElement("img"));
    this.outer.appendChild(this.bg);
    this.outer.appendChild(this.thumb);
    
    this.bg.src = "images/slider_bg.gif";
    this.bg.alt = "slider background";
    this.bg.className = "sliderbgimage";
    
    this.thumb.src = "images/slider_widget.gif";
    this.thumb.alt = "slider widget";
    this.thumb.className = "sliderwidgetimage";

    this.moving = false;
    this.oldX = 0;
    var that = this;
    this.bg.observe("mousedown", function(event) {
        event = EventExtend(event);
        event.abort();
        if (event.isLeftClick()) {
            that.moving = true;
            that.oldX = event.pointerX();
        }
        return false;
    });

    this.bg.observe("mouseup", function(event) {
        event = EventExtend(event);
        that.moving = false;
    });

    this.bg.observe("mousemove", function(event) {
        event = EventExtend(event);
        event.abort();
        if (event.isLeftClick() && that.moving) {
            var oldLeft = parseInt(that.thumb.getStyle("left"));
            var dx = event.pointerX() - that.oldX;
            if (Math.abs(dx) >= that.step) {
                that.setValue(that.getValue() + dx);  // wrong
                that.oldX = event.pointerX();
            }
        }
        return false;
    });

    this.bg.observe("mouseout", function(event) {
        if (that.onmouseup) {
            that.onmouseup(event);
        }
    });
};

Slider.prototype.appendTo = function(element) {
    element.appendChild(this.outer);
};

Slider.prototype.getValue = function() {
    return this.value;
};

Slider.prototype.setValue = function(value) {
    value = Math.max(this.min, Math.min(this.max, value));
    
    // image has 7px horiz buffer
    this.value = value;
    var newX = value + 7;
    this.thumb.style.left = newX + "px";
    
    if (this.onchange) {
        this.onchange(value);
    }
};
