﻿var _ksCount = 0;
var _ksPerSec = 0;
var _timeoutId = null;
var _lastTime = null;

function startCount(ksCount, ksPerSec) {
	_lastTime = new Date();
	_ksCount = ksCount;
	_ksPerSec = ksPerSec;
	var slideshow = $('.slideshow');
	var ksDisplay = slideshow.parent()
		.prepend('<div id="ksDisplay" style="display: none;">Keystrokes Saved: <span style="font-weight: bold;" id="ksCount"></span></div>')
		.find('#ksDisplay').css({ 
			'color': '#003366',
			'font-size': '11px',
			'position': 'absolute',
			'text-align': 'right',
			'width': '240px',
			'z-index': 200
		});
	pinKsDisplay(ksDisplay);
	ksDisplay.show();
	$(window).resize(function(e) {
		pinKsDisplay();
	});
	updateCount();
}

function updateCount() {
	if (_timeoutId !== null) {
		window.clearTimeout(_timeoutId);
	}
	var timeout = Math.round(Math.random() * 7) * 1000;
	var ksCountStr = _ksCount.toString(10);
	var ar = new Array();
	while (ksCountStr.length > 3) {
		ar[ar.length] = ksCountStr.slice(-3);
		ksCountStr = ksCountStr.substring(0, ksCountStr.length - 3)
	}
	var arLength = ar.length;
	var el = $('#ksCount').html('');
	for (var i = 0; i < arLength; i++) {
		el.prepend(ar[i]);
		el.prepend(',');
	}
	el.prepend(ksCountStr);
	var now = new Date();
	var timeDiff = (now.valueOf() - _lastTime.valueOf()) / 1000;
	var ksSaved = Math.round(_ksPerSec * timeDiff);
	_ksCount += ksSaved;
	_lastTime = new Date();
	_timeoutId = window.setTimeout(updateCount, timeout);
}

function pinKsDisplay(ksDisplay) {
	var slideshow = $('.slideshow');
	var slideshowPos = slideshow.position();
	var slideshowWidth = slideshow.outerWidth();
	var slideshowHeight = slideshow.height();
	var left = slideshowPos.left + slideshowWidth - 247;
	var top = slideshowPos.top + slideshowHeight - 25;
	ksDisplay = ksDisplay || $('#ksDisplay');
	ksDisplay.css({
		'left': left, 
		'top': top
	});
}