$(document).ready(function () {
  // Update all the feed item timestamps
  $("li.feed_item[timestamp]").each(function (i) {
    timestamp = parseInt($(this).attr("timestamp"), 10);
    timestamp *= 1000; // The server doesn't care about milliseconds, but the client does
    
    $(this).find("h5 > span.created_at").text($.timeago(new Date(timestamp)));
  });

  // feed filtering
  $("#feed_filter_form .header").click(function (event) {
    $("#feed_filter_list").slideToggle();
    $(this).toggleClass("open");
  });

  $("#feed_filter_list :checkbox").change(function (event) {
    // don't allow all boxes to be unchecked
    if ($("#feed_filter_list :checked")[0] === null) {
      $(this).attr('checked', true);
      return;
    }

    var vals;

    if ($(this).attr('checked')) {
      if ($.cookie('action_types') === null) {
        $.cookie('action_types', '');
      }
      vals = $.cookie('action_types').split(',');
      vals.push($(this).val());
      $.cookie('action_types', vals.join(','));
    } else {
      if ($.cookie('action_types') === null) {
        vals = [];
        $("#feed_filter_list :checkbox").each(function () {
          vals.push($(this).val());
        });
        $.cookie('action_types', vals.join(','));
      }
      var arr = $.cookie('action_types').split(',');
      arr.splice(arr.indexOf($(this).val()), 1);
      $.cookie('action_types', arr.join(','));
    }
    jQuery.ajax({
      url: "/feed.mini",
      type: "GET",
      dataType: 'html',
      beforeSend: function () {
        var pbar = $("<div id='progressbar'></div>");
        $('#list_view').html(pbar);
      },
      success: function (data) { 
        if (data === null || data.replace(/ /g, '') == '') {
          data = "<p>Sorry, your search did not yield any results.</p>";
        }
        $('#list_view').html(data);
        if(logged_in) initialize_stars();
      },
      failure: function (e) {
        alert('Unable to refresh feed. ' + e);
      }
    });
  });

  // Add paginator only if actions list is full
  var feed_length = 20;
  if ($("#list_view > li").length == feed_length) {
    var paginator = $("<p id='paginator'>Click for More Results&hellip;</p>");
    $("#list_view").after(paginator);
    paginator.click(function () {
      jQuery.ajax({
        url: "/feed.mini",
        type: "GET",
        data: {'created_at_before': $("#list_view > li:last").attr('timestamp')},
        dataType: 'html',
        success: function (data) { 
          $('#list_view').append(data);
          // This will be true if the last page is pulled in
          if ($("#list_view > li").length % feed_length !== 0) {
            paginator.remove();
          }
        },
        failure: function (e) {
          alert('Unable to refresh feed. ' + e);
        }
      });
    });
  }
});
