// Array to hold each digit's starting background-position Y value
var initialPos = [0, -180, -360, -540, -720, -900, -1080, -1260, -1440, -1620];
// Amination frames
var animationFrames = 5;
// Frame shift
var frameShift = 30;
 
// Starting time
//var timeStart = getTimeString();
var timeStart = getDateString();

//console.log('timeStart = '+timeStart);

// Pace of counting in milliseconds
var pace = 1000;
 
// Initializing variables
var digitsOld = [], digitsNew = [], subStart, subEnd;
 
// Function that controls counting
function doCount(timeThen){
	//var timeNow = getTimeString();
	var timeNow = getDateString();
	
	digitCheck(timeThen,timeNow);
	setTimeout(function(){
		doCount(timeNow);
	}, pace);
}
 
// This checks the old count value vs. new value, to determine how many digits
// have changed and need to be animated.
function digitCheck(x,y){
	digitsOld = splitToArray(x);
	digitsNew = splitToArray(y);
	for (var i = 0; i < digitsNew.length; i++){
		if (digitsNew[i] != digitsOld[i]){
			animateDigit(i, digitsOld[i], digitsNew[i]);
		}
	}
}
 
// Animation function
function animateDigit(n, oldDigit, newDigit){
	speed = 80;
	// Get the initial Y value of background position to begin animate
	var pos = initialPos[oldDigit];
	// Each animation is 5 frames long, and 103px down the background image.
	// We delay each frame according to the speed we determined above.
	for (var k = 0; k < animationFrames; k++){
		pos = pos - frameShift;
		if (k == (animationFrames - 1)){
			$("#d" + n).delay(speed).animate({'background-position': '0 ' + pos + 'px'}, 0, function(){
				// At end of animation, shift position to new digit.
				$("#d" + n).css({'background-position': '0 ' + initialPos[newDigit] + 'px'}, 0);
			});
		}
		else{
			$("#d" + n).delay(speed).animate({'background-position': '0 ' + pos + 'px'}, 0);
		}
	}
}
 
// Splits each value into an array of digits
function splitToArray(input){
	var digits = new Array();
	for (var i = 0; i < input.length; i++){
		subStart = input.length - (i + 1);
		subEnd = input.length - i;
		digits[i] = input.substring(subStart, subEnd);
	}
	return digits;
}
 
// Sets the correct digits on load
function initialDigitCheck(initial){
	var digits = splitToArray(initial.toString());
	for (var i = 0; i < digits.length; i++){
		$("#d" + i).css({'background-position': '0 ' + initialPos[digits[i]] + 'px'});
	}
}

// Returns time as hhmmss
function getTimeString(){
	var currentDate = new Date();
	
	var hours = currentDate.getHours();
	hours = (hours < 10) ? '0' + hours : hours.toString();
	
	var minutes = currentDate.getMinutes();
	minutes = (minutes < 10) ? '0' + minutes : minutes.toString();
	
	var seconds = currentDate.getSeconds();
	seconds = (seconds < 10) ? '0' + seconds : seconds.toString();
	
	var time = hours + minutes + seconds;
	
	//console.log('h '+hours+' m '+minutes+' s '+seconds);
	return time;
}

// Returns time difference as dddhhmmss
function getDateString() {

	var laterdate = new Date(2010, 6, 3, 19, 0, 0, 0);
	//var laterdate = new Date(2010, 6, 3, 10, 15, 0, 0, 0);
	
	var earlierdate = new Date();

	//console.log('day1 = '+laterdate+' / '+' day2 = '+earlierdate);

    var difference = laterdate.getTime() - earlierdate.getTime();
   
    difference = Math.abs(difference/1000);
    
	//console.log('diff '+(earlierdate.getTimezoneOffset() * 60));
    
    // correct time to UTC (GMT)
    difference = difference + (earlierdate.getTimezoneOffset() * 60);
    
 	//console.log('ticks = '+difference);
 
    var daysDifference = Math.floor(difference/60/60/24).toString();
    difference -= daysDifference*60*60*24
 	//console.log('days = '+daysDifference);
  
    var hoursDifference = Math.floor(difference/60/60).toString();
    difference -= hoursDifference*60*60
 	//console.log('hours = '+hoursDifference);
 
    var minutesDifference = Math.floor(difference/60).toString();
    difference -= minutesDifference*60;
 	//console.log('minutes = '+minutesDifference);
 
    var secondsDifference = Math.floor(difference).toString();
 	//console.log('seconds = '+secondsDifference);
    
    var time = leadingZeros(daysDifference, 3) + leadingZeros(hoursDifference, 2) + leadingZeros(minutesDifference, 2) + leadingZeros(secondsDifference, 2);
    
    var debug_time = leadingZeros(daysDifference, 3) + " " + leadingZeros(hoursDifference, 2) + " " + leadingZeros(minutesDifference, 2) + " " + leadingZeros(secondsDifference, 2);
    
    //console.log('time = '+debug_time);
    
    // return time;
    // When time is up use this line instead... (7pm on 16th Nov is 136010000)
    // Stopped at 16th Nov 20:55
    return 136025500;
}

function leadingZeros(num, totalChars, padWith) {
	num = num + "";
	padWith = (padWith) ? padWith : "0";
	if (num.length < totalChars) {
		while (num.length < totalChars) {
			num = padWith + num;
		}
	} else {}
 
	if (num.length > totalChars) { //if padWith was a multiple character string and num was overpadded
		num = num.substring((num.length - totalChars), totalChars);
	} else {}
 
	return num;
}
 
// Start it up
initialDigitCheck(timeStart);
doCount(timeStart);
