//
// Site
//
; (function(window) {

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

    /*#region Site -> Article*/

    Site.Article = function() {

        /*******************************
        Variables
        */
        var currentCommentPage = 1;
        var currentPhotoUrl;
        var previousVideoId;
        var nextVideoId;
        var previousPhoto;
        var nextPhoto;
        var panel;
        var shortUrlPanel;
        var article;
        var slideInterval = "";
        var isFullscreen = false;
        var replyQuote = "";
        var replyUser = "";
        var uicombo;
        var tooltip;
        var homePostForm;
        var srticlePortForm;
        var self = this;
        var captchaId = 1;

        /*******************************
        Page actions
        */
        var getCurrentArticlePage = function() {

            var stringArray = window.location.toString().split('/');

            if (parseInt(stringArray[stringArray.length - 1]) > 1) {

                return stringArray[stringArray.length - 1];
            } else {
                return 1;
            }
        };

        //disable the Favorite button after an article has been added to favorite
        var articleFavorited = function(jsonData) {

            $('.favorite').parent().children("p").text(jsonData.favoriteText);
            $('.favorite').parent().addClass("disabled");

            $("div.community span.reactions").html(parseInt($("div.community span.reactions").html()) + 1);

        };

        //disable the Recommend button after an article has been recommended
        var articleRecommended = function(jsonData) {

            $('.recommend').parent().children("p").text(jsonData.recommendText);
            $('.recommend').parent().addClass("disabled");

            $("div.community span.recommends").html(parseInt($("div.community span.recommends").html()) + 1);
            $("div.community span.reactions").html(parseInt($("div.community span.reactions").html()) + 1);

        };

        //disable the Flag button after an article has been added to favorite
        var disableFlagButton = function(jsonData) {

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

            $('.flag').parent().children("p").text(jsonData.flagText);
            $('.flag').parent().addClass("disabled");

            $("div.community span.reactions").html(parseInt($("div.community span.reactions").html()) + 1);

        };

        //handler for the Print button click event
        var onPrintClicked = function() {

            window.print();

        };

        var setDialogClose = function(dialogClassName) {

            $(document).click(function() {
                panel.Hide($(dialogClassName));
                tooltip.Hide();

            });

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

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

                panel.Hide($(dialogClassName));
                shortUrlPanel.Hide($(dialogClassName));
                return false;
            });
        };

        var populatePanel = function(jsonData) {

            var panelList = $("#" + jsonData.sortBy).parent().parent().children(".panel").children("ul");
            panelList.empty();

            for (var i = 0; i < jsonData.articleArray.length; i++) {

                var listItem = $("<li/>");
                var anchorItem = $("<a/>", { href: jsonData.articleArray[i].url, target: "_blank" });

                anchorItem.text(jsonData.articleArray[i].title);
                listItem.append(anchorItem);

                panelList.append(listItem);
            }

        };

        var setVideo = function(jsonData) {
            player.setUpPlayer(jsonData.videoId, jsonData.autoPlay, jsonData.previousId, jsonData.nextId);           
            previousVideoId = jsonData.previousId;
            nextVideoId = jsonData.nextId;

            if(previousVideoId == "")
            {
                $("a.previous-video").addClass("disabled");
            }else {
                $("a.previous-video").removeClass("disabled");
            }

            if(nextVideoId == "")
            {
                $("a.next-video").addClass("disabled");
            }else {
                $("a.next-video").removeClass("disabled");
            }
            if(jsonData.title.length > 100)
            {
                $(".video-container div.band div.info span").html(jsonData.title.substring(0, 97) + "...");
            } else {
                 $(".video-container div.band div.info span").html(jsonData.title);
            }
        };

        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("fast");
        };

        this.setCurrentPhoto = function(jsonData) {
            var currentPhotoId = jsonData.uniqueId;
            currentPhotoUrl = jsonData.fullscreenPath;
            var currentPosition = jsonData.position + 1;
            var previousArrow = $("div.buttons a.previous-image");
            var nextArrow = $("div.buttons a.next-image");

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

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

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

            if (jsonData.previous != "") {

                previousPhoto = jsonData.previous;

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

            if (jsonData.next != "") {

                nextPhoto = jsonData.next;

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

            if (!$('.' + currentPhotoId).hasClass("selected")) {
                $('.' + currentPhotoId).addClass("selected");
            }

            $(".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 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 + ")");
            $(this).scrollTop($('div.header').position().top);

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

            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();
            }

        };

        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, "class":"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", value: jsonData.ownerUserId, id : "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", "#");
            var separator1 = $("<div/>", {"class": "separator"});
            var gift = $("<a/>", { "class": "gift", text: "Send Gift" }).attr("href", "#");

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

            vote.append(hidden, hidden1, reply, upButton, upText, separator, downButton, downText, permalink, separator1, gift);
            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;

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

                window.location = location;

                return false;

            });
            $(".comment .gift").bind("click", function(){ sendGiftClickHandler(this, $(this).parent().find('input[type=hidden]').val(), 'Comment', $(this).parent().parent().parent().parent().find('.user').text(), $(this).parent().parent().find('input#commentOwnerId').val()); return false; });
            $("div.comment img[src='']").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("");
            var commentsNumber = parseInt($(".community span.comments-number").html());
            var reactionsNumber = parseInt($(".community span.reactions").html());

            $(".community span.comments-number").html(++commentsNumber);
            $(".header p span").html("(" + commentsNumber + ")");
            $(".community span.reactions").html(++reactionsNumber);

            replyQuote = "";
            replyUser = "";

            $("div#comments div.post img").attr('src', createCaptchaImageUrl + "?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("");

            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
        */

        //Makes a POST request sending data to the ActionScript code
        //functionName - name of the ActionScript function that receives the data
        //postData - the JSON object to be sent
        //successCallback - the function name to be called in case of success
        var ajaxCall = function(postUrl, postData, successCallback, errorCallback) {
            $.ajax({
                url: postUrl,
                type: 'POST',
                cache: false,
                data: postData,
                dataType: 'json',
                error: function(error) {
                    // errorCallback(error);
                },
                success: function(jsonData) {
                    successCallback(jsonData);
                }
            });
        };

        //Sends data necessary for reporting an article
        this.flagArticle = function(flagMessage) {

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

            var data = { articleId: currentArticleId, message: flagMessage };

            ajaxCall(flagArticleUrl, data, disableFlagButton);
            return false;

        };

        //Sends data necessary for adding an article to favorites
        var favoriteArticle = function() {

            ajaxCall(favoriteArticleUrl, { articleId: currentArticleId }, articleFavorited);

        };

        //Sends data necessary for recommending an article  
        var recommendArticle = function(articleID) {

            ajaxCall(recommendArticleUrl, { articleId: currentArticleId }, articleRecommended);

        };

        var getArticleList = function(sortBy) {
            ajaxCall(articleListUrl, { articleId: currentArticleId, sortMethod: sortBy }, populatePanel);
        };

        var submitComment = function() {

            if (noLoginUser) {
                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', createCaptchaImageUrl + "?id=" + (++captchaId).toString());
                            $("p.error").show();
                            $("p.label").hide();
                            $("div.post input").addClass('error');
                            $("div.post div.verify-code").addClass('error');

                        } else {

                            ajaxCall(submitCommentUrl, { comment: body, articleId: currentArticleId, replyText: replyToText, replyUser: replyToUser }, addNewComment);
                        }
                    }

                });


            }

            return false;
        };

        this.getPreviousNextVideos = function(videoId) {
            ajaxCall(videoDetailsUrl, { articleId: currentArticleId, videoYoutubeId: videoId }, setVideo);
        };

        this.getCurrentPhoto = function(photoId) {

            var photoUniqueId = photoId;

            var data = { photoUid: photoUniqueId, articleId: currentArticleId };

            ajaxCall(photoDetailsUrl, data, self.setCurrentPhoto);

        };

        this.getComments = function(pageNumber, commentThreshold) {

            currentCommentPage = pageNumber;
            ajaxCall(retrieveCommentsUrl, { page: pageNumber, threshold: commentThreshold, articleId: currentArticleId }, refreshComments);
        };

        /*******************************
        Handlers
        */
        //handler for the Previous article page button click event
        var previousPageClickHandler = function() {

            currentArticlePage--;

            postForm.AddItem("page", currentArticlePage);
            postForm.Submit();

            return false;
        };

        //handler for the NExt article page button click event
        var nextPageClickHandler = function() {

            currentArticlePage++;

            postForm.AddItem("page", currentArticlePage);
            postForm.Submit();

            return false;
        };

        var recommendClickHandler = function() {

            if (noLoginUser) {
                tooltip.Show($(this));
            } else {
                if (!$(this).hasClass("disabled")) {

                    recommendArticle(currentArticleId);
                }

            }

            return false;
        };

        var sendGiftClickHandler = function(self, sourceIdParam, sourceTypeParam, forUserNameParam, forUserIdParam) {
            if (noLoginUser) {
                tooltip.Show($(self));
            } else {
                sourceId = sourceIdParam;
                giftSourceType = sourceTypeParam;
                forUserName = forUserNameParam;
                forUserId = forUserIdParam;
                $('.overlay-gifts').show();
                window.scroll(0,0);
            }

            return false;
        }

        var favoriteClickHandler = function(e) {
            if (noLoginUser) {
                showLoginTooltip(this, e);
            } else {
                if (!$(this).hasClass("disabled")) {
                    favoriteArticle(currentArticleId);
                }
            }
            return false;
        };

        var flagClickHandler = function(event) {
            if (noLoginUser) {
                showLoginTooltip(this, event);
            } else {
                if (!$(this).hasClass("disabled")) {
                    panel.Show($(event.target));

                }
            }

            return false;
        };

        var shortUrlClickHandler = function(event) {

            if (!$(this).hasClass("disabled")) {
                shortUrlPanel.Show($(event.target));

                setDialogClose(".short-dialog");
            }


            return false;
        };

        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-image").css({ "left": ($("div.image-fullscreen").position().left + 10) });

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

            isFullscreen = true;

            return false;
        };

        var previousClickHandler = function() {

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

                $("a.next-image").removeClass("disabled");

                self.getCurrentPhoto(previousPhoto);
            }

            return false;
        };

        var nextClickHandler = function() {

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

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

                self.getCurrentPhoto(nextPhoto);
            }

            return false;
        };

        var videosClickHandler = function(event) {
            var $target = $(event.target);

            if (!$target.hasClass("selected")) {

                $target.addClass("selected");
                $(".photos").removeClass("selected");

                setUpPlayer(defaultVideoUId);

                $(".image-container").hide();
                $(".video-container").show();
                $(".video-carousel").show();
                $(".photo-carousel").hide();

            }

            return false;
        };

        var photosClickHandler = function(event) {

            var $target = $(event.target);

            if (!$target.hasClass("selected")) {

                $target.addClass("selected");
                $(".videos").removeClass("selected");

                self.getCurrentPhoto("");

                $(".image-container").show();
                $(".video-container").hide();
                $(".video-carousel").hide();
                $(".photo-carousel").show();

                $('.photo-carousel').jcarousel({
                    itemLoadCallback: self.photoCarouselItemLoadCallback,
                    size: parseInt(totalPhotos)


                });

            }

            return false;
        };



        var slideshowClickHandler = function() {

            if (slideInterval == "") {

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

                slideInterval = window.setInterval(function() {

                    self.getCurrentPhoto(nextPhoto);
                }, 5000);

            } else {

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

            }

            return false;

        };


        var upRatingClickHandler = function(event) {

            var $target = $(event.target);

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

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

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

        var downRatingClickHandler = function(event) {

            var $target = $(event.target);

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


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

        var replyClickHandler = function(event) {

            if (noLoginUser) {
                tooltip.Show($(this));
            } 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();
                window.scrollTo(0, $(document).height());

                //$(document).scrollTop($("#descriptionInput").position().top);
                
            }

            return false;
        };


        var printClickHandler = function(event) {
            window.print();
        };

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

        var codeClickHandler = function() {

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

            return false;
        };
        function filterClickHandler(event) {

            var target = $(event.target);

            homePostForm.AddItem("sort", target.attr("id"));
            homePostForm.Submit();
        };

        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;
        };

        

        /*******************************
        Initialize everything
        */
        (this.Init = function() {


            $(".pagination").pagination(commentNumber, { items_per_page: commentsPerPage,
                num_display_entries: 5,
                current_page: currentCommentPage - 1,
                num_edge_entries: 1,
                link_to: "#",
                prev_text: prevText,
                next_text: nextText,
                ellipse_text: "...",
                prev_show_always: true,
                next_show_always: true,
                callback: function(page_index, jq) { currentCommentPage = page_index + 1; onNextButtonClick(currentCommentPage); return false; }
            });
            
            if (parseInt(photoNumber) > 0 && (parseInt(totalVideos) == 0 || totalVideos == "")) {
                $(".photos").click();
            }

            if (commentNumber <= commentsPerPage) {
                $(".pagination").hide();
            }

            uicombo = new PipenoUI.ComboBox($(".combo-box:first"));

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

                commentThreshold = newValue;

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

                currentCommentPage = 1;

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

            setDialogClose(".flag-dialog");

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

            homePostForm = new PipenoUI.SubmitForm("/Category/" + categoryTitleNormalized, {});
            postForm = new PipenoUI.SubmitForm(window.location.toString().split("?")[0], {});

            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;
            });

            $("div.previous").bind("click", previousPageClickHandler);
            $("div.next").bind("click", nextPageClickHandler);

            $(".panel-button").children().bind("click", panelButtonClickHandler);

            $("div.tab.container a.see-all").bind("click", { form: homePostForm }, seeAllButtonClicked);

            $("a.next-image").bind("click", nextClickHandler);
            $("a.previous-image").bind("click", previousClickHandler);
            $(".slideshow").bind("click", slideshowClickHandler);
            $("div.image-container a.fullscreen").bind("click", fullscreenClickHandler);
            $("div.image-fullscreen a.fullscreen").bind("click", exitFullscreenHandler);
            $(".favorite").bind("click", favoriteClickHandler);
            $(".flag").parent().bind("click", flagClickHandler);
            $(".short-url").parent().bind("click", shortUrlClickHandler);
            $(".recommend").parent().bind("click", recommendClickHandler);
            
            $(".send").parent().bind("click", function(){ sendGiftClickHandler(this, currentArticleId, 'Article', articleAuthor, forUserId); return false; });
            $(".comment .gift").bind("click", function(){ sendGiftClickHandler(this, $(this).parent().find('input[type=hidden]').val(), 'Comment', $(this).parent().parent().parent().parent().find('.user').text(), $(this).parent().parent().find('input#commentOwnerId').val()); return false; });
            $(".print").parent().bind("click", printClickHandler);
            $("a.filter").bind("click", filterClickHandler);

            $(".band").hide();
            $("div.overlays img.left").hide();
            $("div.overlays img.right").hide();

            $("div.post input").val("");

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

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

                        },
                        function() {
                            $("div.image-container  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();
                        });

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

                            $(this).css({ "cursor": "pointer" });
                            $(".band").show();

                        },
                        function() {
                            $(".band").hide();

                        }
                );


            $(".videos").bind("click", videosClickHandler);
            $(".photos").bind("click", photosClickHandler);

            //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);
            $(".flag-dialog a.submit").bind("click", self.flagArticle);

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

            $("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;

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

                window.location = location;

                return false;

            });

            $("#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.short-dialog input").bind("click", function() {

                document.getElementById("url").focus();
                document.getElementById("url").select();

                return false;
            });
                $("a.previous-video").click(function(){
                 if(!$(this).hasClass("disabled"))
             {
                if(previousVideoId != undefined)
                {
               self.getPreviousNextVideos(previousVideoId);
               }
               }
               return false;
            });

             $("a.next-video").click(function(){
             if(!$(this).hasClass("disabled"))
             {
                 if(nextVideoId != undefined){
                   self.getPreviousNextVideos(nextVideoId);
                   }
               }
                return false;
            });
            $("a.show").click(function() {

                $(this).parent().parent().parent().find("div.hide").hide();
                $(this).parent().parent().parent().find("div.visible").show();

                return false;

            }); 
            
         
            //add the gifts popup in the page
            loadGiftPopup();
            
            
        })();
    };
    /*#endregion*/

})(window);

function loadGiftPopup()
{
    var overlay = $('div.overlay-gifts');
    $(overlay).height($(document).height() + 'px');
    $(overlay).width($(document).width() + 'px');
}

/* End Of File */
