$(function() {
  set_times_left();
  set_tweet_event();
  set_logout_event();
})

function set_times_left() {
  var duration = moment.duration($('#seconds').text() * 1000, 'milliseconds');

  update_times_left(duration);

  var interval = 1000;
  setInterval(function() {
    duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
    update_times_left(duration);
  }, interval);

  function update_times_left(duration) {
    $('#times_left').text(
      duration.months() + 'ヶ月' +
      duration.days() + '日' +
      duration.hours() + '時間' +
      duration.minutes() + '分'　+
      duration.seconds() + '秒');
  }
}

function set_tweet_event() {
  $('form[action="tweet"]').submit(function(e) {
    e.preventDefault();
    var url = $(this).attr('action');
    var data = {'times_left' : $('#times_left').parent().text()};
    $.post(url, data).done(function(data) {
      window.location = '/';
    });
  });
}

function set_logout_event() {
  $('#logout').click(function(e) {
    e.preventDefault();
    $('#hidden').submit();
  });
}