﻿(function ($) {
    $.fn.jsPSlider = function (options) {

        var defaults = { interval: 8000 };
        options = $.extend(defaults, options);
        
        return this.each(function () {
            var plugin = $(this);
            plugin.find(".nslider-pages > DIV").addClass("nsliderpage-div");

            var timer;

            var timerFn = function () {
                var tabcount = plugin.find(".ntab-buttons > MARQUEE > UL > LI").length;
                var selectedIndex = plugin.find(".ntab-buttons > MARQUEE > UL > .selected").index();
                var newTabIndex = selectedIndex + 1;

                if (newTabIndex == tabcount)
                    newTabIndex = 0;

                plugin.find(".ntab-buttons > MARQUEE > UL > LI").removeClass("selected");
                $(plugin.find(".ntab-buttons > MARQUEE > UL > LI")[newTabIndex]).removeClass("hover").addClass("selected");

                plugin.find(".nslider-pages > DIV").removeClass("selected").fadeOut('slow');
                $(plugin.find(".nslider-pages > DIV")[newTabIndex]).fadeIn('slow').addClass("selected");

                window.clearTimeout(timer);
                timer = window.setTimeout(timerFn, options.interval);
            };

            plugin.find(".ntab-buttons > MARQUEE > UL > LI").each(function () {

                var index = $(this).index();
                var text = $(this).html();
                var link = $(this).html('').append("<a href='javascript:void(0);'>" + text + "</a>");

                link.click(function () {
                    plugin.find(".ntab-buttons > MARQUEE > UL > LI").removeClass("selected");
                    $(plugin.find(".ntab-buttons > MARQUEE > UL > LI")[index]).removeClass("hover").addClass("selected");

                    plugin.find(".nslider-pages > DIV").removeClass("selected").fadeOut('slow');
                    $(plugin.find(".nslider-pages > DIV")[index]).fadeIn('slow').addClass("selected");
                    if (options.interval > 0) {
                        window.clearTimeout(timer);
                        timer = window.setTimeout(timerFn, options.interval);
                    };
                });

            });

            plugin.find(".ntab-buttons > MARQUEE > UL > LI").mouseover(function () {
                if ($(this).hasClass("selected")) return;
                $(this).addClass("hover");
            }).mouseout(function () {
                $(this).removeClass("hover");
            });

            $(plugin.find(".nslider-pages > DIV")[plugin.find(".ntab-buttons > MARQUEE > UL > .selected").index()]).show();

            if (options.interval == 0)
                return;

            window.clearTimeout(timer);
            timer = window.setTimeout(timerFn, options.interval);

        });
    };
})(jQuery);
