﻿/// <reference path="dev/jquery-1.6.1.js" />
/// <reference path="dev/jquery-ui.js" /
/// <reference path="jquery.hoverIntent.minified.js" />
/// <reference path="jquery-jtemplates.js" />
/// <reference path="jquery.jscrollpane.min.js" />
/// <reference path="jquery.mousewheel.js" />
/// <reference path="jquery.watermark.min.js" />
/// <reference path="jquery.highlight-3.js" />

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// articles

var loadingArticles = false;
var articlesStop = false;
var topicsStop = false;

$(function () {
    // if articleID in query string, show it
    var articleID = getUrlVars()["a"];
    if (articleID) showArticlePopup(articleID);

    // round hover element for first and last article
    $('.news:first, .news-nohover2:first').live({
        'mouseenter': function () {
            if (!$(this).hasClass('rbl'))
                $(this).addClass('rtl').addClass('rtr');
        }
    });

    $('.news:last, .news-nohover2:last').live({
        'mouseenter': function () {
            if (!$(this).hasClass('rtl'))
                $(this).addClass('rbl').addClass('rbr');
        }
    });

    // articles comments
    $('#news-comments').live({
        'mouseenter': function (e) {
            var fmtComments = $(this).parent().parent().find('input#fmtComments').val();

            if (fmtComments == '0')
                $(this).attr('title', 'Start Discussion');
            else
                $(this).attr('title', 'Join Discussion');
        }
    });

    $('#news-comments').live({
        'mouseup': function (e) {
            var articleID = $(this).parent().parent().find('input#articleID').val();
            discussArticle(articleID);
        }
    });

    // default to first page
    $('input#articles-page').val(1);

    // article highlight
    $('#news-flag').live('mouseup', function () {
        articleHighlight($(this).parent().parent());
    });

    // article copy
    $('.news').live('mouseenter', function () {
        if ($(this).find('.zclip').length <= 0) { // add zclip if doesn't already exist
            $(this).find('#news-copy').zclip({
                path: '/js/ZeroClipboard.swf',
                copy: function () {
                    var newsParent = $(this).parent().parent();
                    return '<a href="http://' + window.location.host + '?a=' + $(newsParent).find('input#articleID').val() + '" target="_blank" style="font-weight: bold;">' + $(newsParent).find('input#sourceName').val() + ': ' + $(newsParent).find('h1').text() + '</a><br /><br />\n\n' + $(newsParent).find('p').text();
                },
                afterCopy: function () {
                    // nothing
                }
            });
        }

        $(this).find('.zclip').attr('title', 'Copy');
    });

    // article popup
    $('.news > h1 > a, .news-nohover2 > h1 > a').live('mouseup', function () {
        showArticlePopup($(this).parent().parent().find('input#articleID').val());
        return false;
    });

    // load
    loadMoreArticles();
});

// load more on scroll to bottom with 450px buffer
$(window).scroll(function () {
    if ($(window).height() + $(window).scrollTop() >= $(document).height() - 450)
        loadMoreArticles();
});

function loadMoreArticles () {
    if (!loadingArticles && !articlesStop) {
        loadingArticles = true;

        var _current = "";
        $('#articles').children().each(function(index) {
            _current += $(this).find('input#articleID').val() + ",";
        });

        var _page = $('input#articles-page').val();

        if (_page > 1)
            $('#news-loading').show();

        $.ajax({
            cache: false,
            async: true,
            type: "GET",
            dataType: "json",
            url: "/svc/Articles.svc/getArticleList",
            data: { page: _page, current: _current, type: "home" },
            contentType: "application/json;charset=utf-8",
            success: function (r) {
                if (r.d.length == 0)
                    articlesStop = true
                else {
                    $('#articles-append').setTemplateURL('/jtemplates/article.html', null, { filter_data: false });
                    $('#articles-append').processTemplate(r);

                    // add buttons
                    $('#articles-append div.news #news-buttons').each(function () {
                        // add flag
                        if ($('body > input#userLevelID').val() == 9)
                            $(this).append('<div id="news-flag" title="Mark" class="link" style="display: table-cell; vertical-align: middle; padding: 3px 6px;"><img src="/images/flag_79.png" /></div>');

                        // add comments
                        if ($(this).parent().find('input#fmtComments').val() == 0)
                            $(this).append('<div id="news-comments" class="link" style="display: table-cell; vertical-align: middle; padding: 3px 6px;"><img src="/images/comments_79.png" /></div>')
                        else
                            $(this).append('<div id="news-comments" class="link" style="display: table-cell; vertical-align: middle; padding: 3px 6px;"><div style="display: table-cell; vertical-align: middle; padding-right: 4px;"><img src="/images/comments_79.png" /></div><div style="display: table-cell; height: 17px; text-align: center; vertical-align: middle; color: #a4a4a4; font-size: 10px; background-color: #e3e3e3; border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px; padding: 0 5px;">' + $(this).parent().find('input#fmtComments').val() + '</div></div>');

                        // add copy
                        $(this).append('<div id="news-copy" class="link" style="display: table-cell; vertical-align: middle;  padding: 3px 6px;"><img src="/images/copy_79.png" /></div>')
                    });

                    $('#articles').append($('#articles-append').html());
                    $('#articles-append').html('');

                    $('input#articles-page').val(parseInt(_page) + 1);
                }

                $('#news-loading').hide();
                loadingArticles = false;
            }
        });
    }
}

$(function () {
    setInterval("loadNewArticles()", 90000);
});

function loadNewArticles () {
    var _current = "";
    $('#articles').children().each(function (index) {
        _current += $(this).find('input#articleID').val() + ",";
    });

    $.ajax({
        cache: false,
        async: true,
        type: "GET",
        dataType: "json",
        url: "/svc/Articles.svc/getArticleList",
        data: { page: 0, current: _current, type: "home" },
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            $('#articles-prepend').setTemplateURL('/jtemplates/article.html', null, { filter_data: false });
            $('#articles-prepend').processTemplate(r);

            // add buttons
            $('#articles-prepend div.news #news-buttons').each(function () {
                // add flag
                if ($('body > input#userLevelID').val() == 9)
                    $(this).append('<div id="news-flag" title="Mark" class="link" style="display: table-cell; vertical-align: middle; padding: 3px 6px;"><img src="/images/flag_79.png" /></div>');

                // add comments
                if ($(this).parent().find('input#fmtComments').val() == 0)
                    $(this).append('<div id="news-comments" class="link" style="display: table-cell; vertical-align: middle; padding: 3px 6px;"><img src="/images/comments_79.png" /></div>')
                else
                    $(this).append('<div id="news-comments" class="link" style="display: table-cell; vertical-align: middle; padding: 3px 6px;"><div style="display: table-cell; vertical-align: middle; padding-right: 4px;"><img src="/images/comments_79.png" /></div><div style="display: table-cell; height: 17px; text-align: center; vertical-align: middle; color: #a4a4a4; font-size: 10px; background-color: #e3e3e3; border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px; padding: 0 5px;">' + $(this).parent().find('input#fmtComments').val() + '</div></div>');

                // add copy
                $(this).append('<div id="news-copy" class="link" style="display: table-cell; vertical-align: middle;  padding: 3px 6px;"><img src="/images/copy_79.png" /></div>')
            });

            $('#articles').prepend($('#articles-prepend').html());
            $('#articles-prepend').html('')
        }
    });
}

function showArticlePopup(_id) {
    $('#popupContent').text('');

    getBrowserWidthHeight();
    $('#popupContent').css("max-height", h - 200);

    $.ajax({
        cache: false,
        async: true,
        type: "GET",
        dataType: "json",
        url: "/svc/Articles.svc/getArticle",
        data: { _articleId: _id },
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            $('#popupContent').setTemplateURL('/jtemplates/article.popup.html', null, { filter_data: false });
            $('#popupContent').processTemplate(r);

            $('#popupOverlay').show();
            $("body").css("overflow", "hidden");
            $('#popupContainer').fadeIn('fast');
        }
    });

    return false;
};

function discussArticle(_id) {
    // determine if message already exists, if it does, go there
    $.ajax({
        cache: false,
        async: true,
        type: "GET",
        dataType: "json",
        url: "/svc/Articles.svc/getArticleMessage",
        data: { _articleId: _id },
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            if (r.d > 0)
                window.location = 'http://' + window.location.host + '/boards/message.aspx?m=' + r.d;
            else {
                if (readCookie('notpleased')) {
                    // no discussion exists, prompt for board
                    $('#popupContent').text('');
                    $('#popupContent').css({ 'width': '400px', 'overflow-y': 'hidden', 'text-align': 'center' });

                    $('#popupContent').html('<div style="font-size: 13px;"><b>Discuss where?</b> &nbsp; <select id="discussArticleBoard"><option value="3">Football</option><option value="4">Basketball</option><option value="10">Other Sports</option><option value="5">Off Topic</option></select> &nbsp; <div class="button" onclick="discussArticle2(' + _id + ');" title="Start Discussion"><img src="/images/comments_79.png" /></div></div>');

                    $('#popupOverlay').show();
                    $("body").css("overflow", "hidden");
                    $('#popupContainer').fadeIn('fast');
                }
            }
        }
    });

    return false;
};

function discussArticle2(_id) {
    // determine if message already exists, if it does, go there
    var boardID = $('#discussArticleBoard').val();

    $.ajax({
        cache: false,
        async: true,
        type: "GET",
        dataType: "json",
        url: "/svc/Articles.svc/getArticleMessage",
        data: { _articleId: _id },
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            if (r.d > 0)
                window.location = 'http://' + window.location.host + '/boards/message.aspx?m=' + r.d;
            else {
                if (readCookie('notpleased')) {
                    // no discussion exists, create one
                    var data = {
                        _articleID: _id,
                        _boardID: boardID
                    }

                    $.ajax({
                        cache: false,
                        async: true,
                        type: "POST",
                        dataType: "json",
                        url: "/svc/Articles.svc/createArticleDiscussion",
                        data: JSON.stringify(data),
                        contentType: "application/json;charset=utf-8",
                        success: function (r) {
                            window.location = 'http://' + window.location.host + '/boards/message.aspx?m=' + r.d;
                        }
                    });
                }
            }
        }
    });

    return false;
};

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// topics

var loadingTopics = false;

$(function () {
    // stop mouse wheel outside source div
    $('#topics').mousewheel(function (event) {
        return false;
    });

    // load topics
    refreshTopics();

    // bind div scroll to load more topics
    $('#topics').bind('scroll', topics_scroll);
});

// load more topics in div when within 150px of bottom of div
function topics_scroll() {
    var pane = parseInt($(this).find('.jspPane').css('top'));
    pane = (pane * -1);
    var totalPanePos = pane + parseInt($(this).find('.jspTrack').innerHeight());

    //alert($(this).find('#topics-div').innerHeight() + " / " + totalPanePos);

    if ($(this).find('#topics-div').innerHeight() <= totalPanePos + 150)
        loadMoreTopics(false);
}

function loadMoreTopics(clearDiv) {
    if (!loadingTopics && !topicsStop) {
        var cookie = readCookie('notpleased');
        loadingTopics = true;

        var _current = "";

        if (!clearDiv) {
            $('#topics-div').children().each(function (index) {
                _current += $(this).find('input#messageID').val() + ",";
            });
        }

        var _page = $('input#topics-page').val();

        if (_page > 1)
            $('#topics-loading').show();

        $.ajax({
            cache: false,
            async: true,
            type: "GET",
            dataType: "json",
            url: "/svc/Boards.svc/getTopicList",
            data: { boardID: 0, page: _page, current: _current, token: cookie },
            contentType: "application/json;charset=utf-8",
            success: function (r) {
                if (r.d.length == 0)
                    topicsStop = true
                else {
                    $('#topics-append').setTemplateURL('/jtemplates/topic.home.html', null, { filter_data: false });
                    $('#topics-append').processTemplate(r);

                    if (clearDiv)
                        $('#topics-div').html('');

                    $('#topics-div').append($('#topics-append').html());

                    $('#topics-loading').hide();
                    $('#topics').jScrollPane();
                    $('#topics-loading').show();

                    $('#topics-append').html('');

                    $('#topics input#topics-page').val(parseInt(_page) + 1);

                    /*if (!$('#yeller').is(':visible')) {
                        $('#yeller').fadeIn(750);
                        $('#yeller').animate({ left: '+=120', bottom: '+=120' }, 750);
                    }*/
                }

                loadingTopics = false;
            }
        });
    }
}

function refreshTopics() {
    topicsStop = false;
    $('input#topics-page').val(1);

    loadMoreTopics(true);
}

$(function () {
    setInterval("refreshTopics()", 60000);
});

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// tweets

$(function () {
    $('#home-tweets').height($('#home-topics').height() + 10);
    $('#tweets').height($('#home-tweets').height() - 8);

    // tweets hover
    $('.tweet_list li').live({
        'mouseenter': function () {
            $(this).find('#tweet-comment').show();
        },
        'mouseleave': function () {
            $(this).find('#tweet-comment').hide();
        }
    });

    // articles comments click
    $('#tweet-comment').live({
        'mouseup': function (e) {
            var image = $(this).parent().parent().find('.tweet_avatar img').attr('src');
            var url = $(this).parent().parent().find('.tweet_time a').attr('href');
            var name = $(this).parent().parent().find('.tweet_avatar').attr('href').replace('http://twitter.com/', '');
            var tweet = $(this).parent().parent().find('.tweet_text').text();

            var title = escape(name + ': ' + tweet);
            var body = escape('<div><div style="display: table-cell; vertical-align: top; padding-right: 10px;"><img src="' + image + '" /></div>') + escape('<div style="display: table-cell; vertical-align: top;"><b><a href="' + url + '" target="_blank">' + name + '</a> said...</b><br>') + escape(tweet) + escape('</div></div>');

            window.open('http://' + window.location.host + '/boards/post.aspx?'/*title=' + escape(title) + '&*/ + 'type=tweet&body=' + escape(body));
            return false;
        }
    });

    return false;
});

$(function () {
    $(".tweet").tweet({
        avatar_size: 32,
        count: 50,
        filter: function (t) { return !/^@\w+/.test(t["tweet_raw_text"]); },
        username: "NotPleasedcom",
        list: "Pitt",
        loading_text: "",
        refresh_interval: 180
    }).bind("loaded", function () {
        // add discuss tweet div
        var div = '<div style="position: relative;"><div id="tweet-comment" class="link"><div id="tweet-comment-image"><img src="/images/replies_white.png" /></div><div id="tweet-comment-text">Discuss</div></div></div>';
        $('.tweet_list li').each(function () {
            $(this).append(div);
        });

        // change links to open up new window
        $(this).find("a").attr("target", "_blank");
        cycleTweets();
    });

    return false;
});

function cycleTweets() {
    $('.tweet_list li:first').delay(5000).animate({ opacity: .25 }, 800);
    $('.tweet_list li:first').animate({ marginTop: ($('.tweet_list li:first').height() * -1) - 12, opacity: 0 }, 500,
        function () {
            $('.tweet_list li:first').remove();

            if ($('.tweet_list li').length > 6) // 6 beacuse it's the number of tweets displayed in box
                cycleTweets();
        }
    );

    return false;
};

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// admin 

function articleHighlight(obj) {
    if ($(obj).hasClass('news-highlight')) {
        $(obj).addClass('news');
        $(obj).removeClass('news-nohover2');
        $(obj).removeClass('news-highlight');
    } else {
        $(obj).removeClass('news');
        $(obj).addClass('news-nohover2');
        $(obj).addClass('news-highlight');
    }

    return false;
}

function showAdminPanel() {
    if ($('#admin').is(":visible"))
        $('#admin').hide(500);
    else
        $('#admin').show(500);

    return false;
}

function doAdminAction() {
    var _current = "";
    $('.news-highlight').each(function (index) {
        _current += $(this).find('input#articleID').val() + ",";
    });

    if ($('#action').val() == "Delete Articles")
        adminArticlesDelete(_current);

    return false;
}

function adminArticlesDelete(ids) {
    var cookie = readCookie('notpleased')

    $.ajax({
        cache: false,
        async: true,
        type: "POST",
        dataType: "json",
        url: "/svc/Articles.svc/adminDelete",
        data: '{ "articles": "' + ids + '", "token": "' + cookie + '" }',
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            if (r.d == "SUCCESS")
                removeArticles();
        }
    });

    return false;
}

function removeArticles() {
    $('.news-highlight').fadeOut(500, function () {
        $(this).remove();
    });

    return false;
}
