
/**
 * @author drewf
 */
if (!channelv) {
    var channelv = {};
}

channelv.Slider = {};

(function($this){

    $this.SEGMENTS = 6;
    $this.SLIDERID = 'slider';
    $this.POLLINTERVAL = 1500;
    $this.currentSegment;
    $this.timeoutint;
    
    $this.init = function(segments){
    
        this.SEGMENTS = segments;
        this.byGoto = false;
        
        var sliderOptions = {
            max: 700,
            step: 1,
            animate: false,
            clickableTrough: false,
            stop: onStop,
            change: onChange,
            start: onStart
          
        };
        $('#' + $this.SLIDERID).slider(sliderOptions);
        
    };
    
    $this.bind = function(t, f){
        $(this.events).bind(t, f);
    };
    
    $this.gotoSegment = function(segment){
        var segmentSize = getSegmentSize();
        var value = $("#" + this.SLIDERID).slider('option', 'value');
        var segmentPos = segmentSize * segment
        
        if ($this.currentSegment == segment) return;
        
        $this.byGoto = true;
        $("#" + this.SLIDERID).slider("value", segmentPos, true);
    };
    
    function checkPosition(){
        var segmentSize = getSegmentSize();
        var value = $("#" + $this.SLIDERID).slider('option', 'value');
        var segment = Math.round(value / segmentSize)
		
        if ($this.currentSegment != segment) {
            $this.currentSegment = segment;
            
            if (!$this.byGoto) {
                $($this.events).trigger('sliderchange', [inverseSegment($this.currentSegment)]);
            }
        }
    }
    
    function getSegmentSize(){
        var max = $("#" + $this.SLIDERID).slider('option', 'max');
        return max / $this.SEGMENTS;
    }
    
    function inverseSegment(s){
        return $this.SEGMENTS - s;
    }
    
    function onChange(event, ui){
        var value = ui.value;
		clearInterval($this.timeoutint);
		checkPosition();
		$this.byGoto = false
    }
    
    function onStart(event, ui){
        var segmentSize = getSegmentSize();
        var value = ui.value;
        
        $this.currentSegment = Math.round(value / segmentSize);
        
        clearInterval($this.timeoutint);
        $this.timeoutint = setInterval(checkPosition, $this.POLLINTERVAL);
    }
    
   
    function onStop(event, ui){
        var segmentSize = getSegmentSize();
        var value = ui.value;
        var currentSeg = Math.round(value / segmentSize);
        var segmentPos = segmentSize * currentSeg;
        
        $("#" + $this.SLIDERID).slider("value", segmentPos, true);
    }
    
})(channelv.Slider);

$(document).ready(channelv.Slider.init);
