﻿function showLocalTime(container, initialTime, offsetMinutes)
{
  if (!document.getElementById || !document.getElementById(container)) return
  this.container = document.getElementById(container)
  var servertimestring = initialTime
  this.localtime = this.serverdate = new Date(servertimestring)
  this.localtime.setTime(this.serverdate.getTime() + offsetMinutes * 60 * 1000)
  this.updateTime()
  this.updateContainer()
}

showLocalTime.prototype.updateTime = function()
{
  var thisobj = this
  this.localtime.setSeconds(this.localtime.getSeconds() + 1)
  setTimeout(function(){thisobj.updateTime()}, 1000)
}

showLocalTime.prototype.updateContainer = function()
{
  var thisobj = this
  var hour = this.localtime.getHours()
  var minutes = this.localtime.getMinutes()
  var seconds = this.localtime.getSeconds()
  var ampm = (hour >= 12)? "PM" : "AM"
  this.container.innerHTML = formatField(hour, 1) + ":" + formatField(minutes) + ":" + formatField(seconds) + " " + ampm
  setTimeout(function(){thisobj.updateContainer()}, 1000) // Update container every second
}

function formatField(num, isHour)
{
  if (typeof isHour != "undefined")
  {
    // If this is the hour field
    var hour = (num>12)? num - 12 : num
    return (hour == 0)? 12 : hour
  }
  // If this is minute or sec field
  return (num <= 9)? "0" + num : num
}
