//
// Site -> Photo
//
; (function(window) {

    /**
    * Site Object
    **/
    window.Site = Site = new Object();

    /*#region Site -> Photo Gallery*/

    Site.PhotoGallery = function() {

        /*******************************
        Variables
        */
        var sortMethod = "date";
        var slideInterval = "";
        var isFullscreen = false;
        var previous;
        var next;
        var currentCategory;
        var currentPosition;
        var favoriteDisabled;
        var flagDisabled;
        var averageRating;
        var photoRated;
        var uicombo;
        var currentPhotoId;
        var currentPhotoUrl;
        var replyQuote = "";
        var replyUser = "";
        var currentCommentPage = 1;
        var commentThreshold = -1;
        var isFirstLoad = false;
        var commentNumber;
        var captchaId = 0;
        var currentRating = 0;
        var tooltip;
        var panel;
        var self = this;

        /*******************************
        Page actions
        */
        this.setDialogClose = function(dialogClassName) {

            $(document).click(function(event) {
              
                if (!$(event.target).parent().hasClass("button") && !$(event.target).parent().hasClass("vote"))
                {
                   
                    tooltip.Hide();
                }
                panel.Hide($(dialogClassName));              

            });

            $(dialogClassName).click(function() {
                return false;
            });

            $(dialogClassName + " a.close").click(function() {

                panel.Hide($(dialogClassName));

                return false;
            });

        };

        this.setDimensions = function(object, photoWidth, photoHeight, maxWidth, maxHeight) {

            if (photoWidth > maxWidth || photoHeight > maxHeight) {
                object.width(maxWidth);
                object.height(maxHeight);

                object.width(object.height() * photoWidth / photoHeight);

                if (object.width() > maxWidth) {

                    object.width(maxWidth);
                    object.height(maxWidth * photoHeight / photoWidth);
                }
            }

            var positionTop = (maxHeight - object.height()) / 2;
            var positionLeft = (maxWidth - object.width()) / 2;

            object.css({
                "position": "absolute",
                "top": positionTop,
                "left": positionLeft
            });

            object.fadeIn();

        };

        this.populateThumbnails = function(jsonData) {

            $('.item-wrapper').empty();

            $.each(jsonData.photos, function(index, value) {

                var itemElement = $("<a/>", { href: "#", "class": "item " + jsonData.photos[index].uniqueId });
                var imageElement = $("<img/>", { src: jsonData.photos[index].thumbnail });

                itemElement.append(imageElement);

                $('.item-wrapper').append(itemElement);

                $("." + currentPhotoId).attr("class", "item " + currentPhotoId + " selected");

                $(".item").unbind("click", itemClickHandler);
                $(".item").bind("click", itemClickHandler);

            });

            $(".total-photos").html(jsonData.photoCount);
            self.setPhotoArrows();

            var startIndex = ((parseInt(currentThumbPage) - 1) * 21) + 1;
            var endIndex = parseInt(currentThumbPage) * 21;

            if (endIndex > parseInt($(".total-photos").html())) {
                endIndex = parseInt($(".total-photos").html());
            }

            $(".current-photos").html(startIndex + "-" + endIndex);

        };

        this.setPhotoArrows = function() {

            if (currentThumbPage > 1) {
                $(".arrow-previous").removeClass("disabled");
            } else {
                $(".arrow-previous").addClass("disabled");
            }

            if (currentThumbPage >= parseInt($(".total-photos").html()) / 21) {
                $(".arrow-next").addClass("disabled");
            } else {
                $(".arrow-next").removeClass("disabled");
            }
        };

        this.onFlagClicked = function(event) {

            if (userNotLoggedIn) {
                tooltip.Show($(this));
            } else {
                if (!$(this).hasClass("disabled")) {
                    panel.Show($(event.target));

                }
            }

            return false;
        };

        this.setCurrentPhoto = function(jsonData) {

            currentPhotoId = jsonData.uniqueId;

            $(".details h2").text(jsonData.title);
            $("p.description").text(jsonData.description);
            $(".tags span.black").html(jsonData.tags);
            $(".source").text("Source: " + jsonData.source);
            $(".article").attr("href", jsonData.article);

            favoriteDisabled = jsonData.userVariables.Data.favDisabled;
            flagDisabled = jsonData.userVariables.Data.flaggedDisabled;

            $("a.favorite").parent().find("p").text(jsonData.userVariables.Data.favorite);
            $("a.flag").parent().find("p").text(jsonData.userVariables.Data.flag);

            $("a.favorite").parent().removeClass("disabled");
            $("a.favorite").parent().addClass(favoriteDisabled);

            $("a.flag").parent().removeClass("disabled");
            $("a.flag").parent().addClass(flagDisabled);

            $("a.comments").parent().find("p").html("Comments(" + jsonData.commentsNumber + ")");          

            averageRating = jsonData.ratingVariables.Data.average;
            photoRated = jsonData.ratingVariables.Data.rated;

            currentPhotoUrl = jsonData.fullscreenPath;
            currentPosition = jsonData.position + 1;   
            currentPhoto = jsonData.id;        

            $("div.buttons span.position").html(currentPosition + "/" + $(".total-photos").html());
            $("div.buttons span.title").html(jsonData.title);

            if(currentPosition == $(".total-photos").html())
            {
                 $(".slideshow").text("Start slideshow");
                window.clearInterval(slideInterval);
                slideInterval = "";
                }

            $(".image-container img").fadeOut("fast", function() {

                $(".image-container img").remove();
                imageElement = $("<img/>", { src: jsonData.filePath });
                $(".image-container div.controls").before(imageElement);

            });

            $("." + currentPhotoId).attr("class", ("item " + currentPhotoId + " selected"));

            if (jsonData.previous != "") {

                previous = jsonData.previous;

            } else {
                if (!$("a.previous").hasClass("disabled")) {
                    $("a.previous").addClass("disabled");
                }

            }

            if (jsonData.next != "") {

                next = jsonData.next;

            } else {
                if (!$("a.next").hasClass("disabled")) {
                    $("a.next").addClass("disabled");
                }
            }

            $(".current-rating").css({
                "width": (parseInt(averageRating) * 16)
            });

            if (photoRated || userNotLoggedIn) {

                $(".star-rating li a").attr("class", "disabled");

                $(".star-rating li a").click(function() {
                    tooltip.Show($(this));
                    return false;
                });
            }

            $(".image-fullscreen img").remove();
            $(".image-fullscreen").append($("<img/>", { "class": "img-fullscreen", src: jsonData.fullscreenPath }));

            if (isFullscreen) {
                $(".image-fullscreen img").hide();
                $(".image-fullscreen img").load(function() {
                    $(".image-fullscreen img").css({ "left": ($("div.image-fullscreen").width() - $("div.image-fullscreen img").width()) / 2, "top": ($("div.image-fullscreen").height() - $("div.image-fullscreen img").height()) / 2 });
                    $(".image-fullscreen img").fadeIn();
                });
            }

            var startIndex = ((parseInt(currentThumbPage) - 1) * 21) + 1;
            var endIndex = parseInt(currentThumbPage) * 21;

            if (endIndex > parseInt($(".total-photos").html())) {
                endIndex = parseInt($(".total-photos").html());
            }

            $(".current-photos").html(startIndex + "-" + endIndex);

            currentCommentPage = jsonData.defaultCommentPage;
            isFirstLoad = true;

            setRelatedPhotos(jsonData.relatedPhotos);

            self.ajaxCall(retrieveCommentsUrl, { page: currentCommentPage, threshold: commentThreshold, photoId: currentPhotoId }, refreshComments);

        };

        var setRelatedPhotos = function(relatedPhotos) {

            $("div.related div.photos a").each(function() {
                $(this).remove();
            });

            for (var i = 0; i < relatedPhotos.length; i++) {
                $("div.related div.photos").append($("<a/>", { "class": "item " + relatedPhotos[i].relatedPhotoUID, href: relatedPhotos[i].relatedPhotoUrl }).append($("<img/>", { src: relatedPhotos[i].relatedPhotoThumb }), $("<span/>", { "class": "black title", innerHTML: relatedPhotos[i].relatedPhotoTitle })));
                $(".item").unbind("click", itemClickHandler);
                $(".item").bind("click", itemClickHandler);
            }
        }

        this.sortPhotos = function(sortBy) {

            if (sortMethod != sortBy) {

                sortMethod = sortBy;

                if (sortMethod == "views") {
                    $("#recent").attr("class", "sort");
                    $("#popular").attr("class", "sort selected");
                } else {
                    $("#recent").attr("class", "sort selected");
                    $("#popular").attr("class", "sort");
                }

                self.getPhotoThumbs(1);
            }
        };

        this.disableFavoriteButton = function(jsonData) {

            $('a.favorite').parent().find("p").text('Added to favorites');
            $('a.favorite').parent().addClass("disabled");
        };

        this.disableFlagButton = function(jsonData) {

            panel.Hide($(".flag-dialog"));

            $('a.flag').parent().find("p").text('Flagged');
            $('a.flag').parent().addClass("disabled");

        };

        this.setPhotoRating = function(jsonData) {
            $(".current-rating").css({
                "width": currentRating
            });
            $(".star-rating li a").css({
                "background": "url(../img/ratings.png) top left"
            });
            $(".star-rating li a").click(function() {

                return false;
            });
        };
        var refreshComments = function(jsonData) {

            $("div.comment").remove();

            if (jsonData.comments != undefined) {

                for (var i = (jsonData.comments.length - 1); i >= 0; i--) {
                    addComment(jsonData.comments[i]);
                }
            }
           
            $(".header p span").html("(" + jsonData.usableComments + ")");

            $("div.pagination").remove();
            $("div#comments").append($("<div/>", { "class": "pagination" }));

            if (jsonData.totalComments != undefined) {
                commentNumber = jsonData.totalComments;

                $("div.button .comments").parent().find("p").text("Comments(" + commentNumber + ")");
            }

            if (jsonData.usableComments > 0) {
                $(".pagination").pagination(jsonData.usableComments, { items_per_page: commentsPerPage,
                    num_display_entries: 5,
                    current_page: currentCommentPage - 1,
                    num_edge_entries: 1,
                    link_to: "#",
                    prev_text: "&nbsp;&nbsp;&nbsp;",
                    next_text: "&nbsp;&nbsp;&nbsp;",
                    ellipse_text: "...",
                    prev_show_always: true,
                    next_show_always: true,
                    callback: function(page_index, jq) { currentCommentPage = page_index + 1; onNextButtonClick(currentCommentPage); return false; }
                });
            }

            if (jsonData.usableComments <= 10) {
                $(".pagination").hide();
            } else {
                $(".pagination").show();
            }

            if (isFirstLoad) {
                var focusCommentId = self.getUrlVars()["focusComment"];
                var commentId = "#comment" + focusCommentId;

                if (focusCommentId != undefined) {
                    $(document).scrollTop($(commentId).position().top);
                }
            }

        };

        this.getUrlVars = function() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        };
        var onNextButtonClick = function(currentCommentPage) {

            self.getComments(currentCommentPage, commentThreshold);

        };

        var addComment = function(jsonData) {

            var comment = $("<div/>", { "class": "comment", id: "comment" + jsonData.id });
            var img = $("<img/>", { src: jsonData.userThumbnail });
            var items = $("<div/>", { "class": "items" });
            var user = $("<a/>", { innerHTML: jsonData.user, href: "/UserProfile/" + jsonData.user });
            var userReply = $("<a/>", { innerHTML: jsonData.replyUser, href: "/UserProfile/" + jsonData.replyUser });
            var info = $("<p/>", { "class": "publish-details" });
            var hiddenDiv = $("<div/>", { "class": "hide" }).append($("<span/>", { innerHTML: "Comment hidden (as voted by users)" }), $("<a/>", { "class": "show", innerHTML: "Show &rsaquo;", href: "#" }));
            var div = $("<div/>", { "class": "visible" });
            var quote = $("<p/>", { "class": jsonData.quote, text: jsonData.replyText });
            var body = $("<p/>", { "class": "body", text: jsonData.body });
            var vote = $("<div/>", { "class": "vote" });
            var hidden = $("<input/>", { type: "hidden", value: jsonData.id });
            var hidden1 = $("<input/>", { type: "hidden", id: "commentOwnerId", value: jsonData.commentOwnerId });
            var reply = $("<a/>", { "class": "reply", href: "javascript:void(0);", innerHTML: "Reply &rsaquo;" });
            var upButton = $("<a/>", { "class": "up " + jsonData.disabled, href: "javascript:void(0);" });
            var upText = $("<span/>", { "class": "up", innerHTML: jsonData.upRating });
            var separator = $("<div/>");
            var downButton = $("<a/>", { "class": "down " + jsonData.disabled, href: "javascript:void(0);" });
            var downText = $("<span/>", { "class": "down", innerHTML: jsonData.downRating });
            var permalink = $("<a/>", { "class": "permalink", text: "Permalink" }).attr("href", "#");           

            info.append("by ", user, ", " + jsonData.date, jsonData.response, userReply);

            vote.append(hidden, hidden1,reply, upButton, upText, separator, downButton, downText, permalink);
            div.append(quote, body, vote);
            items.append(info, hiddenDiv, div);
            comment.append(img, items);

            $("div#comments").prepend(comment);

            reply.bind("click", replyClickHandler);
            upButton.bind("click", upRatingClickHandler);
            downButton.bind("click", downRatingClickHandler);

            $("div.vote").delegate("a.permalink", "click", function() {

                var permalinkId = $(this).parent().find("input").val().toString();

                var location = window.location.toString().split("?")[0];

                location += "?focusComment=" + permalinkId;
                $.cookie("focusComment", permalinkId, {path: '/'});

                if (self.getUrlVars()["videoId"] != undefined) {
                    location += "&videoId=" + self.getUrlVars()["videoId"];
                }

                window.location = location;

                return false;

            });

            
            $("div.comment img").each(function () {
                if ($(this).attr('src') == '' || $(this).attr('src') == 'a') {
                    $(this).attr("src", defaultUserIconPath);
                }
            });

            $("a.show").click(function() {
                $(this).parent().parent().parent().find("div.hide").hide();
                $(this).parent().parent().parent().find("div.visible").show();

                return false;
            });

            if (jsonData.downRating > maximumNegativeRatings) {
                $(comment).addClass("hidden");
            }
        };
        var addNewComment = function(jsonData) {

            $("#descriptionInput").val("");
            $(".post p.reply-to").html("");

            $("div.button .comments").parent().find("p").text("Comments(" + ++commentNumber + ")");
            $(".header p span").html("(" + commentNumber + ")");

            replyQuote = "";
            replyUser = "";

            $("div#comments div.post img").attr('src', createCaptchaUrl + "?id=" + (++captchaId).toString());
            $("p.error").hide();
            $("p.label").show();
            $("div.post input").removeClass('error');
            $("div.post div.verify-code").removeClass('error');
            $("div.post input").val("");

            currentCommentPage = 0;

            self.getComments(currentCommentPage, commentThreshold);
        };

        var updateCommentRating = function(jsonData) {

            var currentInput = $("input[value=" + jsonData.commentId + "]");

            if (parseInt(jsonData.ratingValue) == 1) {

                var currentValue = parseInt(currentInput.parent().children("span.up").html());
                currentInput.parent().children("span.up").html(currentValue + 1);
            } else {

                var currentValue = parseInt(currentInput.parent().children("span.down").html());
                currentInput.parent().children("span.down").html(currentValue + 1);
            }

            currentInput.parent().children("a.up").addClass("disabled");
            currentInput.parent().children("a.down").addClass("disabled");
        };
        /*******************************
        Server communication
        */
        this.ajaxCall = function(postUrl, jsonData, successCallback) {

            $.ajax({
                url: postUrl,
                type: 'POST',
                cache: false,
                data: jsonData,
                dataType: 'json',
                error: function(error) {

                },
                success: function(jsonData) {
                    successCallback(jsonData);
                }
            });
        };

        this.getCurrentPhoto = function(photoId) {
                        
            if ($(".item-wrapper>a.selected").attr("class") != null) {
                $(".item-wrapper>a.selected").attr("class", $(".item-wrapper>a.selected").attr("class").replace(" selected", ""));
            }

            var photoUniqueId = photoId;

            var data = { photoUid: photoUniqueId, sortBy: sortMethod, category: currentCategory };

            self.ajaxCall(photoDetailsUrl, data, self.setCurrentPhoto);

        };

        this.getPhotoThumbs = function(thumbPage) {

            if (currentThumbPage != thumbPage) {
                currentThumbPage = thumbPage;
            }
            
            var data = { page: thumbPage, sortBy: sortMethod, category: currentCategory };

            self.ajaxCall(photoListUrl, data, self.populateThumbnails);

        };

        this.addToFavorites = function() {

            if (userNotLoggedIn) {
                tooltip.Show($(this));
            } else {
                if (!$(this).hasClass("disabled")) {
                    var data = { photoId: currentPhotoId };

                    self.ajaxCall(favoritePhotoUrl, data, self.disableFavoriteButton);
                }
            }
        };

        this.flagPhoto = function() {

            var flagMessage = $(".flag-dialog textarea").val();

            var data = { photoId: currentPhotoId, message: flagMessage };

            self.ajaxCall(flagPhotoUrl, data, self.disableFlagButton);

            return false;

        };

        this.sendRating = function(value) {

            currentRating = value * 16;

            var data = { rating: value, photoId: currentPhotoId };

            self.ajaxCall(ratePhotoUrl, data, self.setPhotoRating);

        };
        var submitComment = function() {

            if (userNotLoggedIn) {
                tooltip.Show($(this));
            } else {
                var body = $("#descriptionInput").attr('value');
                var replyToText = replyQuote;
                var replyToUser = replyUser;

                var inputValue = $("input.verify-code").val();

                $.ajax({
                    url: verifyCaptchaUrl,
                    type: "POST",
                    cache: false,
                    data: { value: inputValue },
                    dataType: "json",
                    success: function(jsonData) {

                        if (jsonData.valid == false) {

                            $("div#comments div.post img").attr('src', createCaptchaUrl + "?id=" + (++captchaId).toString());
                            $("p.error").show();
                            $("p.label").hide();
                            $("div.post input").addClass('error');
                            $("div.post div.verify-code").addClass('error');

                        } else {

                            self.ajaxCall(submitCommentUrl, { comment: body, photoId: currentPhotoId, replyText: replyToText, replyUser: replyToUser }, addNewComment);
                        }
                    }

                });


            }

            return false;
        };

        this.getComments = function(pageNumber, commentThreshold) {

            currentCommentPage = pageNumber;
            isFirstLoad = false;
            self.ajaxCall(retrieveCommentsUrl, { page: pageNumber, threshold: commentThreshold, photoId: currentPhotoId }, refreshComments);
            $(this).scrollTop($('div.header').position().top);
        };
        /*******************************
        Handlers
        */
        var exitFullscreenHandler = function() {

            $("div.fullscreen").hide();
            isFullscreen = false;
        };

        var fullscreenClickHandler = function() {

            $("div.image-fullscreen img").show();

            $("div.fullscreen").show();

            $("div.background").css({
                "top": "0px",
                "left": "0px",
                "width": $(document).width(),
                "height": $(document).height()

            });

            $(".image-fullscreen").css({ "position": "fixed", "left": ($(window).width() - $("div.image-fullscreen").width()) / 2, "top": ($(window).height() - $("div.image-fullscreen").height()) / 2 });

            $(".image-fullscreen div.controls").css({ "left": ($("div.image-fullscreen").width() - $("div.image-fullscreen div.controls").width()) / 2 });

            $(".image-fullscreen img").css({ "left": ($("div.image-fullscreen").width() - $("div.image-fullscreen img").width()) / 2, "top": ($("div.image-fullscreen").height() - $("div.image-fullscreen img").height()) / 2 });

            $(".image-fullscreen a.previous").css({ "left": ($("div.image-fullscreen").position().left + 10) });

            $(".image-fullscreen a.next").css({ "left": ($("div.image-fullscreen").position().left + 880) });

            isFullscreen = true;

            return false;
        };

        var previousClickHandler = function() {

            if (!$(this).hasClass("disabled")) {

                $("a.next").removeClass("disabled");
                window.location = "/Photo#" + previous;

                self.getCurrentPhoto(previous);
            }

            return false;
        };

        var nextClickHandler = function() {

            if (!$(this).hasClass("disabled")) {

                $("a.previous").removeClass("disabled");

                window.location = "/Photo#" + next;

                self.getCurrentPhoto(next);
            }

            return false;
        };

        var itemClickHandler = function() {

            window.location = "/Photo#" + $(this).attr("class").split(' ')[1];

            self.getCurrentPhoto($(this).attr("class").split(' ')[1]);

            return false;

        };

        var thumbsPreviousClickHandler = function() {

            if (!$(this).hasClass("disabled")) {
                currentThumbPage--;
                self.getPhotoThumbs(currentThumbPage);
            }
            return false;
        };

        var thumbsNextClickHandler = function() {

            if (!$(this).hasClass("disabled")) {
                currentThumbPage++;
                self.getPhotoThumbs(currentThumbPage);
            }
            return false;
        };

        var slideshowClickHandler = function() {

            if (slideInterval == "") {

                $(".slideshow").text("Stop slideshow");

                slideInterval = window.setInterval(function() {
                    window.location = "/Photo#" + next;
                    self.getCurrentPhoto(next);
                }, 5000);

            } else {

                $(".slideshow").text("Start slideshow");
                window.clearInterval(slideInterval);
                slideInterval = "";

            }

            return false;
        };

        var upRatingClickHandler = function(event) {

            var $target = $(event.target);

            if (userNotLoggedIn) {
                tooltip.Show($target);
            } else {
                if (!$target.hasClass("disabled")) {

                    var id = $target.parent().children('input').val();
                    var voteValue = $target.attr("class").trim();

                    self.ajaxCall(submitCommentRatingUrl, { commentId: id, rating: voteValue }, updateCommentRating);
                }
            }
            return false;
        };

        var downRatingClickHandler = function(event) {

            var $target = $(event.target);

            if (userNotLoggedIn) {
                tooltip.Show($target);
            } else {
                if (!$target.hasClass("disabled")) {
                    var id = $target.parent().children('input').val();
                    var voteValue = $target.attr("class").trim();


                    self.ajaxCall(submitCommentRatingUrl, { commentId: id, rating: voteValue }, updateCommentRating);
                }
            }
            return false;
        };

        var replyClickHandler = function(event) {
         if (userNotLoggedIn) {
                tooltip.Show($target);
            } else {
            var $target = $(event.target);

            var content = $target.parent().parent().children(".body").html();
            var user = $target.parent().parent().parent().children("p").children("a").first().html();

            replyQuote = content;
            replyUser = user;

            $(".post p.reply-to").html('in response to <span>' + replyUser + '</span>');

            $("div.post a.submit").focus();
            $("#descriptionInput").focus();
            }
        };

        var subscribeClickHandler = function() {
            window.open(commentFeedUrl + "/" + currentPhoto, "_blank");
            return false;
        };

        var codeClickHandler = function() {

            $("div.post img").attr("src", createCaptchaUrl + "?id=" + (++captchaId).toString());

            return false;
        };
        var menuSearchClicked = function() {

            var searchWord = $("input[name=search-keywords]").val().trim();

            if (searchWord != "" && searchWord != "search") {

                window.location = "/Photo/Search?searchWord=" + searchWord;
            }

            return false;
        };

        var searchInputKeypress = function(event) {

            var searchWord = $(this).val().trim();
            var charCode;

            if (event && event.which) {
                charCode = event.which;
            } else if (window.event) {
                event = window.event;
                charCode = event.keyCode;
            }
            if (charCode == '13' && searchWord != "" && searchWord != "search") {
                window.location = "/Photo/Search?searchWord=" + searchWord;

            }
        };

        var searchInputClicked = function() {

            $(this).attr('value', "");
        };
        /*******************************
        Initialize everything
        */
        (this.Init = function() {

            self.setDialogClose(".flag-dialog");

            self.getCurrentPhoto(window.location.hash.toString().split('?')[0].split("#")[1]);

            panel = new PipenoUI.ShowPanel($(".flag-dialog"), { placement: "bottom", align: "left" });

            uicombo = new PipenoUI.ComboBox($(".combo-box:first"));
            
            if (commentsNumber <= commentsPerPage) {
                $(".pagination").hide();
            }

            if (currentCategory != "") {
                $(".combo-box div").html(currentCategory);
            }

            $(uicombo).bind("change", function(event, oldValue, newValue) {

                currentCategory = newValue;

                if (newValue == "All Categories") {
                    currentCategory = "";
                }

                self.getPhotoThumbs(1);
            });

            var comboComments = new PipenoUI.ComboBox($("div.header .combo-box:first"));

            $(comboComments).bind("change", function(event, oldValue, newValue) {

                commentThreshold = newValue;

                if (newValue == "All comments")
                    commentThreshold = -1;

                currentCommentPage = 0;

                self.getComments(0, commentThreshold);
            });

            var tooltipContainer = $("#dynamic-html div.tooltip-form-login:eq(0)");
            tooltip = new PipenoUI.ShowPanel(tooltipContainer, { placement: "bottom", align: "right" });

            $("div.tooltip-form-login a.close").click(function() {

                tooltip.Hide($(tooltipContainer));

                return false;
            });
            self.setPhotoArrows();

            self.setDialogClose(".flag-dialog");

            $(".item").bind("click", itemClickHandler);

            $(".arrow-previous").bind("click", thumbsPreviousClickHandler);

            $(".arrow-next").bind("click", thumbsNextClickHandler);

            $("a.next").bind("click", nextClickHandler);

            $("a.previous").bind("click", previousClickHandler);

            $(".slideshow").bind("click", slideshowClickHandler);

            $("div.image-container a.fullscreen").bind("click", fullscreenClickHandler);

            $("div.image-fullscreen a.fullscreen").bind("click", exitFullscreenHandler);

            $(".image-container").hover(
                        function() {

                            $(this).css({ "cursor": "pointer" });
                            $("div.slider div.controls").show();

                        },
                        function() {
                            $("div.slider div.controls").hide();
                        });


            $("div.image-fullscreen").hover(
                        function() {

                            $(this).css({ "cursor": "pointer" });
                            $("div.image-fullscreen div.controls").show();
                            $("div.image-fullscreen > a").show();

                        },
                        function() {
                            $("div.image-fullscreen > a").hide();
                            $("div.image-fullscreen div.controls").hide();
                        });

            //Press Escape event!  
            $(document).keypress(function(e) {
                if (e.keyCode == 27) {
                    exitFullscreenHandler();
                }
            });

            $(".post a.submit").bind("click", submitComment);

            $("a.code").bind("click", codeClickHandler);

            $("a.reply").bind("click", replyClickHandler);

            $("a.up").bind("click", upRatingClickHandler);

            $("a.down").bind("click", downRatingClickHandler);

            $("a.subscribe").bind("click", subscribeClickHandler);

            $("div.post input").click(function() {
                $("div.post input").removeClass('error');
                $("div.post div.verify-code").removeClass('error');
            });

            $("a.comments").parent().click(function() {
                $(document).scrollTop($('div.header').position().top);
                return false;
            });

            if (!$('a.favorite').parent().hasClass("disabled")) {
                $("a.favorite").parent().bind("click", self.addToFavorites);
            }

            if (!$('a.flag').parent().hasClass("disabled")) {
                $("a.flag").parent().bind("click", self.onFlagClicked);
            }

            $("#menu-bar div.search input").bind("click", searchInputClicked);
            $('#menu-bar div.search input').bind("keypress", searchInputKeypress);
            $("#menu-bar div.search a").bind("click", menuSearchClicked);
            $("div.image-fullscreen > a").hover(function(event) { event.preventDefault() });

        })();
    };
    /*#endregion*/

})(window);
/* End Of File */
