﻿var RedirectOnLogin = true;
var HotTopicBatchIndex = 0;
$(function () {

    var jsonTopics;
    var currentIndex = 0;
    var maxIndex = 0;
    var jcropApi;
    /*Load digg script*/
    (function () {
        var s = document.createElement('SCRIPT'), s1 = document.getElementsByTagName('SCRIPT')[0];
        s.type = 'text/javascript';
        s.async = true;
        s.src = 'http://widgets.digg.com/buttons.js';
        s1.parentNode.insertBefore(s, s1);
    })();
    //WireTabContent();

    addthis.addEventListener('addthis.menu.share', eventHandler);

    jQuery.validator.addMethod("username", function (value, element) {
        var result = this.optional(element) || /^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+$/i.test(value);
        return result;
    }, "Only letters, numbers, and dot(.) are allowed, must not start or end with a dot");

    RenderCloud();
    UpdateSavedTopicStatus();
    (function RemoveLinkBorder() {

        var links = document.getElementsByTagName('a');
        for (var i = 0; i < links.length; i++) {
            links[i].onmousedown = function () {
                this.blur();
                return false;
            };
            links[i].onclick = function () {
                this.blur();
            };
            if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
                links[i].onfocus = function () {
                    this.blur();
                };
            }
        }
    })();
    /*Email validation*/
    $.fn.email = function () {
        var emails = $(this).val().split(',');
        var isValid = false;
        for (var i = 0; i < emails.length; i++) {
            isValid = ValidEmail(emails[i], true);
            if (!isValid) return false;
        }
        return true;
    };

    function trim(stringToTrim) {
        return stringToTrim.replace(/^\s+|\s+$/g, "");
    }


    /*Read Cookie*/
    //    var IR = readCookie('IR');
    //    if (IR) {
    //        if (!readCookie('UnlockVerification')) {
    //            $.blockUI({ message: $('#invitation_modal')
    //            });
    //        }
    //    }
    //   
    $("#latest_topic_next").live("click", function () {

        var batch = parseInt($(this).attr("batch_number")) + 1;
        $(this).attr("batch_number", batch);
        $('#ajaximg_batchload').removeClass("hide");
        $("#latest_topics_container").load("/topic/RecentlySubmittedTopics", { batchnumber: batch, Ajax: true }, function () {
            $('#ajaximg_batchload').addClass("hide");
            $(this).hide("slide", { direction: "left" }, 100);
            $(this).show("slide", { direction: "right" }, 300);
            $("#latest_topic_prev").show();
        });



    });

    $("#latest_topic_prev").live("click", function () {

        var batch = parseInt($("#latest_topic_next").attr("batch_number")) - 1;
        if (batch == 1) {
            $("#latest_topic_prev").hide();
        }
        $('#ajaximg_batchload').removeClass("hide");
        $("#latest_topic_next").attr("batch_number", batch);
        $("#latest_topics_container").load("/topic/RecentlySubmittedTopics", { batchnumber: batch, Ajax: true }, function () {
            $('#ajaximg_batchload').addClass("hide");
            $(this).hide("slide", { direction: "right" }, 100);
            $(this).show("slide", { direction: "left" }, 300);

        });
    });

    $('#category-menu').mouseover(function () {

        var pos = $(this).offset();
        var width = $(this).width();
        $("#menu_items").css({ "left": (pos.left - 20) + "px", "top": (pos.top + 30) + "px" });
        $("#menu_items").show();

    });
    $('#menu_items').mouseleave(function () {

        $("#menu_items").delay(2000).hide();
    });

    $('.submitlink').click(function () {

        if (CurrentUser != '') {
            $('#submit_topic_wizard').load("/Topic/SubmitTopic", function (data) { $('#submit_topic_wizard').jqmShow(); });
        }
        else {
            LoginRequired();
        }
    });


    $('#add_image_wizard').click(function () {


        $('#topic_wizard').load("/Feature/PartialViewCrop", { topicId: $('#topicID').val(), topicUrl: $('#topicUrl').val() }, function () { $('#topic_wizard').jqmShow(); });

    });

    $('#btn_parse_topic_url').live('click', function () {

        var isValidUrl = ValidUrl($('#topicUrl').val()); $('#error_element').text(" ");
        if (isValidUrl) {
            $.ajax({
                type: "POST",
                url: '/Topic/ParseTopicUrl',
                data: { url: $('#topicUrl').val() },
                dataType: "json",
                beforeSend: function () { $('#ajax_submit').show(); },
                complete: function () { $('#ajax_submit').hide(); },
                traditional: true,
                success: function (result) {

                    //$('#parse_url').hide();
                    var jsonResult = JSON.parse(result.ReturnValue);
                    $('.content >.content_header> textarea#topic_title').text(jsonResult.Title);
                    $('.content > .content_header> textarea#topic_desc').text(jsonResult.Description);
                    var imageHtml = ""; var segmentCount = 3;
                    for (var i = 0; i < jsonResult.ImageList.length; i++) {

                        if (i % segmentCount == 0) {
                            if (i == 0) {
                                imageHtml += "<div>";
                            }
                            else {
                                imageHtml += "</div><div>";
                            }
                        }

                        imageHtml += "<img src=\"" + jsonResult.ImageList[i] + "\" class=\"parsed_image\" />";
                        /*Last element*/
                        if (i == jsonResult.ImageList.length - 1) {
                            imageHtml += "</div>";
                        }
                    }
                    var select_list = "<select id=\"TopicCategoryList\" name=\"TopicCategories\"><option value=\"\">Select Your Topic Category</option>";
                    for (var j = 0; j < jsonResult.Categories.length; j++) {
                        select_list += "<option value=\"" + jsonResult.Categories[j].FeedCategoryID + "\">" + jsonResult.Categories[j].CategoryName + "</option>";
                    }
                    select_list += "</select>";
                    $('.content >.topic_categories').html(select_list);
                    $('.content >.images >.scrollable >.items').html(imageHtml);
                    $('.content').show('slow');
                }

            });
        }
        else {
            $('#error_element').text("Please enter a valid url, missing http:// or www").show();
        }
    });

    $('.parsed_image').live('click', function () {
        $('.parsed_image').each(function () { $(this).removeClass('active'); });
        $(this).addClass('active');
        $('#selected_image').val($(this).attr('src'));

    });
    $('#preference_next').live('click', function () {

        var Categories = new Array();

        $('#channelpreference > div > ol >li').each(function () {
            if ($(this).children("input[type='checkbox']").is(':checked')) {
                Categories.push($(this).children("input[type='checkbox']").attr('CatId'));
            }

        });

        $.ajax({
            type: "POST",
            url: '/Feed/AddDefaultFeed',
            data: { CategoryList: Categories },
            dataType: "json",
            beforeSend: function () { $('.ajax_load_preference').show(); },
            complete: function () { $('.ajax_load_preference').hide(); },
            traditional: true,
            success: function (result) {

                if (result.Message == "") {
                    window.location = "/EditProfile";
                }
                else {
                    $('#channelpreference_message').text(result.Message);
                }
            }
        });
    });

    $("#tabs").children('a').each(function () {
        $(this).click(function () {
            var tab_content_selector = "div#" + $(this).attr('id') + "-content";
            $("#tab-content").empty();
            $("#tab-content").html($('#hidden-tab-content').children(tab_content_selector).html());
            $("#tabs").children('a').each(function () { $(this).removeClass("active"); });
            $(this).addClass("active");
        });
    });
    $("#showTip_watchtopic").click(function () {
        var display = $("#Howto_watch").css("display");
        if (display == "none") { $("#Howto_watch").show('slow'); }
        else {
            $("#Howto_watch").hide('slow');
        }
    });
    $("#QuickAddFeed").click(function () {
        $('#tab_feedmanagement > h1').text("Add Feed to Your FeedBoks.");
        $("#feedOverlay").overlay().load();
    });


    $('#link_box >ol >li').each(function () {
        $(this).children('a').click(function () {
            $('a.selected_days').each(function () { $(this).removeClass('selected_days'); });
            LoadTopics("", $(this).attr('rel'));
        });
    });
    $('#link_box_cat >ol >li').each(function () {
        $(this).children('a').click(function () {
            $('a.selected').each(function () { $(this).removeClass('selected'); });
            $(this).addClass('selected');
            var CSCatIDs = "";
            $('.selected_categories').children('.Category').each(function () {
                CSCatIDs = CSCatIDs + $(this).attr('catid') + ",";
            });
            LoadTopics(CSCatIDs, $(this).attr('rel'));
        });
    });
    $('#registerDiv').hide();

    $('#showreg').click(function () {
        $('#registerDiv').show();
        $('#loginDiv').hide('slow');
        $('div.loginheader').text('Register to FeedBoks, its very easy!');
    });
    $('#showlogin').click(function () {
        $('#registerDiv').hide('slow');
        $('#loginDiv').show();
        $('div.loginheader').text('Login to FeedBoks!');
    });

    $(".sortcolumn").sortable({
        connectWith: '.sortcolumn',
        opacity: 0.6,
        revert: true,
        handle: '.feedheader'
        });


    $('#drawerClose').click(function () { $("#drawer").slideUp(); });
    $('#submit_topic_wizard').jqm({ overlay: 70, modal: true });
    $('#dialog').jqm({ overlay: 70, modal: true });
    $('#channelpreference').jqm({ overlay: 70, modal: true });
    $('#topic_wizard').jqm({ overlay: 70, modal: true });

    //$('.profileoptions >table >tbody >tr>td> input:checkbox:not([safari])').checkbox()
    $("#slider").easySlider({
        auto: false,
        continuous: true
    });
    $('#whatiskey').click(function () {
        $('.whatiskey').show('slow');
    });
    $('#searchquery').focusin(function () {
        if ($(this).val() == "Search FeedBoks...") {
            $(this).val("");
        }
    });
    $('#searchquery').keypress(function (e) {

        if (e.which == 13) {
            $('#asearch').trigger('click');

        }
        else {
            return true;
        }
    });
    $(".star_rating").each(function () {
        $(this).stars({ split: 2, disabled: true });
    });

    $('#logout').click(function () {

        $('#FormLogout').submit();

    });

    $("#sortable, #followers, #following").sortable({
        placeholder: 'ui-state-highlight',
        update: function (event, ui) {
            var serializedOrder = $("#sortable").sortable('serialize');
            $.ajax({
                type: "POST",
                url: '/Feed/ArrangeFeedOrder',
                data: { serializedString: serializedOrder },
                dataType: "json",
                complete: function () { },
                success: function (result) {

                }
            });
        }
    });

    $("#overlay_myFeedBox").overlay({

        // custom top position
        top: 260,

        // some mask tweaks suitable for facebox-looking dialogs
        mask: {
            // you might also consider a "transparent" color for the mask
            color: '#fff',
            // load mask a little faster
            loadSpeed: 200,
            // very transparent
            opacity: 0.5
        },

        // disable this for modal dialog-type of overlays
        closeOnClick: false

    });
    // select the overlay element - and "make it an overlay"
    $("#overlay_invite").overlay({

        // custom top position
        top: 260,

        // some mask tweaks suitable for facebox-looking dialogs
        mask: {
            // you might also consider a "transparent" color for the mask
            color: '#fff',
            // load mask a little faster
            loadSpeed: 200,
            // very transparent
            opacity: 0.5
        },

        // disable this for modal dialog-type of overlays
        closeOnClick: false

    });

    $("#feedOverlay").overlay({

        // custom top position
        top: 260,

        // some mask tweaks suitable for facebox-looking dialogs
        mask: {

            // you might also consider a "transparent" color for the mask
            color: '#fff',

            // load mask a little faster
            loadSpeed: 200,

            // very transparent
            opacity: 0.5
        },

        // disable this for modal dialog-type of overlays
        closeOnClick: false,
        fixed: false

    });

    $('#InviteFriends').click(function () {
        $("#overlay_invite").overlay().load();
        //$('#channelpreference').jqmShow();

    });
    $('#myfeedboks').click(function () {
        $("#overlay_myFeedBox").overlay().load();
    });
    $("#sortable").disableSelection();

    $('#joinFB').click(function () {

        $('#dialog').jqmShow();
        $('#registerDiv').show();
        $('#loginDiv').hide();
        $('div.loginheader').text('Join FeedBoks Today, its very easy and free!');
    });

    $('.url').live('click', function () {

        $(this).prev().trigger("click");

    });

    $('.feedtopic_share').live('click', function () {

        var mediawidget = $(this).nextAll('.mediawidget');
        if (mediawidget.css('display') == "none") {
            var offSet = $(this).offset();
            mediawidget.show();
            var width = mediawidget.width();
            var height = mediawidget.height();
            mediawidget.offset({ top: 0, left: offSet.left - 100 });
            mediawidget.css({ "top": -height / 2 });
            mediawidget.css("z-index", "10000");
        }
        else {
            mediawidget.hide();
        }
    });

    $('#customize_topnews').live('click', function () {
        if (CurrentUser != '') {

            window.location = '/EditProfile';
        }
        else {

            LoginRequired();
        }

    });

    $('.mediawidget').find('a').live('click', function () {

        var url = $(this).attr('url');
        var index = url.indexOf('CreateTopicAjax');
        var split_array = unescape(url.replace(/\+/g, " ")).split('/');
        var title = split_array[split_array.length - 1];
        if (index != -1) {
            var topicID = CreateTopicAjax(url);
            url = escape("http://www.feedboks.com/topic/" + topicID + "/" + title);
        }

        switch ($(this).attr('type')) {

            case "tweet":
                popitup("http://twitter.com/share?url=" + url);
                break;
            case "facebook":
                popitup("http://www.facebook.com/share.php?u=" + url);
                break;
            case "digg":
                popitup("http://digg.com/submit?url=" + url);
                break;
            case "delicious":
                popitup("http://www.delicious.com/save?v=5&noui&jump=close&url='" + url);
                break;
            case "buzz":
                popitup("http://www.google.com/buzz/post?message=Here's%20Buzz!&url=" + url);
                break;
            case "stumble":
                popitup("http://www.stumbleupon.com/submit?url=" + url);
                break;
            case "reddit":
                popitup("http://reddit.com/submit?url=" + url);
                break;
            case "linkedin":
                popitup("http://www.linkedin.com/shareArticle?mini=true&url=" + url + "&title=" + title + "&summary=" + title + "&source=FeedBoks");
                break;

        }


    });


    $('.max').live('click', function () {
        if ($(this).siblings('div').hasClass('hideitem')) {
            $(this).siblings('div').removeClass('hideitem').addClass('itemcontent');
            $(this).removeClass('max').addClass('min');
            $(this).siblings('a.url').attr("status", "0");
            $(this).siblings('a.url').css('font-weight', 'bold');
            /*Get recent comments*/
            RetrieveRecentComments($(this).siblings('a.url'));
        }
        else {

            $(this).closest('.topnews_outer').children('.topnews_inner').removeClass('hideitem');
            $(this).removeClass('max').addClass('min');
            $(this).parent().next().children('a.url').attr("status", "1");
            $(this).parent().next().children('a.url').css('font-weight', 'bold');
        }
    });

    $('.min').live('click', function () {

        if ($(this).siblings('div').hasClass('itemcontent')) {
            $(this).siblings('div').removeClass('itemcontent').addClass('hideitem');
            $(this).removeClass('min').addClass('max');
            $(this).siblings('a.url').css('font-weight', 'normal');
        }
        else {

            $(this).closest('.topnews_outer').children('.topnews_inner').addClass('hideitem');
            $(this).removeClass('min').addClass('max');
            $(this).parent().next().children('a.url').css('font-weight', 'normal');

        }


    });

    $('.min_inner').live('click', function () {

        $(this).nextAll('.topnews_item_body').hide();
        $(this).nextAll('.url_inner').css('font-weight', 'normal');
        $(this).removeClass('min_inner').addClass('max_inner');

    });

    $('.max_inner').live('click', function () {

        $(this).nextAll('.topnews_item_body').show();
        $(this).nextAll('.url_inner').css('font-weight', 'bold');
        $(this).removeClass('max_inner').addClass('min_inner');

    });

    $('.url_inner').live('click', function () {

        $(this).prev().trigger('click');

    });

    $('.url_outer').live('click', function () {

        $(this).parent().prev().children().trigger('click');
    });
    $('.expand').live('click', function () {

        if ($(this).attr("state") == "0") {
            $(this).attr("state", "1");
            $(this).parent().parent().next().children('div.item').each(function () {
                $(this).children('a.max').removeClass('max').addClass('min');
                $(this).children('div.hideitem').removeClass('hideitem').addClass('itemcontent');
                $(this).children('a.url').css('font-weight', 'bold');
                RetrieveRecentComments($(this).children('a.url'));

            });
            $(this).parent().parent().next().children('div.topnews_outer').each(function () {
                $(this).find('a.max').removeClass('max').addClass('min');
                $(this).find('div.hideitem').removeClass('hideitem').addClass('topnews_inner');
                $(this).find('a.url').css('font-weight', 'bold');
                RetrieveRecentComments($(this).children('a.url'));

            });
            $(this).parent().parent().next().children('#latest_topics_container').children('div.item').each(function () {
                $(this).children('a.max').removeClass('max').addClass('min');
                $(this).children('div.hideitem').removeClass('hideitem').addClass('itemcontent');
                $(this).children('a.url').css('font-weight', 'bold');
            });

            $(this).text("Collapse All");
        }
        else {
            $(this).attr('state', '0');
            $(this).parent().parent().next().children('div.item').each(function () {
                $(this).children('a.min').removeClass('min').addClass('max');
                $(this).children('div.itemcontent').removeClass('itemcontent').addClass('hideitem');
                $(this).children('a.url').css('font-weight', 'normal');

            });
            $(this).parent().parent().next().children('div.topnews_outer').each(function () {
                $(this).find('a.min').removeClass('min').addClass('max');
                $(this).find('div.topnews_inner').removeClass('topnews_inner').addClass('hideitem');
                $(this).find('a.url').css('font-weight', 'normal');

            });
            $(this).parent().parent().next().children('#latest_topics_container').children('div.item').each(function () {

                $(this).children('a.min').removeClass('min').addClass('max');
                $(this).children('div.itemcontent').removeClass('itemcontent').addClass('hideitem');
                $(this).children('a.url').css('font-weight', 'normal');
            });
            $(this).text("Expand All");
        }
    });

    $('#feedCancel').live('click', function () {

        $('#displayfeed >div.feed').hide('drop');
    });

    $('#logo').click(function () {
        window.location = '/';
    });

    $('#btnAddFeed').live('click', function () {
        $('#ajaximg').removeClass('hide');
        var param = { FeedID: $("#FeedID").val() };
        var jsonStr = JSON.stringify(param);
        $.ajax({
            type: "POST",
            url: '/Feed/AddFeedByID',
            data: { FeedID: $("#FeedID").val() },
            dataType: "json",
            complete: function () { $('#ajaximg').addClass('hide'); },
            success: function (result) {

                if (result.IsSuccessful) {
                    $('#status_message').html("<img src=\"/Images/noerror.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                }
                else {
                    $('#status_message').html("<img src=\"/Images/error.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                }
            }
        });

    });

    /*Topic page*/
    $('#expandLink').click(function () {
        if ($(this).attr('status') == "0") {
            $('#articleFrame').show();
            $(this).html("<img alt=\"Hide Frame\" src=\"/Images/up_arrow.png\" style=\"border:0;\" />");
            $(this).attr('status', '1');
        }
        else {
            $('#articleFrame').hide();
            $(this).attr('status', '0');
            $(this).html("<img alt=\"Show Frame\" src=\"/Images/down_arrow.png\" style=\"border:0;\" />");

        }

    });

    $('#Title').click(function () {
        $('#expandLink').trigger('click');
    });

    $('#thumbs_up, #thumbs_down').click(function () {

        if (CurrentUser != '') {
            var isPositive = ($(this).attr('val') == '1') ? true : false;

            var param = { TopicID: $("#topicID").val(), Value: $(this).attr('val') };
            var PointVal = 0;
            if ($(this).prev().html() != '') {
                PointVal = parseInt($(this).prev().html().match(/(\+|-)\d+/)[0]);
            }

            $.ajax({
                type: "POST",
                url: '/Topic/RecordRecommendation',
                data: param,
                dataType: "json",
                complete: function () { },
                success: function (result) {

                    if (result.IsSuccessful) {
                        if (isPositive) {
                            $('.posIndicator').html('(+' + (PointVal + 1) + ')');
                        }
                        else {
                            $('.negIndicator').html('(' + (PointVal - 1) + ')');
                        }

                        $('#top_status_message').html("<img src=\"/Images/noerror.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                    }
                    else {
                        $('#top_status_message').html("<img src=\"/Images/error.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                    }
                }
            });
        }
        else {
            LoginRequired();
        }
    });

    $('#AddWatchList').click(function () {
        if (CurrentUser != '') {

            $.ajax({
                type: "POST",
                url: '/Topic/AddToWatchList',
                data: { TopicID: $("#topicID").val() },
                dataType: "json",
                complete: function () { },
                success: function (result) {
                    if (result.IsSuccessful) {
                        $('#top_status_message').html("<img src=\"/Images/noerror.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                        if ($('#watchlist').length == 0) {
                            $('#rightContent >#popular_topics').before("<div id=\"watchlist\"><ol></ol></div>");
                        }
                        var listItem = "<li><a href=\"/topic/" + $("#topicID").val() + "\">" + $('#topicTitle').val() + "</a>";
                        if ($('#CommentCount').text() != "") { listItem += "<span>" + $('#CommentCount').text() + "</span>"; }
                        listItem += "</li>";
                        $('#watchlist').children('ol').append(listItem);
                    }
                    else {
                        $('#top_status_message').html("<img src=\"/Images/error.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                    }
                }
            });
        }
        else {
            LoginRequired();
        }

    });

    $('.removetopic').click(function () {
        var answer = confirm("Do you want to remove this topic from your watchlist?");
        var CurrentTopic = $(this);
        if (answer) {
            $.post('/Topic/RemoveTopic', { TopicID: $(this).attr('topicid') }, function (data) {
                if (data.IsSuccessful) {
                    CurrentTopic.parent().remove();
                    $("#watchlist >ol >li >a[topicid='" + CurrentTopic.attr('topicid') + "']").parent().remove();
                    $('#status_message').html("<img src=\"/Images/noerror.png\">" + data.Message).fadeIn('slow').fadeOut(2000);

                }
            }, "json");
        }
    });



    $('.pen').live('click', function () {

        if ($(this).attr("state") != "true") {
            $(this).parent().siblings('div.QuickComment').show();
            $(this).parent().siblings('div.QuickComment').children('textarea').focus();
            $(this).attr("state", "true");
        }
        else {
            $(this).parent().siblings('div.QuickComment').hide();
            $(this).attr("state", "false");
        }
    });

    $('.postquick').live('click', function () {
        if (CurrentUser != '') {
            var item = $(this).closest('div.item');
            var pFeedID = item.siblings('#FeedID').val();
            var pTitle = item.children('a.url').text();
            var currentRef = $(this);
            //var pCommentTxt = $.trim(item.children('.itemcontent').children('.feedoption').children('.QuickComment').children('textarea.commentText').text());
            var pCommentTxt = $.trim(currentRef.prevAll('textarea').val());
            if (pCommentTxt != "") {

                $.ajax({
                    type: "POST",
                    url: '/Topic/PostQuickComment',
                    data: { Title: pTitle, CommentText: pCommentTxt, FeedID: item.siblings('#FeedID').val() },
                    dataType: "json",
                    beforeSend: function () { currentRef.next('#ajaximg').show(); },
                    complete: function () { currentRef.next('#ajaximg').hide(); },
                    success: function (result) {

                        if (result.IsSuccessful) {
                            currentRef.nextAll('div.status_message').html("<img src=\"/Images/noerror.png\"> Comment Posted!").fadeIn('slow').fadeOut(2000);
                            currentRef.prevAll('div.emptyComment').text(""); currentRef.prevAll('textarea').val("");

                            /*Add the comment in recent comment list*/

                            if (currentRef.closest('.itemcontent').children('.topic_recentcomments').has('ol').length) {
                                currentRef.closest('.itemcontent').children('.topic_recentcomments').children('ol').children('li').first().before("<li>#" + pCommentTxt + "<span class=author> by <a href=\"/user/" + CurrentUser + "\" target=_blank>" + CurrentUser + "</a></span></li>");
                            } else {
                                currentRef.closest('.itemcontent').children('.topic_recentcomments').append("<H2>Recent Comments</H2><ol><li>#" + pCommentTxt + "<span class=author> by <a href=\"/user/" + CurrentUser + "\" target=_blank>" + CurrentUser + "</a></span></li></ol>");
                            }
                            /*end*/
                        }
                        else {
                            currentRef.nextAll('div.status_message').html("<img src=\"/Images/error.png\">" + result.Message).fadeIn('slow').fadeOut(2000);

                        }
                    }
                });
            } else {
                currentRef.prevAll('div.emptyComment').text("Did you forget to write something here?");
            }
        }
        else {
            LoginRequired();
        }

    });

    $('#feed_rating').stars({
        split: 2,
        cancelShow: false,
        oneVoteOnly: true,
        callback: function (ui, type, value, event) {

            if (CurrentUser != '') {

                $.ajax({
                    type: "POST",
                    url: '/Feed/FeedRating',
                    data: { feedID: $('#FeedID').val(), value: value },
                    dataType: "json",
                    complete: function () { $('#ajaximg').addClass('hide'); },
                    success: function (result) {
                        if (result.IsSuccessful) {
                            $('#status_message').html("<img src=\"/Images/noerror.png\">Thank you for your input.").fadeIn('slow').fadeOut(2000);
                            $('#feed_rating').stars('select', result.ReturnValue);
                            if (!isNaN(parseInt($('#rating_count').text()))) {
                                $('#rating_count').text(parseInt($('#rating_count').text()) + 1);
                            }
                            else {
                                $('#rating_count').text('1');
                                $('#rating_count').addClass('ratings');
                            }

                        }
                        else {
                            $('#feed_rating').stars('select', $('#FeedRating').val());

                            $('#status_message').html("<img src=\"/Images/error.png\">" + result.Message).fadeIn('slow').fadeOut(2000);

                        }
                    }
                });

            }
            else {
                LoginRequired();
            }
        }
    });


    $('#LookupQuery').autocomplete('/Feed/FeedLookup', {
        dataType: 'json',
        parse: function (data) {
            if (data.length == 0) {
                $('#LookupUrl').val($('#LookupQuery').val());
            }
            var rows = new Array();
            for (var i = 0; i < data.length; i++) {
                var value = data[i].FeedDomain + "-" + data[i].FeedName;
                rows[i] = { data: data[i], value: data[i].FeedName, result: value };
            }
            return rows;
        },
        formatItem: function (row, i, n) {
            return (row.FeedDomain + "-" + row.FeedName);
        },
        width: 300,
        mustMatch: false,
        limit: 100
    }).result(function (event, row) {

        $('#LookupUrl').val(row.FeedUrl);


    });

    $('#LookupUser').autocomplete('/UserProfile/LookupUser', {
        dataType: 'json',
        parse: function (data) {
            if (data.length == 0) {

            }
            var rows = new Array();
            for (var i = 0; i < data.length; i++) {
                var value = data[i].UserName;
                rows[i] = { data: data[i], value: data[i].UserName, result: value };
            }
            return rows;
        },
        formatItem: function (row, i, n) {
            return (row.UserName);
        },
        width: 300,
        mustMatch: false,
        limit: 100
    }).result(function (event, row) {

        //$('#LookupUsrID').val(row.UserID);
        $('#LookupUserName').val(row.UserName);


    });

    $('#create_rss_head').click(function () {

        if ($("#Title").val() == "") {
            $("#Title").addClass('p_error');
            return;
        }
        else {
            $("#Title").removeClass('p_error');
        }
        if ($("#Description").val() == "") {
            $("#Description").addClass('p_error');
            return;
        } else { $("#Description").removeClass('p_error'); }

        $.ajax({
            type: "POST",
            url: '/UserProfile/UpdateRssHeader',
            data: { Title: $("#Title").val(), Description: $("#Description").val() },
            dataType: "json",
            beforeSend: function () { $('#p_ajaxload').show(); },
            complete: function () { $('#p_ajaxload').hide(); },
            success: function (result) {

                $("#rss_header_update_status").text(result.Message).fadeIn('slow').fadeOut(2000);
                $("#Title").removeClass('p_error'); $("#Description").removeClass('p_error');
            }
        });

    });

    $('#addFeedItem').click(function () {
        if ($('#FeedItemTitle').val() == "") {
            $('#FeedItemTitle').addClass('p_error'); return;
        }
        if ($('#FeedItemDescription').val() == "") {
            $('#FeedItemDescription').addClass('p_error'); return;
        }
        $('#RssItemForm').submit();

    });

    $('.rss_body >ol >li').hover(function () {
        $(this).children('.rssitem_remove').show();
    }, function () { $(this).children('.rssitem_remove').hide(); });



    // $('.searchresults > ol > li:nth-child(even)').css('background-color', '#EBEBEB');

    $('.topicfooter >ol >li').each(function () {
        $(this).children('a').tipsy({ gravity: 's' });
    });
    $('.feedtopic_email').live('click', function () {

        if ($(this).attr("state") != "true") {
            $('.email_topic').each(function () { $(this).html(""); });
            var html = "<input type=\"text\" id=\"email\" /><input type=\"button\" id=\"send_email\" value=\"Send &raquo;\" /><img class=\"hide\" id=\"ajax_email\" src=\"/Images/ajax_loader_blue.gif\" /><br/><span id=\"email_status\"></span>";
            $(this).parent().siblings('.email_topic').html(html);
            $(this).attr("state", "true");
        }
        else {
            $(this).parent().siblings('.email_topic').html("");
            $(this).attr("state", "false");
        }
    });

    $('#send_email').live('click', function () {

        if (CurrentUser != '') {
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

            if ($("#email").val() == "" || !emailPattern.test($("#email").val())) {
                $("#email_status").text("Enter an valid email!");
                return false;
            }
            $.ajax({
                type: "POST",
                url: '/Topic/EmailTopic',
                data: {
                    Email: $("#email").val(),
                    TopicTitle: $(this).closest('.item').children('.url').text(),
                    TopicContent: $(this).closest('.item').children('.itemcontent').children('.rssContent').text(),
                    FeedID: $(this).closest('.feedcontent').children('#FeedID').val()
                },
                dataType: "json",
                beforeSend: function () { $('#ajax_email').show(); },
                complete: function () { $('#ajax_email').hide(); },
                success: function (result) {

                    $("#email_status").text(result.Message).fadeIn('slow').fadeOut(2000);
                    $("#email").val("");

                }
            });
        }
        else {
            LoginRequired();
        }

    });


    $('#addtag').click(function () {

        var targetid = 0;
        var type = 0;
        if ($('#TopicID').length != 0) {

            targetid = parseInt($('#TopicID').val());
            type = 2;
        }
        $.ajax({
            type: "POST",
            url: '/Feature/AssociateTags',
            data: { TargetID: targetid, Tags: $("#TagName").val(), Type: type },
            dataType: "json",
            beforeSend: function () { $('#tag_ajax').show(); },
            complete: function () { $('#tag_ajax').hide(); },
            success: function (result) {

                if (result.IsSuccessful) {
                    var tags = $("#TagName").val().split(','); var tagLinks = "";
                    if (tags.length == 1) {
                        if ($("#TagName").val() != "") {

                            tagLinks = "<a href=\"/Tag/" + $("#TagName").val() + "\"" + ">" + $("#TagName").val() + "</a> ";
                        }
                    }
                    else {
                        for (var i = 0; i < tags.length; i++) {
                            tagLinks += "<a href=\"/Tag/" + tags[i] + "\">" + tags[i] + "</a> ";
                        }
                    }

                    $("DIV.tag_links").append(tagLinks); $("#TagName").val("");
                }

                $("#tagadd_status").text(result.Message).fadeIn('slow').fadeOut(2000);


            }
        });

    });

    /*Login*/

    $("#login-form").validate({

        submitHandler: function (form) {
            TryLogin(form);
        },

        highlight: function (element, errorClass) {
            $(element).css("border", "1px red dotted");

        },
        rules: {
            username: {
                required: true,
                minlength: 4

            },
            passwd: {
                required: true,
                minlength: 3

            }
        },
        messages: {
            username: {
                required: "Please enter a username",
                minlength: "Your username must be between 3 to 10 characters"
            },
            passwd: {
                required: "Please provide a password",
                minlength: "Your password must be at least 4 characters long"
            }
        }
    });


    $("#register-form").validate({

        submitHandler: function (form) {
            TryRegister(form);
        },

        highlight: function (element, errorClass) {
            $(element).css("border", "1px red dotted");

        },
        unhighlight: function (element, errorClass) {
            $(element).css("border", "1px #999999 solid");
        },

        rules: {
            username: {
                required: true,
                minlength: 4,
                username: true

            },
            password: {
                required: true,
                minlength: 6

            },
            repassword: {
                required: true,
                minlength: 6,
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            username: {
                required: "Please enter a username",
                minlength: "Your username must be atleast 4 characters long"
            },
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 6 characters long"
            },
            repassword: {
                required: "Please re-enter password",
                equalTo: "Please enter the same password as above"
            },
            email: "Please enter a valid email address"
        }
    });

    $("#reset-form").validate({
        submitHandler: function (form) {
            TryResetPassword(form);
        },

        highlight: function (element, errorClass) {
            $(element).css("border", "1px red dotted");

        },
        unhighlight: function (element, errorClass) {
            $(element).css("border", "1px #999999 solid");
        },

        rules: {
            password: {
                required: true,
                minlength: 6
            },
            repassword: {
                required: true,
                minlength: 6,
                equalTo: "#password"
            }
        },
        messages: {
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 6 characters long"
            },
            repassword: {
                required: "Please re-enter password",
                equalTo: "Please enter the same password as above"
            }
        }
    });


    $("#message-form").live('mouseover', function () {

        $(this).validate({

            submitHandler: function (form) {
                SendMessage(form);
            },

            highlight: function (element, errorClass) {
                $(element).css("border", "1px red dotted");

            },
            rules: {
                SenderName: {
                    required: true
                },
                SenderEmail: {
                    required: true,
                    email: true

                },
                Message: {
                    required: true,
                    minlength: 20
                }
            },
            messages: {
                SenderName: {
                    required: "Please enter your name"

                },
                SenderEmail: "Please enter a valid email address",
                Message: {
                    minlength: "Your message must be 20 character long.",
                    required: "Please write a message."
                }
            }
        });

    });

    $("#bug-form").live('mouseover', function () {
        $(this).validate({

            submitHandler: function (form) {
                PostBug(form);
            },

            highlight: function (element, errorClass) {
                $(element).css("border", "1px red dotted");

            },
            rules: {
                SenderName: {
                    required: true
                },
                SenderEmail: {
                    required: true,
                    email: true

                },
                Message: {
                    required: true,
                    minlength: 20
                },
                What:
            {
                required: true,
                minlength: 10
            }
            },
            messages: {
                SenderName: {
                    required: "Please enter your name"

                },
                SenderEmail: "Please enter a valid email address",
                Message: {
                    required: "Your message must be 20 character long."
                },
                What: {
                    required: "Please specify what happened",
                    minlength: "Must be atleast 10 charater long"
                }
            }
        });
    });



    /*Invite friends*/
    $('#inviteEmail').click(function () {

        if (!$("#inpt_invite_email").email()) {
            $("#invite_status").text("Not all the emails entered are valid").fadeIn('slow').fadeOut(3000);
        } else {
            $.ajax({
                type: "POST",
                url: '/Feature/InviteFriends',
                data: {
                    Emails: $("#inpt_invite_email").val(),
                    Message: $('#txt_invite_email').val()
                },
                dataType: "json",
                beforeSend: function () { $('#ajax_Invite').show(); },
                complete: function () { $('#ajax_Invite').hide(); },
                success: function (result) {

                    $("#invite_status").text(result.Message).fadeIn('slow').fadeOut(3000);
                    setTimeout(function () { $("#overlay_invite").overlay().close(); }, 3000);
                }
            });
        }
    });

    $('#LoginPopup').click(function () {
        PopLogin();
    });

    $('#validate_code').click(function () {
        if ($("#invitationCode").val() == "") {
            $("#validation_status").text("Invalid Code Entered").fadeIn('slow').fadeOut(4000);
        }
        else {
            $.ajax({
                type: "POST",
                url: '/Feature/VerifyInvitationCode',
                data: {
                    code: $("#invitationCode").val()
                },
                dataType: "json",
                beforeSend: function () { $('#ajax_Invite').show(); },
                complete: function () { $('#ajax_Invite').hide(); },
                success: function (result) {
                    if (!result.IsSuccessful) {
                        $("#validation_status").text(result.Message).fadeIn('slow').fadeOut(3000);
                    }
                    else {
                        $.unblockUI();
                    }
                }
            });
        }
    });


    $('.CatLink').live('click', function () {
        var CatID = $(this).attr('id');
        var CSCatIDs = "";
        var link = "<div class=\"Category\" catid=\"" + CatID + "\"><span>" + $(this).text() + "<a href=\"javascript:void(0)\" class=\"removeCat\" rel=\"" + CatID + "\">x</a></span></div>";
        $('.selected_categories').append(link);
        $('.selected_categories').children('.Category').each(function () {

            CSCatIDs = CSCatIDs + $(this).attr('catid') + ",";
        });
        var days = $('#link_box_cat >ol >li >a.selected').attr('rel');
        $(this).hide();
        LoadTopics(CSCatIDs, days);
    });


    $('.removeCat').live('click', function () {
        var CSCatIDs = "";
        $(this).closest('.Category').remove();
        $('.category-items >ol >li').each(function () {
            $(this).children('a').removeAttr("style");
        });
        if ($('.selected_categories').children('.Category').length == 0) {
            LoadTopics("", 30);
        }
        else {
            $('.selected_categories').children('.Category').each(function () {

                CSCatIDs = CSCatIDs + $(this).attr('catid') + ",";
            });
            var days = $('#link_box_cat >ol >li >a.selected').text();
            FilterTopic(CSCatIDs, days);
        }
    });

    $('#asearch').live('click', function () {

        window.location = "/search?q=" + $('#searchquery').val();
    });

    $('#forgot_pass').click(function () {
        $(this).parent().next().show('slow');
        $('#user_forgotpass').val("Enter your Username...");
    });
    $('#user_forgotpass').focus(function () {
        $(this).val("");
    });

    $('#btnForgotPass').click(function () {
        if ($("#user_forgotpass").val() == "") {
            $(".fp_error").text("Please enter your Username.").fadeIn('slow').fadeOut(3000);
        } else {
            $.ajax({
                type: "POST",
                url: '/Feature/RecoverPasswordEmail',
                data: {
                    username: $("#user_forgotpass").val()
                },
                dataType: "json",
                beforeSend: function () { $('#fp_ajaximg').show(); },
                complete: function () { $('#fp_ajaximg').hide(); },
                success: function (result) {

                    $(".fp_status").text(result.Message).fadeIn('slow').fadeOut(5000);
                }
            });
        }
    });

    $('#howto_joinFB').click(function () {

        $('.overlay_feedbx').empty();
        $('.overlay_feedbx').html("Currently, registration to FeedBoks is invitation only. If you have an invitation email then follow the instructions to register easily for free, or you can request an invitation by <a href=\"mailto:admin@FeedBoks.com?subject=Invitation Code\"> clicking here </a> and we will send you one when one is available");
        $("#overlay_myFeedBox").overlay().load();
    });


    $('.timeframe >ol >li').click(function () {
        var time_frame = 0;
        var currentRef = $(this);
        switch ($(this).attr('id')) {
            case "topic24hrs":
                time_frame = 1;
                break;
            case "topic7days":
                time_frame = 7;
                break;
            case "topic30days":
                time_frame = 30;
                break;
            case "topic_all_time":
                time_frame = null;
                break;

        }

        $.ajax({
            type: "POST",
            url: '/Topic/RenderMostActiveTopics',
            data: { timeframe: time_frame, isAjax: true },
            dataType: "json",
            beforeSend: function () { $('#ai_loadtopic').show(); },
            complete: function () { $('#ai_loadtopic').hide(); },
            success: function (result) {
                if (result.IsSuccessful) {
                    var jsonData = JSON.parse(result.ReturnValue);
                    var html = "";
                    if (jsonData.length > 0) {
                        for (var x = 0; x < jsonData.length; x++) {
                            html += "<li><a href=\"/topic/" + jsonData[x].TopicID + "/" + jsonData[x].FormattedTitle + "\">" + jsonData[x].TopicTitle + "</a>";
                            if (jsonData[x].CommentCount != "") {
                                html += "<span>" + jsonData[x].CommentCount + "</span>";
                            }
                            html += "</li>";
                        }
                    }
                    $('#top_topic_list').empty();
                    $('#top_topic_list').append(html);
                    $('.selected').each(function () {
                        $(this).removeClass("selected");
                    });
                    currentRef.children('a').addClass("selected");

                }

            }
        });

    });
    $('#LoadMore').click(function () {

        var d = $($('#link_box >ol >li >a.selected_days')[0]).attr('rel');
        if (d == undefined) {
            d = $($('#link_box_cat >ol >li >a.selected')[0]).attr('rel');

        }
        var index = parseInt($('#TopicContent > .topic_item').length) + 1;
        var CSCatIDs = "";
        $('.selected_categories').children('.Category').each(function () {
            CSCatIDs = CSCatIDs + $(this).attr('catid') + ",";
        });
        $.ajax({
            type: "POST",
            url: '/Home/TopTopicsJSON',
            data: { days: d, category: CSCatIDs, startindex: index },
            dataType: "json",
            beforeSend: function () {
                $('#ajax_loadmore').show();
            },
            complete: function () {
                $('#ajax_loadmore').hide();
            },
            success: function (result) {
                if (result.IsSuccessful) {
                    jsonTopics = JSON.parse(result.ReturnValue);
                    LoadTopicsJSON(jsonTopics);
                }
            }

        });

    });

    $('.savetopic').live("click", function () {
        var CurrentLink = this;
        if (CurrentUser != '') {
            if ($(CurrentLink).attr('saved') == "0") {
                $.ajax({
                    type: "POST",
                    url: '/Topic/AddToWatchList',
                    data: { TopicID: $(this).attr('topicID') },
                    dataType: "json",
                    complete: function () { },
                    success: function (result) {
                        if (result.IsSuccessful) {
                            $(CurrentLink).children('img.saveimg').attr('src', "/images/saved_topic.png");
                            $(CurrentLink).children('span').text(" Remove");
                            $(CurrentLink).attr('saved', '1');
                            $('#watchlist >ol').append("<li><a topicid=\"" + $(CurrentLink).attr('topicID') + "\" href=\"/Topic/" + $(CurrentLink).attr('topicID') + "/" + $(CurrentLink).attr('title') + "\">" + $(CurrentLink).closest('.right').children('.title').children('a').text() + "</a><span>" + $(CurrentLink).attr('count') + "</span></li>");

                        }
                        else {
                            $('#top_status_message').html("<img src=\"../Images/error.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                        }
                    }
                });
            }
            else {
                //Remove topic
                $.post('/Topic/RemoveTopic', { TopicID: $(this).attr('topicid') }, function (data) {
                    if (data.IsSuccessful) {
                        $(CurrentLink).children('img.saveimg').attr('src', "/images/save_topic.png");
                        $(CurrentLink).children('span').text(" Save Topic");
                        $(CurrentLink).attr('saved', '0');
                        //Remove from Saved list

                        $("#watchlist >ol >li >a[topicid='" + $(CurrentLink).attr('topicid') + "']").parent().remove();


                    }
                }, "json");
            }
        }
        else {
            LoginRequired();
        }
    });

    $('#addUserChannel').live('click', function () {
        var a = { dataType: 'json', success: JsonParseChannelList };
        $('#channelForm').ajaxSubmit(a);
    });
    $('#ChannelCancel').live('click', function () {
        $('#displayUserFeed >div.feed').hide('drop');
    });
    $('.crossfeed').live('click', function () {

        var answer = confirm("You are about to unsubsctibe from this feed, are you sure?");
        if (answer) {
            var FeedID = $(this).attr('id');
            var ctx = $(this);
            $.ajax({
                type: "POST",
                url: '/Feed/RemoveFeed',
                data: { FeedID: FeedID },
                dataType: "json",
                beforeSend: function () {
                    ctx.prev().show();
                },
                complete: function () {
                    ctx.prev().hide();
                },
                success: function (data) {
                    JsonParseFeedList(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });

        }
    });


    $("#ImageForm").live("submit", function () {

        $("#imageUrl").val($('#cropbox').attr("src"));
    });

    $("#enableCrop").live("click", function () {
        $('#cropbox').imgAreaSelect({ handles: true,
            fadeSpeed: 200, onSelectChange: OnChange
        });


    });
    $('#GetContent').live("click", function () {

        $.ajax({
            type: "POST",
            url: '/Feature/GetImagesFromUrl',
            data: { url: $('#topicUrl').val() },
            dataType: "json",
            beforeSend: function () { $('#ajax_crop').show(); },
            complete: function () { $('#ajax_crop').hide(); },
            traditional: true,
            success: function (result) {
                //reset all counters
                currentIndex = 0;
                var jsonResult = JSON.parse(result.ReturnValue);
                maxIndex = jsonResult.length;
                for (var i = 0; i < jsonResult.length; i++) {
                    var li = "<li index=\"" + (i + 1) + "\"><img src=\"" + jsonResult[i] + "\" id=\"cropbox\" name=\"cropbox\" /></li>";
                    $('#image_list > ol').append(li);
                }
                currentIndex = currentIndex + 1;
                var src = $("#image_list > ol >li:nth-child(" + currentIndex + ") >img").attr('src');
                var currentImage = "<img src=\"" + src + "\" id=\"cropbox\" name=\"cropbox\" />";
                $('#current_image').empty();
                $('#current_image').append(currentImage);
                $('#wizard_footer').show('slow');

            }

        });

    });

    $('#fwd').live("click", function () {
        if (currentIndex < maxIndex) {
            currentIndex = currentIndex + 1;
            var src = $("#image_list > ol >li:nth-child(" + currentIndex + ") >img").attr('src');
            var currentImage = "<img src=\"" + src + "\" id=\"cropbox\" name=\"cropbox\" />";
            $('#current_image').empty();
            $('#current_image').append(currentImage);
        }
    });

    $('#back').live("click", function () {
        if (currentIndex > 0) {
            currentIndex = currentIndex - 1;
            var src = $("#image_list > ol >li:nth-child(" + currentIndex + ") >img").attr('src');
            var currentImage = "<img src=\"" + src + "\" id=\"cropbox\" name=\"cropbox\" />";
            $('#current_image').empty();
            $('#current_image').append(currentImage);
        }
    });


    $('#process_submit').live("click", function () {
        var answer = confirm("Save Selection?");
        if (answer) {
            $.ajax({
                type: "POST",
                url: '/Feature/SaveTopicImage',
                data: { TopicID: $('#topicID').val(), imageUrl: $('#cropbox').attr('src'), X1: $('#X1').val(), Y1: $('#Y1').val(), X2: $('#X2').val(), Y2: $('#Y2').val(), H: $('#H').val(), W: $('#W').val(), scale: $('#Scale').val() },
                dataType: "json",
                beforeSend: function () { $('#ajax_crop').show(); },
                complete: function () { $('#ajax_crop').hide(); },
                traditional: true,
                success: function (result) {
                    if (result.IsSuccessful) {
                        location.reload(true);
                    }
                }

            });
        }
    });

    $('#pick_topic').click(function () {
        var answer = confirm("Add to Editors pick?");
        if (answer) {
            $.ajax({
                type: "POST",
                url: '/topic/AddEditorsPick',
                data: { TopicID: $('#TopicID').val() },
                dataType: "json",
                beforeSend: function () { },
                complete: function () { },
                traditional: true,
                success: function (result) {
                    if (result.IsSuccessful) {
                        $('#top_status_message').html("<img src=\"/Images/noerror.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                    }
                    else {
                        $('#top_status_message').html("<img src=\"/Images/error.png\">" + result.Message).fadeIn('slow').fadeOut(2000);
                    }
                }

            });
        }

    });



});

function OnChange(img, selection) {
    jQuery('#X1').val(selection.x1);
    jQuery('#Y1').val(selection.y1);
    jQuery('#X2').val(selection.x2);
    jQuery('#Y2').val(selection.y2);
    jQuery('#W').val(selection.width);
    jQuery('#H').val(selection.height);
    

}
function RemoveChannel(ctx, username) {

    var answer = confirm("You are about to unsubsctibe from this feed, are you sure?");
    if (answer) {
        $.ajax({
            type: "POST",
            url: '/UserProfile/RemoveChannelSubscription',
            data: { UnsubscribeUserName: username },
            dataType: "json",
            beforeSend: function () {
                $(ctx).prev().show();
            },
            complete: function () {
                $(ctx).prev().hide();
            },
            success: function (result) {
                if (result.IsSuccessful) {
                    $(ctx).closest('li').remove();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });

    }

}

function RemoveFollower(ctx, username) {
    var answer = confirm("You are about to remove this follower, are you sure?");
    if (answer) {
        $.ajax({
            type: "POST",
            url: '/UserProfile/RemoveChannelSubscriber',
            data: { FollowerUserName: username },
            dataType: "json",
            beforeSend: function () {
                $(ctx).prev().show();
            },
            complete: function () {
                $(ctx).prev().hide();
            },
            success: function (result) {
                if (result.IsSuccessful) {
                    $(ctx).closest('li').remove();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });

    }
}

function LoadTopicsJSON(jsonTopics) {

    var newcontent = "";
    for (var i = 0; i < jsonTopics.length; i++) {

        var posRecom = (jsonTopics[i].PositiveRecom == null) ? 0 : jsonTopics[i].PositiveRecom;

        newcontent += "<div class=\"topic_item\"><div class=\"left\">";
        newcontent += "<span class=\"comment\">" + jsonTopics[i].CommentCount + "</span><span class=\"reco\">" + posRecom + "</span></div>";
        newcontent += "<div class=\"right\"><div class=\"title\">" + "<a href=\"/topic/" + jsonTopics[i].TopicID + "/" + jsonTopics[i].FormattedTitle + "\">" + jsonTopics[i].TopicTitle + "</a>" + "<span class=\"category\">" + jsonTopics[i].CategoryName + "</span></div>";
        newcontent += "<div class=\"TopicContent\">" + jsonTopics[i].TopicText + "</div><div class=\"footer\"><ol><li><img src=\"../images/clock.png\" />" + jsonTopics[i].TopicPublishTimeSpan + "</li><li><img src=\"../images/pencil.png\" /> " + jsonTopics[i].LastCommentDate + "</li></ol></div>";
        newcontent += "<div class=\"options\"><ol>";
        newcontent += "<li><a href=\"javascript:void(0)\" class=\"savetopic\" saved=\"0\" topicID=\"" + jsonTopics[i].TopicID + "\" count=\"" + jsonTopics[i].CommentCount + "\"><img border=\"0\" src=\"/images/save_topic.png\" class=\"saveimg\"><span> Save Topic</span></a></li>";
        newcontent += "<li>" + RenderDiggButton("http://www.feedboks.com/topic/" + jsonTopics[i].TopicID + "/" + jsonTopics[i].FormattedTitle) + "</li>";
        newcontent += "<li>" + RenderTwitter("http://www.feedboks.com/topic/" + jsonTopics[i].TopicID + "/" + jsonTopics[i].FormattedTitle) + "</li>";
        newcontent += "<li>" + RenderFBLike("www.feedboks.com/topic/" + jsonTopics[i].TopicID + "/" + jsonTopics[i].FormattedTitle) + "</li></ol></div>";
        newcontent += "</div><div class=\"clear\"></div></div>";

    }
    $('#TopicContent').append(newcontent);
    UpdateSavedTopicStatus();
}



function RenderDiggButton(url) {

    //return "<a class=\"DiggThisButton DiggCompact\" href=\"http://digg.com/submit?url=" + escape(url) + "\"><script type=\"text/javascript\" src=\"http://widgets.digg.com/buttons.js\"></script></a>";
    return "<a href=\"http://digg.com/submit?url=" + encodeURIComponent(url) + "&bodytext=\" target=\"_blank\"><img src=\"http://widgets.digg.com/img/button/diggThisDigger.png\" alt=\"Digg Button\" title=\"Digg Button\" class=\"thumbnail-digg-btn\" border=\"0\" /></a>";
}
function RenderFBLike(url) {

    //return "<fb:like href=\"" + url + " layout=\"button_count\"></fb:like><script type=\"text/javascript\" src=\"http://connect.facebook.net/en_US/all.js\"></script>";
    return "<iframe src=\"http://www.facebook.com/plugins/like.php?href=" + escape(url) + "&amp;layout=button_count&amp;show_faces=true&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:50px; height:21px; display:inline;\" allowTransparency=\"true\"></iframe>";
}

function RenderTwitter(url) {

    return "<a href=\"http://twitter.com/share\" class=\"twitter-share-button\" data-url=\"" + url + "\" data-count=\"horizontal\"></a><script type=\"text/javascript\" src=\"http://platform.twitter.com/widgets.js\"></script>";
}

function SetCurrentNav(navid) {
    navid.closest('li').css("border-bottom", "2px #000000 solid");
}
function TryLogin(form) {
    //$('#login-form').submit(function() {
    $('#ajaximg').show();
    $.ajax({
        type: "POST",
        url: $(form).attr('action'),
        data: $(form).serialize(),
        dataType: "json",
        complete: function () { $('#ajaximg').hide(); },
        success: function (result) {

            //var jsonResult = JSON.parse(result);
            if (result.IsSuccessful) {

                //$('#dialog').jqmHide();
                if (RedirectOnLogin) {
                    window.location = '/';
                }
                else {
                    window.location.reload();
                }
                RedirectOnLogin = true;
            }

            else {

                $('#loginerror').show('slow').html(result.Message);
            }
        }
    });
    return false;
}

function TryRegister(form) {
    //$('#register-form').submit(function() {
    if (!$('#AcceptTAC').is(':checked')) {
        $('#registererror').show('slow').html("Please Accept FeedBoks Terms and Privacy Policy.");
        return false;
    }
    else {
        $.ajax({
            type: "POST",
            url: $(form).attr('action'),
            data: $(form).serialize(),
            dataType: "json",
            beforeSend: function () { $('#ajaximg_r').show(); },
            complete: function () { $('#ajaximg_r').hide(); },
            success: function (result) {
                //var jsonResult = JSON.parse(result);
                if (result.IsSuccessful) {
                    //window.location = "/EditProfile";
                    $('#dialog').jqmHide();
                    $('#channelpreference').jqmShow();

                }

                else {
                    $('#registererror').show('slow').html(result.Message);
                    Recaptcha.reload();
                }
            }
        });
    }
    return false;

}

function TryResetPassword(form) {
    $.ajax({
        type: "POST",
        url: $(form).attr('action'),
        data: $(form).serialize(),
        dataType: "json",
        beforeSend: function () { $('#ajaximg_fp').show(); },
        complete: function () { $('#ajaximg_fp').hide(); },
        success: function (result) {
            //var jsonResult = JSON.parse(result);
            if (result.IsSuccessful) {
                $('.ResetPassStatus').html(result.Message + "<a href=\"javascript:PopLogin()\"> Click here to Login.</a>");
            }
            else {
                $('.ResetPassStatus').text(result.Message);
            }

        }
    });
    return false;
}
function SendMessage(form) {
    $.ajax({
        type: "POST",
        url: $(form).attr('action'),
        data: $(form).serialize(),
        dataType: "json",
        beforeSend: function () { $('#ajax_Send').show(); },
        complete: function () { $('#ajax_Send').hide(); },
        success: function (result) {

            if (result.IsSuccessful) {
                $('#status_msg').show('slow').html(result.Message);     
            }
        }
    });
    return false;
}

function PostBug(form) {

    $.ajax({
        type: "POST",
        url: $(form).attr('action'),
        data: $(form).serialize(),
        dataType: "json",
        success: function (result) {
            if (result.IsSuccessful) {
                $('#status_bug').show('slow').html(result.Message);    
            }
        }
    });
    return false;
}
function RemoveRss(feedId) {
    var answer = confirm("Are you sure you want to delete this feed entry?");
    if (answer) {
        $.ajax({
            type: "POST",
            url: '/UserProfile/RemoveUserRssItem',
            data: { FeedItemID: feedId },
            dataType: "json",
            beforeSend: function () { $('#p_ajaxload').show(); },
            complete: function () { $('#p_ajaxload').hide(); },
            success: function (result) {
                if (result.IsSuccessful) {
                    $('.rss_body >ol >li').each(function () {
                        if ($(this).attr("feeditemid") == feedId) {
                            $(this).remove().fadeOut(1000);
                        }
                    });
                }
            }
        });
    }
}


function FeedFetching() {

    $('#ai_loadfeed').removeClass('hide');
}
function FeedFetched() {

    $('#ai_loadfeed').addClass('hide');
}
function UsrFeedFetching() {

    $('#Userloadfeed').removeClass('hide');
}
function UsrFeedFetched() {

    $('#Userloadfeed').addClass('hide');
}


function CommentPosting() {

    if (CurrentUser == '') {
        LoginRequired();
    }
    else if ($('#commentText').val() == "" || $('#commentText').val().length < 10) {
        $('#postAlert').html('Comment must be atleast 10 characters long').show();
        return false;
    }

    $('#commentText').attr('disable', 'disabled');
    $('#postComment').attr('disable', 'disabled');
    $('#ajaximg').removeClass('hide');
    
}

function CommentPosted(content) {
    Recaptcha.reload();
    var json_data = content.get_response().get_object();
    if (json_data.IsSuccessful) {
        /*Add the new comment in the begining*/
        if ($('#topic_comments').length == 0) {
            $('#comments').empty();
            try {
                $('#comments').html("<div id=\"topic_comments\">" + json_data.Message + "</div>");
            }
            catch (e) {
                alert(e);
            }
            $('#status_message').html("<img src=\"/Images/noerror.png\"> Comment Posed Sucessfully").fadeIn('slow').fadeOut(2000);
        }
        else {
            //alert(('#CommentCount').text());
            $('#CommentCount').text(parseInt($('#CommentCount').text()) + 1);
            $('#topic_comments').prepend(json_data.Message);
            $('#status_message').html("<img src=\"/Images/noerror.png\"> Comment Posed Sucessfully").fadeIn('slow').fadeOut(2000);
        }
        $('#commentText').val('');
        $('#postAlert').html('').hide();
    }
    else {
       
        switch (parseInt(json_data.ErrorCode)) {
            case 10:
                /*Login required*/
                LoginRequired();
                break;
            case 16:
                $('#postAlert').html(json_data.Message).show();
                break;
        }

    }
    $('#commentText').removeAttr('disable');
    $('#postComment').removeAttr('disable');
    $('#ajaximg').addClass('hide');
}

function PopLogin() {
   
    $('#dialog').jqmShow();
    $('#registerDiv').hide();
    $('#loginDiv').show();
   /* $('#showreg').hide();*/
}
function LoginRequired() {
    RedirectOnLogin = false;
    $('#dialog').jqmShow();
    $('#registerDiv').hide();
    $('#loginDiv').show();
    $('div.loginheader').text('You must be logged in!');
}
function RetrieveRecentComments(ItemReference) {
    var ItemTitle = ItemReference.text();
    $.ajax({
        type: "POST",
        url: '/Topic/GetTopicComment',
        data: { topicTitle: ItemTitle },
        dataType: "json",
        beforeSend: function () {
            ItemReference.siblings('div.itemcontent').children('div.topic_recentcomments').children("#ajax_loadcomments").show();
            ItemReference.siblings('div.itemcontent').children('div.topic_recentcomments').children("span").show();

        },
        complete: function () {
            ItemReference.siblings('div.itemcontent').children('div.topic_recentcomments').children("#ajax_loadcomments").hide();
            ItemReference.siblings('div.itemcontent').children('div.topic_recentcomments').children("span").hide();

        },
        success: function (result) {
            if (result.IsSuccessful) {
                var jsonData = JSON.parse(result.ReturnValue);
                if (jsonData.length > 0) {

                    var comment_html = "<h2>Recent Comments</h2><ol>";
                    for (var x = 0; x < jsonData.length; x++) {
                        comment_html += "<li>#" + jsonData[x].CommentText + "<span class=\"author\"> by <a href=\"/user/" + jsonData[x].UserName + "\" target=\"_blank\">" + jsonData[x].UserName + "</a></span>" + "</li>";
                    }
                    comment_html += "</ol>";
                    ItemReference.siblings('div.itemcontent').children('div.topic_recentcomments').html(comment_html);
                }
            }
        }
    });
}

/*Top-topic starts*/

function LoadTopics(c,d) {
    $.ajax({
        type: "POST",
        url: '/Home/TopTopicsJSON',
        data: { days: d, category: c, startindex: 0 },
        dataType: "json",
        beforeSend: function () {
            $('#ajax_cat_load').show();
        },
        complete: function () {
            $('#ajax_cat_load').hide();
        },
        success: function (result) {
            if (result.IsSuccessful) {
                jsonTopics = JSON.parse(result.ReturnValue);
                $('#TopicContent').empty();
                $("#" + d + "_d").addClass('selected_days');
                LoadTopicsJSON(jsonTopics);
            }
        }
    });
};

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function get_gravatar(email) {

    var MD5 = function (s) { function L(k, d) { return (k << d) | (k >>> (32 - d));
    } function K(G, k) { var I, d, F, H, x; F = (G & 2147483648); H = (k & 2147483648); I = (G & 1073741824); d = (k & 1073741824); x = (G & 1073741823) + (k & 1073741823); if (I & d) { return (x ^ 2147483648 ^ F ^ H);
                                                                                                                                                                             } if (I | d) { if (x & 1073741824) { return (x ^ 3221225472 ^ F ^ H);
                                                                                                                                                                                            } else { return (x ^ 1073741824 ^ F ^ H);
                                                                                                                                                                                            } } else { return (x ^ F ^ H);
                                                                                                                                                                               } } function r(d, F, k) { return (d & F) | ((~d) & k);
                                                                                                                                                                               } function q(d, F, k) { return (d & k) | (F & (~k));
                                                                                                                                                                               } function p(d, F, k) { return (d ^ F ^ k);
                                                                                                                                                                               } function n(d, F, k) { return (F ^ (d | (~k)));
                                                                                                                                                                               } function u(G, F, aa, Z, k, H, I) { G = K(G, K(K(r(F, aa, Z), k), I)); return K(L(G, H), F);
                                                                                                                                                                               } function f(G, F, aa, Z, k, H, I) { G = K(G, K(K(q(F, aa, Z), k), I)); return K(L(G, H), F);
                                                                                                                                                                               } function D(G, F, aa, Z, k, H, I) { G = K(G, K(K(p(F, aa, Z), k), I)); return K(L(G, H), F);
                                                                                                                                                                               } function t(G, F, aa, Z, k, H, I) { G = K(G, K(K(n(F, aa, Z), k), I)); return K(L(G, H), F);
                                                                                                                                                                               } function e(G) { var Z; var F = G.length; var x = F + 8; var k = (x - (x % 64)) / 64; var I = (k + 1) * 16; var aa = Array(I - 1); var d = 0; var H = 0; while (H < F) { Z = (H - (H % 4)) / 4; d = (H % 4) * 8; aa[Z] = (aa[Z] | (G.charCodeAt(H) << d)); H++;
                                                                                                                                                                                                                                                                                                                                         } Z = (H - (H % 4)) / 4; d = (H % 4) * 8; aa[Z] = aa[Z] | (128 << d); aa[I - 2] = F << 3; aa[I - 1] = F >>> 29; return aa;
                                                                                                                                                                               } function B(x) { var k = "", F = "", G, d; for (d = 0; d <= 3; d++) { G = (x >>> (d * 8)) & 255; F = "0" + G.toString(16); k = k + F.substr(F.length - 2, 2);
                                                                                                                                                                                                                           } return k;
                                                                                                                                                                               } function J(k) { k = k.replace(/\r\n/g, "\n"); var d = ""; for (var F = 0; F < k.length; F++) { var x = k.charCodeAt(F); if (x < 128) { d += String.fromCharCode(x);
                                                                                                                                                                                                                                                                                                         } else { if ((x > 127) && (x < 2048)) { d += String.fromCharCode((x >> 6) | 192); d += String.fromCharCode((x & 63) | 128);
                                                                                                                                                                                                                                                                                                                  } else { d += String.fromCharCode((x >> 12) | 224); d += String.fromCharCode(((x >> 6) & 63) | 128); d += String.fromCharCode((x & 63) | 128);
                                                                                                                                                                                                                                                                                                                  } } } return d;
                                                                                                                                                                               } var C = Array(); var P, h, E, v, g, Y, X, W, V; var S = 7, Q = 12, N = 17, M = 22; var A = 5, z = 9, y = 14, w = 20; var o = 4, m = 11, l = 16, j = 23; var U = 6, T = 10, R = 15, O = 21; s = J(s); C = e(s); Y = 1732584193; X = 4023233417; W = 2562383102; V = 271733878; for (P = 0; P < C.length; P += 16) { h = Y; E = X; v = W; g = V; Y = u(Y, X, W, V, C[P + 0], S, 3614090360); V = u(V, Y, X, W, C[P + 1], Q, 3905402710); W = u(W, V, Y, X, C[P + 2], N, 606105819); X = u(X, W, V, Y, C[P + 3], M, 3250441966); Y = u(Y, X, W, V, C[P + 4], S, 4118548399); V = u(V, Y, X, W, C[P + 5], Q, 1200080426); W = u(W, V, Y, X, C[P + 6], N, 2821735955); X = u(X, W, V, Y, C[P + 7], M, 4249261313); Y = u(Y, X, W, V, C[P + 8], S, 1770035416); V = u(V, Y, X, W, C[P + 9], Q, 2336552879); W = u(W, V, Y, X, C[P + 10], N, 4294925233); X = u(X, W, V, Y, C[P + 11], M, 2304563134); Y = u(Y, X, W, V, C[P + 12], S, 1804603682); V = u(V, Y, X, W, C[P + 13], Q, 4254626195); W = u(W, V, Y, X, C[P + 14], N, 2792965006); X = u(X, W, V, Y, C[P + 15], M, 1236535329); Y = f(Y, X, W, V, C[P + 1], A, 4129170786); V = f(V, Y, X, W, C[P + 6], z, 3225465664); W = f(W, V, Y, X, C[P + 11], y, 643717713); X = f(X, W, V, Y, C[P + 0], w, 3921069994); Y = f(Y, X, W, V, C[P + 5], A, 3593408605); V = f(V, Y, X, W, C[P + 10], z, 38016083); W = f(W, V, Y, X, C[P + 15], y, 3634488961); X = f(X, W, V, Y, C[P + 4], w, 3889429448); Y = f(Y, X, W, V, C[P + 9], A, 568446438); V = f(V, Y, X, W, C[P + 14], z, 3275163606); W = f(W, V, Y, X, C[P + 3], y, 4107603335); X = f(X, W, V, Y, C[P + 8], w, 1163531501); Y = f(Y, X, W, V, C[P + 13], A, 2850285829); V = f(V, Y, X, W, C[P + 2], z, 4243563512); W = f(W, V, Y, X, C[P + 7], y, 1735328473); X = f(X, W, V, Y, C[P + 12], w, 2368359562); Y = D(Y, X, W, V, C[P + 5], o, 4294588738); V = D(V, Y, X, W, C[P + 8], m, 2272392833); W = D(W, V, Y, X, C[P + 11], l, 1839030562); X = D(X, W, V, Y, C[P + 14], j, 4259657740); Y = D(Y, X, W, V, C[P + 1], o, 2763975236); V = D(V, Y, X, W, C[P + 4], m, 1272893353); W = D(W, V, Y, X, C[P + 7], l, 4139469664); X = D(X, W, V, Y, C[P + 10], j, 3200236656); Y = D(Y, X, W, V, C[P + 13], o, 681279174); V = D(V, Y, X, W, C[P + 0], m, 3936430074); W = D(W, V, Y, X, C[P + 3], l, 3572445317); X = D(X, W, V, Y, C[P + 6], j, 76029189); Y = D(Y, X, W, V, C[P + 9], o, 3654602809); V = D(V, Y, X, W, C[P + 12], m, 3873151461); W = D(W, V, Y, X, C[P + 15], l, 530742520); X = D(X, W, V, Y, C[P + 2], j, 3299628645); Y = t(Y, X, W, V, C[P + 0], U, 4096336452); V = t(V, Y, X, W, C[P + 7], T, 1126891415); W = t(W, V, Y, X, C[P + 14], R, 2878612391); X = t(X, W, V, Y, C[P + 5], O, 4237533241); Y = t(Y, X, W, V, C[P + 12], U, 1700485571); V = t(V, Y, X, W, C[P + 3], T, 2399980690); W = t(W, V, Y, X, C[P + 10], R, 4293915773); X = t(X, W, V, Y, C[P + 1], O, 2240044497); Y = t(Y, X, W, V, C[P + 8], U, 1873313359); V = t(V, Y, X, W, C[P + 15], T, 4264355552); W = t(W, V, Y, X, C[P + 6], R, 2734768916); X = t(X, W, V, Y, C[P + 13], O, 1309151649); Y = t(Y, X, W, V, C[P + 4], U, 4149444226); V = t(V, Y, X, W, C[P + 11], T, 3174756917); W = t(W, V, Y, X, C[P + 2], R, 718787259); X = t(X, W, V, Y, C[P + 9], O, 3951481745); Y = K(Y, h); X = K(X, E); W = K(W, v); V = K(V, g);
                                                                                                                                                                                                                                                                                                                                                                                                                                                               } var i = B(Y) + B(X) + B(W) + B(V); return i.toLowerCase();
    };
    var url='http://www.gravatar.com/avatar/' + MD5(email) + '?r=pg&d=identicon&s=40';
    return "<img src=\"" + url + "\" class=\"ProfileImg\"/>";

}

function RenderFeeds(FeedArrayIndex) {
    for (i = 0; i < FeedArrayIndex.length; i++) {
        $("#feed_" + FeedArrayIndex[i]).load("/Feed/RenderFeedByID", { FeedID: FeedArrayIndex[i] }, function (response, status, xhr) {
            $(response).children('.feedheader').children('.feedloader').hide();
            var id = $(response).children('.feedcontent').children('#FeedID').val();
            $("#feed_" + id).removeClass('FeedPlaceHolder'); RemoveLinkBorder();
        });
    }

}



function RemoveLinkBorder() {

    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        links[i].onmousedown = function () {
            this.blur();
            return false;
        };
        links[i].onclick = function () {
            this.blur();
        };
        if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
            links[i].onfocus = function () {
                this.blur();
            };
        }
    }
}


function RenderCloud() {
    //var ColorArray = new Array("#0E0B28", "#9A340E", "#8C4C05", "#180230", "#50232A");
    var ColorArray = new Array("#F4F4F4", "#BE7700", "#D26100", "#E4BB37", "#45ACBB");
    $('#TagCloud').children('a').each(function () {
        if (!$(this).hasClass('moretags')) {
            var ran_index = Math.floor(Math.random() * (ColorArray.length));
            var fontcolor = ColorArray[ran_index];
            var fontsize = $(this).attr('fsize') + "em";
            $(this).css("color", fontcolor);
            $(this).css("font-size", fontsize);
            $(this).hover(function () { $(this).css("color", "#fff"); }, function () { $(this).css("color", fontcolor); });
        }
    });
    $('.moretags').css('color', '#FECD37');

}
function UpdateSavedTopicStatus() {
    $('#watchlist >ol >li >a').each(function () {
        var watchitem = this;
        $('.topic_item >.right>.options >ol >li>a.savetopic').each(function () {
            if ($(watchitem).attr('topicid') == $(this).attr('topicid')) {
                $(this).children('img.saveimg').attr('src', "/images/saved_topic.png");
                $(this).children('span').text(" Remove");
                $(this).attr("saved", '1');
            }
        });
    });
}


function RemoveFeed(FeedID) {
    var answer = confirm("You are about to unsubsctibe from this feed, are you sure?");
    if (answer) {
        //$.post("/Feed/RemoveFeed", { FeedID: FeedID }, JsonParseFeedList, "json");

        $.ajax({
            type: "POST",
            url: '/Feed/RemoveFeed',
            data: { FeedID: FeedID },
            dataType: "json",
            beforeSend: function () {
                
            },
            complete: function () {

            },
            success: function (data) {
                JsonParseFeedList(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });

    }
}


function JsonParseFeedList(data) {
    var feedlist = "";
    if (data.IsSuccessful) {
        var jsonData = JSON.parse(data.Message);
        for (var x = 0; x < jsonData.length; x++) {
            if (jsonData[x].FeedStatistics.FeedRating == null) { jsonData[x].FeedStatistics.FeedRating = "No Rating Available"; }
            feedlist += "<li class=\"ui-state-default\"><span><a href=\"/feed/" + jsonData[x].FeedID + "\">" + jsonData[x].FeedName + "</a></span><span class=\"category\">" + jsonData[x].FeedCategory + "</span><span class=\"attrbrank\">" + jsonData[x].FeedStatistics.FeedRating + "</span><span class=\"attrbCount\">" + jsonData[x].FeedStatistics.SubscribersCount + "</span><img src=\"../../Images/remove.png\" alt=\"Remove Feed\" id=\"" + jsonData[x].FeedID + "\" class=\"crossfeed\"/></li>";
        }
        $('ul#sortable').empty();
        $('ul#sortable').append(feedlist);
        $('#displayfeed >div.feed').hide('slow');
        $('#feed_add_status').html("<img src=\"/Images/noerror.png\"> Your Feed Subscription has been Updated.").fadeIn('slow').fadeOut(2000);

    }
    else {
        $('#message').text(data.Message).show();
    }
}

function JsonParseChannelList(data) {
    var channellist = "";
    var Subscriber="";
    if (data.IsSuccessful) {
        var jsonData = JSON.parse(data.Message);
        for (var x = 0; x < jsonData.length; x++) {
            if (jsonData[x].SubscriberCount == null) { Subscriber = "No"; } else { Subscriber = jsonData[x].SubscriberCount; }

            channellist += "<li class=\"ui-state-default\">" + get_gravatar(jsonData[x].EmailAddress) + "<span><a href=\"/user/" + jsonData[x].UserName + "\">" + jsonData[x].UserName + "</a></span><span class=\"subscibercount\">" + Subscriber + " Followers</span><img class=\"hide\" id=\"ajax_load\" src=\"/images/ajax_loader_blue.gif\" /><img src=\"../../Images/remove.png\" alt=\"Remove Feed\" class=\"cross\" onclick=\"RemoveChannel(this,'" + jsonData[x].UserName + "');\" /></li>";

        }
        $('ul#following').empty();
        $('ul#following').append(channellist);
        $('#displayUserFeed >div.feed').hide('slow');
        $('#channel_add_status').html("<img src=\"/Images/noerror.png\"> Your Channel Subscription has been Updated.").fadeIn('slow').fadeOut(2000);

    }
    else {
        $('#message').text(data.Message).show();
        setTimeout("$('#message').hide()", 3000);
    }
}



function popitup(url) {
    newwindow = window.open(url, 'FeedBoks');
    if (window.focus) { newwindow.focus();
    }
    return false;
}
function eventHandler(evt) {

    if (evt.type == 'addthis.menu.share') {

        CreateTopicAjax(evt.data.url);
    }

};

function CreateTopicAjax(dest) {
    var TopicID;
    var split_array = unescape(dest.replace(/\+/g, " ")).split('/');
    var title = split_array[split_array.length - 1];
    var feedid= split_array[split_array.length - 2];
    $.ajax({
        type: "POST",
        url: "/CreateTopicAjax/" + feedid + "/" + title,
        data: {},
        dataType: "json",
        async: false,
        beforeSend: function () {

        },
        complete: function () {

        },
        success: function (result) {
            if (result.IsSuccessful) {
                TopicID = JSON.parse(result.ReturnValue);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

        }
    });

    return TopicID;
}






/*Top topics end*/
var uservoiceOptions = {
    /* required */
    key: 'feedboks',
    host: 'feedboks.uservoice.com',
    forum: '35548',
    showTab: true,
    /* optional */
    alignment: 'right',
    background_color: '#000',
    text_color: 'white',
    hover_color: '#4180D9',
    lang: 'en'
};

function _loadUserVoice() {
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', ("https:" == document.location.protocol ? "https://" : "http://") + "cdn.uservoice.com/javascripts/widgets/tab.js");
    document.getElementsByTagName('head')[0].appendChild(s);
}
_loadSuper = window.onload;
window.onload = (typeof window.onload != 'function') ? _loadUserVoice : function() { _loadSuper(); _loadUserVoice(); };




function ValidEmail(email) {
    var result = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($.trim(email));
    return result;
}

function ValidUrl(url) {

    
    return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url);
}

