/**
 * Price range slider labels: Persian digits + correct LTR number order in RTL layouts.
 */
(function ($, window) {
    'use strict';

    var PERSIAN_DIGITS = '\u06F0\u06F1\u06F2\u06F3\u06F4\u06F5\u06F6\u06F7\u06F8\u06F9';

    function stToPersianDigits(str) {
        return String(str).replace(/[0-9]/g, function (ch) {
            return PERSIAN_DIGITS.charAt(ch.charCodeAt(0) - 48);
        });
    }

    function stNumberFormat(number, decimals, dec_point, thousands_sep) {
        number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            s = '',
            toFixedFix = function (num, p) {
                var k = Math.pow(10, p);
                return '' + (Math.round(num * k) / k).toFixed(p);
            };

        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }

    function stFormatMoneyPlain(amount) {
        if (typeof st_params === 'undefined') {
            return stToPersianDigits(String(amount));
        }

        var money = stNumberFormat(
            amount,
            st_params.booking_currency_precision,
            st_params.decimal_separator,
            st_params.thousand_separator
        );
        var symbol = st_params.currency_symbol || '';
        var moneyString = '';

        switch (st_params.currency_position) {
            case 'right':
                moneyString = money + symbol;
                break;
            case 'left_space':
                moneyString = symbol + ' ' + money;
                break;
            case 'right_space':
                moneyString = money + ' ' + symbol;
                break;
            case 'left':
            default:
                moneyString = symbol + money;
                break;
        }

        return stToPersianDigits(moneyString);
    }

    function stFormatPriceFilterLabel(amount) {
        var money = stNumberFormat(
            amount,
            (typeof st_params !== 'undefined' && st_params.booking_currency_precision) ? st_params.booking_currency_precision : 0,
            (typeof st_params !== 'undefined' && st_params.decimal_separator) ? st_params.decimal_separator : '.',
            (typeof st_params !== 'undefined' && st_params.thousand_separator) ? st_params.thousand_separator : ','
        );
        money = stToPersianDigits(money);

        var symbol = (typeof st_params !== 'undefined' && st_params.currency_symbol) ? st_params.currency_symbol : '';
        var pos = (typeof st_params !== 'undefined' && st_params.currency_position) ? st_params.currency_position : 'left';
        var num = '<span class="st-price-filter-num" dir="ltr">' + money + '</span>';
        var cur = '<span class="st-price-filter-currency">' + symbol + '</span>';

        switch (pos) {
            case 'right':
            case 'right_space':
                return num + ' ' + cur;
            case 'left_space':
                return cur + ' ' + num;
            case 'left':
            default:
                return cur + ' ' + num;
        }
    }

    function stApplyPriceRangeLabels($scope, data) {
        if (!data) {
            return;
        }

        var $root = $scope && $scope.length ? $scope.closest('.range-slider') : $();
        if (!$root.length) {
            $root = $scope;
        }

        $root.find('.irs-from').html(stFormatPriceFilterLabel(data.from));
        $root.find('.irs-to').html(stFormatPriceFilterLabel(data.to));

        var $input = $root.find('.price_range');
        if ($input.length) {
            stUpdateMinMaxValueLabels($input);
        }
    }

    function stUpdateMinMaxValueLabels($input) {
        var $parent = $input.closest('.range-slider');
        var $from = $('.irs-from', $parent);
        var $to = $('.irs-to', $parent);

        $('.min-max-value .item-value', $parent).first().find('span').html($from.html());
        $('.min-max-value .item-value', $parent).last().find('span').html($to.html());
    }

    function stWrapSliderCallback(opts, name, $input) {
        var original = opts[name];
        opts[name] = function (data) {
            stApplyPriceRangeLabels($input.parents('.range-slider'), data);
            if (typeof original === 'function') {
                original(data);
            }
        };
    }

    function stEnhancePriceSliderOptions(opts, $input) {
        opts.prefix = '';
        opts.postfix = '';
        opts.prettify = false;

        ['onStart', 'onChange', 'onFinish', 'onUpdate'].forEach(function (eventName) {
            if (opts[eventName]) {
                stWrapSliderCallback(opts, eventName, $input);
            }
        });

        return opts;
    }

    function stPatchExistingSliders() {
        $('.price_range').each(function () {
            var $input = $(this);
            var instance = $input.data('ionRangeSlider');

            if (!instance || $input.data('stPriceFilterPatched')) {
                return;
            }

            $input.data('stPriceFilterPatched', true);

            if (instance.result) {
                stApplyPriceRangeLabels($input.parents('.range-slider'), instance.result);
            }
        });
    }

    window.stToPersianDigits = stToPersianDigits;
    window.stFormatMoneyPlain = stFormatMoneyPlain;
    window.stFormatPriceFilterLabel = stFormatPriceFilterLabel;
    window.stApplyPriceRangeLabels = stApplyPriceRangeLabels;
    window.stUpdateMinMaxValueLabels = stUpdateMinMaxValueLabels;
    window.stEnhancePriceSliderOptions = stEnhancePriceSliderOptions;

    $(function () {
        var attempts = 0;
        var timer = setInterval(function () {
            stPatchExistingSliders();
            attempts += 1;
            if (attempts >= 25) {
                clearInterval(timer);
            }
        }, 200);
    });
})(jQuery, window);
