/**
* @file Generic clock object without using any JavaScript libraries.
* @author Raymond Chau
*/

// Create a default, global, namespace
if (!www)
  var www = {};

// Setup child namespaces, using objects
if (!www.ui)
  www.ui = {};

/**
* Clock object constructor.
* @constructor
*/
www.ui.Clock = function(id) {
	this.container = document.getElementById(id);
};

www.ui.Clock.prototype = {
	/**
	* Initialize the clock object.
	* @param	options	object that contains optional configuration
	*/
	init: function(options) {
		var refDate = options.date && Date.parse(options.date) ? new Date(options.date) : new Date();
		var utcOffset = options.utcOffset ? options.utcOffset : 0;		
		
		this.date = new Date (refDate.getTime() + utcOffset * 3600000);		
		this.timeout = options.timeout ? options.timeout : 1000; // default 1 second refresh
		this.timer = null;
	},

	/**
	* Redraw the clock UI.
	*/
	redraw: function() {
		var date = this.date;
		var format = function(p) {
			return p < 10 ? "0" + p : p;
		}
		
		var hh = format(date.getHours() % 12 || 12);
		var mm = format(date.getMinutes());
		var ss = format(date.getSeconds());
		var p = date.getHours() < 12 ? "am" : "pm";
		
		this.container.innerHTML = hh + ":" + mm + ":" + ss + " " + p;
	},
	
	/**
	* Start the clock.
	*/
	start: function() {
		var me = this;
	
		this.timer = window.setInterval(function() { me.update(me); }, me.timeout);
	},
	
	/**
	* Stop the clock.
	*/
	stop: function() {
		window.clearInterval(this.timer);
	},
	
	/**
	* Update internal date object and redraw the UI.
	* @param	me	object reference of the clock
	*/
	update: function(me) {
		var date = me.date;
		var timeout = me.timeout;
		
		me.date = new Date(date.getTime() + timeout);	
		me.redraw();
	}
};