var $ = jQuery;
var kingdom_sidebar_menu = function( $elm ){
	
	// layout fix
	$elm.each(function(){
		var that = $(this);
		
		that.find(' > li > .children').each(function(){
			var submenu = $(this),
				parent = submenu.parent('li').eq(0);
			
			parent.append('<span class="accordsuffix">+</span>');
		}); 
	});
	
	$elm.find('> li').on('click', '.accordsuffix', function(){
		var that = $(this),
			parent = that.parent('li').eq(0),
			submenu = parent.children('ul.children');
		
		if( ! parent.hasClass('open') ){
			
			// close last open menu
			//var last_open = $elm.find(".open");
			//last_open.children('ul.children').slideUp('fast');
			
			// open current submenu
			submenu.slideDown('fast');
			parent.addClass("open");
			that.text('-');
		} else {
			submenu.slideUp('fast');
			parent.removeClass("open");
			that.text('+');
		}
	});
};

$(document).ready(function() {
	// Show or hide the sticky footer button
	$(window).scroll(function() {
		if ($(this).scrollTop() > 200) {
			$('.kd-go-top').fadeIn(200);
		} else {
			$('.kd-go-top').fadeOut(200);
		}
	});

	$(".kd-browsing-history").each(function(){
		var that = $(this),
			pointer = that.find(".kd-browsing-history-cursor-pointer");

		that.on('mouseenter', 'li', function(){
			var elm = $(this),
				position = elm.position();
				
			pointer.stop().animate( {
				'left': (position.left - 20) + "px"
			}, 120 );
		});
	});

	$(".kd-show-by-brands").each(function(){
		var that = $(this);

		function equal_height()
		{
			var max_height = 0,
				all_li = that.find('.kd-show-by-brands-list li');
			all_li.each(function(){
				var li = $(this),
					li_height = li.height();

				if( li_height > max_height ){
					max_height = li_height;
				}
			});

			all_li.height( max_height );
		}
		equal_height();


		that.on('click', '.kd-show-by-brands-hide-all-btn, .kd-show-by-brands-show-all-btn', function(e){
			e.preventDefault();
			that.find('header').toggleClass('kd_is_show_all');
		});

		that.on('click', 'header .kd-show-by-brands-categs li a:not(.kd_is_active)', function(e){
			e.preventDefault();

			var elm = $(this),
				ajax_container = that.find(".kd-show-by-brands-ajax-response");

			ajax_container.append('<div class="kd-show-by-brands-loader"></div>');

			jQuery.post(ajaxurl, {
				'action': 'kingdom_get_brands_by_id',
				'brand_id': elm.data('termid')
				}, function(results) {

					that.find(".kd_is_active").removeClass('kd_is_active');
					elm.addClass('kd_is_active');

					ajax_container.html( results );
					equal_height();
				}
			);
		});
	})
	
	// Animate the scroll to top
	$('.kd-go-top').click(function(event) {
		event.preventDefault();
		
		$('html, body').animate({scrollTop: 0}, 300);
	})
	
	if( $('.kd_filter_by').length > 0 ) {
		
		$('.kd_filter_by').each(function() {
			var filter_by = $(this);
			
			filter_by.on('click', '#kd_filter_by_show', function(e) {
				e.preventDefault();
				
				var that = $(this);
				
				filter_by.find('.kd_filters_list').stop().slideToggle(function() {
					if( filter_by.find('.kd_filters_list').is(':visible') ) {
						that.addClass('filters-visible');
					}else{
						that.removeClass('filters-visible');
					}
				});
				
				return false;
			});
			
			filter_by.on('click', '#kd_filter_display_as_grid_2column', function(e) {
				e.preventDefault();
				
				$('.kd_archive_pg').find('.item .kd_hp_item').css('width', 'auto');
				
				if( $('.kd_archive_pg').find('.item').data('columns') == 3 ) {
					
					$('.kd_archive_pg').find('.item').removeClass('col-lg-4');
					$('.kd_archive_pg').find('.item').addClass('col-lg-6');
				
				}else{
					
					$('.kd_archive_pg').find('.item').removeClass('col-lg-3');
					$('.kd_archive_pg').find('.item').addClass('col-lg-6');
					
				}
				
				
				document.cookie = "kd_shop_columns_list=6";
				
				return false;
			});
			
			filter_by.on('click', '#kd_filter_display_as_grid_3column', function(e) {
				e.preventDefault();
				
				$('.kd_archive_pg').find('.item .kd_hp_item').css('width', 'auto');
				
				if( $('.kd_archive_pg').find('.item').data('columns') == 3 ) {
					
					$('.kd_archive_pg').find('.item').removeClass('col-lg-6');
					$('.kd_archive_pg').find('.item').addClass('col-lg-4');
					
				}else{
					
					$('.kd_archive_pg').find('.item').removeClass('col-lg-6');
					$('.kd_archive_pg').find('.item').addClass('col-lg-3');
					
				}
				
				document.cookie = "kd_shop_columns_list=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
				
				
				return false;
			});
		});
		
	}
	
	$('.widget_kingdom_filter_amz_customer_reviews ul li a').each(function() {
		var that = $(this),
			current_url = kingdom_params.shop_url, //window.location.href,
			new_url = '';
		
		if( current_url.indexOf('?') >= 0 ) {
			if( current_url.indexOf('filter_amazon_rating') >= 0 ) {
				new_url = current_url.replace(/filter_amazon_rating=\d/g, 'filter_amazon_rating=' + that.data('rating'));
			}else{
				new_url = current_url + '&filter_amazon_rating=' + that.data('rating'); 
			}
		}else{
			new_url = current_url + '?filter_amazon_rating=' + that.data('rating'); 
		}
		 
		that.attr('href', new_url); 
	});
	
	$('.kingdom-widget .wc-layered-nav-term a').each(function() {
		var that = $(this),
			current_url = window.location.href,
			new_url = '';
		
		if( current_url.indexOf('filter_amazon_rating') >= 0 ) {
			var regex = /filter_amazon_rating=(\d)/g;
			
			new_url = that.attr('href') + ( that.parent().hasClass('chosen') ? '?' : '&' ) + 'filter_amazon_rating=' + regex.exec(current_url)[1];
			that.attr('href', new_url); 
		}
	});
});

var kdAfterUpdateEffect = function( slider )
{
	slider.find(".item").each(function(i){
		var that = $(this),
			speed = (i + 1) * 240;
		
		if( speed > 1200 ) speed = 1200;
		 
		that.animate({
			opacity: 1
		}, speed);
	});
	
	slider.css('background', 'none');
	slider.css('overflow', 'visible');
	
	if( slider.attr('id') == 'kd_footer_partners' ){
		slider.css('background', '#f6f6f6');
	}
	
}

$(document).ready(function() {
	var $ = jQuery;

	var offset = $(".star-rating").offset();
	$(".kd-own-rating").on('mousemove', '.star-rating', function( e ) {
		var left_pos = e.pageX - offset.left;

		var that = $(this),
			span = that.find('span');

		if( that.parents('.kd_hp_item_image').eq(0).length >= 1 ){
			return true;
		}

		var perc = left_pos * 100 / 95.5,
			rating = (perc * 5 / 100).toFixed(2);

		span.width( perc );

		that.data( 'value', rating );
	});

	// Save Rating
	$('.kd-own-rating').on('click', '.star-rating', function(e)
	{
		var that = $(this),
			value = that.data('value');
		jQuery.post(ajaxurl, {
			'action': 'kingdom_save_stars',
			'value': value,
			'productid': that.data('productid')
		}, function() {
		}, 'json');
	});
	
	
	$('.navigationbar').on('click', '#alternate_menu > span', function(e) {
		e.preventDefault();
		
		var alt_nav_elm = $(this).next('div').children('ul').eq(0);

		if( alt_nav_elm.hasClass('kd_default_open_hp') && $('body').hasClass('home') ){
			e.preventDefault();
			return false;
		}
		
		$('.kd_alternate_menu').toggle();
	});
	
	// variations

	var choose = $('.variations select option').first().text();
	$('.kd_variations').click(function(){
		$('.kd_custom_select .btn .current_value').text( choose );

		$('.kd_pickup_color_image_variation_container').each(function(){
			$(this).removeClass('kd_color_selected');
		});

	});
	
	$('body').on('click', '.menu-headline', function(e){
		e.preventDefault();
		var that = $(this),
			parent = that.parents('.navigationbar').eq(0),
			the_text = that.find('span');

		parent.toggleClass("kd_menu_is_open");

		var old_text = the_text.text();
		the_text.text( the_text.data('alttext') );
		the_text.data('alttext', old_text) 
		
	});
	
	$('.kd_list_type .kd_grid').click(function(e) {
		e.preventDefault();
		$('#kd_products_listitems').removeClass('kd_product_list_list').addClass('kd_product_list_grid');

		$('.kd_list_type .kd_list').removeClass('on');
		$(this).addClass('on');

	});

	$('.kd_list_type .kd_list').click(function(e) {
		e.preventDefault();
		$('#kd_products_listitems').removeClass('kd_product_list_grid').addClass('kd_product_list_list');

		$('.kd_list_type .kd_grid').removeClass('on');
		$(this).addClass('on');
	});

	$("a.prettyPhoto, .woocommerce-main-image.zoom").prettyPhoto({
		social_tools : null,
		theme: 'facebook',
		show_title: false
	});

	// color variations images

	$('.kd_dropdown_pick_up_color').on('change', function(e){
		$('.kd_pickup_color_images a').css('display', 'none');

		$('.kd_pick_up_color_select').find('select option.enabled').each(function(){
			$('.kd_pickup_color_images a[data-variation_color="' + $(this).val() + '"]').css('display', 'inline-block');
		});

	});

	$('.kd_pickup_color_image_variation_container').click(function(e){
		e.preventDefault();

		$('.kd_pickup_color_image_variation_container').each(function(){
			$(this).removeClass('kd_color_selected');
		});

		$(this).addClass('kd_color_selected');

		$('.kd_pick_up_color_select option[value="' + $(this).data('variation_color') + '"]').attr('selected', 'selected').change();

	});

/* thumbs owl */
	var kd_large_gallery = $("#kd_large_gallery");
	$("#kd_large_gallery").on('click', '.owl-item', function(e) {
		e.preventDefault();

		var that = $(this),
			pos = that.index();
			
		kd_large_gallery.trigger('owl.goTo', pos);
	});
	function kdChangeThumbs() {
		var position = this.owl.currentItem;
		$("#kd_large_gallery").trigger('owl.goTo', position);
	};
	
	 $(".flex-control-thumbs").owlCarousel({
		navigation : false,
		pagination : true,
		items : 3,
		stagePadding: 100,
		margin: 14,
		addClassActive:true
	});
	
	kd_large_gallery.owlCarousel({
		navigation : true,
		pagination : false,
		slideSpeed: 30000,
		singleItem	: true,
		items : 1,
		navigationText: ["<span></span>", "<span></span>"],
		afterAction : kdChangeThumbs,
	});
	
	$('#myTab a').click(function(e) {
		e.preventDefault()
		$(this).tab('show')
	})
	


	$(".the-content .woocommerce, .owl-set .woocommerce").each(function(){
		
		if( $('body').hasClass('woocommerce-cart') ) return;
		if( $('body').hasClass('woocommerce-checkout') ) return;
		
		var that = $(this),
			items_no = that.find('.item').data('columns'),
			items_length = that.find('.item').length;
		if( items_length > 1 ) {	
			that.owlCarousel({
				navigation : true,
				pagination : false,
				items : items_no,
				margin: 20,
				itemsDesktop : [1199,4],
				itemsDesktopSmall : [1024,3],
				itemsTablet: [768,2],
				itemsTabletSmall: false,
				itemsMobile : [479,1],
				navigationText: (typeof kingdom_params.owl_nav_arrow != 'undefined' && kingdom_params.owl_nav_arrow != '' && kingdom_params.owl_nav_arrow != 'default' ? ["<i class='micon " + kingdom_params.owl_nav_arrow + "'></i>", "<i class='micon " + kingdom_params.owl_nav_arrow.replace('left', 'right') + "'></i>"] : ["<i class='micon icon-arrow-left6'></i>", "<i class='micon icon-arrow-right6'></i>"]),
				afterUpdate: kdAfterUpdateEffect(that)
			});
		} else {
			that.find('.item').attr('class', 'item');
			that.find('.kd_hp_item').css('width', '100%');
		}
	});

	$("#kd_related_products").owlCarousel({
		navigation: true,
		autoPlay: 3000,
		stopOnHover: true,
		navigationText: (typeof kingdom_params.owl_nav_arrow != 'undefined' && kingdom_params.owl_nav_arrow != '' && kingdom_params.owl_nav_arrow != 'default' ? ["<i class='micon " + kingdom_params.owl_nav_arrow + "'></i>", "<i class='micon " + kingdom_params.owl_nav_arrow.replace('left', 'right') + "'></i>"] : ["<i class='micon icon-arrow-left6'></i>", "<i class='micon icon-arrow-right6'></i>"]),
		pagination: false,
		items: 5, // $("#kd_related_products").find('.item').eq(0).data('columns'),
		itemsDesktop: [1199,3],
		itemsDesktopSmall: [981,3],
		itemsTablet: [768,2],
		itemsTabletSmall: [600,1],
		itemsMobile: [479,1],
		itemsScaleUp: true,
		afterUpdate: kdAfterUpdateEffect( $("#kd_related_products") )
	});

	$("#kd_testimonial_slider").owlCarousel({
		navigation : true,
		pagination : false,
		items : 1,
	});

	$("#kd_footer_partners").owlCarousel({
		navigation : true,
		pagination : false,
		items : 5,
		navigationText: ["<i class='micon icon-arrow-left6'></i>", "<i class='micon icon-arrow-right6'></i>"],
		afterUpdate: kdAfterUpdateEffect( $("#kd_footer_partners") )
	});

	$('a.kd_cart_item-close-btn, .product-remove a').tooltip({
		'placement' : 'bottom'
	});

	$("#kd_slider_range").slider({
		range : true,
		min : 0,
		max : 1800,
		values : [0, 900],
		slide : function(event, ui) {
			$("#kd_amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
		}
	});
	$("#kd_amount").val("$" + $("#kd_slider_range").slider("values", 0) + " - $" + $("#kd_slider_range").slider("values", 1));
	
	$(".nav-tabs").on('click', 'li a', function(e){
		e.preventDefault();
		
		var that = $(this);
		
		if( !that.parent("li").hasClass('active') ){
			
			$(".nav-tabs").find('li.active').removeClass('active');
			that.parent('li').addClass("active");
			
			$(".entry-content.active").removeClass('active');
			$("#" + that.attr('href').replace("#", "")).addClass("active")
		}
	});
	
	$(".not_rating_yet").each( function(){
		var that = $(this),
			parent = that.parent();
		
		jQuery.post(ajaxurl, {
			'action': 'kingdom_show_amazon_rating',
			'productid': that.data('productid')
		}, function(results) {
			
			that.parent().find(".the_loader").remove();
			
			if( results.status == 'invalid' ){
				that.replaceWith('<p>' + ( results.msg ) + '</p>');
			}else{
				that.val( Math.ceil(results.data.rating) );
				that.after("<em>" + ( results.data.when ) + "</em>");
				that.before( results.data.html );
				//that.rating();
				 
				parent.find('[data-value]').data('type', 'static');
			}
			
		}, 'json');
	});
	
	$(".cached-rating").each( function(){
		$(this).parent().find('[data-value]').data('type', 'static');
	});

/* departments menu hover effect overlay */

	var kd_overlay = $('.kd-menu-effect'); 
	$('.kd_alternate_menu').mouseenter(function() {
		kd_overlay.stop().fadeIn(350);
	}).mouseleave( function() {
		kd_overlay.stop().fadeOut(350);
	});

	$('.kd_alternate_menu').each(function(){
		var that = $(this),
			parent = that.parents(".container").eq(0);
		
		that.find(" > li.menu-item-has-children").each(function(){
			var sub_menu = $(this);
			var items_list = [];
			
			sub_menu.find("> ul > li ").each( function(){
				var base_submenu = $(this);

				var base_categ = base_submenu.find(" > a");

				var sub_items_list = {};
				base_submenu.find(" > ul a").each(function(){
					var link = $(this);
					sub_items_list[ link.text() ] = link.attr('href');
				});

				items_list.push( {
					'url': base_categ.attr('href'),
					'name': base_categ.text(),
					'subitems': sub_items_list
				});
			});

			var columns = 1;
			if( items_list.length > 1 ){
				columns = 2;
			}
			if( items_list.length > 2 ){
				columns = 3;
			}


			var html = [];
			html.push('<div class="kd_alternate_menu-submenu">');
			$.each( items_list, function( key, base_categ ){
				html.push('<div class="kd_alternate_menu-submenu-column kd_alternate_colmns-' + columns + '">');
				html.push(	'<h3><a href="' + ( base_categ.url ) + '">' + ( base_categ.name ) + '</a></h3>');

				html.push(	'<div class="kd_alternate_menu-submenu-items">');
				$.each( base_categ.subitems, function( key, value ){
					html.push("<a href='" + ( value ) + "'>" + ( key ) + "</a>");
				})
				html.push(	'</div>');
				html.push('</div>');
			});

			if( sub_menu.find(' > a ').data('bg') != "" ){
				html.push("<img src='" + sub_menu.find(' > a ').data('bg') + "' class='kd_alternate_menu_background' />");
			}
			html.push("</div>");

			sub_menu.find(">ul").replaceWith( html.join("\n") );
			
			//var submenu_height = parseInt(sub_menu.find(">ul").height());
			//sub_menu.find(">ul").height(  );
		});


		
		var the_width = parseInt(parent.width()) - parseInt(that.width());
		var all_submenus = that.find(".kd_alternate_menu-submenu")
		all_submenus.width( the_width );
		//all_submenus.height( parseInt(that.height()) );
		
		that.find(" > li.menu-item-has-children").each(function(){
			$(this).find(".kd_alternate_menu-submenu").each(function() {
				var sub_menu = $(this);
				if( sub_menu.height() > parseInt(that.height()) ) {
					sub_menu.height( sub_menu.height() );
				}else{
					sub_menu.height( parseInt(that.height()) );
				}
			});
		});

	});
	
	
	// woocommerce widget filters
	$('.product_list_widget > li > a > img').each(function() {
		$(this).parent().before(this);
		$(this).wrap('<div class="product_list_widget_img_wrapper" />');
	});
	
	$('.product_list_widget > li > a').each(function() {
		if ($.trim($(this).text()).length > 30 ) { $(this).text($.trim($(this).text()).substr(0, 30) + "..."); }
	});
	
	$('.product_list_widget > li > .product_list_widget_img_wrapper').each(function() {
		$(this).parent().children('a').prepend(this);
	});
	
	// woocommerce product categoies, create accordition
	kingdom_sidebar_menu( $(".widget_product_categories .product-categories") );
	
	$(".kd_small-cart .cart-details-wrapper").each(function(){
		var that = $(this);
		
		that.height( (that.find(".kd_small_cart_items li").size() * 94) + 110 );
		
		if( that.find(".kd_small_cart_items .empty").size() > 0 ){
			that.height( 32 );
		}
	});
	
	$("#top_nav .sub-menu").parent('li').append( '<i class="icon icon_arrow-menu"></i>' );
	
	$("input[type=number]").show();
		
	// Google maps
	$('div.kingdom-map').each(function(){
		var that = $(this);
		that.gMap({ address: that.data('address'), zoom: that.data('zoom') });
	}); 
	
	$(".kd_hovereffect img").each(function(i, img) {	
	    $(img).css({
	        position: "relative",
	        left: ($(img).parent().width()/2) - ($(img).width()/2)
	    });
	});
	
});
