﻿function Slide(containerId, width, autoSlide) {
    this.containerId = containerId;
    this.width = width;

    $(containerId).attr("rel", 0);
    $(containerId + ' .nav a').each(function (i) {
        if (i == 0) {
            $(this).addClass('active');
        }

        $(this).attr("rel", parseInt(i));

        $(this).click(function () {
            var index = parseInt($(this).attr("rel"));
            move(containerId, index, width)
            busy = false;
            return false;
        });
    });
    $(containerId + ' a.next').click(function () {
        busy = false;
        slide(containerId, width, +1);
        return false;
    });
    $(containerId + ' a.prev').click(function () {
        busy = false;
        slide(containerId, width, -1);
        return false;
    });
    
    autoSlide = autoSlide || false;

    if (autoSlide) {
        setTimeout("startAutoSlide('" + containerId + "', " + width + ")", 5000);
        busy = true;
    }
}

function startAutoSlide(containerId, width) {
    setInterval("if (busy) slide('" + containerId + "', " + width + ", 1)", 5000);
}

function slide(id, width, delta) {
    var i = parseInt($(id).attr("rel"));
    var ni = Math.max(Math.min(i + delta, $(id + ' .item').length - 1), 0);
    if (i != ni) {
        $(id).attr("rel", ni);
        $(id + ' .nav a').removeClass('active');
        $(id + ' .nav a:eq(' + ni + ')').addClass('active');
        move(id, ni, width);
    }
}

function move(id, index, width) {
    $(id).val("rel", index);
    var offset = -index * width;
    $(id + ' .items').animate({ marginLeft: offset + 'px' }, 500);
    $(id + ' .nav a').removeClass('active');
    $(id + ' .nav a:eq(' + index + ')').addClass('active');
}


