dojo.require('dojox.timing');

function Slider (slideContainerId, slideObjectType) {

    var loop = true;
    var sliding = false;
    var paused = false;
    var duration = 2000;
    var interval = 10000;
    var container = dojo.byId(slideContainerId);
    var type = slideObjectType.toLowerCase();
    var timer = new dojox.timing.Timer();
    var slideObj = dojo.query('#' + slideContainerId + ' ' +type + ':first-child')[0];
    var slideWidth = - parseInt((dojo.style(slideObj, 'marginRight') + dojo.style(slideObj, 'width')));


    this.loop = function (flag) {
        loop = (flag) ? true : false;
        return loop;
        
    }
    this.is_sliding = function() {
        return sliding;
    }

    this.duration = function (value) {
        if (value == null) {
            return duration;
        }
        if (interval > value) {
            duration = parseInt(value);
        } else {
            alert('Duration shorter than interval');
        }
        return duration;
    }

    this.interval = function (value) {
        if (value == null) {
            return interval;
        }
        if (duration < value) {
            interval = parseInt(value);
            timer.setInterval(interval);
        } else {
            alert('Duration shorter than interval');
        }
        return interval;
    }

    this.start = function () {
        timer.setInterval(interval);
        timer.onTick = function() {
            slide();
        }
        timer.start();
    }

    this.pause = function () {
        paused = true;
        timer.stop();
    }

    this.unpause = function () {
        if (paused) {
            timer.start();
            paused = false;
        }
    }

    finish = function () {
        sliding = false
        slideObj = dojo.query('#' + dojo.attr(container, 'id') + ' ' + type + ':first-child')[0];
        var marginRight = dojo.style(slideObj, 'marginRight');
        if (loop) {
            dojo.style(slideObj, 'marginRight', '0px')
            dojo.place(slideObj, container, 'last');
        } else {
            dojo.destroy(slideObj);
            var children = dojo.query('#' + dojo.attr(container, 'id') + ' ' + type);
            if (children.length <= 1) {
                timer.stop();
            }
        }
        dojo.style(container, 'marginLeft', '0px');

        dojo.style(dojo.query('#' + dojo.attr(container, 'id') + ' ' + type + ':first-child')[0], 'marginRight',  marginRight + 'px');
        
        
    }

    slide = function () {
        sliding = true;
        dojo.animateProperty({
            properties: {
                marginLeft: slideWidth
            },
            node: container,
            duration: duration,
            onEnd: function (node) {
                finish();
            }
        }).play();
    }
}
