var cookieOptions = { path: '/', expires : 365 };

$(document).ready(function() {
  enableTimeFormats();
  updateClocks(true);
  positionClocks();
});

function enableTimeFormats() {
  $('.format').css('visibility', 'visible');
  if ($.cookie('timeFormat') == '12h') {
    showButtonsFor12hFormat();
  } else {
    showButtonsFor24hFormat();
  }
  $('.12h-link').bind('click', function() {
    $.cookie('timeFormat', '12h', cookieOptions);
    updateClocks(false);
    positionClocks();
    showButtonsFor12hFormat();
    return false;
  });
  $('.24h-link').bind('click', function() {
    $.cookie('timeFormat', '24h', cookieOptions);
    updateClocks(false);
    positionClocks();
    showButtonsFor24hFormat();
    return false;
  });
}

function showButtonsFor12hFormat() {
  $('.12h-text, .24h-link').show();
  $('.12h-link, .24h-text').hide();
}

function showButtonsFor24hFormat() {
  $('.12h-text, .24h-link').hide();
  $('.12h-link, .24h-text').show();
}

function positionClocks() {
  $.each($('.clock'), function(i, val) {
    var width = $(val).css('width', 'auto').width();
    $(val).css({ 'text-align': 'center', 'width': width }).find('.time').css('left', '0');
    var left = $(val).find('.time').position().left;
    $(val).css('text-align', 'left').find('.time').css('left', left + 'px');
  });
}

function updateClocks(startSeries) {
  if ($('.clock').length > 0) {
    var localTime = new Date();
    $.each($('.clock'), function(i, val) {
      if ($(val).find('.utc-offset').length > 0) {
        var timezoneOffset = parseFloat($(val).find('.utc-offset')[0].value);
      } else {
        var timezoneOffset = -localTime.getTimezoneOffset() / 60;
      }
      var ms = localTime.getTime() + localTime.getTimezoneOffset() * 60000 + timezoneOffset * 3600000;
      var time =  new Date(ms);
      var hour = time.getHours();
      var minute = time.getMinutes();
      var second = time.getSeconds();
      if ($.cookie('timeFormat') == '12h') {
        if (hour == 0) hour = 12;
        timeHtml = (hour > 12 ? hour - 12 : hour) + (second % 2 == 0 ? ':' : '<span class="hidden">:</span>') + (minute < 10 ? '0' : '') + minute + (hour > 12 ? ' pm' : ' am');
      } else {
        timeHtml = hour + (second % 2 == 0 ? ':' : '<span class="hidden">:</span>') + (minute < 10 ? '0' : '') + minute;
      }
      $(val).find('.time').html(timeHtml);
    });
    if (startSeries) setTimeout('updateClocks(true)', 1000);
  }
}
