var Welcome = function() {
    var pages = $('#Teaser .teaser');
    var currentPage = 0;
    var autoPilotTimeout;

    return {
        autoPilot: true,
        holdTime: 4000,
        fadeTime: 2000,

        setup: function() {
            var self = this;
            $('.LinkMore')
                .click(function(event) {
                           event.preventDefault();
                           self.nextPage();
                           self.stopAutoPilot();
                       });

            this.createNavigation();
            this.updateNavigation();

            pages.eq(currentPage).show();

            if (this.autoPilot) {
                this.startAutoPilot();
            }
        },

        nextPage: function() {
            var nextPage = (currentPage + 1) % pages.length;
            this.showPage(nextPage);
        },

        showPage: function(i) {
            if (currentPage == i) {
                return;
            }

            pages.eq(currentPage).fadeOut();
            pages.eq(i).fadeIn();
            currentPage = i;

            this.updateNavigation();
        },

        createNavigation: function() {
            var self = this;
            var holder = $('.teaserMenu:eq(0) .pages');
            var tpl = '<a href="#" class="page"><span></span></a>';
            pages.each(function(i) {
                           var page = $(this);
                           var item = $(tpl);

                           // give the button a class to match the page's id
                           item.addClass(page.attr('id'));
                           item.find('span').text('Page #' + (i+1));
                           item.click(function(event) {
                                          event.preventDefault();
                                          self.showPage(i);
                                          self.stopAutoPilot();
                                      });

                           // insert
                           holder.append(item);
                       });
        },

        updateNavigation: function() {
            $('.teaserMenu .page.selected').removeClass('selected');
            $('.teaserMenu .page:eq('+currentPage+')').addClass('selected');
        },

        startAutoPilot: function() {
            var self = this;
            window.clearTimeout(autoPilotTimeout);
            autoPilotTimeout = window.setTimeout(function() {
                                                     self.nextPage();
                                                     self.startAutoPilot();
                                                 }, this.holdTime);
        },

        stopAutoPilot: function() {
            window.clearTimeout(autoPilotTimeout);
        }
    };
}().setup();

