$(window).addEvent('domready', function () {
    document.myGallerySet = new gallerySet($('myGallerySet'), {
        timed: false,
        useHistoryManager: true,
        embedLinks: false
    });
    var buttons = $(document.body).getElements('.galleryButton');
    var scrollButtonIntoView = function (btn, i) {
        var buttons = $(document.body).getElements('.galleryButton');
        if (i > 3) {
            buttons.each(function (item, index, array) {
                var j = i - 3;
                if (index < j || index > i) {
                    item.setStyle('display', 'none');
                } else {
                    item.setStyle('display', 'block');
                }
            });
        }
        else {
            buttons.each(function (item, index, array) {
                if (index > 3) {
                    item.setStyle('display', 'none');
                } else {
                    item.setStyle('display', 'block');
                }
            });
        }
    }
    var activateButton = function (btn, i) {
        buttons.removeClass('active');
        $(btn).addClass('active');
        if (i >= 0) {
            scrollButtonIntoView(btn, i);
        }
    }
    buttons.addEvent('click', function () {
        activateButton(this, -1);
    });
    activateButton(buttons[0], 0);
    var nextBtn = $(document.body).getElements('.jdGallery.withArrows .right');
    nextBtn.addEvent('click', function () {
        var buttons = $(document.body).getElements('.galleryButton');
        var activeIndex = 0;
        buttons.each(function (item, index) {
            if (item.hasClass('active'))
                activeIndex = index;
        });
        if (activeIndex < buttons.length - 1) {
            activeIndex++;
        } else {
            activeIndex = 0;
        }
        document.myGallerySet.changeGallery(activeIndex);
        activateButton(buttons[activeIndex], activeIndex);
    });
    var prevBtn = $(document.body).getElements('.jdGallery.withArrows .left');
    prevBtn.addEvent('click', function () {
        var buttons = $(document.body).getElements('.galleryButton');
        var activeIndex = 0;
        buttons.each(function (item, index) {
            if (item.hasClass('active'))
                activeIndex = index;
        });
        if (activeIndex > 0) {
            activeIndex--;
        } else {
            activeIndex = buttons.length - 1;
        }
        document.myGallerySet.changeGallery(activeIndex);
        activateButton(buttons[activeIndex], activeIndex);
    });
});
