﻿$.fn.slidershow = function () {

    return this.each(function () {
        var el = $(this), currentPhoto = 0,
            allSlides = $('.item', el),
            numberOfPhotos = allSlides.length,
            timer = null;
        var mark = $("<div class=\"slide-mark-holder\"/>");

        if (numberOfPhotos > 1) {
            currentPhoto = -1;
            allSlides.each(function (i) {
                var itm = $("<img src=\"img/spot-off.png\"/>");
                mark.append(itm);
                $(this).css('z-index', ((numberOfPhotos - i) + currentPhoto) % numberOfPhotos);
            });
            el.append(mark);
            $("img:first", mark).attr("src", "img/spot-on.png");
            mark.show();
            currentPhoto = 0;

            allSlides.fadeTo(1, 0.99);

            timer = setInterval(function () {
                rotatePics();
            }, 6000);
        }
        else {
            allSlides.show();
        }

        $("img", mark).click(function (e) {
            var id = $("img", mark).index($(this));
            clearInterval(timer);
            //

            $("img", mark)
                .attr("src", "img/spot-off.png")
                .eq(id).attr("src", "img/spot-on.png");

            allSlides.not(allSlides.eq(id)).not(allSlides.eq(currentPhoto)).hide();

            if (currentPhoto != id) {

                allSlides.eq(currentPhoto).fadeOut(500, function () {

                    allSlides.each(function (i) {
                        $(this).css('z-index', ((numberOfPhotos - i) + (id - 1)) % numberOfPhotos);
                    });
                    allSlides.fadeTo(1, 0.99);
                });

                currentPhoto = id;
            }
            else {
                allSlides.each(function (i) {
                    $(this).css('z-index', ((numberOfPhotos - i) + (id - 1)) % numberOfPhotos);
                });

                allSlides.fadeTo(1, 0.99);
            }


        });

        function rotatePics() {
            currentPhoto = currentPhoto % numberOfPhotos;
            var elmt = allSlides.eq(currentPhoto);
            elmt.fadeOut(1500, function () {
                $("img", mark).attr("src", "img/spot-off.png")
                var itmToShow = currentPhoto + 1;
                if (itmToShow > $("img", mark).length - 1) {
                    itmToShow = 0;
                }
                $("img", mark).eq(itmToShow).attr("src", "img/spot-on.png")

                allSlides.each(function (i) {
                    $(this).css('z-index', ((numberOfPhotos - i) + currentPhoto) % numberOfPhotos);
                });


                elmt.fadeTo(1, 0.99);

                currentPhoto++;
            });
        }


    });


}

    


