(function($) {

	"use strict";

	$( document ).ready(function() {

		if ($(window).width() < 800) {

			$('#navmain > div > ul > li').has('ul').addClass('level-one-sub-menu');
			$('#navmain > div > ul li ul li').has('ul').addClass('level-two-sub-menu');

    // add support of browsers which don't support focus-within
    $('#navmain > div > ul > li > a:not(.search-form-icon), #navmain > div > ul > li > ul > li > a, #navmain > div > ul > li > ul > li > ul > li > a')
      .on('mouseenter focus', function() {
        $(this).closest('li.level-one-sub-menu').addClass('menu-item-focused');
        $(this).closest('li.level-two-sub-menu').addClass('menu-item-focused');

        if (!$(this).parent().find('#cart-popup-content').length && $('#cart-popup-content').css('z-index') != '-1')
          $('#cart-popup-content').css('z-index', '-1');
      }).on('mouseleave blur', function() {
        $(this).closest('li.level-one-sub-menu').removeClass('menu-item-focused');
        $(this).closest('li.level-two-sub-menu').removeClass('menu-item-focused');
    });
		}

		zenoffice_initHeaderIconsEvents();

		// init header search 
		$(function () {
	        $(".sb-search").sbSearch();
	    });

	    $.fn.sbSearch = function() {
	       return this.each(function() {
	           new UISearch( this );
	       });
	    };
	});

	function zenoffice_initHeaderIconsEvents() {

		$('a.cart-contents-icon').on('mouseenter focusin', function(){
		
			// display mini-cart if it's not visible
			if ( $('#cart-popup-content').css('z-index') == '-1' ) {
			
				$('#search-popup-content').css('z-index', '-1');

				var rightPos = ($(window).width() - ($(this).offset().left + $(this).outerWidth()));
				var topPos = $(this).offset().top - $(window).scrollTop() + $(this).outerHeight(); 

				$('#cart-popup-content').css('right', rightPos).css('top', topPos).fadeIn();
			}
		});
		
		$('#cart-popup-content').on('mouseleave', function(){
    
      $('#cart-popup-content').css('z-index', '-1');
    });

    $('#main-content-wrapper').on('focusin', function(){
    
      if ($('#cart-popup-content').css('z-index') != '-1')
        $('#cart-popup-content').css('z-index', '-1');

      if ($('#navmain > div > ul').css('z-index') != '-1') {
        $('#navmain > div > ul').css('z-index', '-1');  
      }

    });
		
		$('a.search-form-icon').on('click', function(){

	    $('#cart-popup-content').css('z-index', '-1');
		
			// display mini-cart if it's not visible
			if ( $('#search-popup-content').css('z-index') == '-1' ) {

				var rightPos = ($(window).width() - ($(this).offset().left + $(this).outerWidth()));
				var topPos = $(this).offset().top - $(window).scrollTop() + $(this).outerHeight(); 

				$('#search-popup-content').css('right', rightPos).css('top', topPos).css('z-index', '5000');

			} else {

	      $('#search-popup-content').css('z-index', '-1');
	    }
		});
	}

})(jQuery);