$(function() {
  var $countdowns = $("time.countdown")
  
  $("form.user ul.chooser li").live("click", function() {
    var $item = $(this), $form = $item.closest("form");
    
    $form
      .removeClass($item.siblings().attr("class"))
      .addClass($item.attr("class"))
      .find("button:last").text($item.text())
  })
  
  if ($("#twitter").length) {
    $.getJSON("/tweets.json", function(tweets) {
      var output = ""
            
      $.each(tweets, function() {
        tweet = this
        output += '<li>' + tweet.text + ' <a href="' + tweet.url + '" class="time">' + new Date(tweet.created_at * 1000).relatively() + '</a></li>'
      })
      
      $("#twitter").append("<ul>" + output + "</ul>")
    })
  }
  
  $("audio").mediaelementplayer();
  
  if ($countdowns.length) {
    setInterval(function() {
      $countdowns.each(function() {
        var $c = $(this),
          start = new Date(),
          end = new Date(parseInt($c.data("datetime-unix"), 10) * 1000),
          diff = Math.round((end - start) / 1000),
          diffParts = []
          
        $.each([86400, 3600, 60, 1], function(i, u) {
          var d = Math.floor(diff / u)
          diff -= d * u
          if (d < 10 && i != 0) d = "0" + d
          diffParts.push(d)
        })

        $c.html(diffParts.join(":"))
      })
    }, 1000)
  }
})

// Extendo

Date.prototype.relatively = function() {
  // Thanks again, Marco

  var s = ((new Date()) - this) / 1000,
    label = "",
    future = (s < -10), // leeway
    units,
    unit,
    quantity

  if (future) { s = Math.abs(s) }

  if (s < 60 && s >= 0) {
    label = 'Moments'
  } else {
    units = {
      60:       "minute",
      3600:     "hour",
      86400:    "day",
      604800:   "week",
      2592000:  "month",
      31536000: "year"
    }

    Object.keys(units).forEach(function(v) {      
      if (s > v) {
        quantity = Math.floor(s / v)
        unit = units[v]
        return false; // break
      }
    })

    label = (quantity || 0).pluralize(unit)
  }

  return (future ? "In " + label : label + " ago")
}

Number.prototype.pluralize = function(singular, plural) {
  if (typeof plural == "undefined") {
    plural = singular + "s"
  }

  return this + " " + (this == 1 ? singular : plural)
}

// These prototypes are provided by the Mozilla foundation and
// are distributed under the MIT license.
// http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

Object.keys = Object.keys || function(o) {
    var result = [];
    for(var name in o) {
        if (o.hasOwnProperty(name))
          result.push(name);
    }
    return result;
};

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisp, t[i], i, t);
    }
  };
}

