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

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

    /*#region Site -> Video Gallery*/

    Site.VideoGallery = function() {

        var uicombo;
        var replyQuote = "";
        var replyUser = "";
        var captchaId = 1;
        var postForm;
        var tooltip;
        var panel;
        var self = this;

        this.closeNoPlaylistDiv = function() {
            $(".no-playlist-div").hide();
        };

        //function called by the player
        this.setUpPlayer = function(videoId) {

            self.loadVideo(videoId);

        };

        this.onThumbsPreviousClicked = function() {
            if (!$(".arrow-previous").hasClass("disabled")) {
                currentThumbPage--;
                self.getVideoThumbs(currentThumbPage);
            }
        };

        this.onThumbsNextClicked = function() {
            if (!$(".arrow-next").hasClass("disabled")) {
                currentThumbPage++;
                self.getVideoThumbs(currentThumbPage);
            }
        };

        this.getVideoThumbs = function(thumbPage) {

            if (currentThumbPage != thumbPage) {
                currentThumbPage = thumbPage;
            }

            $.ajax({
                url: videoListUrl,
                type: 'POST',
                cache: false,
                data: { page: thumbPage, sortBy: sortMethod, category: currentCategory },
                dataType: 'json',
                error: function(error) {

                },
                success: function(jsonData) {
                      self.populateThumbnails(jsonData);
                   
                }
            });
        };

        this.sortVideos = function(sortBy) {

            if (sortMethod != sortBy) {
                sortMethod = sortBy;

                $(".sort").removeClass("selected");

                switch (sortMethod) {
                    case "date": $("#recent").addClass("selected");
                        break;
                    case "views": $("#popular").addClass("selected");
                        break;
                    case "playlist": $("#my-playlist").addClass("selected");
                        break;
                }
                self.getVideoThumbs(1);
            }

        };

        this.populateThumbnails = function(jsonData) {

            if (sortMethod == "playlist" && jsonData.videos == undefined) {
                var emptyPlaylistMessage = $("<span/>", { "class": "no-playlist-span", text: "Your playlist is empty. You can always add videos from our most popular or most recent sections. Or you can search for a specific term." });

                $(".area").children().hide();
                $(".area").before(emptyPlaylistMessage);

            } else {
                $(".no-playlist-span").hide();
                $(".area").children().show();
            }

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

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

                var clipElement = $("<a/>", { href: "javascript:videoGallery.loadVideo('" + jsonData.videos[index].uniqueId + "');", "class": "clip " + jsonData.videos[index].uniqueId });
                var imageElement = $("<img/>", { src: jsonData.videos[index].thumbnail });
                var titleElement;
                var viewsElement = $("<span/>", { "class": "light-grey views" });
                var addToPlaylistElement;
                var youtubeIdElement = $("<input/>", { type: "hidden", value: jsonData.videos[index].youtubeId });
                var previousElement = $("<input/>", { type: "hidden", value: jsonData.videos[index].previousID });
                var nextElement = $("<input/>", { type: "hidden", value: jsonData.videos[index].nextID });

                clipElement.append(imageElement, $("<span/>", { "class": "play" }));

                if (jsonData.videos[index].uniqueId == currentVideoId) {

                    titleElement = $("<span/>", { "class": "selected" });
                } else {
                    titleElement = $("<span/>", { "class": "black title" });
                }

                titleElement.html(jsonData.videos[index].title);
                clipElement.append(titleElement);

                viewsElement.html(jsonData.videos[index].views + " views");
                clipElement.append(viewsElement);

                if (sortMethod == "playlist") {

                    addToPlaylistElement = $("<span/>", { "class": "remove-from-playlist" });
                } else {

                    addToPlaylistElement = $("<span/>", { "class": "add-to-playlist" });
                }

                clipElement.append(addToPlaylistElement);
                clipElement.append(youtubeIdElement);
                clipElement.append(previousElement);
                clipElement.append(nextElement);

                $('.clip-wrapper').append(clipElement);

            });

            $(".total-videos").html(jsonData.videoCount);
            self.setClipArrows();

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

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

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

            $(".add-to-playlist").click(function(event) {

                var playlistVariableName = "playlist";
                var videoIds = "";

                if (currentUserId != "") {
                    playlistVariableName += currentUserId;
                }
                if ($.cookie(playlistVariableName) != "" && $.cookie(playlistVariableName) != null) {
                    videoIds = $.cookie(playlistVariableName);
                }

                videoIds += "," + $(this).parent().attr("class").split(" ")[1];
                videoArray = videoIds.split(',');
                $.cookie(playlistVariableName, videoIds, { path: '/' });

                $(this).hide();

                event.preventDefault();
            });


            $.each(videoArray, function(index, value) {
                if (videoArray[index] != "") {

                    $("." + videoArray[index]).children(".add-to-playlist").hide();
                }
            }
            );

            $(".remove-from-playlist").click(function(event) {
                var playlistVariableName = "playlist";
                var videoIds = "";

                if (currentUserId != "") {
                    playlistVariableName += currentUserId;
                }
                if ($.cookie(playlistVariableName) != "" && $.cookie(playlistVariableName) != null) {
                    videoIds = $.cookie(playlistVariableName);
                }
               
                videoIds = videoIds.replace("," + $(this).parent().attr("class").split(" ")[1], "");

                videoArray = videoIds.split(',');
                $.cookie(playlistVariableName, videoIds, { path: '/' });

                $(this).parent().remove();
                if (videoArray == "") {
                    var emptyPlaylistMessage = $("<span/>", { "class": "no-playlist-span", text: "Your playlist is empty. You can always add videos from our most popular or most recent sections. Or you can search for a specific term." });

                    $(".area").children().hide();
                    $(".area").before(emptyPlaylistMessage);
                }
                event.preventDefault();
            });

            $(".clip").each(function(){
              var maxHeight = 40;
              var title = $(this).find("span.title").html();   
              if(title != null)   
              {
                 while (title.length > 0 && $(this).find("span.title").height() >= maxHeight) {
                    title = title.substr(0, title.length - 1);
                    $(this).find("span.title").html(title + "...");
                 }
              }
            });

        };

        this.setClipArrows = function() {

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

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

        this.addToFavorites = function() {

            if (userNotLoggedIn) {
                tooltip.Show($(this));
            } else {
                $.ajax({
                    url: favoriteVideoUrl,
                    type: 'POST',
                    cache: false,
                    data: { videoId: currentVideoId },
                    dataType: 'json',
                    error: function(error) {

                    },
                    success: function(jsonData) {

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

                        $('a.favorite').parent().unbind("click", self.addToFavorites);
                    }
                });
            }

            return false;
        };

        this.onFlagClicked = function(event) {

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

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

            return false;
        };

        this.flagVideo = function() {

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

            $.ajax({
                url: flagVideoUrl,
                type: 'POST',
                cache: false,
                data: { videoId: currentVideoId, message: flagMessage },
                dataType: 'json',
                error: function(error) {

                },
                success: function(jsonData) {
                    panel.Hide($(".flag-dialog"));

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

        this.setDialogClose = function(dialogClassName) {


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

            });

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

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

                panel.Hide($(dialogClassName));

                return false;
            });

        };

        this.sendRating = function(value) {

            var currentRating = value * 16;

            $.ajax({
                url: rateVideoUrl,
                type: 'POST',
                cache: false,
                data: { rating: value, videoId: currentVideoId },
                dataType: 'json',
                error: function(error) {

                },
                success: 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;
                    });
                }
            });
        };

        this.myPlaylist = function() {

            if (currentThumbPage != 1) {
                currentThumbPage = 1;
            }

            sortMethod = "playlist";

            $("#recent").attr("class", "sort");
            $("#popular").attr("class", "sort");
            $("#my-playlist").attr("class", "sort selected");

            $.ajax({
                url: videoListUrl,
                type: 'POST',
                cache: false,
                data: { page: 1, sortBy: sortMethod, category: currentCategory },
                dataType: 'json',
                error: function(error) {

                },
                success: function(jsonData) {
                    self.populateThumbnails(jsonData);
                }
            });
        };
        /*******************************
        Page actions
        */
        this.loadVideo = function(videoId) {

            postForm = new PipenoUI.SubmitForm("/Video?videoId=" + videoId, {});

            postForm.AddItem("videoId", videoId);
            postForm.AddItem("page", currentThumbPage);
            postForm.AddItem("tab", sortMethod);
            postForm.AddItem("category", currentCategory);

            postForm.Submit();
        };

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

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

                window.location = location;

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

            $(".header p span").html("(" + ++commentNumber + ")");
            $("div.button .comments").parent().find("p").text("Comments(" + 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);
                }
            });
        };

        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, videoId: currentVideoId, replyText: replyToText, replyUser: replyToUser }, addNewComment);
                        }
                    }

                });


            }

            return false;
        };

        this.getComments = function(pageNumber, commentThreshold) {

            currentCommentPage = pageNumber;
            self.ajaxCall(retrieveCommentsUrl, { page: pageNumber, threshold: commentThreshold, videoId: currentVideoId }, refreshComments);
            $(this).scrollTop($('div.header').position().top);
        };
        /*******************************
        Handlers
        */
        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();

            event.preventDefault();
            return false;

            }

        };

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

        var codeClickHandler = function() {

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

            return false;
        };

        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 menuSearchClicked = function() {

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

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

                window.location = "/Video/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 = "/Video/Search?searchWord=" + searchWord;

            }
        };

        var searchInputClicked = function() {

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

            $("#menu-bar div.search input").bind("click", searchInputClicked);
            $('#menu-bar div.search input').bind("keypress", searchInputKeypress);
            $("#menu-bar div.search a").bind("click", menuSearchClicked);

            if ($.cookie("playlist" + currentUserId) != null) {
                videoArray = $.cookie("playlist" + currentUserId).split(",");
            } else {
                videoArray = "";
            }
            
            if (commentNumber <= commentsPerPage) {
                $(".pagination").hide();
            }

            $(".pagination").pagination(commentNumber, { 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; }
            });

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

            uicombo = new PipenoUI.ComboBox($(".combo-box:first"));
            if (currentCategory != "") {
                $(".combo-box div").html(currentCategory);
            }
            $(uicombo).bind("change", function(event, oldValue, newValue) {

                currentCategory = newValue;
                if (newValue == "All Categories")
                    currentCategory = "";
                self.getVideoThumbs(1);
            });

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

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

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

            if (videoRated || userNotLoggedIn) {

                $(".star-rating li a").css({
                    "background": "url(../img/ratings.png) top left"
                });

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

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

            $.each(videoArray, function(index, value) {
                if (videoArray[index] != "") {
                    $("." + videoArray[index]).children(".add-to-playlist").hide();
                }
            }
            );

            if ($("." + currentVideoId).children("input.previous").val() != "") {
                previous = $("." + currentVideoId).children("input.previous").val();
            }

            if ($("." + currentVideoId).children("input.next").val() != "") {
                next = $("." + currentVideoId).children("input.next").val();
            }

            $("." + currentVideoId).children("span.black").attr("class", "selected");

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

            $(".add-to-playlist").click(function(event) {

                var playlistVariableName = "playlist";
                var videoIds = "";

                if (currentUserId != "") {
                    playlistVariableName += currentUserId;
                }
                if ($.cookie(playlistVariableName) != "" && $.cookie(playlistVariableName) != null) {
                    videoIds = $.cookie(playlistVariableName);
                }

                videoIds += "," + $(this).parent().attr("class").split(" ")[1];
                videoArray = videoIds.split(',');
                $.cookie(playlistVariableName, videoIds, { path: '/' });

                $(this).hide();

                event.preventDefault();
            });

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

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

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

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

            $(".sort").removeClass("selected");

            switch (sortMethod) {
                case "date": $("#recent").addClass("selected");
                    break;
                case "views": $("#popular").addClass("selected");
                    break;
                case "playlist": $("#my-playlist").addClass("selected");
                    break;
            }


            if ($("#my-playlist").hasClass("selected")) {

                $(".add-to-playlist").each(function() {
                    var removeFromPlaylist = $("<span/>", { "class": "remove-from-playlist" });
                    $(this).replaceWith(removeFromPlaylist);

                });

                $(".remove-from-playlist").click(function(event) {

                    var playlistVariableName = "playlist";
                    var videoIds = "";

                    if (currentUserId != "") {
                        playlistVariableName += currentUserId;
                    }
                    if ($.cookie(playlistVariableName) != "" && $.cookie(playlistVariableName) != null) {
                        videoIds = $.cookie(playlistVariableName);
                    }
                   
                    videoIds = videoIds.replace(',' + $(this).parent().attr("class").split(" ")[1], "");

                    videoArray = videoIds.split(',');
                    $.cookie(playlistVariableName, videoIds, { path: '/' });

                    $(this).parent().remove();
                    if (videoArray == "") {
                        var emptyPlaylistMessage = $("<span/>", { "class": "no-playlist-span", text: "Your playlist is empty. You can always add videos from our most popular or most recent sections. Or you can search for a specific term." });

                        $(".area").children().hide();
                        $(".area").before(emptyPlaylistMessage);
                    }
                    event.preventDefault();
                });
            }
            
            self.setClipArrows();

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

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

            });
           
            $("a.show").click(function() {

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

                return false;

            });

        
            
            $('.comment .gift').hide()
            $('.comment .vote .separator').hide();

            /* THIS CAN BE USED IN THE FUTURE */
            /*

                
            //add the gifts popup in the page
            loadGiftPopup();
            (function(){
                sendGiftClickHandler(sendGiftClickHandler($(this).parent().find('input[type=hidden]').val(), 'Comment', $(this).parent().parent().parent().parent().find('.user').text(), $(this).parent().parent().find('input.commentOwnerId').val()););
            });
            */
            $(".clip").each(function(){
              var maxHeight = 40;
              var title = $(this).find("span.title").html();   
              if(title != null)   
              {
                 while (title.length > 0 && $(this).find("span.title").height() >= maxHeight) {
                    title = title.substr(0, title.length - 1);
                    $(this).find("span.title").html(title + "...");
                 }
              }
            });

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

    /* THIS CAN BE USED IN THE FUTURE */
    /*
var sendGiftClickHandler = function(sourceIdParam, sourceTypeParam, forUserNameParam, forUserIdParam) {
    if (currentUser == '') {
        tooltip.Show($(this));
    } else {
        sourceId = sourceIdParam;
        giftSourceType = sourceTypeParam;
        forUserName = forUserNameParam;
        forUserId = forUserIdParam;
        $('.overlay-gifts').show();
        window.scroll(0,0);
    }

    return false;
}

function loadGiftPopup()
{
    $.ajax({
        url: sendGiftLoadUrl,
        type: 'POST',
        success: function(data){
            var overlay = $('<div/>', {'class': 'overlay-gifts'});
            $(overlay).height($(document).height()+'px');
            $(overlay).width($(document).width()+'px');
            $(overlay).html(data);
            $('body').append($(overlay));
        }
    });
}
*/

/* End Of File */

