﻿
//
// ArticleListing.js
//   for ~/Modules/ArticleListing.ascx
//

/// <reference path="../Edentity.Global.js" />
/// <reference path="../External/jquery-1.3.2-vsdoc2.js" />

$(document).ready(function () {
	if($.browser.mozilla) $("form").attr("autocomplete", "off");
	
    if (ArticleListing_doRequest == 'True') { 
        SetFromUrlHash();
        RequestArticles();
    }
    else {
        RateArticle();
        SetArticleActionsBkg();
    }
});

function RateArticle() { 
    RequestRating();
    var id = ArticleListing_CurrentArticle_ID;
    var cookie = GetWNetworkRatingCookie();
    if (cookie != null && cookie.indexOf(',Article-' + id + ',') > -1) {
        $('div.RatingStars').hide();
        $('div.Thanks').show();
    }
}

function SubmitRating(value) {
    var id = ArticleListing_CurrentArticle_ID;
    $.ajax({
        type: "POST",
        url: ArticleListing_ASMX_Url + '/SubmitRating',
        data: "{'Object':'Article','ObjectID':" + id + ",'Rating': " + value + ",'UserID':null}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.d != undefined && result.d != null) {
                SetWNetworkRatingCookie('Article-' + id);
                $('div.RatingStars').hide();
                $('div.Thanks').show();
                RenderRated(result.d);
            }
        },
        complete: function(XMLHttpRequest, textStatus) {
            //alert(XMLHttpRequest.status + ' ' + textStatus);
            //alert(XMLHttpRequest.responseText);
        }
    });
}

function RenderRated(value) {
    var rated = Math.ceil(value);
    var html = '';
    for (var i = 1; i <= 5; i++) {
        html += "<input class='star' type='radio' name='RatedStars' value='" + i + "' disabled='disabled' ";
        if (i == rated) {
            html += "checked='checked'";
        }
        html += "/>";
    }
    $('div.RatedStars').html(html);
    $('div.RatedStars :radio.star').rating(); 
}

function RenderRating(rated) {
    var html = '';
    rated = Math.ceil(rated);
    for (var i = 1; i <= 5; i++) {
        html += "<input class='star2' type='radio' name='RatingStars' value='" + i + "' ";
        if (i == rated) {
            html += "checked='checked'";
        }
        html += "/>";
    }
    $('div.RatingStars').append("<div class='Left'>" + html + "</div><div class='Clear'></div>");

    $('div.RatingStars :radio.star2').rating({ 
        callback: function(value, link){ 
            SubmitRating(value);
        } 
    });  
}
   
function RequestRating() {
    var id = ArticleListing_CurrentArticle_ID;
    $.ajax({
        type: "POST",
        url: ArticleListing_ASMX_Url + '/RatingResults',
        data: "{'Object':'Article','ObjectID':" + id + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.d != undefined && result.d != null) {
                RenderRated(result.d);
                RenderRating(result.d);
            }
        },
        complete: function(XMLHttpRequest, textStatus) {
            //alert(XMLHttpRequest.status + ' ' + textStatus);
            //alert(XMLHttpRequest.responseText);
        }
    });
}

function IsLargeArticle() {
    var width = $ArticleListing_pnlArticleDetail.width();
    //alert(width);
    return width > 435;
}

function SetArticleActionsBkg() {
    if (!IsLargeArticle()) {
        $('div.ArticleActions').addClass('ShortActionBkg');
        $('div.ArticleComment').addClass('ShortCommentsBkg');
    }
    else {
        $('div.ArticleDetail').addClass('LargeArticle');
        $('div.ArticleActions').addClass('LargeActionBkg');
        $('div.ArticleComment').addClass('LargeCommentsBkg');
    }
}

function RenderPagination() {
    var LeftAdded = false;
    var RightAdded = false;
    var PageSpace = 2;
    if (ArticleListing_CurrentPage < 4) {
        PageSpace = 5 - ArticleListing_CurrentPage;
    }
    if (ArticleListing_CurrentPage > TotalPages - 4) {
        PageSpace = 5 - (TotalPages - ArticleListing_CurrentPage);
    }
    var div = $ArticleListing_divPagination;
    if (ArticleListing_Pagination && TotalPages > 1) {
        var html = '<span>Page</span>';
        for (var i = 1; i <= TotalPages; i++) {
            if (i > ArticleListing_CurrentPage + PageSpace && i < TotalPages) {
                if (!RightAdded) {
                    html += "<span>&nbsp;...&nbsp;</span>";
                    RightAdded = true;
                }
            }
            else if (i > 1 && i < ArticleListing_CurrentPage - PageSpace) {
                if (!LeftAdded) {
                    html += "<span>&nbsp;...&nbsp;</span>";
                    LeftAdded = true;
                }
            }
            else {
                html += "<a " + (i == ArticleListing_CurrentPage ? "class='Selected'" : "") + " >" + i + "</a>";
            }
        }
        div.html(html);
        $('a:not(.Selected)', div).attr('href', 'javascript:void(0);');
        $('a:not(.Selected)', div).click(function () {
            ArticleListing_CurrentPage = eval($(this).text());
            if (!DoingRequest) {
                RequestArticles();
            }
        });
        div.show();
    }
    else {
        div.hide();
    }
}

var Articles = [];
var TotalPages = 0;
var DoingRequest = true;
var TitleFilter = '';

function RequestArticles_Callback(result){

    var Filters = " ";
    if (TitleFilter.length > 0) {
        if (TitleFilter.length == 1) {
            Filters = "ArticleTitle LIKE '" + TitleFilter + "%'";
        }
        else {
            Filters = "ArticleTitle LIKE '%" + TitleFilter + "%'";
        }
    }
    Filters = Base64.encode(Filters);

    var Topic = ArticleListing_selectedTopic;

    var Tag = ArticleListing_Module_Tags;
    if (selectedTag > 0) {
        if (Tag.length > 0) {
            Tag += ",";
        }
        Tag += selectedTag;
    }
    if (Tag == "") {
        Tag = "0";
    }

    if (result.GetArticlesResult != undefined && result.GetArticlesResult != null) {
        Articles = [];
        Articles = result.GetArticlesResult.ArticleList;
        TotalPages = result.GetArticlesResult.TotalPages;
        RenderArticles();

        RenderViewByTopic();
        Tags = result.GetArticlesResult.ArticleTags;
        RenderViewByTag();
        RenderViewByPop();

        RenderPagination();
        RenderAlphaIndex();

        SaveToUrlHash(Topic, Tag, selectedPop);
        
        DoingRequest = false;
    }
}

function RequestArticles() {

    var Filters = " ";
    if (TitleFilter.length > 0) {
        if (TitleFilter.length == 1) {
            Filters = "ArticleTitle LIKE '" + TitleFilter + "%'";
        }
        else {
            Filters = "ArticleTitle LIKE '%" + TitleFilter + "%'";
        }
    }
    Filters = Base64.encode(Filters);

    var Topic = ArticleListing_selectedTopic;

    var Tag = ArticleListing_Module_Tags;
    if (selectedTag > 0) {
        if (Tag.length > 0) {
            Tag += ",";
        }
        Tag += selectedTag;
    }
    if (Tag == "") {
        Tag = "0";
    }
    
    if (Filters.length > 0) {
        DoingRequest = true;
        var FilterWith = Topic + '/' + Tag + '/' + selectedPop + '/' + ArticleListing_PageLen + '/' + ArticleListing_CurrentPage;
        var wsUrl = wcfHostHeader + '/WebServices/Articles.svc/ArticleListing/' + ArticleListing_ContentReferenceName + '/' + Filters + '/' 
            + ArticleListing_SortOrder + '/' + FilterWith + "?method=RequestArticles_Callback";
        $.ajax({
            url: wsUrl,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp"
        });
    }
}

function SaveToUrlHash(topic, tag, pop) {
    window.location.hash = '#' + topic + '|' + tag + '|' + pop;
}

function SetFromUrlHash() {
    var hash = window.location.hash;
    if (hash != undefined && hash != null && hash != '' && hash.split('#').length == 2) {
        var ids = hash.split('#')[1].split("|"); //Removes the '#'
        if (ids.length == 3) {
            ArticleListing_selectedTopic = ids[0]; 
            selectedTag = ids[1];
            selectedPop = ids[2];
        }
    }
}

function Title2Url(title) {
    var url = title.replace(/ /gi, "-").replace(/[^a-z0-9-]/gi, "").replace(/-+/g, '-');
    url = ArticleListing_DetailsUrl.replace(/.aspx/i, "/" + url + ".aspx");
    return url;
}

function RenderArticles() {
    var divArticles = $ArticleListing_divArticles;
    var html = "<div class='Article'></div>";
    for (var i = 0; i < Articles.length; i++) {
        html += "<div class='Article'>";
        if (ArticleListing_inDetails == 'True') {
            html += "<div class='Name'><a href='" + ArticleListing_DetailsUrl + "?ArticleID=" + Articles[i].ID + "'>" + 
                    Articles[i].ArticleTitle + "</a></div>";
        }
        else {
            html += "<div class='Name'><a href=\"" + Title2Url(Articles[i].ArticleTitle) + "\">" + 
                    Articles[i].ArticleTitle + "</a></div>";
        }
        html += "<div class='Right'>";
        html += "<img class='SlideShowList' src='" + ArticleListing_SlideDownArrow + "' ";
        html += "onclick='ToggleArticleView(this, " + Articles[i].ID + ");' /></div><div class='Clear'></div>";
        html += "<div class='Summary'></div><div class='Clear'></div></div>";
    }
    divArticles.html(html);
}

function toggleSummary(sender) {
    var div = $(sender).parent().next().next();
    var isOpen = $(sender).attr('src').indexOf("Up") > -1;
    if (isOpen) {
        div.slideUp();
        $(sender).attr('src', ArticleListing_SlideDownArrow);
    }
    else {
        // Close anyone open
        CloseOpen(sender);
        
        div.slideDown();
        $(sender).attr('src', ArticleListing_SlideUpArrow);
    }
}

function CloseOpen(sender) {
    $(".Summary", $(sender).parent().parent().parent()).each(function () {
        if ($(this).is(":visible")) {
            $(this).slideUp();
            $('img', $(this).prev().prev()).attr('src', ArticleListing_SlideDownArrow);
        }
    });
}

function ToggleArticleView(sender, contentID) {
    var isOpen = $(sender).attr('src').indexOf("Up") > -1;
    // Get Summary div
    var div = $(sender).parent().next().next();
    if (!isOpen && div.html().length == 0) { // Never opened
        div.html("<img src='" + ArticleListing_Loading + "' />");
        div.show();
        RequestArticle(sender, contentID);
    }
    else {
        toggleSummary(sender);
    }
}

var lastSender = null;
function RequestArticle_Callback(result){
    if (result.GetArticleResult != undefined && result.GetArticleResult != null) {
        var article = result.GetArticleResult;
        var html = "<span>" + SummarizeHtmlText(article.Body) + "</span>";
        if (ArticleListing_inDetails == 'True') {
            html += "&nbsp;<a href='" + ArticleListing_DetailsUrl + "?ArticleID=" + article.ID + "'>" + 
                article.ArticleTitle + "</a><br/>";
        }
        else {
            html += "&nbsp;<a href=\"" + Title2Url(article.ArticleTitle) + "\">" + ArticleListing_ReadMore + "</a><br/>";
        }
        // Get Summary div
        var div = $(lastSender).parent().next().next();
        div.hide();
        div.html(html);
        toggleSummary(lastSender);
    }
}

function RequestArticle(sender, ContentID) {
   lastSender = sender;
    $.ajax({
        //ifModified: true,
        url: wcfHostHeader + '/WebServices/Articles.svc/Article/' + ContentID + "?method=RequestArticle_Callback",
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp"
    });
}

function SummarizeHtmlText(html)  {
    if (html == null) {
        return '';
    }
    var text = jQuery('<div/>').html(html).text();
    if (text.length > 160) {
        return text.substring(0, 160) + ' ..';
    }
    else {
        return text;
    }
}

function RenderAlphaIndex() {
    if (ArticleListing_ShowAlphanumericIndex) {
        var html = '<div>';
        for (var i = 65; i < 91; i++) {
            html += "<a " + 
                ((TitleFilter.length == 1 && TitleFilter == String.fromCharCode(i)) ? "class='Selected'>" : '>') + 
                String.fromCharCode(i) + "</a>";
            if (i - 65 == 13) {
                html += "</div><br/><div>";
            }
        }
        html += "<a>0-9</a></div><div class='Clear'></div>";
        var ai = $(".AlphaIndex", $ArticleListing_pnlAlphanumericIndex).html(html);
        $('a', ai).click(function () {
            $('a', ai).removeClass("Selected");
            $(this).addClass("Selected");
            $('#txtSearchArticle').val($(this).text());
            FilterListing($(this).text());
        });
    }
}

function DoSearch(sender) {
    var ai = $(".AlphaIndex", $ArticleListing_pnlAlphanumericIndex);
    $('a', ai).removeClass("Selected");
    FilterListing($(sender).prev().val());
}

function FilterListing(text) {
    TitleFilter = text;
    RequestArticles();
}

function isNumber(input) {
    return (input - 0) == input && input.length > 0;
}

var TopicDropDown = null;

function RenderViewByTopic() {
    if (ArticleListing_ShowViewBy && ArticleListing_Topics.length > 0) {
        TopicDropDown = $ArticleListing_divTopicFilter.WSelectBox({
            DefaultText: ArticleListing_ViewByTopicLabel,
            ClearItemText: "--clear--",
            KeyFieldName: "ID",
            ValueFieldName: "Name",
            SelectedValue: ArticleListing_selectedTopic,
            Items: ArticleListing_Topics,
            Horizontal: true,
            SelectImage: ArticleListing_btnSelectBox,
            onSelectedChange: function (selectedvalue, selectedtext) {
                //console.log("text: " + selectedtext + ", value: " + selectedvalue);
                $("#ArticleListingTitle").text(selectedtext.toUpperCase() + " ARTICLES");
                ArticleListing_selectedTopic = selectedvalue;
                if (!DoingRequest) {
                    if (ArticleListing_Pagination) {
                        ArticleListing_CurrentPage = 1;
                    }
                    RequestArticles();
                }
            }
        });
        $ArticleListing_divTopicFilter.show();
    }
    else {
        $ArticleListing_divTopicFilter.hide();
        ArticleListing_selectedTopic = 0;
    }
}

var Tags = [];
var TagsDropDown = null;
var selectedTag = 0;

function RenderViewByTag() {
    if (ArticleListing_ShowViewBy && Tags.length > 0) {
        TagsDropDown = $ArticleListing_divTagFilter.WSelectBox({
            DefaultText: ArticleListing_ViewByKeywordLabel,
            ClearItemText: "--clear--",
            KeyFieldName: "key",
            ValueFieldName: "value",
            Items: Tags,
            SelectedValue: selectedTag,
            SelectImage: ArticleListing_btnSelectBox,
            Horizontal: true,
            onSelectedChange: function (selectedvalue, selectedtext) {
                selectedTag = selectedvalue;
                if (!DoingRequest) {
                    if (ArticleListing_Pagination) {
                        ArticleListing_CurrentPage = 1;
                    }
                    RequestArticles();
                }
            }
        });
        $ArticleListing_divTagFilter.show();
    }
    else {
        $ArticleListing_divTagFilter.hide();
        selectedTag = 0;
    }
}

var PopsDropDown = null;
var selectedPop = 0;

function RenderViewByPop() {
    if (ArticleListing_ShowViewBy && ArticleListing_Pops.length > 0) {
        PopsDropDown = $ArticleListing_divPopularityFilter.WSelectBox({
            DefaultText: ArticleListing_ViewByPopularityLabel,
            ClearItemText: "--clear--",
            KeyFieldName: "ID",
            ValueFieldName: "Name",
            Items: ArticleListing_Pops,
            SelectedValue: selectedPop,
            SelectImage: ArticleListing_btnSelectBox,
            Horizontal: true,
            onSelectedChange: function (selectedvalue, selectedtext) {
                selectedPop = selectedvalue;
                if (!DoingRequest) {
                    if (ArticleListing_Pagination) {
                        ArticleListing_CurrentPage = 1;
                    }
                    RequestArticles();
                }
            }
        });
        $ArticleListing_divPopularityFilter.show();
    }
    else {
        $ArticleListing_divPopularityFilter.hide();
        selectedPop = 0;
    }
}

function SelectSubPage(sender) {
    $('a', $(sender).parent()).removeClass('Selected');
    $(sender).addClass('Selected');
    $('.ArticleBody', $(sender).parent().parent()).html($(sender).next().html());
}

function ShowShareThis(sender)
{
    $(sender).parent().find('a').trigger('click');
}

