

var photoalbum = $.inherit(Module, {
    __constructor: function(elem) {
        this.__base(elem);
        this.type = "photoalbum";
        this.isResizing = false;
        this.isFloat = false;
    },

    initialize: function() {
        this.initializeVars();
        this.showLargeImage(this.currentIndex);
        this.bindEvents();
    },

    loadModuleCallback: function(data) {
        this.container.html(data.html);
        this.initializeVars();
        this.showLargeImage(this.currentIndex);
        this.bindEvents();
        this.addDragHandle(data);
        this.appropriatelyResize();
    },

    initializeVars: function() {
        this.$mainImg = this.container.find(".mainImage");
        this.$leftButton = this.container.find("a.left").css({"display": "none"});
        this.$rightButton = this.container.find("a.right").css({"display": "none"});
        this.$playButton = this.container.find("a.play-status");

        this.$thumbContainer = this.container.find(".thumbnails");
        this.$thumbList  = this.$thumbContainer.find("#thumbnails_" + this.getModuleId());
        this.$thumbLeft = this.$thumbContainer.find("a.photo-album-thumb-nav-left");
        this.$thumbRight = this.$thumbContainer.find("a.photo-album-thumb-nav-right");

        this.$commentContainer = this.container.find("#COMMENTS_" + this.getModuleId());
        this.$commentSubmitForm = $("#add_comment_form_" + this.getModuleId());
        this.$commentCount = $("#comment_count_" + this.getModuleId());

        var _this = this;
        this.imgList = [];
        this.thumbList = [];
        this.currentIndex = 0;
        //this.timer = null;
        this.imgCount = 0;

        // Build a list of the images.
        this.$thumbList.find("li").each(function(i) {
            var $g = $(this).find("img").first();
            var $h = $(this).find("img").last();
            _this.thumbList.push($g);
            _this.imgList.push($h);
            _this.imgCount++;
        });

        // Calculating the number of pages to show.
        this.currentPage = 0;
        this.imgSize = this.$thumbList.find("li").first().outerWidth(true);
        this.perPage = Math.floor(this.$thumbContainer.width() / this.imgSize);
        this.numPages = Math.ceil(this.imgCount / this.perPage);
    },


    generateImage: function(url, title) {
        return $("<div class='image'></div>")
            .append($("<img />", {
                    src: url,
                    title: title
                }));
    },

    bindEvents: function() {
        var _this = this;

        if (this.showThumbnails) {
            this.$thumbContainer.show();
        }

        this.container.unbind().hover(
            function() {
                _this.$leftButton.show();
                _this.$rightButton.show();
            },
            function() {
                _this.$leftButton.hide();
                _this.$rightButton.hide();
            }
        );
 
        this.$leftButton.unbind().click(function() {
            _this.playPrevImage();
            return false;
        });

        this.$rightButton.unbind().click(function() {
            _this.playNextImage();
            return false;
        });

        this.$thumbList.find("a").each(function(i) {
            $(this).unbind().click(function() {
                _this.showLargeImage(i);
                _this.currentIndex = i;
                return false;
            });
        });

        this.$thumbLeft.unbind().click(function() {
            _this.slideThumbsLeft();
            return false;
        });

        this.$thumbRight.unbind().click(function() {
            _this.slideThumbsRight();
            return false;
        });


        // Comments form submit.
        this.$commentSubmitForm.submit(function() {
            // TODO: Add "Loading..." thing.
            var $i = _this.getCurrentPhoto();
            var id = $i.attr("id").replace("photo_", '');
            var c = $(this).find("#photo_comment_" + _this.getModuleId()).val();

            _this.ajaxPost("addComment", {"commentText": c, "id": id}, function() {
                // TODO: remove "Loading..." thing.
                _this.loadCommentsForPhoto($i.attr("id"));
            });
            return false;
        });

    },

    getCurrentPhoto: function() {
        return this.imgList[this.currentIndex];
    },

    showLargeImage: function(index) {
        var _this = this;
        var $i = this.imgList[index];
        if (!$i) {
            return;
        }
        var t = this.transitionDuration;
        var $imgDiv = this.generateImage($i.attr("src"), $i.attr("alt"));
        var $img = $imgDiv.children("img");

        this.$mainImg.children(".image").fadeOut(t, function() {
            $(this).remove();
        });

        $imgDiv.css({"display": "none"}).addClass("new");
        this.$mainImg.append($imgDiv);

        $imgDiv.fadeIn(t, function() {
            $.each(_this.thumbList, function() {
                $(this).removeClass("selected");
            });
            _this.thumbList[index].addClass("selected");
        });

        this.loadCommentsForPhoto($i.attr('id'));

    },

    playNextImage: function() {
        this.currentIndex++;
        this.currentIndex = (this.thumbList[this.currentIndex]) ? this.currentIndex : 0;
        this.showLargeImage(this.currentIndex);
    },

    playPrevImage: function() {
        this.currentIndex--;
        this.currentIndex = (this.currentIndex < 0) ? this.thumbList.length - 1 : this.currentIndex;
        this.showLargeImage(this.currentIndex);
    },


    slideThumbsLeft: function() {
        // instead of doing on the fly width() calcs, we'll just use page 
        // numbers, which makes it more OO-y.
        if (this.currentPage > 0) {
            this.currentPage--;
            var x = this.imgSize * this.perPage * this.currentPage;
            this.$thumbList.animate({"left": -x + 'px'}, 500);
        }
    },

    slideThumbsRight: function() {
        if (this.currentPage < this.numPages - 1) {
            this.currentPage++;
            var x = this.imgSize * this.perPage * this.currentPage;
            this.$thumbList.animate({"left": -x + 'px'}, 500);
        }
    },

    // Comments.
    loadCommentsForPhoto: function(id) {
        var _this = this;
        var photoid = id.replace("photo_", '');
        this.ajaxPost("getComments", {
               id:photoid
            }, 
            function(d) {
                _this.setCommentBlock(d.response);
            }
        );
    },


    setCommentBlock: function(data) {
        this.$commentCount.html(data.commentCount);
        this.$commentContainer.empty();

        for (i in data.commentsObj) {
            var c = data.commentsObj[i];
            var $comment = $("<div></div>", {"class": "comment"});

            $comment.append($("<p></p>", { "class": "date", "html":c.date}));
            $comment.append($("<p></p>", { "class": "user", "html":c.user}));
            $comment.append($("<p></p>", { "html":c.comment}));
            this.$commentContainer.append($comment);
        }

    },


    /**********************************************************************************/

    getCurrentPhotoComments: function () {
        var curr = document.getElementById("photo"+this.instId+"_"+this.slideshowId);
        if (curr) {
            var id = this.getPhotoId(curr);
            this.getComments(id);
        }
    },

    getComments: function(id) {
        this.lyAjaxObj({showspams:(this.showspams ? "yes" : "no"),id:id, region: this.region}, "getComments");
    },

    onAddComment: function( evt ) {

        // Don't increase the comment count if we're editing a pre-existing comment
        if ( evt.lyResponse.isedit == "yes" ) return;

        // Increase the comment count if the comment was successfully submitted (i.e., an error is not returned)
        if (typeof(evt.lyResponse.error) == 'undefined') {
            commentCount = parseInt(document.getElementById("numComments"+this.instId).innerHTML) + 1;
            document.getElementById("numComments"+this.instId).innerHTML = commentCount; 
            document.getElementById("viewSpanNoComments"+this.instId).style.display="none";
            document.getElementById("viewSpan"+this.instId).style.display="inline";
        }
    },

    onDeleteComment: function( evt ) {
        commentCount = parseInt(document.getElementById("numComments"+this.instId).innerHTML) - 1;
        if (commentCount <= 0) {
            commentCount = 0;
            document.getElementById("viewSpanNoComments"+this.instId).style.display="inline";
            document.getElementById("viewSpan"+this.instId).style.display="none";
        }
        document.getElementById("numComments"+this.instId).innerHTML = commentCount;
    },

    onMarkCommentAsSpam: function( evt ) {
        objNumSpams = document.getElementById("numSpams"+this.instId);
        spamCount = parseInt(objNumSpams.innerHTML) + 1;
        document.getElementById("viewSpam"+this.instId).style.display="inline";
        objNumSpams.innerHTML = spamCount;
        this.onDeleteComment( evt );
    },

    onUnmarkCommentAsSpam: function( evt ) {
        objNumSpams = document.getElementById("numSpams"+this.instId);
        spamCount = parseInt(objNumSpams.innerHTML) - 1;
        if (spamCount <= 0) {
            spamCount = 0;
            document.getElementById("viewSpam"+this.instId).style.display="none";
        }
        objNumSpams.innerHTML = spamCount;
        this.onAddComment( evt );
    }




});

