﻿var SlideShow = Class.create({
    initialize: function(Container, Options) {
        if (typeof Container == "string") {
            this.container = $(Container);
        } else {
            this.container = Container;
        }
        this.opts = Options;
        this.count = 0;
        if (this.container) {
            this.elements = $(this.container).select(".slide_item");
            if ($(Options.pagerContainer)) {
                this.pagerContainer = $(Options.pagerContainer);
                Event.observe(window, 'load', this.setUpControls.bind(this));
            }
            Event.observe(window, 'load', this.start.bind(this));
        }
    },
    setUpControls: function() {
        var _self = this;
        for (var i = 0; i < this.elements.length; i++) {
            var title = this.elements[i].title;
            this.pagerContainer.insert(
                    new Element('a', { 'href': 'javascript:void(0);', 'title': i })
                    .addClassName(i == 0 ? "active" : "")
                    .observe('click', function() {
                        _self.goTo(this.title);
                    }).update(i + 1)
                );
        }
    },
    start: function() {
        var _self = this;
        this.slideShowInterval = setInterval(function() { _self.slideShow() }, (this.opts.delay * 1000));
    },
    goTo: function(elementNum) {
        clearInterval(this.slideShowInterval);
        this.fadeOut();
        this.count = elementNum;
        this.fadeIn();
        this.start();
    },
    goToNext: function() {
        clearInterval(this.slideShowInterval);
        this.fadeOut();
        this.nextCount();
        this.fadeIn();
        this.start();
    },
    goToPrev: function() {
        clearInterval(this.slideShowInterval);
        this.fadeOut();
        this.prevCount();
        this.fadeIn();
        this.start();
    },
    fadeOut: function() {
        Effect.Fade(this.elements[this.count], { duration: 1, from: 1.0, to: 0.0 });
    },
    fadeIn: function() {
        Effect.Appear(this.elements[this.count], { duration: 1, from: 0.0, to: 1.0 });
        if (this.pagerContainer) {
            this.pagerContainer.select('a').each(function(el) {
                el.removeClassName('active');
            });
            //alert(this.pagerContainer.select('a[title="' + this.count + '"]')[0]);
            this.pagerContainer.select('a[title="' + this.count + '"]')[0].addClassName('active');
        }
    },
    nextCount: function() {
        this.count++;
        if (this.count == this.elements.length) this.count = 0;
    },
    prevCount: function() {
        if (this.count == 0) {
            this.count = this.elements.length - 1;
        } else {
            this.count--;
        }
    },
    slideShow: function() {
        this.fadeOut();
        this.nextCount();
        this.fadeIn();
    }
});
