

var storyHandleSuccess = function(o){
  toggleOFFthrobber('main_throbber');
  setTimeout(function(){ displayStories(o);}, 250);
}

function GetNoStoriesHtml() {
  tempString = "";
  tempString += '<div class="news-alert">';
  tempString += '<h2><strong>Nothing\'s surfaced here today.</strong></h2>';
  tempString += '<h3>Stories haven\'t surfaced in this category today yet.</h3>';
  tempString += '<a class="alert_transf" href="#" onclick="changeSort(3)";><span>Show Yesterday\'s News</span></a>';
  tempString += '<a class="alert_transf" href="' + g_domain + 'all/"><span>Show All News</span></a>';
  tempString += '</div>';
  return tempString;
}

function GetNoStoriesLastVisitHtml() {
  tempString = "";
  tempString += '<div class="news-alert">';
  tempString += '<h2><strong>No stories have surfaced since your last visit.</strong></h2>';
  tempString += '<h3>Nothing has surfaced since the last time you visited Newspond (' + GetLastVisitTimeString() + ')</h3>';
  tempString += '<a class="alert_transf" href="#" onclick="toggleShowNewButton()";><span>Show All Stories</span></a>';
  tempString += '</div>';
  return tempString;
}

function GetLastVisitTimeString() {
  var my_date=new Date();
  my_date = my_date / 1000;
  var deltaT = my_date - g_lastVisitTime;
  var minAgo = Math.floor(deltaT / 60);
  var hrsAgo = Math.floor(minAgo / 60);
  var daysAgo = Math.floor(hrsAgo / 24);
  minAgo = minAgo % 60;
  hrsAgo = hrsAgo % 24; 
  if (daysAgo > 0) {return daysAgo + "d " + hrsAgo + "h " + minAgo + "m ago";}
  if (hrsAgo > 0) { return hrsAgo + "h " + minAgo + "m ago";}
  else {return minAgo + "m ago";}
}
function displayStories(o) {
  var storyDiv = document.getElementById('main');
  if(o.responseText !== undefined){
    var stories = o.responseXML.documentElement.getElementsByTagName("story");
    storyDiv.innerHTML = "";   
    if(g_lastVisit != 0) { storyDiv.innerHTML += '<div class="showunread-notif">showing only stories that have surfaced since your last visit (' + GetLastVisitTimeString() + ')</div>'; }
    if(g_currentPage != 1) { storyDiv.innerHTML += '<div class="pagenum-notif">' + g_currentPage + '</div>'; }
    if(stories.length == 0) {
      if(g_lastVisit == 0) { 
        storyDiv.innerHTML = GetNoStoriesHtml();
      } else {
        storyDiv.innerHTML = GetNoStoriesLastVisitHtml();
      }
      g_totalStories = 0;
      toggleONsubInfo(g_currentPage,g_pageSize,g_totalStories);
    }

    for(i=0; i< stories.length; i++)
    {
      g_totalStories = stories[i].getAttribute("totalCount");
      storyId  = stories[i].getAttribute("id");
      storyTitle = stories[i].getAttribute("title");
      storySummary = stories[i].getAttribute("summary");
      storyUrl = stories[i].getAttribute("link");
      storySource = stories[i].getAttribute("displayName");
      storyScore = stories[i].getAttribute("relatedScore");
      peakScore = stories[i].getAttribute("peakScore");
      storyRelatedCount = stories[i].getAttribute("relatedCount");
      //Add 1 to account for oneself
      storyRelatedCount = + storyRelatedCount + 1;

      catName = stories[i].getAttribute("topCategoryName");
      subCatName = stories[i].getAttribute("subCategoryName");
      subCatVisible = stories[i].getAttribute("subCatVisible");
      clientUserId = stories[i].getAttribute("clientUserId");

      timeString = "Surfaced " + stories[i].getAttribute("age");
      storySaved = stories[i].getAttribute("userid"); 
      commentCount = stories[i].getAttribute("commentCount");
      lastScore = stories[i].getAttribute("lastScore");
 
      //Story Save States
      //tagbutton-disabled = not logged in
      //tagbutton-saved = SAVED
      //tagbutton = UNSAVED
      //First you need to check if the user is even logged in.  If they arn't set to tagbutton-disabled
      //If the user IS logged in, Write SQL query to get the story save state from the DB when you load the story
      //If the story is saved, set a string to tagbutton-saved, if not, tagbutton
      
      saveStateText = "";
      if(g_user_logged_in == 0) {
        storySaveState = "tagbutton-disabled"; 
        saveStateText = "Save";
      } else {
        if(storySaved == clientUserId) {
          storySaveState = "tagbutton-saved";
          saveStateText = "Saved";
        } else { 
          storySaveState = "tagbutton";
          saveStateText = "Save";
        }
      }

      //Related Height box
      relatedHeight = 53 + storyRelatedCount * 20;

      //Handle percentage change stuff
      if (storyScore == 0) {
        tmpScore = 0;
      } else if (lastScore == 0){
        tmpScore = 100;
      } else {
        tmpScore = storyScore / lastScore;
        tmpScore = tmpScore - 1;
        tmpScore = tmpScore * 100;
      }

      scoreChangeClass = "";
      if(tmpScore < 0) { 
        scoreChangeClass = "buoy-change buoy-decrease";
        tmpScore = tmpScore * -1;
      } else if(tmpScore == 0) {
        scoreChangeClass = "buoy-change buoy-neutral";
      } else {
        scoreChangeClass = "buoy-change buoy-increase";
      }
      
      breadCrumbText = "";
      if(subCatVisible == 0) {
        breadCrumbText = '<a href="' + g_domain + catName.toLowerCase() + '/">' + catName + '</a> > <a href="' + g_domain + catName.toLowerCase() + '/' + subCatName.toLowerCase() + '/">' + subCatName + '</a>';
      } else {
        breadCrumbText = '<a href="' + g_domain + catName.toLowerCase() + '/">' + catName + '</a>';
      }
     
      storyState = "bluebox";
      if(storyScore == 0) { 
        storyState = "greybox"; 
        storyStateHtml = '<span class="buoyancy" title="Our measure of real time global popularity.">Story Sunken</span><span class="peak-explain">Peak Buoyancy</span><div class="buoy-rating" title="The higher the rating is, the more popular the story is around the internet."><div class="bu1"><div class="bu2"><span class="buoy-text"><a href="#">' + peakScore + '</a></span></div></div></div>';
      } else { 
        storyState = "bluebox";
        storyStateHtml = '<span class="buoyancy" title="Our measure of real time global popularity.">Buoyancy Rating:</span><div class="buoy-rating" title="The higher the rating is, the more popular the story is around the internet."><div class="bu1"><div class="bu2"><span class="buoy-text"><a href="#">+' + storyScore + '</a></span></div></div></div><div class="' + scoreChangeClass + '" >' + Math.round(tmpScore) + '%</div>'; 
      } 

      storyAward = "";
      if(i == 0 && g_selectedSort == 1 && g_selectedDate == 1 && g_selectedView == 1 && g_currentPage == 1) {
        storyAward = '<strong class="rankaward">Top Story</strong>';
      } else {
        storyAward = "";
      }

      if(g_selectedView == 1 || g_expandedHeadlines[storyId] == 1) { 
      	// add ' + commentCount2 + ' in front of comments to get the number back
        storyDiv.innerHTML += '<!-- Start News Box --><div class="' + storyState + '"><div class="newsbox"><div class="n1"><div class="n2"><div class="n3"><div class="n4"><div class="newsbox-title"><a href="' + storyUrl + '" target="_blank">' + storyTitle + ' </a></div><div class="newsbox-date">' + storyAward + ' ' + timeString + ' on <strong class="sourcetitle">' + storySource + '</strong> (+<strong class="otherstreams">' + --storyRelatedCount + '</strong> others)</div><div class="newsbox-words">' + storySummary + '</div></div></div></div></div></div><div class="catbox">' + storyStateHtml + '<span class="cats">' + breadCrumbText + '</span></div><div id="streamsbox_' + storyId + '" class="streamsbox"></div><div class="combar"><div class="cb1"><div class="cb2"><span class="commentbutton"><a href="' + g_domain + 'story=' + storyId + '">Comments</a></span><span id="savebutton_' + storyId + '" class="' + storySaveState +'"><a onclick="toggleSaveButton(\'savebutton_' + storyId + '\',\'savebuttonText_' + storyId + '\',' + storyId + ',' + storyId + ');"><span id="savebuttonText_' + storyId + '" class="text-saved">' + saveStateText + '</span></a></span><span id="streamsbutton_' + storyId + '" class="streams"><a onclick="toggleStreamsBox(\'streamsbox_' + storyId + '\',' + relatedHeight + ',\'streamsbutton_' + storyId + '\', ' + storyId + ');">View All Sources (<strong>' + ++storyRelatedCount + '</strong>)</a></span></div></div></div></div><!---End News Box -->';
      } else {  
        storyDiv.innerHTML += '<table class="news-headline" border="0" cellspacing="0" cellpadding="0"><tr class="nheadline"><td class="title"><a class="story" href="' + storyUrl + '">' + storyTitle + ' <span class="date">' + timeString + ' <strong>(+' + storyRelatedCount + ') </strong></span></a></td><td class="buoyancy"><div><div><div><div>' + storyScore + '</div></div></div></div></td><td class="controls"><div><div><a onclick="expandStory(' + storyId + ');" href="#" class="expand">&nbsp;</a><a href="' + g_domain + 'story=' + storyId + '" class="commentsbutton">' + commentCount + '</a></div></div></td></tr></table>';
      }

    }
  displayPaging();
  toggleONsubInfo(g_currentPage,g_pageSize,g_totalStories);
  //toggleOFFthrobber('main_throbber');
  }
  
  if(g_lastVisit != 0 && stories.length > 5) { storyDiv.innerHTML += '<div class="showunread-notif">showing only stories that have surfaced since your last visit (15m ago)</div>'; }
  
 }


var storyHandleFailure = function(o){
  if(o.responseText !== undefined){
    catDiv.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
    catDiv.innerHTML += "<li>HTTP status: " + o.status + "</li>";
    catDiv.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
  }
}
var storyCallback =
{
  success:storyHandleSuccess,
  failure:storyHandleFailure,
  argument: { foo:"foo", bar:"bar" }
};


function expandStory(entryId) {
  g_expandedHeadlines[entryId] = 1;
  doStories();
}

function doStories(){
  var offset = (g_currentPage-1) * g_pageSize;
  if (g_pageType == 0) {
    var sUrl = g_domain + "xml/storyxml.php?category=" + g_selectedSubCat + "&dateRange=" + g_selectedDate + "&sortMode=" + g_selectedSort + "&offset=" + offset + "&pagesize=" + g_pageSize + "&pageType=" + g_pageType + "&lastVisit=" + g_lastVisit;
  } else if(g_pageType == 1) {
    var sUrl = g_domain + "xml/storyxml.php?category=" + g_selectedSubCat + "&offset=" + offset + "&pagesize=" + g_pageSize + "&pageType=" + g_pageType + "&UserID=" + g_selectedUserId;
  }
  catRequest = YAHOO.util.Connect.asyncRequest('GET', sUrl, storyCallback);
}

