(function($) {

	function pad(number, length) {
		var str = '' + number;
		
		while (str.length < length) {
			str = '0' + str;
		}
		
		return str;
	}
	
	var methods = {
	
		init: function(options) {
			var settings = {
				startValue: '0000',
				pad: 4,
				tFH: 16,
				bFH: 20,
				fW: 46,
				bOffset: 160,
				multiAnimation: true
			};
			
			return this.each(function() {
				var $this = $(this);
				
				if (options) {
					$.extend(settings, options);
				}
				
				$this.data('settings', settings);
				
				$this.data('value', parseInt($this.text().trim())).text('');
				
				var startValue;
				
				if (settings.multiAnimation) {
					startValue = pad(settings.startValue, settings.pad);
				} else {
					startValue = pad($this.data('value'), settings.pad);	
				}
				
				$this.fadeIn();
				
				$this.data('obj', new flipCounter($this.attr('id'), {
					value: startValue,
					tFH: settings.tFH,
					bFH: settings.bFH,
					fW: settings.fW,
					bOffset: settings.bOffset,
					auto: false
				}));
				
				if (settings.multiAnimation) {
					var elem = $this;
					
					setTimeout(function() {
						elem.data('obj').setValue(pad(Math.floor(elem.data('value')/6), settings.pad));
					}, 1000);
					
					setTimeout(function() {
						elem.data('obj').setValue(pad(Math.floor(elem.data('value')/4), settings.pad));
					}, 1400);
					
					setTimeout(function() {
						elem.data('obj').setValue(pad(Math.floor(elem.data('value')/2), settings.pad));
					}, 1800);
					
					setTimeout(function() {
						elem.data('obj').setValue(pad(Math.floor(elem.data('value')), settings.pad));
					}, 2200);
				}
			});
		},
		
		update: function(value) {
			return this.each(function() {
				var $this = $(this);
				
				$this.data('obj').setValue(pad(Math.floor(value), $this.data('settings').pad));
			});
		}
	
	}
	
	$.fn.counter = function(method) {
		
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.counter');
		}
	
	};

})(jQuery);
