A.Gallery = {
    openFirst: function() {
        var firstGallery = Y.one('.gallery');
        var content = firstGallery.one('.sliding-content');
        content.setStyle('height', 'auto');
        firstGallery.removeClass('element-closed');
    },
    initImagePaging: function() {
        Y.one('#galleries').delegate('click', function(e) {
            var target = e.target;
            var next = 1;
            if (target.hasClass('prev')) {
                next = 0;
            }
            var pictureId = e.target.ancestor('.sliding-content').get('id').split('-').pop();
            A.Gallery.turn(pictureId, next);
        }, '.pager');
    },

    turn: function(pictureId, next) {
        var picture     = Y.one('#picture-' + pictureId);
        var loader      = picture.one('.loader');
        var image       = picture.one('img.gallery-image');
        var counter     = picture.one('.gallery-counter .count');
        var caption = picture.one('.gallery-counter p');
        var anim        = new Y.Anim({
            node: image,
            to: {
                opacity: 0
            },
            duration: "0.1"
        });
        anim.on('end', function() {
            loader.removeClass('hidden');
            Y.io('/gallery/turn/' + pictureId, {
                data: 'next=' + next,
                headers: { accept: 'text/javascript' },
                on: {
                    success: function(id, r) {
                        var json = Y.JSON.parse(r.responseText).next;
                        var anim    = new Y.Anim({
                            node: image,
                            to: {
                                opacity: 1
                            },
                            duration: "0.1"
                        });
                        image.on('load', function(e) {
                            loader.addClass('hidden');
                            anim.run();
                            picture.set('id', 'picture-' + json.id);
                            caption.one('.picture-title').setContent(json.title);
                            caption.one('.picture-description').setContent(json.description);
                            counter.one('.count-current').setContent(json.ordering);
                        });
                        image.set('src', context.urls.gallery + json.filename);
                    }
                }
            });
        });
        anim.run();
    }
};

