/* 

	mootools clock
 	mooclock.js

	Created by Ryan Mitchell, ryan@rtnetworks.net
	
	Based on the php.net/date strings

*/
var Mooclock = Class({
					 
	Implements: Options,
	
    options: {
        element: null,
        format: '<strong>%d%S %m %y:</strong> %H:%i'
    },
	
	// variable string corresponding to months
	months: Array('January','February','March','April','May','June','July','August','September','October','November','December'),
					 		
	// initialise the class
	initialize: function(options) {
		
		// overwrite default values
		this.setOptions(options);
		
		// only if have an element
		if($(this.options.element) != null) {
		   
			// set initial date
			this.tick();
					
			// start ticking
			this.tick.periodical(1000,this);
				
		}
		else {
			alert('Mooclock Error:\r\n\You need to specify an element to make into a clock');	
		}
	},
	
	// function to tick the clock
	tick: function() {
		
		// get time
		var time = new Date();
		
		// replace format string as appropriate			
		var clock = this.options.format.replace('%d',time.getDate());
		clock = clock.replace('%F',this.day(time.getDay()));
		clock = clock.replace('%S',this.suffix(time.getDate()));
		clock = clock.replace('%m',this.months[time.getMonth()]);
		clock = clock.replace('%a',this.ampm(time.getHours()));
		clock = clock.replace('%y',time.getFullYear());	
		clock = clock.replace('%g',(time.getHours()%12));
		clock = clock.replace('%G',(time.getHours()%12).toString().pad(2,'0',0));
		clock = clock.replace('%H',time.getHours().toString().pad(2,'0',0));
		clock = clock.replace('%i',time.getMinutes().toString().pad(2,'0',0));
		clock = clock.replace('%s',time.getSeconds().toString().pad(2,'0',0));
		
		this.options.element.set('html',clock);
		
	},
	
	// handle day of the week
	day: function(d) {
	
		switch(d) {
		
			case 0: return "Sunday"; break;
			case 1: return "Monday"; break;
			case 2: return "Tuesday"; break;
			case 3: return "Wednesday"; break;
			case 4: return "Thursday"; break;
			case 5: return "Friday"; break;
			case 6: return "Saturday"; break;
		
		}
	
	},
	
	// ampm
	ampm: function(h) {
	
		if(h>=12) return "pm";
		else return "am";
	
	},
	
	// handle day suffixes
	suffix: function(d) {
		
		switch(d) {
			
			// st
			case 1: case 21: case 31:
				return 'st';
			break;
			
			// nd
			case 2: case 22:
				return 'nd';
			break;
			
			// rd
			case 3: case 23:
				return 'rd';
			break;
			
			// th
			default:
				return 'th';
			break;
			
		}
		
	}
	
});

String.prototype.pad = function(l, s, t){
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};