// JavaScript Document
$(document).ready(function(){

	var aClock = $('.analogClock'),
		clockWidthHeight = aClock.width(),//width and height of the clock
		currentTime = [];

	if (window.currentTime === undefined) {
		window.currentTime = currentTime;
	}

	function startClock(){

		aClock.css({"height":clockWidthHeight +"px"});//sets the height if .js is enabled. If not, height = 0;
		aClock.fadeIn();//fade it in

		//call rotatehands function
		setInterval(function(){

			rotateHands();

		}, 1000);//1000 = 1 second

		if (currentTime[0]) {
			rotateHands();//make sure they start in the right position
		} else {
			window.rotateHands = rotateHands;
		}
	}

	function rotateHands(){

		aClock.each(function(i, parent){
			//get current time/date from local computer
			var now,
				second = $('.secondHand', parent),
				minute = $('.minuteHand', parent),
				hour = $('.hourHand', parent);

			if (currentTime[i]) {
				now = currentTime[i];
				currentTime[i].setSeconds(currentTime[i].getSeconds() + 1);
			} else {
				now = new Date();
			}

			//set the second hand
			var secondAngle = 360/60 * now.getSeconds();//turn the time into angle
			second.rotate(secondAngle, 'abs');//set the hand angle
			second = $('.secondHand', parent);
			second.css({"left": (clockWidthHeight - second.width())/2 + "px",
					"top": (clockWidthHeight - second.height())/2 + "px"});//set x and y pos

			//set the minute hand
			var minuteAngle = 360/60 * now.getMinutes();//turn the time into angle
			minute.rotate(minuteAngle, 'abs');//set the hand angle
			minute = $('.minuteHand', parent);
			minute.css({"left": (clockWidthHeight - minute.width())/2 + "px",
					"top": (clockWidthHeight - minute.height())/2 + "px"});//set x and y pos

			//set the hour hand
			var hourAngle = 360/12 * now.getHours();//turn the time into angle
			hour.rotate((hourAngle + minuteAngle/12)%360, 'abs');//set the hand angle
			hour = $('.hourHand', parent);
			hour.css({"left": (clockWidthHeight - hour.width())/2 + "px",
					"top": (clockWidthHeight - hour.height())/2 + "px"});//set x and y pos
		});
	}

	startClock();


});
