﻿(function () {
    function Promotion(el, timeout) {
        var that = this;

        that.container = $("#" + el).first();
        that.options.autoTimeout = timeout;

        that.images = that.container.find(".promo.image").hide();
        that.texts = that.container.find(".promo.text").hide();
        var i = 0;
        that.navs = that.container.find(".promoNav").each(function () {
            jQuery(this).attr("fekSlide", i++);
        });

        jQuery(that.images[0]).show();
        jQuery(that.texts[0]).show();
        jQuery(that.navs[0]).find("img").attr("src", "/img/icons/fek-nav-filled-2.png");

        that.pause();
    }

    Promotion.prototype = {
        currentSlide: 0,
        options: {
            autoTimeout: 0,
            animationSpeed: 250
        },

        showSlide: function (nextSlide) {
            var that = this;
            var cs = that.currentSlide;

            jQuery(that.images[nextSlide]).add(that.texts[nextSlide]).css("z-index", 10);
            jQuery(that.images[cs]).add(that.texts[cs]).css("z-index", 0); // TODO Needed?

            jQuery(that.images[nextSlide]).fadeIn(that.options.animationSpeed, function () {
                jQuery(that.images[cs]).hide();
                jQuery(that.images[nextSlide]).add(that.texts[nextSlide]).css("z-index", 0);
            });

            jQuery(that.texts[nextSlide]).fadeIn(that.options.animationSpeed);
            jQuery(that.texts[cs]).fadeOut(that.options.animationSpeed);

            jQuery(that.navs[cs]).find("img").attr("src", "/img/icons/fek-nav-empty-2.png");
            jQuery(that.navs[nextSlide]).find("img").attr("src", "/img/icons/fek-nav-filled-2.png");

            that.currentSlide = nextSlide;
        },

        showPrevSlide: function () {
            var n = this.currentSlide == 0 ? this.images.length - 1 : this.currentSlide - 1;
            this.showSlide(n);
        },

        showNextSlide: function () {
            var n = (this.currentSlide + 1) % this.images.length;
            this.showSlide(n);
        },

        pause: function () {
            if (this.timer) {
                window.clearInterval(this.timer);
                this.timer = null;
                return true;
            } else {
                if (this.options.autoTimeout > 0) {
                    var m = this;
                    this.timer = window.setInterval(function () { m.showNextSlide(); }, this.options.autoTimeout);
                    return false;
                }
            }
        },

        resetTimer: function () {
            if (this.timer) {
                this.pause();
                this.pause();
            }
        }
    }

    window.Promotion = Promotion;
})();
