/* 
 * Article gallery.
 *
 * @author (c) Zsolt Mészárovics
 */

/*globals jQuery PMMI*/

(function ($) {

    var galleries = {}, // gallery_id -> gallery
        clickRelParser = /^([0-9]+)\.([a-z]+)$/,
        PIC_WIDTH = 126;

    function Gallery(imageCount) {
        this.imageCount = imageCount;
        this.index = 0;
        this.animating = false;
        this.boxed = false;
    }

    Gallery.createInstance = function (data) {
        galleries[data.id] = new Gallery(data.imageCount);
        $("#gallery_pictures_" + data.id + " a").lightBox();
    };

    Gallery.prototype = {
        doSlide: function (rel, a) {
            var $ul, self = this;

            if (!this.animating) {
                this.animating = true;
                $ul = $("ul:first", $(a).parent().prev());
                $ul.animate({left: rel + PIC_WIDTH + "px"}, 300, function () {
                    self.animating = false;
                });
            }
        },

        onNext: function (a) {
            if (this.index < this.imageCount - 1) {
                this.doSlide("-=", a);
                this.index++;
            }
        },

        onPrev: function (a) {
            if (this.index > 0) {
                this.doSlide("+=", a);
                this.index--;
            }
        },

        onEnlarge: function (a) {
            console.log("enlarge");
        }
    };

    $("a[rel^='pmmi\\.gallery']").live("click", function (e) {
        var id, action, rel = e.target && this.rel, m, gallery;

        if (e.button === 0) {
            e.preventDefault();

            if (rel && rel.length > 13) {
                rel = rel.substring(13);
                m = clickRelParser.exec(rel);
                if (m) {
                    id = parseInt(m[1], 10);
                    action = "on" + m[2].substring(0, 1).toUpperCase() + m[2].substring(1);
                    if (Gallery.prototype.hasOwnProperty(action)) {
                        gallery = galleries[id];
                        gallery[action](this);
                    }
                }
            }
        }
    });

    Object.setToDotRef("pmmi.Gallery", Gallery)
})(jQuery);
