var widgetClock = new Class({
	ready: true,
	holder: false,
	bgsrc: "",
	secondsHand: "",
	minutesHand: "",
	hoursHand: "",
	w: 0,
	h: 0,
	init: function(b,s,m,h){
		this.ready = false;
		this.bgsrc = b;

		this.minutesHand = m;
		this.hoursHand = h;

		this.loadImage(b,this.bg,function(el){
			this.w = el.width;
			this.h = el.height;

			this.loadImage(s,this.secondsHand,function(el){
				this.secondsHand = el;
				this.loadImage(m,this.minutesHand,function(el){
					this.minutesHand = el;
					this.loadImage(h,this.hoursHand,function(el){
						this.hoursHand = el;
						this.ready = true;
						if(this.holder){this.create(this.holder);}
					}.bind(this));
				}.bind(this));
			}.bind(this));
		}.bind(this));
	},
	loadImage: function(src,cont,callback){
		cont = new Image();
		cont.src = src;
		cont.onload = function(){callback(cont);}
	},
	create: function(holder){
		if(!this.ready){this.holder = holder;return;}
		d = document.createElement("DIV");
		c = document.createElement("CANVAS");
		d.appendChild(c);
		holder.appendChild(d);

		w = this.w;
		h = this.h;

		d.style.width = w+"px";
		d.style.height = h+"px";
		c.style.width = w+"px";
		c.style.height = h+"px";
		c.width = w;
		c.height = h;
		c.style.background = "URL("+this.bgsrc+") no-repeat";

		var context = c.getContext("2d");
		context.translate(w/2,h/2);

		holder.timer = window.setInterval(function(){this.sync(context);}.bind(this),1000);
		this.sync(context);
	},
	sync: function(context){
		var now = new Date();
		var offsetAngle = (180/360) * (Math.PI*2);
		var minutesAngle = (now.getMinutes()/60 )*(Math.PI*2) + offsetAngle;
		var secondsAngle = (now.getSeconds()/60)*(Math.PI*2)  + offsetAngle;
		var hoursAngle = ((now.getHours()%12)/12)*(Math.PI*2) + offsetAngle;

		context.clearRect(-this.w,-this.h,this.w*2,this.h*2);

		var sechand = this.secondsHand;
		context.save();
		context.rotate(secondsAngle);
		context.drawImage(sechand,-sechand.width/2,0, sechand.width, sechand.height);
		context.restore();

		var minhand = this.minutesHand;
		context.save();
		context.rotate(minutesAngle);
		context.drawImage(minhand,-minhand.width/2,0, minhand.width, minhand.height);
		context.restore();

		var hourhand = this.hoursHand;
		context.save();
		context.rotate(hoursAngle);
		context.drawImage(hourhand,-hourhand.width/2,0, hourhand.width, hourhand.height);
		context.restore();
	}
});

