// source --> https://motorodina.sk/wp-content/plugins/wt-smart-coupons-for-woocommerce/public/js/wt-smart-coupon-public.js?ver=2.2.9 
jQuery(function ($) {
    "use strict";
    $('form.checkout').on('change.wt_sc_payment_method_change', 'input[name="payment_method"]', function () {

        let t = {updateTimer: !1, dirtyInput: !1,
            reset_update_checkout_timer: function () {
                clearTimeout(t.updateTimer)
            }, trigger_update_checkout: function () {
                t.reset_update_checkout_timer(), t.dirtyInput = !1,
                        $(document.body).trigger("update_checkout")
            }
        };
        t.trigger_update_checkout();
        
    });


    $('document').ready(function(){
        
        /* After the coupon box click event was done */
        $(document).on("wt_sc_api_coupon_click_done", function(e){
            wt_unblock_node($( 'div.wt_coupon_wrapper'));
            wt_unblock_node($("div.wt-mycoupons"));
            wt_unblock_node($("div.wt_store_credit"));
        });

        /** Handle keyboard Enter press on coupons */
        $( document ).on("keypress", '.wt-single-coupon.active-coupon', function(e){
            if( 13 === e.which ) { // Enter key
                $( this ).trigger( 'click' );
            }
        } );

        $(document).on("click", '.wt-single-coupon.active-coupon', function(){        
            
            if(!$('.woocommerce-notices-wrapper').length){
                $('#main').prepend('<div class="woocommerce-notices-wrapper"></div>');
            }
            
            const coupon_code = ( typeof $(this).attr('data-code') === 'undefined' ? $(this).find('code').text() : $(this).attr('data-code') );
            const coupon_id = $(this).attr('data-id');

            $('div.wt_coupon_wrapper, div.wt_store_credit').each(function(){
                if($(this).find('.wt-single-coupon').length)
                {
                    wt_block_node($(this));
                }
            });

            /* For checkout block compatibility */
            if( $('.wc-block-checkout, .wc-block-cart').length ) {
                
                const coupon_click_event = new CustomEvent("wt_sc_api_coupon_clicked", {
                    detail:{ 'coupon_code' : coupon_code, 'coupon_id': coupon_id}
                });
                document.dispatchEvent(coupon_click_event);
                return false;
            }
            
            const data = {
                'coupon_code'   : coupon_code,
                'coupon_id'     : coupon_id,
                '_wpnonce'      : WTSmartCouponOBJ.nonces.apply_coupon
            };

            $.ajax({
                type: "POST",
                async: true,
                url: WTSmartCouponOBJ.wc_ajax_url + 'apply_coupon_on_click',
                data: data,
                success: function (response) {
                    if ( $( '.woocommerce-cart-form' ).length) {
                        update_cart(true);  // need only for cart page
                    }
                    
                    wt_unblock_node( $( 'div.wt_coupon_wrapper' ) );
                    wt_unblock_node($("div.wt-mycoupons"));
                    wt_unblock_node($("div.wt_store_credit"));

                    $( '.woocommerce-error, .woocommerce-message, .woocommerce-info' ).remove();
                    show_notice( response );
                    $(document.body).trigger("update_checkout");
                    $( document.body ).trigger("applied_coupon");

                    $('html, body').animate({
                        scrollTop: $(".woocommerce").offset().top
                    }, 1000);
                }
            });

        });

        /* For checkout block */
        if( $('.wc-block-checkout').length ) {
            $( document ).on("click", '[name="radio-control-wc-payment-method-options"]', function(){
                WTSmartCouponOBJ.payment_method = $('[name="radio-control-wc-payment-method-options"]:checked').val();
                let parent_div = $('[name="radio-control-wc-payment-method-options"]').parents('.wc-block-components-radio-control');
                parent_div.find('.wc-block-components-radio-control__option').removeClass('wc-block-components-radio-control__option-checked');
                wbte_set_block_checkout_values();
            });

            setTimeout( wbte_set_block_checkout_values, 200);
        }
    
    });

    /** Update payment method on session, if coupons are changed update checkout */
    $( document.body ).on( 'payment_method_selected', 
        function() {
            jQuery( document ).on( "updated_checkout", 
                function(){
                    const selectedPaymentMethod = $( 'form.checkout' ).find( 'input[name="payment_method"]:checked' ).val();
                    $.ajax({
                        type: "POST",
                        url: WTSmartCouponOBJ.wc_ajax_url + 'wbte_sc_update_payment_method_on_session',
                        data: {
                            'payment_method': selectedPaymentMethod,
                            '_wpnonce': WTSmartCouponOBJ.nonces.public
                        },
                        success: function( response ) {
                            if ( response ) {
                                $( 'form.checkout' ).trigger( 'update' );
                            }
                        }
                    });
                }
            );
        }
    );

    const wbte_set_block_checkout_values = function() {

        let payment_method = '';
        const shipping_method = {};
      
        if( $('[name="radio-control-wc-payment-method-options"]').length ) {
            
            /* Prepare payment method from radio button */
            payment_method = $('[name="radio-control-wc-payment-method-options"]:checked').val();           

        }
        
        /* Prepare shipping method from radio button */
        if( $('.wc-block-components-shipping-rates-control input[type="radio"]').length ) {         
            $('.wc-block-components-shipping-rates-control input[type="radio"]:checked').each(function(index){
                shipping_method[index] = $(this).val(); 
            });
        }

        /* Store the value to global variable to prevent future auto refresh blocking */
        WTSmartCouponOBJ.shipping_method = shipping_method;
        WTSmartCouponOBJ.payment_method = payment_method;

        
        /* Send ajax request to set the value */
        let order_summary_block = $('.wp-block-woocommerce-checkout-order-summary-block');
        wt_block_node( order_summary_block );
        
        $.ajax({
            type: "POST",
            async: true,
            url: WTSmartCouponOBJ.wc_ajax_url + 'wbte_sc_set_block_checkout_values',
            data: { '_wpnonce': WTSmartCouponOBJ.nonces.public, 'payment_method': payment_method, 'shipping_method': shipping_method },
            dataType: 'json',
            success:function( data ) {
                wt_unblock_node( order_summary_block );
            },
            error:function() {
               wt_unblock_node( order_summary_block ); 
            }
        });

        /* Trigger checkout block refresh */
        setTimeout(function(){ 
            const checkout_value_updated_event = new CustomEvent("wbte_sc_checkout_value_updated", {
                detail:{ 'payment_method' : payment_method, 'shipping_method': shipping_method }
            });
            document.dispatchEvent(checkout_value_updated_event);
        }, 1000);
        
    }

    
    /**
     * Function from cart.js by woocommmerce
     * @param {bool} preserve_notices 
     */
    const update_cart = function( preserve_notices ) {
        const $form = $( '.woocommerce-cart-form' );
        wt_block_node( $form );
        wt_block_node( $( 'div.cart_totals' ) );
        
        

        // Make call to actual form post URL.
        $.ajax( {
            type:     $form.attr( 'method' ),
            url:      $form.attr( 'action' ),
            data:     $form.serialize(),
            dataType: 'html',
            success:  function( response ) {
                update_wc_div( response, preserve_notices );
            },
            complete: function() {
                wt_unblock_node( $form );
                wt_unblock_node( $( 'div.cart_totals' ) );
            }
        } );
    }


    /**
     * 
     * @param {string} html_str 
     * @param {bool} preserve_notices 
     */
    const update_wc_div = function( html_str, preserve_notices ) {
        const $html       = $.parseHTML( html_str );
        const $new_form   = $( '.woocommerce-cart-form', $html );
        const $new_totals = $( '.cart_totals', $html );
        const $notices    = $( '.woocommerce-error, .woocommerce-message, .woocommerce-info', $html );

        // No form, cannot do this.
        if ( $( '.woocommerce-cart-form' ).length === 0 ) {
            window.location.href = window.location.href;
            return;
        }

        // Remove errors
        if ( ! preserve_notices ) {
            $( '.woocommerce-error, .woocommerce-message, .woocommerce-info' ).remove();
        }

        if ( $new_form.length === 0 ) {
            // If the checkout is also displayed on this page, trigger reload instead.
            if ( $( '.woocommerce-checkout' ).length ) {
                window.location.href = window.location.href;
                return;
            }

            // No items to display now! Replace all cart content.
            const $cart_html = $( '.cart-empty', $html ).closest( '.woocommerce' );
            $( '.woocommerce-cart-form__contents' ).closest( '.woocommerce' ).replaceWith( $cart_html );

            // Display errors
            if ( $notices.length > 0 ) {
                show_notice( $notices );
            }
        } else {
            // If the checkout is also displayed on this page, trigger update event.
            if ( $( '.woocommerce-checkout' ).length ) {
                $( document.body ).trigger( 'update_checkout' );
            }

            $( '.woocommerce-cart-form' ).replaceWith( $new_form );
            $( '.woocommerce-cart-form' ).find( ':input[name="update_cart"]' ).prop( 'disabled', true );

            if ( $notices.length > 0 ) {
                show_notice( $notices );
            }

            update_cart_totals_div( $new_totals );
        }

        $( document.body ).trigger( 'updated_wc_div' );
    };
    

    /**
     * Function from woocmmerce cart.js
     * @param {string} html_str 
     */
    const update_cart_totals_div = function( html_str ) {
        $( '.cart_totals' ).replaceWith( html_str );
        $( document.body ).trigger( 'updated_cart_totals' );
    };



    /**
     * function from cart.js by wooocommerce
     * @param { jQuery object } node 
     */
    const wt_block_node = function( node ) {

        node.addClass( 'processing' );

        if(typeof $.fn.block === 'function')
        {
            node.block({
                message: null,
                overlayCSS: {
                    background: '#fff',
                    opacity: 0.6
                }
            });
        }
    }
    window.wbte_sc_block_node = wt_block_node;
    
    /**
     * function from cart.js by wooocommerce
     * @param {jQuery object} $node 
     */
    const wt_unblock_node = function( node ) {
        
        node.removeClass( 'processing' );
        
        if(typeof $.fn.unblock === 'function')
        {
            node.unblock();
        }      
    };
    window.wbte_sc_unblock_node = wt_unblock_node;


    const show_notice = function( html_element, $target ) {
        if ( ! $target ) {
            $target = $( '.woocommerce-notices-wrapper:first' ) || $( '.cart-empty' ).closest( '.woocommerce' ) || $( '.woocommerce-cart-form' );
        }
        $target.prepend( html_element );
    };

});
// source --> https://motorodina.sk/wp-includes/js/jquery/ui/core.min.js?ver=1.13.3 
/*! jQuery UI - v1.13.3 - 2024-04-26
* https://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-patch.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
!function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(x){"use strict";var t,e,i,n,W,C,o,s,r,l,a,h,u;function E(t,e,i){return[parseFloat(t[0])*(a.test(t[0])?e/100:1),parseFloat(t[1])*(a.test(t[1])?i/100:1)]}function L(t,e){return parseInt(x.css(t,e),10)||0}function N(t){return null!=t&&t===t.window}x.ui=x.ui||{},x.ui.version="1.13.3",
/*!
 * jQuery UI :data 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.extend(x.expr.pseudos,{data:x.expr.createPseudo?x.expr.createPseudo(function(e){return function(t){return!!x.data(t,e)}}):function(t,e,i){return!!x.data(t,i[3])}}),
/*!
 * jQuery UI Disable Selection 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.fn.extend({disableSelection:(t="onselectstart"in document.createElement("div")?"selectstart":"mousedown",function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}),enableSelection:function(){return this.off(".ui-disableSelection")}}),
/*!
 * jQuery UI Focusable 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.ui.focusable=function(t,e){var i,n,o,s=t.nodeName.toLowerCase();return"area"===s?(o=(i=t.parentNode).name,!(!t.href||!o||"map"!==i.nodeName.toLowerCase())&&0<(i=x("img[usemap='#"+o+"']")).length&&i.is(":visible")):(/^(input|select|textarea|button|object)$/.test(s)?(n=!t.disabled)&&(o=x(t).closest("fieldset")[0])&&(n=!o.disabled):n="a"===s&&t.href||e,n&&x(t).is(":visible")&&function(t){var e=t.css("visibility");for(;"inherit"===e;)t=t.parent(),e=t.css("visibility");return"visible"===e}(x(t)))},x.extend(x.expr.pseudos,{focusable:function(t){return x.ui.focusable(t,null!=x.attr(t,"tabindex"))}}),x.fn._form=function(){return"string"==typeof this[0].form?this.closest("form"):x(this[0].form)},
/*!
 * jQuery UI Form Reset Mixin 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.ui.formResetMixin={_formResetHandler:function(){var e=x(this);setTimeout(function(){var t=e.data("ui-form-reset-instances");x.each(t,function(){this.refresh()})})},_bindFormResetHandler:function(){var t;this.form=this.element._form(),this.form.length&&((t=this.form.data("ui-form-reset-instances")||[]).length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t))},_unbindFormResetHandler:function(){var t;this.form.length&&((t=this.form.data("ui-form-reset-instances")).splice(x.inArray(this,t),1),t.length?this.form.data("ui-form-reset-instances",t):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset"))}},x.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),
/*!
 * jQuery UI Support for jQuery core 1.8.x and newer 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 *
 */
x.expr.pseudos||(x.expr.pseudos=x.expr[":"]),x.uniqueSort||(x.uniqueSort=x.unique),x.escapeSelector||(e=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,i=function(t,e){return e?"\0"===t?"�":t.slice(0,-1)+"\\"+t.charCodeAt(t.length-1).toString(16)+" ":"\\"+t},x.escapeSelector=function(t){return(t+"").replace(e,i)}),x.fn.even&&x.fn.odd||x.fn.extend({even:function(){return this.filter(function(t){return t%2==0})},odd:function(){return this.filter(function(t){return t%2==1})}}),
/*!
 * jQuery UI Keycode 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},
/*!
 * jQuery UI Labels 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.fn.labels=function(){var t,e,i;return this.length?this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(e=this.eq(0).parents("label"),(t=this.attr("id"))&&(i=(i=this.eq(0).parents().last()).add((i.length?i:this).siblings()),t="label[for='"+x.escapeSelector(t)+"']",e=e.add(i.find(t).addBack(t))),this.pushStack(e)):this.pushStack([])},x.ui.plugin={add:function(t,e,i){var n,o=x.ui[t].prototype;for(n in i)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([e,i[n]])},call:function(t,e,i,n){var o,s=t.plugins[e];if(s&&(n||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(o=0;o<s.length;o++)t.options[s[o][0]]&&s[o][1].apply(t.element,i)}},
/*!
 * jQuery UI Position 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 *
 * https://api.jqueryui.com/position/
 */
W=Math.max,C=Math.abs,o=/left|center|right/,s=/top|center|bottom/,r=/[\+\-]\d+(\.[\d]+)?%?/,l=/^\w+/,a=/%$/,h=x.fn.position,x.position={scrollbarWidth:function(){var t,e,i;return void 0!==n?n:(i=(e=x("<div style='display:block;position:absolute;width:200px;height:200px;overflow:hidden;'><div style='height:300px;width:auto;'></div></div>")).children()[0],x("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),n=t-i)},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.width<t.element[0].scrollWidth;return{width:"scroll"===i||"auto"===i&&t.height<t.element[0].scrollHeight?x.position.scrollbarWidth():0,height:e?x.position.scrollbarWidth():0}},getWithinInfo:function(t){var e=x(t||window),i=N(e[0]),n=!!e[0]&&9===e[0].nodeType;return{element:e,isWindow:i,isDocument:n,offset:!i&&!n?x(t).offset():{left:0,top:0},scrollLeft:e.scrollLeft(),scrollTop:e.scrollTop(),width:e.outerWidth(),height:e.outerHeight()}}},x.fn.position=function(f){var c,d,p,g,m,v,y,w,b,_,t,e;return f&&f.of?(v="string"==typeof(f=x.extend({},f)).of?x(document).find(f.of):x(f.of),y=x.position.getWithinInfo(f.within),w=x.position.getScrollInfo(y),b=(f.collision||"flip").split(" "),_={},e=9===(e=(t=v)[0]).nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:N(e)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:e.preventDefault?{width:0,height:0,offset:{top:e.pageY,left:e.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()},v[0].preventDefault&&(f.at="left top"),d=e.width,p=e.height,m=x.extend({},g=e.offset),x.each(["my","at"],function(){var t,e,i=(f[this]||"").split(" ");(i=1===i.length?o.test(i[0])?i.concat(["center"]):s.test(i[0])?["center"].concat(i):["center","center"]:i)[0]=o.test(i[0])?i[0]:"center",i[1]=s.test(i[1])?i[1]:"center",t=r.exec(i[0]),e=r.exec(i[1]),_[this]=[t?t[0]:0,e?e[0]:0],f[this]=[l.exec(i[0])[0],l.exec(i[1])[0]]}),1===b.length&&(b[1]=b[0]),"right"===f.at[0]?m.left+=d:"center"===f.at[0]&&(m.left+=d/2),"bottom"===f.at[1]?m.top+=p:"center"===f.at[1]&&(m.top+=p/2),c=E(_.at,d,p),m.left+=c[0],m.top+=c[1],this.each(function(){var i,t,r=x(this),l=r.outerWidth(),a=r.outerHeight(),e=L(this,"marginLeft"),n=L(this,"marginTop"),o=l+e+L(this,"marginRight")+w.width,s=a+n+L(this,"marginBottom")+w.height,h=x.extend({},m),u=E(_.my,r.outerWidth(),r.outerHeight());"right"===f.my[0]?h.left-=l:"center"===f.my[0]&&(h.left-=l/2),"bottom"===f.my[1]?h.top-=a:"center"===f.my[1]&&(h.top-=a/2),h.left+=u[0],h.top+=u[1],i={marginLeft:e,marginTop:n},x.each(["left","top"],function(t,e){x.ui.position[b[t]]&&x.ui.position[b[t]][e](h,{targetWidth:d,targetHeight:p,elemWidth:l,elemHeight:a,collisionPosition:i,collisionWidth:o,collisionHeight:s,offset:[c[0]+u[0],c[1]+u[1]],my:f.my,at:f.at,within:y,elem:r})}),f.using&&(t=function(t){var e=g.left-h.left,i=e+d-l,n=g.top-h.top,o=n+p-a,s={target:{element:v,left:g.left,top:g.top,width:d,height:p},element:{element:r,left:h.left,top:h.top,width:l,height:a},horizontal:i<0?"left":0<e?"right":"center",vertical:o<0?"top":0<n?"bottom":"middle"};d<l&&C(e+i)<d&&(s.horizontal="center"),p<a&&C(n+o)<p&&(s.vertical="middle"),W(C(e),C(i))>W(C(n),C(o))?s.important="horizontal":s.important="vertical",f.using.call(this,t,s)}),r.offset(x.extend(h,{using:t}))})):h.apply(this,arguments)},x.ui.position={fit:{left:function(t,e){var i,n=e.within,o=n.isWindow?n.scrollLeft:n.offset.left,n=n.width,s=t.left-e.collisionPosition.marginLeft,r=o-s,l=s+e.collisionWidth-n-o;n<e.collisionWidth?0<r&&l<=0?(i=t.left+r+e.collisionWidth-n-o,t.left+=r-i):t.left=!(0<l&&r<=0)&&l<r?o+n-e.collisionWidth:o:0<r?t.left+=r:0<l?t.left-=l:t.left=W(t.left-s,t.left)},top:function(t,e){var i,n=e.within,n=n.isWindow?n.scrollTop:n.offset.top,o=e.within.height,s=t.top-e.collisionPosition.marginTop,r=n-s,l=s+e.collisionHeight-o-n;o<e.collisionHeight?0<r&&l<=0?(i=t.top+r+e.collisionHeight-o-n,t.top+=r-i):t.top=!(0<l&&r<=0)&&l<r?n+o-e.collisionHeight:n:0<r?t.top+=r:0<l?t.top-=l:t.top=W(t.top-s,t.top)}},flip:{left:function(t,e){var i=e.within,n=i.offset.left+i.scrollLeft,o=i.width,i=i.isWindow?i.scrollLeft:i.offset.left,s=t.left-e.collisionPosition.marginLeft,r=s-i,s=s+e.collisionWidth-o-i,l="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,a="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,h=-2*e.offset[0];r<0?((o=t.left+l+a+h+e.collisionWidth-o-n)<0||o<C(r))&&(t.left+=l+a+h):0<s&&(0<(n=t.left-e.collisionPosition.marginLeft+l+a+h-i)||C(n)<s)&&(t.left+=l+a+h)},top:function(t,e){var i=e.within,n=i.offset.top+i.scrollTop,o=i.height,i=i.isWindow?i.scrollTop:i.offset.top,s=t.top-e.collisionPosition.marginTop,r=s-i,s=s+e.collisionHeight-o-i,l="top"===e.my[1]?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,a="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,h=-2*e.offset[1];r<0?((o=t.top+l+a+h+e.collisionHeight-o-n)<0||o<C(r))&&(t.top+=l+a+h):0<s&&(0<(n=t.top-e.collisionPosition.marginTop+l+a+h-i)||C(n)<s)&&(t.top+=l+a+h)}},flipfit:{left:function(){x.ui.position.flip.left.apply(this,arguments),x.ui.position.fit.left.apply(this,arguments)},top:function(){x.ui.position.flip.top.apply(this,arguments),x.ui.position.fit.top.apply(this,arguments)}}},x.ui.safeActiveElement=function(e){var i;try{i=e.activeElement}catch(t){i=e.body}return i=(i=i||e.body).nodeName?i:e.body},x.ui.safeBlur=function(t){t&&"body"!==t.nodeName.toLowerCase()&&x(t).trigger("blur")},
/*!
 * jQuery UI Scroll Parent 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.fn.scrollParent=function(t){var e=this.css("position"),i="absolute"===e,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,t=this.parents().filter(function(){var t=x(this);return(!i||"static"!==t.css("position"))&&n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==e&&t.length?t:x(this[0].ownerDocument||document)},
/*!
 * jQuery UI Tabbable 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.extend(x.expr.pseudos,{tabbable:function(t){var e=x.attr(t,"tabindex"),i=null!=e;return(!i||0<=e)&&x.ui.focusable(t,i)}}),
/*!
 * jQuery UI Unique ID 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
x.fn.extend({uniqueId:(u=0,function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++u)})}),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&x(this).removeAttr("id")})}});
/*!
 * jQuery UI Widget 1.13.3
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */
var f,c=0,d=Array.prototype.hasOwnProperty,p=Array.prototype.slice;x.cleanData=(f=x.cleanData,function(t){for(var e,i,n=0;null!=(i=t[n]);n++)(e=x._data(i,"events"))&&e.remove&&x(i).triggerHandler("remove");f(t)}),x.widget=function(t,i,e){var n,o,s,r={},l=t.split(".")[0],a=l+"-"+(t=t.split(".")[1]);return e||(e=i,i=x.Widget),Array.isArray(e)&&(e=x.extend.apply(null,[{}].concat(e))),x.expr.pseudos[a.toLowerCase()]=function(t){return!!x.data(t,a)},x[l]=x[l]||{},n=x[l][t],o=x[l][t]=function(t,e){if(!this||!this._createWidget)return new o(t,e);arguments.length&&this._createWidget(t,e)},x.extend(o,n,{version:e.version,_proto:x.extend({},e),_childConstructors:[]}),(s=new i).options=x.widget.extend({},s.options),x.each(e,function(e,n){function o(){return i.prototype[e].apply(this,arguments)}function s(t){return i.prototype[e].apply(this,t)}r[e]="function"!=typeof n?n:function(){var t,e=this._super,i=this._superApply;return this._super=o,this._superApply=s,t=n.apply(this,arguments),this._super=e,this._superApply=i,t}}),o.prototype=x.widget.extend(s,{widgetEventPrefix:n&&s.widgetEventPrefix||t},r,{constructor:o,namespace:l,widgetName:t,widgetFullName:a}),n?(x.each(n._childConstructors,function(t,e){var i=e.prototype;x.widget(i.namespace+"."+i.widgetName,o,e._proto)}),delete n._childConstructors):i._childConstructors.push(o),x.widget.bridge(t,o),o},x.widget.extend=function(t){for(var e,i,n=p.call(arguments,1),o=0,s=n.length;o<s;o++)for(e in n[o])i=n[o][e],d.call(n[o],e)&&void 0!==i&&(x.isPlainObject(i)?t[e]=x.isPlainObject(t[e])?x.widget.extend({},t[e],i):x.widget.extend({},i):t[e]=i);return t},x.widget.bridge=function(s,e){var r=e.prototype.widgetFullName||s;x.fn[s]=function(i){var t="string"==typeof i,n=p.call(arguments,1),o=this;return t?this.length||"instance"!==i?this.each(function(){var t,e=x.data(this,r);return"instance"===i?(o=e,!1):e?"function"!=typeof e[i]||"_"===i.charAt(0)?x.error("no such method '"+i+"' for "+s+" widget instance"):(t=e[i].apply(e,n))!==e&&void 0!==t?(o=t&&t.jquery?o.pushStack(t.get()):t,!1):void 0:x.error("cannot call methods on "+s+" prior to initialization; attempted to call method '"+i+"'")}):o=void 0:(n.length&&(i=x.widget.extend.apply(null,[i].concat(n))),this.each(function(){var t=x.data(this,r);t?(t.option(i||{}),t._init&&t._init()):x.data(this,r,new e(i,this))})),o}},x.Widget=function(){},x.Widget._childConstructors=[],x.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=x(e||this.defaultElement||this)[0],this.element=x(e),this.uuid=c++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=x(),this.hoverable=x(),this.focusable=x(),this.classesElementLookup={},e!==this&&(x.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=x(e.style?e.ownerDocument:e.document||e),this.window=x(this.document[0].defaultView||this.document[0].parentWindow)),this.options=x.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:x.noop,_create:x.noop,_init:x.noop,destroy:function(){var i=this;this._destroy(),x.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:x.noop,widget:function(){return this.element},option:function(t,e){var i,n,o,s=t;if(0===arguments.length)return x.widget.extend({},this.options);if("string"==typeof t)if(s={},t=(i=t.split(".")).shift(),i.length){for(n=s[t]=x.widget.extend({},this.options[t]),o=0;o<i.length-1;o++)n[i[o]]=n[i[o]]||{},n=n[i[o]];if(t=i.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=e}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];s[t]=e}return this._setOptions(s),this},_setOptions:function(t){for(var e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(t){var e,i,n;for(e in t)n=this.classesElementLookup[e],t[e]!==this.options.classes[e]&&n&&n.length&&(i=x(n.get()),this._removeClass(n,e),i.addClass(this._classes({element:i,keys:e,classes:t,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(o){var s=[],r=this;function t(t,e){for(var i,n=0;n<t.length;n++)i=r.classesElementLookup[t[n]]||x(),i=o.add?(function(){var i=[];o.element.each(function(t,e){x.map(r.classesElementLookup,function(t){return t}).some(function(t){return t.is(e)})||i.push(e)}),r._on(x(i),{remove:"_untrackClassesElement"})}(),x(x.uniqueSort(i.get().concat(o.element.get())))):x(i.not(o.element).get()),r.classesElementLookup[t[n]]=i,s.push(t[n]),e&&o.classes[t[n]]&&s.push(o.classes[t[n]])}return(o=x.extend({element:this.element,classes:this.options.classes||{}},o)).keys&&t(o.keys.match(/\S+/g)||[],!0),o.extra&&t(o.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(i){var n=this;x.each(n.classesElementLookup,function(t,e){-1!==x.inArray(i.target,e)&&(n.classesElementLookup[t]=x(e.not(i.target).get()))}),this._off(x(i.target))},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,n){var o="string"==typeof t||null===t,e={extra:o?e:i,keys:o?t:e,element:o?this.element:t,add:n="boolean"==typeof n?n:i};return e.element.toggleClass(this._classes(e),n),this},_on:function(o,s,t){var r,l=this;"boolean"!=typeof o&&(t=s,s=o,o=!1),t?(s=r=x(s),this.bindings=this.bindings.add(s)):(t=s,s=this.element,r=this.widget()),x.each(t,function(t,e){function i(){if(o||!0!==l.options.disabled&&!x(this).hasClass("ui-state-disabled"))return("string"==typeof e?l[e]:e).apply(l,arguments)}"string"!=typeof e&&(i.guid=e.guid=e.guid||i.guid||x.guid++);var t=t.match(/^([\w:-]*)\s*(.*)$/),n=t[1]+l.eventNamespace,t=t[2];t?r.on(n,t,i):s.on(n,i)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.off(e),this.bindings=x(this.bindings.not(t).get()),this.focusable=x(this.focusable.not(t).get()),this.hoverable=x(this.hoverable.not(t).get())},_delay:function(t,e){var i=this;return setTimeout(function(){return("string"==typeof t?i[t]:t).apply(i,arguments)},e||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){this._addClass(x(t.currentTarget),null,"ui-state-hover")},mouseleave:function(t){this._removeClass(x(t.currentTarget),null,"ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){this._addClass(x(t.currentTarget),null,"ui-state-focus")},focusout:function(t){this._removeClass(x(t.currentTarget),null,"ui-state-focus")}})},_trigger:function(t,e,i){var n,o,s=this.options[t];if(i=i||{},(e=x.Event(e)).type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),e.target=this.element[0],o=e.originalEvent)for(n in o)n in e||(e[n]=o[n]);return this.element.trigger(e,i),!("function"==typeof s&&!1===s.apply(this.element[0],[e].concat(i))||e.isDefaultPrevented())}},x.each({show:"fadeIn",hide:"fadeOut"},function(s,r){x.Widget.prototype["_"+s]=function(e,t,i){var n,o=(t="string"==typeof t?{effect:t}:t)?!0!==t&&"number"!=typeof t&&t.effect||r:s;"number"==typeof(t=t||{})?t={duration:t}:!0===t&&(t={}),n=!x.isEmptyObject(t),t.complete=i,t.delay&&e.delay(t.delay),n&&x.effects&&x.effects.effect[o]?e[s](t):o!==s&&e[o]?e[o](t.duration,t.easing,i):e.queue(function(t){x(this)[s](),i&&i.call(e[0]),t()})}})});
// source --> https://motorodina.sk/wp-content/plugins/woocommerce/assets/js/jquery-cookie/jquery.cookie.min.js?ver=1.4.1-wc.10.7.0 
/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?e(require("jquery")):e(jQuery)}(function(e){var n=/\+/g;function o(e){return r.raw?e:encodeURIComponent(e)}function i(e,o){var i=r.raw?e:function(e){0===e.indexOf('"')&&(e=e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return e=decodeURIComponent(e.replace(n," ")),r.json?JSON.parse(e):e}catch(o){}}(e);return"function"==typeof o?o(i):i}var r=e.cookie=function(n,t,u){if(t!==undefined&&"function"!=typeof t){if("number"==typeof(u=e.extend({},r.defaults,u)).expires){var c=u.expires,f=u.expires=new Date;f.setTime(+f+864e5*c)}return document.cookie=[o(n),"=",function(e){return o(r.json?JSON.stringify(e):String(e))}(t),u.expires?"; expires="+u.expires.toUTCString():"",u.path?"; path="+u.path:"",u.domain?"; domain="+u.domain:"",u.secure?"; secure":""].join("")}for(var d,a=n?undefined:{},p=document.cookie?document.cookie.split("; "):[],s=0,m=p.length;s<m;s++){var x=p[s].split("="),y=(d=x.shift(),r.raw?d:decodeURIComponent(d)),k=x.join("=");if(n&&n===y){a=i(k,t);break}n||(k=i(k))===undefined||(a[y]=k)}return a};r.defaults={},e.removeCookie=function(n,o){return e.cookie(n)!==undefined&&(e.cookie(n,"",e.extend({},o,{expires:-1})),!e.cookie(n))}});
// source --> https://motorodina.sk/wp-content/plugins/ymm-search/view/frontend/web/main.js?ver=6.9.4 
( function ($) {
  "use strict";

  $.widget("pektsekye.ymm", { 
    
    rootCategoryIds: [],    
    selectedValues : [],
     
     
    _create : function () {

      $.extend(this, this.options);       

      this.garageContainer    = this.element.find('.ymm-garage');
      this.garageSelect       = this.element.find('.ymm-garage-select');        	
      this.extraContainer     = this.element.find('.ymm-extra');
      this.categoryContainer  = this.element.find('.ymm-category-container');    
      this.searchField        = this.element.find('.ymm-search-field');     
      this.searchAnySelButton = this.element.find('.ymm-submit-any-selection'); 
      
      
      this._on({ 
          "change .ymm-garage-select": $.proxy(this.preSelectDropdowns, this),        
          "click .ymm-remove-from-garage": $.proxy(this.garageRemove, this),      
          "change .ymm-select": $.proxy(this.loadLevel, this),
          "change .ymm-category-select": $.proxy(this.checkSubCategories, this),
          "submit form": $.proxy(this.submitSearch, this),                 
          "click button.ymm-submit-any-selection": $.proxy(this.submit, this),
          "click .ymm-clear-filter": $.proxy(this.clearFilter, this),  
          "click .ymm-search-all-link": $.proxy(this.searchAll, this)                                                                         
      }); 
      
      
      // reset drop-downs on browser's cached page
      var option = this.element.find('select.ymm-select option:selected:not(:first-child):not([selected])').eq(0);
      if (option.length){
        option.closest('select')[0].selectedIndex = 0;
        this.element.find('select.ymm-select:disabled').val('');
      }                           
    },
  
  
    preSelectDropdowns : function(e){
    
      var vehicle = $(e.target).val();
      
      if (vehicle){
      
        this.selectedValues = vehicle.split(',');
      
        if (!this.canShowExtra){
      
          this._submit(null, null, this.selectedValues);

        } else {

          var firstValue = this.selectedValues[0];
          var firstSelect = this.element.find('.ymm-select').first();
      
          var option;
          var valueChanged = false;
          
          var l = firstSelect[0].options.length;
          for (var i=0;i<l;i++){
            option = firstSelect[0].options[i];
            if (option.value == firstValue){
              option.selected = true;
              valueChanged = true;
              break;
            }  
          }
          
          if (valueChanged){
            this.loadLevel({target:firstSelect});
          } else {// remove not found values
            this.garageRemove();
          }
        }
      }
      
      this.garageSetSelected(vehicle);            
    },  
  
  
    garageSetSelected : function(vehicle){ 
      var cookie = Cookies.get(this.ymmCookieName);
      if (cookie){
        var selected = $.parseJSON(cookie);
        if (selected.vehicles && selected.vehicle != vehicle){
          selected.vehicle = vehicle;  
          Cookies.set(this.ymmCookieName, JSON.stringify(selected)); 
        }                
      }    
    },  
  
  
    garageAdd : function(vehicle){
    
      var selected = {vehicle:vehicle, vehicles:[vehicle]};
    
      var cookie = Cookies.get(this.ymmCookieName);
      if (cookie){
        var selectedOld;
        
      	try {
          selectedOld = $.parseJSON(cookie);                        		
        } catch (e){}
        
        if (selectedOld && selectedOld.vehicles && selectedOld.vehicles.length){ 
          selected.vehicles = selectedOld.vehicles;
          if (selectedOld.vehicles.indexOf(vehicle) == -1){
            if (selectedOld.vehicles.length > 9){ // limit garage to 10 values
              selected.vehicles.shift();
            }  
            selected.vehicles.push(vehicle);
            selected.vehicles.sort($.proxy(this.sortCaseIns, this));
          }
        }           
      }    
      
      Cookies.set(this.ymmCookieName, JSON.stringify(selected));         
    },  
  
  
    garageRemove : function(){
      var vehicle = this.garageSelect.val();
      if (vehicle == ''){
        return false;
      }  
      var cookie = Cookies.get(this.ymmCookieName);
      if (cookie){
        var selected = $.parseJSON(cookie);
        if (selected.vehicles){
          this.without(selected.vehicles, vehicle);
          if (selected.vehicle == vehicle){
            selected.vehicle = selected.vehicles[0] ? selected.vehicles[0] : '';
          }
          
          this.garageSelect[0].remove(this.garageSelect[0].selectedIndex);       
                
          Cookies.set(this.ymmCookieName, JSON.stringify(selected)); 
        }                
      }
      return false;    
    },


    clearFilter : function(){
      this.garageSetSelected('');
      return true;    
    },
    
    
    searchAll : function(){
    
      this.filterCategoryPage = 0;
      this.submitUrl = this.submitSearchUrl;
      this.canShowExtra = this.categorySearchEnabled || this.wordSearchEnabled;    
    
      var firstSelect = this.element.find('.ymm-select').first();
      
      this.disableLevels(firstSelect);
            
      firstSelect[0].length = 1;
        
      var l = this.firstLevelOptions.length;		  
      for (var i=0;i<l;i++){
        firstSelect[0].options[i+1] = new Option(this.firstLevelOptions[i], this.firstLevelOptions[i]);
      } 
      
      if (this.garageEnabled){          
        var cookie = Cookies.get(this.ymmCookieName);
        if (cookie){
          var selected = $.parseJSON(cookie);
          if (selected.vehicles){
            var vehicle;
            var l = selected.vehicles.length;		  
            for (var i=0;i<l;i++){
              vehicle = selected.vehicles[i];
              this.garageSelect[0].options[i+1] = new Option(vehicle.split(',').join(' '), vehicle);
            }
            if (selected.vehicle){
              this.garageSelect.val(selected.vehicle).change();
            }
            this.garageContainer.show();          
          }                
        }       
      }
      
      var titleSpan = this.element.find('.ymm-title span');
      if (titleSpan.length){
        titleSpan.text(this.searchTitle);        
      } else {
        this.element.closest('div.widget').find('span.widget-title').text(this.searchTitle);
      }
      this.element.find('span.ymm-garage-text').text(this.garageText);
      this.searchAnySelButton.prop('title', this.searchButtonText).text(this.searchButtonText);
      this.element.find('span.ymm-filter-links').hide();
      
      return false;    
    },
    
    
    loadLevel : function(e){

      var element = $(e.target);    
      var value = element.val();
 
      this.disableLevels(element);
      this.hideExtra();
            
      if (value != ''){
    
        var values = [];
        var selects = this.element.find('.ymm-select');
        selects.each(function() {
          values.push($(this).val());                
          if (this == element[0])
            return false;  
        });         
              
        var nextLevel = values.length;
                 
        if (selects.length == values.length){// last drop-down is selected 
          if (this.canShowExtra)
            this.showExtra(values);
          else  
            this.submit();     
        } else {
          var categoryId = this.filterCategoryPage ? this.categoryId : 0;
          var widget = this;
          $.ajax({
              type: 'GET',
              url: this.ajaxShortUrl ? this.ajaxShortUrl : this.ajaxUrl,
              async: true,
              data: {action:'ymm_selector_fetch', cId:categoryId, 'values[]':values},
              dataType: 'json'
          }).done(
              function (data) {
                if (!data.error){           
                  if (data.length == 0){//there are no values for the next drop-down
                    widget.submit();
                  } else {                
                    widget.enableLevel(element, data, nextLevel);
                  }
                }  
              }
            );
        }  
      
      }
    
    },
  
  
    enableLevel : function(element, options, level){
    
      if (this.isHorizontal)
        var select = $(element).closest('.level').next().find('.ymm-select');
      else  
        var select = $(element).next('.ymm-select');
    
      var l = options.length;		  
      for (var i=0;i<l;i++)
        select[0].options[i+1] = new Option(options[i], options[i]);
      
      select[0].disabled = false; 
      select.removeClass('disabled');  
      
      if (this.garageEnabled){
        var selectedValue = this.selectedValues[level];
        if (selectedValue){
        
          var option;
          var valueChanged = false;
          
          var l = select[0].options.length;
          for (var i=0;i<l;i++){
            option = select[0].options[i];
            if (option.value == selectedValue){
              option.selected = true;
              valueChanged = true;
              break;
            }  
          }
          
          if (valueChanged){
            this.loadLevel({target:select});
          } else {// remove not found values
            this.garageRemove();
          } 
                
          this.selectedValues[level] = '';
        }
      }         
    },


    disableLevels : function(element){
      var disable = false;
      this.element.find('.ymm-select').each(function() {
        if (disable){
          this.length = 1;
          this.disabled = true;
          $(this).addClass('disabled');          
        }                  
        if (this == element[0])
          disable = true;  
      });   
    }, 
      

    showExtra : function(values){ 
  
      this.hideExtra(); 
             
      if (this.lastLevelIsSelected()){
        
        this.rootCategoryIds = [];
        this.categories = {}; 
          
        if (this.categorySearchEnabled){
          var jqxhr = this.loadCategoryDropdowns(values);
          if (jqxhr){
            jqxhr.always($.proxy(function(){           
              if (this.rootCategoryIds.length > 0){
                this.addCategorySelect(this.rootCategoryIds);
                if (this.wordSearchEnabled){
                  this.extraContainer.addClass('or-search');                  
                }                  
              }                
              this.extraContainer.show();
              if (this.wordSearchEnabled){              
                this.searchAnySelButton.hide();
              }                     
            },this));
          }       
        } else {
          this.extraContainer.show();
          if (this.wordSearchEnabled){          
            this.searchAnySelButton.hide();
          }
        }
            
      }	  
    },


    hideExtra : function(){
  
      if (this.categorySearchEnabled || this.wordSearchEnabled){
      
        this.extraContainer.hide();
      
        if (this.categorySearchEnabled)   
          this.removeSubCategories();
          
        if (this.wordSearchEnabled){
          this.extraContainer.removeClass('or-search');                  
          this.searchField.val('');         
        }                      
      }
         
      this.searchAnySelButton.show(); 
    },


    removeSubCategories : function(element){
           
      var isHorisontal = this.isHorizontal;            
           
      var startRemove = element == undefined ? true : false;
      this.element.find('.ymm-category-select').each(function() {
        if (startRemove){
          if (isHorisontal)
            $(this).closest('.level').remove();
          else
            $(this).remove();
        }                 
        if (!startRemove && this == element[0])
          startRemove = true;  
      });     
    },
 
 
    loadCategoryDropdowns : function(values){    
      var widget = this;
      var jqxhr = $.ajax({
          type: 'GET',
          url: this.ajaxShortUrl ? this.ajaxShortUrl : this.ajaxUrl,
          async: true,
          data: {action:'ymm_selector_get_categories', 'values[]':values},
          dataType: 'json'
      }).done(
          function (data) {
            if (!data.error && data.rootCategoryIds){            
              $.extend(widget, data);                         
            }  
          }
        );
        
      return jqxhr;              
    },

     
    addCategorySelect : function(categoryIds){
    
      var selectHtml = '<select class="ymm-category-select"></select>';

      if (this.isHorizontal){  
        selectHtml = '<div class="level">' +selectHtml+ '</div>';
        this.categoryContainer.find('.ymm-clear').before(selectHtml); 
      } else {
        this.categoryContainer.append(selectHtml);
      }     
         
      var select = this.element.find('.ymm-category-select').last();
      
      select[0].options[0] = new Option(this.categoryDefOptionTitle, '');
      
      var cId;  
      var l = categoryIds.length;		  
      for (var i=0;i<l;i++){
        cId = categoryIds[i];
        select[0].options[i+1] = new Option(this.categories[cId].title, cId);
      }    
    
    },


    checkSubCategories : function(e){
      var element = $(e.target)

      this.removeSubCategories(element);

      var cId = element.val();
      if (cId != ''){     
        if (this.categories[cId].children){
          this.addCategorySelect(this.categories[cId].children);
        } else {
          this.submitCategory(cId);
        }
      }        
    },  
      
      
    getLastSelectedCategory : function(){
    
      var categoryId = null;
      
      var widget = this;
      this.element.find('.ymm-category-select').each(function() {
        var cId = $(this).val();
        if (cId && widget.categories[cId].url){
          categoryId = cId;
        }   
      });
      
      return categoryId;
    },
    
          
    submit : function(){

      if (!this.firstLevelIsSelected()){
        return;
      }
      
      if (this.rootCategoryIds.length > 0){
        var categoryId = this.getLastSelectedCategory();
        if (categoryId){
          this.submitCategory(categoryId);
          return;
        }
      }        
        
      this._submit();
    },

    
    submitCategory : function(categoryId){
    
      var categoryUrl = this.categories[categoryId].url;

      this._submit(null, categoryUrl);
    },


    submitSearch : function(){

      var searchWord = this.searchField.val();         

      if (searchWord == '' && this.rootCategoryIds.length > 0){
        var categoryId = this.getLastSelectedCategory();
        if (categoryId){
          this.submitCategory(categoryId);
          return false;
        }
      }      
      
      this._submit(searchWord);    

      return false;
    },


    _submit : function(searchWord, categoryUrl, garageValues){

      if (!garageValues){
        if (this.lastLevelIsSelected()){
          var values = [];
          this.element.find('.ymm-select').each(function() {
            values.push($(this).val());                  
          });     
          this.garageAdd(values.join(','));
        } else {
          this.garageSetSelected('');
        }
      }
      
      var searchWord = searchWord ? searchWord : '';
      
      var params = (this.isCategoryPage && this.filterCategoryPage) || categoryUrl ? {} : {s:searchWord, ymm_search:1, post_type:'product'};
      
      var values = garageValues ? this.getValuesAsParams(garageValues) : this.getLevelValuesAsParams();
      $.extend(params, values);  
    
      var url = categoryUrl ? categoryUrl : this.submitUrl;
      
      if (url == ''){
        var currentUrl = window.location.href;
        if (currentUrl.indexOf('/page/') != -1){
          url = currentUrl.replace(/\/page\/\d+\//,'/').replace(/\?.*/, '');
        }  
      }
            
      window.location.href = url + '?' + $.param(params);
    },
    

    getLevelValuesAsParams : function(){  
  
      var params = {};
      var pNames = this.levelParameterNames;
      this.element.find('.ymm-select').each(function(i) {
        var v = $(this).val();
        if (v){
          params[pNames[i]] = v;
        }   
      });     
      
      return params;  	  
    },


    getValuesAsParams : function(garageValues){  
  
      var params = {};     
      var pNames = this.levelParameterNames;
      var l = garageValues.length;
      for (var i=0;i<l;i++) {
        params[pNames[i]] = garageValues[i];   
      }     
      
      return params;  	  
    },
    
    
    firstLevelIsSelected : function(){
      return this.element.find('.ymm-select').first().val() != '';
    },
    
   
    lastLevelIsSelected : function(){
      return this.element.find('.ymm-select').last().val() != '';
    },
    
    
    without : function(a, v){
      var i = a.indexOf(v);
      if (i != -1)
        a.splice(i, 1);
    },
    
    
    sortCaseIns : function(a, b){
      a = a.toLowerCase();
      b = b.toLowerCase();
      if (a == b) return 0;
      if (a > b) return 1;
    }	                  
    
            
  });
  
})(jQuery);