﻿var slideObj;

var sShow = function() {
    var delay = 5;
    var timer;
    var slideObj;
    var nextIndex;
    var prevIndex;

    this.init = function(obj, sec) {
        slideObj = obj;
        delay = sec;

        obj.css({ "position": "relative" });
        $(".slide", obj).css({ "display": "none", "position": "absolute", "top": "0px", "left": "0px", "right": "0px", "bottom": "0px" });

        this.setupSlideButtons($(".slide", obj).length);

        var switchFunc = this.switchSlide;
        $(".nextSlide", obj).click(function() {
            switchFunc(nextIndex);
        });

        $(".prevSlide", obj).click(function() {
            switchFunc(prevIndex);
        });

        this.switchSlide(0);
    }

    this.setupSlideButtons = function(count) {
        var p = $(".slideControl .slideBtn", slideObj).parent();
        var template = $(".slideControl .slideBtn", slideObj).parent().html();
        p.text("");
        for (var j = 0; j < count; j++) {
            var obj = $(template);
            obj.text(j + 1);
            p.append(obj);
        }
        var switchFunc = this.switchSlide;
        $(".slideControl .slideBtn", slideObj).each(function(i) {
            $(this).click(function() {
                switchFunc(i);
            });
        });
    }

    this.switchSlide = function(index) {
        clearTimeout(timer);

        var visibleSlide = null, nextSlide;
        visibleSlide = $(".slide:visible", slideObj);
        nextSlide = $(".slide:nth(" + index + ")", slideObj);

        if (visibleSlide != null)
            visibleSlide.fadeOut("slow");
        nextSlide.fadeIn("slow");

        var o = $(".slideSelectedBtn", slideObj);
        o.removeClass("slideSelectedBtn");
        o.addClass("slideBtn");

        o = $(".slideControl .slideBtn:nth(" + index + ")", slideObj);
        o.removeClass("slideBtn");
        o.addClass("slideSelectedBtn");

        prevIndex = index - 1;
        if (prevIndex < 0)
            prevIndex = $(".slide", slideObj).length - 1;

        if (index == ($(".slide", slideObj).length - 1))
            index = -1;
        nextIndex = index + 1;

        timer = setTimeout("slideObj.switchSlide(" + nextIndex + ")", delay * 1000);
    }
}

$(document).ready(function()
{
    jQuery.fn.slideShow = function(sec)
    {
        slideObj = new sShow();

        slideObj.init(this, sec);
    }
});
