/*jslint browser:true */

var months = [ "Jan", "Feb", "Mar",  "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var days   = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ];

function updateClock (utc, offset, clockDiv) {

  var currentTime = new Date(utc + (3600000 * offset));
  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );

  // Pad the minutes and seconds with leading zeros, if required
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

  // Choose either "AM" or "PM" as appropriate
  var timeOfDay = ( currentHours < 12 ) ? "am" : "pm";

  // Convert the hours component to 12-hour format if needed
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

  // Convert an hours component of "0" to "12"
  currentHours = ( currentHours === 0 ) ? 12 : currentHours;

  // Compose the string for display
  var currentTimeString = days[currentTime.getDay()] + " " +
                          currentTime.getDate() + " " +
                          months[currentTime.getMonth()] + " " +
                          (currentTime.getYear() + 1900) + ", " +
                          currentHours + ":" + currentMinutes + ":" +
                          currentSeconds + timeOfDay;

  // Update the time display
  document.getElementById(clockDiv).firstChild.nodeValue = currentTimeString;
}

function getUTC () {
  var localDateTime = new Date();
  var localTime = localDateTime.getTime();
  var localOffset = localDateTime.getTimezoneOffset() * 60000;

  return localTime + localOffset;
}

function updateClocks () {
  var utc = getUTC();

  updateClock(utc, 0, "utc_clock");
  updateClock(utc, 1, "london_clock");
  updateClock(utc, -7, "california_clock");
  updateClock(utc, 12, "nz_clock");
  updateClock(utc, 9, "tokyo_clock");
  updateClock(utc, 8, "taiwan_clock");
  updateClock(utc, 8, "hongkong_clock");
}

window.onload = function () {
  updateClocks();
  setInterval(updateClocks, 1000);
};
