/**
 * @author Kevin Hamilton
 */
var clock = {
	time  : '',
	el_id : '',
	intid : 0,
	
	months : [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ],
	weekdays : [ 'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday' ],
	//weekdays : [ 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' ],

	init : function(date_el) {
		
		this.el_id = $(date_el);
		if(!this.el_id) {
			//alert('Clock failed to start');
			return;
		}
	    
		this.start();
		
	},
	start : function(id) {
		this.update();
		this.intid = window.setInterval( this.update.bind(this), 1000);
	},
	stop : function() {
		clearInterval(this.intid);
	},
	update : function() {
		this.dateObj = new Date();
		
		var time = this.getTimeString(this.dateObj);
		var date = this.getDateString(this.dateObj);
		
		if(time != this.time) {
			this.el_id.update(date + ' ' + time);
			this.time = time;
		}
	},
	
	getDateString : function(oDate) {
		var weekday = this.weekdays[ oDate.getDay() ];
	    var date    = oDate.getDate();
		var suffix  = this.getSuffix(date);
		var month   = this.months[ oDate.getMonth()];
	    var year    = oDate.getFullYear();

		var str = weekday + ', ' + date + suffix + ' ' + month + ' ' + year;
		
		return  str;
	},
	getTimeString : function(oDate) {

		var h = oDate.getHours();
		h = (h>12?h-12:h);
		
        var m = oDate.getMinutes();
		m = (m<10?'0':'')+m;
		
        var s = oDate.getSeconds();
		s = (s<10?'0':'')+s;
		
		var suffix = (oDate.getHours() > 12 ? 'pm' : 'am');
		
		var time = h + ':' + m + ':' + s + suffix;

		return time;	
	},

	getSuffix: function(date) {

		var dateSuffixes = [ 'th','st','nd','rd','th'];

		var suffix;
		var i = date
	    while (i >= 10) {
			i = i - 10;
		}
		
		suffix = dateSuffixes[ Math.min(i,4) ];
		if (date >= 11 && date <= 13) {
			suffix = dateSuffixes[0];
		}

		return suffix;
	}
}


