/**
 * Count at Rate
 * by Peter Bleickardt
 * based on code by Matt Huggins
 *
 * Given an initial date and value plus a rate (value per second), this counter
 * will count upwards to show the value growing over time at the indicated
 * rate and starting with the current value at the current date.
 *
 */
(function($) {
	$.fn.countAtRate=function(options) {

		/**
		 * Merge options
		 */
		options=$.extend({}, $.fn.countAtRate.defaults, options || {});
		
		/**
		 * Main
		 */
		return $(this).each(function() {
			
			var _this=this;
			
			// Immediately update
			updateCounter();
			
			// Begin timer
			var interval=setInterval(updateCounter, options.refreshInterval);
			
			// Update function
			function updateCounter() {

				// Get current value
				var nowDate=new Date(),
					dateDiff=nowDate.getTime()-options.initialDate.getTime(),
					value=options.initialValue+(dateDiff/((1/options.rate)*1000));
				
				// Format string
				var displayValue=value.toFixed(options.decimals).toString();
				if (options.commify==true) {
					displayValue=displayValue.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
				}

				// Display
				$(_this).html(displayValue);
				//$(_this).html((dateDiff/(options.rate*1000)));

				// Handle callback "onUpdate"
				if (typeof(options.onUpdate)=="function") {
					options.onUpdate.call(_this, value);
				}

			}
			
		});
	};

	/**
	 * Options defaults
	 */
	$.fn.countAtRate.defaults={
		initialDate:		new Date(2011, 1, 1, 0, 0, 0, 0), // The initial date (remember, month and time parts are zero-based!)
		initialValue:		1500000000, // The initial value at the initial date
		rate:				1.65343915, // The rate expressed in "value per second"
		refreshInterval:	2000, // The refresh interval, in milliseconds
		decimals:			0, // The number of decimal places to show
		commify:			true, // Commify the output value, or not
		onUpdate:			null // Callback method for every time the element is updated
	};
})(jQuery);
