﻿(function($) { // Hide scope, no $ conflict

    /* Made by Mathias Bynens <http://mathiasbynens.be/> */
    function number_format(a, b, c, d) {
        a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
        e = a + '';
        f = e.split('.');
        if (!f[0]) {
            f[0] = '0';
        }
        if (!f[1]) {
            f[1] = '';
        }
        if (f[1].length < b) {
            g = f[1];
            for (i = f[1].length + 1; i <= b; i++) {
                g += '0';
            }
            f[1] = g;
        }
        if (d != '' && f[0].length > 3) {
            h = f[0];
            f[0] = '';
            for (j = 3; j < h.length; j += 3) {
                i = h.slice(h.length - j, h.length - j + 3);
                f[0] = d + i + f[0] + '';
            }
            j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
            f[0] = j + f[0];
        }
        c = (b <= 0) ? '' : c;
        return f[0] + c + f[1];
    };

    var current = null;

    function PriceCounter(root, options) {
        // current instance
        var self = this;
        if (!current) { current = self; }

        // retrieve id for pricecounter
        var id;
        try {
            id = parseInt(root.attr('title'));
            // clear title attribute
            root.attr('title', '');
        }
        catch (err) {
            return;
        }

        var intval = '';
        var counter_run_time = 0;
        var price_data;
        var price = 0;
        var msec_till_next_update = 0;
        var price_decr = 0;
        var price_end = 0;
        var msec_till_auction_end = 0;
        var disabled = false;

        refresh();

        function refresh() {
            // Reset counter run time
            counter_run_time = 0;
            // Clear previous set interval
            if (intval != '') {
                clearInterval(intval);
                intval = '';
            }

            // Retrieve price data from url
            retrievePriceFromUrl(options.url, id);
        };

        //Convert duration from milliseconds to 0000:00:00.00 format
        function MillisecondsToDuration(n) {
            var hms = "";
            var dtm = new Date();
            dtm.setTime(n);
            var h = Math.floor(n / 3600000);
            var m = dtm.getMinutes();
            var s = dtm.getSeconds();
            hms = h + " uur en " + m + ((m == 1) ? " minuut" : " minuten");
            return hms;
        };


        function displayRemainingTime() {
            jQuery(root).html('');
            var counter_html = '<span class="timer">{0}</span>';
            root.append(counter_html.replace('{0}', MillisecondsToDuration(msec_till_auction_end)));
            if (msec_till_auction_end - options.update_interval > 0) {
                msec_till_auction_end = msec_till_auction_end - options.update_interval;
            }
            else {
                msec_till_auction_end = 0;
                clearInterval(intval);
            }
        };

        function firstPriceUpdate() {
            counter_run_time += msec_till_next_update;
            updatePrice();

            // Update counter after every update_interval milliseconds
            if (intval == '') {
                intval = setInterval(function() { updateCounter() }, options.update_interval);
            }
        };

        function updatePrice() {
            if (price - price_decr > price_end) {
                price = price - price_decr;
            }
            else {
                price = price_end;
                clearInterval(intval);
            }
            displayPrice();
        };

        function retrievePriceFromUrl(pUrl, id) {
            $.ajax({
                url: pUrl + '?jsonp=?',
                data: { id: id },
                dataType: "jsonp",
                async: false,
                success: function(data) {
                    price_data = data;
                    // Set price data
                    if (price_data == undefined || price_data == null)
                        return;
                    if (price_data.status != -1) {
                        price = price_data.price;
                        msec_till_next_update = price_data.msecTillNextUpdate;
                        price_decr = price_data.priceDecrement;
                        price_end = price_data.priceEnd;
                        msec_till_auction_end = price_data.msecTillAuctionEnd;
                        disabled = price_data.disabled;
                    }

                    if (options.is_timecountdown) {
                        // Display remaining time
                        displayRemainingTime();

                        // Update counter after every update_interval milliseconds
                        if (intval == '') {
                            intval = setInterval(function() { updateCounter() }, options.update_interval);
                        }
                    }
                    else {
                        // Display starting price
                        displayPrice();

                        // Do first update after msec_till_next_update milliseconds
                        setTimeout(function() { firstPriceUpdate() }, msec_till_next_update);
                    }
                },
                error: function() {
                }
            });
        };

        function displayPrice() {
            jQuery(root).html('');
            var counter_html = '';

            var priceText = number_format(price, 2, ',', '.');

            if (options.text_only) {
                counter_html = '<em>&euro;' + priceText + '</em>' + '<span id="price" class="hidden-price">' + number_format(price, 2, '.', '') + '</span>';
            }
            else {
                // if price < 10000, prefix with zeros
                var missingZero = 5 - ('' + Math.floor(price)).length;
                for (var i = 0; i < missingZero; i++) {
                    priceText = '0' + priceText;
                }
                var priceText = '€' + priceText;
                var start_cents = false;
                for (var i = 0; i < priceText.length; i++) {
                    var class_name;
                    switch (priceText.charAt(i)) {
                        case '€':
                            class_name = 'euro';
                            break;
                        case '.':
                            class_name = 'dot';
                            break;
                        case ',':
                            start_cents = true;
                            class_name = 'comma';
                            break;
                        case '0':
                            class_name = 'zero';
                            break;
                        case '1':
                            class_name = 'one';
                            break;
                        case '2':
                            class_name = 'two';
                            break;
                        case '3':
                            class_name = 'three';
                            break;
                        case '4':
                            class_name = 'four';
                            break;
                        case '5':
                            class_name = 'five';
                            break;
                        case '6':
                            class_name = 'six';
                            break;
                        case '7':
                            class_name = 'seven';
                            break;
                        case '8':
                            class_name = 'eight';
                            break;
                        case '9':
                            class_name = 'nine';
                            break;
                    }
                    var digit_html = '<span class="{0}" />';
                    if (start_cents) {
                        class_name += '-decimal';
                    }
                    if (disabled) {
                        class_name += '-disabled';
                    }
                    counter_html += digit_html.replace('{0}', class_name);
                }
                if (options.size == 'small') {
                    counter_html = '<div class="small">' + counter_html + '</div>';
                }
            }
            root.append(counter_html);

            try {
                if (options.text_only) {
                    calculatePrice();
                }
            }
            catch (err) { }
        };

        function updateCounter() {
            counter_run_time += options.update_interval;
            if (counter_run_time >= options.refresh_interval) {
                refresh();
            }
            else if (options.is_timecountdown) {
                displayRemainingTime();
            }
            else {
                updatePrice();
            }
        };

        this.stop = function() {
            clearInterval(intval);
        };
    };

    $.fn.pricecounter = function(options) {
        var defaults = {
            url: 'http://price.auto.nl/handlers/getpricedata.ashx',
            update_interval: 5000,
            refresh_interval: 300000,
            is_timecountdown: false,
            size: 'normal',
            text_only: false
        };
        var options = $.extend(defaults, options);

        this.each(function() {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('counter')) {
            }
            else {
                var counter = new PriceCounter($(this), options);

                // Store plugin object in this element's data
                element.data('counter', counter);
            }
        });

        return this;
    };

})(jQuery);
