// JavaScript Document
var fixed_header_showing = false;
var fixed_header_height = false;

$(document).ready(function() {
	// Align drop down menus so they dont hang outside the page container
	$('#menu .dropdown-menu').each(function() {
		// Reset the margin on each menu item
		$(this).css('margin-left', '0px');

		var $menu_selector = $('#menu .container');

		var menu = $menu_selector.offset();
		var dropdown = $(this).parent().offset();

		var i = (dropdown.left + $(this).outerWidth()) - (menu.left + $menu_selector.outerWidth(false));

		if (i > 0) {
			$(this).css('margin-left', '-' + (i + 15) + 'px');
		}
	});

	$('#subimgs_prev').on('click', function() {
		var img_w = $('#subimgs_inner > a:first').outerWidth(true);
		var curr_left = parseInt($('#subimgs_inner').css('left'));

		if (curr_left + img_w < 0) {
			$('#subimgs_inner').css('left', (curr_left + img_w) + 'px');
		}
	});
	$('#subimgs_next').on('click', function() {
		var img_w = $('#subimgs_inner > a:first').outerWidth(true);
		var img_count = $('#subimgs_inner > a').length;
		var outer_w = $('#subimgs_outer').width();
		var curr_left = parseInt($('#subimgs_inner').css('left'));

		var total_w = img_w * img_count;

		if ((curr_left + (total_w)) - outer_w > 0) {
			$('#subimgs_inner').css('left', (curr_left - img_w) + 'px');
		}
	});

	$('body').on('click', '.video[data-yt-src]', function() {
		var $video = $(this).closest('.video[data-yt-src]');
		var src = $video.data('yt-src');

		if (src.indexOf('?') == -1) {
			src = src + '?autoplay=1&rel=0';
		} else {
			src = src + '&autoplay=1&rel=0';
		}

		$video.html('<iframe src="' + src + '" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" scrolling="no"></iframe>');
		$video.addClass('loaded');
	});

	$('#contactmap.fullsize').closest('.container').css({
		padding : '0px',
		width: '100%'
	});

	$(window).scroll();

	/* Mobile menu */
	$('#menu-xs .menu-xs-button').on('click', function() {
		if ($('#menu-xs').hasClass('open')) {
			$('.menu-xs-content').stop(true, false).slideUp('fast', function() {
				$('#menu-xs').removeClass('open');

				// Close all open submenus
				$('#menu-xs .dropdown.open > .children').stop(true, false).hide();
				$('#menu-xs .dropdown.open').removeClass('open');
			});
		} else {
			$('#menu-xs').addClass('open');
			$('.menu-xs-content').stop(true, false).slideDown('fast');
		}
	});
	$('#menu-xs .dropdown > .parent').on('click', function() {
		var open = $(this).closest('.dropdown').hasClass('open') == false;

		// Close all open submenus
		$('#menu-xs .dropdown.open > .children').stop(true, false).slideUp('fast', function() {
			$(this).closest('.dropdown').removeClass('open');
		});

		// Open the clicked menu
		if (open) {
			$(this).closest('.dropdown').addClass('open');
			$(this).siblings('.children').stop(true, false).slideDown('fast');
		}
	});
	$('body').on('click', function(e) {
		if ($('#menu-xs').hasClass('open') && $(e.target).closest('#menu-xs').length == 0) {
			$('#menu-xs').removeClass('open');
			$('.menu-xs-content').slideUp('fast');
		}
	});
	/* Mobile menu */
});

$(window).on('resize', function() {
	$('.vcenter').each(function() {
		vcenter($(this));
	});

	fixed_header_height = $('#stickymenu').outerHeight(false);

	showHideFixedHeader();

	$('.prodcatslides').each(function() {
		updateScrollingProdCatSlides($(this));
	});
});
$(window).on('scroll', function() {
	showHideFixedHeader();
});
$(window).on('load', function() {
	// This is here because it waits for the entire DOM to be loaded,
	// e.g. it will wait for images to load, thus ensuring elements
	// have the right height before trying to vcenter stuff
	$('.vcenter').each(function() {
		vcenter($(this));
	});

	fixed_header_height = $('#stickymenu').outerHeight(false);

	showHideFixedHeader(true);

	$('.prodcatslides').each(function() {
		updateScrollingProdCatSlides($(this));
	});
});

function updateScrollingProdCatSlides($pcs) {
	var $outer = $pcs.find('.pcs_outer');
	var $inner = $outer.children('.pcs_inner');
	var $slides = $inner.children('.prodcatslide');
	var $nav = $pcs.find('.pcs_nav');
	var $paging = $pcs.find('.pcs_paging');

	var outer_width = $outer.outerWidth(false);
	var slide_width = $slides.eq(0).outerWidth();
	var num_slides = $slides.length;

	if (num_slides) {
		$inner.css({ width : (Math.max(outer_width, slide_width) * num_slides) + 'px' });
		$slides.css({
			width : Math.max(outer_width, slide_width) + 'px',
			display : 'block'
		});
	}

	if (num_slides > 1) {
		$nav.css({ width : outer_width + 'px' });

		$nav.find('.prev').on('click', function() {
			var curr_slide = $paging.find('.page.active').prevAll('.page').length;
			showPCSSlide($pcs, curr_slide - 1);
		});
		$nav.find('.next').on('click', function() {
			var curr_slide = $paging.find('.page.active').prevAll('.page').length;
			showPCSSlide($pcs, curr_slide + 1);
		});
		$paging.find('.page').on('click', function() {
			if ( ! $(this).hasClass('active')) {
				var curr_slide = $paging.find('.page.active').prevAll('.page').length;
				showPCSSlide($pcs, $(this).prevAll('.page').length);
			}
		});

		$nav.show();
		$paging.show();
	} else {
		$nav.hide();
		$paging.hide();
	}
}

function showPCSSlide($pcs, eq) {
	if (eq < 0) {
		eq = $pcs.find('.pcs_inner .prodcatslide').length - 1;
	}
	if (eq > $pcs.find('.pcs_inner .prodcatslide').length - 1) {
		eq = 0;
	}

	$pcs.find('.pcs_inner').stop(true, false).animate({ 'margin-left' : ($pcs.find('.pcs_outer').width() * eq * -1) + 'px' }, 1000);
	$pcs.find('.pcs_paging .page.active').removeClass('active');
	$pcs.find('.pcs_paging .page:eq(' + eq + ')').addClass('active');
}

function showHideFixedHeader(instant) {
	if (typeof instant == 'undefined' || instant !== true) {
		instant = false;
	}

	var header_height = $('header').outerHeight(false) + $('#adv_menu').outerHeight(false) +
						$('#adv_menu_mask').outerHeight(false) + $('#menu').outerHeight(false);

	if (parseInt($(window).width()) > 991 && $(document).scrollTop() > (header_height - fixed_header_height)) {
		if (fixed_header_showing == false) {
			fixed_header_showing = true;

			if (instant) {
				$('#stickymenu').show();
			} else {
				$('#stickymenu').slideDown('fast');
			}
		}
	} else {
		if (instant) {
			$('#stickymenu').hide();
			fixed_header_showing = false;
		} else {
			$('#stickymenu').slideUp('fast', function() { fixed_header_showing = false });
		}
	}
}

function vcenter($item) {
	$item.css({
		'margin-top' : '0px',
		'margin-bottom': '0px'
	});

	var inner_height = $item.outerHeight(true);
	var outer_height = $item.parent().innerHeight();

	var new_margin_top = Math.max(0, Math.floor((outer_height - inner_height) / 2));

	$item.css({ 'margin-top' : new_margin_top + 'px' });
}

function reloadLazyImages() {
	$('#cart .lazyload').each(function() {
		if ($(this).data('srcset')) {
			$(this).attr('srcset', $(this).data('srcset'));
			$(this).removeAttr('data-srcset');
		}

		if ($(this).data('src')) {
			$(this).attr('src', $(this).data('src'));
			$(this).removeAttr('data-src');
		}

		$(this).removeClass('lazyload');
		$(this).addClass('lazyreloaded');
	});
}

// Cart add remove functions
var cart = {
	'add': function(product_id, quantity) {
		$.ajax({
			url: 'index.php?route=checkout/cart/add',
			type: 'post',
			data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
			dataType: 'json',
			success: function(json) {
				$('.alert, .text-danger').remove();

				if (json['redirect']) {
					location = json['redirect'];
				}

				if (json['success']) {
					$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');

					$('html, body').animate({ scrollTop: 0 }, 'slow');

					$('#cart').load('index.php?route=common/cart/info #cart > *', function() {
						reloadLazyImages();
						$('#cart .dropdown-toggle').trigger('click');
					});
					//KLAVIYO ADDED TO CART
				       var_learnq = _learnq || [];
				       $.ajax({
					    url: 'index.php?route=module/klaviyo/added_to_cart&product_id='+product_id+'&quantity='+ (typeof(quantity) != 'undefined' ? quantity : 1),
					    type: 'post',
					    dataType: 'json',
					    success: function(json) {
						    console.log(json['klaviyo_addtocart_items']);
						    _learnq.push(["track", "Added to Cart", json['klaviyo_addtocart_items']]);
					    }
					});
				       //KLAVIYO  ADDED TO CART					
					$('#stickymenu .stickycart > a').load('index.php?route=common/cart/info #cart .ct_items');
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},
	'update': function(key, quantity) {
		$.ajax({
			url: 'index.php?route=checkout/cart/edit',
			type: 'post',
			data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
			dataType: 'json',
			success: function(json) {
				if (window.location.pathname == '/basket' || window.location.pathname == '/checkout') {
					location.reload();
				} else if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
					location = 'index.php?route=checkout/cart';
				} else {
					$('#cart').load('index.php?route=common/cart/info #cart > *', function() {
						reloadLazyImages();
						$('#cart .dropdown-toggle').trigger('click');
					});
					$('#stickymenu .stickycart > a').load('index.php?route=common/cart/info #cart .ct_items');
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},
	'remove': function(key) {
		$.ajax({
			url: 'index.php?route=checkout/cart/remove',
			type: 'post',
			data: 'key=' + key,
			dataType: 'json',
			success: function(json) {
				if (window.location.pathname == '/basket' || window.location.pathname == '/checkout') {
					location.reload();
				} else if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
					location = 'index.php?route=checkout/cart';
				} else {
					$('#cart').load('index.php?route=common/cart/info #cart > *', function() {
						reloadLazyImages();
						$('#cart .dropdown-toggle').trigger('click');
					});
					$('#stickymenu .stickycart > a').load('index.php?route=common/cart/info #cart .ct_items');
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},
	'clear': function() {
		$.ajax({
			url: 'index.php?route=checkout/cart/clear',
			type: 'post',
			dataType: 'json',
			success: function(json) {
console.log(json);
				location.reload();
			},
			error: function(xhr, ajaxOptions, thrownError) {
				console.log(xhr);
				console.log(ajaxOptions);
				console.log(thrownError);
			}
		});
	}
};

var coupon = {
	'remove': function() {
		$.ajax({
			url: 'index.php?route=checkout/cart/removeCoupon',
			dataType: 'json',
			success: function(json) {
				location.reload();
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	}
}
