
function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(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 deleteCookie(name) {
    setCookie(name,"",-1);
}

var last_read_cookie_name = "last_read";

function toggleIveReadLink() {
    /* check if any items are visible, 
       if they are then show the link, otherwise hide it
    */
    if (0 == $("div.entrygroup").filter(":visible").length) {
        $(".ivereadthese").hide();
    } else {
        $(".ivereadthese").show();
    }
}
function markRead(id) {
    setCookie(last_read_cookie_name, id);
    hideRead(id);
}
function unMarkRead() {
    deleteCookie(last_read_cookie_name);
    $('div.entrygroup').show();
    $(".alreadyread").hide();
    $(".alreadyreadcount").text(0);
    toggleIveReadLink();
}
function hideRead(id) {

    var group = $('div[name="'+id+'"]').add('div[name="'+id+'"] ~ div.entrygroup');
    var numHidden = group.length;
    group.hide();
    if (0 < numHidden) {
        $(".alreadyreadcount").text(numHidden);
        $(".alreadyread").show();
    } else {
        $(".alreadyread").hide();
    }
    toggleIveReadLink();
}

/* Expand collapsed entry groups
 *
 * There are two possible ways the content of an entry group might be collapsed:
 *  1) content is enclosed in a 'planet:content' attribute on the entrygroup 
 *     and needs to be added as a new div.
 *     (how entries that are collapsed by default are sent to browser)
 *  2) entry div is "hidden" the usual way
 *
 * FYI: the reason we do it this way instead of sending a 'hidden' div
 * in the first place because browsers still load images/iframes inside of hidden
 * DOM elements
 */
function expand(entrygroup) {
    // figure out what type of entrygroup we are expanding

    var content = entrygroup.attr('planet:content');
    if (typeof content === 'undefined') {
        // regular hidden div, so show it
        entrygroup.find('div.entry').show();
    } else {
        // encoded content, add as a new div
        var contentDiv = '<div class="content">'+content+'</div>';
        entrygroup.children("div.entry").append(contentDiv);
    }

    // remove the attributes we no longer want/need
    entrygroup.removeAttr('planet:content');
    entrygroup.removeClass('collapsed');

    // fix the click hooks to re-collapse later
    entrygroup.off('click', handleExpand);
    entrygroup.on('click', 'h2', handleCollapse);
}

/* hides the contents of an entrygroup div in the usual way, 
 * but also decorates it with a click action to expand later
 */
function collapse(entrygroup) {
    entrygroup.find('div.entry').hide();
    entrygroup.addClass('collapsed');

    // fix the click hooks to expand later
    entrygroup.off('click', 'h2', handleCollapse);
    entrygroup.on('click', handleExpand);
}

function handleCollapse(event) {
    // :TODO:
    // as written this ignores clicks to things that are not
    // the bound target, even if they have no default action
    // ie: if a user clicks on a span inside the h2 (like the "@")
    // the collapse won't happen
    //
    // is there a better way to identify when an event does/doesn't have a 
    // default action?
    //
    if (event.target === event.currentTarget) {
        /* direct action on the target, not decendent item 
         * ie: clicked the h2, not a link in the h2
         */
        event.preventDefault(); // useless?
        collapse($(event.delegateTarget));
    }
    /* else: :NOOP: let the event propogate up to default action, 
     * ie: let the browser take them to the link
     */
}
function handleExpand(event) {
    // don't pass clicks on to links for this entry group
    event.preventDefault();
    // instead expand the item...
    expand($(this));
}



/* Actions to do on page load */
$(function() {
  /* hidden by default 
     so we don't display them to people with javascript disabled
  */
  $(".hideunlessscript").show();

  /* decorate all items with functions based on their "collapsed" state */
  $('.entrygroup.collapsed').on('click', handleExpand);
  $('.entrygroup').not('.collapsed').on('click', 'h2', handleCollapse);

  /* do this here instead of with css since it's missleading if 
   * users have javascript disabled 
   */
  $('.entrygroup h2').css('cursor','pointer');

  /* hide anything the users' cookie says they've read */
  var lastReadCookieVal = getCookie(last_read_cookie_name);
  if (null != lastReadCookieVal) {
      hideRead(lastReadCookieVal);
  }
  $(".unreadall").click(function(event) {
      event.preventDefault();
      unMarkRead();
  });
  $(".readall").click(function(event) {
      markRead( $("div.entrygroup").filter(":first").attr("name") );
  });

  /* handy for testing
   * Put "debug=true" in the URL query args to see a "done" link for 
   * each item to test cookie behavior
   */
  if (0 <= window.location.href.indexOf("debug=true")) {
      $(".entrygroup > h2").append('<a href="#" class="donehere" style="float: right">&#10004</a>');
      $(".donehere").click(function(event) {
          event.preventDefault();
          markRead($(this).parent().parent().attr("name"));
      });
  }

});

