/*jshint eqnull:true, browser:true */
//
// Twitch display-related helpers
// Depends on twitch.core.js
//

(function (Twitch, $) {

  var zeroPad = function (number, length) {
    length -= number.toString().length;

    if (length > 0) {
      return new Array(length + (/\./.test(number) ? 2 : 1)).join('0') + number;
    }

    return number + ""; // always return a string
  };

  var display = {
    capitalize: function (string) {
      string = string || '';
      return string.charAt(0).toUpperCase() + string.slice(1);
    },
    commatize: function (number) {
      number = number || 0;
      if (isNaN(number)) {
        return number;
      }

      // http://stackoverflow.com/a/2901298
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    getTime: function (date) {
      var mins = zeroPad(date.getMinutes(), 2);
      var hours = date.getHours();
      if (hours > 12) {
        hours -= 12;
      } else if (hours === 0) {
        hours = 12;
      }
      return hours + ":" + mins;
    },
    lengthAsClock: function (n) {
      var s = Math.floor(n % 60);
      var m = Math.floor((n % 3600) / 60);
      var h = Math.floor(n / 3600);
      if (h) {
        return h + ":" + zeroPad(m, 2) + ":" + zeroPad(s, 2);
      } else {
        return m + ":" + zeroPad(s, 2);
      }
    },
    clockAsLength: function (string) {
      var parts = string.split(':'),
          s = parseInt(parts[parts.length - 1], 10),
          m = parseInt(parts[parts.length - 2], 10),
          h = 0;

      if (parts.length > 2) {
        h = parseInt(parts[parts.length - 3], 10);
      }

      return s + 60 * m + 60 * 60 * h;
    },
    // Escapes HTML characters. TODO: Use _.escape instead once underscore is
    // available everywhere on our site
    escape: function (string) {
      return $("<div/>").text(string).html();
    }
  };

  Twitch.mixin({
    display: display
  });

})(Twitch, jQuery);
