// source --> https://adabl.org/wp-content/plugins/local-pickup-for-woocommerce/public/js/local-pickup-woocommerce-public.js?ver=v1.1.2 
(function( $ ) {
	'use strict';

	/**
	 * All of the code for your public-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * $(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * $( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */
    $(function() {
        //pickup location dropdown init & change event ( "o" function in reference plugin )
        function dslpfw_initiate_select2() {
            var selct2_obj = $('.pickup-location-list');
            // var width = selct2_obj.closest('td').css('width');
            
            // Fixes for #105002 ticket issue
            if (selct2_obj.length === 0) { return; }

            selct2_obj.select2({ 
                width: 'resolve',
                templateResult: function (state) {
                    if (!state.id) {
                        return state.text;
                    }
                    var location_name = state.name ? state.name : $(state.element).data('name'),
                        location_address = state.address ? state.address : $(state.element).data('address'),
                        location_postcode = state.postcode ? state.postcode : $(state.element).data('postcode');
                    var $state = $(
                        '<span>' + location_name + '</span><br>' + 
                        '<small>' + location_address + ' - <em>' + location_postcode + '</em></small>'
                    );
                    return $state ? $state : state.text;
                },
                matcher: function(params, data) {
                    // If there are no search terms, return all of the data
                    if ($.trim(params.term) === '') {
                        return data;
                    }

                    // Prepare variables for matching
                    var term = params.term.toLowerCase();

                    // Search name, address, postcode fields
                    var name = '';
                    var address = '';
                    var postcode = '';
                    
                    // state.option for legacy, state.element for select2 4+
                    if (data.name) {
                        name = data.name.toLowerCase();
                    } else if (data.element) {
                        name = ($(data.element).data('name') || '').toLowerCase();
                    }

                    if (data.address) {
                        address = data.address.toLowerCase();
                    } else if (data.element) {
                        address = ($(data.element).data('address') || '').toLowerCase();
                    }
                    
                    if (data.postcode) {
                        postcode = data.postcode.toLowerCase();
                    } else if (data.element) {
                        var postcodeData = $(data.element).data('postcode');
                        postcode = (typeof postcodeData === 'string' ? postcodeData : (postcodeData !== undefined && postcodeData !== null ? String(postcodeData) : '')).toLowerCase();
                    }

                    // If search term matches name, address, or postcode
                    if (
                        name.indexOf(term) > -1 ||
                        address.indexOf(term) > -1 ||
                        postcode.indexOf(term) > -1
                    ) {
                        return data;
                    }

                    // Return null if not matched
                    return null;
                }
            });

            selct2_obj.off('change.ds-local-pickup').on( 'change.ds-local-pickup', function () {
                var object_type = $(this).data('pickup-object-type');
                var object_id = $(this).data('pickup-object-id');
                var current_val = $(this).val();
                var data;
                if( 'cart-item' === object_type ){
                    data = { 
                        action: 'dslpfw_set_cart_item_handling', 
                        security: dslpfw_front_vars.dslpfw_set_cart_item_handling_nonce, 
                        cart_item_key: object_id, 
                        pickup_data: { 
                            handling: 'pickup',
                            pickup_location_id: current_val 
                        } 
                    };
                }
                if( 'package' === object_type ){
                    data = { 
                        action: 'dslpfw_set_package_handling', 
                        security: dslpfw_front_vars.dslpfw_set_package_handling_nonce, 
                        package_id: object_id,  
                        pickup_location_id: current_val 
                    };
                } 
                $('.woocommerce-cart-form, .cart_totals, .woocommerce-checkout-review-order').block({
                    message: null,
                    overlayCSS: {
                        background: 'rgb(255, 255, 255)',
                        opacity: 0.6,
                    },
                });
                $.ajax({
                    type: 'POST',
                    url: dslpfw_front_vars.ajaxurl,
                    data: data,
                    success: function( responce ){
                        $('.woocommerce-cart-form, .cart_totals, .woocommerce-checkout-review-order').unblock();
                        if( responce.success ) {
                            if( dslpfw_front_vars.is_cart ) {
                                $(document).trigger('wc_update_cart');
                            }
                            if( dslpfw_front_vars.is_checkout ) {
                                $(document.body).trigger('update_checkout');
                            }
                        }
                    }
                });
            });
        }
        dslpfw_initiate_select2();

        //Toggle pickup and shipping handling for cart items ( "c" function in reference plugin )
        function dslpfw_toggle_pickup_shipping_handling() {
            $('a.dslpfw-local-pickup-enable, a.dslpfw-local-pickup-disable').on('click', function (e) {
                e.preventDefault();
                var handling;
                var toggle_parent = $(this).closest('.dslpfw-pickup-location-field-toggle');
                if( $(this).hasClass('dslpfw-local-pickup-enable') ) {
                    handling = 'pickup'; 
                    toggle_parent.find('a.dslpfw-local-pickup-enable').parent().hide();
                    toggle_parent.find('a.dslpfw-local-pickup-disable').parent().show();
                    toggle_parent.find('> div').show();
                } else {
                    handling = 'ship';
                    toggle_parent.find('a.dslpfw-local-pickup-enable').parent().show();
                    toggle_parent.find('a.dslpfw-local-pickup-disable').parent().hide();
                    toggle_parent.find('> div').hide();
                }
                var pickup_location_id = $(this).closest('td').find('.pickup-location-list').val();

                var data = {
                    action: 'dslpfw_set_cart_item_handling',
                    security: dslpfw_front_vars.dslpfw_set_cart_item_handling_nonce,
                    cart_item_key: toggle_parent.data('pickup-object-id'),
                    pickup_data: { 
                        handling: handling, 
                        pickup_location_id: pickup_location_id 
                    },
                };
                $('.woocommerce-cart-form').block({
                    message: null,
                    overlayCSS: {
                        background: 'rgb(255, 255, 255)',
                        opacity: 0.6,
                    },
                });
                $.ajax({
                    type: 'POST',
                    url: dslpfw_front_vars.ajaxurl,
                    data: data,
                    success: function( responce ){
                        if( 'per-order' === dslpfw_front_vars.pickup_selection_mode) {
                            $('.pickup-location-list').trigger('change');
                        }
                        $('.woocommerce-cart-form').unblock();
                        if( responce.success ) {
                            if( dslpfw_front_vars.is_cart ) {
                                $(document).trigger('wc_update_cart');
                            }
                            if( dslpfw_front_vars.is_checkout ) {
                                $(document.body).trigger('update_checkout');
                            }
                        }
                    }
                });
            });
        }
        dslpfw_toggle_pickup_shipping_handling();

        //On change shipping methos session data modify ( "i" function in reference plugin )
        $('input[name^="shipping_method"][type="radio"]').off('change.ds-local-pickup').on('change.ds-local-pickup', function () {
            var shipping_type = $(this).is(':checked') && 'ds_local_pickup' === $(this).val() ? 'pickup' : 'ship';
            var package_id = $(this).attr('data-index');
            $.ajax({
                type: 'POST',
                url: dslpfw_front_vars.ajaxurl,
                data: {
                    action: 'dslpfw_set_package_items_handling', 
                    security: dslpfw_front_vars.dslpfw_set_package_items_handling_nonce, 
                    package_id: package_id,  
                    handling: shipping_type
                },
                success: function( responce ){
                    if( responce.success ) {
                        if( dslpfw_front_vars.is_cart ) {
                            $(document.body).on('updated_shipping_method', function () {
                                return $(document).trigger('wc_update_cart');
                            });
                        }
                        if( dslpfw_front_vars.is_checkout ) {
                            h(document.body).one('updated_checkout', function () {
                                return h(document.body).trigger('update_checkout');
                            });
                        }
                    }
                }
            });
        });

        if(dslpfw_front_vars.is_cart) {
            remove_shipping_calc_and_details();
        }
        if(dslpfw_front_vars.is_checkout){
            dslpfw_show_hide_shipping_fields_checkout();
        }
        
        $('#order_review').find('> p.woocommerce-shipping-contents').remove(),
        $(document.body).on('updated_cart_totals', function () {
            remove_shipping_calc_and_details();
            dslpfw_toggle_pickup_shipping_handling();
            dslpfw_initiate_select2();
        });

        $(document.body).on('updated_checkout', function () {
            dslpfw_show_hide_shipping_fields_checkout();
            if( $('.dslpfw-pickup-location-appointment') ) {
                $('.dslpfw-pickup-location-appointment').each(function(){
                    var $this = $(this);
                    var pickup_location = $this.find('input.dslpfw-pickup-location-appointment-date').data('location-id');
                    $.ajax({
                        type: 'POST',
                        url: dslpfw_front_vars.ajaxurl,
                        data: {
                            action: 'dslpfw_get_pickup_location_appointment_data', 
                            security: dslpfw_front_vars.dslpfw_get_pickup_location_appointment_data_nonce, 
                            location_id: pickup_location
                        },
                        success: function( responce ){
                            if( responce.success ) {
                                update_datepicker($this, responce.data);
                            }                            
                        }
                    });
                });
                dslpfw_toggle_pickup_shipping_handling();
                dslpfw_initiate_select2();
            }
        });
    });

    function update_datepicker( $this, $appointment_data) {
        var datepicker_field = $this.find('input.dslpfw-pickup-location-appointment-date');
        var datepicker_field_val = $this.find('input.dslpfw-pickup-location-appointment-date-alt');
        var clear_datepicker = $this.find('[id^=dslpfw-date-clear-]');
        var datepicker_val = datepicker_field.val();
        var location_id = datepicker_field.data('location-id');
        var package_id = datepicker_field.data('package-id');
        var date_from_datepicker = ( '' !== datepicker_val ) ? new Date(datepicker_val) : ($appointment_data.default_date && '' !== $appointment_data.default_date ? new Date(1e3 * $appointment_data.default_date) : null );
        var disabled_dates = $appointment_data.unavailable_dates ? $.map($appointment_data.unavailable_dates, function (date) {
            return date;
        }) : [];
        
        // datepicker_field.attr('value', '');
        // datepicker_field.trigger('change');
        // datepicker_field.removeClass('hasDatepicker');
        // datepicker_field.datepicker('destroy');

        var min_date = new Date(1e3 * $appointment_data.calendar_start);
        var max_date = new Date(1e3 * $appointment_data.calendar_end);
        min_date = new Date(min_date.getTime() + 60 * min_date.getTimezoneOffset() * 1e3);
        max_date = new Date(max_date.getTime() + 60 * max_date.getTimezoneOffset() * 1e3);
        date_from_datepicker = new Date(date_from_datepicker.getTime() + 60 * date_from_datepicker.getTimezoneOffset() * 1e3);

        datepicker_field.datepicker({
            minDate: min_date,
            maxDate: max_date,
            altField: '#' + datepicker_field_val.attr('id'),
            altFormat: 'yy-mm-dd',
            dateFormat: 'MM dd, yy',
            defaultDate: date_from_datepicker || null,
            firstDay: dslpfw_front_vars.start_of_week,
            prevText: '',
            nextText: '',
            showOn: 'both',
            gotoCurrent: true,
            changeMonth: true,
            changeYear: true,
            beforeShow: function (e, t) {
                return $(t.dpDiv).addClass('dslpfw-appointment-datepicker').addClass('dslpfw-appointment-datepicker-' + package_id);
            },
            beforeShowDay: function (date) {
                date = $.datepicker.formatDate('yy-mm-dd', date);
                return [-1 === disabled_dates.indexOf(date), 'dslpfw_available'];
            },
            onSelect: show_timerange,
        })
        .one('init', function () {
            return $('button.ui-datepicker-trigger').attr('title', dslpfw_front_vars.datepicker_title);
        })
        .trigger('init');
        
        $this.find('select.dslpfw-pickup-location-appointment-offset').select2().on('change', function (e) {
            return e.preventDefault(), e.stopPropagation(), show_timerange($.datepicker.formatDate('yy-mm-dd', datepicker_field.datepicker('getDate')), datepicker_field);
        });

        var selected_date = datepicker_field.val() && datepicker_field.val().match(/^\d{4}-\d{2}-\d{2}$/) ? $.datepicker.parseDate('yy-mm-dd', datepicker_field.val()) : null;
        if( selected_date ){
            datepicker_field.datepicker('setDate', selected_date);
            $('#ui-datepicker-div').hide();
        } else {
            if( $appointment_data.auto_select_default && $appointment_data.default_date && '' !== $appointment_data.default_date ){
                var default_date = $.datepicker.parseDate('yy-mm-dd', $appointment_data.default_date);
                datepicker_field.datepicker('setDate', default_date);
                $('#ui-datepicker-div').hide();
                show_timerange( default_date, datepicker_field );
            }
        }

        clear_datepicker.on( 'click', function(e){
            e.preventDefault();
            $('.woocommerce-checkout-review-order').block({
                message: null,
                overlayCSS: {
                    background: 'rgb(255, 255, 255)',
                    opacity: 0.6,
                },
            });
            datepicker_field.datepicker('setDate', null);
            datepicker_field.attr('value', '');
            $.ajax({
                type: 'POST',
                url: dslpfw_front_vars.ajaxurl,
                data: {
                    action: 'dslpfw_set_package_handling', 
                    security: dslpfw_front_vars.dslpfw_set_package_handling_nonce, 
                    pickup_date: '', 
                    package_id: package_id, 
                    pickup_location_id: location_id,
                },
                success: function( responce ){
                    $('.woocommerce-checkout-review-order').unblock();
                    if( responce.success ) {
                        $this.find('.dslpfw-pickup-location-schedule').empty();
                        $(document.body).trigger('update_checkout');
                    }                            
                }
            });
        });
    }

    function show_timerange( datetext, ele ) {
        ele = ele.input ? ele.input : ele;
        var location_id = ele.data('location-id');
        var show_schedule_ele = ele.parent().parent();
        var package_id = ele.data('package-id');
        var pickup_date = $('#dslpfw-pickup-date-' + package_id).val();
        var pickup_offset = $('#dslpfw-pickup-appointment-offset-' + package_id);
        var pickup_offset_val = pickup_offset.val();
        if( datetext && pickup_date && new Date(pickup_date) ) {
            ele.attr( 'value', datetext );
            $('.woocommerce-checkout-review-order').block({
                message: null,
                overlayCSS: {
                    background: 'rgb(255, 255, 255)',
                    opacity: 0.6,
                },
            });
            $.ajax({
                type: 'POST',
                url: dslpfw_front_vars.ajaxurl,
                data: {
                    action: 'dslpfw_set_package_handling', 
                    security: dslpfw_front_vars.dslpfw_set_package_handling_nonce, 
                    pickup_date: pickup_date, 
                    package_id: package_id, 
                    pickup_location_id: location_id, 
                    appointment_offset: pickup_offset_val
                },
                success: function( responce ){
                    if( responce.success ) {
                        if( pickup_offset.length === 0 ) {
                            $.ajax({
                                type: 'POST',
                                url: dslpfw_front_vars.ajaxurl,
                                data: {
                                    action: 'dslpfw_get_pickup_location_opening_hours_list', 
                                    security: dslpfw_front_vars.dslpfw_get_pickup_location_opening_hours_list_nonce, 
                                    location: location_id, 
                                    package_id: package_id, 
                                    pickup_date: pickup_date
                                },
                                success: function( responce ){
                                    if (responce && responce.success) {
                                        var append_html = show_schedule_ele.find('.dslpfw-pickup-location-schedule');
                                        append_html.empty();
                                        append_html.append(responce.data);
                                        $(document.body).trigger('update_checkout');
                                    }
                                    $('.woocommerce-checkout-review-order').unblock();              
                                }
                            });
                        } else {
                            $(document.body).trigger('update_checkout');
                            $('.woocommerce-checkout-review-order').unblock();
                        }
                    } else {
                        $('.woocommerce-checkout-review-order').unblock();
                    }                        
                }
            });
        }
    }

    /** hide shipping calc and address for shipping details ("u" function in reference plugin) */
    function remove_shipping_calc_and_details(){
        $('.woocommerce-shipping-totals').each(function () {
            var checkValue = $(this).find('input.shipping_method:checked').val();
            var hiddenValue = $(this).find('input:hidden.shipping_method').val();
            if (checkValue === dslpfw_front_vars.shipping_method_id || hiddenValue === dslpfw_front_vars.shipping_method_id) {
                $(this).find('p.woocommerce-shipping-destination, .woocommerce-shipping-calculator').hide();
            }
        });
    }
    /** Hide shipping method checkbox from checkout page for pickup only ("p" function in reference plugin) */
    function dslpfw_show_hide_shipping_fields_checkout(){
        if( ! dslpfw_front_vars.dslpfw_display_shipping_address_fields ){
            var pickup_selected;
            if( 'per-item' === dslpfw_front_vars.pickup_selection_mode) {
                pickup_selected = parseInt($('#dslpfw-packages-to-pickup').val());
            } else {
                pickup_selected = $('.woocommerce-shipping-methods').find('input[value=ds_local_pickup]:checked').length;
        
                // If no radio button is found, get the value from the hidden input for local pick up
                if ( pickup_selected === 0 ) {
                    pickup_selected = $('input[type="hidden"][name^="shipping_method"][value="ds_local_pickup"]').length;
                }
            }

            if( pickup_selected > 0 ) {
                $('#shiptobilling, #ship-to-different-address').hide(),
                $('#shiptobilling, #ship-to-different-address').parent().find('h3').hide(),
                $('#ship-to-different-address input').prop('checked', !1),
                $('.shipping_address').hide();
            } else {
                $('#shiptobilling, #ship-to-different-address').show(),
                $('#shiptobilling, #ship-to-different-address').parent().find('h3').show(),
                $('#ship-to-different-address input').is(':checked') ? $('.shipping_address').show() : $('.shipping_address').hide();
            }
        }
    }

})( jQuery );
// source --> https://adabl.org/wp-content/plugins/qsm-advanced-timer//js/circle-progress.js?ver=6.9.4 
/**
 * jquery-circle-progress - jQuery Plugin to draw animated circular progress bars:
 * {@link http://kottenator.github.io/jquery-circle-progress/}
 *
 * @author Rostyslav Bryzgunov <kottenator@gmail.com>
 * @version 1.2.2
 * @licence MIT
 * @preserve
 */
// UMD factory - https://github.com/umdjs/umd/blob/d31bb6ee7098715e019f52bdfe27b3e4bfd2b97e/templates/jqueryPlugin.js
// Uses AMD, CommonJS or browser globals to create a jQuery plugin.
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD - register as an anonymous module
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    var $ = require('jquery');
    factory($);
    module.exports = $;
  } else {
    // Browser globals
    factory(jQuery);
  }
})(function($) {
  /**
   * Inner implementation of the circle progress bar.
   * The class is not exposed _yet_ but you can create an instance through jQuery method call.
   *
   * @param {object} config - You can customize any class member (property or method).
   * @class
   * @alias CircleProgress
   */
  function CircleProgress(config) {
    this.init(config);
  }

  CircleProgress.prototype = {
    //--------------------------------------- public options ---------------------------------------
    /**
     * This is the only required option. It should be from `0.0` to `1.0`.
     * @type {number}
     * @default 0.0
     */
    value: 0.0,

    /**
     * Size of the canvas in pixels.
     * It's a square so we need only one dimension.
     * @type {number}
     * @default 100.0
     */
    size: 100.0,

    /**
     * Initial angle for `0.0` value in radians.
     * @type {number}
     * @default -Math.PI
     */
    startAngle: -Math.PI,

    /**
     * Width of the arc in pixels.
     * If it's `'auto'` - the value is calculated as `[this.size]{@link CircleProgress#size} / 14`.
     * @type {number|string}
     * @default 'auto'
     */
    thickness: 'auto',

    /**
     * Fill of the arc. You may set it to:
     *
     *   - solid color:
     *     - `'#3aeabb'`
     *     - `{ color: '#3aeabb' }`
     *     - `{ color: 'rgba(255, 255, 255, .3)' }`
     *   - linear gradient _(left to right)_:
     *     - `{ gradient: ['#3aeabb', '#fdd250'], gradientAngle: Math.PI / 4 }`
     *     - `{ gradient: ['red', 'green', 'blue'], gradientDirection: [x0, y0, x1, y1] }`
     *     - `{ gradient: [["red", .2], ["green", .3], ["blue", .8]] }`
     *   - image:
     *     - `{ image: 'http://i.imgur.com/pT0i89v.png' }`
     *     - `{ image: imageObject }`
     *     - `{ color: 'lime', image: 'http://i.imgur.com/pT0i89v.png' }` -
     *       color displayed until the image is loaded
     *
     * @default {gradient: ['#3aeabb', '#fdd250']}
     */
    fill: {
      gradient: ['#3aeabb', '#fdd250']
    },

    /**
     * Color of the "empty" arc. Only a color fill supported by now.
     * @type {string}
     * @default 'rgba(0, 0, 0, .1)'
     */
    emptyFill: 'rgba(0, 0, 0, .1)',

    /**
     * jQuery Animation config.
     * You can pass `false` to disable the animation.
     * @see http://api.jquery.com/animate/
     * @type {object|boolean}
     * @default {duration: 1200, easing: 'circleProgressEasing'}
     */
    animation: {
      duration: 1200,
      easing: 'circleProgressEasing'
    },

    /**
     * Default animation starts at `0.0` and ends at specified `value`. Let's call this _direct animation_.
     * If you want to make _reversed animation_ - set `animationStartValue: 1.0`.
     * Also you may specify any other value from `0.0` to `1.0`.
     * @type {number}
     * @default 0.0
     */
    animationStartValue: 0.0,

    /**
     * Reverse animation and arc draw.
     * By default, the arc is filled from `0.0` to `value`, _clockwise_.
     * With `reverse: true` the arc is filled from `1.0` to `value`, _counter-clockwise_.
     * @type {boolean}
     * @default false
     */
    reverse: false,

    /**
     * Arc line cap: `'butt'`, `'round'` or `'square'` -
     * [read more]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.lineCap}.
     * @type {string}
     * @default 'butt'
     */
    lineCap: 'butt',

    /**
     * Canvas insertion mode: append or prepend it into the parent element?
     * @type {string}
     * @default 'prepend'
     */
    insertMode: 'prepend',

    //------------------------------ protected properties and methods ------------------------------
    /**
     * Link to {@link CircleProgress} constructor.
     * @protected
     */
    constructor: CircleProgress,

    /**
     * Container element. Should be passed into constructor config.
     * @protected
     * @type {jQuery}
     */
    el: null,

    /**
     * Canvas element. Automatically generated and prepended to [this.el]{@link CircleProgress#el}.
     * @protected
     * @type {HTMLCanvasElement}
     */
    canvas: null,

    /**
     * 2D-context of [this.canvas]{@link CircleProgress#canvas}.
     * @protected
     * @type {CanvasRenderingContext2D}
     */
    ctx: null,

    /**
     * Radius of the outer circle. Automatically calculated as `[this.size]{@link CircleProgress#size} / 2`.
     * @protected
     * @type {number}
     */
    radius: 0.0,

    /**
     * Fill of the main arc. Automatically calculated, depending on [this.fill]{@link CircleProgress#fill} option.
     * @protected
     * @type {string|CanvasGradient|CanvasPattern}
     */
    arcFill: null,

    /**
     * Last rendered frame value.
     * @protected
     * @type {number}
     */
    lastFrameValue: 0.0,

    /**
     * Init/re-init the widget.
     *
     * Throws a jQuery event:
     *
     * - `circle-inited(jqEvent)`
     *
     * @param {object} config - You can customize any class member (property or method).
     */
    init: function(config) {
      $.extend(this, config);
      this.radius = this.size / 2;
      this.initWidget();
      this.initFill();
      this.draw();
      this.el.trigger('circle-inited');
    },

    /**
     * Initialize `<canvas>`.
     * @protected
     */
    initWidget: function() {
      if (!this.canvas)
        this.canvas = $('<canvas>')[this.insertMode == 'prepend' ? 'prependTo' : 'appendTo'](this.el)[0];

      var canvas = this.canvas;
      canvas.width = this.size;
      canvas.height = this.size;
      this.ctx = canvas.getContext('2d');

      if (window.devicePixelRatio > 1) {
        var scaleBy = window.devicePixelRatio;
        canvas.style.width = canvas.style.height = this.size + 'px';
        canvas.width = canvas.height = this.size * scaleBy;
        this.ctx.scale(scaleBy, scaleBy);
      }
    },

    /**
     * This method sets [this.arcFill]{@link CircleProgress#arcFill}.
     * It could do this async (on image load).
     * @protected
     */
    initFill: function() {
      var self = this,
        fill = this.fill,
        ctx = this.ctx,
        size = this.size;

      if (!fill)
        throw Error("The fill is not specified!");

      if (typeof fill == 'string')
        fill = {color: fill};

      if (fill.color)
        this.arcFill = fill.color;

      if (fill.gradient) {
        var gr = fill.gradient;

        if (gr.length == 1) {
          this.arcFill = gr[0];
        } else if (gr.length > 1) {
          var ga = fill.gradientAngle || 0, // gradient direction angle; 0 by default
            gd = fill.gradientDirection || [
                size / 2 * (1 - Math.cos(ga)), // x0
                size / 2 * (1 + Math.sin(ga)), // y0
                size / 2 * (1 + Math.cos(ga)), // x1
                size / 2 * (1 - Math.sin(ga))  // y1
              ];

          var lg = ctx.createLinearGradient.apply(ctx, gd);

          for (var i = 0; i < gr.length; i++) {
            var color = gr[i],
              pos = i / (gr.length - 1);

            if ($.isArray(color)) {
              pos = color[1];
              color = color[0];
            }

            lg.addColorStop(pos, color);
          }

          this.arcFill = lg;
        }
      }

      if (fill.image) {
        var img;

        if (fill.image instanceof Image) {
          img = fill.image;
        } else {
          img = new Image();
          img.src = fill.image;
        }

        if (img.complete)
          setImageFill();
        else
          img.onload = setImageFill;
      }

      function setImageFill() {
        var bg = $('<canvas>')[0];
        bg.width = self.size;
        bg.height = self.size;
        bg.getContext('2d').drawImage(img, 0, 0, size, size);
        self.arcFill = self.ctx.createPattern(bg, 'no-repeat');
        self.drawFrame(self.lastFrameValue);
      }
    },

    /**
     * Draw the circle.
     * @protected
     */
    draw: function() {
      if (this.animation)
        this.drawAnimated(this.value);
      else
        this.drawFrame(this.value);
    },

    /**
     * Draw a single animation frame.
     * @protected
     * @param {number} v - Frame value.
     */
    drawFrame: function(v) {
      this.lastFrameValue = v;
      this.ctx.clearRect(0, 0, this.size, this.size);
      this.drawEmptyArc(v);
      this.drawArc(v);
    },

    /**
     * Draw the arc (part of the circle).
     * @protected
     * @param {number} v - Frame value.
     */
    drawArc: function(v) {
      if (v === 0)
        return;

      var ctx = this.ctx,
        r = this.radius,
        t = this.getThickness(),
        a = this.startAngle;

      ctx.save();
      ctx.beginPath();

      if (!this.reverse) {
        ctx.arc(r, r, r - t / 2, a, a + Math.PI * 2 * v);
      } else {
        ctx.arc(r, r, r - t / 2, a - Math.PI * 2 * v, a);
      }

      ctx.lineWidth = t;
      ctx.lineCap = this.lineCap;
      ctx.strokeStyle = this.arcFill;
      ctx.stroke();
      ctx.restore();
    },

    /**
     * Draw the _empty (background)_ arc (part of the circle).
     * @protected
     * @param {number} v - Frame value.
     */
    drawEmptyArc: function(v) {
      var ctx = this.ctx,
        r = this.radius,
        t = this.getThickness(),
        a = this.startAngle;

      if (v < 1) {
        ctx.save();
        ctx.beginPath();

        if (v <= 0) {
          ctx.arc(r, r, r - t / 2, 0, Math.PI * 2);
        } else {
          if (!this.reverse) {
            ctx.arc(r, r, r - t / 2, a + Math.PI * 2 * v, a);
          } else {
            ctx.arc(r, r, r - t / 2, a, a - Math.PI * 2 * v);
          }
        }

        ctx.lineWidth = t;
        ctx.strokeStyle = this.emptyFill;
        ctx.stroke();
        ctx.restore();
      }
    },

    /**
     * Animate the progress bar.
     *
     * Throws 3 jQuery events:
     *
     * - `circle-animation-start(jqEvent)`
     * - `circle-animation-progress(jqEvent, animationProgress, stepValue)` - multiple event
     *   animationProgress: from `0.0` to `1.0`; stepValue: from `0.0` to `value`
     * - `circle-animation-end(jqEvent)`
     *
     * @protected
     * @param {number} v - Final value.
     */
    drawAnimated: function(v) {
      var self = this,
        el = this.el,
        canvas = $(this.canvas);

      // stop previous animation before new "start" event is triggered
      canvas.stop(true, false);
      el.trigger('circle-animation-start');

      canvas
        .css({animationProgress: 0})
        .animate({animationProgress: 1}, $.extend({}, this.animation, {
          step: function(animationProgress) {
            var stepValue = self.animationStartValue * (1 - animationProgress) + v * animationProgress;
            self.drawFrame(stepValue);
            el.trigger('circle-animation-progress', [animationProgress, stepValue]);
          }
        }))
        .promise()
        .always(function() {
          // trigger on both successful & failure animation end
          el.trigger('circle-animation-end');
        });
    },

    /**
     * Get the circle thickness.
     * @see CircleProgress#thickness
     * @protected
     * @returns {number}
     */
    getThickness: function() {
      return $.isNumeric(this.thickness) ? this.thickness : this.size / 14;
    },

    /**
     * Get current value.
     * @protected
     * @return {number}
     */
    getValue: function() {
      return this.value;
    },

    /**
     * Set current value (with smooth animation transition).
     * @protected
     * @param {number} newValue
     */
    setValue: function(newValue) {
      if (this.animation)
        this.animationStartValue = this.lastFrameValue;
      this.value = newValue;
      this.draw();
    }
  };

  //----------------------------------- Initiating jQuery plugin -----------------------------------
  $.circleProgress = {
    // Default options (you may override them)
    defaults: CircleProgress.prototype
  };

  // ease-in-out-cubic
  $.easing.circleProgressEasing = function(x) {
    if (x < 0.5) {
      x = 2 * x;
      return 0.5 * x * x * x;
    } else {
      x = 2 - 2 * x;
      return 1 - 0.5 * x * x * x;
    }
  };

  /**
   * Creates an instance of {@link CircleProgress}.
   * Produces [init event]{@link CircleProgress#init} and [animation events]{@link CircleProgress#drawAnimated}.
   *
   * @param {object} [configOrCommand] - Config object or command name.
   *
   * Config example (you can specify any {@link CircleProgress} property):
   *
   * ```js
   * { value: 0.75, size: 50, animation: false }
   * ```
   *
   * Commands:
   *
   * ```js
   * el.circleProgress('widget'); // get the <canvas>
   * el.circleProgress('value'); // get the value
   * el.circleProgress('value', newValue); // update the value
   * el.circleProgress('redraw'); // redraw the circle
   * el.circleProgress(); // the same as 'redraw'
   * ```
   *
   * @param {string} [commandArgument] - Some commands (like `'value'`) may require an argument.
   * @see CircleProgress
   * @alias "$(...).circleProgress"
   */
  $.fn.circleProgress = function(configOrCommand, commandArgument) {
    var dataName = 'circle-progress',
      firstInstance = this.data(dataName);

    if (configOrCommand == 'widget') {
      if (!firstInstance)
        throw Error('Calling "widget" method on not initialized instance is forbidden');
      return firstInstance.canvas;
    }

    if (configOrCommand == 'value') {
      if (!firstInstance)
        throw Error('Calling "value" method on not initialized instance is forbidden');
      if (typeof commandArgument == 'undefined') {
        return firstInstance.getValue();
      } else {
        var newValue = arguments[1];
        return this.each(function() {
          $(this).data(dataName).setValue(newValue);
        });
      }
    }

    return this.each(function() {
      var el = $(this),
        instance = el.data(dataName),
        config = $.isPlainObject(configOrCommand) ? configOrCommand : {};

      if (instance) {
        instance.init(config);
      } else {
        var initialConfig = $.extend({}, el.data());
        if (typeof initialConfig.fill == 'string')
          initialConfig.fill = JSON.parse(initialConfig.fill);
        if (typeof initialConfig.animation == 'string')
          initialConfig.animation = JSON.parse(initialConfig.animation);
        config = $.extend(initialConfig, config);
        config.el = el;
        instance = new CircleProgress(config);
        el.data(dataName, instance);
      }
    });
  };
});
// source --> https://adabl.org/wp-content/plugins/qsm-advanced-timer//js/front.js?ver=6.9.4 
jQuery(document).ready(function () {
    jQuery('.stoptimer').click(function () {
        MicroModal.show( 'stop-timer-popup' );
    });
    
    //Submit the form on popup click
    jQuery('.stop-timer-submit-the-form').click(function(e){
        e.preventDefault();
        var quiz_id = jQuery(this).data('quiz_id');
        qsmEndTimeTakenTimer();
        QSM.endTimer( quiz_id );
        jQuery('#quizForm' + quiz_id ).submit();
        jQuery('#stop-timer-popup').removeClass('is-open');
    });
    
    //Check stop timer div
    if(jQuery('.stoptimer-p').length > 0){        
        jQuery('.stoptimer-p').parents('.qsm-quiz-container').addClass('qsm-stop-timer-enabled');
    }
});