jQuery(document).ready(function($){
var mq = window.matchMedia( "(max-width: 991px)" ); //usage - if(mq.matches){}
    var mobile = window.matchMedia( "(max-width: 767px)" )

    jQuery(".text-check .a-tag-woo").click(function(e){
        e.preventDefault();
            jQuery("#cup-container .checkout_coupon").fadeIn(); 
            jQuery(".text-check").hide();    
    });

  jQuery('.forside_slider').slick({
      dots: false,
      arrows: false,
      infinite: true,
      autoplay: true,
      speed: 800,
      slidesToShow: 1,
      slidesToScroll: 1, 
      prevArrow: '<div class="work-prev oc-left"><i class="fa fa-angle-left"></i></div>',
      nextArrow: '<div class="work-next oc-right"><i class="fa fa-angle-right"></i></div>',
       responsive: [
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1,
        infinite: true,
        dots: false
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1,
         dots: false
      }
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1,
        dots: false
      }
    }
    // You can unslick at a given breakpoint now by adding:
    // settings: "unslick"
    // instead of a settings object
  ]
  });
	if(jQuery('.video').length){
		jQuery('.video').magnificPopup({
		  type: 'iframe'
		});		
	}
	
	
	wrapper_padding();

    $(window).resize(function() {
        wrapper_padding();
    });
	
	/*var stickyTop = jQuery('.sticky').offset().top;
	var header_height = jQuery('.desktop-menu').height();
	var sticky_width = jQuery('.sticky').width();
	stickyTop = stickyTop - header_height;
	console.log(stickyTop);
	jQuery(window).scroll(function () { // scroll event
	// console.log(topSpace);
		var windowTop = jQuery(window).scrollTop(); // returns number
		 if (stickyTop > windowTop) {
			jQuery('.sticky').css({position: 'fixed'});
			jQuery('.sticky').width(sticky_width);
		} 
	});*/



  // Hero slider slick
  if($('.hero-slider').length){
      $('.hero-slider__slider').slick({
          infinite: true, 
          slidesToShow: 1,
          slidesToScroll: 1,
          dots: true, 
          autoplay: true, 
          autoplaySpeed: 5000, 
          fade: true, 
          //adaptiveHeight: true,
          cssEase: 'linear',
          responsive: [
          {
            breakpoint: 991,
            settings: {
              appendDots:'.mob-dots', 
            }
          },
        ]
      });

      if(mq.matches){
        $('.hero-slider__slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
                // console.log(currentSlide);
                // console.log(slick.$dots[currentSlide]);
                $(slick.$dots[currentSlide]).find('li:nth-child(' +(currentSlide+1)+ ')').addClass('slick-active');
                // $('')
          });
      }

  }
	
  // Brands module
    if($('.brands-module').length){
      var brands_length = $('.brand-list li').length;
      var mob_brands_length = $('.mob-brand-list .wrapper').length;
      $('.brand-list').slick({
          infinite: true, 
          slidesToShow: 9,
          slidesToScroll: 1,
          dots: false,
          arrows: false, 
          autoplay: true, 
          autoplaySpeed: 5000, 
          cssEase: 'linear',
          responsive: [
          {
            breakpoint: 1600,
            settings: {
              slidesToShow : 7,
            }
          },
          {
            breakpoint: 1025,
            settings: {
              slidesToShow : 6,
            }
          },
           {
            breakpoint: 480,
            settings: {
              slidesToShow : 4,
            }
          },
        ]
      });

      $('.mob-brand-list').slick({
          infinite: true, 
          slidesToShow: 1,
          slidesToScroll: 1,
          dots: false,
          arrows: false, 
          autoplay: false, 
          cssEase: 'linear',
      });

      if(window.matchMedia( "(min-width: 1601px)" ).matches){
        if(brands_length <= 9){
          $('.brand-list').slick('unslick');
          $('.brand-list').addClass('no-slick');
        }
      }
      else if(window.matchMedia( "(min-width: 1025px) and (max-width: 1600px)" ).matches){
       if(brands_length <= 7){
          $('.brand-list').slick('unslick');
          $('.brand-list').addClass('no-slick');
        } 
      }
      else if(window.matchMedia( "(min-width: 1024px) and (max-width: 1190px)" ).matches){
       if(brands_length <= 6){
          $('.brand-list').slick('unslick');
          $('.brand-list').addClass('no-slick');
        } 
      }
      else if(window.matchMedia( "(max-width: 991px)" ).matches){
       if(mob_brands_length <= 1){
          $('.mob-brand-list').slick('unslick');
          $('.mob-brand-list').addClass('no-slick');
        } 
      }

  }

// Blog slider frontpage module
   if($('.blogg_seksjon').length){
      // var brands_length = $('.brand-list li').length;
      // var mob_brands_length = $('.mob-brand-list .wrapper').length;
      var $status = $('.slider-status');
      var $slickElement = $('.blogg_seksjon__wrapper');

      $slickElement.on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
        //currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
        var i = (currentSlide ? currentSlide : 0) + 1;
        var binary = '0';
        if((i >=10) || (slick.slideCount >=10)){
          binary = '';
        }
        $status.html('<span class="current">'+binary+i+'</span>' + '<span class="separator">/</span>' + '<span class="total">'+binary+slick.slideCount+'</span>');
      });


      $slickElement.slick({
          infinite: false, 
          slidesToShow: 2,
          slidesToScroll: 1,
          dots: false,
          arrows: true, 
          cssEase: 'linear',
          responsive: [
          {
            breakpoint: 991,
            settings: {
              slidesToShow : 2,
            }
          },
          {
            breakpoint: 600,
            settings: {
              slidesToShow : 1,
            }
          },
        ]
      });
    }


  function calc_outer_width(){
    if(window.matchMedia( "(min-width: 1601px)" ).matches){
       var container_width = $('.container').outerWidth();
       var element = container_width - 15;
    }
    else{
      var element = $(window).width() - 30;
    }
     width = $(window).width() 
     $before_divide = width - element;
     $final_value = $before_divide / 2;
     //console.log( $final_value);
     $('.blogg_seksjon').css('padding-left', $final_value);

        // if($(window).width() >= 1800) {
        //  $('.hero-banner.wysiwyg .hero-banner__content').css('left', $final_value - 26); 
        // } else if($(window).width() >= 1024) { 
        //     $('.hero-banner.wysiwyg .hero-banner__content').css('left', $final_value);  
        // }
    } 
    if(!mq.matches){
      calc_outer_width();
    }

    $(window).on('resize', function(e) {
        if(!mq.matches){
          calc_outer_width();
        }
     });
        
    jQuery('#login_modal, #forgot_pwd_modal').on('shown.bs.modal', function () {
        jQuery('.email_input').focus();
    })
	
	/* Login Begins */
    jQuery(document).on('submit', '#login_modal #submitbtn', function (e) {
		e.preventDefault();
        var emailLogIn = jQuery("#login_modal .email_input").val();
        var passwordLogIn = jQuery("#login_modal .password_input").val();
		var rememberme_bx = jQuery("#login_modal .rememberme").is(':checked');
        if (!(isEmail(emailLogIn))) {
            jQuery("#login_modal .validation-result .msg").html("E-post adressen er ugyldig.");
        } else if (passwordLogIn.length < 3) {
            jQuery("#login_modal .validation-result .msg").html("Passordet må ha minst 3 karakterer.");
        } else {
            jQuery("#login_modal .validation-result .msg").empty();

            jQuery.ajax({
                type: "post",
                dataType: "json",
                url: myAjax.ajaxurl,
                data: {action: "krefting_logIn", email: emailLogIn, password: passwordLogIn, rememberme: rememberme_bx},
                success: function (response) {
                    if (response.type == "success") {
                        jQuery("#login_modal .validation-result .msg").html(response.message);
                    } else {
                        jQuery("#login_modal .validation-result .msg").html(response.message);
                    }
                }
            });

        }

    });
    /* Login Begins Ends*/

    /* Glempt Password */
    jQuery(document).on('click', '#forgot_pwd_modal .submit_button', function () {
        var emailLogIn = jQuery("#forgot_pwd_modal .email_input").val();
        if (!(isEmail(emailLogIn))) {
            jQuery("#forgot_pwd_modal .validation-result .msg").html("E-post adressen er ugyldig.");
        } else {
            jQuery("#forgot_pwd_modal .validation-result .msg").empty();

            jQuery.ajax({
                type: "post",
                dataType: "json",
                url: myAjax.ajaxurl,
                data: {action: "custom_reset_password", email: emailLogIn},
                success: function (response) {
                    if (response.type == 1) {
                        jQuery("#forgot_pwd_modal .validation-result .msg").html(response.msg);
                    } else {
                        jQuery("#forgot_pwd_modal .validation-result .msg").html(response.msg);
                    }
                }
            });

        }

    });
    /* Glempt Password Ends */

    /* Signup user */
    jQuery(document).on('click', '#register_user_modal .submit_button', function () {

        var i_email = jQuery("#register_user_modal .email_input").val();
        var i_password = jQuery("#register_user_modal .password_input").val();
        var i_kundeforhold = jQuery('input[name=kundeforhold]:checked').val();
        var validation = true;

        if (!isEmail(i_email)) {
            jQuery("#register_user_modal .validation-result.error_email_input .msg").html("Postadresse er ugyldig.");

            validation = false;
        } else if (i_password.length < 3) {
            jQuery("#register_user_modal .validation-result.error_password_input .msg").html("Passordet må ha minst 3 karakterer.");

            validation = false;
        }



        if (validation) {
            jQuery("#register_user_modal .validation-result .msg").empty();
            jQuery.ajax({
                type: "post",
                dataType: "json",
                url: myAjax.ajaxurl,
                data: {action: "register_user", email: i_email, password: i_password,kundeforhold: i_kundeforhold},
                success: function (response) {
                    if (response.type == "success") {
                        jQuery("#register_user_modal .validation-result .msg").empty();
                        jQuery("#register_user_modal .validation-result.overall  .msg").html(response.message);
                    } else {
                        jQuery("#register_user_modal .validation-result.overall  .msg").html(response.message);
                    }
                }
            });
        }

    });
	
  if(mq.matches){
    // Mobil Menu Drilldown
    $('#drilldown-menu').slinky({
        resize: true, // auto resize height
        speed: 300, // animation speed
        theme: 'slinky-theme-default', // theme CSS
        title: true // shows title of sub menu
    });

    // Custom Slinky Menu 
      slinky();
    

  }

  // $('#drilldown-menu-1').slinky({
  //       resize: true, // auto resize height
  //       speed: 300, // animation speed
  //       theme: 'slinky-theme-default', // theme CSS
  //       title: true // shows title of sub menu
  //   });
	
	jQuery(document).click(function (e){
		if($('#main_menu_wrap').hasClass('open')){
			var container = $(".main_menu_wrap_inner .navbar-nav,.main_menu_wrap_inner .navbar-nav > li,.slideout-menu-toggle");

			if (!container.is(e.target) // if the target of the click isn't the container...
				&& container.has(e.target).length === 0) // ... nor a descendant of the container
			{
				$('#main_menu_wrap').removeClass("open");
				$('#overlay').removeClass("opacity");
        $('#nav-icon').removeClass('active');
			}
		}
	});
	
  if(!mq.matches){

  	jQuery('.slideout-menu-toggle').on('click', function(event){
      	event.preventDefault();
      	// create menu variables
          menu_height();

        $('#nav-icon').toggleClass('active');
  		
      	var slideoutMenu = $('#main_menu_wrap');
  		
      	//var slideoutMenuWidth = $('.slideout-menu').width();
      	
      	// toggle open class
      	slideoutMenu.toggleClass("open");

  		  jQuery('#overlay').toggleClass('opacity');
      	

      });

      $('.slideout-menu-toggle').on('mouseenter', function(event){
        setTimeout(function(){
                menu_height();
            }, 10);
      });



  	
  	jQuery('#menu-main-menu > li').on('mouseenter',function(){
  		$('#menu-main-menu > li').removeClass('active');
  		$(this).addClass('active');
  	});

    $('#menu-produkt-meny > li').on('mouseenter',function(){
      $('#menu-produkt-meny > li').removeClass('active');
      $(this).addClass('active');
    });

    $('#menu-produkt-meny > li').on('mouseleave',function(){
      $(this).removeClass('active');
    });

    $('#menu-produkt-meny > li > .sub-menu > li').on('mouseenter',function(){
      $('#menu-produkt-meny > li > .sub-menu > li').removeClass('active');
      $(this).addClass('active');
    });

    $('#menu-produkt-meny > li > .sub-menu > li').on('mouseleave',function(){
      $(this).removeClass('active');
    });
}
else{

  $('.navbar-toggle').on('click', function(event){
    $('.menu-wrapper_mobile').addClass('active');
    $('body,html').addClass('freeze');
  });

  $('.menu-header .close').on('click', function(event){
    $('.menu-wrapper_mobile').removeClass('active');
    $('body,html').removeClass('freeze');
  });

}

   jQuery(document).on('click', '.plus_wl, .minus_wl', function () {
    
     var $qty = jQuery(this).closest('.quantity').find('.qty'),
             currentVal = parseFloat($qty.val()),
             max = parseFloat($qty.attr('max')),
             min = $qty.attr('min'),
             step = $qty.attr('step');

     // Format values
     if (!currentVal || currentVal === '' || currentVal === 'NaN')
         currentVal = 0;
     if (max === '' || max === 'NaN')
         max = '';
     if (min === '' || min === 'NaN')
         min = 1;
     if (step === 'any' || step === '' || step === undefined || parseFloat(step) === 'NaN')
         step = 1;

     // Change the value
     if (jQuery(this).is('.plus_wl')) {

         if (max && ((currentVal + parseFloat(step)) >= max)) {
             $qty.val(currentVal);
         } else {
             $qty.val(currentVal + parseFloat(step));
         }

     } else {

         if (min && (min == currentVal || (currentVal - parseFloat(step)) < min)) {
             $qty.val(currentVal);
         } else if (currentVal > 0) {
             $qty.val(currentVal - parseFloat(step));
         }
      
     }
             
   });
        
    // jQuery('#checkall').trigger("click");  
    jQuery(document).on("click",".update_qty",function(){  
         post_data = jQuery('#wl-items-form').serialize();
         jQuery.ajax({
             type: "post",
             dataType: "json",
             url: myAjax.ajaxurl,
             data: {action: "update_wishlist_qty_cart", list_data: post_data},
             success: function (resp) {

             },
             error: function (resp) {
             }
         });
    });
//
   jQuery('.wishlist_add_prdt_cart_btn').click(function(e){
      e.preventDefault();
      jQuery('#checkall').trigger('click');
      jQuery('#wleditaction1').val('add-to-cart');
      jQuery('#wl-items-form').submit();
   });
  
//   jQuery(document).on("change","#tab-wl-items .qty",function(){
//      console.log("sdsdsds");
//      var parent = jQuery(this).parents().find().closest('.cart_table_item');
//      console.log(parent);
//      
//   });


    
    //blog archive function
    
    //filter blog archive post by term ids
    $("input[name='blog_terms']").on('change', function(){
                 
        if($(this).val() == 0){
            $("[name='blog_terms']").prop("checked",false);
            $(this).prop("checked",true);
        }else{
            $("[name='blog_terms'][value='0']").prop("checked",false);
           
            var selected = $(this).val();
            if($(this).is(":checked")){
                $("[name='blog_terms'][value='" + selected + "']").prop("checked",true);
            }else{
                $("[name='blog_terms'][value='" + selected + "']").prop("checked",false);
            }
        }

        //pass values selected
        var option_checked = [];
        $.each($("[name='blog_terms']:checked"),function(){
            var value = $(this).val();
            if($.inArray(value, option_checked) == -1){
                option_checked.push($(this).val());
            }              
        });

        //select all if no option is selected
        if(option_checked.length == 0 ){{
            $("input[name='blog_terms'][value='0']").prop("checked",true);
        }}

        $('#page_no').val(2);
        $('input[name=load_more]').data('total_pages', 1).prop('disabled', false);

        var data_json = [];
        data_json['category'] = option_checked.join(',');
        data_json['page_no'] = $('#page_no').val();

        parseUrlParams ( data_json );

        //ajax
        $.ajax({
            url: myAjax.ajaxurl,
            dataType: "json",
            type: "POST",
            data: {
                "action": "get_blogg_posts_by_term",
                "option_checked": option_checked
            },
            success:function(data){      
                $("html, body").animate({ scrollTop: 0 } , 1000);                
                $("#bloggarkiv-wrapper").html(data.blogg_post);
                
                $('input[name=load_more]').data('total_pages', data.total_pages);
            }
        });
    });


    //on scroll load blogg post
    $(window).scroll(function() {
       var top_pos = parseInt($(window).scrollTop()) + parseInt($(window).height());
       var window_ht = parseInt($(window).height());
    

      //  console.log($(window).scrollTop(), ($(document).height() - $("#footer").height() - 500));
        if( $('#bloggarkiv-wrapper').length ) {  
            if( top_pos >= (parseInt($('#bloggarkiv-wrapper').offset().top) + parseInt($('#bloggarkiv-wrapper').height()) -  (window_ht/8)) ) {             
                $('input[name=load_more]').click().prop('disabled', true);
            }  
        }
    });

    //load more
    $('input[name=load_more]').click(function (e) {
        if(!$(this).prop('disabled')) {
            var page_no = $('#page_no').val();

            page_no++;
           // console.log(page_no);

            if(page_no <= parseInt($(this).data('total_pages'))) {
                $('#page_no').val(page_no);    
                filter_post_by_term(e, true);
            }
        }
    });
    //blog archive function --

    // adjustWSRow();
    // $(window).resize(function(){
    //     adjustWSRow();
    // });

    var temp = setInterval(function(){
        if($("span.algolia-autocomplete").length) {
            $("span.algolia-autocomplete").each(function(i){
                $(this).addClass("algolia-autocomplete-"+i);
            });

            clearInterval(temp);
        }
    }, 100);

    if( $(window).width() > 991 ) {
        $(document).on("DOMSubtreeModified", '.algolia-autocomplete-0', function(){
            if($(this).css("display") == "block") {
                $("body").addClass("overflow_none");

                $("body, .site-nav").css({
                    "padding-right": $.scrollBarWidth(),
                });
            } else {
                $("body").removeClass("overflow_none");
                $("body, .site-nav").css({
                    "padding-right": "",
                });
            }
        });
    } else {

        $(document).on("DOMSubtreeModified", '.algolia-autocomplete-1', function(){
            if($(this).css("display") == "block") {
                $.lockBody();

                $.validate_dataset();
            } else {
                $.unlockBody();
            }
        });
    }

    $(document).keyup(".search_input", function(){
        if( $(window).width() < 992 ) {
            setTimeout(function(){
                if($('.algolia-autocomplete-1').css("display") == "block") {
                    $.lockBody();

                    $.validate_dataset();
                } else {
                    $.unlockBody();
                }
            }, 500)
        }
    });

    $.validate_dataset = function() {
        $(".aa-dataset-2, .aa-dataset-3, .aa-dataset-4, .aa-dataset-5, .aa-dataset-6, .aa-dataset-7").removeClass("hidden");
        for (var i = 2; i <= 7; i++) {
            if( $(".aa-dataset-"+i).length ) {
                if(!$(".aa-dataset-"+i).html()) {
                    $(".aa-dataset-"+i).addClass("hidden");
                }
            }
        }
    }

    $.scrollBarWidth = function() {
        var scrollDiv = document.createElement('div')
        scrollDiv.className = 'modal-scrollbar-measure'
        $(document.body).append(scrollDiv)
        var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
        $(document.body)[0].removeChild(scrollDiv)
        return scrollbarWidth;
    }
        

    // prevent body scroll
    var $docEl = $('html, body'),
        $wrap = $('.site_wrapper'),
        $scrollTop;

    $.lockBody = function() {
        if(window.pageYOffset) {
            $scrollTop = window.pageYOffset;
            $wrap.css({
                top: - ($scrollTop)
            });
        }
        $docEl.css({
            height: "100%",
            overflow: "hidden"
        });
    }

    $.unlockBody = function() {
        $docEl.css({
            height: "",
            overflow: ""
        });
        $wrap.css({
            top: ''
        });
        window.scrollTo(0, $scrollTop);
        window.setTimeout(function () {
            $scrollTop = null;
        }, 0);
    }
});

function adjustWSRow() {
    if( jQuery("tr.cart_table_item").length && jQuery("tr.wishlist_action_row").length ) {
        var w = 0;

        jQuery("tr.cart_table_item td").each(function(){
            w += jQuery(this).innerWidth();
        });

        jQuery("tr.wishlist_action_row").css("width", w);
    }
}

function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

 var windowWidth;
 jQuery(document).ready(function ($) {
	 windowWidth = jQuery(window).width();
	 if (windowWidth < 1025) {
		jQuery(document).on('click', '.navbar-nav li.menu-item-has-children > a', function (event) {
            event.preventDefault();
        });
        
       
    
		jQuery(document).on('click', '.navbar-nav li.menu-item-has-children:not(.opened)', function (e) {
            jQuery(this).siblings('li.menu-item-has-children').removeClass('opened');
            jQuery(this).addClass('opened');
			e.stopPropagation();
        });

        jQuery(document).on('click', '.navbar-nav li.menu-item-has-children.opened', function (e) {
            jQuery(this).removeClass('opened');
			e.stopPropagation();
        });
    }
    
     var sum_height = $('.summary').outerHeight();
    if (windowWidth > 767) {
        console.log(sum_height);
        if(sum_height < 460){
        //$('.summary').css('min-height','460px');
        }
        if(sum_height > 460){

            $('.single-product.woocommerce .single_thumb_wrap .item-img').css('height', sum_height+'px');
        }
    }
    
//	jQuery(document).on("keyup", ".live_search_box .search_input", function () {
//        var obj=jQuery(this);
//        var keyword = jQuery(this).val();
//        if (keyword != "") {
//            jQuery(this).next('#searchsubmit').prop('disabled', false);
//            live_search_js(keyword,obj);
//        } else {
//            jQuery(this).next('#searchsubmit').prop('disabled', true);
//            jQuery(".live_search_box .live_search_results").html('');
//        }
//    });
//
//    jQuery(document).on("focus", ".live_search_box .search_input", function () {
//        jQuery('#overlay').addClass('opacity');
//        var keyword = jQuery(this).val();
//            var obj=jQuery(this);
//        if (keyword != "") {
//            live_search_js(keyword,obj);
//        } else {
//            jQuery(this).next('#searchsubmit').prop('disabled', true);
//            jQuery(".live_search_box .live_search_results").html('');
//        }
//        obj.parent().siblings('.live_search_results').fadeIn();
//        //jQuery(".live_search_box .live_search_results").fadeIn();
//    });
//
//    jQuery(document).on("focusout", ".live_search_box .search_input", function () {
//        jQuery('#overlay').removeClass('opacity');
//        jQuery(".live_search_box .live_search_results").fadeOut();
//    });

    
    $(document).on('click', '.show-shipping-fields',function(e){
        e.preventDefault();
        $('.woocommerce-shipping-fields').show();
        $('.shipping_wrap').hide();
    });
    $(document).on('click', '.close-shipping-form',function(e){
        e.preventDefault();
        $('.woocommerce-shipping-fields').hide();
        var value = $('#shipping_company').val() + '<br/>'+$('#shipping_first_name').val() + ' ' + $('#shipping_last_name').val();
        value += '<br/>'+$('#shipping_address_1').val() + '<br/>'+$('#shipping_address_2').val();
        value += '<br/>'+$('#shipping_postcode').val() + ' '+$('#shipping_city').val();
        $('.shipping_wrap .shipping_wrap_summary').html(value);
        $('.shipping_wrap').show();
    });
});

function live_search_js(search_text,obj) {

    if (search_text.length >= 3) {

        jQuery.ajax({
            type: "post",
            dataType: "json",
            url: myAjax.ajaxurl,
            data: {action: "live_search", search_keyword: search_text},
            success: function (response) {
                obj.parent().siblings('.live_search_results').html(response.code);
            }
        });

    } else {
                obj.parent().siblings('.live_search_results').html();
    }

}

function wrapper_padding() {
	if (jQuery(window).width() > 992) {
		var header_height = jQuery('.desktop-menu').height();
		jQuery('.site_wrapper').css('padding-top', header_height);
	}
	else{
		var header_height = jQuery('.responsive-menu').height();
		jQuery('.site_wrapper').css('padding-top', header_height);
	}
	
}

jQuery(document).on('click', '.hide-filter, .vis_resultat_btn', function () {
    jQuery('.filtered_category').toggle('display');
    jQuery('.toggle_filter_resp').toggle('display');
    jQuery('.vis_resultat_btn').fadeToggle(300);
    jQuery('.hide-filter').find("span").toggle();
});

jQuery(document).on('added_to_cart', function (e,fragments,hash,button) {
    
    var slideoutpopup = $('.custom-popup');
    var id = button.data('product_id');
    $.ajax({
            url: myAjax.ajaxurl,
            method: 'post',
            data: { 
                    action: 'add_to_cart_archive',
                    id: id,
            }
    }).done( function (response) {
              if( response.error != 'undefined' && response.error ){
                    return true;
              } else {
                    response = jQuery.parseJSON(response);
                    jQuery('.cart-header').find('.sub-total-value').html(response.header_cart);
                    jQuery('.header-free-shipping').html(response.header_shipping);
                    jQuery('html,body').addClass("no_overflow");
                    jQuery('.custom-popup').html(response.html);

                    slideoutpopup.animate({
                            right: "0px"
                    });

              }
    });
});

jQuery(document).on('click','.top-header-popup .fa, .close-section', function(event){
        var slideoutpopup = jQuery('.custom-popup');
        slideoutpopup.removeClass("open");
        jQuery('html,body').removeClass("no_overflow");
        slideoutpopup.animate({
                right: "-700px"
        });
});

jQuery(document).ready(function ($) {	
	windowWidth = jQuery(window).width();
    stickywidth = jQuery('.sticky_sb').width();
    stickyheight = jQuery('.sticky_sb').height();
    
    if(jQuery('.sticky-wrap').length) {
        jQuery('.sticky-wrap').css('min-height',stickyheight + 'px');
    }
	calculation();
	calculation_one();
	
    var attr_selected;
    var tax_selected;
    var attr_names = {};
    jQuery('.custom_filter input').change(function () {
        jQuery('body').addClass('content_loading');
        if(jQuery('body').hasClass('search')){
          search = $("input[name='search-val'").val();

          if(!search){
            search = '';
          }
          loadAlgoliaPosts(search, 1); 

        }else{
            loadArticle(1);
        }

    });
    /* jQuery('.custom_sort input').change(function () {
        jQuery('body').addClass('content_loading');
        loadArticle(1);
    }); */
	jQuery('.custom_sort').change(function(){
		jQuery('body').addClass('content_loading');
                $value = jQuery(this).find('option:selected').val();
		loadArticle(1); 
	});
		
    
    	
	
        
	jQuery(document).on('click', '.single_add_to_cart_button', function (event) {
		event.preventDefault();
                if(jQuery(this).hasClass('disabled')){
                    return false;
                }
		var slideoutpopup = $('.custom-popup');
		var id = jQuery('button[name="add-to-cart"]').val(),
			var_id = jQuery('.variation_id:not(.custom-quantity .variation_id)').val(),
			qty = jQuery('.custom-quantity').find('.qty').val();
		//qty = jQuery(this).prevAll('.quantity').find('.qty').val();	
		var arlene1 = {};
		var attkey = jQuery('.variations select').data('attribute_name');
		jQuery('.variations select').each(function () {
			arlene1[attkey] = jQuery(this).val();
		});
                
                console.log(id);
		
		$.ajax({
			url: myAjax.ajaxurl,
			method: 'post',
			data: { 
				action: 'add_to_cart',
				id: id,
				var_id: var_id,
				qty: qty,
				arlene1: arlene1
			}
		}).done( function (response) {
			  if( response.error != 'undefined' && response.error ){
				//some kind of error processing or just redirect to link
				// might be a good idea to link to the single product page in case JS is disabled
				//console.log(response);
				//window.location.href = response.product_url;
				return true;
			  } else {
				response = jQuery.parseJSON(response);
                                jQuery('.header_right_cart .cart_link').find('.sub_total').html(response.cart_total);
				jQuery('.cart-header').find('.sub-total-value').html(response.header_cart);
                                jQuery('.cart-header').find('.count').html(response.header_cart_count);
                                jQuery('.header-free-shipping').html(response.header_shipping);
				jQuery('html,body').addClass("no_overflow");
				slideoutpopup.animate({
					right: "0px"
				});
				
			  }
		});
	});
       
	 $('.top-header-popup .fa, .close-section-wish').on('click', function(event){
		var slideoutpopup = $('.custom-popup-wish');
		slideoutpopup.removeClass("open");
		jQuery('html,body').removeClass("no_overflow");
		slideoutpopup.animate({
			right: "-700px"
		});
	});
	
    var $form = $('.wl-add-to').closest('form.cart').eq(0);
    $form.on('submit', function (e) {
        if (jQuery('input#wlid').val() != 'session' && jQuery('input#wlid').val() != '' && typeof jQuery('input#wlid').val() != 'undefined') {
            e.preventDefault();
            $.post($(this).attr('action'), $(this).serialize());
            jQuery.ajax({
                type: "post",
                dataType: "json",
                url: myAjax.ajaxurl,
                data: {action: "get_wishlist_url", wlid: jQuery('input#wlid').val()},
                success: function (response) {
                    jQuery('.custom-popup-wish .goto-cart-section a').attr('href',response);
                }
            });
            var slideoutpopup = $('.custom-popup-wish');
            slideoutpopup.animate({
                right: "0px"
            });
        }

    }); 
    
    jQuery(document).on('woocommerce_variation_has_changed', function(){
       // jQuery('input.qty').attr('step',jQuery('input.qty').attr('min'));
        //jQuery('input.qty').val(jQuery('input.qty').attr('min'));
    });
    
    jQuery(document).on('reset_data', function(){
       // jQuery('input.qty').attr('min',1);
       // jQuery('input.qty').attr('step',1);
      //  jQuery('input.qty').val(1);
    });	
    
    jQuery('#brosjyre_menu_cont li').click(function(){
       jQuery("html, body").animate({ scrollTop: 0 }, "swing");
    });
    setTimeout(function(){
        if(jQuery('.brosjyre__scene').length) {
            window.mapwidth = jQuery('.brosjyre__scene > img').width();
            window.mapheight = jQuery('.brosjyre__scene > img').height();
            console.log('w: '+window.mapwidth+ 'h: '+window.mapheight);
            jQuery('.house-map').width(window.mapwidth);
            jQuery('.house-map').height(window.mapheight);
            jQuery('.house-map').fadeIn();
        }
    },100);
    
    
    
});
jQuery(window).resize(function(){
   // setTimeout(function(){
        if(jQuery('.brosjyre__scene').length) {
            width = jQuery('.brosjyre__scene > img').width();
            height = jQuery('.brosjyre__scene > img').height();
            console.log('w: '+width+ 'h: '+height);
            if(width == 0){
               jQuery('.house-map').width(window.mapwidth);
            } else {
               jQuery('.house-map').width(width);
               window.mapwidth = width;
            }
            if(height  == 0){
               jQuery('.house-map').width(window.mapwidth);
            } else {
               jQuery('.house-map').height(height);
               window.mapheight = height;
            }
           // jQuery('.house-map').fadeIn();
        }
  //  }, 10);
});
function image_map_pro_click(section) {
        if(section == 'car'){
            jQuery('.menu-bil').trigger('click');
        }else{
            jQuery(".brosjyre__page--hjem .oversikt img[data-section='"+section+"']").trigger('click');
        }
    }

jQuery(document).on('change','.custom-quantity .quantity .qty',function(){	
	console.log(jQuery(this).val());
	jQuery('.cart .quantity .qty').val(jQuery(this).val());
});

jQuery(window).resize(function () {
    windowWidth = jQuery(window).width();
    stickywidth = jQuery('.sticky_sb').width();
    stickyheight = jQuery('.sticky_sb').height();
    if(jQuery('.sticky-wrap').length) {
        jQuery('.sticky-wrap').css('min-height',stickyheight + 'px');
    }
    calculation();
	calculation_one();
	//wrapper_padding();
});

jQuery(window).load(function () {
    stickywidth = jQuery('.sticky_sb').width();
    stickyheight = jQuery('.sticky_sb').height();
    if(jQuery('.sticky-wrap').length) {
        jQuery('.sticky-wrap').css('min-height',stickyheight + 'px');
    }
    calculation();
	calculation_one();
	// jQuery('.custom_sort').val('popularity').change();
});

  
  var clickTimeout;
 jQuery(document).on('click', '.plus, .minus', function () {
    
    
       
    

      // Get values
      var $qty = jQuery(this).closest('.quantity').find('.qty'),
              currentVal = parseFloat($qty.val()),
              max = parseFloat($qty.attr('max')),
              min = $qty.attr('min'),
              step = $qty.attr('step');

      // Format values
      if (!currentVal || currentVal === '' || currentVal === 'NaN')
          currentVal = 0;
      if (max === '' || max === 'NaN')
          max = '';
      if (min === '' || min === 'NaN')
          min = 1;
      if (step === 'any' || step === '' || step === undefined || parseFloat(step) === 'NaN')
          step = 1;

      // Change the value
      if (jQuery(this).is('.plus')) {

          if (max && ((currentVal + parseFloat(step)) > max)) {
              $qty.val(currentVal);
          } else {
              $qty.val(currentVal + parseFloat(step));
          }

      } else {

          if (min && (min == currentVal || (currentVal - parseFloat(step)) < min)) {
              $qty.val(currentVal);
          } else if (currentVal > 0) {
              $qty.val(currentVal - parseFloat(step));
          }

      }
      clearTimeout(clickTimeout);
      clickTimeout = setTimeout(function(){ 
         // Trigger change event
         $qty.trigger('change');
         matches = $qty.attr('name').match(/cart\[(\w+)\]/);
         if(matches){
            cart_item_key = matches[1];
            qty = $qty.val();
            cart_quantity_change(cart_item_key, qty);
        }
      }, 500);
  });
  
    jQuery(document).on('change', '.quantity .qty', function () {
        var $qty = jQuery(this).closest('.quantity').find('.qty'),
                currentVal = parseFloat($qty.val()),
                max = parseFloat($qty.attr('max')),
                min = $qty.attr('min'),
                step = $qty.attr('step');
        if (!currentVal) {
            $qty.val(min);
            currentVal = min;
        }
        if (min && (min == currentVal || currentVal < min)) {
            $qty.val(min);
            currentVal = min;
        }
        if (max && (max == currentVal || currentVal > max)) {
            $qty.val(max);
            currentVal = max;
        }
        if (currentVal % step !== 0) {
            var val = Math.floor(currentVal / step);
            $qty.val(val * step);
        }
    });
  
  function cart_quantity_change(cart_item_key, qty) {
      jQuery.ajax({
          type: "post",
          dataType: "json",
          url: myAjax.ajaxurl,
          data: {action: "update_cart_on_qty", cart_item_key: cart_item_key, qty: qty},
          success: function (resp) {
              jQuery('.cart_content').html(resp.items);
              jQuery('.header_right_cart .sub_total').html(resp.header_cart);
              jQuery('.header_free_shipping').html(resp.header_shipping);
          },
          error: function (resp) {
          }
      });
  }
  
  /* Cart Update Options Strats */
  jQuery(document).on('change', '.woocommerce-cart .qty', function () {
     console.log('sfsfs');
      matches = jQuery(this).attr('name').match(/cart\[(\w+)\]/);
      cart_item_key = matches[1];
      qty = jQuery(this).val();
      cart_quantity_change(cart_item_key, qty);
      
  });
  /* Cart Update Options Ends */
  
  jQuery(document).on('change', '#wl-items-form .qty', function () {

      post_data = jQuery('#wl-items-form').serialize();
      jQuery.ajax({
          type: "post",
          dataType: "json",
          url: myAjax.ajaxurl,
          data: {action: "update_wishlist_qty_cart", list_data: post_data},
          success: function (resp) {
              
          },
          error: function (resp) {
          }
      });
  });
  
  jQuery(document).on('click', '.wl-add-to-cart', function(){
      jQuery('.wl-list-pop-wrap-cart').show();
      jQuery('.wl-list-pop-cart').show();

			var wlx = jQuery(this).offset().left;
			var wly = jQuery(this).offset().top;
                        if (jQuery('#wpadminbar ').length) {
				jQuery(".wl-list-pop-cart").css({
					top: wly - 28,
					left: wlx
				}).show();
			} else { // if not logged in, just display in regular position
				jQuery(".wl-list-pop-cart").css({
					top: wly,
					left: wlx
				}).show();
			}
  });
 
  jQuery(document).on('click', '.move-cart-to-wishlist', function (e) {
      e.preventDefault();
      var list_id = jQuery(this).data('listid');
      jQuery.ajax({
          type: "post",
          dataType: "json",
          url: myAjax.ajaxurl,
          data: {action: "add_cart_to_wishlist", list_id: list_id},
          success: function (resp) {
              window.location.href = resp;
          },
          error: function (resp) {
          }
      });
  });
  
  function internal_search(keyword, post_type, page){
        var tax = '';
        var term = '';
        var video_tax = new Array();
      if(typeof jQuery('#search').data('tax') != 'undefined'){
          tax = jQuery('#search').data('tax');
          term = jQuery('#search').data('term');
          if (typeof jQuery('.custom_video_filter').data('taxo') != 'undefined') {
            var all_checkboxes = jQuery('.custom_video_filter input:checked');
            jQuery(all_checkboxes).each(function () {
                video_tax.push(jQuery(this).attr('data-term_id'));
            });
        }
      }
      jQuery.ajax({
          type: "post",
          dataType: "json",
          url: myAjax.ajaxurl,
          data: {action: "internal_search", keyword: keyword, post_type: post_type, page: page, tax: tax, term: term, filter: video_tax},
          success: function (resp) {
              jQuery('.search-container').html(resp.response);
          },
          error: function (resp) {
          }
      });
  }
  
jQuery(document).on("keyup", "#search", function () {
    var post_type = jQuery(this).data('type');
    var keyword = jQuery(this).val();
    var page = 1;
        internal_search(keyword, post_type, page);
});
jQuery(document).on("change", ".custom_video_filter input", function () {
    var post_type = jQuery("#search").data('type');
    var keyword = jQuery("#search").val();
    var page = 1;
        internal_search(keyword, post_type, page);
});
jQuery(document).on("click", ".page-numbers", function () {
    var post_type = jQuery('#search').data('type');
    var keyword = jQuery('#search').val();
    var page = jQuery(this).data('page');
    internal_search(keyword, post_type, page);
});



//code for sticky sb starts
var stickywidth;
var stickyheight;
var adminBar = 0; // admin bar check

function calculation() {
	var header_height = jQuery('.desktop-menu').height();
    var topSpace = header_height;
    if (jQuery(window).width() > 1024) {

        if (!!jQuery('.sticky').offset() && !!jQuery('.footer').offset()) { // make sure ".sticky" element exists
            var stickyTop = jQuery('.sticky').offset().top; // Sb top 
            var footerTop = jQuery('.footer').offset().top; // FooterTop Height
 
            setTimeout(function () {
                stickyTop = jQuery('.sticky').offset().top; // Sb top
                footerTop = jQuery('.footer').offset().top; // FooterTop Height
            }, 1000);

            jQuery(window).scroll(function () { // scroll event
				
                var windowTop = jQuery(window).scrollTop(); // returns number 
				
                if (stickyTop > windowTop + topSpace) {
                    jQuery('.sticky').css({position: 'relative'});
                    jQuery('.sticky').css({top: '0'});
                } else
                if (stickyTop < (windowTop + topSpace) && ((windowTop + stickyheight + topSpace) < (footerTop + 40))) {
                    jQuery('.sticky').css({position: 'fixed', top: header_height + 'px'});
                    jQuery('.sticky').css({width: stickywidth});
                } else {
                    jQuery('.sticky').css({position: 'fixed', top: footerTop - (windowTop + stickyheight + topSpace)});
                }
            });
        }
	}
}

function calculation_one() {
	var header_height = jQuery('.site-nav').height();
    var topSpace = header_height;
    if (jQuery(window).width() > 1024) {

        if (!!jQuery('.sticky').offset() && !!jQuery('.footer').offset()) { // make sure ".sticky" element exists
            var stickyTop = jQuery('.sticky').offset().top; // Sb top 
            var footerTop = jQuery('.footer').offset().top; // FooterTop Height
 
            setTimeout(function () {
                stickyTop = jQuery('.sticky').offset().top; // Sb top
                footerTop = jQuery('.footer').offset().top; // FooterTop Height
            }, 1000);

            jQuery(window).scroll(function () { // scroll event
				
                var windowTop = jQuery(window).scrollTop(); // returns number 
				
                if (stickyTop > windowTop + topSpace) {
                    jQuery('.sticky').css({position: 'relative'});
                    jQuery('.sticky').css({top: '0'});
                } else
                if (stickyTop < (windowTop + topSpace) && ((windowTop + stickyheight + topSpace) < (footerTop + 40))) {
                    jQuery('.sticky').css({position: 'fixed', top: header_height + 'px'});
                    jQuery('.sticky').css({width: stickywidth});
                } else {
                    jQuery('.sticky').css({position: 'fixed', top: footerTop - (windowTop + stickyheight + topSpace)});
                }
            });
        }
	}
}


jQuery(document).scroll(function () {
    if (jQuery(this).scrollTop() > (jQuery(".custom-header").height() - 22)) {
		jQuery('body').addClass("show-sticky");
    } else {
        jQuery('body').removeClass("show-sticky");
    }
    
});

/*
setTimeout(function () {
    if (jQuery('svg.hs-poly-svg').length) {
            count = 5;
        jQuery('svg.hs-poly-svg').children('polygon').each(function () {
            str = '';
            cords = new Array();
            title = jQuery(this).attr('data-shape-title');
            points = jQuery(this).attr('points');
            arr = points.split(' ');
            jQuery.each(arr, function (key, value) {
                if (value) {
                    x = value.split(',');
                    cords.push(x);
                }
            });
            x = getCentroid(cords);
//            console.log(x);
            jQuery('.testtext').html(title);
            var newText = document.createElementNS("http://www.w3.org/2000/svg", "text");
            newText.setAttributeNS(null, "x", x[0]-(jQuery('.testtext').width()));
            newText.setAttributeNS(null, "y", x[1]);
            newText.setAttributeNS(null, "font-size", "50");
            newText.setAttributeNS(null, "fill", "#fff");

            var textNode = document.createTextNode(title);
            newText.appendChild(textNode);
            newText.setAttributeNS(null, "y", x[1]);// - (newText.width/2)
            jQuery('svg.hs-poly-svg').append(newText);
//            jQuery('svg.hs-poly-svg').append('<text style="'+jQuery(this).attr('style')+'" data-index="'+count+'" x="'+x[0]+'" y="'+x[1]+'">' + title + '</text>');
            count += 1;
        });
    }
}, 5000);
*/
var getCentroid = function (coord) 
{
	var center = coord.reduce(function (x,y) {
		return [x[0] + y[0]/coord.length, x[1] + y[1]/coord.length] 
	}, [0,0])
	return center;
}


jQuery(document).ready(function($){ 
    //   $(document).ajaxComplete(function(event, xhr, settings) {
    //     var str = settings.url;
    //     if (str.indexOf("apply_coupon") >= 0) {
    //    		console.log(str.indexOf);
    //    	}
    //   });
       $(document).ajaxSuccess(function(event, xhr, settings) {
         var str = settings.url.toString();
    //     console.log(xhr);
    //     console.log('_'+xhr.responseText+'_');
    //     console.log(typeof(str));
    //     console.log(str.indexOf("apply_coupon"));
         
         if (str.indexOf("apply_coupon") >= 0) {
                $('#msg').html(xhr.responseText);
            }
       });
       
       $(document).ajaxSuccess(function (event, xhr, settings) {
        var str = settings.url.toString();
        if (str.indexOf("refresh_sco_snippet") >= 0) {
            $('.custom-shipping-text').slice(1).remove();
        }
    });
});

function menu_height() {
  var sub_menu_height = jQuery('#menu-produkt-meny').outerHeight();
  var sub_menu_height_1 = jQuery('#menu-produkt-meny > li .sub-menu').outerHeight();
  jQuery('#menu-produkt-meny > li > .sub-menu').css('min-height',sub_menu_height+'px');
  jQuery('#menu-produkt-meny > li > .sub-menu > li > .sub-menu').css('min-height',sub_menu_height_1+'px');
  $menu_max_height = 0;
  jQuery('.main_menu_wrap_inner .sub-menu').each(function(){
    $this = jQuery(this);
    $menu_height = $this.outerHeight();
    if($menu_height > $menu_max_height) {
      $menu_max_height = $menu_height;
    }
  });
  jQuery('.main_menu_wrap_inner').css('min-height', $menu_max_height);
}



function slinky(){
    var menu_title = 'MENY';
    var back_buttontext = 'Tilbake';
    var elementid;

    if(jQuery('.slinky-menu').length){
        jQuery('.slinky-menu li.header').each(function(){
         jQuery(this).find('header.title').text(back_buttontext);
         //jQuery(this).find('header.title').text(back_buttontext);
        });

          jQuery('.slinky-menu ul > li.menu-item-has-children').find('.sub-menu').find('> .header').after('<li class="parent-name"><a href="#">Se alle «<span>Text</span>»</a></li>');

          jQuery('.menu-header .header').on('click', function(){
            console.log('clicked');
            var submenu = jQuery('.menu-first').find('.sub-menu');
            submenu.each(function(){
              if($(this).hasClass('active')){
                $('.menu-header .header').addClass('active');
                $(this).find('.header .back').trigger('click');

              } 
              else{
                $('.menu-header .header').removeClass('active');
              }
            })
            
          });

        jQuery('.slinky-menu ul > li.menu-item-has-children').each(function(){
            var target = jQuery(this).find('.next');
            var sub_menu = jQuery(this).find('.sub-menu');
            var sub_menu_text = sub_menu.siblings('.next').text();
            sub_menu.find('> .parent-name a span').text(sub_menu_text);
            jQuery(target).on('click',function(){
                var target_name = jQuery(this).find('span').last().text(); //Get Parent text
                var target_anchor = jQuery(this).attr('href'); // Get Parent anchor
                // jQuery(this).siblings('.sub-menu').find('.parent-name').remove();

                // jQuery(this).siblings('.sub-menu').find('> .header').after('<li class="parent-name"><a href="' + target_anchor + '">Se alle «' + target_name + '»</a></li>');

                $('.menu-header .header').addClass('active');

                jQuery(this).siblings('.sub-menu').find('> .parent-name a').attr('href',target_anchor);
                jQuery(this).siblings('.sub-menu').find('> .parent-name a span').text(target_name);


                if(target_anchor != '#'){
                    jQuery(this).siblings('.sub-menu').find('.view-main').remove();
                }
                if(jQuery('.first-level').hasClass('active')){
                    jQuery('.menu-header').removeClass('opac');
                }
                else{
                    jQuery('.menu-header').addClass('opac');   
                }
            })
        });

        jQuery(document).on('click', '.slinky-menu .back',function(){
            setTimeout(function(){
                 if(jQuery('.first-level').hasClass('active')){
                        jQuery('.menu-header').removeClass('opac');
                        }
                        else{
                            jQuery('.menu-header').addClass('opac');   
                        }
                },300);
        });
    }
}



//blog archive function -- 
function filter_post_by_term( e, is_next_page ) {
    //var post_type = "blogg";
    //var data_action = 'false';
    var page_no = jQuery('#page_no').val();
    //var filter_category_name = "blog_terms";   

    var option_checked = [];
    jQuery.each(jQuery("[name='blog_terms']:checked"),function(){
        var value = jQuery(this).val();
        if(jQuery.inArray(value, option_checked) == -1){
            option_checked.push(jQuery(this).val());
        }
    });

    var data_json = [];
    data_json['category'] = option_checked.join(',');
    data_json['page_no'] = page_no;

    parseUrlParams ( data_json );

    jQuery.ajax({
        url: myAjax.ajaxurl,
        type: 'POST',
        dataType: 'json',
        data: {
            "action": "get_blogg_posts_by_page",
            "option_checked": option_checked,
            "page_no": page_no,
        },
        success: function (response) {
            //console.log(response);
            if(is_next_page) { 
                if(response.total_pages) {
                  jQuery('#bloggarkiv-wrapper').append(response.blogg_post).removeClass('loader-active');
                }
            } else {
                jQuery('#bloggarkiv-wrapper').html(response.blogg_post).removeClass('loader-active');
            }

          jQuery('input[name=load_more]').data('total_pages', response.total_pages);
          jQuery('input[name=load_more]').prop('disabled', false);
        },
        error: function (err) {
          jQuery('input[name=load_more]').prop('disabled', false);
        },
    });
}

//archive page filter url
function parseUrlParams ( param_json ) {
  var data = '';

  for (var key in param_json) {
    if( param_json.hasOwnProperty(key) ) {
      changeUrlParam( key, param_json[key] );

      if(param_json[key]!='') {
        data += '&'+key+'='+param_json[key];
      }
    } 
  }

  return data;
}

function changeUrlParam (param, value) {
  var currentURL = window.location.href+'&';

  var uri_str = window.location.href;
  var param_str = '';
  var anchor_str = '';

  var anchor_pos = uri_str.indexOf('#');
  if(anchor_pos !== -1) {
    anchor_str = uri_str.substr(anchor_pos+1);
    uri_str = uri_str.substr(0, anchor_pos);
  }

  var param_pos = uri_str.indexOf('?');
  var is_params = false;
  if(param_pos !== -1) {
    param_str = uri_str.substr(param_pos+1);
    uri_str = uri_str.substr(0, param_pos);

    params = param_str.split('&');
    params_len = params.length;

    for(i=0; i < params_len; i++) {
      p = params[i];
      key = '';

      if(params[i].indexOf('=')===-1) {
        key = params[i];
      } else {
        p = params[i].split('=');
        key = p[0];
      }

      if(key==param) {
        params[i] = (value>0 || value!='')? key+'='+value: '';
        is_params = true;
      }
    }

    param_str = '';
    for(i=0; i < params_len; i++) {
      if(params[i]!='') {
        p = params[i].split('=');    
        param_str += '&'+p[0]+'='+p[1];
      }
    }

    if(param_str!='') {
      param_str = param_str.substr(1);
    }
  }

  if(!is_params && (value>0 || value!='')) {
    param_str += '&'+param+'='+value;
  }

  if(param_str!='') {
    uri_str += '?'+param_str;
  }

  if(anchor_str!='') {
    uri_str += '#'+anchor_str;
  }

  if (getURLParameter(param) !== null || value==''){
    try {
      window.history.replaceState('', '',uri_str);
    } catch (e) {
      console.log(e);
    }
  }else {
    var currURL = window.location.href;
    if (currURL.indexOf("?") !== -1){
      window.history.replaceState('', '', currentURL.slice(0, - 1) + '&' + param + '=' + encodeURIComponent(value));
    } else {
      window.history.replaceState('', '', currentURL.slice(0, - 1) + '?' + param + '=' + encodeURIComponent(value));
    }
  }
}

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
}//

//blog archive function -- 