
var currentNewsTitle;
var currentNewsDate;
var currentShowStatusUpdates;
var currentShowComments;
var updatedNewsTitle;
var g_HideCommentsText = 'Hide Comments';
var g_ShowCommentsText = 'Show Comments';
var g_HideStatusUpdatesText = 'Hide Status Updates';
var g_ShowStatusUpdatesText = 'Show Status Updates';
var g_ShowOneMorePost = 'Show 1 more post';
var g_ShowMorePosts = 'Show %%TOTAL%% more posts';

function SetNewsUpdate(dt)
{
    currentNewsTitle= document.title;
    currentNewsDate= dt;
    setInterval("GetNewsUpdates()",60000); //60 seconds
}

function GetNewsUpdates()
{
    var statuses= (currentShowStatusUpdates) ? "1" : "0";
    
    $.post("news/news_refresh.aspx", {MaxDate: currentNewsDate, ShowStatusUpdates: statuses}, function(response) { 
                
         var arr;                     
         try { arr= eval(response); }
         catch (e) { return; }
          
         var total= arr[0].Total;
      
         if (total > 0)
         {
            var display= (total >= 20) ? "20+" : total;
            var text = "";
            
            if (total == 1)
            {
                text = g_ShowOneMorePost;
            }
            else
            {
                text = g_ShowMorePosts.replace("%%TOTAL%%", display);
            }
         
            $(".refresh-anim").html(text).show();
            updatedNewsTitle= "("+ total +") " + currentNewsTitle;
         }
         else
         {
            $(".refresh-anim").hide();
            updatedNewsTitle= currentNewsTitle;
         }    
         
         document.title= updatedNewsTitle;
    });
}

var g_StatusUpdateDisplayMax= 15;
var g_NewStatusUpdateCount= 0;

function OnNewsFeedAdd()
{
    g_NewStatusUpdateCount++;
    var $rows= $("table#jq-today-items tr.row-1");
    
    if (g_NewStatusUpdateCount > g_StatusUpdateDisplayMax)
    {
        $rows.eq(g_StatusUpdateDisplayMax - 1).hide();
    }
}

function SetNewsPreferences(bStatus,bComment)
{
    currentShowStatusUpdates= bStatus;
    currentShowComments= bComment;
    
    var statusLink= $("#toggle-status-updates");
    var commentLink= $("#toggle-comments");
        
    if (statusLink.length > 0)
    {
        var statusDisplay= (bStatus) ? g_HideStatusUpdatesText : g_ShowStatusUpdatesText;
        statusLink.html(statusDisplay);
        statusLink.click(function() { OnToggleStatusUpdates(); return false; });  
    }
    
    if (commentLink.length > 0)
    {
        var commentDisplay= (bComment) ? g_HideCommentsText : g_ShowCommentsText;
        commentLink.html(commentDisplay);      
        commentLink.click(function() { OnToggleComments(); return false });
    }
        
    $("#new-posts").show();
}

function OnToggleStatusUpdates()
{
    UpdateNewsPreference("statusupdate",!currentShowStatusUpdates, function() { window.location= "news.aspx"; });
}

function OnToggleComments()
{   
    currentShowComments= !currentShowComments;
    var display= (currentShowComments) ? g_HideCommentsText : g_ShowCommentsText;
 
    $("#toggle-comments").html(display);
    ShowComments(currentShowComments); 
    
    UpdateNewsPreference("comment",currentShowComments);
}

function ShowComments(bShow)
{    
    if (bShow)
    {
        $('.comment-list-active.ls-off').removeClass("ls-off").addClass("ls-on");
    }
    else
    {
        $('.comment-list-active.ls-on').removeClass("ls-on").addClass("ls-off");
        $('.comment-list-inactive.ls-on').removeClass("ls-on").addClass("ls-off");
    }   
}

function UpdateNewsPreference(type,bVal,CallBack)
{    
    var val= (bVal) ? "1" : "0";
    $.post("news/newspreferences_update.aspx", {Type: type, Value: val}, CallBack);
}

function ShowConsecutivePosts(Sender)
{
    var tr = $(Sender).parent().parent().nextAll();
    
    var rowclass = "row-1";
    var onclass = "ls-open";
    var offclass = "ls-off";
    var removeclass = offclass;
    var addclass = onclass;
    var lesstext = "less";
    var moretext = "more";
    var lessclass = "see-less";
    var moreclass = "see-more";
    
    if ($(Sender).is("."+lessclass))
    {
        removeclass = onclass;
        addclass = offclass;
        $(Sender).text($(Sender).text().replace(lesstext, moretext));
        $(Sender).removeClass(lessclass);
        $(Sender).addClass(moreclass);
    }
    else if ($(Sender).is("."+moreclass))
    {
        $(Sender).text($(Sender).text().replace(moretext, lesstext));  
        $(Sender).removeClass(moreclass);
        $(Sender).addClass(lessclass);  
    }
   
    for (i = 0; i < tr.length; i++)
    {
        var c = $(tr[i]).attr('class');
        
        if ($(tr[i]).is("."+removeclass))
        {
            $(tr[i]).removeClass(removeclass).addClass(addclass)
        }
        else
        {
            if (c == rowclass)
                return;
        }    
    }
}

var g_NewsToday;

function LoadNewsFeed()
{
    var $btnSubmit= $("input.jq-status-submit");
    
    if ($btnSubmit.length > 0)
    {
        $btnSubmit.click(function() { AddNewsStatusUpdate(this, 'jq-today', 'jq-today-items','news',OnNewsFeedAdd); return false; });
    }
    
    var args= {};

    var regToday= /[?&]today=([^&#]*)/ig;
    var results = regToday.exec(window.location.href);

    if (results != null)
        args.Today= decodeURIComponent(results[1].replace(/\+/gi, " "))
    
    CallNewsGet(args, function(response)
	{ 
	    var $response= $(response);	    
	    DisplayResponse($response);
	    
        $("#news-waiting").hide();
	});
	
	function DisplayResponse($response)
	{
	    var errorPanel= "span#jq-noresults-message";
	    
	    if (!$response.is("span#ajaxresponse"))
	    {
	        return;
	    }
	    else if ($response.find("span.jq-error").html().length > 0)
	    {
	        $(errorPanel).html($response.find("span.jq-error").html());
	        $(errorPanel).show();
	        return;
	    }
	    
	    var $newPosts= $("div#new-posts");
	    $newPosts.html($response.find("span#jq-new-posts").html());
	    
	    var $newsItems= $response.find("span#jq-newsitems");
	    
	    if ($newsItems.find("tr.row-1").length == 0)
	    {
	        $(errorPanel).show();	        
	    }
	    else
	    {  	    
    	    g_NewsToday= $response.find("span.jq-today").text();    	    
	        DisplayNewsItems($newsItems);
        }
        
        SetNewsUpdate($response.find("span.jq-news-refresh").text());
            
	    var bStatus= ($response.find("span.jq-bShowStatusUpdates").text() == "true");
	    var bComment= ($response.find("span.jq-bShowComments").text() == "true");
	    SetNewsPreferences(bStatus, bComment);
	}
}

function DisplayNewsItems($newsItems)
{
    var $todayRows= $newsItems.find("span#jq-today tr.row-1");
    var $yesterdayRows= $newsItems.find("span#jq-yesterday tr.row-1");
    var $earlierRows= $newsItems.find("span#jq-earlier tr.row-1");
    var bShowMore= ($newsItems.find("span.jq-bShowMore").text() == "true");    
    
    DisplayNewsBucket($todayRows, "div#jq-today", "table#jq-today-items", (bShowMore && $earlierRows.length == 0 && $yesterdayRows.length == 0));
    DisplayNewsBucket($yesterdayRows, "div#jq-yesterday", "table#jq-yesterday-items", (bShowMore && $earlierRows.length == 0 && $yesterdayRows.length > 0));
    DisplayNewsBucket($earlierRows, "div#jq-earlier", "table#jq-earlier-items", (bShowMore && $earlierRows.length > 0));
}

function DisplayNewsBucket($rows,divLabel,tableLabel, bShowMore)
{
    if ($rows.length == 0)
        return;
    
    $(divLabel).show();
    var $tbl= $(tableLabel);
    
    var prevCustomerID= '';
    var consecutiveCount= 0;
    var maxConsecutive= 3;
    var $trLast;
    var $existingRows= $tbl.find("tr.row-1");
    var bPreviousExpanded= false;
               
    for (var i=0; i < $rows.length; i++)
    {
        var $tr= $rows.eq(i);
        var customerID= $tr.find("span.jq-customerid").text();
        
        if (i == 0 && $existingRows.length > 0) //after more link, check if bucket already has rows.
        {
            var existingVisibleCount= 0;
        
            for (var j=0; j < $existingRows.length; j++)
            {
                var $trExisting= $existingRows.eq($existingRows.length - j - 1);
                var existingCustomerID= $trExisting.find("span.jq-customerid").text();
                
                if (j == 0)
                {
                    $trLast= $trExisting;
                    prevCustomerID= existingCustomerID;
                }
                
                if (existingCustomerID != customerID)
                    break;
                    
                if (!$trExisting.is(".ls-off"))
                    existingVisibleCount++;
                                    
                consecutiveCount++;
            }
            
            if (existingVisibleCount > maxConsecutive)
                bPreviousExpanded= true;
        }
        
        if (prevCustomerID == customerID)
        {
            $tr.find("div.jq-user-image").hide();
            consecutiveCount++;
            
            if (consecutiveCount > maxConsecutive && !bPreviousExpanded)
            {
                $tr.addClass('ls-off');
                
                if (consecutiveCount == (maxConsecutive + 1))
                {
                    var txt= $tr.find("span.jq-seemore").text();                            
                    txt= '<a href="#" class="see-more" onclick="ShowConsecutivePosts(this);return false;">'+ txt +'</a>';                            
                    $trLast.children("td").append(txt);
                }
            }
        }
        else
        {
            bPreviousExpanded= false;
            consecutiveCount= 1;
            prevCustomerID= customerID;
        }
        
        $trLast= $tr;
    }
    
    $tbl.append($rows);
    
    if (bShowMore)
    {
        var trMore= '<tr class="row-1"><td class="cell-3"><div class="details-block" style="margin-left: 0px;">';
        trMore+= '<a href="#" class="see-more" onClick="OnNewsFeedMore(this); return false;" style="float: none; font-size: 1em;" >'+ g_NewsMoreText +'</a>';
        trMore+= '<a href="#" class="see-more-loading" onClick="return false;" style="display: none; float: none; font-size: 1em;" >'+ g_NewsLoadingMoreText +'</a>';
        trMore+= '</div></td></tr>';
        
        $tbl.append($(trMore));
    }
        
    if ($existingRows.length == 0)
        InitComments($tbl.find(".commentinput")); //in comments.js
    else
        InitComments($tbl.find("tr.row-1:gt("+ ($existingRows.length-1) +")").find(".commentinput"));
}

function OnNewsFeedMore(lnk)
{
    var $lnk= $(lnk);
    $lnk.next().show();
    $lnk.hide();
    
    var $trMore= $lnk.parents("tr.row-1").eq(0);
    var $trLast= $trMore.prev();
    args= { MaxDate: $trLast.find("span.jq-item-date").text(), Today: g_NewsToday };
    
    CallNewsGet(args, function(response)
    {
        var $newsItems= $(response).find("span#jq-newsitems");
        $trMore.remove();
                
	    if ($newsItems.find("tr.row-1").length > 0)
            DisplayNewsItems($newsItems);            
    });
}

function CallNewsGet(args, callback)
{
    $.post("news_get.aspx", args, callback);
}
