var templates = {
  'latest': '<li><img src="/gaikaex/mark/calendar/images/flags/#{currency_code}.gif" width="14" height="14" alt="#{country}" title="#{country}" />#{released_at}&nbsp;#{name}</li>',
  'country': '<div class="monthly_country"><img src="/gaikaex/mark/calendar/images/flags/#{code}.gif" width="14" height="14" alt="#{country}" title="#{country}" />#{country}</div>',
  'detail_row': '<tr>' +
    '<td class="flag"><img src="/gaikaex/mark/calendar/images/flags/#{currency_code}.gif" alt="#{country}" title="#{country}" width="14" height="14" /></td>' +
    '<td class="country">（#{country_short}）</td>' +
    '<td class="indicator">#{in_month}#{name}#{comparison}</td>' +
    '<td class="time">#{released_at}</td>' +
    '</tr>'
}
function set_active(elem) {
  reset_active();
  if ($(elem)) { elem.addClassName('active'); }
}
function show_detail(elem) {
  var base = Position.cumulativeOffset(elem);
  date_detail.style.top  = base.top  + elem.getHeight() + 'px';
  date_detail.style.left = base.left + 'px';
  date_detail.show();
  $('detail_date').innerHTML = '<img src="/gaikaex/mark/calendar/images/icons/prev_off.gif" width="21" height="13" alt=" " style="margin-right: 5px;" />' + elem.id.substring(0, 4) + '.' + elem.id.substring(4, 6) + '.' + elem.id.substring(6, 8) + '<img src="/gaikaex/mark/calendar/images/icons/next_off.gif" width="21" height="13" alt=" " style="margin-left: 5px;" />';
  $('weekly_anchor').href = '/gaikaex/mark/calendar/' + elem.id;
  load_detail(elem.id);
}
function load_detail(date) {
  $('detail_table').hide();
  $('detail_loading').show();
  new Ajax.Request('/gaikaex/mark/calendar/' + date + '/json', {
    method: 'get',
    onSuccess: function(conn, obj) {
      if (!obj) { obj = eval('(' + conn.responseText + ')'); }
      var tpl = new Template(templates['detail_row']);
      var dummy_table = '<table><tbody>';
      obj['indicators'].each(function(indicator) {
        if (indicator['has_time']) {
          var date = new Date(indicator['released_at']);
          aligned_time = align_time(date)
          aligned_time.hours   += '';
          aligned_time.minutes += '';
          indicator['released_at'] = (aligned_time.hours.length == 1 ? '0' : '') + aligned_time.hours + ':' + (aligned_time.minutes.length == 1 ? '0' : '') + aligned_time.minutes;
        } else {
          indicator['released_at'] = '--:--';
        }
        if (indicator['comparison'] != '') { indicator['comparison'] = '(' + indicator['comparison'] + ')'; }
        dummy_table += tpl.evaluate(indicator);
      });
      var dummy_div = document.createElement('DIV');
      dummy_div.innerHTML = dummy_table + '</tbody></table>';
      $('detail_table').replaceChild(dummy_div.getElementsByTagName('TBODY')[0], $('detail_table').getElementsByTagName('TBODY')[0]);
      $('detail_date').innerHTML  = obj['enable_previous'] ? '<a href="javascript:void(0);" onclick="load_detail(\'' + obj['enable_previous'] + '\')"><img src="/gaikaex/mark/calendar/images/icons/prev.gif" width="21" height="13" alt=" " style="margin-right: 5px;" /></a>' : '<img src="/gaikaex/mark/calendar/images/icons/prev_off.gif" width="21" height="13" alt=" " style="margin-right: 5px;" />';
      $('detail_date').innerHTML += date.substring(0, 4) + '.' + date.substring(4, 6) + '.' + date.substring(6, 8);
      $('detail_date').innerHTML += obj['enable_next']     ? '<a href="javascript:void(0);" onclick="load_detail(\'' + obj['enable_next']     + '\')"><img src="/gaikaex/mark/calendar/images/icons/next.gif" width="21" height="13" alt=" " style="margin-left: 5px;" /></a>' : '<img src="/gaikaex/mark/calendar/images/icons/next_off.gif" width="21" height="13" alt=" " style="margin-left: 5px;" />';
      set_active($(date));
      $('detail_table').show();
      $('detail_loading').hide();
    },
    onException: function(conn, e) {
      alert(e.number + ':' + e.description);
    }
  });
}

function hide_detail() {
  reset_active();
  $('date_detail').hide();
}

function reset_active() {
  $$('#economy_calendar tbody td').each(function(e) {
    e.removeClassName('active');
  });
}

function load_flags(date) {
  new Ajax.Request('/gaikaex/mark/calendar/' + date + '/json?only=countries', {
    method: 'get',
    onSuccess: function(conn, obj) {
      if (!obj) { obj = eval('(' + conn.responseText + ')'); }
      var tpl = new Template(templates['country']);
      var result = '';
      obj.each(function(currency, index) {
        if (index >= 5) { return; }
        currency['code'] = currency['code'].toLowerCase();
        result += tpl.evaluate(currency);
      });
      if (obj.length > 5) { result += '<p class="monthly_etc">etc.</p>'; }
      $('flags').innerHTML = result;
      $('flags_loading').hide();
      $('flags').show();
    },
    onException: function(conn, e) {
      alert(e.number + ':' + e.description);
    }
  });
}

function load_latest_indicators(limit) {
  new Ajax.Request('/gaikaex/mark/calendar/latest?limit=' + limit, {
    method: 'get',
    onSuccess: function(conn, obj) {
      if (!obj) { obj = eval('(' + conn.responseText + ')'); }
      var tpl = new Template(templates['latest']);
      var result = '';
      obj.each(function(indicator) {
        var date  = new Date(indicator['released_at']);
        var month = date.getMonth() + 1;
        var day   = date.getDate();
        indicator['released_at']  = (month.length == 1 ? '0' : '') + month + '/';
        indicator['released_at'] += (day.length   == 1 ? '0' : '') + day;
        indicator['released_at'] += '（' + ['日', '月', '火', '水', '木', '金', '土'][date.getDay()] + '）&nbsp;';
        if (indicator['has_time']) {
          aligned_time = align_time(date)
          aligned_time.hours   += '';
          aligned_time.minutes += '';
          indicator['released_at'] += (aligned_time.hours.length == 1 ? '0' : '') + aligned_time.hours + ':' + (aligned_time.minutes.length == 1 ? '0' : '') + aligned_time.minutes;
        } else {
          indicator['released_at'] += '--:--';
        }
        result += tpl.evaluate(indicator);
      });
      $('calendar').innerHTML = result;
      $('calendar_loading').hide();
      $('calendar').show();
    },
    onException: function(conn, e) {
      alert(e.number + ':' + e.description);
    }
  });
}

function align_time(date) {
  var hours   = date.getHours();
  var minutes = date.getMinutes();
  if (hours < 5 || hours == 5 && minutes < 30) { hours += 24; }
  return {hours: hours, minutes: minutes};
}

