/*
 * jQuery Flip Counter v1.0 by Brolly.ca - http://bloggingsquared.com/jquery/flipcounter/
 *
 * Uses valid markup and an image sprite to render an analogue clock / odometer effect.
 * Clock image is easily customizable, default options can be easily overriden, can be easily animated and extended with jQuery.easing plugin, gracefully degrades if Javascript is not available.
 *
 * TERMS OF USE - jQuery Flip Counter
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2010 Dan Imbrogno and Brolly Inc. 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

(function ($) {

    $.fn.flipCounter = function (options) {
        var style_character = false; // css style of characters
        return this.each(function () {
            // Public Variables
            var obj = false; // reference to current DOM object
            var currNumber = 0;
            var _interval;

            var _options;

            var defaults = {
                velocity: 15,
                refreshInterval: 80,
                digitWidth: 37
            };

            // Private Functions

            // Render the counter
            function _renderCounter() {
                // Add or remove enough digits to fit number
                var digits = obj.children('.counter-digit');
                var number = currNumber.toFixed().toString();

                var digitSpaces = number.length + Math.floor(number.length / 3);

                while (digitSpaces != digits.length) {
                    if (digitSpaces > digits.length) {
                        obj.prepend('<span class="counter-digit inline-image-replacement inline-block" style="' + style_character['0'] + '">,</span>');
                    }
                    else if (digitSpaces < digits.length) {
                        obj.children('.counter-digit:nth-child(1)').remove();
                    }
                    digits = obj.children('.counter-digit');
                }

                var commas = 0;
                digits.reverse().each(function (index, value) {
                    if (index == 3 || index == 7 || index == 11) {
                        $(value).addClass("comma");
                        commas++;
                    } else {
                        var digit = number.charAt(number.length - (index - commas) - 1);
                        $(value).removeClass("comma").attr('style', style_character[digit]);
                    }
                });
            }
            // Setup the CSS styles
            function _setupStyles() {
                style_character = {
                    '1': 'background-position: ' + _options.digitWidth * 0 + 'px 0px;',
                    '2': 'background-position: -' + _options.digitWidth * 1 + 'px 0px;',
                    '3': 'background-position: -' + _options.digitWidth * 2 + 'px 0px;',
                    '4': 'background-position: -' + _options.digitWidth * 3 + 'px 0px;',
                    '5': 'background-position: -' + _options.digitWidth * 4 + 'px 0px;',
                    '6': 'background-position: -' + _options.digitWidth * 5 + 'px 0px;',
                    '7': 'background-position: -' + _options.digitWidth * 6 + 'px 0px;',
                    '8': 'background-position: -' + _options.digitWidth * 7 + 'px 0px;',
                    '9': 'background-position: -' + _options.digitWidth * 8 + 'px 0px;',
                    '0': 'background-position: -' + _options.digitWidth * 9 + 'px 0px;',
                    '.': 'background-position: -' + _options.digitWidth * 10 + 'px 0px;',
                    '-': 'background-position: -' + _options.digitWidth * 11 + 'px 0px;'
                };
            }

            // Do animation step
            function _doAnimation() {
                currNumber += ((_options.refreshInterval / 1000) * _options.velocity);
                _renderCounter();
            }
            // Set reference to this DOM object
            obj = $(this);

            // new options override defaults
            _options = $.extend(defaults, options);

            currNumber = parseFloat(obj.find('> input').val());

            // Render counter
            _setupStyles();
            _renderCounter();
            _interval = setInterval(_doAnimation, _options.refreshInterval);
        })

    }

})(jQuery);
