function Time(h, m, s) {
  this.hours = h;
  this.minutes = m;
  this.seconds = s;
}

// Factory method
Time.parse = function(input) {
  var hours = Number(String(input).replace(/^([0-9]{2})[0-9]{2}[0-9]{2}\..*|$/,"$1")) || 0;
  var minutes = Number(String(input).replace(/^[0-9]{2}([0-9]{2})[0-9]{2}\..*|$/,"$1")) || 0;
  var seconds = Number(String(input).replace(/^[0-9]{2}[0-9]{2}([0-9]{2})\..*|$/,"$1")) || 0;
  return new Time(hours, minutes, seconds);
}

Time.prototype.offsetHours = function(hourOffset) {
  var h = this.hours + hourOffset;
  
  /* todo: adjust date also */ 
  if (h < 0) { h += 24; }
  if (h > 23) { h -= 24; }
  
  return new Time(h, this.minutes, this.seconds);
}

Time.prototype.render = function(opts) {
  opts = opts || {};

  function pad(input) {
    if (input < 10) {
      return '0' + String(input);
    } else {
      return String(input);
    }
  }

  var rendered = this.hours + ':' + pad(this.minutes);
  
  if (opts.seconds) { rendered += ':' + pad(this.seconds); }
  
  return rendered;
}

// No support for negative intervals. If it comes up negative,
// add 24 hours.
function TimeInterval(time, otherTime) {
  this.seconds = time.seconds - otherTime.seconds;
  this.minutes = time.minutes - otherTime.minutes;
  this.hours = time.hours - otherTime.hours;
  
  if (this.seconds < 0) {
    this.seconds += 60;
    this.minutes--;
  }

  if (this.minutes < 0) {
    this.minutes += 60;
    this.hours--;
  }

  if (this.hours < 0) {
    this.hours += 24;
  }
}

TimeInterval.prototype.inSeconds = function() {
  return this.hours * 3600 + this.minutes * 60 + this.seconds;
}

TimeInterval.prototype.render = function() {
  var output = '';
  if (this.hours > 0) {
    output += '' + this.hours + 'hrs, ';
  }
  if (this.minutes > 0) {
    output += '' + this.minutes + 'mins, ';
  }
  if (this.seconds > 0) {
    output += '' + this.seconds + 's';
  }
  return output;
}


function formatDate(input) {
  return String(input).replace(/^([0-9]{2})([0-9]{2})([0-9]{2})(\..*|)$/,"20$3-$2-$1");
}

